// Account dashboard

function AccountPage({ go, purchases }) {
  const [tab, setTab] = React.useState('subs');

  return (
    <section className="max-w-[1280px] mx-auto px-5 md:px-8 pt-8 md:pt-12">
      <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-8">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-full flex items-center justify-center mono font-semibold text-lg" style={{ background: 'linear-gradient(135deg, var(--accent), var(--accent-2))', color: '#0b0320' }}>
            AK
          </div>
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-1">Account</div>
            <h1 className="text-3xl font-semibold tracking-tight">@alex_k</h1>
            <div className="text-sm text-white/55 mt-1 flex items-center gap-2 flex-wrap">
              <span>Joined Oct 2024</span>
              <span className="text-white/20">·</span>
              <span>{purchases.length + 7} orders · $642.18 lifetime</span>
              <span className="chip">VIP · tier 2</span>
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <button className="btn-ghost px-4 py-2.5 text-sm inline-flex items-center gap-2">
            <Icon name="wallet" size={14} /> Wallet
          </button>
          <button className="btn-ghost px-4 py-2.5 text-sm inline-flex items-center gap-2">
            <Icon name="support" size={14} /> Support
          </button>
        </div>
      </div>

      <div className="hairline rounded-xl flex overflow-auto hide-scroll" style={{ background: 'var(--bg-1)' }}>
        {[
          { id: 'subs', label: 'Active subscriptions', count: 4 },
          { id: 'history', label: 'Purchase history', count: purchases.length + 7 },
          { id: 'tickets', label: 'Replacement tickets', count: 1 },
          { id: 'settings', label: 'Settings' },
        ].map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className="px-4 py-3 text-sm whitespace-nowrap transition-colors"
            style={{ color: tab === t.id ? 'var(--ink)' : 'var(--ink-dim)', borderBottom: `2px solid ${tab === t.id ? 'var(--accent)' : 'transparent'}` }}
          >
            {t.label}{t.count != null && <span className="ml-2 text-white/40 mono text-xs">{t.count}</span>}
          </button>
        ))}
      </div>

      <div className="mt-6">
        {tab === 'subs' && <ActiveSubs go={go} />}
        {tab === 'history' && <PurchaseHistory purchases={purchases} go={go} />}
        {tab === 'tickets' && <TicketsTab />}
        {tab === 'settings' && <SettingsTab />}
      </div>
    </section>
  );
}

