// Search step — GreenPan's open-search drawer with a demo query picker.
// Default state: empty drawer (Most Searched + Recent Searches grid).
// Selecting a query from the picker fills the search bar and shows results.

const SEARCH_QUERIES = [
  { id: 'none', label: '— pick a demo query —', q: '', note: '', intent: 'Empty state' },
  {
    id: 'misspell',
    label: 'ceramik nonstick',
    q: 'ceramik nonstick',
    note: 'Misspelling of "ceramic nonstick"',
    intent: 'Typo tolerance',
    interpretation: 'ceramic nonstick',
    expectedThuma: 'and',
  },
  {
    id: 'semantic',
    label: 'pan that won\'t ruin scrambled eggs',
    q: 'pan that won\'t ruin scrambled eggs',
    note: 'Long-tail intent — GreenPan matches no keywords',
    intent: 'Semantic intent',
    interpretation: 'ceramic nonstick frypan · stay-cool · easy release',
    expectedThuma: 'and',
  },
  {
    id: 'aesthetic',
    label: 'blue pots like Tucci has',
    q: 'blue pots like Tucci has',
    note: 'Aesthetic descriptor — GreenPan keyword-matches "blue" + "pots", returns noisy mix',
    intent: 'Aesthetic match',
    interpretation: 'Marino Blue / Twilight cookware · Tucci collection',
    expectedThuma: 'noisy',
  },
];

const RECENT_PRODUCT_IDS = ['stanley-tucci-11pc-marino-blue', 'valencia-pro-19pc-sage', 'frost-pro-ice-cream', 'reserve-bakeware-7pc-twilight'];
function getRecentProducts() {
  const all = window.PRODUCTS || [];
  const byId = (id) => all.find(p => p.id === id);
  const preferred = RECENT_PRODUCT_IDS.map(byId).filter(Boolean);
  if (preferred.length === 4) return preferred;
  return all.filter(p => p.img).slice(0, 4);
}

