/* Multi-step Xendit renewal checkout flow */
const { useState: useStateCheckout, useMemo: useMemoCheckout } = React;

const DURATIONS = [
  { id: 1,  label: "1 Bulan",  months: 1 },
  { id: 3,  label: "3 Bulan",  months: 3,  badge: "Hemat 3%",  discount: 0.03 },
  { id: 6,  label: "6 Bulan",  months: 6,  badge: "Hemat 5%",  discount: 0.05 },
  { id: 12, label: "12 Bulan", months: 12, badge: "Hemat 10%", discount: 0.10, recommended: true },
];

const PAYMENT_METHODS = [
  { id:"bca",       group:"va",    label:"BCA Virtual Account",       fee:4000,  iconBg:"#0060AF", iconText:"BCA" },
  { id:"mandiri",   group:"va",    label:"Mandiri Virtual Account",   fee:4000,  iconBg:"#003D7A", iconText:"M" },
  { id:"bni",       group:"va",    label:"BNI Virtual Account",       fee:4000,  iconBg:"#F46524", iconText:"BNI" },
  { id:"bri",       group:"va",    label:"BRI Virtual Account",       fee:4000,  iconBg:"#005CAB", iconText:"BRI" },
  { id:"qris",      group:"qris",  label:"QRIS",                      fee:0,     iconBg:"#1A1A1A", iconText:"QR" },
  { id:"ovo",       group:"ewallet", label:"OVO",                      fee:0,    iconBg:"#4C2A85", iconText:"O" },
  { id:"gopay",     group:"ewallet", label:"GoPay",                    fee:0,    iconBg:"#00AED6", iconText:"G" },
  { id:"dana",      group:"ewallet", label:"DANA",                     fee:0,    iconBg:"#118EEA", iconText:"D" },
  { id:"shopeepay", group:"ewallet", label:"ShopeePay",                fee:0,    iconBg:"#EE4D2D", iconText:"S" },
];

function CheckoutView() {
  const { route, machines, navigate, client, toast } = useApp();
  const m = machines.find(x => x.id === route.id) || machines[0];

  const [step, setStep] = useStateCheckout(1);
  const [duration, setDuration] = useStateCheckout(DURATIONS[2]);
  const [addons, setAddons] = useStateCheckout({
    cloud: m.addons.cloud,
    refill: m.addons.refill,
    cloudApi: m.addons.cloudApi,
    cloudYearly: true,
  });
  const [method, setMethod] = useStateCheckout(null);

  // Pricing
  const calc = useMemoCheckout(() => {
    const cloudRate = addons.cloudYearly ? 350000 : 400000;
    const monthlyItems = [
      { label:"Sewa Pokok", desc:m.model, qty:duration.months, unit:m.rates.sewa, total:duration.months*m.rates.sewa, required:true },
      ...(addons.cloud ? [{ label:"Cloud Server / Dashboard", desc:addons.cloudYearly?"tahunan":"bulanan", qty:duration.months, unit:cloudRate, total:duration.months*cloudRate }] : []),
      ...(addons.refill ? [{ label:"Jasa Refill", desc:"max 10x/bln", qty:duration.months, unit:1500000, total:duration.months*1500000 }] : []),
      ...(addons.cloudApi ? [{ label:"Cloud API", desc:"integrasi data", qty:duration.months, unit:100000, total:duration.months*100000 }] : []),
    ];
    const subtotal = monthlyItems.reduce((a,b) => a+b.total, 0);
    const discount = Math.round(subtotal * (duration.discount || 0));
    const afterDisc = subtotal - discount;
    const ppn = Math.round(afterDisc * 0.11);
    const adminFee = method?.fee || 0;
    const total = afterDisc + ppn + adminFee;
    return { items: monthlyItems, subtotal, discount, afterDisc, ppn, adminFee, total };
  }, [duration, addons, method, m]);

  // Compute new end date
  const newEnd = useMemoCheckout(() => {
    const d = new Date(m.contractEnd);
    d.setMonth(d.getMonth() + duration.months);
    return d.toISOString().split("T")[0];
  }, [duration, m]);

  return (
    <div className="px-5 md:px-8 py-7 md:py-9 max-w-5xl mx-auto">
      <button onClick={() => navigate({ name: "machine-detail", id: m.id })} className="flex items-center gap-1.5 text-sm font-semibold text-stone-500 hover:text-[#FF2D55] mb-5">
        <Icon name="chevronL" size={16}/> Kembali ke {m.id}
      </button>

      <PageHeader
        eyebrow="Perpanjang Kontrak"
        jp="契約延長"
        title="Perpanjang Sewa"
        sub={`${m.id} · ${m.model} · ${m.location}`}
      />

      <Stepper step={step}/>

      {step === 1 && <Step1 m={m} duration={duration} setDuration={setDuration} addons={addons} setAddons={setAddons} onNext={() => setStep(2)} calc={calc}/>}
      {step === 2 && <Step2 m={m} duration={duration} addons={addons} calc={calc} newEnd={newEnd} onBack={() => setStep(1)} onNext={() => setStep(3)}/>}
      {step === 3 && <Step3 m={m} duration={duration} addons={addons} calc={calc} method={method} setMethod={setMethod} client={client} onBack={() => setStep(2)} onPay={() => {
        if (!method) { toast("Pilih metode pembayaran dulu.", "warning"); return; }
        navigate({ name: "payment-success", id: m.id, method: method.label, total: calc.total, newEnd });
      }}/>}
    </div>
  );
}