function ActiveSubs({ go }) {
  const subs = [
    { id: 's1', product: PRODUCTS.find(p => p.id === 'stream-plus'), variant: '6 Months · Private', expires: 142, total: 180, orderId: 'DS-X7KQ-9M2P' },
    { id: 's2', product: PRODUCTS.find(p => p.id === 'music-pro'), variant: 'Family · 12mo', expires: 287, total: 365, orderId: 'DS-B3RT-7K9N' },
    { id: 's3', product: PRODUCTS.find(p => p.id === 'chat-nitro'), variant: 'Full · 1 Year', expires: 58, total: 365, orderId: 'DS-P4CQ-2H8L' },
    { id: 's4', product: PRODUCTS.find(p => p.id === 'vpn-pro'), variant: '24 Months', expires: 612, total: 730, orderId: 'DS-MN3X-5V7W' },
  ];
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {subs.map(s => {
        const p = s.product;
        const pct = Math.round((s.expires / s.total) * 100);
        const urgent = s.expires < 60;
        return (
          <div key={s.id} className="glass rounded-2xl p-5">
            <div className="flex items-start gap-4">
              <ProductThumb product={p} size={56} rounded="rounded-lg" glyphClass="text-2xl" />
              <div className="flex-1 min-w-0">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="font-medium">{p.name}</div>
                    <div className="text-xs text-white/55 truncate">{s.variant}</div>
                  </div>
                  {urgent ? <Badge tone="warn">renew soon</Badge> : <Badge tone="ok">active</Badge>}
                </div>
                <div className="mt-3 text-xs mono text-white/50 flex items-center justify-between">
                  <span>{s.expires} days left</span>
                  <span>{s.orderId}</span>
                </div>
                <div className="mt-2 h-1.5 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.06)' }}>
                  <div className="h-full rating-bar" style={{ width: `${pct}%`, background: urgent ? 'linear-gradient(90deg, var(--warn), #ff9645)' : 'linear-gradient(90deg, var(--accent), var(--accent-2))' }} />
                </div>
              </div>
            </div>
            <div className="mt-4 flex gap-2">
              <button onClick={() => go('product', { productId: p.id })} className="flex-1 btn-ghost py-2 text-xs inline-flex items-center justify-center gap-1.5">
                <Icon name="refresh" size={12} /> Re-order
              </button>
              <button className="flex-1 btn-ghost py-2 text-xs inline-flex items-center justify-center gap-1.5">
                <Icon name="support" size={12} /> Replacement
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PurchaseHistory({ purchases, go }) {
  const base = [
    { id: 'DS-H4KN-M2L9', product: PRODUCTS[0], variant: '3 Months · Shared', paid: 9.49, crypto: 'LTC', when: '2d ago', status: 'delivered' },
    { id: 'DS-Q3X8-R7V2', product: PRODUCTS[1], variant: 'Family · 12mo', paid: 52.99, crypto: 'USDT', when: '18d ago', status: 'delivered' },
    { id: 'DS-B7MN-K4T3', product: PRODUCTS[5], variant: '2× Boosts · 1 Month', paid: 7.49, crypto: 'SOL', when: '1mo ago', status: 'delivered' },
    { id: 'DS-L8RP-W2Z6', product: PRODUCTS[8], variant: '12 Months', paid: 21.99, crypto: 'BTC', when: '2mo ago', status: 'delivered' },
    { id: 'DS-N5JK-P3Q7', product: PRODUCTS[2], variant: 'Full · 1 Year', paid: 44.99, crypto: 'ETH', when: '3mo ago', status: 'delivered' },
    { id: 'DS-T2VX-C6Y9', product: PRODUCTS[6], variant: '1 Month Code', paid: 6.99, crypto: 'USDT', when: '4mo ago', status: 'replaced' },
  ];
  const list = [...purchases, ...base];
  return (
    <div className="hairline rounded-2xl overflow-hidden" style={{ background: 'var(--bg-1)' }}>
      <div className="grid grid-cols-[auto_1fr_auto_auto_auto] gap-4 px-5 py-3 text-[10px] mono uppercase tracking-widest text-white/40 border-b" style={{ borderColor: 'var(--line)' }}>
        <span>Order</span>
        <span>Product</span>
        <span className="hidden md:block">Paid</span>
        <span>When</span>
        <span>Status</span>
      </div>
      {list.map((o, i) => (
        <div key={i} className="grid grid-cols-[auto_1fr_auto_auto_auto] gap-4 px-5 py-4 items-center border-t hover:bg-white/[0.02] transition-colors" style={{ borderColor: 'var(--line)' }}>
          <span className="mono text-xs text-white/50">{o.id}</span>
          <div className="flex items-center gap-3 min-w-0">
            <ProductThumb product={o.product} size={36} rounded="rounded-md" glyphClass="text-sm" />
            <div className="min-w-0">
              <div className="text-sm font-medium truncate">{o.product.name}</div>
              <div className="text-xs text-white/50 truncate">{o.variant}</div>
            </div>
          </div>
          <div className="hidden md:block text-right">
            <div className="text-sm font-medium mono">{formatUSD(o.paid)}</div>
            <div className="text-[10px] mono text-white/40">{o.crypto}</div>
          </div>
          <span className="text-xs mono text-white/50">{o.when}</span>
          <Badge tone={o.status === 'delivered' ? 'ok' : 'warn'}>{o.status}</Badge>
        </div>
      ))}
    </div>
  );
}

function TicketsTab() {
  return (
    <div className="hairline rounded-2xl p-5" style={{ background: 'var(--bg-1)' }}>
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <Badge tone="accent">in progress</Badge>
            <span className="text-[11px] mono uppercase tracking-widest text-white/40">Ticket TC-4821</span>
          </div>
          <div className="mt-2 font-medium">Replacement requested · MusicPro · Family 12mo</div>
          <div className="text-xs text-white/55 mt-1">Opened 42 minutes ago · Auto-fulfillment in progress</div>
        </div>
        <button className="btn-ghost px-3 py-2 text-xs">View thread</button>
      </div>
      <div className="mt-4 space-y-2">
        {[
          { t: '[T+00:00]', m: 'Ticket opened: "family plan downgraded overnight"', who: 'you' },
          { t: '[T+00:01]', m: 'Auto-triage: flagged for replacement · priority normal', who: 'bot' },
          { t: '[T+00:12]', m: 'Validation passed · pulling fresh credentials from vault', who: 'bot' },
          { t: '[T+00:38]', m: 'Replacement issued · credentials sent to your endpoint', who: 'bot' },
        ].map((l, i) => (
          <div key={i} className="mono text-xs flex gap-3">
            <span className="text-white/30">{l.t}</span>
            <span className="text-white/40 w-8">{l.who}</span>
            <span className="text-white/75">{l.m}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsTab() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div className="glass rounded-2xl p-5">
        <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Delivery endpoint</div>
        <div className="text-sm mb-3">Where automated deliveries are dispatched. Encrypted end-to-end.</div>
        <div className="hairline rounded-lg px-3 py-2 mono text-xs flex items-center justify-between">
          <span>alex.k.7421@anon.mail.example</span>
          <button className="text-white/50 hover:text-white">change</button>
        </div>
      </div>
      <div className="glass rounded-2xl p-5">
        <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Default payout</div>
        <div className="text-sm mb-3">Refunds for pre-delivery cancellations go here.</div>
        <div className="hairline rounded-lg px-3 py-2 mono text-xs">
          LTC · ltc1qr8j2mxs6k9v4ze0xhw3nr7fu2ql5jk0d3n9atp
        </div>
      </div>
      <div className="glass rounded-2xl p-5 md:col-span-2">
        <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Privacy</div>
        <div className="space-y-3">
          {[
            { t: 'Delete order history on delivery', s: 'Orders are purged 24h after successful delivery. You still have warranty coverage.' },
            { t: 'Require confirmation before auto-reorder', s: 'We pause scheduled re-orders until you confirm in-app.' },
            { t: 'Show live order feed on homepage', s: 'You\'ll appear as @anonymous when enabled.' },
          ].map((x, i) => (
            <div key={i} className="flex items-start justify-between gap-4 hairline rounded-lg p-3">
              <div>
                <div className="text-sm font-medium">{x.t}</div>
                <div className="text-xs text-white/55 mt-0.5 max-w-lg">{x.s}</div>
              </div>
              <span className="relative w-9 h-5 rounded-full mt-1" style={{ background: i === 0 ? 'var(--accent)' : 'rgba(255,255,255,0.1)' }}>
                <span className="absolute top-0.5 w-4 h-4 rounded-full bg-white transition-all" style={{ left: i === 0 ? '18px' : '2px' }} />
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AccountPage });
