// screen-analysis.jsx — Analysis v2.1. All charts are interactive: tap or drag
// across any chart and the numbers update live, so you can pinpoint exactly
// what happened and when. Minimal words, big glyphs.
//
// Layout (top → bottom):
//   1. Range toggle (Day / Week / Month)
//   2. Hero chart — scrub the bars, big $ + kWh follows your finger
//   3. "Where it goes" — split bar + appliance tiles → tap = detail sheet
//   4. "Watt found" — swipeable personalised insight cards

const ANALYSIS_DATA = {
  day:   { kwh: 8.4,  prev: 9.6,  period: 'Today',
           bars: [0.4,0.3,0.3,0.2,0.2,0.3,0.5,1.2,0.8,0.6,0.5,0.5,0.6,0.7,0.7,0.6,0.5,0.6,0.8,1.4,1.2,1.0,0.7,0.5],
           xLabels: ['12am','6am','12pm','6pm','12am'], compare: 11.2 },
  week:  { kwh: 56.7, prev: 64.3, period: 'This week',
           bars: [9.2,10.8,8.4,9.6,11.2,7.8,7.5,8.4],
           xLabels: ['M','T','W','T','F','S','S','M'], compare: 78.4 },
  month: { kwh: 247,  prev: 312,  period: 'This month',
           bars: [56,62,58,71],
           xLabels: ['W1','W2','W3','W4'], compare: 348 },
  sixmo: { kwh: 1193, prev: 1420, period: 'Last 6 months',
           bars: [240,227,203,193,173,157],
           xLabels: ['Feb','Mar','Apr','May','Jun','Jul'], compare: 1480 },
};

const AN_HOURS = Array.from({ length: 24 }, (_, i) =>
  i === 0 ? '12am' : i < 12 ? `${i}am` : i === 12 ? '12pm' : `${i - 12}pm`);

const AN_PREV_WORD = { day: 'than yesterday', week: 'than last week', month: 'than last month', sixmo: 'than the 6 months before' };

const AN_RANGE_LABELS = { day: 'Day', week: 'Week', month: 'Month', sixmo: '6 mo' };

const AN_BAR_LABELS = {
  day:   AN_HOURS,
  week:  ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon'],
  month: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
  sixmo: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
};

// Appliance split — consistent across ranges for the prototype.
const AN_APPLIANCES = [
  { id: 'ac',     name: 'Aircon',       Icon: IcAC,     pct: 52, tone: 'primary', runtime: '6h 12m', peak: '8–11pm',
    bars: [1,1,1,0,0,0,0,0,0,0,1,2,3,3,2,2,2,3,5,8,9,8,5,2],
    tips: ['25°C, not 22°C', 'Timer off at 1am', 'Clean filter monthly'] },
  { id: 'water',  name: 'Water heater', Icon: IcWater,  pct: 30, tone: 'sky',     runtime: '38m',    peak: '6–8am',
    bars: [0,0,0,0,0,2,8,9,3,0,0,0,0,0,0,0,0,0,2,4,3,1,0,0],
    tips: ['Heat 30 min before shower', 'Set to 50°C'] },
  { id: 'fridge', name: 'Fridge',       Icon: IcFridge, pct: 12, tone: 'sand',    runtime: '24h',    peak: 'all day',
    bars: [2,2,2,2,2,2,2,2,3,3,3,3,4,4,3,3,3,3,4,4,3,3,2,2],
    tips: ['Keep at 4°C', 'Defrost when ice > 5mm'] },
  { id: 'other',  name: 'Other',        Icon: IcBolt,   pct: 6,  tone: 'accent',  runtime: '—',      peak: 'evenings',
    bars: [1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,4,4,4,3,2,1],
    tips: ['Unplug standby devices'] },
];

// Personalised insights — things the user hasn't thought about.
const AN_INSIGHTS = [
  { id: 'i1', Icon: IcClock,  tone: 'accent',  head: 'Aircon runs 2h after you sleep', save: '$9/mo',   hint: 'Set a 1am timer' },
  { id: 'i2', Icon: IcFridge, tone: 'sand',    head: 'Fridge works 12% harder than May', save: '$2/mo', hint: 'Check the door seal' },
  { id: 'i3', Icon: IcWind,   tone: 'primary', head: 'Nights are 27°C this week', save: '$4/mo',        hint: 'Windows beat aircon before 9pm' },
  { id: 'i4', Icon: IcUsers,  tone: 'sky',     head: 'Your Saturdays spike at noon', save: '$3/mo',     hint: 'Neighbours cook before the heat' },
];

