// Brand Growth Tracker — month-over-month brand awareness tracking
const { useState: useState_gt } = React;

function GrowthTracker() {
  const [period, setPeriod] = useState_gt('6m');
  const [compareWith, setCompareWith] = useState_gt('prev');

  // Monthly snapshots — Top of Mind share %
  const monthly = [
    { m: 'Nov 25', us: 18.2, c1: 31.0, c2: 16.0, n: 612, nps: 28 },
    { m: 'Des 25', us: 20.1, c1: 30.4, c2: 16.3, n: 718, nps: 30 },
    { m: 'Jan 26', us: 22.8, c1: 29.8, c2: 17.0, n: 824, nps: 33 },
    { m: 'Feb 26', us: 25.6, c1: 30.5, c2: 17.4, n: 901, nps: 36 },
    { m: 'Mar 26', us: 28.0, c1: 29.9, c2: 18.0, n: 1058, nps: 38 },
    { m: 'Apr 26', us: 32.4, c1: 28.1, c2: 18.6, n: 1284, nps: 42 },
  ];

  const cur = monthly[monthly.length - 1];
  const prev = monthly[monthly.length - 2];
  const yearAgo = monthly[0];
  const cmp = compareWith === 'prev' ? prev : yearAgo;

  // Marketing milestones
  const events = [
    { m: 'Des 25', label: 'Promo Akhir Tahun', icon: '🎄', impact: '+1.9' },
    { m: 'Jan 26', label: 'Launch outlet ke-3', icon: '🏪', impact: '+2.7' },
    { m: 'Mar 26', label: 'Kolaborasi influencer', icon: '⭐', impact: '+2.4' },
    { m: 'Apr 26', label: 'Iklan Tiktok Ads', icon: '📱', impact: '+4.4' },
  ];

  // Cohort retention — % of mention week-over-week (mock)
  const cohort = [
    { label: 'Jan',  retention: [100, 78, 62, 54, 48, 42] },
    { label: 'Feb',  retention: [100, 82, 70, 60, 52, null] },
    { label: 'Mar',  retention: [100, 84, 72, 64, null, null] },
    { label: 'Apr',  retention: [100, 88, 76, null, null, null] },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <TopBar
        title="Brand Growth Tracker"
        subtitle="Pantau pertumbuhan awareness brand bulan ke bulan, identifikasi pola, dan ukur efek kampanye"
        right={
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <select className="select" value={compareWith} onChange={(e) => setCompareWith(e.target.value)} style={{ width: 'auto', padding: '6px 28px 6px 10px', fontSize: 12.5 }}>
              <option value="prev">vs Bulan Lalu</option>
              <option value="year">vs 6 Bulan Lalu</option>
            </select>
            <div style={{ display: 'flex', background: 'var(--bg-2)', borderRadius: 8, padding: 2 }}>
              {['3m', '6m', '12m'].map((p) => (
                <button key={p} onClick={() => setPeriod(p)} style={{
                  border: 'none', background: period === p ? 'var(--surface)' : 'transparent',
                  padding: '5px 10px', borderRadius: 6, fontSize: 12, fontWeight: 500,
                  color: period === p ? 'var(--ink)' : 'var(--ink-3)',
                  boxShadow: period === p ? 'var(--shadow-sm)' : 'none', cursor: 'pointer',
                }}>{p}</button>
              ))}
            </div>
            <button className="btn btn-soft"><I.Send size={14} />Export PDF</button>
          </div>
        }
      />

      <div className="scroll" style={{ flex: 1, overflow: 'auto', padding: 20, background: 'var(--bg)' }}>
        {/* Hero KPI */}
        <div className="card" style={{ padding: 24, marginBottom: 16, background: 'linear-gradient(135deg, var(--surface), var(--primary-50))' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
                Top of Mind · {cur.m}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
                <span className="mono" style={{ fontSize: 48, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--primary)' }}>
                  {cur.us}%
                </span>
                <span className="mono" style={{ fontSize: 14, padding: '4px 8px', borderRadius: 6, background: 'var(--success-soft)', color: 'oklch(0.42 0.12 155)', fontWeight: 600 }}>
                  ↑ {(cur.us - cmp.us).toFixed(1)} pp
                </span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 6 }}>
                vs {cmp.m} · <b className="mono">{cmp.us}%</b>
              </div>
            </div>
            {/* Sparkline hero */}
            <svg viewBox="0 0 400 100" style={{ width: '100%', height: 90 }}>
              <defs>
                <linearGradient id="heroGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.3" />
                  <stop offset="100%" stopColor="var(--primary)" stopOpacity="0" />
                </linearGradient>
              </defs>
              {(() => {
                const w = 400, h = 100, pad = 6;
                const max = 36, min = 14;
                const xs = monthly.map((_, i) => pad + (i / (monthly.length - 1)) * (w - pad * 2));
                const ys = monthly.map((d) => h - pad - ((d.us - min) / (max - min)) * (h - pad * 2));
                const linePath = monthly.map((_, i) => `${i === 0 ? 'M' : 'L'} ${xs[i]} ${ys[i]}`).join(' ');
                const areaPath = linePath + ` L ${xs[xs.length - 1]} ${h} L ${xs[0]} ${h} Z`;
                return (
                  <>
                    <path d={areaPath} fill="url(#heroGrad)" />
                    <path d={linePath} fill="none" stroke="var(--primary)" strokeWidth="2.5" strokeLinecap="round" />
                    {monthly.map((d, i) => (
                      <g key={i}>
                        <circle cx={xs[i]} cy={ys[i]} r={i === monthly.length - 1 ? 5 : 2.5} fill={i === monthly.length - 1 ? 'var(--primary)' : 'white'} stroke="var(--primary)" strokeWidth="2" />
                      </g>
                    ))}
                  </>
                );
              })()}
            </svg>
            <div style={{ textAlign: 'right' }}>
              <div className="badge badge-success" style={{ fontSize: 11.5 }}>
                <I.Trend size={11} />Tren Bullish
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 8, maxWidth: 180 }}>
                6 bulan tumbuh konsisten <b style={{ color: 'oklch(0.42 0.12 155)' }}>+14.2 pp</b>, di atas rata-rata industri.
              </div>
            </div>
          </div>
        </div>

        {/* Comparison KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
          <CompareCard label="Top of Mind" cur={`${cur.us}%`} prev={`${cmp.us}%`} delta={cur.us - cmp.us} suffix="pp" positive />
          <CompareCard label="Total Responden" cur={cur.n.toLocaleString('id-ID')} prev={cmp.n.toLocaleString('id-ID')} delta={((cur.n - cmp.n) / cmp.n) * 100} suffix="%" positive />
          <CompareCard label="NPS Score" cur={cur.nps} prev={cmp.nps} delta={cur.nps - cmp.nps} suffix="" positive />
          <CompareCard label="Gap vs Pemimpin" cur={`${(cur.c1 - cur.us).toFixed(1)} pp`} prev={`${(cmp.c1 - cmp.us).toFixed(1)} pp`} delta={(cmp.c1 - cmp.us) - (cur.c1 - cur.us)} suffix="pp" positive />
        </div>

        {/* Timeline + Events */}
        <div className="card" style={{ padding: 20, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Pertumbuhan vs Kompetitor + Marketing Events</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>Hubungkan kampanye dengan lonjakan awareness</div>
            </div>
            <div style={{ display: 'flex', gap: 14, fontSize: 11.5 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 10, height: 2.5, background: 'var(--primary)' }}></span>Kopi Kenanga</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5, color: 'var(--ink-3)' }}><span style={{ width: 10, height: 2.5, background: 'oklch(0.68 0.16 25)' }}></span>Janji Manis</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5, color: 'var(--ink-3)' }}><span style={{ width: 10, height: 2.5, background: 'oklch(0.62 0.14 145)' }}></span>Tomoro</span>
            </div>
          </div>

          <GrowthChart data={monthly} events={events} />
        </div>

        {/* Insights row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 12, marginBottom: 16 }}>
          <div className="card" style={{ padding: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Pola Pertumbuhan</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 16 }}>Decomposition: musiman vs efek kampanye</div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 16 }}>
              <DecompCard label="Pertumbuhan Organik" value="+5.4 pp" pct={38} color="var(--primary)" />
              <DecompCard label="Efek Kampanye" value="+7.2 pp" pct={51} color="oklch(0.55 0.16 25)" />
              <DecompCard label="Musiman" value="+1.6 pp" pct={11} color="oklch(0.55 0.14 145)" />
            </div>

            <div style={{ padding: 12, background: 'var(--bg-2)', borderRadius: 10, fontSize: 12.5, color: 'var(--ink-2)', display: 'flex', gap: 10 }}>
              <I.Sparkle size={14} style={{ color: 'var(--primary)', flexShrink: 0, marginTop: 1 }} />
              <span>
                <b>51% pertumbuhan</b> berasal dari kampanye marketing, terutama Tiktok Ads di April. Promo akhir tahun memberi efek lebih kecil (1.9 pp) dari yang diharapkan — pertimbangkan format berbeda untuk Q4 berikutnya.
              </span>
            </div>
          </div>

          <div className="card" style={{ padding: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Posisi Kompetitif</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 16 }}>Perubahan ranking 6 bulan</div>

            {[
              { rank: 1, name: 'Kopi Janji Manis', share: 28.1, prev: 31.0, prevRank: 1, us: false },
              { rank: 2, name: 'Kopi Kenanga',     share: 32.4, prev: 18.2, prevRank: 3, us: true },
              { rank: 3, name: 'Tomoro Coffee',    share: 18.6, prev: 16.0, prevRank: 2, us: false },
              { rank: 4, name: 'Fore Coffee',      share: 12.3, prev: 14.0, prevRank: 4, us: false },
            ].map((b) => {
              const moved = b.prevRank - b.rank;
              return (
                <div key={b.name} style={{
                  display: 'grid', gridTemplateColumns: 'auto 1fr auto auto', alignItems: 'center', gap: 10,
                  padding: '10px 0', borderTop: '1px solid var(--line)', fontSize: 13,
                }}>
                  <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: b.us ? 'var(--primary)' : 'var(--ink-3)', minWidth: 18 }}>#{b.rank}</span>
                  <span style={{ fontWeight: b.us ? 600 : 500, color: b.us ? 'var(--primary)' : 'var(--ink)' }}>
                    {b.name}{b.us && <span className="badge badge-primary" style={{ marginLeft: 6, fontSize: 10, padding: '1px 6px' }}>Kamu</span>}
                  </span>
                  <span className="mono" style={{ fontWeight: 600 }}>{b.share}%</span>
                  <span className="mono" style={{
                    fontSize: 11, padding: '2px 6px', borderRadius: 5, minWidth: 38, textAlign: 'center',
                    background: moved > 0 ? 'var(--success-soft)' : moved < 0 ? 'var(--danger-soft)' : 'var(--bg-2)',
                    color: moved > 0 ? 'oklch(0.42 0.12 155)' : moved < 0 ? 'oklch(0.50 0.18 25)' : 'var(--ink-3)',
                    fontWeight: 600,
                  }}>
                    {moved > 0 ? `↑${moved}` : moved < 0 ? `↓${Math.abs(moved)}` : '—'}
                  </span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Cohort + forecast */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="card" style={{ padding: 20 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Loyalty Cohort</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 14 }}>Berapa % responden tetap menyebut brand-mu di survei berikutnya</div>

            <div style={{ overflow: 'auto' }}>
              <table style={{ width: '100%', fontSize: 11.5, borderCollapse: 'separate', borderSpacing: 2 }}>
                <thead>
                  <tr style={{ color: 'var(--ink-3)' }}>
                    <th style={{ textAlign: 'left', padding: '4px 6px', fontWeight: 500 }}>Cohort</th>
                    {['M0', 'M1', 'M2', 'M3', 'M4', 'M5'].map((m) => (
                      <th key={m} style={{ padding: '4px 0', fontWeight: 500, fontFamily: 'var(--font-mono)' }}>{m}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {cohort.map((row) => (
                    <tr key={row.label}>
                      <td style={{ padding: '4px 6px', color: 'var(--ink-2)', fontWeight: 500 }}>{row.label}</td>
                      {row.retention.map((v, i) => (
                        <td key={i} style={{
                          padding: '6px 0', textAlign: 'center', fontFamily: 'var(--font-mono)',
                          background: v == null ? 'transparent' : `oklch(0.52 0.18 265 / ${v / 100})`,
                          color: v == null ? 'var(--ink-4)' : v > 60 ? 'white' : 'var(--ink)',
                          borderRadius: 4, fontWeight: 600, fontSize: 11,
                        }}>
                          {v == null ? '—' : `${v}%`}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 12 }}>
              Cohort April-26 menunjukkan retensi 88% di M1 — terbaik dalam 4 bulan terakhir.
            </div>
          </div>

          <div className="card" style={{ padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Forecast 3 Bulan</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>Prediksi AI berdasarkan tren saat ini</div>
              </div>
              <span className="badge badge-primary"><I.Sparkle size={11} />AI</span>
            </div>

            <ForecastChart data={monthly} />

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 14 }}>
              {[
                { m: 'Mei 26',  v: 35.2, conf: 'Tinggi' },
                { m: 'Jun 26',  v: 37.8, conf: 'Sedang' },
                { m: 'Jul 26',  v: 40.1, conf: 'Sedang' },
              ].map((f) => (
                <div key={f.m} style={{ padding: 10, background: 'var(--bg-2)', borderRadius: 8 }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{f.m}</div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: 'var(--primary)', letterSpacing: '-0.01em' }}>{f.v}%</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>Conf: {f.conf}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Compare KPI card ────────────────────────────────────────────────
function CompareCard({ label, cur, prev, delta, suffix, positive }) {
  const isPos = delta >= 0;
  const showPos = positive ? isPos : !isPos;
  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 500 }}>{label}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 4 }}>
        {cur}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, fontSize: 11.5 }}>
        <span className="mono" style={{
          padding: '2px 6px', borderRadius: 4,
          background: showPos ? 'var(--success-soft)' : 'var(--danger-soft)',
          color: showPos ? 'oklch(0.42 0.12 155)' : 'oklch(0.50 0.18 25)',
          fontWeight: 600,
        }}>
          {isPos ? '↑' : '↓'} {Math.abs(delta).toFixed(1)}{suffix}
        </span>
        <span className="mono" style={{ color: 'var(--ink-3)' }}>vs {prev}</span>
      </div>
    </div>
  );
}

// ─── Decomposition card ──────────────────────────────────────────────
function DecompCard({ label, value, pct, color }) {
  return (
    <div style={{ padding: 12, border: '1px solid var(--line)', borderRadius: 10, background: 'var(--surface)' }}>
      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{label}</div>
      <div className="mono" style={{ fontSize: 18, fontWeight: 700, color, letterSpacing: '-0.01em', marginTop: 2 }}>{value}</div>
      <div style={{ height: 5, borderRadius: 3, background: 'var(--bg-2)', marginTop: 8, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 3 }}></div>
      </div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>{pct}% dari total</div>
    </div>
  );
}

// ─── Growth chart with event markers ─────────────────────────────────
function GrowthChart({ data, events }) {
  const w = 900, h = 280, pad = { l: 40, r: 16, t: 28, b: 36 };
  const cw = w - pad.l - pad.r, ch = h - pad.t - pad.b;
  const xs = data.map((_, i) => pad.l + (i / (data.length - 1)) * cw);
  const max = 36, min = 14;
  const yScale = (v) => pad.t + ch - ((v - min) / (max - min)) * ch;

  const series = [
    { key: 'us', color: 'var(--primary)', strokeWidth: 2.5 },
    { key: 'c1', color: 'oklch(0.68 0.16 25)', strokeWidth: 1.6, dash: '5 4' },
    { key: 'c2', color: 'oklch(0.62 0.14 145)', strokeWidth: 1.6, dash: '5 4' },
  ];

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="growthGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.18" />
          <stop offset="100%" stopColor="var(--primary)" stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* gridlines */}
      {[15, 20, 25, 30, 35].map((v) => (
        <g key={v}>
          <line x1={pad.l} y1={yScale(v)} x2={w - pad.r} y2={yScale(v)} stroke="var(--line)" strokeDasharray="2 4" />
          <text x={pad.l - 8} y={yScale(v) + 3} fontSize="10" fill="var(--ink-3)" textAnchor="end" fontFamily="var(--font-mono)">{v}%</text>
        </g>
      ))}

      {/* event vertical markers */}
      {events.map((e, i) => {
        const idx = data.findIndex((d) => d.m === e.m);
        if (idx < 0) return null;
        const x = xs[idx];
        return (
          <g key={i}>
            <line x1={x} y1={pad.t - 6} x2={x} y2={pad.t + ch} stroke="oklch(0.78 0.10 75)" strokeDasharray="3 3" strokeWidth="1" />
            <g transform={`translate(${x}, ${pad.t - 14})`}>
              <rect x={-44} y={-10} width="88" height="20" rx="10" fill="oklch(0.96 0.04 75)" stroke="oklch(0.82 0.08 75)" />
              <text x={-30} y={4} fontSize="11">{e.icon}</text>
              <text x={-15} y={4} fontSize="9.5" fill="oklch(0.45 0.12 75)" fontWeight="600">{e.label.slice(0, 12)}</text>
            </g>
          </g>
        );
      })}

      {/* x labels */}
      {data.map((d, i) => (
        <text key={i} x={xs[i]} y={h - 12} fontSize="11" fill="var(--ink-3)" textAnchor="middle">{d.m}</text>
      ))}

      {/* area for us */}
      <path
        d={data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${xs[i]} ${yScale(d.us)}`).join(' ') + ` L ${xs[xs.length - 1]} ${pad.t + ch} L ${xs[0]} ${pad.t + ch} Z`}
        fill="url(#growthGrad)"
      />

      {/* lines */}
      {series.map((s) => (
        <path key={s.key}
          d={data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${xs[i]} ${yScale(d[s.key])}`).join(' ')}
          fill="none" stroke={s.color} strokeWidth={s.strokeWidth} strokeDasharray={s.dash || '0'}
          strokeLinecap="round" strokeLinejoin="round"
        />
      ))}

      {/* dots */}
      {data.map((d, i) => (
        <circle key={i} cx={xs[i]} cy={yScale(d.us)}
          r={i === data.length - 1 ? 5 : 3}
          fill={i === data.length - 1 ? 'var(--primary)' : 'white'}
          stroke="var(--primary)" strokeWidth="2"
        />
      ))}

      {/* current value callout */}
      {(() => {
        const last = data[data.length - 1];
        const lx = xs[xs.length - 1], ly = yScale(last.us);
        return (
          <g transform={`translate(${lx + 8}, ${ly - 14})`}>
            <rect x={0} y={0} width="56" height="22" rx="11" fill="var(--primary)" />
            <text x={28} y={14.5} fontSize="11" fontWeight="700" fill="white" textAnchor="middle" fontFamily="var(--font-mono)">{last.us}%</text>
          </g>
        );
      })()}
    </svg>
  );
}

