/**
 * Global Search — חיפוש גלובלי
 * Cmd+K / Ctrl+K פותח modal
 * מחפש: פרויקטים, משימות, דוחות, לקוחות, ספקים, מכרזים, פרוטוקולים, אנשי קשר
 * Fuzzy search על הצד-לקוח, debounce 200ms
 */
(function () {

const { useState, useEffect, useRef, useMemo } = React;

// ── Search index builder ─────────────────────────────────────────────────────
function buildSearchIndex() {
  const items = [];
  const data = window.YBP_DATA || { projects: [] };
  const store = window.SyncStore ? window.SyncStore.get() : {};

  // פרויקטים
  (data.projects || []).forEach(p => {
    items.push({
      id: p.id, type: 'project', icon: '🏗',
      title: p.name, sub: p.location || p.address || '',
      tags: [p.client, p.status].filter(Boolean),
      screen: 'detail', projectId: p.id,
      searchText: [p.name, p.location, p.address, p.client, p.status].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // משימות (v57 — מסנן archived)
  (store.tasks || []).filter(t => t.status !== 'archived').forEach(t => {
    const proj = (data.projects || []).find(p => p.id === t.projectId);
    items.push({
      id: t.id, type: 'task', icon: '✅',
      title: t.title, sub: proj?.name || '',
      tags: [t.assignee, t.status].filter(Boolean),
      screen: 'tasks', projectId: t.projectId,
      searchText: [t.title, t.description, t.assignee, proj?.name].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // דוחות
  (store.reports || []).forEach(r => {
    const proj = (data.projects || []).find(p => p.id === r.projectId);
    items.push({
      id: r.id, type: 'report', icon: '📋',
      title: r.title || r.id, sub: proj?.name || '',
      tags: [r.kind, r.author].filter(Boolean),
      screen: 'reportView', projectId: r.projectId, reportId: r.id,
      searchText: [r.title, r.id, r.author, r.kind, proj?.name].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // לקוחות
  const customers = window.SyncStore?.getCustomers ? window.SyncStore.getCustomers() : [];
  customers.forEach(c => {
    items.push({
      id: c.id, type: 'customer', icon: '👤',
      title: c.name, sub: c.company || '',
      tags: [c.taxId].filter(Boolean),
      screen: 'customers',
      searchText: [c.name, c.company, c.taxId, c.accountingEmail].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // בעלי מקצוע
  const vendors = window.SyncStore?.getVendors ? window.SyncStore.getVendors() : [];
  vendors.forEach(v => {
    items.push({
      id: v.id, type: 'vendor', icon: '🔧',
      title: v.name, sub: v.company || v.primaryCat || '',
      tags: [v.primaryCat, ...(v.secondaryCats || []).slice(0, 2)],
      screen: 'vendors',
      searchText: [v.name, v.company, v.primaryCat, ...(v.secondaryCats || []), v.phone, v.email].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // מכרזים
  const tenders = window.SyncStore?.getTenders ? window.SyncStore.getTenders() : [];
  tenders.forEach(t => {
    const proj = (data.projects || []).find(p => p.id === t.projectId);
    items.push({
      id: t.id, type: 'tender', icon: '📬',
      title: t.name, sub: proj?.name || '',
      tags: [t.category, t.status].filter(Boolean),
      screen: 'tenders', projectId: t.projectId,
      searchText: [t.name, t.category, t.description, proj?.name].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // פרוטוקולים
  const protocols = window.SyncStore?.getProtocols ? window.SyncStore.getProtocols() : [];
  protocols.forEach(p => {
    const proj = (data.projects || []).find(pr => pr.id === p.projectId);
    items.push({
      id: p.id, type: 'protocol', icon: '📝',
      title: p.title, sub: proj?.name || '',
      tags: [p.type, p.author].filter(Boolean),
      screen: 'protocols', projectId: p.projectId,
      searchText: [p.title, p.summary, p.participants, p.author, proj?.name].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  // אנשי קשר (מ-sync store אם יש)
  const contacts = (store.contacts || []);
  contacts.forEach(c => {
    items.push({
      id: c.id, type: 'contact', icon: '📞',
      title: c.name, sub: c.company || c.role || '',
      tags: [c.phone].filter(Boolean),
      screen: 'contactDetail', contactId: c.id,
      searchText: [c.name, c.company, c.role, c.phone, c.email].filter(Boolean).join(' ').toLowerCase(),
    });
  });

  return items;
}

// ── Simple fuzzy match ────────────────────────────────────────────────────────
function fuzzyMatch(query, text) {
  const q = query.toLowerCase().trim();
  if (!q) return true;
  // exact substring
  if (text.includes(q)) return true;
  // all words present
  const words = q.split(/\s+/);
  return words.every(w => text.includes(w));
}

// ── Score: rank exact matches higher ─────────────────────────────────────────
function scoreMatch(query, item) {
  const q = query.toLowerCase().trim();
  const title = item.title.toLowerCase();
  if (title.startsWith(q)) return 3;
  if (title.includes(q)) return 2;
  return 1;
}

// ── Type labels ───────────────────────────────────────────────────────────────
const TYPE_LABELS = {
  project:  { label: 'פרויקט',    color: '#1a2c4a', bg: '#eef2ff' },
  task:     { label: 'משימה',     color: '#dc2626', bg: '#fef2f2' },
  report:   { label: 'דוח',       color: '#2563eb', bg: '#eff6ff' },
  customer: { label: 'לקוח',      color: '#7c3aed', bg: '#f5f3ff' },
  vendor:   { label: 'בעל מקצוע', color: '#ea580c', bg: '#fff7ed' },
  tender:   { label: 'מכרז',      color: '#0891b2', bg: '#ecfeff' },
  protocol: { label: 'פרוטוקול', color: '#16a34a', bg: '#f0fdf4' },
  contact:  { label: 'איש קשר',  color: '#6b7280', bg: '#f9fafb' },
};

const RECENT_KEY = 'ybp_search_recent';
function loadRecent() {
  try { return JSON.parse(localStorage.getItem(RECENT_KEY) || '[]'); } catch { return []; }
}
function saveRecent(items) {
  try { localStorage.setItem(RECENT_KEY, JSON.stringify(items.slice(0, 8))); } catch {}
}

// ── SearchResult ──────────────────────────────────────────────────────────────
const SearchResult = ({ item, query, active, onClick }) => {
  const cfg = TYPE_LABELS[item.type] || TYPE_LABELS.contact;

  // Highlight matching text
  const highlightText = (text) => {
    if (!query) return text;
    const q = query.trim();
    const idx = text.toLowerCase().indexOf(q.toLowerCase());
    if (idx === -1) return text;
    return (
      <>
        {text.slice(0, idx)}
        <mark style={{ background: '#fef08a', padding: '0 1px', borderRadius: 2 }}>
          {text.slice(idx, idx + q.length)}
        </mark>
        {text.slice(idx + q.length)}
      </>
    );
  };

  return (
    <div onClick={onClick} style={{
      padding: '10px 16px', cursor: 'pointer', display: 'flex', gap: 12, alignItems: 'center',
      background: active ? 'var(--ybp-row-hover,#f0f4f8)' : 'transparent',
      borderRadius: 8, margin: '0 4px',
    }}>
      <span style={{ fontSize: 18, flexShrink: 0 }}>{item.icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {highlightText(item.title)}
        </div>
        {item.sub && (
          <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 1 }}>
            {item.sub}
          </div>
        )}
      </div>
      <span style={{
        padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600,
        background: cfg.bg, color: cfg.color, flexShrink: 0,
      }}>{cfg.label}</span>
    </div>
  );
};

// ── GlobalSearch Modal ────────────────────────────────────────────────────────
const GlobalSearchModal = ({ onClose, onNavigate }) => {
  const [query, setQuery] = useState('');
  const [activeIdx, setActiveIdx] = useState(0);
  const [recent, setRecent] = useState(loadRecent);
  const inputRef = useRef(null);
  const timerRef = useRef(null);
  const [debouncedQuery, setDebouncedQuery] = useState('');

  // Focus on mount
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  // Debounce query
  useEffect(() => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setDebouncedQuery(query), 200);
    return () => clearTimeout(timerRef.current);
  }, [query]);

  // Build index (memoized)
  const index = useMemo(() => buildSearchIndex(), []);

  // Filter results
  const results = useMemo(() => {
    if (!debouncedQuery.trim()) return [];
    return index
      .filter(item => fuzzyMatch(debouncedQuery, item.searchText))
      .sort((a, b) => scoreMatch(debouncedQuery, b) - scoreMatch(debouncedQuery, a))
      .slice(0, 12);
  }, [debouncedQuery, index]);

  const displayItems = debouncedQuery ? results : recent;
  const sectionLabel = debouncedQuery ? `${results.length} תוצאות` : 'חיפושים אחרונים';

  // Keyboard navigation
  useEffect(() => {
    const handler = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setActiveIdx(i => Math.min(i + 1, displayItems.length - 1));
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault();
        setActiveIdx(i => Math.max(i - 1, 0));
      }
      if (e.key === 'Enter' && displayItems[activeIdx]) {
        handleSelect(displayItems[activeIdx]);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [displayItems, activeIdx]);

  useEffect(() => setActiveIdx(0), [debouncedQuery]);

  const handleSelect = (item) => {
    // Save to recent
    const newRecent = [item, ...recent.filter(r => r.id !== item.id)];
    setRecent(newRecent);
    saveRecent(newRecent);

    // Navigate
    onNavigate(item);
    onClose();
  };

  // Group results by type
  const grouped = useMemo(() => {
    if (!debouncedQuery) return null;
    const groups = {};
    results.forEach(r => {
      if (!groups[r.type]) groups[r.type] = [];
      groups[r.type].push(r);
    });
    return groups;
  }, [results, debouncedQuery]);

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      zIndex: 99999, paddingTop: 80, fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderRadius: 14, width: '100%', maxWidth: 560,
        maxHeight: '70vh', display: 'flex', flexDirection: 'column',
        boxShadow: '0 20px 60px rgba(0,0,0,0.25)',
        border: '1px solid var(--ybp-border,#e5e7eb)',
        overflow: 'hidden',
        margin: '0 16px',
      }}>
        {/* Search input */}
        <div style={{
          padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10,
          borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        }}>
          <Icon name="search" size={18} color="var(--ybp-ink-faint,#9ca3af)" />
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="חפש פרויקטים, משימות, מכרזים, ספקים..."
            style={{
              flex: 1, border: 'none', outline: 'none', fontSize: 16,
              fontFamily: 'Assistant, sans-serif', background: 'transparent',
              color: 'var(--ybp-ink,#111827)', direction: 'rtl',
            }}
          />
          {query && (
            <button onClick={() => setQuery('')} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: 'var(--ybp-ink-faint,#9ca3af)', fontSize: 16, padding: 2,
            }}>✕</button>
          )}
          <kbd style={{
            padding: '2px 6px', borderRadius: 4, background: 'var(--ybp-row-hover,#f3f4f6)',
            border: '1px solid var(--ybp-border,#e5e7eb)', fontSize: 11,
            color: 'var(--ybp-ink-faint,#6b7280)', fontFamily: 'monospace',
          }}>Esc</kbd>
        </div>

        {/* Results */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {displayItems.length === 0 && debouncedQuery ? (
            <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', fontSize: 14 }}>
              לא נמצאו תוצאות עבור "<strong>{debouncedQuery}</strong>"
            </div>
          ) : displayItems.length === 0 && !debouncedQuery ? (
            <div style={{ padding: '24px 16px', textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', fontSize: 13 }}>
              <div style={{ fontSize: 32, marginBottom: 8 }}>🔍</div>
              התחל להקליד לחיפוש
            </div>
          ) : (
            <>
              {/* Section label */}
              <div style={{ padding: '4px 20px 6px', fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#9ca3af)', letterSpacing: 0.5, textTransform: 'uppercase' }}>
                {sectionLabel}
              </div>

              {/* Results list */}
              {displayItems.map((item, i) => (
                <SearchResult
                  key={item.id + i}
                  item={item}
                  query={debouncedQuery}
                  active={i === activeIdx}
                  onClick={() => handleSelect(item)}
                />
              ))}
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: '8px 16px', borderTop: '1px solid var(--ybp-border,#e5e7eb)',
          display: 'flex', gap: 14, alignItems: 'center',
          fontSize: 11, color: 'var(--ybp-ink-faint,#9ca3af)',
        }}>
          <span><kbd style={{ fontFamily: 'monospace', fontSize: 10 }}>↑↓</kbd> ניווט</span>
          <span><kbd style={{ fontFamily: 'monospace', fontSize: 10 }}>Enter</kbd> פתח</span>
          <span><kbd style={{ fontFamily: 'monospace', fontSize: 10 }}>Esc</kbd> סגור</span>
          <span style={{ marginRight: 'auto' }}>{index.length} פריטים באינדקס</span>
        </div>
      </div>
    </div>
  );
};

// ── GlobalSearchTrigger — כפתור + Cmd+K listener ────────────────────────────
const GlobalSearchTrigger = ({ onNavigate }) => {
  const [open, setOpen] = useState(false);

  // Cmd+K / Ctrl+K
  useEffect(() => {
    const handler = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setOpen(true);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const handleNavigate = (item) => {
    if (!onNavigate) return;
    onNavigate(item.screen, item.projectId, item);
  };

  return (
    <>
      {/* Search button in SessionBar */}
      <button onClick={() => setOpen(true)} style={{
        display: 'flex', alignItems: 'center', gap: 6,
        background: 'rgba(255,255,255,0.08)',
        border: '1px solid rgba(255,255,255,0.12)',
        borderRadius: 8, padding: '5px 10px',
        cursor: 'pointer', color: 'rgba(255,255,255,0.7)',
        fontSize: 12, fontFamily: 'Assistant, sans-serif',
        transition: 'background 0.15s',
      }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.14)'}
        onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
        aria-label="חיפוש"
      >
        <Icon name="search" size={14} color="rgba(255,255,255,0.7)" />
        <span>חיפוש</span>
        <kbd style={{
          padding: '1px 5px', borderRadius: 3,
          background: 'rgba(255,255,255,0.1)',
          border: '1px solid rgba(255,255,255,0.15)',
          fontSize: 10, fontFamily: 'monospace',
          color: 'rgba(255,255,255,0.5)',
        }}>⌘K</kbd>
      </button>

      {open && (
        <GlobalSearchModal
          onClose={() => setOpen(false)}
          onNavigate={handleNavigate}
        />
      )}
    </>
  );
};

Object.assign(window, { GlobalSearchTrigger, GlobalSearchModal, addNotification: window.addNotification });
})();