function Stepper({ step }) {
  const steps = [
    { id:1, label:"Pilih Durasi" },
    { id:2, label:"Ringkasan" },
    { id:3, label:"Pembayaran" },
  ];
  return (
    <div className="mb-7 flex items-center gap-2">
      {steps.map((s, i) => (
        <React.Fragment key={s.id}>
          <div className={`flex items-center gap-2 px-3 py-2 rounded-full text-sm font-semibold transition-all ${
            step === s.id ? "bg-[#FF2D55] text-white" : step > s.id ? "bg-emerald-50 text-emerald-700" : "bg-stone-100 text-stone-500"
          }`}>
            <span className={`w-5 h-5 rounded-full flex items-center justify-center text-xs ${step > s.id ? "bg-emerald-600 text-white" : step===s.id?"bg-white text-[#FF2D55]":"bg-white text-stone-500"}`}>
              {step > s.id ? <Icon name="check" size={12}/> : s.id}
            </span>
            <span className="hidden sm:inline">{s.label}</span>
          </div>
          {i < steps.length - 1 && <div className={`flex-1 h-px ${step > s.id ? "bg-emerald-300" : "bg-stone-200"}`}></div>}
        </React.Fragment>
      ))}
    </div>
  );
}

/* STEP 1 — Pilih durasi + add-ons */
function Step1({ m, duration, setDuration, addons, setAddons, onNext, calc }) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
      <div className="lg:col-span-2 space-y-5">
        <Card className="p-6">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500 mb-1">Step 1</div>
          <h2 className="font-display text-2xl uppercase text-[#1A1A1A]">Pilih Durasi Perpanjangan</h2>
          <p className="text-sm text-stone-500 mt-1">Semakin lama, semakin hemat.</p>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-5">
            {DURATIONS.map(d => {
              const active = duration.id === d.id;
              return (
                <button key={d.id} onClick={() => setDuration(d)} className={`relative text-left rounded-2xl p-4 border-2 transition-all ${
                  active ? "border-[#FF2D55] bg-pink-50" : "border-stone-200 bg-white hover:border-stone-400"
                }`}>
                  {d.recommended && <span className="absolute -top-2 left-3 px-2 py-0.5 bg-[#1A1A1A] text-white text-[10px] font-bold uppercase tracking-wider rounded">Rekomendasi</span>}
                  <div className="font-display text-2xl uppercase text-[#1A1A1A]">{d.label}</div>
                  {d.badge && <div className="text-xs font-bold text-[#FF2D55] mt-1">{d.badge}</div>}
                  {!d.badge && <div className="text-xs text-stone-500 mt-1">Standar</div>}
                  {active && <div className="absolute top-3 right-3 w-5 h-5 rounded-full bg-[#FF2D55] text-white flex items-center justify-center"><Icon name="check" size={12}/></div>}
                </button>
              );
            })}
          </div>
        </Card>

        <Card className="p-6">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500 mb-1">Add-on</div>
          <h2 className="font-display text-2xl uppercase text-[#1A1A1A]">Layanan Tambahan</h2>
          <p className="text-sm text-stone-500 mt-1">Pilih sesuai kebutuhan operasional Anda.</p>

          <div className="mt-5 space-y-3">
            <AddonRow
              checked={addons.cloud}
              onChange={v => setAddons({...addons, cloud:v})}
              icon="cpu"
              title="Cloud Server / Dashboard"
              desc="Real-time monitoring penjualan, stok, dan status mesin."
              price={addons.cloudYearly?350000:400000}
              extra={
                <div className="flex gap-2 mt-3">
                  {[{id:true,l:"Tahunan",p:"Rp 350k/bln"},{id:false,l:"Bulanan",p:"Rp 400k/bln"}].map(o => (
                    <button key={String(o.id)} type="button" onClick={() => setAddons({...addons, cloudYearly:o.id})} disabled={!addons.cloud}
                      className={`flex-1 px-3 py-2 rounded-lg text-sm font-semibold border transition ${
                        addons.cloudYearly===o.id ? "border-[#FF2D55] bg-pink-50 text-[#FF2D55]" : "border-stone-200 text-stone-600 hover:border-stone-400"
                      } ${!addons.cloud?"opacity-40":""}`}>
                      {o.l}<span className="font-normal text-xs ml-1.5">{o.p}</span>
                    </button>
                  ))}
                </div>
              }
            />
            <AddonRow
              checked={addons.refill}
              onChange={v => setAddons({...addons, refill:v})}
              icon="shoppingBag"
              title="Jasa Refill"
              desc="Tim kami yang refill produk. Maksimal 10× per bulan."
              price={1500000}
            />
            <AddonRow
              checked={addons.cloudApi}
              onChange={v => setAddons({...addons, cloudApi:v})}
              icon="zap"
              title="Cloud API"
              desc="Integrasi data penjualan ke sistem Anda."
              price={100000}
            />
          </div>
        </Card>
      </div>

      <div className="lg:col-span-1">
        <SummarySidebar m={m} duration={duration} calc={calc} onNext={onNext} ctaLabel="Lanjut ke Ringkasan"/>
      </div>
    </div>
  );
}

