/* ============================================================
   FRUTA FRESCA — Hamper Builder (step flow, live price)
   ============================================================ */
function HamperScreen() {
  const { go, toast } = useApp();
  const [step, setStep] = useState(0);
  const [box, setBox] = useState("kraft");
  const [picks, setPicks] = useState({});
  const [packaging, setPackaging] = useState("ribbon");
  const [message, setMessage] = useState("");

  const boxes = [
    { id: "kraft", name: "Kraft Crate", price: 299, cap: 4, img: FF.PH.mangoBasket, desc: "Rustic, recyclable wooden crate" },
    { id: "signature", name: "Signature Box", price: 499, cap: 6, img: FF.PH.plateFruit, desc: "Linen-lined keepsake gift box" },
    { id: "luxe", name: "Luxe Hamper", price: 799, cap: 8, img: FF.PH.slicedBowl, desc: "Premium basket with wrap & tag" },
  ];
  const packs = [
    { id: "ribbon", name: "Satin ribbon", price: 0 },
    { id: "wrap", name: "Cellophane & bow", price: 99 },
    { id: "premium", name: "Velvet pouch & wax seal", price: 199 },
  ];
  const curBox = boxes.find((b) => b.id === box);
  const cap = curBox.cap;
  const totalPicks = Object.values(picks).reduce((s, n) => s + n, 0);
  const fruitsTotal = Object.entries(picks).reduce((s, [id, n]) => s + FF.byId(id).price * n, 0);
  const packPrice = packs.find((p) => p.id === packaging).price;
  const livePrice = curBox.price + fruitsTotal + packPrice;

  const steps = ["Choose box", "Add fruits", "Packaging", "Message", "Preview"];
  const setPick = (id, delta) => setPicks((prev) => {
    const n = (prev[id] || 0) + delta;
    if (n <= 0) { const c = { ...prev }; delete c[id]; return c; }
    if (delta > 0 && totalPicks >= cap) return prev;
    return { ...prev, [id]: n };
  });

  const canNext = step !== 1 || totalPicks > 0;

  return (
    <div data-screen-label="Hamper builder" className="container" style={{ paddingBlock: 24 }}>
      <div className="text-center" style={{ maxWidth: 560, margin: "0 auto 8px" }}>
        <p className="eyebrow">Bespoke gifting</p>
        <h1 className="h2">Build your own hamper</h1>
        <p className="muted" style={{ marginTop: 8 }}>Five simple steps to a beautiful, personal gift.</p>
      </div>

      {/* Step pills */}
      <div className="row" style={{ gap: 6, justifyContent: "center", flexWrap: "wrap", margin: "22px 0 28px" }}>
        {steps.map((s, i) => (
          <button key={s} onClick={() => i <= step && setStep(i)} className="row" style={{ gap: 7, background: "none", border: "none",
            opacity: i <= step ? 1 : 0.5, cursor: i <= step ? "pointer" : "default" }}>
            <span className={`step-dot ${step > i ? "done" : step === i ? "active" : ""}`} style={{ width: 26, height: 26, fontSize: 12 }}>
              {step > i ? <Icon name="check" size={12} stroke={3} /> : i + 1}</span>
            <span className="small hide-mobile" style={{ fontWeight: step === i ? 600 : 500 }}>{s}</span>
          </button>
        ))}
      </div>

      <div className="hamper-layout" style={{ display: "grid", gridTemplateColumns: "1fr", gap: 28 }}>
        <div>
          {/* STEP 0 — box */}
          {step === 0 && (
            <div className="pgrid--3">
              {boxes.map((b) => (
                <button key={b.id} onClick={() => setBox(b.id)} className="surface-card" style={{ overflow: "hidden",
                  textAlign: "left", padding: 0, cursor: "pointer", border: `2px solid ${box === b.id ? "var(--green)" : "var(--line)"}` }}>
                  <div style={{ aspectRatio: "4/3" }}><img src={FF.img(b.img, 400)} alt={b.name} className="fill" /></div>
                  <div style={{ padding: 16 }}>
                    <div className="between"><span style={{ fontWeight: 600, fontFamily: "var(--display)", fontSize: 18 }}>{b.name}</span>
                      {box === b.id && <Icon name="check" size={18} style={{ color: "var(--green)" }} stroke={3} />}</div>
                    <p className="small muted" style={{ margin: "4px 0 10px" }}>{b.desc}</p>
                    <div className="between"><span className="small">Holds up to {b.cap}</span><span style={{ fontWeight: 600 }}>{FF.rupee(b.price)}</span></div>
                  </div>
                </button>
              ))}
            </div>
          )}

          {/* STEP 1 — fruits */}
          {step === 1 && (
            <div>
              <div className="between" style={{ marginBottom: 14 }}>
                <span className="muted small">Pick up to {cap} fruits</span>
                <span className="badge badge--instock">{totalPicks}/{cap} added</span>
              </div>
              <div className="pgrid">
                {FF.products.map((p) => {
                  const n = picks[p.id] || 0;
                  return (
                    <div key={p.id} className="card" style={{ overflow: "hidden", border: n ? "1.5px solid var(--green)" : "1px solid var(--line)" }}>
                      <div style={{ aspectRatio: "1/1", position: "relative" }}>
                        <img src={FF.img(p.img, 300)} alt={p.name} className="fill" />
                        {n > 0 && <span style={{ position: "absolute", top: 8, right: 8, width: 26, height: 26, borderRadius: "50%",
                          background: "var(--green)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 13 }}>{n}</span>}
                      </div>
                      <div style={{ padding: 12 }}>
                        <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.2 }}>{p.name}</div>
                        <div className="small muted" style={{ marginBottom: 10 }}>{FF.rupee(p.price)}</div>
                        {n === 0
                          ? <button className="btn btn--ghost btn--sm btn--block" onClick={() => setPick(p.id, 1)}
                              disabled={totalPicks >= cap}>Add</button>
                          : <QtyStepper qty={n} onChange={(q) => setPick(p.id, q - n)} size="sm" />}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* STEP 2 — packaging */}
          {step === 2 && (
            <div style={{ display: "grid", gap: 12 }}>
              {packs.map((pk) => (
                <button key={pk.id} onClick={() => setPackaging(pk.id)} className="between" style={{ textAlign: "left",
                  border: `1.5px solid ${packaging === pk.id ? "var(--green)" : "var(--border)"}`, background: packaging === pk.id ? "var(--green-tint)" : "var(--paper)",
                  borderRadius: 12, padding: "16px 18px", cursor: "pointer" }}>
                  <span className="row" style={{ gap: 12 }}>
                    <Icon name="gift" size={20} style={{ color: "var(--green)" }} />
                    <span style={{ fontWeight: 600 }}>{pk.name}</span></span>
                  <span style={{ fontWeight: 600 }}>{pk.price === 0 ? "Included" : "+ " + FF.rupee(pk.price)}</span>
                </button>
              ))}
            </div>
          )}

          {/* STEP 3 — message */}
          {step === 3 && (
            <div className="surface-card" style={{ padding: 22 }}>
              <label className="field"><span className="label">Your gift message</span>
                <textarea className="textarea" rows={5} maxLength={240} value={message} onChange={(e) => setMessage(e.target.value)}
                  placeholder="Wishing you a basket full of joy — with love, always." /></label>
              <div className="small muted text-center" style={{ marginTop: 8 }}>{message.length}/240 · handwritten on a linen card</div>
            </div>
          )}

          {/* STEP 4 — preview */}
          {step === 4 && (
            <div className="surface-card" style={{ overflow: "hidden" }}>
              <div style={{ aspectRatio: "16/10", position: "relative" }}>
                <img src={FF.img(curBox.img, 800)} alt="Hamper preview" className="fill" />
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg,rgba(28,42,33,0) 50%,rgba(28,42,33,.7))" }}></div>
                <div style={{ position: "absolute", bottom: 16, left: 18, color: "#fff" }}>
                  <div className="serif" style={{ fontSize: 24, fontWeight: 600 }}>{curBox.name}</div>
                  <div style={{ fontSize: 13, opacity: .9 }}>{packs.find((p) => p.id === packaging).name}</div>
                </div>
              </div>
              <div style={{ padding: 20 }}>
                <h3 className="h3" style={{ marginBottom: 12 }}>Inside your hamper</h3>
                <div className="row wrap" style={{ gap: 8, marginBottom: 16 }}>
                  {Object.entries(picks).map(([id, n]) => (
                    <span key={id} className="badge">{FF.byId(id).name} × {n}</span>
                  ))}
                  {totalPicks === 0 && <span className="muted small">No fruits added yet.</span>}
                </div>
                {message && <div style={{ background: "var(--surface)", borderRadius: 12, padding: 16, fontStyle: "italic",
                  fontFamily: "var(--display)", fontSize: 16 }}>“{message}”</div>}
              </div>
            </div>
          )}

          {/* Nav */}
          <div className="row" style={{ gap: 12, marginTop: 22 }}>
            {step > 0 && <button className="btn btn--ghost btn--lg" onClick={() => setStep(step - 1)}>Back</button>}
            {step < 4
              ? <button className="btn btn--primary btn--lg" style={{ flex: 1 }} disabled={!canNext} onClick={() => setStep(step + 1)}>
                  Continue</button>
              : <button className="btn btn--primary btn--lg" style={{ flex: 1 }} onClick={() => { toast("Hamper added to cart!"); go("cart"); }}>
                  Add hamper to cart · {FF.rupee(livePrice)}</button>}
          </div>
        </div>

        {/* Live summary */}
        <aside className="hamper-summary" style={{ position: "sticky", top: 84, alignSelf: "start" }}>
          <div className="surface-card" style={{ padding: 20 }}>
            <h3 className="h3" style={{ fontSize: 18, marginBottom: 4 }}>Your hamper</h3>
            <p className="small muted" style={{ marginBottom: 16 }}>Live price updates as you build</p>
            <div style={{ display: "grid", gap: 9, fontSize: 14, paddingBottom: 14, borderBottom: "1px solid var(--line)" }}>
              <div className="between"><span className="muted">{curBox.name}</span><span className="tabnum">{FF.rupee(curBox.price)}</span></div>
              <div className="between"><span className="muted">Fruits ({totalPicks})</span><span className="tabnum">{FF.rupee(fruitsTotal)}</span></div>
              <div className="between"><span className="muted">Packaging</span><span className="tabnum">{packPrice === 0 ? "Free" : FF.rupee(packPrice)}</span></div>
            </div>
            <div className="between" style={{ paddingTop: 14 }}>
              <span style={{ fontWeight: 600 }}>Total</span>
              <span className="serif" style={{ fontSize: 26, fontWeight: 600 }}>{FF.rupee(livePrice)}</span>
            </div>
            <div style={{ marginTop: 14, height: 8, background: "var(--surface)", borderRadius: 4, overflow: "hidden" }}>
              <div style={{ width: `${Math.min(100, (totalPicks / cap) * 100)}%`, height: "100%", background: "var(--leaf)", transition: ".3s" }}></div>
            </div>
            <p className="small muted" style={{ marginTop: 8 }}>{cap - totalPicks > 0 ? `Room for ${cap - totalPicks} more` : "Hamper full"}</p>
          </div>
        </aside>
      </div>
    </div>
  );
}
Object.assign(window, { HamperScreen });
