// screen-analytics.jsx — Analytics: SVG charts, KPIs, push performance table
// Exports: AnalyticsScreen

const DATA_NOUR = {
  months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
  installs: [120, 180, 340, 520, 890, 1240],
  sessions: [240, 390, 680, 1040, 1780, 2480],
  revenue: [0, 3200, 5800, 8400, 10900, 12400],
  conversion: [0, 1.8, 2.4, 2.9, 3.1, 3.2],
  pushCampaigns: [
    { name: 'Summer Flash Sale', sent: 1240, opens: 228, conversions: 44, revenue: 'EGP 4,380', rate: '18.4%' },
    { name: 'Cart abandon · 1h', sent: 312, opens: 69, conversions: 18, revenue: 'EGP 1,840', rate: '22.1%' },
    { name: 'New arrivals tease', sent: 980, opens: 141, conversions: 22, revenue: 'EGP 1,240', rate: '14.4%' },
    { name: 'Order shipped', sent: 88, opens: 36, conversions: null, revenue: '—', rate: '41.2%' },
  ],
  funnel: [1240, 820, 340, 118, 44],
  funnelLabels: ['Installs', 'Sessions', 'Product views', 'Add to cart', 'Purchases'],
};

const DATA_MARCUS = {
  months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
  installs: [420, 680, 1020, 1850, 2940, 3847],
  sessions: [840, 1360, 2040, 3700, 5880, 7694],
  revenue: [0, 4200, 9800, 16500, 22100, 28900],
  conversion: [0, 2.2, 3.1, 3.8, 4.5, 4.8],
  pushCampaigns: [
    { name: 'Studio Speaker launch', sent: 3847, opens: 485, conversions: 112, revenue: '$14,200', rate: '12.6%' },
    { name: 'Weekend deal — earbuds', sent: 1920, opens: 188, conversions: 74, revenue: '$6,400', rate: '9.8%' },
    { name: 'Cart abandon · 1h', sent: 624, opens: 152, conversions: 38, revenue: '$3,100', rate: '24.3%' },
    { name: 'Back-in-stock alert', sent: 218, opens: 83, conversions: 29, revenue: '$2,900', rate: '38.1%' },
  ],
  funnel: [3847, 2890, 1540, 680, 185],
  funnelLabels: ['Installs', 'Sessions', 'Product views', 'Add to cart', 'Purchases'],
};

// Generic SVG line chart
const LineChart = ({ data, months, color = 'var(--ink)', label, format, height = 160 }) => {
  const W = 520, H = height, PL = 40, PR = 16, PT = 12, PB = 28;
  const cW = W - PL - PR, cH = H - PT - PB;
  const max = Math.max(...data) * 1.1 || 1;
  const pts = data.map((v, i) => [PL + (i / (data.length - 1)) * cW, PT + cH - (v / max) * cH]);

  const pathD = pts.reduce((acc, [x, y], i) => {
    if (i === 0) return `M ${x},${y}`;
    const [px, py] = pts[i - 1];
    const cpx = (px + x) / 2;
    return `${acc} C ${cpx},${py} ${cpx},${y} ${x},${y}`;
  }, '');

  const areaD = `${pathD} L ${pts[pts.length - 1][0]},${PT + cH} L ${pts[0][0]},${PT + cH} Z`;

  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(f => ({
    y: PT + cH - f * cH,
    label: format ? format(Math.round(f * max)) : Math.round(f * max).toLocaleString(),
  }));

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: H, display: 'block' }}>
      <defs>
        <linearGradient id={`grad-${label}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color === 'var(--ink)' ? '#1A1A1A' : '#E8B83A'} stopOpacity="0.12" />
          <stop offset="100%" stopColor={color === 'var(--ink)' ? '#1A1A1A' : '#E8B83A'} stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* Grid lines */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={PL} y1={t.y} x2={W - PR} y2={t.y} stroke="rgba(26,26,26,0.06)" strokeWidth="1" />
          <text x={PL - 6} y={t.y + 4} textAnchor="end" fontSize="10" fill="rgba(26,26,26,0.4)" fontFamily="JetBrains Mono, monospace">{t.label}</text>
        </g>
      ))}

      {/* Area fill */}
      <path d={areaD} fill={`url(#grad-${label})`} />

      {/* Line */}
      <path d={pathD} fill="none" stroke={color === 'var(--ink)' ? '#1A1A1A' : '#E8B83A'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />

      {/* Dots + month labels */}
      {pts.map(([x, y], i) => (
        <g key={i}>
          <circle cx={x} cy={y} r={4} fill="var(--white)" stroke={color === 'var(--ink)' ? '#1A1A1A' : '#E8B83A'} strokeWidth="2" />
          <text x={x} y={H - 4} textAnchor="middle" fontSize="10" fill="rgba(26,26,26,0.5)" fontFamily="Geist, sans-serif">{months[i]}</text>
        </g>
      ))}
    </svg>
  );
};

// Bar chart
const BarChart = ({ data, months, color = '#E8B83A', height = 140 }) => {
  const W = 520, H = height, PL = 40, PR = 16, PT = 12, PB = 28;
  const cW = W - PL - PR, cH = H - PT - PB;
  const max = Math.max(...data) * 1.1 || 1;
  const barW = Math.max(8, (cW / data.length) * 0.55);
  const gap = cW / data.length;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: H, display: 'block' }}>
      {data.map((v, i) => {
        const x = PL + i * gap + gap / 2 - barW / 2;
        const barH = (v / max) * cH;
        const y = PT + cH - barH;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={barH} rx={4} fill={color} opacity={0.85} />
            <text x={x + barW / 2} y={H - 4} textAnchor="middle" fontSize="10" fill="rgba(26,26,26,0.5)" fontFamily="Geist, sans-serif">{months[i]}</text>
          </g>
        );
      })}
    </svg>
  );
};