function AddonRow({ checked, onChange, icon, title, desc, price, extra }) {
  return (
    <label className={`flex items-start gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all ${checked ? "border-[#FF2D55] bg-pink-50/40" : "border-stone-200 bg-white hover:border-stone-300"}`}>
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} className="mt-1 accent-[#FF2D55] w-5 h-5"/>
      <div className={`w-11 h-11 rounded-xl flex items-center justify-center flex-none ${checked ? "bg-[#FF2D55] text-white" : "bg-stone-100 text-stone-500"}`}>
        <Icon name={icon} size={20}/>
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <div>
            <div className="font-semibold text-[#1A1A1A]">{title}</div>
            <div className="text-xs text-stone-500 mt-0.5 leading-relaxed">{desc}</div>
          </div>
          <div className="font-display text-lg text-[#FF2D55] whitespace-nowrap">{formatRp(price)}<span className="font-sans font-normal text-xs text-stone-400 ml-1">/bln</span></div>
        </div>
        {extra}
      </div>
    </label>
  );
}

/* Sidebar summary */
function SummarySidebar({ m, duration, calc, onNext, ctaLabel }) {
  return (
    <Card className="p-5 sticky top-24">
      <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500">Ringkasan</div>
      <div className="font-display text-xl uppercase text-[#1A1A1A] mt-1">Total Bayar</div>

      <div className="mt-4 pt-4 border-t border-stone-100 space-y-2 text-sm">
        <div className="flex justify-between"><span className="text-stone-600">Subtotal ({duration.months} bln)</span><span className="font-semibold text-[#1A1A1A]">{formatRp(calc.subtotal)}</span></div>
        {calc.discount > 0 && (
          <div className="flex justify-between"><span className="text-emerald-700">Diskon durasi</span><span className="font-semibold text-emerald-700">−{formatRp(calc.discount)}</span></div>
        )}
        <div className="flex justify-between"><span className="text-stone-600">PPN 11%</span><span className="font-semibold text-[#1A1A1A]">{formatRp(calc.ppn)}</span></div>
        {calc.adminFee > 0 && (
          <div className="flex justify-between"><span className="text-stone-600">Biaya admin</span><span className="font-semibold text-[#1A1A1A]">{formatRp(calc.adminFee)}</span></div>
        )}
      </div>

      <div className="mt-4 pt-4 border-t-2 border-dashed border-stone-200 flex items-baseline justify-between">
        <span className="text-sm font-bold text-stone-700">Total</span>
        <div className="text-right">
          <div className="font-display text-2xl text-[#FF2D55] leading-none">{formatRp(calc.total)}</div>
          <div className="text-[10px] uppercase tracking-widest text-stone-500 mt-1">untuk {duration.months} bulan</div>
        </div>
      </div>

      <Button size="lg" className="w-full mt-5" onClick={onNext}>
        {ctaLabel} <Icon name="arrowR" size={16}/>
      </Button>
      <div className="flex items-center gap-1.5 mt-3 text-[11px] text-stone-500 justify-center">
        <Icon name="shield" size={12}/> Pembayaran aman via <strong className="text-[#1A1A1A]">Xendit</strong>
      </div>
    </Card>
  );
}

