/* ============================================================
   FRUTA FRESCA — Checkout
   ============================================================ */
function Segmented({ options, value, onChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${options.length},1fr)`, gap: 8 }}>
      {options.map((o) => (
        <button key={o.v} onClick={() => onChange(o.v)} style={{ padding: "12px 8px", borderRadius: 12,
          border: `1.5px solid ${value === o.v ? "var(--green)" : "var(--border)"}`,
          background: value === o.v ? "var(--green-tint)" : "var(--paper)", textAlign: "center", cursor: "pointer" }}>
          {o.icon && <Icon name={o.icon} size={18} style={{ color: "var(--green)", margin: "0 auto 4px" }} />}
          <span style={{ fontWeight: 600, fontSize: 13.5, display: "block" }}>{o.label}</span>
          {o.sub && <span className="small muted">{o.sub}</span>}
        </button>
      ))}
    </div>
  );
}

function CheckoutScreen() {
  const { cart, cartTotal, go, clearCart, toast } = useApp();
  const [step, setStep] = useState(1);
  const [login, setLogin] = useState("phone");
  const [slot, setSlot] = useState("tomorrow-am");
  const [pay, setPay] = useState("upi");
  const [isGift, setIsGift] = useState(false);
  const delivery = cartTotal > 999 ? 0 : 79;
  const total = cartTotal + delivery;
  const steps = ["Account", "Delivery", "Payment"];

  const place = () => { toast("Order placed — confirmation sent!"); clearCart(); go("tracking"); };

  if (cart.length === 0) {
    return <div className="container text-center" style={{ paddingBlock: 80 }}>
      <p className="muted">Your basket is empty.</p>
      <button className="btn btn--primary" style={{ marginTop: 16 }} onClick={() => go("shop")}>Shop fruit</button>
    </div>;
  }

  return (
    <div data-screen-label="Checkout" className="container" style={{ paddingBlock: 24 }}>
      <button className="row small muted" style={{ background: "none", border: "none", marginBottom: 16 }}
        onClick={() => go("cart")}><Icon name="chevronL" size={16} /> Back to basket</button>

      {/* Steps */}
      <div className="steps" style={{ maxWidth: 460, marginBottom: 28 }}>
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <div className="row" style={{ gap: 8 }}>
              <span className={`step-dot ${step > i + 1 ? "done" : step === i + 1 ? "active" : ""}`}>
                {step > i + 1 ? <Icon name="check" size={14} stroke={3} /> : i + 1}</span>
              <span className="small hide-mobile" style={{ fontWeight: step === i + 1 ? 600 : 500,
                color: step >= i + 1 ? "var(--ink)" : "var(--muted)" }}>{s}</span>
            </div>
            {i < steps.length - 1 && <span className={`step-line ${step > i + 1 ? "done" : ""}`} style={{ marginInline: 10 }}></span>}
          </React.Fragment>
        ))}
      </div>

      <div className="checkout-layout" style={{ display: "grid", gridTemplateColumns: "1fr", gap: 28 }}>
        <div style={{ display: "grid", gap: 20 }}>
          {/* STEP 1 — Account */}
          {step === 1 && (
            <section className="surface-card" style={{ padding: 22 }}>
              <h2 className="h3" style={{ marginBottom: 16 }}>How would you like to continue?</h2>
              <Segmented value={login} onChange={setLogin} options={[
                { v: "phone", label: "Phone", icon: "phone" },
                { v: "whatsapp", label: "WhatsApp", icon: "whatsapp" },
                { v: "google", label: "Google", icon: "user" },
                { v: "instagram", label: "Instagram", icon: "instagram" },
              ]} />
              <div style={{ marginTop: 18, display: "grid", gap: 14 }}>
                {(login === "phone" || login === "whatsapp") ? (
                  <>
                    <label className="field"><span className="label">Mobile number</span>
                      <div className="row" style={{ gap: 8 }}>
                        <span className="input" style={{ width: 64, flex: "none", textAlign: "center" }}>+91</span>
                        <input className="input" placeholder="98765 43210" inputMode="numeric" />
                      </div>
                    </label>
                    <p className="small muted">We'll send a one-time code to verify {login === "whatsapp" ? "on WhatsApp" : "via SMS"}.</p>
                  </>
                ) : (
                  <button className="btn btn--outline btn--lg btn--block">
                    <Icon name={login === "google" ? "user" : "instagram"} size={18} /> Continue with {login === "google" ? "Google" : "Instagram"}</button>
                )}
                <label className="row" style={{ gap: 8, fontSize: 13.5 }}><input type="checkbox" defaultChecked /> Continue as guest — checkout without an account</label>
              </div>
              <button className="btn btn--primary btn--lg btn--block" style={{ marginTop: 8 }} onClick={() => setStep(2)}>Continue to delivery</button>
            </section>
          )}

          {/* STEP 2 — Delivery + gift */}
          {step === 2 && (
            <>
              <section className="surface-card" style={{ padding: 22 }}>
                <h2 className="h3" style={{ marginBottom: 16 }}>Delivery address</h2>
                <div style={{ display: "grid", gap: 12 }}>
                  <div className="row" style={{ gap: 12 }}>
                    <label className="field" style={{ flex: 1 }}><span className="label">Full name</span><input className="input" placeholder="Ananya Mehta" /></label>
                    <label className="field" style={{ flex: 1 }}><span className="label">Phone</span><input className="input" placeholder="+91 98765 43210" /></label>
                  </div>
                  <label className="field"><span className="label">Flat / house, street</span><input className="input" placeholder="A-1203, Oberoi Springs, Andheri West" /></label>
                  <div className="row" style={{ gap: 12 }}>
                    <label className="field" style={{ flex: 1 }}><span className="label">City</span><input className="input" defaultValue="Mumbai" /></label>
                    <label className="field" style={{ flex: 1 }}><span className="label">Pincode</span><input className="input" defaultValue="400053" /></label>
                  </div>
                  <div className="row wrap" style={{ gap: 8 }}>
                    {["Home", "Work", "Other"].map((t, i) => <span key={t} className={`chip ${i === 0 ? "chip--active" : ""}`}>{t}</span>)}
                  </div>
                </div>
              </section>

              <section className="surface-card" style={{ padding: 22 }}>
                <h2 className="h3" style={{ marginBottom: 6 }}>Delivery slot</h2>
                <p className="small muted" style={{ marginBottom: 14 }}>Cold-chain delivery to 400053</p>
                <Segmented value={slot} onChange={setSlot} options={[
                  { v: "tomorrow-am", label: "Tomorrow", sub: "8–11 AM" },
                  { v: "tomorrow-pm", label: "Tomorrow", sub: "5–8 PM" },
                  { v: "scheduled", label: "Pick a date", sub: "Schedule", icon: "calendar" },
                ]} />
              </section>

              <section className="surface-card" style={{ padding: 22 }}>
                <button className="between" onClick={() => setIsGift(!isGift)} style={{ width: "100%", background: "none", border: "none", padding: 0 }}>
                  <span className="row" style={{ gap: 10 }}><Icon name="gift" size={20} style={{ color: "var(--green)" }} />
                    <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 18 }}>Make it a gift</span></span>
                  <span style={{ width: 44, height: 26, borderRadius: 13, background: isGift ? "var(--green)" : "var(--border)",
                    position: "relative", transition: ".2s", flex: "none" }}>
                    <span style={{ position: "absolute", top: 3, left: isGift ? 21 : 3, width: 20, height: 20, borderRadius: "50%",
                      background: "#fff", transition: ".2s" }}></span></span>
                </button>
                {isGift && (
                  <div style={{ display: "grid", gap: 12, marginTop: 16 }}>
                    <label className="field"><span className="label">Recipient name</span><input className="input" placeholder="For Priya" /></label>
                    <label className="field"><span className="label">Gift message</span>
                      <textarea className="textarea" rows={3} placeholder="Happy birthday! A little freshness from us to you. ♥" /></label>
                    <label className="field"><span className="label">Schedule delivery date</span>
                      <input className="input" type="date" defaultValue="2026-06-12" /></label>
                    <label className="row" style={{ gap: 8, fontSize: 13.5 }}><input type="checkbox" defaultChecked /> Hide prices on the packing slip</label>
                  </div>
                )}
              </section>

              <div className="row" style={{ gap: 12 }}>
                <button className="btn btn--ghost btn--lg" onClick={() => setStep(1)}>Back</button>
                <button className="btn btn--primary btn--lg" style={{ flex: 1 }} onClick={() => setStep(3)}>Continue to payment</button>
              </div>
            </>
          )}

          {/* STEP 3 — Payment */}
          {step === 3 && (
            <section className="surface-card" style={{ padding: 22 }}>
              <h2 className="h3" style={{ marginBottom: 16 }}>Payment</h2>
              <div style={{ display: "grid", gap: 10 }}>
                {[["upi", "UPI", "GPay, PhonePe, Paytm", "phone"],
                  ["card", "Credit / Debit card", "Visa, Mastercard, RuPay", "bag"],
                  ["wallet", "Wallets", "Paytm, Amazon Pay", "award"],
                  ["netbanking", "Netbanking", "All major banks", "shield"],
                  ["cod", "Cash on delivery", "Pay when it arrives", "truck"]].map(([v, t, s, ic]) => (
                  <button key={v} onClick={() => setPay(v)} className="between" style={{ textAlign: "left",
                    border: `1.5px solid ${pay === v ? "var(--green)" : "var(--border)"}`, background: pay === v ? "var(--green-tint)" : "var(--paper)",
                    borderRadius: 12, padding: "14px 16px", cursor: "pointer" }}>
                    <span className="row" style={{ gap: 12 }}>
                      <Icon name={ic} size={20} style={{ color: "var(--green)" }} />
                      <span><span style={{ fontWeight: 600, fontSize: 14.5, display: "block" }}>{t}</span><span className="small muted">{s}</span></span>
                    </span>
                    <span style={{ width: 18, height: 18, borderRadius: "50%", border: `5px solid ${pay === v ? "var(--green)" : "var(--border)"}`, background: "#fff" }}></span>
                  </button>
                ))}
              </div>
              {pay === "upi" && (
                <label className="field" style={{ marginTop: 14 }}><span className="label">UPI ID</span>
                  <input className="input" placeholder="yourname@okhdfcbank" /></label>
              )}
              <div className="row" style={{ gap: 12, marginTop: 20 }}>
                <button className="btn btn--ghost btn--lg" onClick={() => setStep(2)}>Back</button>
                <button className="btn btn--primary btn--lg" style={{ flex: 1 }} onClick={place}>
                  Pay {FF.rupee(total)}</button>
              </div>
              <p className="small muted text-center" style={{ marginTop: 12 }}>
                <Icon name="shield" size={13} style={{ verticalAlign: "-2px" }} /> Secure, encrypted payment</p>
            </section>
          )}
        </div>

        {/* Summary */}
        <aside style={{ position: "sticky", top: 84 }}>
          <div className="surface-card" style={{ padding: 20 }}>
            <h3 className="h3" style={{ fontSize: 18, marginBottom: 14 }}>Your order</h3>
            <div style={{ display: "grid", gap: 12, marginBottom: 14 }}>
              {cart.map((item) => (
                <div key={item.key} className="row" style={{ gap: 12 }}>
                  <div style={{ position: "relative", flex: "none" }}>
                    <img src={FF.img(item.img, 120)} alt="" style={{ width: 48, height: 48, borderRadius: 10, objectFit: "cover" }} />
                    <span style={{ ...cartDot, background: "var(--green)", top: -6, right: -6 }}>{item.qty}</span>
                  </div>
                  <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500 }}>{item.name}</span>
                  <span className="tabnum small" style={{ fontWeight: 600 }}>{FF.rupee(item.price * item.qty)}</span>
                </div>
              ))}
            </div>
            <div style={{ display: "grid", gap: 8, fontSize: 14, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
              <div className="between"><span className="muted">Subtotal</span><span className="tabnum">{FF.rupee(cartTotal)}</span></div>
              <div className="between"><span className="muted">Delivery</span><span className="tabnum">{delivery === 0 ? "Free" : FF.rupee(delivery)}</span></div>
              <div className="between" style={{ paddingTop: 8, marginTop: 4, borderTop: "1px solid var(--line)" }}>
                <span style={{ fontWeight: 600 }}>Total</span>
                <span className="serif" style={{ fontSize: 22, fontWeight: 600 }}>{FF.rupee(total)}</span></div>
            </div>
            <div className="row" style={{ gap: 7, marginTop: 14, fontSize: 12.5, color: "var(--muted)" }}>
              <Icon name="snowflake" size={15} style={{ color: "var(--green)" }} /> Cold-chain · freshness guaranteed</div>
          </div>
        </aside>
      </div>
    </div>
  );
}
Object.assign(window, { CheckoutScreen });