// Conversion funnel
const FunnelChart = ({ data, labels }) => {
  const maxW = 400, H = data.length * 44;
  const max = data[0];
  return (
    <svg viewBox={`0 0 ${maxW} ${H}`} style={{ width: '100%', height: H, display: 'block' }}>
      {data.map((v, i) => {
        const w = (v / max) * (maxW - 80);
        const x = (maxW - w) / 2;
        const y = i * 44;
        const pct = i === 0 ? 100 : Math.round((v / data[i - 1]) * 100);
        return (
          <g key={i}>
            <rect x={x} y={y + 4} width={w} height={30} rx={6} fill={i === 0 ? '#1A1A1A' : i === data.length - 1 ? '#E8B83A' : `rgba(26,26,26,${0.7 - i * 0.12})`} />
            <text x={maxW / 2} y={y + 23} textAnchor="middle" fontSize="11" fill={i === data.length - 1 ? '#1A1A1A' : '#F5F1E8'} fontWeight="600" fontFamily="Geist, sans-serif">
              {labels[i]}  ·  {v.toLocaleString()}
            </text>
            {i > 0 && (
              <text x={x - 6} y={y + 23} textAnchor="end" fontSize="10" fill="rgba(26,26,26,0.45)" fontFamily="JetBrains Mono, monospace">{pct}%</text>
            )}
          </g>
        );
      })}
    </svg>
  );
};

