// src/product.jsx — Product detail with customization.
// Customize pattern variants: 'modal' | 'sheet' | 'inline' (controlled via tweaks).
// For the sandwich builder, uses DELI_BUILDER spec. For non-customizable products, shows a simpler detail.

function Price({ value, size = 22 }) {
  return <span className="num" style={{ fontSize: size, fontWeight: 600 }}>{money(value)}</span>;
}

function BuilderPanel({ builder, value, setValue, helpMode }) {
  const isMobile = useMedia("(max-width: 720px)");
  // value = { bread: 'hero', protein: 'turkey', ... , qty: 1, notes: '' }
  const toggleMulti = (sec, id) => {
    const arr = value[sec.id] || [];
    if (arr.includes(id)) setValue({ ...value, [sec.id]: arr.filter(x => x !== id) });
    else if (!sec.max || arr.length < sec.max) setValue({ ...value, [sec.id]: [...arr, id] });
  };
  const setSingle = (secId, id) => setValue({ ...value, [secId]: id });

  // Accordion: single-open. Click to open replaces, click open header to close.
  const firstRequired = builder.sections.find(s => s.required)?.id;
  const [openId, setOpenId] = React.useState(firstRequired || null);
  const toggleOpen = (id) => setOpenId(prev => prev === id ? null : id);

  // Summary of the current selection in a section — shown when it's collapsed.
  const summarize = (sec) => {
    if (sec.multi) {
      const ids = value[sec.id] || [];
      if (ids.length === 0) return "None";
      return ids.map(id => sec.options.find(o => o.id === id)?.label).filter(Boolean).join(", ");
    }
    const v = value[sec.id];
    if (!v) return "—";
    return sec.options.find(o => o.id === v)?.label || "—";
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {builder.sections.map(sec => {
        const isOpen = openId === sec.id;
        const recommended = helpMode && sec.options.find(o => o.popular);
        return (
          <section key={sec.id} style={{
            border: "1px solid var(--line)", borderRadius: 12,
            background: "var(--surface)",
            overflow: "hidden",
            transition: "box-shadow 0.15s",
            boxShadow: isOpen ? "var(--shadow-sm)" : "none",
          }}>
            <button className="btn-reset" onClick={() => toggleOpen(sec.id)}
              aria-expanded={isOpen}
              style={{
                width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                padding: "14px 16px",
                textAlign: "left",
              }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0, flex: 1 }}>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
                  <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>{sec.label}</h3>
                  {sec.required && <span style={{ fontSize: 11, color: "var(--accent)", fontWeight: 500 }}>Required</span>}
                  {sec.multi && <span style={{ fontSize: 11, color: "var(--ink-4)" }}>{sec.max ? `up to ${sec.max}` : "multi"}</span>}
                </div>
                {!isOpen && (
                  <div style={{ fontSize: 13, color: "var(--ink-3)",
                                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {summarize(sec)}
                  </div>
                )}
              </div>
              <Icons.ChevronDown size={16} stroke={2}
                style={{ color: "var(--ink-3)", transform: isOpen ? "rotate(180deg)" : "none", transition: "transform 0.18s" }} />
            </button>
            {isOpen && (
              <div className="fade-in" style={{ padding: "0 14px 14px" }}>
                <div style={{ display: "grid",
                              gridTemplateColumns: isMobile ? "1fr" : "repeat(auto-fill, minmax(180px, 1fr))",
                              gap: 6 }}>
                  {sec.options.map(opt => {
                    const selected = sec.multi
                      ? (value[sec.id] || []).includes(opt.id)
                      : value[sec.id] === opt.id;
                    const isRec = helpMode && recommended && opt.id === recommended.id && !selected;
                    return (
                      <button key={opt.id} className="btn-reset"
                        onClick={() => sec.multi ? toggleMulti(sec, opt.id) : setSingle(sec.id, opt.id)}
                        style={{
                          display: "flex", alignItems: "center", justifyContent: "space-between",
                          padding: "10px 12px", borderRadius: 10,
                          background: selected ? "var(--navy-fill)" : "var(--surface)",
                          border: "1px solid " + (selected ? "var(--navy)" : isRec ? "var(--accent)" : "var(--line)"),
                          color: selected ? "var(--on-navy, #fff)" : "var(--ink-2)",
                          fontSize: 13, fontWeight: 500, textAlign: "left",
                          position: "relative",
                          transition: "background 0.12s",
                        }}>
                        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <span style={{
                            width: 16, height: 16, borderRadius: sec.multi ? 4 : 999,
                            border: "1.5px solid " + (selected ? "#fff" : "var(--line)"),
                            background: selected ? "rgba(255,255,255,0.2)" : "transparent",
                            display: "inline-flex", alignItems: "center", justifyContent: "center",
                            color: "#fff", flexShrink: 0,
                          }}>
                            {selected && <Icons.Check size={10} stroke={3} />}
                          </span>
                          {opt.label}
                          {opt.popular && <span style={{ fontSize: 10, color: "var(--accent)", fontWeight: 600 }}>· hot</span>}
                        </span>
                        {opt.price !== 0 && (
                          <span className="num" style={{ fontSize: 12, color: "var(--ink-4)" }}>
                            {opt.price > 0 ? `+${money(opt.price)}` : money(opt.price)}
                          </span>
                        )}
                        {isRec && (
                          <span style={{ position: "absolute", top: -8, right: 8,
                                         background: "var(--accent)", color: "#fff",
                                         fontSize: 9.5, fontWeight: 600, padding: "2px 6px", borderRadius: 999,
                                         letterSpacing: "0.04em", textTransform: "uppercase" }}>
                            Opa pick
                          </span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
          </section>
        );
      })}

      {/* AI notes field — always visible, below the accordion */}
      <section style={{ marginTop: 8 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}>
            Anything else? <Icons.Sparkle size={13} stroke={2} style={{ color: "var(--accent)" }} />
          </h3>
          <span style={{ fontSize: 11, color: "var(--ink-4)" }}>AI understands "make it spicy, no mayo"</span>
        </div>
        <textarea value={value.notes || ""} onChange={e => setValue({ ...value, notes: e.target.value })}
          placeholder='e.g. "pressed hot, extra pickles, skip the mayo"'
          style={{
            width: "100%", minHeight: 60, padding: 12,
            border: "1px solid var(--line)", borderRadius: 10,
            background: "var(--surface)", color: "var(--ink)",
            fontFamily: "inherit", fontSize: 14, resize: "vertical", outline: "none",
          }} />
      </section>
    </div>
  );
}

function computePrice(p, builderValue) {
  if (!p.customizable) return p.price;
  const b = DELI_BUILDER;
  let sum = b.basePrice;
  for (const sec of b.sections) {
    const v = builderValue[sec.id];
    if (sec.multi) {
      (v || []).forEach(id => { const o = sec.options.find(o => o.id === id); if (o) sum += o.price; });
    } else {
      const o = sec.options.find(o => o.id === v);
      if (o) sum += o.price;
    }
  }
  return Math.max(0, sum);
}

function defaultBuilderValue() {
  return {
    bread: "hero", protein: "turkey", cheese: "provolone",
    toppings: ["lettuce", "tomato"], sauce: ["mayo"],
    prep: "cold", qty: 1, notes: "",
  };
}

function Product({ storeId, productId, onNav, cart, addToCart, tweaks, showToast }) {
  const isMobile = useMedia("(max-width: 720px)");
  const p = PRODUCT_INDEX[productId] || PRODUCT_INDEX["deli-custom"];
  const store = STORES.find(s => s.id === storeId) || STORES[0];
  const [bv, setBv] = React.useState(defaultBuilderValue);
  const [qty, setQty] = React.useState(1);
  const [showCustomize, setShowCustomize] = React.useState(false); // used for modal / sheet variants
  const [helpMode, setHelpMode] = React.useState(false);
  const isCustom = !!p.customizable;

  // Toggling "Help me choose" populates the popular / first-option pick for every
  // section at once, so it's a real "do it for me" action not just a subtle badge.
  const applyOpaPicks = () => {
    if (!isCustom) return;
    const next = { ...bv };
    for (const sec of DELI_BUILDER.sections) {
      const pick = sec.options.find(o => o.popular) || sec.options[0];
      if (!pick) continue;
      if (sec.multi) {
        const current = next[sec.id] || [];
        const already = current.includes(pick.id);
        if (!already) {
          const max = sec.max || Infinity;
          next[sec.id] = current.length >= max ? [pick.id, ...current.slice(0, max - 1)] : [...current, pick.id];
        }
      } else {
        next[sec.id] = pick.id;
      }
    }
    setBv(next);
  };
  const toggleHelp = () => {
    setHelpMode(v => {
      const nextOn = !v;
      if (nextOn) applyOpaPicks();
      return nextOn;
    });
  };
  // Pattern was a tweak with inline/modal/sheet variants. For the demo we've
  // committed to inline — the modal/sheet branches below are kept in source
  // as a fallback if future product types need overlay behavior, but no UI
  // exposes a way to switch them.
  const pattern = "inline";

  const unitPrice = computePrice(p, bv);
  const total = unitPrice * qty;

  const onAdd = () => {
    addToCart(storeId, p.id, qty);
    showToast(`Added ${qty} × ${p.name}`);
    onNav({ screen: "store", storeId });
  };

  const builderInline = isCustom;
  const builderModal  = false;
  const builderSheet  = false;

  return (
    <div style={{ maxWidth: 1240, margin: "0 auto", padding: isMobile ? "14px 16px 120px" : "28px 28px 60px" }}>
      {/* Breadcrumb + back */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
        <button className="btn-reset" onClick={() => onNav({ screen: "store", storeId })}
          style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "6px 12px 6px 8px", borderRadius: 999,
            background: "var(--surface)", border: "1px solid var(--line)",
            fontSize: 12.5, fontWeight: 500, color: "var(--ink-2)",
          }}>
          <Icons.ArrowLeft size={14} stroke={2} /> Back to {store.name}
        </button>
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--ink-3)" }}>
          <button className="btn-reset" onClick={() => onNav({ screen: "store", storeId })}>{store.name}</button>
          <Icons.Chevron size={12} stroke={2} />
          <span style={{ color: "var(--ink)" }}>{p.name}</span>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.1fr 1fr", gap: 40 }}>
        {/* Left: media + facts */}
        <div>
          <Ph label={p.name} aspect="4/3" radius="var(--radius-lg)" img={productImage(p)} seed={p.id + "-hero"} style={{ marginBottom: 12 }} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8 }}>
            <Ph label="angle 2" aspect="1/1" radius={10} img={productImage(p)} seed={p.id + "-a2"} />
            <Ph label="angle 3" aspect="1/1" radius={10} img={productImage(p)} seed={p.id + "-a3"} />
            <Ph label="detail" aspect="1/1" radius={10} img={productImage(p)} seed={p.id + "-a4"} />
          </div>
          {!isMobile && (
            <div style={{ marginTop: 24, padding: 16, borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
              <div className="uppercase-mono" style={{ marginBottom: 8 }}>From {store.name}</div>
              <div style={{ display: "flex", gap: 16, fontSize: 13, color: "var(--ink-2)", flexWrap: "wrap" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icons.Clock size={13} stroke={1.8} /> {store.eta}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icons.Pin size={13} stroke={1.8} /> {store.distance}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icons.ShieldCheck size={13} stroke={1.8} /> Fresh-made daily</span>
              </div>
            </div>
          )}
        </div>

        {/* Right: product content */}
        <div>
          {p.popular && <Pill tone="navy" icon={<Icons.Flame size={11} stroke={2} />} style={{ marginBottom: 10 }}>Popular at {store.name}</Pill>}
          <h1 className="serif" style={{ fontSize: 38, margin: 0, letterSpacing: "-0.02em", lineHeight: 1.1 }}>{p.name}</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 10, fontSize: 13, color: "var(--ink-3)" }}>
            <Price value={unitPrice} size={22} />
            <span>·</span>
            <span>{p.unit}</span>
            {isCustom && <><span>·</span><span style={{ color: "var(--navy)" }}>Fully customizable</span></>}
          </div>
          {p.desc && <p style={{ marginTop: 14, fontSize: 15, color: "var(--ink-2)", lineHeight: 1.5 }}>{p.desc}</p>}

          {builderInline && (
            <div style={{ marginTop: 24, padding: 20, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 18, paddingBottom: 6 }}>
                <h2 className="serif" style={{ margin: 0, fontSize: 22, lineHeight: 1.3, paddingBottom: 2 }}>Build your sandwich</h2>
                <button className="btn-reset" onClick={toggleHelp}
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 6,
                    padding: "7px 13px", borderRadius: 999,
                    background: helpMode ? "var(--accent)" : "var(--surface-2)",
                    color: helpMode ? "#fff" : "var(--ink-2)",
                    border: "1px solid " + (helpMode ? "var(--accent)" : "var(--line)"),
                    fontSize: 12.5, fontWeight: 500,
                  }}>
                  <Icons.Sparkle size={13} stroke={2} /> {helpMode ? "Opa is helping" : "Help me choose"}
                </button>
              </div>
              <BuilderPanel builder={DELI_BUILDER} value={bv} setValue={setBv} helpMode={helpMode} />
            </div>
          )}

          {(builderModal || builderSheet) && (
            <div style={{ marginTop: 20 }}>
              <Btn variant="secondary" full icon={<Icons.Sliders size={16} stroke={1.8} />}
                onClick={() => setShowCustomize(true)}>
                Customize this sandwich
              </Btn>
            </div>
          )}

          {/* Qty + add */}
          <div style={{
            position: "sticky", bottom: 0, marginTop: 28,
            padding: "16px 0",
            display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap",
            background: "linear-gradient(180deg, transparent, var(--bg) 30%)",
          }}>
            <div style={{ display: "inline-flex", alignItems: "center", height: 52, border: "1px solid var(--line)", borderRadius: 999, background: "var(--surface)" }}>
              <button className="btn-reset" onClick={() => setQty(q => Math.max(1, q-1))}
                style={{ width: 48, height: 48, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--ink-2)" }}>
                <Icons.Minus size={16} stroke={2.2} />
              </button>
              <span className="num" style={{ minWidth: 24, textAlign: "center", fontSize: 16, fontWeight: 600 }}>{qty}</span>
              <button className="btn-reset" onClick={() => setQty(q => q+1)}
                style={{ width: 48, height: 48, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--ink-2)" }}>
                <Icons.Plus size={16} stroke={2.2} />
              </button>
            </div>
            <Btn variant="primary" size="lg" onClick={onAdd} style={{ flex: 1, minWidth: 200 }}>
              Add {qty} to cart · <span className="num" style={{ marginLeft: 2 }}>{money(total)}</span>
            </Btn>
          </div>
        </div>
      </div>

      {/* Goes with */}
      {GOES_WITH[p.id] && (
        <div style={{ marginTop: 40 }}>
          <GoesWithStrip anchorId={p.id}
            addToCart={(pid) => addToCart(storeId, pid, 1)}
            onOpen={(pid) => onNav({ screen: "product", storeId, productId: pid })} />
        </div>
      )}

      {/* Modal variant */}
      {builderModal && showCustomize && (
        <div style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(10,31,68,0.4)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}
             onClick={() => setShowCustomize(false)}>
          <div className="scale-in" onClick={(e) => e.stopPropagation()}
            style={{ background: "var(--surface)", borderRadius: "var(--radius-lg)", padding: 24, maxWidth: 640, width: "100%", maxHeight: "85vh", overflow: "auto", boxShadow: "var(--shadow-lg)" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
              <h2 className="serif" style={{ fontSize: 24, margin: 0 }}>Customize</h2>
              <button className="btn-reset" onClick={() => setShowCustomize(false)}
                style={{ width: 36, height: 36, borderRadius: 999, background: "var(--surface-2)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                <Icons.Close size={16} stroke={2} />
              </button>
            </div>
            <BuilderPanel builder={DELI_BUILDER} value={bv} setValue={setBv} helpMode={helpMode} />
            <div style={{ marginTop: 20, display: "flex", gap: 10 }}>
              <Btn variant="primary" size="lg" full onClick={() => setShowCustomize(false)}>
                Save · <span className="num" style={{ marginLeft: 4 }}>{money(unitPrice)}</span>
              </Btn>
            </div>
          </div>
        </div>
      )}

      {/* Side drawer variant (from the right) */}
      {builderSheet && showCustomize && (
        <div style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(10,31,68,0.4)" }}
             onClick={() => setShowCustomize(false)}>
          <div className="drawer-in" onClick={(e) => e.stopPropagation()}
            style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: "min(480px, 92vw)",
                     background: "var(--surface)", boxShadow: "-12px 0 40px rgba(0,0,0,0.18)",
                     padding: "18px 20px 20px",
                     display: "flex", flexDirection: "column", overflow: "hidden" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16, flexShrink: 0 }}>
              <h2 className="serif" style={{ fontSize: 22, margin: 0 }}>Customize</h2>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <button className="btn-reset" onClick={toggleHelp}
                  style={{ display: "inline-flex", alignItems: "center", gap: 6,
                    padding: "6px 11px", borderRadius: 999,
                    background: helpMode ? "var(--accent)" : "var(--surface-2)",
                    color: helpMode ? "#fff" : "var(--ink-2)",
                    border: "1px solid " + (helpMode ? "var(--accent)" : "var(--line)"),
                    fontSize: 12, fontWeight: 500 }}>
                  <Icons.Sparkle size={12} stroke={2} /> Help
                </button>
                <button className="btn-reset" onClick={() => setShowCustomize(false)}
                  style={{ width: 34, height: 34, borderRadius: 999, background: "var(--surface-2)",
                           display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <Icons.Close size={16} stroke={2} />
                </button>
              </div>
            </div>
            <div style={{ flex: 1, overflowY: "auto", margin: "0 -20px", padding: "0 20px" }}>
              <BuilderPanel builder={DELI_BUILDER} value={bv} setValue={setBv} helpMode={helpMode} />
            </div>
            <Btn variant="primary" size="lg" full onClick={() => setShowCustomize(false)} style={{ marginTop: 16, flexShrink: 0 }}>
              Save · <span className="num" style={{ marginLeft: 4 }}>{money(unitPrice)}</span>
            </Btn>
          </div>
        </div>
      )}
    </div>
  );
}

window.Product = Product;