function StepSearch({ state, setState, mode }) {
  const [queryId, setQueryId] = React.useState('none');
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const query = SEARCH_QUERIES.find(q => q.id === queryId);
  const isEmpty = !query.q;
  const persona = window.PERSONAS.find(p => p.id === state.persona) || window.PERSONAS[0];
  const recentProducts = getRecentProducts();

  const barRef = React.useRef(null);
  React.useEffect(() => {
    if (!drawerOpen) return;
    const onDocClick = (e) => {
      if (barRef.current && !barRef.current.contains(e.target)) setDrawerOpen(false);
    };
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, [drawerOpen]);

  const allProducts = window.PRODUCTS || [];

  // GreenPan's literal keyword search — behavior varies per query to match real quirks.
  const STOPWORDS = new Set(['for','the','a','an','and','of','with','to','my','in','on','that','fits','room','colored','at','has','like','wont','won\'t','will','it']);
  const literalMatches = (q, mode = 'and') => {
    const tokens = q.toLowerCase().split(/\s+/).filter(t => t && !STOPWORDS.has(t));
    if (!tokens.length) return [];
    return allProducts.filter(p => {
      const text = (p.name + ' ' + (p.brand || '') + ' ' + (p.cats || []).join(' ')).toLowerCase();
      return mode === 'noisy'
        ? tokens.some(t => text.includes(t))
        : tokens.every(t => text.includes(t));
    });
  };

  // Malachyte: hand-curated by query — semantic / typo / aesthetic understanding.
  const malachyteForQuery = () => {
    if (!query.q) return [];
    const byId = (id) => allProducts.find(x => x.id === id);
    const order = {
      misspell: ['valencia-pro-19pc-sage', 'reserve-pro-10pc-cream', 'valencia-pro-frypan-set-gray', 'gp5-frypan-set-cloud-cream', 'valencia-pro-19pc-gray', 'spectra-thermobond-10pc'],
      semantic: ['valencia-pro-frypan-set-gray', 'valencia-pro-frypan-set-twilight', 'gp5-frypan-set-cloud-cream', 'reserve-pro-10pc-cream'],
      aesthetic: ['stanley-tucci-11pc-marino-blue', 'tucci-pizza-oven-marino-blue', 'reserve-pro-stainless-12pc-twilight', 'valencia-pro-frypan-set-twilight', 'reserve-bakeware-7pc-twilight', 'titanium-ultimate-knife-block-16'],
    };
    const ids = order[queryId] || [];
    return ids.map(byId).filter(Boolean);
  };

  const thumaResults = literalMatches(query.q, query.expectedThuma === 'noisy' ? 'noisy' : 'and');
  const malachyteResults = malachyteForQuery().slice(0, 8);

  return (
    <div className="search-root">
      {/* Search bar — custom dropdown */}
      <div ref={barRef} className={`search-bar-row ${drawerOpen || !isEmpty ? 'is-active' : ''}`}>
        <button
          type="button"
          className="search-bar-trigger"
          onClick={() => setDrawerOpen(d => !d)}
        >
          <span className={`search-bar-trigger-text ${query.q ? '' : 'is-placeholder'}`}>
            {query.q || 'Search'}
          </span>
          <svg className="search-bar-trigger-caret" width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M3.5 5.5l3.5 3.5 3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        {drawerOpen && (
          <div className="search-bar-menu">
            <div className="search-bar-menu-eye">Demo queries</div>
            {SEARCH_QUERIES.map(q => (
              <button
                key={q.id}
                type="button"
                className={`search-bar-menu-item ${q.id === queryId ? 'is-selected' : ''} ${q.id === 'none' ? 'is-empty' : ''}`}
                onClick={() => { setQueryId(q.id); setDrawerOpen(false); }}
              >
                <span className="search-bar-menu-item-q">{q.q || '— clear search —'}</span>
                {q.intent && q.intent !== 'Empty state' && (
                  <span className="search-bar-menu-item-intent">{q.intent}</span>
                )}
              </button>
            ))}
          </div>
        )}
      </div>

      {isEmpty && <SearchDrawer recent={recentProducts} />}

      {!isEmpty && mode === 'alpha' && (
        <GreenPanSearchResults query={query} results={thumaResults} recent={recentProducts} />
      )}
      {!isEmpty && mode === 'malachyte' && (
        <MalachyteSearchResults query={query} results={malachyteResults} persona={persona} />
      )}
    </div>
  );
}

function SearchDrawer({ recent }) {
  return (
    <div className="search-drawer">
      <div className="search-drawer-left">
        <div className="search-suggest-eye">Most Searched</div>
        <a>Stanley Tucci Cookware</a>
        <a>Frost Ice Cream Maker</a>
        <a>Valencia Pro Frypan</a>
        <a>Bakeware Set</a>
      </div>
      <div className="search-drawer-right">
        <div className="search-suggest-eye search-suggest-eye--strong">Recent Searches</div>
        <div className="search-recent-grid">
          {recent.map((p) => (
            <div key={p.id} className="search-recent-card">
              <div className="search-recent-img"><img src={p.img} alt={p.name} /></div>
              <div className="search-recent-name">{p.name}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function GreenPanSearchResults({ query, results, recent }) {
  if (results.length === 0) {
    return (
      <div className="search-results">
        <div className="search-empty">
          <div className="search-empty-eye">No results</div>
          <h3>We couldn't find anything for "{query.q}"</h3>
          <p>Check your spelling or try a different keyword.</p>
        </div>
        <SearchDrawer recent={recent} />
      </div>
    );
  }
  return (
    <div className="search-results">
      <div className="search-results-head">
        <h3>{results.length} result{results.length === 1 ? '' : 's'} for "{query.q}"</h3>
      </div>
      <div className="search-grid">
        {results.slice(0, 8).map(p => <SearchCard key={p.id} p={p} />)}
      </div>
    </div>
  );
}

function MalachyteSearchResults({ query, results, persona }) {
  return (
    <div className="search-results">
      <div className="search-results-head">
        <div className="mal-results-banner">
          <span className="mal-results-tag">MALACHYTE</span>
          <span>
            Read "<b>{query.q}</b>" as <b>{query.interpretation}</b> · ranked for <b>{persona.name}</b>
          </span>
        </div>
        <h3>{results.length} result{results.length === 1 ? '' : 's'}</h3>
      </div>
      <div className="search-grid">
        {results.map(p => <SearchCard key={p.id} p={p} />)}
      </div>
    </div>
  );
}

function SearchCard({ p }) {
  return (
    <a className="search-card">
      <div className="search-card-img">
        {p.img ? <img src={p.img} alt={p.name} /> : <div className="search-card-ph" />}
      </div>
      <div className="search-card-name">{p.name}</div>
      <div className="search-card-price">${p.price.toFixed(2)}</div>
    </a>
  );
}

Object.assign(window, { StepSearch });
