const AccountPage = ({ user, onLogout, setPage, lang }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const [tab, setTab] = React.useState("profile");
  const [profile, setProfile] = React.useState({ name: user?.name || "", phone: "" });
  const [address, setAddress] = React.useState({ address:"", district:"", city:"", province:"", postal:"", area_id:"" });
  const [savedAddr, setSavedAddr] = React.useState(null);
  const [password, setPassword] = React.useState({ old:"", new1:"", new2:"" });
  const [orders,  setOrders]  = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [msg,     setMsg]     = React.useState({ text:"", ok:true });

  // Modal states
  const [trackingModal, setTrackingModal] = React.useState(null);  // { order, tracking, loading }
  const [paying,        setPaying]        = React.useState(null);  // order_number being paid

  const STATUS_LABEL = {
    pending:"Menunggu Bayar", paid:"Dibayar", confirmed:"Dikonfirmasi",
    processing:"Diproses", shipped:"Dikirim", delivered:"Selesai", cancelled:"Dibatalkan"
  };
  const STATUS_COLOR = {
    pending:"#f59e0b", paid:"#10b981", confirmed:"#3b82f6",
    processing:"#8b5cf6", shipped:"#06b6d4", delivered:"#22c55e", cancelled:"#ef4444"
  };
  const fmt  = n => "Rp" + Number(n).toLocaleString("id-ID");
  const fmtD = d => new Date(d).toLocaleDateString("id-ID", { day:"numeric", month:"short", year:"numeric" });
  const fmtDT = d => new Date(d).toLocaleString("id-ID", { day:"numeric", month:"short", hour:"2-digit", minute:"2-digit" });

  const showMsg = (text, ok=true) => { setMsg({text,ok}); setTimeout(()=>setMsg({text:"",ok:true}),3000); };

  // Load profil & alamat
  React.useEffect(() => {
    fetch("api/account.php", { credentials:"include" })
      .then(r => r.json())
      .then(d => {
        if (d.user) {
          setProfile({ name: d.user.name||"", phone: d.user.phone||"" });
          if (d.user.saved_address) {
            setSavedAddr(d.user.saved_address);
            setAddress(prev => ({ ...prev, ...d.user.saved_address }));
          }
        }
      }).catch(() => {});
  }, []);

  // Load orders
  const loadOrders = () => {
    setLoading(true);
    fetch(`api/order.php?email=${encodeURIComponent(user?.email||"")}`, { credentials:"include" })
      .then(r => r.json())
      .then(d => setOrders(d.orders || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  };
  React.useEffect(() => { if (tab === "orders") loadOrders(); }, [tab]);

  const saveProfile = async () => {
    setLoading(true);
    const res = await fetch("api/account.php", { method:"POST", credentials:"include", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ action:"update_profile", name:profile.name, phone:profile.phone }) });
    const d   = await res.json();
    setLoading(false);
    if (d.success) showMsg("✓ Profil berhasil disimpan!");
    else showMsg("❌ " + (d.error||"Gagal — coba login ulang"), false);
  };

  const saveAddress = async () => {
    setLoading(true);
    const res = await fetch("api/account.php", { method:"POST", credentials:"include", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ action:"save_address", address:address.address, district:address.district, city:address.city, province:address.province, postal:address.postal, area_id:address.area_id||"" }) });
    const d   = await res.json();
    setLoading(false);
    if (d.success) { setSavedAddr({...address}); showMsg("✓ Alamat berhasil disimpan!"); }
    else showMsg("❌ " + (d.error||"Gagal"), false);
  };

  const changePassword = async () => {
    if (password.new1 !== password.new2) { showMsg("❌ Password baru tidak cocok", false); return; }
    if (password.new1.length < 6) { showMsg("❌ Password minimal 6 karakter", false); return; }
    setLoading(true);
    const res = await fetch("api/account.php", { method:"POST", credentials:"include", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ action:"change_password", old_password:password.old, new_password:password.new1 }) });
    const d   = await res.json();
    setLoading(false);
    if (d.success) { setPassword({old:"",new1:"",new2:""}); showMsg("✓ Password berhasil diubah!"); }
    else showMsg("❌ " + (d.error||"Gagal"), false);
  };

  // ── Pay pending order (re-open Duitku) ────────────────
  const payNow = async (order_number) => {
    setPaying(order_number);
    try {
      const r = await fetch("api/payment.php", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({ order_number })
      });
      const d = await r.json();
      if (!d.success || !d.reference) {
        showMsg("❌ Gagal init pembayaran: " + (d.error || ""), false);
        setPaying(null);
        return;
      }
      // Load Duitku POP script
      if (!window.checkout || typeof window.checkout.process !== "function") {
        await new Promise((resolve, reject) => {
          const s = document.createElement("script");
          s.src     = d.popUrl || "https://app-sandbox.duitku.com/lib/js/duitku.js";
          s.onload  = resolve;
          s.onerror = () => reject(new Error("Gagal load Duitku"));
          document.head.appendChild(s);
        });
      }
      window.checkout.process(d.reference, {
        successEvent: () => { showMsg("✓ Pembayaran berhasil!"); loadOrders(); setPaying(null); },
        pendingEvent: () => { showMsg("⏳ Pembayaran pending..."); loadOrders(); setPaying(null); },
        errorEvent:   (e) => { showMsg("❌ " + (e?.message || "Pembayaran gagal"), false); setPaying(null); },
        closeEvent:   () => setPaying(null),
      });
    } catch (e) {
      showMsg("❌ " + e.message, false);
      setPaying(null);
    }
  };

  // ── Open tracking modal ───────────────────────────────
  const openTracking = async (order) => {
    setTrackingModal({ order, tracking:null, loading:true });
    try {
      const r = await fetch(`api/order.php?track=${encodeURIComponent(order.order_number)}`);
      const d = await r.json();
      setTrackingModal({ order: d.order || order, tracking: d.tracking, loading:false });
    } catch (e) {
      setTrackingModal({ order, tracking:null, loading:false });
    }
  };

  // ── Countdown timer untuk order pending ────────────────
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    if (tab !== "orders") return;
    const i = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(i);
  }, [tab]);

  const getCountdown = (created_at, expireMinutes = 60) => {
    const created = new Date(created_at).getTime();
    const expire  = created + expireMinutes * 60 * 1000;
    const left    = expire - now;
    if (left <= 0) return null;
    const mm = Math.floor(left / 60000);
    const ss = Math.floor((left % 60000) / 1000);
    return `${String(mm).padStart(2,"0")}:${String(ss).padStart(2,"0")}`;
  };

  // ── Timeline steps ────────────────────────────────────
  const TIMELINE_STEPS = [
    { key:"paid",       label:"Dibayar"   },
    { key:"processing", label:"Diproses"  },
    { key:"shipped",    label:"Dikirim"   },
    { key:"delivered",  label:"Diterima"  },
  ];
  const getStepIndex = (status) => {
    if (status === "delivered") return 4;
    if (status === "shipped")   return 3;
    if (status === "processing" || status === "confirmed") return 2;
    if (status === "paid")      return 1;
    return 0;
  };

  // ── Helper: check if order has PO items ────────────────
  const isPoOrder = (o) => o.tracking_status === "waiting_production";

  // ── Styles ────────────────────────────────────────────
  const inp = { width:"100%", padding:"11px 14px", border:"1px solid #e0deda", background:"#fafaf8", fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#111", outline:"none", borderRadius:2 };
  const lbl = { display:"block", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 };
  const btn = (bg="#111",cl="#f9f8f6") => ({ background:bg, color:cl, border:"none", cursor:"pointer", fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.1em", textTransform:"uppercase", fontWeight:600, padding:"11px 28px", borderRadius:2 });
  const tabStyle = (active) => ({
    flex: "1 1 auto",
    minWidth: 0,
    padding: "12px 8px",
    background: "none",
    border: "none",
    borderBottom: active ? "2px solid #111" : "2px solid transparent",
    fontFamily: "'DM Sans',sans-serif",
    fontSize: 10,
    letterSpacing: "0.05em",
    textTransform: "uppercase",
    color: active ? "#111" : "#aaa",
    cursor: "pointer",
    fontWeight: active ? 600 : 400,
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis"
  });

  // ── Single Order Card renderer ────────────────────────
  const renderOrderCard = (o) => {
    const isPo       = isPoOrder(o);
    const isPending  = o.status === "pending";
    const countdown  = isPending ? getCountdown(o.created_at, 60) : null;
    const stepIdx    = getStepIndex(o.status);
    const showTimeline = ["paid","processing","confirmed","shipped","delivered"].includes(o.status);
    const items      = o.items || [];

    return (
      <div key={o.id} style={{
        border:"1px solid #e8e6e2", borderRadius:4, background:"#fff",
        marginBottom:16, overflow:"hidden"
      }}>
        {/* Header */}
        <div style={{
          background:"#fafaf8", padding:"14px 16px", borderBottom:"1px solid #e8e6e2",
          display:"flex", justifyContent:"space-between", alignItems:"center", gap:12, flexWrap:"wrap"
        }}>
          <div>
            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:600, color:"#111" }}>
              {o.order_number}
            </p>
            <p style={{ fontSize:11, color:"#aaa", marginTop:2 }}>{fmtD(o.created_at)}</p>
          </div>
          <div style={{ display:"flex", gap:6, alignItems:"center", flexWrap:"wrap" }}>
            <span style={{
              padding:"3px 12px", borderRadius:20, fontSize:10, fontWeight:700,
              textTransform:"uppercase", letterSpacing:"0.05em",
              background:(STATUS_COLOR[o.status]||"#ddd")+"22",
              color: STATUS_COLOR[o.status]||"#888"
            }}>
              {STATUS_LABEL[o.status]||o.status}
            </span>
            {isPo && (
              <span style={{
                padding:"3px 10px", borderRadius:20, fontSize:10, fontWeight:700,
                textTransform:"uppercase", background:"#fde68a", color:"#92400e"
              }}>⏳ PO</span>
            )}
          </div>
        </div>

        {/* Pending — countdown + pay button */}
        {isPending && (
          <div style={{ background:"#fffbeb", padding:"14px 16px", borderBottom:"1px solid #fde68a" }}>
            {countdown ? (
              <>
                <p style={{ fontSize:12, color:"#92400e", marginBottom:10 }}>
                  ⏱ {t("Pay within", "Bayar dalam")}: <strong style={{ fontFamily:"monospace", fontSize:14 }}>{countdown}</strong>
                </p>
                <button onClick={() => payNow(o.order_number)} disabled={paying === o.order_number}
                  style={{ ...btn("#f59e0b","#fff"), padding:"10px 22px", fontSize:11, opacity: paying === o.order_number ? 0.6 : 1 }}>
                  {paying === o.order_number ? "Membuka..." : "💳 Bayar Sekarang"}
                </button>
              </>
            ) : (
              <p style={{ fontSize:12, color:"#c55", margin:0 }}>
                ⚠ {t("This order has expired", "Pesanan ini sudah expired")}
              </p>
            )}
          </div>
        )}

        {/* PO Banner */}
        {isPo && o.status === "paid" && (
          <div style={{ background:"#fffbeb", padding:"12px 20px", borderBottom:"1px solid #fde68a", fontSize:12, color:"#92400e" }}>
            ⏳ {t(
              "Your order is being produced. We'll notify you once it's ready to ship.",
              "Pesanan kamu sedang dibuat. Kami akan kabari setelah siap dikirim."
            )}
          </div>
        )}

        {/* Visual Timeline (untuk order paid+) */}
        {showTimeline && !isPo && (
          <div style={{ padding:"18px 12px", borderBottom:"1px solid #f0efed", overflowX:"auto" }}>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap:2, minWidth:280 }}>
              {TIMELINE_STEPS.map((step, i) => {
                const active = i < stepIdx;
                const current = i === stepIdx - 1;
                return (
                  <React.Fragment key={step.key}>
                    <div style={{ textAlign:"center", flexShrink:0, minWidth:50 }}>
                      <div style={{
                        width:24, height:24, borderRadius:"50%",
                        background: active ? (current ? "#10b981" : "#22c55e") : "#e8e6e2",
                        color: active ? "#fff" : "#aaa",
                        display:"flex", alignItems:"center", justifyContent:"center",
                        fontSize:10, fontWeight:700, margin:"0 auto",
                        border: current ? "3px solid #d1fae5" : "none",
                        boxSizing: current ? "border-box" : "content-box"
                      }}>
                        {active ? "✓" : (i+1)}
                      </div>
                      <p style={{
                        fontSize:8, fontWeight:600, marginTop:5,
                        color: active ? "#111" : "#aaa",
                        letterSpacing:"0.04em", textTransform:"uppercase",
                        whiteSpace:"nowrap"
                      }}>{step.label}</p>
                    </div>
                    {i < TIMELINE_STEPS.length - 1 && (
                      <div style={{
                        flex:1, height:2, marginTop:-18, minWidth:8,
                        background: i < stepIdx - 1 ? "#22c55e" : "#e8e6e2",
                      }} />
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </div>
        )}

        {/* Items */}
        <div style={{ padding:"14px 16px" }}>
          {items.map((it, idx) => (
            <div key={idx} style={{ display:"flex", gap:12, alignItems:"center", padding: idx === 0 ? "0 0 10px 0" : "10px 0", borderTop: idx > 0 ? "1px solid #f0efed" : "none" }}>
              {it.image && (
                <img src={it.image} alt={it.name}
                  style={{ width:50, height:50, objectFit:"cover", borderRadius:3, background:"#f0efed", flexShrink:0 }} />
              )}
              <div style={{ flex:1, minWidth:0 }}>
                <p style={{ fontSize:13, color:"#111", fontWeight:500, marginBottom:2, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{it.name}</p>
                <p style={{ fontSize:11, color:"#888" }}>
                  {it.selectedColor && `${it.selectedColor} · `}
                  {t("Qty", "Jumlah")}: {it.qty || it.quantity || 1}
                </p>
              </div>
              <p style={{ fontSize:13, color:"#111", fontWeight:500, flexShrink:0 }}>
                {fmt((it.price||0) * (it.qty||it.quantity||1))}
              </p>
            </div>
          ))}
        </div>

        {/* Footer */}
        <div style={{ padding:"14px 16px", background:"#fafaf8", borderTop:"1px solid #f0efed", display:"flex", justifyContent:"space-between", alignItems:"center", gap:12, flexWrap:"wrap" }}>
          <div style={{ fontSize:11, color:"#888" }}>
            {o.courier_name && <span>{o.courier_name.toUpperCase()} {o.courier_service?.toUpperCase()}</span>}
            {o.waybill_id && (
              <span style={{ marginLeft:8 }}>
                · {t("Tracking", "Resi")}: <strong style={{ color:"#111", fontFamily:"monospace" }}>{o.waybill_id}</strong>
              </span>
            )}
          </div>
          <div style={{ display:"flex", gap:8, alignItems:"center" }}>
            <p style={{ fontFamily:"'Cormorant Garant',serif", fontSize:20, color:"#111" }}>{fmt(o.total)}</p>
            {o.waybill_id && (
              <button onClick={() => openTracking(o)} style={{
                background:"#fff", border:"1px solid #111", color:"#111", padding:"8px 14px",
                fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.1em",
                textTransform:"uppercase", fontWeight:600, cursor:"pointer", borderRadius:2
              }}>
                📍 {t("Track", "Lacak")}
              </button>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div style={{ paddingTop:72, minHeight:"100vh", background:"#f9f8f6" }}>
      <div style={{ maxWidth:760, margin:"0 auto", padding:"32px 16px" }}>
        {/* Header */}
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:32, flexWrap:"wrap", gap:12 }}>
          <div style={{ minWidth:0, flex:"1 1 200px" }}>
            <h1 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:32, fontWeight:300, color:"#111" }}>Akun Saya</h1>
            <p style={{ fontSize:13, color:"#aaa", marginTop:4, overflow:"hidden", textOverflow:"ellipsis" }}>{user?.email}</p>
          </div>
          <button onClick={onLogout} style={{ ...btn("#fff5f5","#e55"), border:"1px solid #fcc", marginTop:8, flexShrink:0 }}>Logout</button>
        </div>

        {/* Toast */}
        {msg.text && (
          <div style={{ background:msg.ok?"#f0fdf4":"#fff5f5", border:`1px solid ${msg.ok?"#86efac":"#fcc"}`, padding:"12px 16px", borderRadius:2, marginBottom:20, fontSize:13, color:msg.ok?"#15803d":"#c55" }}>
            {msg.text}
          </div>
        )}

        <div style={{ background:"#fff", border:"1px solid #e8e6e2", borderRadius:3, overflow:"hidden" }}>
          {/* Tabs */}
          <div style={{ display:"flex", borderBottom:"1px solid #e8e6e2" }}>
            {[["profile","👤 Profil"],["orders","🛍 Pesanan"],["address","📍 Alamat"],["password","🔑 Password"]].map(([id,label]) => (
              <button key={id} style={tabStyle(tab===id)} onClick={() => setTab(id)}>{label}</button>
            ))}
          </div>

          <div style={{ padding:"24px 18px" }}>
            {/* ── Profil ── */}
            {tab === "profile" && (
              <div style={{ display:"flex", flexDirection:"column", gap:20, maxWidth:480 }}>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:24, fontWeight:400, marginBottom:8 }}>Informasi Profil</h2>
                <div>
                  <label style={lbl}>Nama Lengkap</label>
                  <input style={inp} value={profile.name} onChange={e => setProfile(p => ({...p, name:e.target.value}))} placeholder="Nama kamu" />
                </div>
                <div>
                  <label style={lbl}>Nomor HP / WhatsApp</label>
                  <input style={inp} value={profile.phone} onChange={e => setProfile(p => ({...p, phone:e.target.value}))} placeholder="08xx xxxx xxxx" />
                </div>
                <div>
                  <label style={lbl}>Email</label>
                  <input style={{ ...inp, background:"#f5f5f5", color:"#aaa" }} value={user?.email || ""} disabled />
                  <p style={{ fontSize:11, color:"#bbb", marginTop:4 }}>Email tidak bisa diubah</p>
                </div>
                <button onClick={saveProfile} disabled={loading} style={btn()}>
                  {loading ? "Menyimpan..." : "Simpan Profil"}
                </button>
              </div>
            )}

            {/* ── Pesanan (UPGRADED) ── */}
            {tab === "orders" && (
              <div>
                <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:20 }}>
                  <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:24, fontWeight:400 }}>Riwayat Pesanan</h2>
                  <button onClick={loadOrders} style={{ background:"none", border:"1px solid #e0deda", color:"#888", padding:"6px 12px", fontSize:11, cursor:"pointer", borderRadius:2 }}>
                    🔄 Refresh
                  </button>
                </div>
                {loading && <p style={{ color:"#aaa", fontSize:14 }}>Memuat...</p>}
                {!loading && orders.length === 0 && (
                  <div style={{ textAlign:"center", padding:"48px 0", color:"#bbb" }}>
                    <p style={{ fontSize:40, marginBottom:12 }}>📦</p>
                    <p style={{ fontSize:14 }}>Belum ada pesanan</p>
                    <button onClick={() => setPage("catalog")} style={{ ...btn(), marginTop:20 }}>Mulai Belanja</button>
                  </div>
                )}
                {!loading && orders.map(renderOrderCard)}
              </div>
            )}

            {/* ── Alamat ── */}
            {tab === "address" && (
              <div style={{ maxWidth:560 }}>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:24, fontWeight:400, marginBottom:8 }}>Alamat Tersimpan</h2>
                <p style={{ fontSize:13, color:"#aaa", marginBottom:24 }}>Alamat ini akan otomatis terisi saat checkout</p>
                {savedAddr && (
                  <div style={{ background:"#f9f8f6", border:"1px solid #e8e6e2", padding:"14px 18px", borderRadius:2, marginBottom:24, fontSize:13, color:"#555", lineHeight:1.8 }}>
                    <p style={{ fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#aaa", fontWeight:600, marginBottom:8 }}>Alamat Tersimpan</p>
                    {savedAddr.address}<br/>
                    {savedAddr.district && savedAddr.district + ", "}{savedAddr.city}<br/>
                    {savedAddr.province && savedAddr.province + " "}{savedAddr.postal}
                  </div>
                )}
                <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
                  <div>
                    <label style={lbl}>Alamat Jalan *</label>
                    <input style={inp} value={address.address} onChange={e => setAddress(a => ({...a, address:e.target.value}))} placeholder="Jalan, No., RT/RW" />
                  </div>
                  <AreaSearch value={address.city} district={address.district} province={address.province} postal={address.postal}
                    onChange={(city, district, province, postal, area_id) => setAddress(a => ({...a, city, district, province, postal, area_id}))} />
                  <button onClick={saveAddress} disabled={loading} style={btn()}>
                    {loading ? "Menyimpan..." : "Simpan Alamat"}
                  </button>
                </div>
              </div>
            )}

            {/* ── Password ── */}
            {tab === "password" && (
              <div style={{ display:"flex", flexDirection:"column", gap:16, maxWidth:400 }}>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:24, fontWeight:400, marginBottom:8 }}>Ganti Password</h2>
                <div>
                  <label style={lbl}>Password Lama</label>
                  <input style={inp} type="password" value={password.old} onChange={e => setPassword(p => ({...p, old:e.target.value}))} placeholder="••••••••" />
                </div>
                <div>
                  <label style={lbl}>Password Baru</label>
                  <input style={inp} type="password" value={password.new1} onChange={e => setPassword(p => ({...p, new1:e.target.value}))} placeholder="Min. 6 karakter" />
                </div>
                <div>
                  <label style={lbl}>Konfirmasi Password Baru</label>
                  <input style={inp} type="password" value={password.new2} onChange={e => setPassword(p => ({...p, new2:e.target.value}))} placeholder="••••••••" />
                </div>
                <button onClick={changePassword} disabled={loading} style={btn()}>
                  {loading ? "Menyimpan..." : "Ganti Password"}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ── Tracking Modal ──────────────────────────────────── */}
      {trackingModal && (
        <div onClick={() => setTrackingModal(null)}
          style={{ position:"fixed", inset:0, background:"rgba(0,0,0,0.5)", zIndex:9999, display:"flex", alignItems:"center", justifyContent:"center", padding:20 }}>
          <div onClick={e => e.stopPropagation()}
            style={{ background:"#fff", borderRadius:6, maxWidth:520, width:"100%", maxHeight:"85vh", overflow:"auto", boxShadow:"0 20px 50px rgba(0,0,0,0.3)" }}>
            {/* Header */}
            <div style={{ padding:"20px 24px", borderBottom:"1px solid #e8e6e2", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
              <div>
                <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.14em", textTransform:"uppercase", color:"#888", fontWeight:600 }}>
                  Lacak Paket
                </p>
                <p style={{ fontFamily:"'Cormorant Garant',serif", fontSize:22, color:"#111", marginTop:2 }}>
                  {trackingModal.order.order_number}
                </p>
              </div>
              <button onClick={() => setTrackingModal(null)}
                style={{ background:"none", border:"none", fontSize:24, cursor:"pointer", color:"#888", padding:0, lineHeight:1 }}>×</button>
            </div>

            {/* Info pengiriman */}
            <div style={{ padding:"16px 24px", background:"#fafaf8", borderBottom:"1px solid #e8e6e2", fontSize:12, color:"#555", lineHeight:1.8 }}>
              <div><strong style={{ color:"#111" }}>Kurir:</strong> {trackingModal.order.courier_name?.toUpperCase()} {trackingModal.order.courier_service?.toUpperCase()}</div>
              <div><strong style={{ color:"#111" }}>No. Resi:</strong> <span style={{ fontFamily:"monospace" }}>{trackingModal.order.waybill_id}</span></div>
            </div>

            {/* Timeline */}
            <div style={{ padding:"20px 24px" }}>
              {trackingModal.loading && <p style={{ color:"#aaa", fontSize:13 }}>Memuat tracking dari kurir...</p>}
              {!trackingModal.loading && (!trackingModal.tracking || !trackingModal.tracking.history || trackingModal.tracking.history.length === 0) && (
                <div style={{ textAlign:"center", padding:"30px 0", color:"#aaa" }}>
                  <p style={{ fontSize:36, marginBottom:8 }}>📭</p>
                  <p style={{ fontSize:13 }}>{t("No tracking history yet", "Belum ada riwayat tracking")}</p>
                  <p style={{ fontSize:11, color:"#bbb", marginTop:4 }}>{t("Try again in a few hours", "Coba lagi dalam beberapa jam")}</p>
                </div>
              )}
              {!trackingModal.loading && trackingModal.tracking?.history?.length > 0 && (
                <div style={{ position:"relative", paddingLeft:24 }}>
                  {/* Vertical line */}
                  <div style={{ position:"absolute", left:7, top:8, bottom:8, width:2, background:"#e8e6e2" }} />
                  {trackingModal.tracking.history.map((h, i) => (
                    <div key={i} style={{ marginBottom:18, position:"relative" }}>
                      <div style={{
                        position:"absolute", left:-23, top:4, width:14, height:14, borderRadius:"50%",
                        background: i === 0 ? "#10b981" : "#888",
                        border: "3px solid #fff", boxShadow:"0 0 0 2px " + (i === 0 ? "#10b981" : "#ddd")
                      }} />
                      <p style={{ fontSize:11, color:"#888", marginBottom:2 }}>
                        {h.updated_at ? fmtDT(h.updated_at) : ""}
                      </p>
                      <p style={{ fontSize:13, color:"#111", lineHeight:1.5 }}>
                        {h.note || h.status || "-"}
                      </p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

    </div>
  );
};

Object.assign(window, { AccountPage });
