/* Universal Search — segmented control with per-vertical fields */

const usearchStyles = {
  wrap: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 },
  tabs: {
    display: 'inline-flex', gap: 4,
    background: 'rgba(255,255,255,0.78)',
    backdropFilter: 'blur(10px)',
    borderRadius: 999,
    padding: 5,
    border: '1px solid rgba(11, 31, 37, 0.08)',
  },
  tab: (active) => ({
    padding: '9px 18px',
    borderRadius: 999,
    fontSize: 13,
    fontWeight: 600,
    letterSpacing: '-0.005em',
    color: active ? 'var(--paper)' : 'var(--ink)',
    background: active ? 'var(--ink)' : 'transparent',
    cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6,
    transition: 'all 200ms cubic-bezier(0.2,0,0.2,1)',
  }),
  bar: {
    background: 'var(--surface)',
    borderRadius: 999,
    padding: 7,
    display: 'inline-flex',
    boxShadow: '0 24px 60px rgba(11, 31, 37, 0.18), 0 1px 0 rgba(255,255,255,0.3) inset',
    border: '1px solid rgba(11, 31, 37, 0.06)',
    alignItems: 'center',
    minWidth: 880,
    maxWidth: '100%',
  },
  field: (last) => ({
    flex: 1,
    minWidth: 0,
    padding: '10px 24px',
    borderRight: last ? 'none' : '1px solid var(--rule)',
    cursor: 'pointer',
    borderRadius: 999,
    transition: 'background 150ms',
  }),
  fieldLabel: {
    fontFamily: 'var(--font-ui)',
    fontSize: 10.5,
    fontWeight: 700,
    letterSpacing: '0.16em',
    textTransform: 'uppercase',
    color: 'var(--ink)',
    marginBottom: 4,
    display: 'block',
  },
  fieldValue: {
    fontSize: 14,
    color: 'var(--ink-mute)',
    fontWeight: 500,
    display: 'block',
  },
  go: {
    width: 56, height: 56,
    minWidth: 56,
    borderRadius: 999,
    background: 'var(--coral)',
    color: 'white',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    flexShrink: 0,
    marginLeft: 6,
    transition: 'background 150ms',
  },
};

const USEARCH_VERTICALS = [
  { id: 'stay',       label: 'Stay',        icon: 'home' },
  { id: 'charter',    label: 'Charter',     icon: 'boat' },
  { id: 'experience', label: 'Experience',  icon: 'diving' },
  { id: 'shop',       label: 'Shop',        icon: 'bag' },
  { id: 'eat',        label: 'Eat',         icon: 'mortar' },
];

const USEARCH_FIELDS = {
  stay:       [['Where', 'All atolls'], ['Check in', 'Add date'], ['Check out', 'Add date'], ['Guests', '2 adults · 0 kids']],
  charter:    [['Departure', 'Malé · Hulhumalé Jetty'], ['Type', 'Sunset / Fishing / Liveaboard'], ['Date', 'Add date'], ['Guests', '2 adults']],
  experience: [['Where', 'All atolls'], ['When', 'Anytime'], ['Activity', 'All — dive, snorkel, sandbank…'], ['Party', '2 adults']],
  shop:       [['Search', 'Lacquer, hedhikaa, electronics…'], ['Category', 'All categories'], ['Deliver to', 'Malé · K Atoll'], ['Sort', 'Most relevant']],
  eat:        [['Search', 'Hedhikaa, cake, fresh tuna…'], ['Kitchen', 'Home bakery / Restaurant / Catering'], ['When', 'Today · 6:00 PM'], ['Where', 'Malé']],
};

