// Search step — side-by-side: keyword search vs personalized search
// Each visitor gets queries written from THEIR intent (a pilates shopper
// types pilates words; a runner types run words; a men's shopper types
// golf words). Both sides filter the catalog to the visitor's gender so
// post-PLP we never leak cross-gender products.

const QUERY_SETS = {
  pilates: [
    { q: 'butery soft leggins',           intent: 'typo',     aliases: ['butter', 'lux', 'legging'] },
    { q: 'what to wear to pilates class', intent: 'semantic', aliases: ['studio', 'legging', 'bra'] },
    { q: 'matching set for studio',       intent: 'combo',    aliases: ['set', 'studio'] },
  ],
  runner: [
    { q: 'lightsreme shrts',              intent: 'typo',     aliases: ['lightstreme', 'short', 'performance'] },
    { q: 'outfit for morning run',        intent: 'semantic', aliases: ['run', 'short', 'tank'] },
    { q: 'high waist running tight',      intent: 'combo',    aliases: ['legging', 'waistband', 'run'] },
  ],
  'mens-active': [
    { q: 'perforance jogers',             intent: 'typo',     aliases: ['performance', 'jogger'] },
    { q: 'what to wear golfing',          intent: 'semantic', aliases: ['golf', 'tee', 'short', 'pant'] },
    { q: 'soft tee for warm days',        intent: 'combo',    aliases: ['tee', 'performance', 'cationic'] },
  ],
};

function StepSearch({ state, setState }) {
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  const favorites = state.favorites || [];

  const scriptedQueries = QUERY_SETS[persona.id] || QUERY_SETS.pilates;
  const [query, setQuery] = React.useState(scriptedQueries[0].q);

  // When persona changes, snap query to that persona's first scripted query.
  React.useEffect(() => {
    setQuery(scriptedQueries[0].q);
  }, [persona.id]);

  const genderPool = React.useMemo(
    () => window.PRODUCTS.filter(p => p.gender === persona.gender),
    [persona.gender]
  );

  const keywordResults = React.useMemo(() => {
    // 1. Try literal word match (typos & semantic queries fail here)
    // 2. Fall back to alias category guess in catalog order (no persona ranking)
    const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2);
    if (!words.length) return genderPool.slice(0, 6);

    const literal = genderPool.filter(p => {
      const n = (p.name + ' ' + p.type).toLowerCase();
      return words.every(w => n.includes(w));
    }).sort((a, b) => (a.sku || '').localeCompare(b.sku || ''));
    if (literal.length) return literal.slice(0, 6);

    const scripted = scriptedQueries.find(s => s.q === query);
    const aliases = scripted ? scripted.aliases : [];
    if (!aliases.length) return genderPool.slice(0, 6);
    const fallback = genderPool.filter(p => {
      const n = (p.name + ' ' + p.type).toLowerCase();
      return aliases.some(a => p.cats.includes(a) || n.includes(a));
    }).sort((a, b) => (a.sku || '').localeCompare(b.sku || ''));
    return fallback.length ? fallback.slice(0, 6) : genderPool.slice(0, 6);
  }, [query, genderPool, scriptedQueries]);

  const favWeights = window.buildFavWeights ? window.buildFavWeights(favorites) : null;
  const personalizedResults = React.useMemo(() => {
    const scripted = scriptedQueries.find(s => s.q === query);
    const aliases = scripted ? scripted.aliases : [query.toLowerCase()];
    if (!aliases.length) return window.rankProducts(genderPool, persona, favWeights).slice(0, 6);
    const pool = genderPool.filter(p => {
      const n = (p.name + ' ' + p.type).toLowerCase();
      return aliases.some(a => p.cats.includes(a) || n.includes(a));
    });
    const ranked = window.rankProducts(pool.length ? pool : genderPool, persona, favWeights);
    return ranked.slice(0, 6);
  }, [query, genderPool, persona, favWeights, scriptedQueries]);

  return (
    <div className="sbs-shell">
      <div className="sbs-grid">
        <SearchColumn mode="alpha"     query={query} setQuery={setQuery} results={keywordResults}     persona={persona} scriptedQueries={scriptedQueries} />
        <SearchColumn mode="malachyte" query={query} setQuery={setQuery} results={personalizedResults} persona={persona} scriptedQueries={scriptedQueries} favWeights={favWeights} />
      </div>
    </div>
  );
}

