// Search step — 3 scripted queries exposing HOKA's search weaknesses

const HOKA_QUERIES = [
  {
    q: 'rinning shoe',
    intent: 'typo',
    aliases: ['shoe', 'race-shoe', 'trail-shoe', 'fitness-shoe', 'running', 'everyday'],
    note: 'Typo of "running shoe" — HOKA returns 0 results. Malachyte resolves intent → full shoe catalog ranked for visitor.'
  },
  {
    q: 'light shoe for long distanse runs',
    intent: 'combo',
    aliases: ['responsive', 'performance', 'mach', 'clifton', 'neutral', 'race-shoe', 'everyday-shoe'],
    note: 'Typo ("distanse") + semantic intent (long distance → lightweight performance) — HOKA returns 0 results. Malachyte resolves to Mach 7, Clifton 10, Mach X 3.'
  },
  {
    q: 'what shoe is good for bad knees',
    intent: 'semantic',
    aliases: ['stable', 'max-cushion', 'gaviota', 'arahi', 'stinson', 'bondi'],
    note: 'Natural language — HOKA returns 0 results. Malachyte maps to stability + max-cushion shoes.'
  },
];

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

  const keywordResults = React.useMemo(() => {
    const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2);
    if (!words.length) return [];
    return window.PRODUCTS.filter(p => {
      const text = (p.name + ' ' + p.type).toLowerCase();
      return words.every(w => text.includes(w));
    }).sort((a, b) => (b.reviews || 0) - (a.reviews || 0)).slice(0, 6);
  }, [query]);

  const favWeights = window.buildFavWeights ? window.buildFavWeights(favorites) : null;
  const personalizedResults = React.useMemo(() => {
    const scripted = HOKA_QUERIES.find(s => s.q === query);
    const aliases = scripted ? scripted.aliases : [query.toLowerCase()];
    if (!aliases.length) return [];
    const pool = window.PRODUCTS.filter(p => {
      const text = (p.name + ' ' + p.type + ' ' + p.cats.join(' ')).toLowerCase();
      return aliases.some(a => text.includes(a));
    });
    // For search, don't hard-filter by gender — intent matters more than collection.
    // Persona weights still penalise opposite-gender items, keeping them ranked lower.
    return window.rankProducts(pool, persona, favWeights).slice(0, 6);
  }, [query, persona, favWeights]);

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

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

  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' : 'uploads/hoka-logo-removebg-preview.png'}
          alt={isMal ? 'Malachyte' : 'HOKA'}
          className={`sbs-col__logo sbs-col__logo--${isMal ? 'mal' : 'brand'}`}
        />
        <span className="sbs-col__caption">
          {isMal ? 'Semantic + personalized search' : 'Keyword match only'}
        </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">
            hoka.com/search?q={encodeURIComponent(query)}
            {isMal ? ' · personalized by malachyte' : ''}
          </div>
        </div>

        <HokaChrome />

        <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 HOKA…'}
              </span>
              <span className="search-bar-trigger-caret">▾</span>
            </button>
            {open && (
              <div className="search-bar-menu">
                <div className="search-bar-menu-eye">SCRIPTED QUERIES</div>
                {HOKA_QUERIES.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 ? 'SEMANTIC · PERSONALIZED' : 'KEYWORD RESULTS'}
            </div>
            <h2 className="search-head__title">
              {results.length} {results.length === 1 ? 'result' : 'results'} for "{query}"
            </h2>
            <p className="search-head__note">
              {isMal
                ? `Intent resolved → ${(scripted?.aliases || []).slice(0, 3).join(' · ')} · ranked for ${persona.userId}.`
                : results.length
                  ? `Exact keyword matches only, sorted by bestsellers. No persona signal applied.`
                  : `No products match those exact words. HOKA's search can't handle typos or intent queries.`}
            </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 });