/* STEP 2 — Ringkasan order */
function Step2({ m, duration, addons, calc, newEnd, onBack, onNext }) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
      <div className="lg:col-span-2 space-y-5">
        <Card className="p-6">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500 mb-1">Step 2</div>
          <h2 className="font-display text-2xl uppercase text-[#1A1A1A]">Ringkasan Order</h2>
          <p className="text-sm text-stone-500 mt-1">Periksa detail sebelum melanjutkan ke pembayaran.</p>

          <div className="mt-5 p-4 rounded-xl bg-stone-50 border border-stone-200 flex gap-4">
            <div className="w-14 h-16 rounded-lg flex items-center justify-center flex-none" style={{background: m.color}}>
              <Icon name={m.category==="coffee"?"coffee":"grid"} size={26} className="text-[#1A1A1A]"/>
            </div>
            <div className="flex-1">
              <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500">{m.model}</div>
              <div className="font-display text-lg uppercase text-[#1A1A1A] mt-0.5">{m.id}</div>
              <div className="text-sm text-stone-600">{m.location}</div>
            </div>
            <div className="text-right text-sm">
              <div className="text-stone-500">Periode baru</div>
              <div className="font-semibold text-[#1A1A1A]">{formatDateID(m.contractEnd)}</div>
              <div className="text-xs text-stone-400">s/d</div>
              <div className="font-semibold text-[#FF2D55]">{formatDateID(newEnd)}</div>
            </div>
          </div>

          <div className="mt-5 overflow-hidden rounded-xl border border-stone-200">
            <div className="grid grid-cols-12 px-4 py-3 text-[11px] font-bold uppercase tracking-widest text-stone-500 bg-stone-50 border-b border-stone-200">
              <div className="col-span-6">Item</div>
              <div className="col-span-2 text-right">Qty</div>
              <div className="col-span-2 text-right">Harga</div>
              <div className="col-span-2 text-right">Total</div>
            </div>
            {calc.items.map((it, i) => (
              <div key={i} className="grid grid-cols-12 px-4 py-3 items-center text-sm border-b border-stone-100 last:border-0">
                <div className="col-span-6"><div className="font-medium text-[#1A1A1A]">{it.label}</div><div className="text-xs text-stone-500">{it.desc}</div></div>
                <div className="col-span-2 text-right text-stone-600">×{it.qty}</div>
                <div className="col-span-2 text-right text-stone-600">{formatRp(it.unit)}</div>
                <div className="col-span-2 text-right font-semibold text-[#1A1A1A]">{formatRp(it.total)}</div>
              </div>
            ))}
          </div>

          <div className="mt-5 space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-stone-600">Subtotal</span><span className="text-[#1A1A1A]">{formatRp(calc.subtotal)}</span></div>
            {calc.discount > 0 && <div className="flex justify-between text-emerald-700"><span>Diskon {Math.round((duration.discount||0)*100)}%</span><span>−{formatRp(calc.discount)}</span></div>}
            <div className="flex justify-between"><span className="text-stone-600">PPN 11%</span><span className="text-[#1A1A1A]">{formatRp(calc.ppn)}</span></div>
            <div className="flex justify-between pt-3 border-t-2 border-dashed border-stone-200">
              <span className="font-bold text-stone-700">Total</span>
              <span className="font-display text-2xl text-[#FF2D55]">{formatRp(calc.total - (calc.adminFee||0))}</span>
            </div>
            <div className="text-xs text-stone-500 text-right">+ biaya admin tergantung metode pembayaran</div>
          </div>
        </Card>
      </div>

      <div className="lg:col-span-1 space-y-3">
        <Card className="p-5 sticky top-24">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500 mb-2">Konfirmasi</div>
          <h3 className="font-display text-xl uppercase text-[#1A1A1A]">Siap bayar?</h3>
          <p className="text-sm text-stone-500 mt-1.5">Pilih metode pembayaran di langkah berikutnya.</p>
          <Button size="lg" className="w-full mt-5" onClick={onNext}>
            Lanjut Pembayaran <Icon name="arrowR" size={16}/>
          </Button>
          <Button variant="subtle" className="w-full mt-2" onClick={onBack}>
            <Icon name="chevronL" size={16}/> Kembali ubah
          </Button>
          <div className="mt-4 pt-4 border-t border-stone-100 text-[11px] text-stone-500 flex items-center gap-2">
            <Icon name="shield" size={14}/> Invoice akan dibuat via Xendit dan dikirim ke email Anda.
          </div>
        </Card>
      </div>
    </div>
  );
}

