// admin-overview.jsx

const fmt$ = (v) => '$' + v.toLocaleString();

const AdminKPICard = ({ label, value, sub, valueColor }) => (
  <div style={{ background: '#fff', borderRadius: 10, padding: '20px 24px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 1px 4px oklch(18% 0.06 265 / 0.04)' }}>
    <div style={{ fontSize: 11, fontWeight: 600, color: 'oklch(58% 0.03 265)', letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 8 }}>{label}</div>
    <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 30, fontWeight: 700, color: valueColor || 'oklch(14% 0.04 265)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    {sub && <div style={{ fontSize: 12, color: 'oklch(62% 0.03 265)', marginTop: 6 }}>{sub}</div>}
  </div>
);

const AdminBarChart = ({ data, labels }) => {
  const max = Math.max(...data);
  const barW = 38, gap = 10, chartH = 110;
  const totalW = data.length * (barW + gap);
  return (
    <svg width={totalW} height={chartH + 32} style={{ display: 'block', overflow: 'visible' }}>
      {data.map((val, i) => {
        const barH = max > 0 ? Math.max(4, (val / max) * chartH) : 4;
        const x = i * (barW + gap);
        const y = chartH - barH;
        const isLast = i === data.length - 1;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={barH} rx={5}
              fill={isLast ? 'oklch(72% 0.17 80)' : 'oklch(62% 0.08 265)'}
              opacity={isLast ? 1 : 0.45 + i * 0.07}
            />
            <text x={x + barW / 2} y={chartH + 18} textAnchor="middle" fontSize={11} fill="oklch(60% 0.03 265)" fontFamily="'Plus Jakarta Sans', sans-serif">{labels[i]}</text>
            <text x={x + barW / 2} y={y - 5} textAnchor="middle" fontSize={10} fill="oklch(38% 0.05 265)" fontFamily="'Plus Jakarta Sans', sans-serif" fontWeight="700">{val}</text>
          </g>
        );
      })}
    </svg>
  );
};

const PipelineBar = ({ label, count, max, cfg }) => {
  const pct = max > 0 ? (count / max) * 100 : 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
      <div style={{ width: 110, fontSize: 12, fontWeight: 600, color: 'oklch(42% 0.04 265)', textAlign: 'right', flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, background: 'oklch(94% 0.01 265)', borderRadius: 4, height: 8, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: cfg.color, borderRadius: 4, transition: 'width 0.5s ease' }} />
      </div>
      <div style={{ width: 28, fontSize: 13, fontWeight: 700, color: cfg.color, textAlign: 'right', flexShrink: 0 }}>{count}</div>
    </div>
  );
};

