// admin-dashboard.jsx
const Icon = window.Icon;

function MetricCard({ label, value, sub, up, delta }) {
  return (
    <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, padding:'18px 20px' }}>
      <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em', marginBottom:10 }}>{label}</div>
      <div style={{ fontSize:26, fontWeight:900, color:'#1A2B3B', letterSpacing:'-0.02em', lineHeight:1 }}>{value}</div>
      {sub && <div style={{ fontSize:11, color:'#9CA3AF', marginTop:4 }}>{sub}</div>}
      {delta && (
        <div style={{ display:'flex', alignItems:'center', gap:3, marginTop:8, fontSize:11, fontWeight:700, color: up ? '#10B981' : '#F43F5E' }}>
          <Icon name={up ? 'ArrowUpRight' : 'ArrowDownRight'} size={12} color={up ? '#10B981' : '#F43F5E'} />
          {delta}
        </div>
      )}
    </div>
  );
}

function DashboardPage() {
  const { metrics, revenue_chart, plans_breakdown, users } = window.MOCK;
  const fmt = n => '$' + n.toLocaleString();
  const topCost = [...users].sort((a,b) => b.api_cost - a.api_cost).slice(0,5);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>

      {/* Revenue row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }} className="g4">
        <MetricCard label="MRR"        value={fmt(metrics.mrr)}       sub="Monthly recurring"           up delta="+12% vs last mo" />
        <MetricCard label="ARR"        value={fmt(metrics.arr)}       sub="Annual run rate"              up delta="On track" />
        <MetricCard label="Net Profit" value={fmt(metrics.netProfit)} sub={`${metrics.grossMargin}% margin`} up delta="+8% vs last mo" />
        <MetricCard label="Total Costs" value={fmt(metrics.totalCosts)} sub={`$${metrics.costPerPaidUser}/paid user`} up={false} delta="+$18 vs last mo" />
      </div>

      {/* Ops row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }} className="g4">
        <MetricCard label="Paid Users"     value={metrics.paidUsers}      sub="Active subscriptions" />
        <MetricCard label="On Trial"       value={metrics.trialUsers}     sub="Free trial users" up delta={`+${metrics.newLast30d} this mo`} />
        <MetricCard label="Trial → Paid"   value={`${metrics.trialToPaid}%`} sub="Conversion rate" up delta="+4pp this month" />
        <MetricCard label="Leads This Mo"  value={metrics.totalLeadsThisMo.toLocaleString()} sub="Across all funnels" up delta="+22% vs last mo" />
      </div>

      {/* Charts row */}
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:12 }} className="g2">
        {/* Revenue chart */}
        <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, padding:20 }}>
          <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:16 }}>
            <div>
              <div style={{ fontSize:13, fontWeight:700, color:'#1A2B3B' }}>Revenue vs Costs</div>
              <div style={{ fontSize:11, color:'#9CA3AF', marginTop:2 }}>Last 6 months</div>
            </div>
            <div style={{ display:'flex', gap:12, fontSize:10, fontWeight:700 }}>
              <span style={{ display:'flex', alignItems:'center', gap:4, color:'#9CA3AF' }}>
                <span style={{ width:8, height:8, borderRadius:2, background:'#FFF7ED', border:'1.5px solid #F97316', display:'inline-block' }}/>MRR
              </span>
              <span style={{ display:'flex', alignItems:'center', gap:4, color:'#9CA3AF' }}>
                <span style={{ width:8, height:8, borderRadius:2, background:'#F97316', display:'inline-block' }}/>Costs
              </span>
            </div>
          </div>
          <BarChart data={revenue_chart} height={100} />
          <div style={{ display:'flex', marginTop:6 }}>
            {revenue_chart.map((d,i) => (
              <div key={i} style={{ flex:1, textAlign:'center', fontSize:10, fontWeight:700, color:'#1A2B3B' }}>
                ${(d.mrr/1000).toFixed(1)}k
              </div>
            ))}
          </div>
        </div>

        {/* Plan mix */}
        <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, padding:20 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'#1A2B3B', marginBottom:16 }}>Plan Mix</div>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {plans_breakdown.map(p => (
              <div key={p.key}>
                <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5, fontSize:12 }}>
                  <span style={{ fontWeight:600, color:'#1A2B3B' }}>{p.name}</span>
                  <span style={{ fontWeight:700, color:'#6B7280' }}>{p.users} users</span>
                </div>
                <div style={{ height:5, borderRadius:3, background:'#F3F4F6', overflow:'hidden' }}>
                  <div style={{ height:'100%', width:`${(p.users/metrics.totalUsers)*100}%`, background:p.color, borderRadius:3, transition:'width 1s ease' }}/>
                </div>
                {p.price > 0 && <div style={{ fontSize:10, color:'#9CA3AF', marginTop:3 }}>${(p.users*p.price).toLocaleString()}/mo</div>}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Credit usage + top cost users */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }} className="g2">

        {/* Credit consumption summary */}
        <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, padding:20 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'#1A2B3B', marginBottom:14 }}>Credit Consumption — This Month</div>
          {plans_breakdown.filter(p=>p.price>0).map((p,i,arr) => {
            const planUsers = users.filter(u=>u.plan===p.key);
            const used = planUsers.reduce((s,u)=>s+u.credits_used, 0);
            const cfg = window.MOCK.plan_cfg[p.key];
            const total = cfg.credits * planUsers.length;
            const pct = total > 0 ? Math.min(100, Math.round((used/total)*100)) : 0;
            return (
              <div key={p.key} style={{ marginBottom: i<arr.length-1?14:0 }}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:12, marginBottom:5 }}>
                  <span style={{ fontWeight:600, color:'#1A2B3B' }}>{p.name} <span style={{ color:'#9CA3AF', fontWeight:400 }}>({planUsers.length} users)</span></span>
                  <span style={{ fontWeight:700, color:'#6B7280' }}>{used.toLocaleString()} / {total.toLocaleString()}</span>
                </div>
                <div style={{ height:5, borderRadius:3, background:'#F3F4F6', overflow:'hidden' }}>
                  <div style={{ height:'100%', width:`${pct}%`, background: pct>85?'#F43F5E':p.color, borderRadius:3, transition:'width 1s ease' }}/>
                </div>
                <div style={{ fontSize:10, color:'#9CA3AF', marginTop:2 }}>{pct}% consumed · $0.02/credit top-up</div>
              </div>
            );
          })}
        </div>

        {/* Top users by API cost */}
        <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, padding:20 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'#1A2B3B', marginBottom:14 }}>Highest API Cost — Top 5</div>
          {topCost.map((u,i) => (
            <div key={u.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'9px 0', borderBottom:i<4?'1px solid #F3F4F6':'none' }}>
              <span style={{ fontSize:11, fontWeight:700, color:'#D1D5DB', width:16, textAlign:'center' }}>{i+1}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'#1A2B3B', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{u.name}</div>
                <div style={{ fontSize:11, color:'#9CA3AF' }}>{u.credits_used.toLocaleString()} credits used</div>
              </div>
              <PlanBadge plan={u.plan} />
              <span style={{ fontSize:13, fontWeight:700, color:'#F43F5E', minWidth:52, textAlign:'right' }}>${u.api_cost.toFixed(2)}</span>
              <span style={{ fontSize:11, color: u.mrr>0 ? '#10B981' : '#9CA3AF', minWidth:52, textAlign:'right' }}>
                {u.mrr > 0 ? `${((1-(u.api_cost/u.mrr))*100).toFixed(0)}% mgn` : 'no rev'}
              </span>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

Object.assign(window, { DashboardPage });
