// admin-analytics.jsx

const fmtK  = v => v >= 1000 ? '$' + (v / 1000).toFixed(0) + 'K' : '$' + v;
const fmtDol = v => '$' + Number(v).toLocaleString();

// ── KPI Card ─────────────────────────────────────────────────────────────────
const AKPICard = ({ label, value, sub, color, trendVal }) => (
  <div style={{ background: '#fff', borderRadius: 10, padding: '20px 22px', 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: color || 'oklch(14% 0.04 265)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 7 }}>
      {trendVal != null && (
        <span style={{ fontSize: 11, fontWeight: 700, color: trendVal >= 0 ? 'oklch(32% 0.14 150)' : 'oklch(42% 0.1 25)', background: trendVal >= 0 ? 'oklch(92% 0.1 150)' : 'oklch(94% 0.08 25)', padding: '2px 7px', borderRadius: 20 }}>
          {trendVal >= 0 ? '↑' : '↓'} {Math.abs(trendVal)}%
        </span>
      )}
      {sub && <div style={{ fontSize: 12, color: 'oklch(60% 0.03 265)' }}>{sub}</div>}
    </div>
  </div>
);

// ── Line / Area Chart ─────────────────────────────────────────────────────────
const LineAreaChart = ({ data, labels, color = 'oklch(38% 0.12 265)' }) => {
  const W = 500, H = 100;
  const pad = { t: 12, r: 16, b: 28, l: 32 };
  const cW = W - pad.l - pad.r, cH = H - pad.t - pad.b;
  const max = Math.max(...data), min = Math.min(...data);
  const rng = max - min || 1;
  const px = i => pad.l + (i / (data.length - 1)) * cW;
  const py = v => pad.t + cH - ((v - min) / rng) * cH;
  const pts = data.map((v, i) => `${px(i)},${py(v)}`).join(' ');
  const area = `M${px(0)},${py(data[0])} ${data.map((v, i) => `L${px(i)},${py(v)}`).join(' ')} L${px(data.length - 1)},${H - pad.b} L${px(0)},${H - pad.b} Z`;
  const yVals = [min, Math.round((min + max) / 2), max];
  return (
    <svg viewBox={`0 0 ${W} ${H + pad.b}`} width="100%" style={{ display: 'block', overflow: 'visible' }}>
      {yVals.map((v, i) => (
        <g key={i}>
          <line x1={pad.l} y1={py(v)} x2={W - pad.r} y2={py(v)} stroke="oklch(92% 0.01 265)" strokeWidth="1" />
          <text x={pad.l - 4} y={py(v) + 4} textAnchor="end" fontSize={9} fill="oklch(62% 0.03 265)" fontFamily="'Plus Jakarta Sans', sans-serif">{v}</text>
        </g>
      ))}
      <path d={area} fill={color} opacity="0.09" />
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round" />
      {data.map((v, i) => <circle key={i} cx={px(i)} cy={py(v)} r={3} fill={color} stroke="#fff" strokeWidth="1.5" />)}
      {labels.map((l, i) => (
        <text key={i} x={px(i)} y={H + pad.b - 2} textAnchor="middle" fontSize={9} fill="oklch(62% 0.03 265)" fontFamily="'Plus Jakarta Sans', sans-serif">{l}</text>
      ))}
    </svg>
  );
};

// ── Horizontal Bar ────────────────────────────────────────────────────────────
const HorizBar = ({ label, value, maxVal, display, secondary, hue = 265, idx = 0 }) => {
  const pct = Math.max(2, (value / maxVal) * 100);
  const lum = 52 - idx * 4;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ width: 88, fontSize: 12, fontWeight: 600, color: 'oklch(40% 0.04 265)', textAlign: 'right', flexShrink: 0, lineHeight: 1.2 }}>{label}</div>
      <div style={{ flex: 1, height: 26, background: 'oklch(95% 0.01 265)', borderRadius: 5, overflow: 'hidden', position: 'relative' }}>
        <div style={{ width: pct + '%', height: '100%', background: `oklch(${lum}% 0.13 ${hue - idx * 18})`, borderRadius: 5 }} />
        {pct > 22 && (
          <span style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', fontSize: 10, fontWeight: 700, color: '#fff' }}>{secondary}</span>
        )}
      </div>
      <div style={{ width: 58, fontSize: 12, fontWeight: 700, color: 'oklch(28% 0.06 265)', textAlign: 'right', flexShrink: 0 }}>{display}</div>
    </div>
  );
};