// 6-month bill trend now lives in the hero chart as the "6 mo" range.

// ── AnBars — shared interactive bar chart. Tap a bar or drag across the
//    whole chart; reports the index via onPick. Vertical page scroll still
//    works (touchAction: pan-y).
function AnBars({ bars, sel, onPick, height, gap = 4, radius = 4, colorFor, overlay }) {
  const ref = React.useRef(null);
  const max = Math.max(...bars) || 1;  // avoid divide-by-zero on all-zero (sparse real) data
  const pick = (clientX) => {
    const r = ref.current.getBoundingClientRect();
    return Math.min(bars.length - 1, Math.max(0, Math.floor((clientX - r.left) / r.width * bars.length)));
  };
  return (
    <div ref={ref}
      onPointerDown={(e) => { e.currentTarget.setPointerCapture?.(e.pointerId); onPick(pick(e.clientX)); }}
      onPointerMove={(e) => { if (e.buttons > 0) onPick(pick(e.clientX)); }}
      style={{ height, display: 'flex', alignItems: 'flex-end', gap, position: 'relative', touchAction: 'pan-y', cursor: 'pointer' }}>
      {overlay}
      {bars.map((v, i) => {
        const isSel = sel === i;
        const dim = sel != null && !isSel;
        return (
          <div key={i} style={{
            flex: 1, height: Math.max(4, (v / max) * (height - 18)),
            background: colorFor(i, isSel),
            borderRadius: radius,
            opacity: dim ? 0.35 : 1,
            transition: 'opacity .15s',
          }}></div>
        );
      })}
    </div>
  );
}

// Small ✕ pill to clear a chart selection.
function AnClear({ c, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 22, height: 22, borderRadius: 999, border: 'none', background: c.surfaceAlt,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0,
    }}><IcX size={12} color={c.textMuted} /></button>
  );
}

// Turn a GET /household/usage/history response
//   { range, bucket:"hour"|"day", series:[{ device_id, bucket_start, kwh }] }
// into the shape the hero chart consumes: total kWh per time-bucket (summed
// across devices), axis + per-bar labels, and the period total. Returns null if
// there's nothing to show, so the caller can fall back to the sample data.
function buildFromHistory(resp, apiRange) {
  const series = (resp && resp.series) || [];
  const byBucket = new Map();
  for (const row of series) {
    byBucket.set(row.bucket_start, (byBucket.get(row.bucket_start) || 0) + (row.kwh || 0));
  }
  const buckets = [...byBucket.keys()].sort();  // ISO strings sort chronologically
  if (!buckets.length) return null;
  const bars = buckets.map((b) => +byBucket.get(b).toFixed(3));
  const kwh = +bars.reduce((s, v) => s + v, 0).toFixed(3);
  const isHour = (resp && resp.bucket) === 'hour';
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  // Parse straight from the string — timestamps are already truncated to SGT,
  // so avoid Date() timezone shifts.
  const fmt = (iso) => {
    if (isHour) {
      let h = parseInt(iso.slice(11, 13), 10);
      const ap = h < 12 ? 'am' : 'pm';
      h = h % 12 || 12;
      return h + ap;
    }
    return MON[parseInt(iso.slice(5, 7), 10) - 1] + ' ' + parseInt(iso.slice(8, 10), 10);
  };
  const barLabels = buckets.map(fmt);
  // ~5 evenly spaced axis ticks regardless of how many buckets came back.
  const n = buckets.length;
  const ticks = Math.min(5, n);
  const xLabels = [];
  for (let i = 0; i < ticks; i++) {
    xLabels.push(fmt(buckets[Math.round((i * (n - 1)) / (ticks - 1 || 1))]));
  }
  const period = { '24h': 'Last 24 hours', '7d': 'Last 7 days', '30d': 'Last 30 days' }[apiRange] || 'Usage';
  return { bars, xLabels, barLabels, kwh, period, real: true, prev: null, compare: null };
}