// ─── Forecast chart ──────────────────────────────────────────────────
function ForecastChart({ data }) {
  const forecast = [
    { m: 'Mei',  v: 35.2 },
    { m: 'Jun',  v: 37.8 },
    { m: 'Jul',  v: 40.1 },
  ];
  const all = [...data.map((d) => ({ m: d.m.split(' ')[0], v: d.us, real: true })), ...forecast.map((f) => ({ ...f, real: false }))];
  const w = 360, h = 160, pad = { l: 8, r: 8, t: 8, b: 18 };
  const cw = w - pad.l - pad.r, ch = h - pad.t - pad.b;
  const xs = all.map((_, i) => pad.l + (i / (all.length - 1)) * cw);
  const max = 42, min = 14;
  const yScale = (v) => pad.t + ch - ((v - min) / (max - min)) * ch;

  const realPts = all.filter((d) => d.real);
  const realXs = xs.slice(0, realPts.length);
  const forecastXs = xs.slice(realPts.length - 1); // overlap by 1
  const forecastPts = [realPts[realPts.length - 1], ...all.filter((d) => !d.real)];

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', display: 'block' }}>
      <defs>
        <linearGradient id="fcGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.18" />
          <stop offset="100%" stopColor="var(--primary)" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="confBand" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--primary)" stopOpacity="0.12" />
          <stop offset="100%" stopColor="var(--primary)" stopOpacity="0.04" />
        </linearGradient>
      </defs>

      {/* confidence band on forecast */}
      {(() => {
        const top = forecastPts.map((d, i) => `${i === 0 ? 'M' : 'L'} ${forecastXs[i]} ${yScale(d.v + (i * 1.2))}`).join(' ');
        const bottom = forecastPts.slice().reverse().map((d, i) => {
          const realI = forecastPts.length - 1 - i;
          return `L ${forecastXs[realI]} ${yScale(d.v - (realI * 1.2))}`;
        }).join(' ');
        return <path d={`${top} ${bottom} Z`} fill="url(#confBand)" />;
      })()}

      {/* real area */}
      <path
        d={realPts.map((d, i) => `${i === 0 ? 'M' : 'L'} ${realXs[i]} ${yScale(d.v)}`).join(' ') + ` L ${realXs[realXs.length - 1]} ${pad.t + ch} L ${realXs[0]} ${pad.t + ch} Z`}
        fill="url(#fcGrad)"
      />

      {/* real line */}
      <path
        d={realPts.map((d, i) => `${i === 0 ? 'M' : 'L'} ${realXs[i]} ${yScale(d.v)}`).join(' ')}
        fill="none" stroke="var(--primary)" strokeWidth="2" strokeLinecap="round"
      />
      {/* forecast line dashed */}
      <path
        d={forecastPts.map((d, i) => `${i === 0 ? 'M' : 'L'} ${forecastXs[i]} ${yScale(d.v)}`).join(' ')}
        fill="none" stroke="var(--primary)" strokeWidth="2" strokeDasharray="5 4" strokeLinecap="round"
      />

      {/* dots */}
      {realPts.map((d, i) => (
        <circle key={i} cx={realXs[i]} cy={yScale(d.v)} r={2.5} fill="var(--primary)" />
      ))}
      {forecastPts.slice(1).map((d, i) => (
        <circle key={i} cx={forecastXs[i + 1]} cy={yScale(d.v)} r={3} fill="white" stroke="var(--primary)" strokeWidth="1.8" strokeDasharray="2 1.5" />
      ))}

      {/* divider */}
      <line x1={realXs[realXs.length - 1]} y1={pad.t} x2={realXs[realXs.length - 1]} y2={pad.t + ch} stroke="var(--line-2)" strokeDasharray="2 3" />
      <text x={realXs[realXs.length - 1] - 4} y={pad.t + 9} fontSize="9" fill="var(--ink-3)" textAnchor="end">Sekarang</text>
      <text x={realXs[realXs.length - 1] + 4} y={pad.t + 9} fontSize="9" fill="var(--primary)" fontWeight="600">Prediksi</text>

      {/* x labels */}
      {all.map((d, i) => (
        <text key={i} x={xs[i]} y={h - 4} fontSize="9" fill={d.real ? 'var(--ink-3)' : 'var(--primary)'} textAnchor="middle" fontWeight={d.real ? 400 : 600}>{d.m}</text>
      ))}
    </svg>
  );
}

Object.assign(window, { GrowthTracker });