// ── Platform Comparison Table ─────────────────────────────────────────────────
const PlatformTable = ({ profiles }) => {
  const [sortBy, setSortBy] = React.useState('roi');
  const rows = profiles.map(p => ({
    ...p,
    cpl:      (p.totalInvested / p.totalLeads).toFixed(2),
    convRate: ((p.studentsConverted / p.totalLeads) * 100).toFixed(1),
    roi:      ((p.totalRevenue - p.totalInvested) / p.totalInvested).toFixed(1),
    cps:      Math.round(p.totalInvested / Math.max(1, p.studentsConverted)),
  }));
  const sorted = [...rows].sort((a, b) => parseFloat(b[sortBy]) - parseFloat(a[sortBy]));
  const cols = [
    { key: 'platform',      label: 'Platform'       },
    { key: 'totalLeads',    label: 'Leads'          },
    { key: 'cpl',           label: 'Cost / Lead'    },
    { key: 'convRate',      label: 'Conv. Rate'     },
    { key: 'cps',           label: 'Cost / Student' },
    { key: 'avgStudentLTV', label: 'Student LTV'    },
    { key: 'totalRevenue',  label: 'Revenue'        },
    { key: 'roi',           label: 'ROI'            },
  ];
  return (
    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
      <thead>
        <tr style={{ background: 'oklch(97.5% 0.006 60)', borderBottom: '2px solid oklch(91% 0.01 265)' }}>
          {cols.map(c => (
            <th key={c.key} onClick={() => setSortBy(c.key)} style={{ padding: '10px 14px', textAlign: 'left', fontWeight: 700, fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer', userSelect: 'none', color: sortBy === c.key ? 'oklch(34% 0.1 265)' : 'oklch(52% 0.04 265)', background: sortBy === c.key ? 'oklch(94% 0.03 265)' : 'transparent', whiteSpace: 'nowrap' }}>
              {c.label} {sortBy === c.key ? '↓' : ''}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sorted.map((p, i) => {
          const roiNum = parseFloat(p.roi);
          const roiColor = roiNum >= 15 ? 'oklch(30% 0.14 150)' : roiNum >= 8 ? 'oklch(42% 0.14 75)' : 'oklch(44% 0.1 25)';
          const convNum = parseFloat(p.convRate);
          return (
            <tr key={p.id} style={{ borderBottom: '1px solid oklch(95% 0.005 60)', background: i % 2 === 0 ? '#fff' : 'oklch(99% 0.003 265)' }}>
              <td style={{ padding: '11px 14px' }}>
                <div style={{ fontWeight: 700, fontSize: 12, color: `oklch(36% 0.1 ${p.platformHue})` }}>{p.platform}</div>
                <div style={{ fontSize: 10, color: 'oklch(58% 0.03 265)' }}>{p.instructor} · {p.subject}</div>
              </td>
              <td style={{ padding: '11px 14px', fontWeight: 600 }}>{p.totalLeads}</td>
              <td style={{ padding: '11px 14px', color: 'oklch(40% 0.04 265)' }}>${p.cpl}</td>
              <td style={{ padding: '11px 14px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 52, height: 5, background: 'oklch(92% 0.01 265)', borderRadius: 3, overflow: 'hidden', flexShrink: 0 }}>
                    <div style={{ width: Math.min(100, convNum * 3) + '%', height: '100%', background: 'oklch(42% 0.12 150)', borderRadius: 3 }} />
                  </div>
                  <span style={{ fontWeight: 700, color: 'oklch(34% 0.12 150)' }}>{p.convRate}%</span>
                </div>
              </td>
              <td style={{ padding: '11px 14px', color: 'oklch(44% 0.04 265)' }}>${p.cps}</td>
              <td style={{ padding: '11px 14px', fontWeight: 600, color: 'oklch(32% 0.13 150)' }}>{fmtDol(p.avgStudentLTV || 0)}</td>
              <td style={{ padding: '11px 14px', fontWeight: 600, color: 'oklch(30% 0.13 150)' }}>{fmtDol(p.totalRevenue || 0)}</td>
              <td style={{ padding: '11px 14px' }}>
                <span style={{ fontWeight: 700, fontSize: 14, color: roiColor }}>{p.roi}x</span>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

// ── Funnel Chart ──────────────────────────────────────────────────────────────
const FunnelChart = ({ steps }) => {
  const max = steps[0].value;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {steps.map((s, i) => {
        const pct = (s.value / max) * 100;
        const indent = ((100 - pct) / 2);
        return (
          <div key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'oklch(42% 0.04 265)', width: 110, textAlign: 'right', flexShrink: 0 }}>{s.label}</div>
              <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
                <div style={{ width: pct + '%', height: 28, background: `oklch(${58 - i * 5}% 0.1 ${265 - i * 20})`, borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'width 0.5s ease' }}>
                  <span style={{ fontSize: 11, fontWeight: 700, color: '#fff' }}>{s.value}</span>
                </div>
              </div>
              <div style={{ width: 40, fontSize: 11, color: 'oklch(55% 0.03 265)', flexShrink: 0 }}>
                {i === 0 ? '100%' : Math.round((s.value / max) * 100) + '%'}
              </div>
            </div>
            {i < steps.length - 1 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 110, flexShrink: 0 }} />
                <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
                  <div style={{ fontSize: 10, color: 'oklch(62% 0.03 265)' }}>
                    → {Math.round((steps[i + 1].value / s.value) * 100)}% proceed
                  </div>
                </div>
                <div style={{ width: 40, flexShrink: 0 }} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
};

// ── Main Component ────────────────────────────────────────────────────────────
const AdminAnalytics = () => {
  const data = window.useAdminData();
  const { profiles, leads, months, weeks, weeklyLeads, revenueBySubject, monthlyLeadTarget, monthlyRevenueTarget } = data;

  if (data.loading) {
    return <div style={{ padding: 60, textAlign: 'center', color: 'oklch(55% 0.03 265)', fontSize: 14 }}>Loading analytics…</div>;
  }
  if (!profiles.length) {
    return <div style={{ padding: 60, textAlign: 'center', color: 'oklch(55% 0.03 265)', fontSize: 14 }}>No platform profiles yet — add some on the Lead Sources tab to see analytics.</div>;
  }

  // Aggregated metrics
  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 totalEnrolled = profiles.reduce((s, p) => s + p.studentsConverted, 0);
  const avgCPL        = totalInvested / totalLeads;

  const monthlyTotals   = months.map((_, i) => profiles.reduce((s, p) => s + (p.monthlyLeads[i] || 0), 0));
  const thisMonthLeads  = monthlyTotals[monthlyTotals.length - 1];
  const lastMonthLeads  = monthlyTotals[monthlyTotals.length - 2];
  const leadTrend       = Math.round(((thisMonthLeads - lastMonthLeads) / Math.max(1, lastMonthLeads)) * 100);

  // Weekly trend
  const thisWeek = weeklyLeads ? weeklyLeads[weeklyLeads.length - 1] : 0;
  const lastWeek = weeklyLeads ? weeklyLeads[weeklyLeads.length - 2] : 0;
  const weekTrend = Math.round(((thisWeek - lastWeek) / Math.max(1, lastWeek)) * 100);

  // Best / worst profile
  const withROI = profiles.map(p => ({ ...p, roi: (p.totalRevenue - p.totalInvested) / p.totalInvested }));
  const bestP   = [...withROI].sort((a, b) => b.roi - a.roi)[0];
  const lowestConv = [...profiles].sort((a, b) => (a.studentsConverted / a.totalLeads) - (b.studentsConverted / b.totalLeads))[0];
  const lowestCPL  = [...profiles].sort((a, b) => (a.totalInvested / a.totalLeads) - (b.totalInvested / b.totalLeads))[0];

  // Pipeline funnel
  const statusCounts = s => leads.filter(l => l.status === s).length;
  const funnelSteps = [
    { label: 'Total Leads',      value: leads.length },
    { label: 'Contacted',        value: statusCounts('contacted') + statusCounts('trial_scheduled') + statusCounts('trial_done') + statusCounts('enrolled') },
    { label: 'Trial Scheduled',  value: statusCounts('trial_scheduled') + statusCounts('trial_done') + statusCounts('enrolled') },
    { label: 'Trial Completed',  value: statusCounts('trial_done') + statusCounts('enrolled') },
    { label: 'Enrolled',         value: statusCounts('enrolled') },
  ];

  // Revenue by subject bar chart
  const maxRev = revenueBySubject ? Math.max(...revenueBySubject.map(s => s.revenue)) : 1;

  return (
    <div>
      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        <AKPICard label="Leads This Month"    value={thisMonthLeads} trendVal={leadTrend} sub={`Target: ${monthlyLeadTarget}`} />
        <AKPICard label="Leads This Week"     value={thisWeek} trendVal={weekTrend} sub="vs. prior week" />
        <AKPICard label="Avg Cost per Lead"   value={'$' + avgCPL.toFixed(2)} sub="All platforms combined" />
        <AKPICard label="Best ROI Platform"   value={bestP.roi.toFixed(1) + 'x'} color="oklch(30% 0.14 150)" sub={bestP.platform + ' · ' + bestP.instructor} />
      </div>

      {/* Charts: weekly trend + revenue by subject */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 20, marginBottom: 20 }}>
        <div style={{ background: '#fff', borderRadius: 14, padding: '22px 26px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'oklch(20% 0.06 265)', marginBottom: 2 }}>Weekly Lead Velocity</div>
          <div style={{ fontSize: 11, color: 'oklch(60% 0.03 265)', marginBottom: 18 }}>All platforms · last 8 weeks</div>
          {weeklyLeads && weeks && <LineAreaChart data={weeklyLeads} labels={weeks} color="oklch(38% 0.12 265)" />}
        </div>
        <div style={{ background: '#fff', borderRadius: 14, padding: '22px 26px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'oklch(20% 0.06 265)', marginBottom: 2 }}>Revenue by Subject</div>
          <div style={{ fontSize: 11, color: 'oklch(60% 0.03 265)', marginBottom: 18 }}>All-time enrolled revenue</div>
          {revenueBySubject && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {revenueBySubject.map((s, i) => (
                <HorizBar key={s.subject} label={s.subject} value={s.revenue} maxVal={maxRev}
                  display={'$' + (s.revenue / 1000).toFixed(0) + 'K'} secondary={s.enrolled + ' enrolled'} idx={i} />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Platform table + Funnel */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 1fr', gap: 20, marginBottom: 20 }}>
        <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: '18px 22px 12px' }}>
            <div style={{ fontWeight: 700, fontSize: 14, color: 'oklch(20% 0.06 265)', marginBottom: 2 }}>Platform Deep Dive</div>
            <div style={{ fontSize: 11, color: 'oklch(60% 0.03 265)' }}>Click any column header to sort</div>
          </div>
          <PlatformTable profiles={profiles} />
        </div>
        <div style={{ background: '#fff', borderRadius: 14, padding: '22px 26px', border: '1px solid oklch(90% 0.01 265)', boxShadow: '0 2px 10px oklch(18% 0.06 265 / 0.05)' }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'oklch(20% 0.06 265)', marginBottom: 2 }}>Conversion Funnel</div>
          <div style={{ fontSize: 11, color: 'oklch(60% 0.03 265)', marginBottom: 20 }}>All leads · all platforms</div>
          <FunnelChart steps={funnelSteps} />
          <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid oklch(93% 0.01 265)', display: 'flex', justifyContent: 'space-between' }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: 'oklch(30% 0.13 150)' }}>{((totalEnrolled / totalLeads) * 100).toFixed(1)}%</div>
              <div style={{ fontSize: 10, color: 'oklch(58% 0.03 265)' }}>Lead → Enrolled</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: 'oklch(34% 0.12 265)' }}>${Math.round(totalInvested / totalEnrolled)}</div>
              <div style={{ fontSize: 10, color: 'oklch(58% 0.03 265)' }}>Cost / Enrolled</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: 'oklch(34% 0.13 150)' }}>{((totalRevenue - totalInvested) / totalInvested).toFixed(1)}x</div>
              <div style={{ fontSize: 10, color: 'oklch(58% 0.03 265)' }}>Blended ROI</div>
            </div>
          </div>
        </div>
      </div>

      {/* Insight cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <div style={{ background: '#fff', borderRadius: 10, padding: '18px 22px', border: '1px solid oklch(90% 0.01 265)', borderLeft: '3px solid oklch(42% 0.14 150)', boxShadow: '0 1px 4px oklch(18% 0.06 265 / 0.04)' }}>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(34% 0.13 150)', marginBottom: 8 }}>Top Performer</div>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(18% 0.03 265)', marginBottom: 4 }}>{bestP.platform} — {bestP.instructor}</div>
          <div style={{ fontSize: 12, color: 'oklch(50% 0.03 265)', lineHeight: 1.6 }}>
            {bestP.roi.toFixed(1)}x ROI · {fmtDol(bestP.totalRevenue)} revenue · {bestP.studentsConverted} students enrolled
          </div>
        </div>
        <div style={{ background: '#fff', borderRadius: 10, padding: '18px 22px', border: '1px solid oklch(90% 0.01 265)', borderLeft: '3px solid oklch(52% 0.13 75)', boxShadow: '0 1px 4px oklch(18% 0.06 265 / 0.04)' }}>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(40% 0.12 75)', marginBottom: 8 }}>Scale Opportunity</div>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(18% 0.03 265)', marginBottom: 4 }}>Lowest CPL: {lowestCPL.platform}</div>
          <div style={{ fontSize: 12, color: 'oklch(50% 0.03 265)', lineHeight: 1.6 }}>
            Only ${(lowestCPL.totalInvested / lowestCPL.totalLeads).toFixed(2)}/lead. Increasing budget here will yield the cheapest new leads.
          </div>
        </div>
        <div style={{ background: '#fff', borderRadius: 10, padding: '18px 22px', border: '1px solid oklch(90% 0.01 265)', borderLeft: '3px solid oklch(52% 0.12 25)', boxShadow: '0 1px 4px oklch(18% 0.06 265 / 0.04)' }}>
          <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(44% 0.1 25)', marginBottom: 8 }}>Needs Attention</div>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'oklch(18% 0.03 265)', marginBottom: 4 }}>Low Conv.: {lowestConv.platform}</div>
          <div style={{ fontSize: 12, color: 'oklch(50% 0.03 265)', lineHeight: 1.6 }}>
            Only {((lowestConv.studentsConverted / lowestConv.totalLeads) * 100).toFixed(1)}% conversion on {lowestConv.instructor}'s profile. Review follow-up script.
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AdminAnalytics });
