// Global search modal — stub for now (autocomplete over services + directions + doctors)
const { useState: smS, useEffect: smE, useRef: smR, useMemo: smM } = React;

const SearchModal = ({ open, onClose }) => {
  const [q, setQ] = smS('');
  const inputRef = smR(null);

  smE(() => {
    if (open) {
      setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
      setQ('');
    }
  }, [open]);

  // Build combined index
  const index = smM(() => {
    const items = [];
    DATA.directions.forEach(d => items.push({
      type: 'Направление', label: d.name, sub: d.desc, icon: d.icon, href: `direction.html?id=${d.id}`,
    }));
    DATA.doctors.forEach(d => items.push({
      type: 'Врач', label: d.fullName, sub: d.specs.join(', '), icon: 'doctor', href: `doctor.html?id=${d.id}`,
    }));
    DATA.services.forEach(s => items.push({
      type: 'Услуга', label: s, sub: '', icon: 'pill', href: '#',
    }));
    return items;
  }, []);

  const filtered = smM(() => {
    if (!q.trim()) return index.slice(0, 8);
    const lq = q.toLowerCase();
    return index.filter(it =>
      it.label.toLowerCase().includes(lq) ||
      (it.sub || '').toLowerCase().includes(lq)
    ).slice(0, 12);
  }, [q, index]);

  const popular = ['Кардиолог', 'МРТ', 'Гастроэнтерология', 'Второе мнение', 'Чек-ап'];

  if (!open) return null;

  return (
    <div className="sm-overlay" onClick={onClose}>
      <div className="sm" onClick={(e) => e.stopPropagation()}>
        <div className="sm__input">
          <Icon name="search" size={20} className="sm__input-icon" />
          <input
            ref={inputRef}
            type="text"
            placeholder="Найдите врача, направление или услугу..."
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <button className="sm__close" onClick={onClose} aria-label="Закрыть">
            <Icon name="close" size={18} />
          </button>
        </div>

        <div className="sm__body">
          {!q.trim() && (
            <div className="sm__section">
              <div className="sm__heading">Популярные запросы</div>
              <div className="sm__chips">
                {popular.map((p) => (
                  <button key={p} className="sm__chip" onClick={() => setQ(p)}>
                    <Icon name="search" size={12} /> {p}
                  </button>
                ))}
              </div>
            </div>
          )}

          {filtered.length > 0 ? (
            <div className="sm__section">
              <div className="sm__heading">{q.trim() ? 'Результаты' : 'Подсказки'}</div>
              <ul className="sm__list">
                {filtered.map((it, i) => (
                  <li key={i}>
                    <a className="sm__item" href={it.href} onClick={(e) => { if (it.href === '#') e.preventDefault(); onClose(); }}>
                      <span className="sm__item-icon"><Icon name={it.icon} size={16} /></span>
                      <span className="sm__item-body">
                        <span className="sm__item-label">{it.label}</span>
                        {it.sub && <span className="sm__item-sub">{it.sub}</span>}
                      </span>
                      <span className="sm__item-type">{it.type}</span>
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ) : (
            <div className="sm__empty">
              <Icon name="search" size={28} />
              <p>Ничего не найдено по запросу «<strong>{q}</strong>»</p>
              <p className="sm__empty-sub">Попробуйте другое слово или позвоните администратору</p>
            </div>
          )}
        </div>

        <div className="sm__foot">
          <span>↵ Открыть</span>
          <span>Esc Закрыть</span>
          <span style={{ marginLeft: 'auto' }}>
            Не нашли нужное? <a href={`tel:${DATA.brand.phoneRaw}`}>{DATA.brand.phone}</a>
          </span>
        </div>
      </div>

      <style>{`
        .sm-overlay {
          position: fixed;
          inset: 0;
          background: oklch(0.18 0.04 255 / 0.45);
          backdrop-filter: blur(4px);
          z-index: 100;
          display: flex;
          align-items: flex-start;
          justify-content: center;
          padding: 80px 24px 24px;
          animation: fadeIn .15s ease;
        }
        .sm {
          background: #fff;
          border-radius: var(--r-lg);
          width: 100%;
          max-width: 640px;
          box-shadow: var(--shadow-lg);
          overflow: hidden;
          animation: modalIn .2s cubic-bezier(.22,.61,.36,1);
        }
        .sm__input {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 18px 22px;
          border-bottom: 1px solid var(--border);
        }
        .sm__input-icon { color: var(--navy-700); flex-shrink: 0; }
        .sm__input input {
          flex: 1;
          border: 0;
          background: transparent;
          font-size: 17px;
          font-weight: 500;
          color: var(--ink-900);
          padding: 0;
        }
        .sm__input input:focus { outline: none; }
        .sm__input input::placeholder { color: var(--ink-400); font-weight: 400; }
        .sm__close {
          width: 28px; height: 28px;
          border-radius: 999px;
          background: var(--navy-100);
          color: var(--ink-700);
          display: inline-flex;
          align-items: center;
          justify-content: center;
        }
        .sm__close:hover { background: var(--navy-200); }

        .sm__body {
          max-height: 60vh;
          overflow-y: auto;
          padding: 14px 12px;
        }
        .sm__section + .sm__section { margin-top: 14px; }
        .sm__heading {
          font-size: 11px;
          color: var(--ink-500);
          text-transform: uppercase;
          letter-spacing: 0.08em;
          font-weight: 500;
          padding: 4px 10px 8px;
        }
        .sm__chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 10px; }
        .sm__chip {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 7px 12px;
          background: var(--navy-100);
          color: var(--navy-700);
          font-size: 13px;
          font-weight: 500;
          border-radius: var(--r-full);
          transition: background .15s ease;
        }
        .sm__chip:hover { background: var(--navy-200); }

        .sm__list { list-style: none; padding: 0; margin: 0; }
        .sm__item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 10px 14px;
          border-radius: var(--r-sm);
          color: var(--ink-900);
          transition: background .15s ease;
        }
        .sm__item:hover { background: var(--navy-50); }
        .sm__item-icon {
          width: 32px; height: 32px;
          border-radius: var(--r-sm);
          background: var(--navy-100);
          color: var(--navy-700);
          display: inline-flex; align-items: center; justify-content: center;
          flex-shrink: 0;
        }
        .sm__item-body { flex: 1; min-width: 0; }
        .sm__item-label { display: block; font-size: 14.5px; font-weight: 500; line-height: 1.25; }
        .sm__item-sub { display: block; font-size: 12.5px; color: var(--ink-500); margin-top: 2px; line-height: 1.3; }
        .sm__item-type {
          font-size: 11px;
          color: var(--ink-500);
          text-transform: uppercase;
          letter-spacing: 0.06em;
          font-weight: 500;
          flex-shrink: 0;
        }

        .sm__empty {
          padding: 40px 20px;
          text-align: center;
          color: var(--ink-500);
        }
        .sm__empty svg { color: var(--ink-400); margin-bottom: 12px; }
        .sm__empty p { color: var(--ink-700); }
        .sm__empty-sub { color: var(--ink-500); font-size: 13px; margin-top: 6px; }

        .sm__foot {
          display: flex;
          gap: 18px;
          align-items: center;
          padding: 12px 22px;
          background: var(--navy-50);
          border-top: 1px solid var(--border);
          font-size: 12px;
          color: var(--ink-500);
        }
        .sm__foot a { color: var(--navy-700); font-weight: 500; }
        .sm__foot a:hover { text-decoration: underline; }
      `}</style>
    </div>
  );
};

Object.assign(window, { SearchModal });
