/* Live Stats page — top counter row, outlet bars, daily sparkline, match-by-match. */

/* ---------- Top stat card with triangular accent ---------- */
function TopStat({ label, value, accent = 'orange', valueColor }) {
  const colors = {
    orange: 'var(--orange)',
    ink: 'var(--ink)',
    green: 'var(--success)',
    grey: 'var(--grey-300)',
  };
  return (
    <div style={{
      position: 'relative',
      background: '#fff',
      border: '1px solid var(--grey-200)',
      borderRadius: 10,
      padding: '22px 22px 24px',
      boxShadow: '0 2px 12px rgba(17,6,24,0.07)',
      overflow: 'hidden',
    }}>
      <div className="clip-tri-tr" style={{
        position: 'absolute', top: 0, right: 0, width: 64, height: 64, background: colors[accent],
      }} />
      <div style={{
        fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--grey-600)',
        position: 'relative', zIndex: 1,
      }}>
        {label}
      </div>
      <div className="font-display" style={{
        fontSize: 44, lineHeight: 1, marginTop: 12, color: valueColor || 'var(--ink)', letterSpacing: '-0.02em',
        position: 'relative', zIndex: 1,
      }}>
        {value}
      </div>
    </div>
  );
}

/* ---------- Chart card wrapper ---------- */
function ChartCard({ title, sub, children, right }) {
  return (
    <section style={{
      background: '#fff',
      border: '1px solid var(--grey-200)',
      borderRadius: 10,
      overflow: 'hidden',
      padding: 0,
      boxShadow: '0 2px 12px rgba(17,6,24,0.07)',
    }}>
      <header style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12,
        padding: '20px 24px 14px',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, minWidth: 0 }}>
          <div style={{ width: 6, alignSelf: 'stretch', background: 'var(--orange)', minHeight: 36, flexShrink: 0 }} />
          <div style={{ minWidth: 0 }}>
            <h3 className="font-display" style={{ margin: 0, fontSize: 22, letterSpacing: '-0.01em' }}>{title}</h3>
            {sub && <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--grey-600)' }}>{sub}</p>}
          </div>
        </div>
        {right}
      </header>
      <div style={{ padding: '8px 24px 24px' }}>{children}</div>
    </section>
  );
}

