/* ============================================================
   FRUTA FRESCA — Product Detail (PDP) v2
   ============================================================ */
function Accordion({ title, children, defaultOpen = false }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--line)" }}>
      <button className="between" onClick={() => setOpen(!open)} style={{ width: "100%", background: "none",
        border: "none", padding: "18px 0", fontWeight: 600, fontSize: 16, fontFamily: "var(--display)", color: "var(--ink)" }}>
        {title}<Icon name={open ? "minus" : "plus"} size={18} />
      </button>
      {open && <div className="muted" style={{ paddingBottom: 18, fontSize: 14.5, lineHeight: 1.65 }}>{children}</div>}
    </div>
  );
}

const pdpSegBtn = { padding: "11px 8px", borderRadius: 12, border: "1.5px solid var(--border)",
  background: "var(--paper)", textAlign: "center", cursor: "pointer", lineHeight: 1.25, transition: ".15s" };
const pdpSegOn = { borderColor: "var(--green)", background: "var(--green-tint)" };
function PdpSeg({ options, value, onChange, cols }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols || options.length},1fr)`, gap: 8 }}>
      {options.map((o) => (
        <button key={o.v} onClick={() => onChange(o.v)} style={{ ...pdpSegBtn, ...(value === o.v ? pdpSegOn : {}) }}>
          <span style={{ fontWeight: 600, fontSize: 13.5, display: "block", color: "var(--ink)" }}>{o.t}</span>
          {o.s && <span className="small muted" style={{ display: "block", marginTop: 1 }}>{o.s}</span>}
        </button>
      ))}
    </div>
  );
}

function SensoryDial({ label, level }) {
  const frac = { High: 0.9, Medium: 0.55, Soft: 0.35, Low: 0.22 }[level] ?? 0.5;
  const r = 30, C = 2 * Math.PI * r;
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ position: "relative", width: 88, height: 88, margin: "0 auto" }}>
        <svg width="88" height="88" viewBox="0 0 88 88" style={{ transform: "rotate(-90deg)" }}>
          <circle cx="44" cy="44" r={r} fill="none" stroke="var(--border)" strokeWidth="7" />
          <circle cx="44" cy="44" r={r} fill="none" stroke="var(--citrus)" strokeWidth="7" strokeLinecap="round"
            strokeDasharray={C} strokeDashoffset={C * (1 - frac)} />
        </svg>
        <span style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center",
          fontFamily: "var(--display)", fontWeight: 600, fontSize: 14.5 }}>{level}</span>
      </div>
      <div className="small" style={{ marginTop: 8, fontWeight: 600 }}>{label}</div>
    </div>
  );
}

const SPEC_ICONS = { Origin: "mappin", Variety: "sprout", Grade: "award", Harvest: "calendar",
  "Net weight": "bag", Ripening: "leaf" };

function PdpScreen() {
  const { routeParams, go, addToCart, toggleWish, wish } = useApp();
  const p = FF.byId(routeParams?.id) || FF.products[0];
  const packs = FF.genPacks(p);
  const [active, setActive] = useState(0);
  const [packIdx, setPackIdx] = useState(Math.max(0, packs.findIndex((x) => x.def)));
  const [qty, setQty] = useState(1);
  const [mode, setMode] = useState("once");
  const [ripeness, setRipeness] = useState("ready");
  const [added, setAdded] = useState(false);
  const liked = wish.includes(p.id);
  useEffect(() => {
    const pk = FF.genPacks(p);
    setActive(0); setQty(1); setMode("once"); setPackIdx(Math.max(0, pk.findIndex((x) => x.def)));
    window.scrollTo(0, 0);
  }, [p.id]);

  const pack = packs[packIdx] || packs[0];
  const base = pack.price;
  const subPrice = Math.round(base * 0.9);
  const unitPrice = mode === "subscribe" ? subPrice : base;
  const related = FF.products.filter((x) => x.id !== p.id && (x.cat === p.cat || x.exotic === p.exotic)).slice(0, 4);
  const netQty = packs.some((x) => x.qty) ? packs.map((x) => x.qty).filter(Boolean).join(" / ") + " pcs" : pack.sub;

  const doAdd = () => {
    addToCart({ ...p, price: unitPrice, unit: pack.sub || pack.label }, qty, mode === "subscribe");
    setAdded(true); setTimeout(() => setAdded(false), 1300);
  };

  return (
    <div data-screen-label="Product detail">
      <div className="container" style={{ paddingBlock: 20 }}>
        <nav className="small muted" style={{ marginBottom: 16 }}>
          <a href="#" onClick={(e) => { e.preventDefault(); go("home"); }}>Home</a><span className="divider-dot"></span>
          <a href="#" onClick={(e) => { e.preventDefault(); go("shop"); }}>Shop</a><span className="divider-dot"></span>
          <span style={{ color: "var(--ink)" }}>{p.name}</span>
        </nav>

        <div className="split--sticky">
          {/* Gallery */}
          <div>
            <div style={{ position: "relative", borderRadius: 18, overflow: "hidden", aspectRatio: "1/1", background: "var(--surface)" }}>
              <img src={FF.img(p.gallery[active], 900)} alt={p.name} className="fill" />
              <div className="pc-badges" style={{ top: 14, left: 14 }}>
                <SeasonBadge season={p.season} />
                {p.organic && <span className="badge badge--organic">Organic</span>}
              </div>
            </div>
            <div className="row" style={{ gap: 10, marginTop: 12 }}>
              {p.gallery.map((g, i) => (
                <button key={i} onClick={() => setActive(i)} style={{ width: 72, height: 72, borderRadius: 12,
                  overflow: "hidden", border: `2px solid ${i === active ? "var(--green)" : "transparent"}`, padding: 0, flex: "none" }}>
                  <img src={FF.img(g, 160)} alt="" className="fill" />
                </button>
              ))}
            </div>
          </div>

          {/* Buy box */}
          <div className="pdp-buy" style={{ position: "sticky", top: 84, alignSelf: "start" }}>
            <p className="eyebrow" style={{ marginBottom: 8 }}>{p.cat}</p>
            <h1 className="h2" style={{ marginBottom: 8 }}>{p.name}</h1>
            <div className="row wrap" style={{ gap: 10, marginBottom: 12 }}>
              <span className="row" style={{ gap: 6 }}><Stars value={p.rating} /> <span className="small muted">{p.rating} · {p.reviews} reviews</span></span>
            </div>
            <p className="lead" style={{ fontSize: 16, marginBottom: 16 }}>{p.tagline}</p>
            <div className="row wrap" style={{ gap: 8, marginBottom: 18 }}>
              <span className="badge badge--origin"><Icon name="mappin" size={13} style={{ color: "var(--green)" }} /> {p.origin}</span>
              <span className="badge"><Icon name="award" size={13} /> {p.grade}</span>
            </div>

            {/* ① Pack-size selector */}
            <div style={{ marginBottom: 16 }}>
              <div className="between" style={{ marginBottom: 8 }}>
                <span className="label">Pack size</span>
                <span className="small muted">{pack.sub}</span>
              </div>
              <PdpSeg cols={packs.length} value={packIdx}
                options={packs.map((pk, i) => ({ v: i, t: pk.label, s: FF.rupee(pk.price) }))}
                onChange={setPackIdx} />
            </div>

            {/* Purchase mode */}
            <div style={{ display: "grid", gap: 10, marginBottom: 16 }}>
              {[["once", "One-time", `${FF.rupee(base)} ${p.unit}`],
                ["subscribe", "Subscribe & save 10%", `${FF.rupee(subPrice)} ${p.unit} · skip anytime`]].map(([m, t, s]) => (
                <button key={m} onClick={() => setMode(m)} className="between" style={{ textAlign: "left",
                  border: `1.5px solid ${mode === m ? "var(--green)" : "var(--border)"}`, background: mode === m ? "var(--green-tint)" : "var(--paper)",
                  borderRadius: 12, padding: "13px 15px", cursor: "pointer" }}>
                  <span className="row" style={{ gap: 11 }}>
                    <span style={{ width: 18, height: 18, borderRadius: "50%", border: `5px solid ${mode === m ? "var(--green)" : "var(--border)"}`,
                      background: "var(--paper)", flex: "none" }}></span>
                    <span>
                      <span style={{ fontWeight: 600, fontSize: 14.5, display: "block" }}>{t}</span>
                      <span className="small muted">{s}</span>
                    </span>
                  </span>
                  {m === "subscribe" && <span className="badge badge--season">Save 10%</span>}
                </button>
              ))}
            </div>

            {/* ② Ripeness preference */}
            <div style={{ marginBottom: 16 }}>
              <span className="label" style={{ display: "block", marginBottom: 8 }}>Ripeness preference</span>
              <PdpSeg cols={2} value={ripeness}
                options={[{ v: "ready", t: "Ready to eat" }, { v: "home", t: "Ripen at home", s: "2–4 days" }]}
                onChange={setRipeness} />
            </div>

            <div className="row between" style={{ marginBottom: 16 }}>
              <span className="small muted">Quantity</span>
              <QtyStepper qty={qty} onChange={setQty} />
            </div>

            <div className="between" style={{ marginBottom: 16 }}>
              <span className="serif" style={{ fontSize: 28, fontWeight: 600 }}>{FF.rupee(unitPrice * qty)}</span>
              <span className="badge badge--instock"><span className="dot"></span>In stock · ships today</span>
            </div>

            <div className="row" style={{ gap: 10 }}>
              <button className={`btn ${added ? "btn--ink" : "btn--primary"} btn--lg`} style={{ flex: 1 }} onClick={doAdd}>
                {added ? <><Icon name="check" size={18} /> Added to cart</> : (mode === "subscribe" ? "Start subscription" : "Add to cart")}
              </button>
              <button className="btn btn--outline btn--lg" aria-label="Save" onClick={() => toggleWish(p.id)} style={{ flex: "none", padding: "16px 18px" }}>
                <Icon name="heart" size={18} fill={liked ? "var(--berry)" : "none"} style={{ color: liked ? "var(--berry)" : "var(--ink)" }} />
              </button>
            </div>

            {/* Reassurance */}
            <div style={{ display: "grid", gap: 10, marginTop: 18, padding: 16, background: "var(--surface)", borderRadius: 12 }}>
              {[["snowflake", "Cold-chain delivered — kept perfectly chilled, farm to door"],
                ["shield", "100% freshness guarantee, or we replace it free"],
                ["truck", "Order before 6 PM for next-day metro delivery"]].map(([ic, t]) => (
                <div key={t} className="row" style={{ gap: 10, fontSize: 13.5 }}>
                  <Icon name={ic} size={17} style={{ color: "var(--green)", flex: "none" }} /> {t}</div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ③ Sensory band */}
      <section style={{ background: "var(--surface)", borderBlock: "1px solid var(--line)" }}>
        <div className="container" style={{ paddingBlock: 36 }}>
          <div className="between wrap" style={{ marginBottom: 24, gap: 10 }}>
            <div>
              <p className="eyebrow" style={{ marginBottom: 4 }}>Tasting profile</p>
              <h2 className="h3" style={{ fontSize: 24 }}>How it tastes</h2>
            </div>
            <span className="small muted" style={{ maxWidth: 280 }}>Assessed by our buyers at peak ripeness.</span>
          </div>
          <div className="sensory-grid" style={{ display: "grid", gap: 16 }}>
            {Object.entries(p.sensory).map(([k, v]) => <SensoryDial key={k} label={k} level={v} />)}
          </div>
        </div>
      </section>

      {/* ④ At-a-glance spec grid */}
      <section className="container" style={{ paddingBlock: 40 }}>
        <h2 className="h3" style={{ fontSize: 24, marginBottom: 20 }}>At a glance</h2>
        <div className="spec-grid" style={{ display: "grid", gridTemplateColumns: "repeat(1,1fr)", gap: 14 }}>
          {Object.entries(p.specs).map(([k, v]) => (
            <div key={k} className="row" style={{ gap: 12, alignItems: "flex-start", padding: "14px 16px",
              background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 12 }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: "var(--green-tint)", color: "var(--green)",
                display: "grid", placeItems: "center", flex: "none" }}><Icon name={SPEC_ICONS[k] || "leaf"} size={19} /></span>
              <div>
                <div className="small muted" style={{ fontSize: 12, letterSpacing: ".04em", textTransform: "uppercase" }}>{k}</div>
                <div style={{ fontWeight: 600, fontSize: 14.5, marginTop: 2 }}>{v}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Details + additional table */}
      <section className="container" style={{ paddingBottom: 44 }}>
        <div className="pdp-details" style={{ display: "grid", gridTemplateColumns: "1fr", gap: 36 }}>
          <div>
            <h2 className="h3" style={{ fontSize: 24, marginBottom: 4 }}>Product details</h2>
            <Accordion title="About this fruit" defaultOpen>{p.about}</Accordion>
            <Accordion title="Nutrition">{p.nutrition}</Accordion>
            <Accordion title="Freshness & storage">{p.storage}</Accordion>
            <Accordion title="Delivery & returns">
              Cold-chain delivered across India. Next-day in Mumbai, Delhi, Bengaluru, Pune & Hyderabad;
              2–3 days elsewhere. Not happy with freshness? We replace or refund — just message us within 24 hours.
            </Accordion>
          </div>
          {/* ⑤ Additional details table */}
          <div>
            <h3 className="h3" style={{ fontSize: 19, marginBottom: 12 }}>Additional details</h3>
            <div className="surface-card" style={{ overflow: "hidden" }}>
              {[["Country of origin", p.country], ["Packed by", p.packedBy],
                ["FSSAI No.", p.fssai], ["Net quantity", netQty]].map(([k, v], i, a) => (
                <div key={k} className="between" style={{ gap: 16, padding: "13px 16px",
                  borderBottom: i < a.length - 1 ? "1px solid var(--line)" : "none", fontSize: 14 }}>
                  <span className="muted">{k}</span>
                  <span style={{ fontWeight: 600, textAlign: "right" }}>{v}</span>
                </div>
              ))}
            </div>
            <p className="small muted" style={{ marginTop: 12, lineHeight: 1.5 }}>
              <Icon name="shield" size={13} style={{ verticalAlign: "-2px", color: "var(--green)" }} /> Sold by Fruta Fresca Pvt. Ltd. ·
              Quality assured under our 100% freshness guarantee.</p>
          </div>
        </div>
      </section>

      {/* ⑥ Meet the grower */}
      <section style={{ background: "var(--green)", color: "#fff" }}>
        <div className="container" style={{ paddingBlock: 0 }}>
          <div className="grower-split" style={{ display: "grid", gridTemplateColumns: "1fr", gap: 0, alignItems: "stretch" }}>
            <div style={{ minHeight: 280, position: "relative" }}>
              <img src={FF.img(p.grower.img, 900)} alt={`${p.grower.place} orchard`} className="fill" style={{ minHeight: 280 }} />
            </div>
            <div className="grower-copy">
              <p className="eyebrow" style={{ color: "var(--citrus)" }}>Meet the grower</p>
              {p.grower.coords && <div className="row" style={{ gap: 8, marginBottom: 10, color: "rgba(255,255,255,.8)", fontSize: 13.5 }}>
                <Icon name="mappin" size={15} style={{ color: "var(--citrus)" }} /> {p.grower.coords}</div>}
              <h2 className="h2" style={{ color: "#fff" }}>{p.grower.place}</h2>
              <p className="lead" style={{ color: "rgba(255,255,255,.88)", marginTop: 14, maxWidth: 460 }}>{p.grower.story}</p>
              <button className="btn btn--primary btn--lg" style={{ marginTop: 22 }} onClick={() => go("about")}>
                Explore our sourcing <Icon name="arrowR" size={16} /></button>
            </div>
          </div>
        </div>
      </section>

      {/* Reviews */}
      <section className="section" style={{ background: "var(--paper)", borderBottom: "1px solid var(--line)" }}>
        <div className="container">
          <div className="split--sticky">
            <div>
              <h2 className="h2" style={{ marginBottom: 6 }}>Ratings & reviews</h2>
              <div className="row" style={{ gap: 14, marginTop: 14 }}>
                <span className="serif" style={{ fontSize: 52, fontWeight: 600, lineHeight: 1 }}>{p.rating}</span>
                <div><Stars value={p.rating} size={18} /><div className="small muted" style={{ marginTop: 4 }}>{p.reviews} verified reviews</div></div>
              </div>
              <div style={{ display: "grid", gap: 6, marginTop: 18, maxWidth: 300 }}>
                {[[5, 86], [4, 10], [3, 3], [2, 1], [1, 0]].map(([s, pct]) => (
                  <div key={s} className="row" style={{ gap: 10, fontSize: 13 }}>
                    <span className="muted" style={{ width: 12 }}>{s}</span><Icon name="star" size={13} style={{ color: "var(--citrus)" }} />
                    <span style={{ flex: 1, height: 7, background: "var(--surface)", borderRadius: 4, overflow: "hidden" }}>
                      <span style={{ display: "block", width: pct + "%", height: "100%", background: "var(--citrus)" }}></span></span>
                    <span className="muted" style={{ width: 34, textAlign: "right" }}>{pct}%</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ display: "grid", gap: 14 }}>
              {FF.reviews.map((r, i) => (
                <figure key={i} className="card" style={{ padding: 18, margin: 0 }}>
                  <div className="between">
                    <div className="row" style={{ gap: 10 }}>
                      <span style={{ width: 38, height: 38, borderRadius: "50%", background: "var(--green-tint)", color: "var(--green)",
                        display: "grid", placeItems: "center", fontWeight: 700, fontSize: 15 }}>{r.name[0]}</span>
                      <div><div style={{ fontWeight: 600, fontSize: 14.5 }}>{r.name}</div>
                        <div className="small muted">{r.verified && "Verified buyer · "}{r.date}</div></div>
                    </div>
                    <Stars value={r.rating} size={14} />
                  </div>
                  <p style={{ marginTop: 12, fontSize: 14.5, lineHeight: 1.6 }}>{r.text}</p>
                </figure>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Related row 1 */}
      <section className="section container" style={{ paddingBottom: 24 }}>
        <SectionHead eyebrow="You may also like" title="Pairs beautifully with" />
        <div className="pgrid">{related.map((r) => <ProductCard key={r.id} p={r} />)}</div>
      </section>

      {/* ⑦ Gift row 2 */}
      <section className="container" style={{ paddingBottom: 56 }}>
        <SectionHead eyebrow="Gifting" title="Make it a gift"
          action="Build your own hamper" onAction={() => go("hampers")} />
        <div className="pgrid--3">
          {FF.hampers.map((h) => (
            <article key={h.id} className="surface-card" style={{ overflow: "hidden", cursor: "pointer" }} onClick={() => go("hampers")}>
              <div style={{ position: "relative", aspectRatio: "4/3" }}>
                <img src={FF.img(h.img, 500)} alt={h.name} className="fill" />
                {h.tag && <span className="badge badge--limited" style={{ position: "absolute", top: 12, left: 12 }}>{h.tag}</span>}
              </div>
              <div style={{ padding: 18 }}>
                <h3 className="h3" style={{ fontSize: 20 }}>{h.name}</h3>
                <p className="muted small" style={{ margin: "6px 0 12px" }}>{h.desc}</p>
                <div className="between">
                  <span style={{ fontWeight: 600 }}>{FF.rupee(h.price)}</span>
                  <span className="btn btn--primary btn--sm">Gift this <Icon name="gift" size={15} /></span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}
Object.assign(window, { PdpScreen });