const AnalyticsScreen = ({ persona, tweaks }) => {
  const [range, setRange] = React.useState('30d');
  const [metric, setMetric] = React.useState('installs');
  const { dark } = tweaks;
  const d = persona.id === 'nour' ? DATA_NOUR : DATA_MARCUS;

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  const metricTabs = [
    { id: 'installs', label: 'Installs', data: d.installs, color: 'var(--ink)', fmt: null },
    { id: 'sessions', label: 'Sessions', data: d.sessions, color: 'var(--ink)', fmt: null },
    { id: 'revenue', label: 'Revenue', data: d.revenue, color: 'honey', fmt: v => (persona.id === 'nour' ? 'EGP ' : '$') + (v >= 1000 ? `${(v/1000).toFixed(1)}k` : v) },
    { id: 'conversion', label: 'Conversion', data: d.conversion, color: 'var(--ink)', fmt: v => `${v}%` },
  ];
  const activeMetric = metricTabs.find(m => m.id === metric);

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

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: textColor, margin: 0, lineHeight: 1.1 }}>Analytics</h1>
          <div style={{ fontSize: 13, color: subColor, marginTop: 6 }}>App performance, customer behavior, and revenue attribution.</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <window.FilterPills options={['7d', '30d', '90d', 'All time']} active={range} onSelect={setRange} />
          <window.Button variant="secondary" size="sm" icon="download">Export</window.Button>
        </div>
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { label: 'App installs', value: persona.id === 'nour' ? '1,240' : '3,847', delta: '+23%', sub: 'total installed' },
          { label: 'Avg sessions / user', value: persona.id === 'nour' ? '4.2' : '5.1', delta: '+0.6', sub: 'per 30 days' },
          { label: 'Conversion rate', value: `${persona.stats.conversion}%`, delta: '+0.4pp', sub: 'vs mobile web: 1.1%' },
          { label: 'Revenue attributed', value: persona.id === 'nour' ? 'EGP 12.4k' : '$28.9k', delta: '+34%', sub: 'from app channel' },
        ].map((k, i) => (
          <div key={i} style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 10, padding: '18px 20px' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: subColor, fontWeight: 500, marginBottom: 10 }}>{k.label}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, lineHeight: 1, color: i === 3 ? 'var(--honey)' : textColor, marginBottom: 6 }}>{k.value}</div>
            <div style={{ fontSize: 11, color: 'var(--mint)', fontWeight: 500, marginBottom: 2 }}>↗ {k.delta}</div>
            <div style={{ fontSize: 11, color: subColor }}>{k.sub}</div>
          </div>
        ))}
      </div>

      {/* Main chart */}
      <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor }}>Growth over time</div>
          <div style={{ display: 'flex', gap: 4, background: dark ? 'rgba(0,0,0,0.2)' : 'var(--sand-50)', borderRadius: 999, padding: 3 }}>
            {metricTabs.map(m => (
              <button key={m.id} onClick={() => setMetric(m.id)} style={{ padding: '4px 12px', borderRadius: 999, fontSize: 12, fontWeight: metric === m.id ? 500 : 400, background: metric === m.id ? (dark ? 'rgba(255,255,255,0.12)' : 'var(--white)') : 'transparent', color: metric === m.id ? textColor : subColor, border: 'none', cursor: 'pointer', transition: 'all 150ms' }}>
                {m.label}
              </button>
            ))}
          </div>
        </div>
        {activeMetric.id === 'revenue'
          ? <BarChart data={activeMetric.data} months={d.months} color="#E8B83A" />
          : <LineChart data={activeMetric.data} months={d.months} label={activeMetric.id} color={activeMetric.color} format={activeMetric.fmt} />
        }
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Conversion funnel */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 20 }}>Conversion funnel</div>
          <FunnelChart data={d.funnel} labels={d.funnelLabels} />
          <div style={{ marginTop: 16, fontSize: 12, color: subColor, textAlign: 'center' }}>
            Overall conversion: <strong style={{ color: textColor }}>{((d.funnel[d.funnel.length - 1] / d.funnel[0]) * 100).toFixed(1)}%</strong> of installs purchase
          </div>
        </div>

        {/* Push performance */}
        <div style={{ background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 12, padding: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: textColor, marginBottom: 16 }}>Push campaign performance</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr>
                {['Campaign', 'Sent', 'Opens', 'Rate', 'Revenue'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '0 8px 10px 0', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: subColor, fontWeight: 500, borderBottom: `1px solid ${cardBorder}` }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {d.pushCampaigns.map((c, i) => (
                <tr key={i} style={{ borderBottom: i < d.pushCampaigns.length - 1 ? `1px solid ${dark ? 'rgba(255,255,255,0.05)' : 'var(--hairline-soft)'}` : 'none' }}>
                  <td style={{ padding: '10px 8px 10px 0', fontWeight: 500, color: textColor, maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</td>
                  <td style={{ padding: '10px 8px', fontFamily: 'var(--font-mono)', color: textColor }}>{c.sent.toLocaleString()}</td>
                  <td style={{ padding: '10px 8px', fontFamily: 'var(--font-mono)', color: textColor }}>{c.opens}</td>
                  <td style={{ padding: '10px 8px', fontFamily: 'var(--font-mono)', color: 'var(--mint)', fontWeight: 600 }}>{c.rate}</td>
                  <td style={{ padding: '10px 0', fontFamily: 'var(--font-mono)', color: c.revenue !== '—' ? 'var(--honey-deep)' : subColor }}>{c.revenue}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Attribution banner */}
      <div style={{ background: 'var(--ink)', borderRadius: 12, padding: '20px 28px', display: 'flex', alignItems: 'center', gap: 24 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(245,241,232,0.5)', fontWeight: 500, marginBottom: 6 }}>Revenue attribution</div>
          <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 28, color: 'var(--honey)', lineHeight: 1 }}>
            {persona.id === 'nour' ? 'EGP 12,400' : '$28,900'}
          </div>
          <div style={{ fontSize: 13, color: 'rgba(245,241,232,0.65)', marginTop: 6 }}>
            attributed to your app this month — {persona.id === 'nour' ? '~15%' : '~19%'} of total store revenue
          </div>
        </div>
        <div style={{ display: 'flex', gap: 20 }}>
          {[
            { label: 'From push', value: persona.id === 'nour' ? 'EGP 6,220' : '$26,600' },
            { label: 'From app sessions', value: persona.id === 'nour' ? 'EGP 6,180' : '$2,300' },
          ].map(item => (
            <div key={item.label} style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10, color: 'rgba(245,241,232,0.4)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>{item.label}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 600, color: 'var(--paper)' }}>{item.value}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

window.AnalyticsScreen = AnalyticsScreen;