function USearch({ initial = 'stay', sticky = false }) {
  const [active, setActive] = React.useState(initial);
  React.useEffect(() => {
    localStorage.setItem('malzive:usearch:vertical', active);
  }, [active]);
  const [query, setQuery] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    const onClickOutside = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, []);

  const corpus = React.useMemo(() => {
    const atolls = (window.ATOLLS || []).map((a) => ({
      kind: 'atoll', label: a.name, sub: `${a.count} listings · hero: ${a.hero}`, href: `prototype-browse.html?atoll=${a.id}`, icon: 'pin',
    }));
    const stays = (window.STAYS || []).map((s) => ({
      kind: 'stay', label: s.name, sub: `${s.atoll} · ${s.kindOf} · from $${s.price}/night`, href: 'prototype-stay.html', icon: 'home',
    }));
    const charters = (window.CHARTERS || []).map((c) => ({
      kind: 'charter', label: c.name, sub: `${c.route} · from $${c.price}/${c.perUnit || 'pp'}`, href: 'prototype-charter.html', icon: 'boat',
    }));
    const shop = (window.SHOP || []).map((p) => ({
      kind: 'shop', label: p.name, sub: `${p.vendor} · $${p.price}`, href: 'prototype-shop.html', icon: 'bag',
    }));
    const food = (window.FOOD || []).map((f) => ({
      kind: 'eat', label: f.name, sub: `${f.kitchen} · ${f.island}`, href: 'prototype-food.html', icon: 'mortar',
    }));
    return [...atolls, ...stays, ...charters, ...shop, ...food];
  }, []);

  const matches = React.useMemo(() => {
    if (!query) return corpus.slice(0, 8);
    const q = query.toLowerCase();
    const scored = corpus
      .map((it) => {
        const lbl = it.label.toLowerCase();
        const sub = (it.sub || '').toLowerCase();
        let score = 0;
        if (lbl.startsWith(q)) score += 10;
        if (lbl.includes(q)) score += 5;
        if (sub.includes(q)) score += 1;
        return { it, score };
      })
      .filter((x) => x.score > 0)
      .sort((a, b) => b.score - a.score)
      .slice(0, 10);
    return scored.map((x) => x.it);
  }, [corpus, query]);

  const grouped = matches.reduce((acc, it) => {
    (acc[it.kind] = acc[it.kind] || []).push(it);
    return acc;
  }, {});

  const SUGGEST_HEADINGS = { atoll: 'Atolls', stay: 'Stay', charter: 'Charter', experience: 'Experiences', shop: 'Shop', eat: 'Eat' };

  const fields = USEARCH_FIELDS[active];
  const [whereLabel, wherePlaceholder] = fields[0];

  return (
    <div style={usearchStyles.wrap} ref={containerRef}>
      <div style={usearchStyles.tabs} role="tablist">
        {USEARCH_VERTICALS.map(v => (
          <button
            key={v.id}
            role="tab"
            aria-selected={active === v.id}
            style={usearchStyles.tab(active === v.id)}
            onClick={() => setActive(v.id)}
          >
            <Icon name={v.icon} size={15}/> {v.label}
          </button>
        ))}
      </div>
      <div style={{ position: 'relative', maxWidth: '100%' }}>
        <div style={usearchStyles.bar} role="search">
          <div style={usearchStyles.field(false)} className="usearch-field">
            <label style={usearchStyles.fieldLabel}>{whereLabel}</label>
            <input
              type="text"
              value={query}
              onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
              onFocus={() => setOpen(true)}
              placeholder={wherePlaceholder}
              style={{ width: '100%', border: 'none', background: 'transparent', outline: 'none', fontSize: 14, padding: 0, color: 'var(--ink)' }}
              aria-label={whereLabel}
            />
          </div>
          {fields.slice(1).map(([label, value]) => (
            <div key={label} style={usearchStyles.field(false)} className="usearch-field">
              <span style={usearchStyles.fieldLabel}>{label}</span>
              <span style={usearchStyles.fieldValue}>{value}</span>
            </div>
          ))}
          <a
            href={query ? `prototype-browse.html?v=${active}&q=${encodeURIComponent(query)}` : `prototype-browse.html?v=${active}`}
            style={usearchStyles.go}
            aria-label="Search"
          >
            <Icon name="search" size={20} stroke={2}/>
          </a>
        </div>

        {open && (
          <div style={{
            position: 'absolute', top: 'calc(100% + 8px)', left: 0, right: 0,
            background: 'var(--surface)', borderRadius: 16,
            border: '1px solid var(--rule)',
            boxShadow: '0 24px 60px rgba(11, 31, 37, 0.18)',
            padding: 10, zIndex: 50, maxHeight: 480, overflowY: 'auto',
            color: 'var(--ink)', textAlign: 'left',
          }}>
            {matches.length === 0 ? (
              <div style={{ padding: 20, color: 'var(--ink-mute)', fontSize: 14 }}>
                No matches for <strong>{query}</strong>. Try an atoll name (Baa, Addu) or a category (lacquer, hedhikaa, dhoni).
              </div>
            ) : (
              Object.entries(grouped).map(([kind, items]) => (
                <div key={kind} style={{ marginBottom: 8 }}>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600, padding: '8px 12px 4px' }}>
                    {SUGGEST_HEADINGS[kind] || kind}
                  </div>
                  {items.map((it) => (
                    <a
                      key={it.label}
                      href={it.href}
                      style={{ display: 'grid', gridTemplateColumns: '32px 1fr auto', gap: 12, padding: '10px 12px', borderRadius: 10, alignItems: 'center', textDecoration: 'none', color: 'var(--ink)' }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--paper-2)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                    >
                      <span style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--lagoon)' }}>
                        <Icon name={it.icon} size={14}/>
                      </span>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: 'block', fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.label}</span>
                        <span style={{ display: 'block', fontSize: 12, color: 'var(--ink-mute)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.sub}</span>
                      </span>
                      <Icon name="arrowUpRight" size={14} color="var(--ink-mute)"/>
                    </a>
                  ))}
                </div>
              ))
            )}
            <div style={{
              borderTop: '1px solid var(--rule)', padding: '10px 12px',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.06em', color: 'var(--ink-mute)',
            }}>
              <span>{matches.length} matches · {active}</span>
              <span><Icon name="info" size={11}/> Hint: try "Baa", "lacquer", "iftar"</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { USearch, USEARCH_VERTICALS });