const AdminOverview = () => {
  const data = window.useAdminData();
  const { profiles, leads, months } = data;
  const trialsToday     = data.trialsToday || [];
  const followUpDates   = data.followUpDates || {};
  const todayStr        = new Date().toISOString().slice(0, 10);
  const overdueFollowups = leads.filter(l => followUpDates[l.id] && followUpDates[l.id] <= todayStr && !['enrolled','lost'].includes(l.status));

  if (data.loading) {
    return <div style={{ padding: 60, textAlign: 'center', color: 'oklch(55% 0.03 265)', fontSize: 14 }}>Loading overview…</div>;
  }
  if (!profiles.length && !leads.length) {
    return <div style={{ padding: 60, textAlign: 'center', color: 'oklch(55% 0.03 265)', fontSize: 14 }}>Nothing to show yet — add a lead source on the Lead Sources tab or some leads on the Leads CRM tab.</div>;
  }

  const totalLeads      = profiles.reduce((s, p) => s + p.totalLeads, 0);
  const totalInvested   = profiles.reduce((s, p) => s + p.totalInvested, 0);
  const totalRevenue    = profiles.reduce((s, p) => s + p.totalRevenue, 0);
  const totalConverted  = profiles.reduce((s, p) => s + p.studentsConverted, 0);
  const roi             = totalInvested > 0 ? ((totalRevenue - totalInvested) / totalInvested) : 0;
  const cpl             = totalLeads    > 0 ? (totalInvested / totalLeads) : 0;
  const convRate        = totalLeads    > 0 ? ((totalConverted / totalLeads) * 100) : 0;

  const monthlyTotals = months.map((_, i) => profiles.reduce((s, p) => s + (p.monthlyLeads[i] || 0), 0));

  const recentLeads = [...leads].sort((a, b) => b.dateAdded.localeCompare(a.dateAdded)).slice(0, 9);
  const profileById = Object.fromEntries(profiles.map(p => [p.id, p]));

  const statusCfg = {
    new:             { label: 'New',             color: 'oklch(55% 0.17 80)'  },
    contacted:       { label: 'Contacted',       color: 'oklch(45% 0.1 265)'  },
    trial_scheduled: { label: 'Trial Scheduled', color: 'oklch(45% 0.12 295)' },
    trial_done:      { label: 'Trial Done',      color: 'oklch(45% 0.1 200)'  },
    enrolled:        { label: 'Enrolled',        color: 'oklch(40% 0.14 150)' },
    lost:            { label: 'Lost',            color: 'oklch(50% 0.08 20)'  },
  };
  const statusOrder = ['new','contacted','trial_scheduled','trial_done','enrolled','lost'];
  const pipelineCounts = Object.fromEntries(statusOrder.map(s => [s, leads.filter(l => l.status === s).length]));
  const pipelineMax = Math.max(...Object.values(pipelineCounts));

  const topProfiles = [...profiles]
    .map(p => ({ ...p, roi: ((p.totalRevenue - p.totalInvested) / p.totalInvested) }))
    .sort((a, b) => b.roi - a.roi);

  return (
    <div>

      {/* ── Today at a Glance ── */}
      {(trialsToday.length > 0 || overdueFollowups.length > 0) && (
        <div style={{ display:'grid', gridTemplateColumns: trialsToday.length > 0 && overdueFollowups.length > 0 ? '1fr 1fr' : '1fr', gap:14, marginBottom:22 }}>
          {trialsToday.length > 0 && (
            <div style={{ background:'oklch(22% 0.06 265)', borderRadius:14, padding:'18px 22px' }}>
              <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.08em', color:'oklch(72% 0.17 80)', marginBottom:10 }}>Today's Trials</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {trialsToday.map((t,i) => (
                  <div key={i} style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                    <div>
                      <div style={{ fontSize:13, fontWeight:600, color:'#fff' }}>{t.name}</div>
                      <div style={{ fontSize:11, color:'rgba(255,255,255,0.55)' }}>{t.subject} · {t.instructor}</div>
                    </div>
                    <span style={{ fontSize:12, fontWeight:700, color:'oklch(72% 0.17 80)' }}>{t.time}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {overdueFollowups.length > 0 && (
            <div style={{ background:'oklch(96% 0.07 25)', borderRadius:14, padding:'18px 22px', border:'1px solid oklch(88% 0.09 25)' }}>
              <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.08em', color:'oklch(36% 0.1 25)', marginBottom:10 }}>Overdue Follow-ups</div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {overdueFollowups.slice(0,4).map(l => (
                  <div key={l.id} style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                    <span style={{ fontSize:13, fontWeight:600, color:'oklch(26% 0.08 25)' }}>{l.name}</span>
                    <span style={{ fontSize:11, color:'oklch(40% 0.08 25)' }}>{followUpDates[l.id]}</span>
                  </div>
                ))}
                {overdueFollowups.length > 4 && <div style={{ fontSize:11, color:'oklch(42% 0.08 25)' }}>+{overdueFollowups.length-4} more</div>}
              </div>
            </div>
          )}
        </div>
      )}

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 24 }}>
        <AdminKPICard label="Total Leads (All Time)" value={totalLeads.toLocaleString()} sub={`Across ${profiles.length} active profiles`} />
        <AdminKPICard label="Total Invested" value={fmt$(totalInvested)} sub="All platforms, 8 months" />
        <AdminKPICard label="Total Revenue Generated" value={fmt$(totalRevenue)} sub={`${totalConverted} students enrolled`} valueColor="oklch(34% 0.13 150)" />
        <AdminKPICard label="Return on Investment" value={roi.toFixed(1) + 'x'} sub="Revenue ÷ investment" valueColor="oklch(34% 0.13 150)" />
        <AdminKPICard label="Avg Cost per Lead" value={'$' + cpl.toFixed(2)} sub="All platforms combined" />
        <AdminKPICard label="Conversion Rate" value={convRate.toFixed(1) + '%'} sub="Lead → enrolled student" />
      </div>

      {/* Charts row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 20, marginBottom: 20 }}>
        {/* Monthly leads bar chart */}
        <div style={{ background: '#fff', borderRadius: 14, padding: '24px 28px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(20% 0.06 265)', marginBottom: 3 }}>Monthly Leads</div>
          <div style={{ fontSize: 12, color: 'oklch(60% 0.03 265)', marginBottom: 22 }}>All platforms combined · Oct 2025 – May 2026</div>
          <div style={{ overflowX: 'auto' }}>
            <AdminBarChart data={monthlyTotals} labels={months} />
          </div>
        </div>

        {/* Pipeline funnel */}
        <div style={{ background: '#fff', borderRadius: 14, padding: '24px 28px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(20% 0.06 265)', marginBottom: 3 }}>Current Pipeline</div>
          <div style={{ fontSize: 12, color: 'oklch(60% 0.03 265)', marginBottom: 22 }}>{leads.length} leads tracked in CRM</div>
          {statusOrder.map(s => (
            <PipelineBar key={s} label={statusCfg[s].label} count={pipelineCounts[s]} max={pipelineMax} cfg={statusCfg[s]} />
          ))}
        </div>
      </div>

      {/* Bottom row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        {/* Profile performance table */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1px solid oklch(90% 0.01 265)', overflow: 'hidden', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ padding: '20px 24px 14px', fontWeight: 700, fontSize: 15, color: 'oklch(20% 0.06 265)' }}>Profiles by ROI</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ background: 'oklch(97% 0.006 60)', borderBottom: '1px solid oklch(91% 0.01 265)' }}>
                {['Profile', 'Leads', 'Revenue', 'ROI', 'CPL'].map(h => (
                  <th key={h} style={{ padding: '9px 16px', textAlign: 'left', fontWeight: 700, fontSize: 10, color: 'oklch(52% 0.04 265)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {topProfiles.map((p, i) => (
                <tr key={p.id} style={{ borderBottom: '1px solid oklch(95% 0.005 60)' }}>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ fontWeight: 600, fontSize: 12, color: 'oklch(22% 0.06 265)' }}>{p.instructor}</div>
                    <div style={{ fontSize: 10, color: `oklch(46% 0.1 ${p.platformHue})`, fontWeight: 600 }}>{p.platform}</div>
                  </td>
                  <td style={{ padding: '11px 16px', fontWeight: 600, color: 'oklch(28% 0.05 265)' }}>{p.totalLeads}</td>
                  <td style={{ padding: '11px 16px', fontWeight: 600, color: 'oklch(34% 0.13 150)' }}>{fmt$(p.totalRevenue)}</td>
                  <td style={{ padding: '11px 16px', fontWeight: 700, color: 'oklch(34% 0.13 150)' }}>{p.roi.toFixed(1)}x</td>
                  <td style={{ padding: '11px 16px', color: 'oklch(48% 0.04 265)' }}>${(p.totalInvested / p.totalLeads).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Recent activity */}
        <div style={{ background: '#fff', borderRadius: 14, padding: '20px 24px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(20% 0.06 265)', marginBottom: 16 }}>Recent Leads</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {recentLeads.map((lead, i) => {
              const p = profileById[lead.profileId];
              const cfg = statusCfg[lead.status] || { color: '#ccc' };
              return (
                <div key={lead.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < recentLeads.length - 1 ? '1px solid oklch(94% 0.005 60)' : 'none' }}>
                  <div style={{ width: 9, height: 9, borderRadius: '50%', background: cfg.color, flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, color: 'oklch(22% 0.06 265)' }}>{lead.name}</div>
                    <div style={{ fontSize: 11, color: 'oklch(58% 0.03 265)' }}>{lead.subject} · {p?.platform}</div>
                  </div>
                  <div style={{ fontSize: 10, color: 'oklch(62% 0.03 265)', flexShrink: 0 }}>{lead.dateAdded}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AdminOverview });
