/* GMC FONT — Cart + Checkout */

function Cart() {
  const a = useApp();
  const r = useRoute();
  const [coupon, setCoupon] = useState("");
  const subtotal = a.cart.reduce((s, item) => s + item.price, 0);
  const discount = a.cart.length > 1 ? Math.round(subtotal * 0.1) : 0;
  const total = subtotal - discount;

  return (
    <div data-screen-label="Cart">
      <section style={{padding:"40px 0 24px", borderBottom:"1px solid var(--line)"}}>
        <div className="container">
          <span className="eyebrow">🛒 Cart</span>
          <h1 className="display" style={{fontSize:"clamp(36px, 4.5vw, 62px)", margin:"8px 0 8px"}}>ตะกร้าของคุณ</h1>
          <div className="steps">
            <div className="step on"><span className="n">1</span>ตะกร้า</div>
            <span className="dash"/>
            <div className="step"><span className="n">2</span>ชำระเงิน</div>
            <span className="dash"/>
            <div className="step"><span className="n">3</span>ดาวน์โหลด</div>
          </div>
        </div>
      </section>
      <section className="section-tight">
        <div className="container cart-grid" style={{display:"grid", gridTemplateColumns:"1.5fr 1fr", gap:32}}>
          <div>
            {a.cart.length === 0 ? (
              <div className="card" style={{padding:60, textAlign:"center"}}>
                <div className="display" style={{fontSize:48, marginBottom:8}}>ยังไม่มีฟอนต์ในตะกร้า 😅</div>
                <p style={{color:"var(--ink-soft)"}}>ลองเลือกจากคลังฟอนต์ของเราดูสิ</p>
                <button className="btn coral lg" style={{marginTop:18}} onClick={() => r.go("fonts")}>
                  ไปเลือกฟอนต์ <Icon name="arrow-r" size={14}/>
                </button>
              </div>
            ) : (
              <div style={{display:"flex", flexDirection:"column", gap:14}}>
                {a.cart.map((item, i) => (
                  <div key={i} className="cart-line">
                    <div className="thumb" style={{background:`var(--${item.color})`, fontFamily:item.family}}>
                      {item.image
                        ? <img src={item.image} alt={item.name} style={{width:"100%", height:"100%", objectFit:"cover"}}/>
                        : (item.languages.includes("thai") ? "ก" : "A")}
                    </div>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{display:"flex", alignItems:"baseline", gap:8, flexWrap:"wrap"}}>
                        <span style={{fontFamily:"var(--f-display)", fontWeight:500, fontSize:15}}>{item.name}</span>
                        <span style={{fontSize:12, color:"var(--ink-soft)"}}>{item.thai_name}</span>
                      </div>
                      <div style={{fontSize:12, color:"var(--ink-soft)", marginTop:3}}>
                        ใบอนุญาต: <b style={{color:"var(--ink)"}}>{item.licenseTier === "personal" ? "ส่วนตัว" : item.licenseTier === "commercial" ? "เชิงพาณิชย์" : item.licenseTier === "team" ? "ทีม 5 คน" : "ไม่จำกัด"}</b> · {item.weights.length} weights
                      </div>
                    </div>
                    <div style={{fontFamily:"var(--f-display)", fontWeight:500, fontSize:16, flexShrink:0}}>฿{item.price}</div>
                    <button className="icon-btn" style={{width:34, height:34, flexShrink:0, boxShadow:"none", color:"var(--coral-deep)"}}
                            onClick={() => a.removeFromCart(i)}>
                      <Icon name="trash" size={14}/>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
          {a.cart.length > 0 && (
            <div>
              <div className="summary">
                <h3 className="display" style={{fontSize:28, margin:"0 0 4px"}}>สรุปคำสั่งซื้อ</h3>
                <div className="line"><span>ราคารวม</span><b>฿{subtotal}</b></div>
                {discount > 0 && <div className="line" style={{color:"var(--coral-deep)"}}><span>ส่วนลด (2+ ฟอนต์)</span><b>-฿{discount}</b></div>}
                <div className="line"><span>ภาษี</span><b>รวมแล้ว</b></div>
                <div style={{height:1, background:"var(--line)", margin:"4px 0"}}/>
                <div className="line" style={{fontSize:22, fontFamily:"var(--f-display-2)"}}>
                  <span>ยอดสุทธิ</span><span>฿{total}</span>
                </div>
                <div className="field flat" style={{marginTop:10}}>
                  <Icon name="tag" size={14}/>
                  <input placeholder="โค้ดส่วนลด" value={coupon} onChange={e => setCoupon(e.target.value)}/>
                  <button className="btn sm">ใช้</button>
                </div>
                <button className="btn coral lg block" style={{marginTop:6}} onClick={() => r.go("checkout")}>
                  ชำระเงิน <Icon name="arrow-r" size={16}/>
                </button>
                <div style={{textAlign:"center", fontSize:13, color:"var(--ink-soft)", cursor:"pointer"}} onClick={() => r.go("fonts")}>
                  เลือกสินค้าอื่น
                </div>
                <div style={{fontSize:12, color:"var(--ink-soft)", textAlign:"center"}}>
                  <Icon name="lock" size={12}/> การชำระเงินปลอดภัย • รับ PromptPay
                </div>
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

function Checkout() {
  const a = useApp();
  const r = useRoute();
  const cfg = window.GFV_CONFIG || {};

  // Steps: "form" → "qr" → "verifying" → "waiting" | "done"
  const [step, setStep] = useState("form");
  const [email, setEmail] = useState(a.user?.email || "");
  const [orderId, setOrderId] = useState(null);
  const [slipFile, setSlipFile] = useState(null);
  const [slipPreview, setSlipPreview] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [autoVerified, setAutoVerified] = useState(false);

  const subtotal = a.cart.reduce((s, item) => s + item.price, 0);
  const discount = a.cart.length > 1 ? Math.round(subtotal * 0.1) : 0;
  const total = subtotal - discount;

  const handleStartPayment = async () => {
    if (!email.trim() || !email.includes("@")) { setErr("กรอกอีเมลให้ถูกต้อง"); return; }
    if (!a.cart.length) { setErr("ตะกร้ายังว่างอยู่"); return; }
    setBusy(true); setErr("");
    try {
      const order = await createPendingOrder({ email, items: a.cart, total });
      setOrderId(order.id);
      a.clearCart();
      setStep("qr");
    } catch(e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const pickSlip = (e) => {
    const f = e.target.files[0];
    if (!f) return;
    setSlipFile(f);
    setSlipPreview(URL.createObjectURL(f));
  };

  const handleSubmitSlip = async () => {
    if (!slipFile) { setErr("เลือกสลิปก่อนส่ง"); return; }
    setBusy(true); setErr("");
    setStep("verifying");
    try {
      const res = await submitSlip(slipFile, orderId, total);
      if (res.verified) {
        setAutoVerified(true);
        setStep("done");
      } else {
        setStep("waiting");
      }
    } catch(e) {
      setErr(e.message);
      setStep("qr");
    } finally { setBusy(false); }
  };

  // ── Success ────────────────────────────────────────
  if (step === "done") {
    return (
      <div data-screen-label="Checkout Success" style={{padding:"80px 0"}}>
        <div className="container">
          <div className="card" style={{maxWidth:520, margin:"0 auto", padding:44, textAlign:"center"}}>
            <div className="checkmark"><Icon name="check" size={48} stroke={3}/></div>
            <h1 className="display" style={{fontSize:44, margin:"16px 0 8px"}}>ชำระเงินสำเร็จ!</h1>
            <p style={{color:"var(--ink-soft)", marginTop:0}}>
              {autoVerified ? "ระบบตรวจสลิปสำเร็จ" : "แอดมินยืนยันการชำระเงินแล้ว"} — ฟอนต์พร้อมโหลดใน Dashboard
            </p>
            <div style={{display:"flex", gap:10, marginTop:24, justifyContent:"center"}}>
              <button className="btn coral lg" onClick={() => r.go("dashboard")}>
                <Icon name="download" size={16}/> ไปดาวน์โหลดฟอนต์
              </button>
              <button className="btn lg" onClick={() => r.go("fonts")}>ช็อปต่อ</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Waiting for admin ──────────────────────────────
  if (step === "waiting") {
    return (
      <div data-screen-label="Waiting" style={{padding:"80px 0"}}>
        <div className="container">
          <div className="card" style={{maxWidth:480, margin:"0 auto", padding:44, textAlign:"center"}}>
            <div style={{fontSize:56, marginBottom:16}}>⏳</div>
            <h2 className="display" style={{fontSize:32, margin:"0 0 8px"}}>รอแอดมินตรวจสลิป</h2>
            <p style={{color:"var(--ink-soft)"}}>ทีมงานจะตรวจสอบและยืนยันภายใน 15–30 นาที หลังยืนยันแล้วโหลดได้ใน Dashboard</p>
            <div style={{background:"var(--paper)", border:"1px solid var(--line)", borderRadius:12, padding:14, marginTop:18, textAlign:"left"}}>
              <div style={{fontSize:12, color:"var(--ink-soft)"}}>หมายเลขคำสั่งซื้อ</div>
              <div style={{fontFamily:"var(--f-mono)", fontSize:15, fontWeight:500}}>#{String(orderId).slice(0,8).toUpperCase()}</div>
            </div>
            <button className="btn" style={{marginTop:20}} onClick={() => r.go("dashboard")}>ไปที่ Dashboard</button>
          </div>
        </div>
      </div>
    );
  }

  // ── Verifying slip ─────────────────────────────────
  if (step === "verifying") {
    return (
      <div data-screen-label="Verifying" style={{padding:"80px 0"}}>
        <div className="container" style={{maxWidth:400, margin:"0 auto", textAlign:"center"}}>
          <div style={{fontSize:48, marginBottom:16}}>🔍</div>
          <h2 className="display" style={{fontSize:28}}>กำลังตรวจสอบสลิป…</h2>
          <p style={{color:"var(--ink-soft)"}}>กรุณารอสักครู่</p>
        </div>
      </div>
    );
  }

  // ── QR + slip upload ───────────────────────────────
  if (step === "qr") {
    const qrUrl = cfg.promptpayQrUrl;
    return (
      <div data-screen-label="PromptPay" style={{padding:"48px 0"}}>
        <div className="container" style={{maxWidth:520, margin:"0 auto"}}>
          <h2 className="display" style={{fontSize:32, marginBottom:4, textAlign:"center"}}>โอนเงินผ่าน PromptPay</h2>
          <p style={{color:"var(--ink-soft)", textAlign:"center", marginTop:0}}>สแกน QR → โอนยอดตามที่แสดง → แนบสลิป</p>

          <div className="card" style={{padding:28, textAlign:"center", marginBottom:18}}>
            {qrUrl
              ? <img src={qrUrl} style={{width:200, height:200, display:"block", margin:"0 auto 12px"}} alt="PromptPay QR"/>
              : <div style={{width:200, height:200, margin:"0 auto 12px", background:"var(--paper)", border:"2px dashed var(--line)", borderRadius:12, display:"grid", placeItems:"center", color:"var(--ink-soft)", fontSize:13}}>ใส่ QR ใน store-config.js</div>
            }
            <div style={{fontSize:13, color:"var(--ink-soft)", marginBottom:4}}>{cfg.promptpayName || "GMC Fontverse"}</div>
            <div className="display-2" style={{fontSize:40}}>฿{total}</div>
            <div style={{fontSize:13, color:"var(--ink-soft)", marginTop:4}}>โอนยอดนี้เท่านั้น</div>
          </div>

          <div className="card" style={{padding:24}}>
            <div style={{fontWeight:600, marginBottom:12}}>แนบสลิปการโอน</div>
            {slipPreview
              ? <img src={slipPreview} style={{width:"100%", maxHeight:280, objectFit:"contain", borderRadius:10, marginBottom:12, border:"1px solid var(--line)"}}/>
              : (
                <label style={{display:"block", border:"2px dashed var(--line)", borderRadius:12, padding:"32px 0", textAlign:"center", cursor:"pointer", background:"var(--paper)", marginBottom:12}}>
                  <div style={{fontSize:32, marginBottom:6}}>📎</div>
                  <div style={{fontWeight:500}}>แตะเพื่อเลือกสลิป</div>
                  <div style={{fontSize:12, color:"var(--ink-soft)", marginTop:4}}>รองรับ JPG, PNG</div>
                  <input type="file" accept="image/*" style={{display:"none"}} onChange={pickSlip}/>
                </label>
              )
            }
            {slipPreview && (
              <label className="btn sm ghost" style={{display:"block", textAlign:"center", cursor:"pointer", marginBottom:12}}>
                เปลี่ยนสลิป
                <input type="file" accept="image/*" style={{display:"none"}} onChange={pickSlip}/>
              </label>
            )}
            {err && <div style={{color:"var(--coral-deep)", fontSize:13, marginBottom:10}}>{err}</div>}
            <button className="btn coral lg block" disabled={!slipFile || busy} onClick={handleSubmitSlip}>
              {busy ? "⏳ กำลังส่ง…" : "ส่งสลิปยืนยันการชำระ"}
            </button>
            <div style={{fontSize:11, color:"var(--ink-soft)", textAlign:"center", marginTop:8}}>
              {cfg.easyslipEnabled ? "ระบบตรวจสลิปอัตโนมัติ" : "แอดมินจะตรวจสอบภายใน 30 นาที"}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Email + confirm form ───────────────────────────
  return (
    <div data-screen-label="Checkout">
      <section style={{padding:"40px 0 24px", borderBottom:"1px solid var(--line)"}}>
        <div className="container">
          <span className="eyebrow">💳 Checkout</span>
          <h1 className="display" style={{fontSize:"clamp(36px, 4.5vw, 62px)", margin:"8px 0 12px"}}>ชำระเงิน</h1>
          <div className="steps">
            <div className="step"><span className="n">1</span>ตะกร้า</div>
            <span className="dash"/>
            <div className="step on"><span className="n">2</span>ชำระเงิน</div>
            <span className="dash"/>
            <div className="step"><span className="n">3</span>ดาวน์โหลด</div>
          </div>
        </div>
      </section>
      <section className="section-tight">
        <div className="container" style={{maxWidth:520}}>
          <div className="summary">
              <h3 className="display" style={{fontSize:22, margin:"0 0 4px"}}>คำสั่งซื้อ</h3>
              {a.cart.map((item,i) => (
                <div key={i} style={{display:"flex", alignItems:"center", gap:10, padding:"10px 0", borderBottom:"1px dashed var(--line-soft)"}}>
                  <div style={{width:40, height:40, borderRadius:10, background:`var(--${item.color})`, border:"1px solid var(--line)", display:"grid", placeItems:"center", fontFamily:item.family, fontSize:18, flexShrink:0, overflow:"hidden", padding:0}}>
                    {item.image
                      ? <img src={item.image} alt={item.name} style={{width:"100%", height:"100%", objectFit:"cover"}}/>
                      : (item.languages.includes("thai") ? "ก" : "A")}
                  </div>
                  <div style={{flex:1, fontSize:13}}>
                    <div style={{fontWeight:500}}>{item.name}</div>
                    <div style={{color:"var(--ink-soft)"}}>{item.licenseTier === "personal" ? "ส่วนตัว" : "พาณิชย์"}</div>
                  </div>
                  <div className="display-2" style={{fontSize:16}}>฿{item.price}</div>
                </div>
              ))}
              <div className="line"><span>ราคารวม</span><b>฿{subtotal}</b></div>
              {discount > 0 && <div className="line" style={{color:"var(--coral-deep)"}}><span>ส่วนลด</span><b>-฿{discount}</b></div>}
              <div style={{height:1, background:"var(--line)"}}/>
              <div className="line" style={{fontSize:22, fontFamily:"var(--f-display-2)"}}><span>ยอดสุทธิ</span><span>฿{total}</span></div>
              <button className="btn coral lg block" disabled={busy} onClick={handleStartPayment}>
                {busy ? "⏳ กำลังสร้างคำสั่งซื้อ…" : <><Icon name="lock" size={14}/> ดำเนินการชำระเงิน</>}
              </button>
              {err && <div style={{color:"var(--coral-deep)", fontSize:13, marginTop:6}}>{err}</div>}
            </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Cart, Checkout });