function SearchColumn({ mode, query, setQuery, results, persona, favWeights, scriptedQueries }) {
  const isMal = mode === 'malachyte';
  const handleImgErr = (e) => { e.target.src = window.PRODUCT_FALLBACK; };
  const [open, setOpen] = React.useState(false);

  const pick = (q) => { setQuery(q); setOpen(false); };
  const aliasesForCurrentQuery = scriptedQueries.find(s => s.q === query)?.aliases || [];

  return (
    <div className={`sbs-col sbs-col--${mode}`}>
      <div className="sbs-col__head">
        <span className="sbs-col__tag">{isMal ? 'AFTER' : 'BEFORE'}</span>
        <img
          src={isMal ? 'assets/malachyte-logo-gradient.png' : 'assets/90degree-logo.png'}
          alt={isMal ? 'Malachyte' : '90 Degree by Reflex'}
          className={`sbs-col__logo sbs-col__logo--${isMal ? 'mal' : 'ndr'}`}
        />
        <span className="sbs-col__caption">{isMal ? 'Personalized search' : 'Keyword match'}</span>
      </div>

      <div className="sbs-col__viewport">
        <div className="demo-urlbar">
          <div className="demo-urlbar__dots"><span /><span /><span /></div>
          <div className="demo-urlbar__url">
            90degreebyreflex.com/search?q={encodeURIComponent(query)}{isMal ? ' · personalized by malachyte' : ''}
          </div>
        </div>

        <WihaChrome />

        <div className="wiha-plp-root">
          <div className={`search-bar-row ${open ? 'is-active' : ''}`}>
            <button className="search-bar-trigger" onClick={() => setOpen(o => !o)}>
              <span className={`search-bar-trigger-text ${!query ? 'is-placeholder' : ''}`}>
                {query || 'Search 90 Degree by Reflex…'}
              </span>
              <span className="search-bar-trigger-caret">▾</span>
            </button>

            {open && (
              <div className="search-bar-menu">
                <div className="search-bar-menu-eye">SCRIPTED QUERIES · {persona.userId}</div>
                {scriptedQueries.map(s => (
                  <button
                    key={s.q}
                    className={`search-bar-menu-item ${s.q === query ? 'is-selected' : ''}`}
                    onClick={() => pick(s.q)}
                  >
                    <span className="search-bar-menu-item-q">{s.q}</span>
                    <span className={`search-bar-menu-item-intent search-bar-menu-item-intent--${s.intent}`}>{s.intent}</span>
                  </button>
                ))}
              </div>
            )}
          </div>

          <div className="search-head">
            <div className="search-head__eye">
              {isMal ? 'PERSONALIZED RESULTS' : 'KEYWORD RESULTS'}
            </div>
            <h2 className="search-head__title">
              {results.length} matches for "{query}"
            </h2>
            <p className="search-head__note">
              {isMal
                ? `Resolved to ${aliasesForCurrentQuery.join(' + ') || 'intent vector'} — ranked for ${persona.userId}.`
                : `Returned in catalog order. No persona signal applied.`}
            </p>
          </div>

          <div className="wiha-grid">
            {results.map((p, i) => (
              <ProductCard
                key={p.id}
                product={p}
                index={i}
                mode={mode}
                persona={persona}
                favWeights={favWeights}
                isFav={false}
                onFav={() => {}}
                onImgErr={handleImgErr}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StepSearch });
