// src/search.jsx — cross-store search with live-filter results, suggestion chips, recent queries.

function Search({ onNav, cart, addToCart }) {
  const isMobile = useMedia("(max-width: 720px)");
  const [q, setQ] = React.useState("");
  const inputRef = React.useRef(null);

  React.useEffect(() => { setTimeout(() => inputRef.current?.focus(), 50); }, []);

  const results = React.useMemo(() => {
    if (!q.trim()) return null;
    const needle = q.toLowerCase();
    const ps = PRODUCTS.filter(p =>
      p.name.toLowerCase().includes(needle) ||
      p.category.toLowerCase().includes(needle) ||
      (p.subcategory || "").toLowerCase().includes(needle)
    ).slice(0, 24);
    const ss = STORES.filter(s => s.name.toLowerCase().includes(needle) ||
      (s.tags || []).some(t => t.toLowerCase().includes(needle))).slice(0, 4);
    return { products: ps, stores: ss };
  }, [q]);

  const recent = ["modelo", "advil", "turkey sandwich", "oat milk", "lime"];
  const trending = ["Honeycrisp apples", "Cold brew", "Gatorade", "Topo Chico", "Martin's potato rolls"];

  return (
    <div style={{ maxWidth: 900, margin: "0 auto", padding: isMobile ? "14px 16px 100px" : "28px 28px 60px" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "14px 18px",
        background: "var(--surface)", border: "1px solid var(--line)",
        borderRadius: 16, boxShadow: "var(--shadow-sm)",
      }}>
        <Icons.Search size={20} stroke={1.8} style={{ color: "var(--ink-3)" }} />
        <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
          placeholder='Search "Coke", or ask "what helps a cough?"'
          style={{ flex: 1, height: 32, border: 0, background: "transparent", outline: 0, color: "var(--ink)",
                   fontSize: 16, fontFamily: "inherit" }} />
        <button className="btn-reset" onClick={() => onNav({ screen: "home" })}
          style={{ color: "var(--ink-3)", fontSize: 13, padding: "6px 10px" }}>Cancel</button>
      </div>

      {!q.trim() && (
        <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 28 }}>
          {/* Top picks block: try-this prompts in a grid */}
          <div>
            <div className="uppercase-mono" style={{ marginBottom: 12 }}>Try a question</div>
            <div style={{ display: "grid",
              gridTemplateColumns: isMobile ? "1fr 1fr" : "repeat(3, 1fr)", gap: 10 }}>
              {[
                { q: "what helps a cough?",       hint: "Cross-store · 6 results", tone: "navy" },
                { q: "modelo 12-pack near me",    hint: "Beer · 4 stores stock it" },
                { q: "everything for tacos",      hint: "Bundle · ~18 items" },
                { q: "lactose-free milk",         hint: "Pantry · 2 stores" },
                { q: "a sandwich under $10",      hint: "Deli · 14 results" },
                { q: "something for a headache",  hint: "OTC · 3 picks" },
              ].map(p => (
                <button key={p.q} className="btn-reset" onClick={() => setQ(p.q)}
                  style={{ display: "flex", flexDirection: "column", alignItems: "flex-start",
                           gap: 6, padding: "12px 14px", borderRadius: 14,
                           background: p.tone === "navy" ? "var(--navy-tint)" : "var(--surface)",
                           border: "1px solid " + (p.tone === "navy" ? "transparent" : "var(--line)"),
                           textAlign: "left" }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Icons.Sparkle size={13} stroke={1.8} style={{ color: "var(--accent)" }} />
                    <span style={{ fontSize: 13.5, color: p.tone === "navy" ? "var(--navy)" : "var(--ink)", fontWeight: 500 }}>
                      "{p.q}"
                    </span>
                  </span>
                  <span style={{ fontSize: 11.5, color: "var(--ink-4)", marginLeft: 21 }}>{p.hint}</span>
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="uppercase-mono" style={{ marginBottom: 10 }}>Recent</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {recent.map(r => (
                <button key={r} className="btn-reset" onClick={() => setQ(r)}
                  style={{ padding: "8px 14px", borderRadius: 999, background: "var(--surface-2)",
                           border: "1px solid var(--line)", fontSize: 13, color: "var(--ink-2)" }}>
                  <Icons.Clock size={12} stroke={1.8} style={{ marginRight: 6, verticalAlign: "-2px" }} />
                  {r}
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="uppercase-mono" style={{ marginBottom: 10 }}>Trending nearby</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {trending.map(r => (
                <button key={r} className="btn-reset" onClick={() => setQ(r)}
                  style={{ padding: "8px 14px", borderRadius: 999, background: "var(--navy-tint)",
                           fontSize: 13, color: "var(--navy)", fontWeight: 500 }}>
                  <Icons.Flame size={12} stroke={2} style={{ marginRight: 6, verticalAlign: "-2px" }} />
                  {r}
                </button>
              ))}
            </div>
          </div>

          {/* Browse by store — horizontal scroller on all widths */}
          <div>
            <div className="uppercase-mono" style={{ marginBottom: 10 }}>Or browse by store</div>
            <div className="no-scrollbar" style={{
              display: "grid", gridAutoFlow: "column",
              gridAutoColumns: isMobile ? "78%" : "280px",
              gap: 10,
              overflowX: "auto", overflowY: "hidden",
              scrollSnapType: "x mandatory",
              marginInline: isMobile ? -16 : 0,
              paddingInline: isMobile ? 16 : 0,
              paddingBottom: 4,
            }}>
              {STORES.map(s => (
                <button key={s.id} className="btn-reset" onClick={() => onNav({ screen: "store", storeId: s.id })}
                  style={{ display: "flex", alignItems: "center", gap: 10,
                           padding: "10px 12px", borderRadius: 12,
                           background: "var(--surface)", border: "1px solid var(--line)",
                           textAlign: "left", scrollSnapAlign: "start" }}>
                  <Ph label={s.name.split(" ")[0]} aspect="1/1" radius={8} img={s.img} seed={s.id}
                    style={{ width: 38, height: 38, flexShrink: 0, fontSize: 9 }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden",
                                  textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{s.eta}</div>
                  </div>
                  <Icons.Chevron size={14} stroke={2} style={{ color: "var(--ink-4)", flexShrink: 0 }} />
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {results && (
        <div style={{ marginTop: 24 }}>
          {results.stores.length > 0 && (
            <div style={{ marginBottom: 28 }}>
              <div className="uppercase-mono" style={{ marginBottom: 10 }}>Stores</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {results.stores.map(s => (
                  <button key={s.id} className="btn-reset" onClick={() => onNav({ screen: "store", storeId: s.id })}
                    style={{ display: "flex", alignItems: "center", gap: 14, padding: 10,
                             background: "var(--surface)", border: "1px solid var(--line)",
                             borderRadius: 14, textAlign: "left" }}>
                    <Ph label={s.name.split(" ")[0]} aspect="1/1" radius={10} img={s.img} seed={s.id} style={{ width: 56, height: 56, flexShrink: 0 }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{s.name}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{s.tagline} · {s.eta}</div>
                    </div>
                    <Icons.Chevron size={16} stroke={2} style={{ color: "var(--ink-4)" }} />
                  </button>
                ))}
              </div>
            </div>
          )}
          <div>
            <div className="uppercase-mono" style={{ marginBottom: 10 }}>
              {results.products.length} items across {new Set(results.products.map(p => storeForProduct(p).id)).size || 1} stores
            </div>
            {results.products.length === 0 ? (
              <SearchNoResults q={q} setQ={setQ} onNav={onNav} />
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: "var(--grid-gap)" }}>
                {results.products.map(p => {
                  const src = storeForProduct(p);
                  return (
                    <MiniProductCard key={p.id} p={p}
                      storeName={src.name}
                      onOpen={() => onNav({ screen: "product", storeId: src.id, productId: p.id })}
                      qty={cart.items.find(i => i.productId === p.id)?.qty || 0}
                      onAdd={() => addToCart(src.id, p.id, 1)}
                      onRemove={() => addToCart(src.id, p.id, -1)} />
                  );
                })}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

window.Search = Search;

// ─── SearchNoResults ───────────────────────────────────────────────────────
// When the live filter returns 0 items, fill the void with: re-frame as a
// query for Opa, suggest fuzzy near-matches, and offer to request the item.
function SearchNoResults({ q, setQ, onNav }) {
  // crude near-match: products whose name shares any 3-char prefix with the query word(s)
  const tokens = q.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
  const near = PRODUCTS.filter(p => {
    const n = p.name.toLowerCase();
    return tokens.some(tok => n.includes(tok.slice(0, 3)));
  }).slice(0, 6);

  return (
    <div className="fade-in" style={{
      borderRadius: "var(--radius-lg)", border: "1px solid var(--line)",
      background: "var(--surface)", overflow: "hidden",
    }}>
      {/* Top: re-frame as Opa question */}
      <div style={{
        padding: "22px 24px",
        background: "linear-gradient(135deg, var(--navy-fill) 0%, oklch(from var(--navy-fill) calc(l - 0.05) c h) 100%)",
        color: "#fff",
        display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", gap: 14, alignItems: "flex-start", maxWidth: 540 }}>
          <span style={{ width: 36, height: 36, borderRadius: 99,
                         background: "rgba(255,255,255,0.12)", color: "var(--accent)",
                         display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icons.Sparkle size={16} stroke={2} />
          </span>
          <div>
            <div style={{ fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase",
                          opacity: 0.7, marginBottom: 4 }}>Nothing matched on the shelves.</div>
            <div className="serif" style={{ fontSize: 22, lineHeight: 1.2, letterSpacing: "-0.01em" }}>
              Want Opa to figure out "{q}"?
            </div>
            <div style={{ fontSize: 13, marginTop: 6, opacity: 0.78, lineHeight: 1.5 }}>
              Sometimes what you mean isn't a product name. Opa will ask the closest 3 stores, build a cart, and show you what they propose.
            </div>
          </div>
        </div>
        <Btn variant="accent" iconRight={<Icons.Chevron size={14} stroke={2.2} />}
          onClick={() => onNav({ screen: "home" })}>
          Ask Opa
        </Btn>
      </div>

      {/* Middle: closest near-matches if any */}
      {near.length > 0 && (
        <div style={{ padding: "18px 24px", borderTop: "1px solid var(--line)" }}>
          <div className="uppercase-mono" style={{ marginBottom: 12 }}>Closest matches we did find</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {near.map(p => (
              <button key={p.id} className="btn-reset"
                onClick={() => onNav({ screen: "product", storeId: "kalymnos", productId: p.id })}
                style={{ display: "inline-flex", alignItems: "center", gap: 8,
                         padding: "8px 12px 8px 8px", borderRadius: 99,
                         background: "var(--surface-2)", border: "1px solid var(--line)",
                         fontSize: 13, color: "var(--ink-2)" }}>
                <span style={{ width: 22, height: 22, borderRadius: 99, overflow: "hidden",
                               background: "var(--navy-tint)", flexShrink: 0 }}>
                  <Ph label="" aspect="1/1" radius={99} img={productImage(p)} seed={p.id} />
                </span>
                {p.name}
                <span className="num" style={{ color: "var(--ink-4)", fontSize: 12 }}>{money(p.price)}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Bottom: shortcuts / request stocking */}
      <div style={{ padding: "16px 24px", borderTop: "1px solid var(--line)",
                    display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center",
                    justifyContent: "space-between" }}>
        <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
          Or skip the search.
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Btn size="sm" variant="secondary" icon={<Icons.Store size={13} stroke={1.8} />}
            onClick={() => onNav({ screen: "store", storeId: "kalymnos" })}>
            Browse Kalymnos
          </Btn>
          <Btn size="sm" variant="secondary" icon={<Icons.Plus size={13} stroke={2} />}
            onClick={() => alert(`Request to stock "${q}" sent to nearby store managers.`)}>
            Request "{q}"
          </Btn>
          <Btn size="sm" variant="ghost" onClick={() => setQ("")}>Clear</Btn>
        </div>
      </div>
    </div>
  );
}

window.SearchNoResults = SearchNoResults;