/* STEP 3 — Pembayaran */
function Step3({ m, duration, addons, calc, method, setMethod, client, onBack, onPay }) {
  const groups = [
    { id:"va", label:"Transfer Virtual Account", desc:"Bayar via ATM, mobile/internet banking." },
    { id:"qris", label:"QRIS", desc:"Scan dengan aplikasi e-wallet atau mobile banking." },
    { id:"ewallet", label:"E-Wallet", desc:"OVO, GoPay, DANA, ShopeePay." },
  ];
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
      <div className="lg:col-span-2 space-y-5">
        <Card className="p-6">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500 mb-1">Step 3</div>
          <h2 className="font-display text-2xl uppercase text-[#1A1A1A]">Metode Pembayaran</h2>
          <p className="text-sm text-stone-500 mt-1">Powered by <strong className="text-[#1A1A1A]">Xendit</strong>. Aman, instan, dan otomatis update status.</p>

          {groups.map(g => (
            <div key={g.id} className="mt-6">
              <div className="text-sm font-bold text-[#1A1A1A]">{g.label}</div>
              <div className="text-xs text-stone-500 mb-3">{g.desc}</div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {PAYMENT_METHODS.filter(pm => pm.group === g.id).map(pm => {
                  const active = method?.id === pm.id;
                  return (
                    <button key={pm.id} onClick={() => setMethod(pm)} className={`flex items-center gap-3 p-3.5 rounded-xl border-2 text-left transition-all ${
                      active ? "border-[#FF2D55] bg-pink-50" : "border-stone-200 bg-white hover:border-stone-400"
                    }`}>
                      <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white text-[11px] font-bold flex-none" style={{background: pm.iconBg}}>{pm.iconText}</div>
                      <div className="flex-1">
                        <div className="font-semibold text-[#1A1A1A] text-sm">{pm.label}</div>
                        <div className="text-xs text-stone-500">{pm.fee > 0 ? `Biaya admin ${formatRp(pm.fee)}` : "Tanpa biaya admin"}</div>
                      </div>
                      {active && <div className="w-5 h-5 rounded-full bg-[#FF2D55] text-white flex items-center justify-center"><Icon name="check" size={12}/></div>}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </Card>

        <Card className="p-6 bg-stone-900 text-white">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-400 mb-2">Xendit Invoice Payload (dev)</div>
          <pre className="text-xs text-stone-300 overflow-auto font-mono leading-relaxed">{`POST https://api.xendit.co/v2/invoices

{
  "external_id": "yappari-${m.id}-${Date.now()}",
  "amount": ${calc.total},
  "currency": "IDR",
  "description": "Perpanjangan ${duration.label} — ${m.model}",
  "invoice_duration": 86400,
  "customer": {
    "given_names": "${client.name}",
    "email": "${client.email}",
    "mobile_number": "${client.phone}"
  },
  "payment_methods": [${method ? `"${method.id.toUpperCase()}"` : "..."}]
}`}</pre>
        </Card>
      </div>

      <div className="lg:col-span-1">
        <Card className="p-5 sticky top-24">
          <div className="text-[11px] font-bold uppercase tracking-widest text-stone-500">Ringkasan Final</div>
          <div className="font-display text-xl uppercase text-[#1A1A1A] mt-1">Total</div>

          <div className="mt-4 pt-4 border-t border-stone-100 space-y-2 text-sm">
            <div className="flex justify-between"><span className="text-stone-600">{m.id} × {duration.months} bln</span><span className="text-[#1A1A1A]">{formatRp(calc.subtotal)}</span></div>
            {calc.discount > 0 && <div className="flex justify-between text-emerald-700"><span>Diskon</span><span>−{formatRp(calc.discount)}</span></div>}
            <div className="flex justify-between"><span className="text-stone-600">PPN 11%</span><span className="text-[#1A1A1A]">{formatRp(calc.ppn)}</span></div>
            {calc.adminFee > 0 && <div className="flex justify-between"><span className="text-stone-600">Admin {method?.label}</span><span className="text-[#1A1A1A]">{formatRp(calc.adminFee)}</span></div>}
          </div>
          <div className="mt-4 pt-4 border-t-2 border-dashed border-stone-200 flex items-baseline justify-between">
            <span className="text-sm font-bold text-stone-700">Total bayar</span>
            <div className="font-display text-2xl text-[#FF2D55]">{formatRp(calc.total)}</div>
          </div>
          <Button size="lg" className="w-full mt-5" onClick={onPay} disabled={!method}>
            Bayar Sekarang <Icon name="arrowR" size={16}/>
          </Button>
          <Button variant="subtle" className="w-full mt-2" onClick={onBack}><Icon name="chevronL" size={16}/> Kembali</Button>
          <div className="flex items-center gap-1.5 mt-3 text-[11px] text-stone-500 justify-center">
            <Icon name="shield" size={12}/> Anda akan diarahkan ke halaman pembayaran Xendit.
          </div>
        </Card>
      </div>
    </div>
  );
}

/* ===== PAYMENT SUCCESS ===== */
function PaymentSuccessView() {
  const { route, navigate } = useApp();
  return (
    <div className="px-5 md:px-8 py-12 md:py-16 max-w-2xl mx-auto">
      <Card className="p-8 md:p-10 text-center relative overflow-hidden">
        <div className="absolute -right-4 -top-4 font-jp font-black text-[200px] leading-[0.8] text-pink-100 select-none">完</div>
        <div className="relative">
          <div className="w-20 h-20 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center mx-auto">
            <Icon name="check" size={40} stroke={2.5}/>
          </div>
          <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-emerald-700 mt-5">Pembayaran Berhasil</div>
          <h1 className="font-display text-4xl md:text-5xl uppercase text-[#1A1A1A] mt-2 leading-none">Terima kasih!</h1>
          <p className="text-stone-600 mt-3">Kontrak mesin <strong>{route.id}</strong> berhasil diperpanjang sampai <strong className="text-[#FF2D55]">{formatDateID(route.newEnd)}</strong>.</p>

          <div className="mt-6 p-4 rounded-xl bg-stone-50 border border-stone-200 text-left">
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div><div className="text-xs text-stone-500">Metode</div><div className="font-semibold text-[#1A1A1A]">{route.method}</div></div>
              <div><div className="text-xs text-stone-500">Total bayar</div><div className="font-semibold text-[#1A1A1A]">{formatRp(route.total)}</div></div>
              <div><div className="text-xs text-stone-500">Invoice ID</div><div className="font-mono text-xs text-[#1A1A1A]">yappari-{route.id}-{Date.now().toString().slice(-6)}</div></div>
              <div><div className="text-xs text-stone-500">Status</div><Badge tone="success" className="mt-0.5">Lunas</Badge></div>
            </div>
          </div>

          <p className="text-xs text-stone-500 mt-4">Email konfirmasi sudah dikirim. Receipt PDF tersedia di Detail Mesin.</p>

          <div className="flex flex-wrap justify-center gap-2 mt-6">
            <Button variant="primary" onClick={() => navigate({ name: "machine-detail", id: route.id })}>
              Lihat Mesin <Icon name="arrowR" size={16}/>
            </Button>
            <Button variant="ghost" onClick={() => navigate({ name: "overview" })}>Kembali ke Dashboard</Button>
          </div>
        </div>
      </Card>
    </div>
  );
}

/* ===== PAYMENT FAILED ===== */
function PaymentFailedView() {
  const { route, navigate } = useApp();
  return (
    <div className="px-5 md:px-8 py-12 md:py-16 max-w-2xl mx-auto">
      <Card className="p-8 md:p-10 text-center">
        <div className="w-20 h-20 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center mx-auto">
          <Icon name="x" size={40} stroke={2.5}/>
        </div>
        <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-rose-700 mt-5">Pembayaran Gagal</div>
        <h1 className="font-display text-4xl uppercase text-[#1A1A1A] mt-2">Mohon dicoba lagi.</h1>
        <p className="text-stone-600 mt-3">Pembayaran tidak berhasil diproses. Coba metode lain atau hubungi tim kami.</p>
        <div className="flex flex-wrap justify-center gap-2 mt-6">
          <Button variant="primary" onClick={() => navigate({ name: "machine-renew", id: route.id })}>Coba Lagi</Button>
          <Button variant="ghost" onClick={() => navigate({ name: "overview" })}>Kembali</Button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { CheckoutView, PaymentSuccessView, PaymentFailedView });
