// ProductScreen — single sensory-bin detail page.
const PS = window.TheLittleScoopDesignSystem_cee583;
const PS_THEME_BG = {
  spring: "linear-gradient(135deg,#DCF2BE,#B6E27F)",
  summer: "linear-gradient(135deg,#FFEFB8,#FFDC6B)",
  ocean: "linear-gradient(135deg,#C5F1F6,#86E0EA)",
  berry: "linear-gradient(135deg,#FFD8E1,#FF9DB3)",
  cosmic: "linear-gradient(135deg,#E4D8F8,#C3A9EE)",
};

function Thumb({ bg, active, onClick }) {
  return <button onClick={onClick} style={{ width: 64, height: 64, borderRadius: "var(--radius-md)", background: bg,
    border: active ? "3px solid var(--brand-primary)" : "2px solid var(--border-soft)", cursor: "pointer", flex: "none" }} />;
}

function ProductScreen({ product, onAdd, onBack, onOpen, mobile }) {
  const { Button, Badge, QuantityStepper, ProductCard } = PS;
  const [qty, setQty] = React.useState(1);
  const gallery = (product.gallery && product.gallery.length) ? product.gallery : (product.image ? [product.image] : []);
  const [mainImg, setMainImg] = React.useState(gallery[0] || null);
  React.useEffect(() => { setMainImg((product.gallery && product.gallery[0]) || product.image || null); }, [product.id]);
  const TEAL = "#94d1c5";
  const hasOptions = typeof product.priceNoBin === "number";
  const fillers = Array.isArray(product.fillers) ? product.fillers : null;
  const [binOpt, setBinOpt] = React.useState("with");
  const [filler, setFiller] = React.useState(fillers ? fillers[0] : null);
  const unitPrice = hasOptions ? (binOpt === "with" ? product.price : product.priceNoBin) : product.price;
  const fillerLabel = filler || "";
  const addItem = () => onAdd({
    ...product,
    id: product.id + "-" + binOpt + (fillers ? "-" + filler : ""),
    title: product.title + (hasOptions ? ` (${binOpt === "with" ? "with bin" : "no bin"}${fillers ? ", " + fillerLabel : ""})` : ""),
    price: unitPrice,
  }, qty);
  const OptBtn = ({ selected, onClick, children, sub }) => (
    <button onClick={onClick} style={{ flex: 1, cursor: "pointer", textAlign: "left", padding: "12px 16px", borderRadius: "var(--radius-lg)",
      border: selected ? `2px solid ${TEAL}` : "2px solid var(--border-strong)", background: selected ? "rgba(148,209,197,0.16)" : "#fff",
      display: "flex", flexDirection: "column", gap: 2, transition: "all var(--dur-fast)" }}>
      <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-md)", color: "var(--text-strong)" }}>{children}</span>
      {sub && <span style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: "var(--text-sm)", color: selected ? TEAL : "var(--text-muted)" }}>{sub}</span>}
    </button>
  );
  const OptGroup = ({ label, children }) => (
    <div style={{ marginBottom: "var(--space-4)" }}>
      <div style={{ fontFamily: "var(--font-body)", fontWeight: 800, fontSize: "var(--text-xs)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: "var(--space-2)" }}>{label}</div>
      <div style={{ display: "flex", gap: "var(--space-3)" }}>{children}</div>
    </div>
  );
  const bg = mainImg ? `center/cover no-repeat url(${mainImg})` : (PS_THEME_BG[product.theme] || PS_THEME_BG.berry);
  const themeLabel = window.SCOOP_DATA.themes.find((t) => t.id === product.theme)?.label;
  const related = window.SCOOP_DATA.products.filter((p) => p.id !== product.id).slice(0, mobile ? 2 : 4);

  return (
    <div style={{ background: "#fff", minHeight: "100vh" }}>
    <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "var(--space-5) var(--container-pad) var(--space-8)" }}>
      <button onClick={onBack} style={{ border: "none", background: "none", cursor: "pointer", color: "var(--text-muted)", fontFamily: "var(--font-body)", fontWeight: 700, fontSize: "var(--text-sm)", padding: "0 0 var(--space-4)" }}>← Back to shop</button>

      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: "var(--space-7)", alignItems: "start" }}>
        {/* Gallery */}
        <div>
          <div style={{ aspectRatio: "1/1", borderRadius: "var(--radius-2xl)", background: bg, boxShadow: "var(--shadow-md)",
            display: "flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
            {product.badge && <span style={{ position: "absolute", top: 16, left: 16, background: TEAL, color: "#fff", fontFamily: "var(--font-body)", fontWeight: 800, fontSize: "var(--text-2xs)", letterSpacing: "0.02em", padding: "4px 11px", borderRadius: "var(--radius-pill)" }}>{product.badge}</span>}
            {!mainImg && <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, color: "rgba(42,36,64,.4)" }}>product photo</span>}
          </div>
          <div style={{ display: "flex", gap: 10, marginTop: "var(--space-3)" }}>
            {gallery.length > 0
              ? gallery.map((g, idx) => (
                  <Thumb key={idx} bg={`center/cover no-repeat url(${g})`} active={mainImg === g} onClick={() => setMainImg(g)} />
                ))
              : <React.Fragment><Thumb bg={bg} active /><Thumb bg="var(--surface-sunken)" /><Thumb bg="var(--surface-sunken)" /><Thumb bg="var(--surface-sunken)" /></React.Fragment>}
          </div>
        </div>

        {/* Info */}
        <div>
          <h1 style={{ margin: "0 0 var(--space-3)", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-3xl)", lineHeight: 1.1, color: "var(--text-strong)" }}>{product.title}</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: "var(--space-4)" }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-3xl)", color: TEAL }}>${unitPrice.toFixed(2)}</span>
            <span style={{ display: "flex", color: "var(--sunshine-500)", fontSize: 18 }}>★★★★★</span>
            <span style={{ color: "var(--text-muted)", fontSize: "var(--text-sm)" }}>(48 reviews)</span>
          </div>
          <p style={{ margin: "0 0 var(--space-5)", fontSize: "var(--text-lg)", lineHeight: 1.6, color: "var(--text-body)" }}>{product.blurb}</p>

          {hasOptions && (
            <React.Fragment>
              <OptGroup label="Choose your kit">
                <OptBtn selected={binOpt === "with"} onClick={() => setBinOpt("with")} sub={"$" + product.price.toFixed(2)}>With bin</OptBtn>
                <OptBtn selected={binOpt === "without"} onClick={() => setBinOpt("without")} sub={"$" + product.priceNoBin.toFixed(2)}>Without bin</OptBtn>
              </OptGroup>
              {fillers && (
                <OptGroup label="Choose your rice filler">
                  {fillers.map((f) => (
                    <OptBtn key={f} selected={filler === f} onClick={() => setFiller(f)}>{f}</OptBtn>
                  ))}
                </OptGroup>
              )}
            </React.Fragment>
          )}

          <div style={{ display: "flex", gap: "var(--space-3)", alignItems: "center", marginBottom: "var(--space-5)", flexWrap: "wrap" }}>
            <QuantityStepper value={qty} onChange={setQty} max={10} accent={TEAL} />
            <Button variant="primary" size="lg" onClick={addItem} style={{ flex: mobile ? "1 1 auto" : "0 0 auto", background: TEAL, color: "var(--ink-900)" }}>Add {qty} to cart · ${(unitPrice * qty).toFixed(2)}</Button>
          </div>

          <div style={{ background: "var(--surface-raised)", border: "2px solid var(--border-soft)", borderRadius: "var(--radius-xl)", padding: "var(--space-5)" }}>
            <h3 style={{ margin: "0 0 var(--space-3)", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-lg)", color: "var(--text-strong)" }}>What's in the bin</h3>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 10 }}>
              {product.contents.map((c) => (
                <li key={c} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: "var(--text-md)", color: "var(--text-body)" }}>
                  <span style={{ width: 22, height: 22, flex: "none", borderRadius: "50%", background: "rgba(148,209,197,0.22)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#94d1c5" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l4 4 10-10"/></svg>
                  </span>
                  {c}
                </li>
              ))}
            </ul>
          </div>

          {/* Safety & care */}
          <div style={{ marginTop: "var(--space-4)", background: "var(--sunshine-50)", border: "2px solid var(--sunshine-300)", borderRadius: "var(--radius-xl)", padding: "var(--space-5)" }}>
            <h3 style={{ margin: "0 0 var(--space-3)", display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-lg)", color: "var(--text-strong)" }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--sunshine-600)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/></svg>
              Safety &amp; care
            </h3>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
              {[
                "Choking hazard — contains small parts. For ages 3+ with adult supervision at all times. Not for children under 3.",
                "Made with food dye and non-toxic acrylic paint. Not edible — for sensory play only.",
                product.scent
                  ? `Lightly ${product.scent}-scented.`
                  : "Most items are lightly vanilla-scented.",
                "If your child has severe food allergies, it's best to avoid — fillers may include rice, beans, dried pasta (wheat), or other grains.",
              ].map((line, idx) => (
                <li key={idx} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: "var(--text-sm)", lineHeight: 1.5, color: "var(--text-body)" }}>
                  <span style={{ marginTop: 7, width: 6, height: 6, flex: "none", borderRadius: "50%", background: "var(--sunshine-600)" }} />
                  {line}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      {/* Related */}
      <section style={{ marginTop: "var(--space-8)" }}>
        <h2 style={{ margin: "0 0 var(--space-5)", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-2xl)", color: "var(--text-strong)" }}>You might also love</h2>
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${mobile ? 2 : 4}, 1fr)`, gap: "var(--space-5)" }}>
          {related.map((p) => (
            <ProductCard key={p.id} title={p.title} price={typeof p.priceNoBin === "number" ? p.priceNoBin : p.price} from={typeof p.priceNoBin === "number"} ages={p.ages} theme={p.theme} badge={p.badge} image={p.image}
              onAdd={() => onAdd(p, 1)} onClick={() => onOpen(p)} />
          ))}
        </div>
      </section>
    </div>
    </div>
  );
}

Object.assign(window, { ProductScreen });