function AnalysisScreen({ c }) {
  const [range, setRangeRaw] = React.useState('week');
  const [compare, setCompare] = React.useState(false);
  const [sel, setSel] = React.useState(null);        // appliance detail sheet
  const [heroSel, setHeroSel] = React.useState(null); // hero chart scrub
  const setRange = (r) => { setRangeRaw(r); setHeroSel(null); };

  // Real usage history for the hero chart. Day/Week/Month map to the API's
  // 24h/7d/30d; "6 mo" has no API equivalent so it stays on the sample data.
  // Falls back to the design's sample data until a range loads (or if it fails).
  const apiRange = { day: '24h', week: '7d', month: '30d' }[range];
  const [history, setHistory] = React.useState({});
  React.useEffect(() => {
    if (!apiRange || history[apiRange] !== undefined) return;  // unsupported range, or already fetched
    let alive = true;
    SaveHorAPI.getUsageHistory(apiRange)
      .then((resp) => { if (alive) setHistory((h) => ({ ...h, [apiRange]: buildFromHistory(resp, apiRange) })); })
      .catch(() => { if (alive) setHistory((h) => ({ ...h, [apiRange]: null })); });  // remember failure; don't refetch
    return () => { alive = false; };
  }, [apiRange]);

  const data = (apiRange && history[apiRange]) || ANALYSIS_DATA[range];
  const change = data.prev ? ((data.kwh - data.prev) / data.prev * 100) : 0;
  const dollars = data.kwh * 0.30;
  const maxIdx = data.bars.indexOf(Math.max(...data.bars));

  // Hero readout — total, or the scrubbed bar.
  const heroKwh = heroSel == null ? data.kwh : data.bars[heroSel];
  const heroLbl = heroSel == null ? data.period
    : (data.barLabels ? data.barLabels[heroSel] : AN_BAR_LABELS[range][heroSel]);

  return (
    <div data-screen-label="Analysis" style={{ display: 'flex', flexDirection: 'column', gap: 18, paddingBottom: 100 }}>
      <Header c={c} big title="Analysis" />

      {/* 1 · RANGE TOGGLE */}
      <div style={{ padding: '0 20px' }}>
        <div style={{ display: 'flex', background: c.surfaceAlt, padding: 4, borderRadius: 12, gap: 2 }}>
          {['day', 'week', 'month', 'sixmo'].map(r => (
            <button key={r} onClick={() => setRange(r)} style={{
              flex: 1, height: 38, border: 'none', borderRadius: 9,
              background: range === r ? c.surface : 'transparent',
              color: range === r ? c.text : c.textMuted,
              fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
              boxShadow: range === r ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
              cursor: 'pointer',
            }}>{AN_RANGE_LABELS[r]}</button>
          ))}
        </div>
      </div>

      {/* 2 · HERO CHART — scrub to inspect */}
      <div style={{ padding: '0 20px' }}>
        <AnSectionHd c={c} title="What you used" />
        <Card c={c} style={{ padding: '18px 20px', marginTop: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: heroSel == null ? c.textLight : c.primaryDk, letterSpacing: 0.4, textTransform: 'uppercase' }}>{heroLbl}</span>
            {heroSel != null && <AnClear c={c} onClick={() => setHeroSel(null)} />}
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
            <span style={{ fontSize: 36, fontWeight: 700, color: c.text, letterSpacing: -0.8, fontVariantNumeric: 'tabular-nums' }}>${(heroKwh * 0.30).toFixed(2)}</span>
            <span style={{ fontSize: 14, fontWeight: 600, color: c.textMuted, fontVariantNumeric: 'tabular-nums' }}>{heroKwh} kWh</span>
          </div>
          {heroSel == null && data.prev != null && (
            <div style={{ marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 999, background: change < 0 ? c.goodSoft : c.warnSoft }}>
              {change < 0 ? <IcArrowD size={12} color="#2F6147" /> : <IcArrowU size={12} color="#7C5A1B" />}
              <span style={{ fontSize: 12.5, fontWeight: 700, color: change < 0 ? '#2F6147' : '#7C5A1B', fontVariantNumeric: 'tabular-nums' }}>
                ${Math.abs((data.kwh - data.prev) * 0.30).toFixed(2)} {change < 0 ? 'less' : 'more'} {AN_PREV_WORD[range]}
              </span>
            </div>
          )}

          <div style={{ marginTop: 18 }}>
            <AnBars
              bars={data.bars}
              sel={heroSel}
              onPick={setHeroSel}
              height={120}
              gap={range === 'day' ? 2 : range === 'sixmo' ? 10 : 6}
              radius={range === 'day' ? 1.5 : range === 'sixmo' ? 6 : 4}
              colorFor={(i, isSel) => isSel ? c.accent : i === maxIdx ? c.accent : c.primary}
              overlay={compare && data.compare != null && (
                <div style={{ position: 'absolute', left: 0, right: 0, top: 120 - (data.compare / data.bars.length / Math.max(...data.bars)) * 102, height: 0, borderTop: `1.5px dashed ${c.sky}`, zIndex: 1, pointerEvents: 'none' }}>
                  <div style={{ position: 'absolute', right: 0, top: -16, fontSize: 10.5, fontWeight: 600, color: c.sky, background: c.surface, padding: '0 4px' }}>Neighbours</div>
                </div>
              )}
            />
            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 500, color: c.textLight }}>
              {data.xLabels.map((l, i) => <span key={i}>{l}</span>)}
            </div>
          </div>

          {/* compare pill — hidden on real data (the history endpoint has no
              neighbours benchmark; this stays with the sample-data ranges) */}
          {!data.real && (
          <button onClick={() => setCompare(!compare)} style={{
            marginTop: 14, height: 36, padding: '0 14px',
            border: `1px solid ${compare ? c.sky : c.borderSoft}`,
            background: compare ? c.skySoft : 'transparent',
            borderRadius: 999, fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            color: compare ? '#345070' : c.textMuted, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            <IcUsers size={15} color={compare ? '#345070' : c.textMuted} />
            Neighbours
          </button>
          )}
        </Card>
      </div>

      {/* 3 · WHERE IT GOES */}
      <div style={{ padding: '0 20px' }}>
        <AnSectionHd c={c} title="Where it goes" />
        {/* split bar — styled like the Home battery; tap a segment to open that appliance */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 10 }}>
          <div style={{
            flex: 1, height: 48, display: 'flex', gap: 3,
            background: c.surfaceAlt, border: `2.5px solid ${c.border}`,
            borderRadius: 16, padding: 4, boxSizing: 'border-box', overflow: 'hidden',
          }}>
            {AN_APPLIANCES.map(a => {
              const t = anTone(c, a.tone);
              return (
                <div key={a.id} onClick={() => setSel(a)} style={{
                  width: `${a.pct}%`, background: t.bar, borderRadius: 10, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {a.pct >= 12 && (
                    <div style={{ width: 24, height: 24, borderRadius: 7, background: 'rgba(255,255,255,0.28)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <a.Icon size={15} color="#fff" />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
          {/* terminal nub */}
          <div style={{ width: 7, height: 20, background: c.border, borderRadius: 3, flexShrink: 0 }} />
        </div>
        {/* appliance tiles */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 10 }}>
          {AN_APPLIANCES.map(a => {
            const t = anTone(c, a.tone);
            return (
              <button key={a.id} onClick={() => setSel(a)} style={{
                background: c.surface, border: `1.5px solid ${c.borderSoft}`, borderRadius: 16,
                padding: '13px 12px', fontFamily: 'inherit', cursor: 'pointer', textAlign: 'center',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                WebkitTapHighlightColor: 'transparent',
              }}>
                <div style={{ width: 46, height: 46, borderRadius: 14, background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <a.Icon size={26} color={t.fg} />
                </div>
                <div style={{ fontSize: 14, fontWeight: 700, color: c.text, letterSpacing: -0.2 }}>{a.name}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
                  <span style={{ fontSize: 15, fontWeight: 800, color: c.text, fontVariantNumeric: 'tabular-nums' }}>${(dollars * a.pct / 100).toFixed(2)}</span>
                  <span style={{ fontSize: 12, fontWeight: 700, color: t.fg, fontVariantNumeric: 'tabular-nums' }}>{a.pct}%</span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* 4 · WATT FOUND — personalised insights */}
      <div>
        <div style={{ padding: '0 20px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Watt size={26} color={c.primary} bg={c.primarySoft} mood="happy" />
          <AnSectionHd c={c} title="Watt found" />
        </div>
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', padding: '10px 20px 4px', scrollSnapType: 'x mandatory' }} className="an-scroll">
          {AN_INSIGHTS.map(ins => {
            const t = anTone(c, ins.tone);
            return (
              <div key={ins.id} style={{
                flex: '0 0 200px', scrollSnapAlign: 'start',
                background: c.surface, border: `1.5px solid ${c.borderSoft}`, borderRadius: 16,
                padding: '14px 14px 13px', display: 'flex', flexDirection: 'column', gap: 10,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ width: 40, height: 40, borderRadius: 12, background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <ins.Icon size={22} color={t.fg} />
                  </div>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 12, fontWeight: 800, color: c.primaryDk, background: c.primarySoft, padding: '4px 8px', borderRadius: 999, fontVariantNumeric: 'tabular-nums' }}>
                    <IcCoins size={11} color={c.primary} />{ins.save}
                  </span>
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: c.text, lineHeight: 1.25, letterSpacing: -0.2 }}>{ins.head}</div>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: c.textMuted, lineHeight: 1.35, marginTop: 'auto' }}>{ins.hint}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* APPLIANCE DETAIL SHEET */}
      {sel && <ApplianceSheet c={c} a={sel} dollars={dollars} onClose={() => setSel(null)} />}
    </div>
  );
}

function AnSectionHd({ c, title, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <div style={{ fontSize: 17, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>{title}</div>
      {sub && <div style={{ fontSize: 12, fontWeight: 500, color: c.textLight }}>{sub}</div>}
    </div>
  );
}

function anTone(c, tone) {
  return {
    primary: { bg: c.primarySoft, fg: c.primary,  bar: c.primary },
    sky:     { bg: c.skySoft,     fg: '#345070',  bar: c.sky },
    sand:    { bg: c.sand,        fg: '#5A4A22',  bar: c.sandDk },
    accent:  { bg: c.accentSoft,  fg: '#8A5A1E',  bar: c.accent },
  }[tone];
}

// Bottom sheet — per-appliance detail. The "when it runs" chart is scrubbable:
// drag across it to see the share of the day at each hour.
function ApplianceSheet({ c, a, dollars, onClose }) {
  const t = anTone(c, a.tone);
  const [hr, setHr] = React.useState(null);
  const sum = a.bars.reduce((s, v) => s + v, 0);
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,30,25,0.4)', zIndex: 100, display: 'flex', alignItems: 'flex-end', animation: 'm-fadeup .2s ease' }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: c.surface, borderRadius: '24px 24px 0 0',
        padding: '20px 24px 32px', display: 'flex', flexDirection: 'column', gap: 16,
        animation: 'sh-slideup 0.24s ease',
      }}>
        <div style={{ width: 36, height: 4, background: c.border, borderRadius: 2, alignSelf: 'center' }}></div>

        {/* head */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <a.Icon size={30} color={t.fg} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 20, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>{a.name}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
              <span style={{ fontSize: 17, fontWeight: 800, color: c.text, fontVariantNumeric: 'tabular-nums' }}>${(dollars * a.pct / 100).toFixed(2)}</span>
              <span style={{ fontSize: 13, fontWeight: 600, color: c.textMuted }}>· {a.pct}% of home</span>
            </div>
          </div>
        </div>

        {/* when it runs — scrubbable 24h bars */}
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: c.textLight, letterSpacing: 0.4, textTransform: 'uppercase' }}>When it runs</div>
            {hr == null ? (
              <span style={{ fontSize: 12, fontWeight: 700, color: c.textMuted }}>Peak {a.peak}</span>
            ) : (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 800, color: c.primaryDk, fontVariantNumeric: 'tabular-nums' }}>{AN_HOURS[hr]} · {sum ? Math.round(a.bars[hr] / sum * 100) : 0}%</span>
                <AnClear c={c} onClick={() => setHr(null)} />
              </span>
            )}
          </div>
          <AnBars
            bars={a.bars}
            sel={hr}
            onPick={setHr}
            height={60}
            gap={2}
            radius={2}
            colorFor={(i, isSel) => isSel ? c.accent : t.bar}
          />
          <div style={{ marginTop: 6, display: 'flex', justifyContent: 'space-between', fontSize: 10.5, fontWeight: 500, color: c.textLight }}>
            <span>12am</span><span>6am</span><span>12pm</span><span>6pm</span><span>12am</span>
          </div>
        </div>

        {/* stats */}
        <div style={{ display: 'flex', gap: 8 }}>
          {[['Runtime', a.runtime], ['Peak', a.peak]].map(([k, v]) => (
            <div key={k} style={{ flex: 1, background: c.surfaceAlt, borderRadius: 12, padding: '10px 12px' }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: c.textLight, letterSpacing: 0.4, textTransform: 'uppercase' }}>{k}</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: c.text, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{v}</div>
            </div>
          ))}
        </div>

        {/* tips — short */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {a.tips.map((tip, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, background: c.primarySoft, borderRadius: 12, padding: '10px 12px' }}>
              <IcSparkle size={15} color={c.primary} />
              <span style={{ fontSize: 13.5, fontWeight: 600, color: c.primaryDk }}>{tip}</span>
            </div>
          ))}
        </div>

        <Btn kind="primary" size="lg" full c={c} onClick={onClose}>Done</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { AnalysisScreen, ApplianceSheet, AnBars, AnClear });