/* ---------- Outlet bars ---------- */
function OutletBars({ data }) {
  const max = Math.max(...data.map(d => d.count)) || 1;
  return (
    <div style={{ display: 'grid', gap: 12, paddingTop: 8 }}>
      {data.map((d, i) => (
        <div key={d.outlet} className="outlet-row" style={{ display: 'grid', gridTemplateColumns: '140px 1fr 64px', gap: 12, alignItems: 'center' }}>
          <div style={{ fontWeight: 700, fontSize: 13.5, letterSpacing: '0.02em' }}>{d.outlet}</div>
          <div style={{
            position: 'relative',
            height: 30, background: 'var(--grey-100)',
            border: '1px solid var(--grey-200)',
          }}>
            <div className="grow-bar stripes-bg" style={{
              width: `${(d.count / max) * 100}%`, height: '100%',
              animationDelay: `${i * 60}ms`,
            }} />
          </div>
          <div className="font-display" style={{ fontSize: 18, textAlign: 'right' }}>
            <AnimatedCounter value={d.count} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Daily sparkline ---------- */
function DailySparkline({ data }) {
  if (!data || data.length < 2) {
    return (
      <div style={{ textAlign:'center', color:'var(--grey-400)', padding:'48px 0', fontSize:13, letterSpacing:'0.08em', textTransform:'uppercase', fontWeight:600 }}>
        No data yet — predictions will appear here once the campaign goes live.
      </div>
    );
  }
  const W = 640, H = 220;
  const pad = { l: 40, r: 16, t: 16, b: 28 };
  const innerW = W - pad.l - pad.r;
  const innerH = H - pad.t - pad.b;
  const max = (Math.max(...data.map(d => d.n)) || 1) * 1.08;
  const xStep = innerW / (data.length - 1);
  const pts = data.map((d, i) => [pad.l + i * xStep, pad.t + (1 - d.n / max) * innerH]);
  const linePath = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`).join(' ');
  const areaPath = `${linePath} L ${pts[pts.length-1][0]} ${pad.t + innerH} L ${pts[0][0]} ${pad.t + innerH} Z`;

  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="220" style={{ display: 'block', maxWidth: '100%' }}>
      <defs>
        <linearGradient id="orangeFade" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--orange)" stopOpacity="0.30" />
          <stop offset="100%" stopColor="var(--orange)" stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* gridlines */}
      {Array.from({ length: ticks + 1 }).map((_, i) => {
        const y = pad.t + (i / ticks) * innerH;
        const v = Math.round((1 - i / ticks) * max);
        return (
          <g key={i}>
            <line x1={pad.l} x2={W - pad.r} y1={y} y2={y} stroke="var(--grey-200)" strokeDasharray="4 4" />
            <text x={pad.l - 8} y={y + 4} fontSize="10" fill="var(--grey-500)" textAnchor="end">{v}</text>
          </g>
        );
      })}

      {/* area */}
      <path d={areaPath} fill="url(#orangeFade)" />
      {/* line */}
      <path d={linePath} fill="none" stroke="var(--orange)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />

      {/* dots */}
      {pts.map(([x, y], i) => {
        const last = i === pts.length - 1;
        return last
          ? <circle key={i} cx={x} cy={y} r="6" fill="var(--ink)" stroke="#fff" strokeWidth="2" />
          : <circle key={i} cx={x} cy={y} r="4" fill="var(--orange)" />;
      })}

      {/* x labels */}
      {data.map((d, i) => {
        if (i % 2 !== 0 && i !== data.length - 1) return null;
        const x = pad.l + i * xStep;
        return (
          <text key={i} x={x} y={H - 8} fontSize="10" fill="var(--grey-500)" textAnchor="middle">
            {d.d}
          </text>
        );
      })}

      {/* last value callout */}
      <g transform={`translate(${pts[pts.length-1][0] - 50}, ${pts[pts.length-1][1] - 34})`}>
        <rect x="0" y="0" width="92" height="22" fill="var(--ink)" />
        <text x="46" y="15" fontSize="11" fill="#fff" textAnchor="middle" fontWeight="700" letterSpacing="0.06em">
          {data[data.length-1].n} TODAY
        </text>
      </g>
    </svg>
  );
}

/* ---------- Match-by-match split ---------- */
function MatchSplit({ rows }) {
  return (
    <div style={{ display: 'grid', gap: 18 }}>
      {rows.map(r => {
        const total = (r.a_n + r.draw_n + r.b_n) || 1;
        const pa = (r.a_n / total) * 100;
        const pd = (r.draw_n / total) * 100;
        const pb = (r.b_n / total) * 100;
        return (
          <div key={r.id} style={{
            border: '1px solid var(--grey-200)', borderRadius: 8, padding: '16px 18px', background: '#fff',
          }}>
            {/* header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Flag code={r.flagA} w={30} h={20} />
                <div className="font-display" style={{ fontSize: 16 }}>{r.a}</div>
                <VSHex size={28} />
                <div className="font-display" style={{ fontSize: 16 }}>{r.b}</div>
                <Flag code={r.flagB} w={30} h={20} />
              </div>
              <div style={{ textAlign: 'right', fontSize: 12, color: 'var(--grey-500)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>
                <span className="font-display" style={{ fontSize: 18, color: 'var(--ink)' }}>{total.toLocaleString()}</span>{' '}
                <span style={{ marginLeft: 8 }}>predictions · {r.stage}</span>
              </div>
            </div>

            {/* stacked bar */}
            <div style={{ display: 'flex', height: 40, marginTop: 14, borderRadius: 4, overflow: 'hidden', border: '1px solid var(--grey-200)' }}>
              <SplitSeg w={pa} bg="var(--ink)"        fg="#fff" label={`${r.a} · ${Math.round(pa)}%`} />
              <SplitSeg w={pd} bg="var(--grey-400)"   fg="#fff" label={`Draw · ${Math.round(pd)}%`} />
              <SplitSeg w={pb} bg="var(--orange)"     fg="#fff" label={`${r.b} · ${Math.round(pb)}%`} />
            </div>

            {/* foot row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 10 }}>
              <FootCount color="var(--ink)"      label={r.a}    n={r.a_n} />
              <FootCount color="var(--grey-400)" label="Draw"   n={r.draw_n} />
              <FootCount color="var(--orange)"   label={r.b}    n={r.b_n} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SplitSeg({ w, bg, fg, label }) {
  return (
    <div style={{
      width: `${w}%`, background: bg, color: fg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 11.5, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase',
      overflow: 'hidden', whiteSpace: 'nowrap',
      transition: 'width 0.6s cubic-bezier(.2,.7,.2,1)',
    }}>
      {w >= 8 ? label : ''}
    </div>
  );
}

function FootCount({ color, label, n }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--grey-700)' }}>
      <span style={{ width: 10, height: 10, background: color, flexShrink: 0 }} />
      <span style={{ fontWeight: 600 }}>{label}</span>
      <span className="font-mono" style={{ color: 'var(--ink)', marginLeft: 'auto' }}>{n.toLocaleString()}</span>
    </div>
  );
}

/* ---------- Live pill ---------- */
function LivePill({ lastUpdated }) {
  return (
    <div className="skew-tag" style={{
      background: 'var(--success-bg)', color: '#0f5f2e',
      border: '2px solid var(--success)',
      padding: '8px 18px',
      display: 'inline-flex', alignItems: 'center', gap: 10,
      fontSize: 12, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase',
    }}>
      <span className="skew-tag-inner" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
        <span className="pulse-dot" style={{ width: 8, height: 8, background: 'var(--success)', borderRadius: '50%' }} />
        Live · {lastUpdated}
      </span>
    </div>
  );
}

/* ---------- Dashboard page ---------- */
function DashboardPage() {
  const [tick, setTick] = useState(0);
  const lastUpdated = useMemo(() => {
    const d = new Date();
    return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`;
  }, [tick]);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 30000);
    return () => clearInterval(id);
  }, []);

  const t = DASHBOARD.totals;

  return (
    <main>
      <PageBand
        eyebrow="Live campaign stats"
        title={<>The crowd<br />has spoken.</>}
        sub={<>Aggregated data only. <span style={{ color: 'var(--grey-500)' }}>No customer information shown.</span></>}
        right={<LivePill lastUpdated={lastUpdated} />}
      />

      <section style={{ padding: '32px 0 16px', background: '#fff' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
          {/* Top stats */}
          <div className="topstats-grid" style={{
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16,
          }}>
            <TopStat label="Total predictions"
              value={<AnimatedCounter value={t.totalPredictions} />}
              accent="orange" valueColor="var(--orange)" />
            <TopStat label="Matches tracked"
              value={<AnimatedCounter value={t.matchesTracked} format={(n) => String(Math.round(n)).padStart(2,'0')} duration={800} />}
              accent="ink" />
            <TopStat label="Open now"
              value={<AnimatedCounter value={t.openNow} format={(n) => String(Math.round(n)).padStart(2,'0')} duration={800} />}
              accent="green" valueColor="var(--success)" />
            <TopStat label="Settled"
              value={<AnimatedCounter value={t.settled} format={(n) => String(Math.round(n)).padStart(2,'0')} duration={800} />}
              accent="grey" />
          </div>
        </div>
      </section>

      <section style={{ padding: '20px 0 0', background: '#fff' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
          <div className="dash-grid" style={{
            display: 'grid', gridTemplateColumns: 'minmax(0, 1.05fr) minmax(0, 0.95fr)', gap: 22, marginTop: 20,
          }}>
            <ChartCard
              title="Participation by outlet"
              sub="How predictions split across the four SunFront outlets."
            >
              <OutletBars data={DASHBOARD.byOutlet} />
            </ChartCard>

            <ChartCard
              title="Daily participation"
              sub="Last 14 days · cumulative count of predictions received."
            >
              <DailySparkline data={DASHBOARD.daily} />
            </ChartCard>
          </div>

          <div style={{ marginTop: 22 }}>
            <ChartCard
              title="Match-by-match split"
              sub="Where the crowd is putting its money for each tracked match."
            >
              <MatchSplit rows={DASHBOARD.byMatch} />
            </ChartCard>
          </div>

          <p style={{
            marginTop: 28, fontSize: 12, color: 'var(--grey-500)', textAlign: 'center',
          }}>
            Auto-refreshes every 30 seconds · No personal data is ever displayed on this page.
          </p>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { DashboardPage });
