Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

156 KB
Raw Blame
<!doctype html>
<html lang="en" data-theme="dark">
<head>
  <meta charset="utf-8">
  <title>Phosphene · stats</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="robots" content="noindex,nofollow">
  <link rel="icon" type="image/svg+xml" href="/assets/phosphene_favicon.svg">
  <link rel="icon" type="image/png" sizes="64x64" href="/assets/phosphene_favicon_64.png">
  <!--
    Phosphene repo-stats dashboard.

    Served BY THE PANEL at http://127.0.0.1:8199/stats. The HTML
    template lives at panel_assets/stats.html and is read at request
    time; the JSONL data is appended daily by the maintainer's launchd
    job (or by the panel's stats_fetch_loop, opt-in only with
    PHOSPHENE_STATS_FETCH=1) and persisted at
    state/stats-data.jsonl (gitignored — never on the public repo).
    Both endpoints are 127.0.0.1-only.

    Pure vanilla — single file, no build, no framework. Chart.js from
    CDN is the only outside dep.

    Feature-detects every optional field the fetcher may add over time:
      - clones_window, views_window     — 15d rolling per-day arrays
      - stars_timeline                  — cumulative {date,count} per day
      - forks_timeline                  — cumulative {date,count} per day
      - issues_opened / issues_closed   — daily {date,count}
      - prs_opened    / prs_closed      — daily {date,count}
      - commits_timeline                — daily {date,count}
      - release_timeline                — [{tag, published_at, total_downloads}]
    Anything else unknown is ignored gracefully.

    Visual identity: matches the Phosphene panel. Dark only (no light
    theme — Phosphene has none). Trademark pink→purple→cyan gradient is
    used sparingly: the wordmark in the header and the headline
    "growth" number on the right-now strip. Everything else uses the
    blue accent so the gradient stays special.
  -->
  <style>
    /* ============================================================
       Phosphene design tokens — kept 1:1 with mlx_ltx_panel.py so
       the dashboard reads as the same product, not a sibling site.
       ============================================================ */
    :root {
      --bg:            #0a0a0b;
      --bg-2:          #0e0e10;
      --panel:         #121214;
      --panel-2:       #1f1f23;
      --panel-3:       rgba(16, 16, 17, 0.35);
      --border:        #2a2a2f;
      --border-soft:   rgba(140, 160, 220, 0.08);
      --border-strong: #3a3a40;
      --text:          #f4f4f5;
      --muted:         #b4b4bb;
      --faint:         #6b6b73;
      --accent:        #2f81f7;
      --accent-bright: #58a6ff;
      --accent-dim:    rgba(47, 129, 247, 0.18);
      --success:       #3fb950;
      --warning:       #d29922;
      --danger:        #f85149;
      /* Signature gradient — pink → purple → cyan. Used only on
         the wordmark + one hero KPI to keep it special. */
      --ph-grad-pink:   #FF2E9F;
      --ph-grad-purple: #B14AFF;
      --ph-grad-cyan:   #5EEAFF;
      --ph-grad: linear-gradient(90deg,
                  var(--ph-grad-pink)   0%,
                  var(--ph-grad-purple) 50%,
                  var(--ph-grad-cyan)   100%);
      --ph-grad-soft: linear-gradient(135deg,
                  rgba(255, 46, 159, 0.18),
                  rgba(177, 74, 255, 0.18),
                  rgba(94, 234, 255, 0.18));
      --ph-font-mono: "SF Mono", "JetBrains Mono", ui-monospace, Menlo, monospace;
      --shadow-1: 0 1px 2px rgba(0,0,0,0.30), 0 1px 0 rgba(255,255,255,0.02) inset;
      --shadow-2: 0 8px 24px rgba(0,0,0,0.40);
      --r-xs: 6px;
      --r-sm: 8px;
      --r-md: 10px;
      --r-lg: 14px;
      --r-pill: 999px;
      --t-fast: 120ms cubic-bezier(.2,.8,.2,1);
      --t-base: 180ms cubic-bezier(.2,.8,.2,1);
    }

    * { box-sizing: border-box; }
    html, body { margin: 0; padding: 0; height: 100%; }
    body {
      background: var(--bg);
      background-image:
        radial-gradient(ellipse 1200px 600px at 50% -10%,
                        rgba(47, 129, 247, 0.08), transparent 60%),
        radial-gradient(ellipse 900px 500px at 85% 10%,
                        rgba(255, 255, 255, 0.040), transparent 65%);
      background-attachment: fixed;
      color: var(--text);
      font: 13px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text",
            "Segoe UI", system-ui, sans-serif;
      min-height: 100vh;
      -webkit-font-smoothing: antialiased;
    }
    a { color: var(--accent-bright); text-decoration: none; }
    a:hover { text-decoration: underline; }
    :focus { outline: none; }
    :focus-visible {
      outline: 2px solid var(--accent-bright);
      outline-offset: 2px;
      border-radius: var(--r-xs);
    }
    @media (prefers-reduced-motion: reduce) {
      *, *::before, *::after {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
      }
    }

    .wrap { max-width: 1200px; margin: 0 auto; padding: 28px 24px 80px; }

    /* ============================================================
       HEADER — wordmark in the trademark gradient, meta strip below.
       ============================================================ */
    header.hero {
      margin-bottom: 22px;
    }
    .hero-top {
      display: flex; align-items: center; justify-content: space-between;
      gap: 16px; flex-wrap: wrap;
    }
    .wordmark {
      display: inline-flex; align-items: baseline; gap: 10px;
      text-decoration: none;
    }
    .wordmark .mark {
      font-size: 30px; font-weight: 700;
      letter-spacing: -0.02em; line-height: 1;
      background: var(--ph-grad);
      -webkit-background-clip: text;
              background-clip: text;
      -webkit-text-fill-color: transparent;
              color: transparent;
      filter: drop-shadow(0 0 18px rgba(177, 74, 255, 0.25));
    }
    .wordmark .sep {
      color: var(--faint); font-size: 22px; font-weight: 300; line-height: 1;
    }
    .wordmark .what {
      color: var(--muted); font-size: 14px; font-weight: 500;
      letter-spacing: 0.01em;
    }
    .hero-actions {
      display: inline-flex; align-items: center; gap: 8px; flex-shrink: 0;
    }
    .icon-btn {
      display: inline-flex; align-items: center; gap: 6px;
      background: var(--panel);
      border: 1px solid var(--border);
      color: var(--muted);
      font: inherit; font-size: 12px;
      padding: 7px 12px; border-radius: var(--r-sm);
      cursor: pointer;
      transition: background var(--t-base), color var(--t-base), border-color var(--t-base);
      text-decoration: none;
    }
    .icon-btn:hover {
      background: var(--panel-2);
      color: var(--text);
      border-color: var(--border-strong);
      text-decoration: none;
    }
    .icon-btn.is-busy { opacity: 0.6; pointer-events: none; }
    .icon-btn .ico { font-family: var(--ph-font-mono); font-size: 13px; line-height: 1; }
    .sub-meta {
      margin-top: 12px;
      display: flex; align-items: center; gap: 14px; flex-wrap: wrap;
      color: var(--muted); font-size: 12px;
    }
    .sub-meta .lock {
      display: inline-flex; align-items: center; gap: 5px;
      padding: 3px 9px; border-radius: var(--r-pill);
      background: rgba(63, 185, 80, 0.08);
      border: 1px solid rgba(63, 185, 80, 0.30);
      color: var(--success);
      font-size: 11px; font-weight: 500;
      letter-spacing: 0.01em;
    }
    .sub-meta .lock .ico { font-size: 10px; }
    .sub-meta .dot-sep { color: var(--faint); }
    .sub-meta strong { color: var(--text); font-weight: 600; }
    .hero-underline {
      margin-top: 14px;
      height: 1px;
      background: linear-gradient(90deg,
        rgba(255, 255, 255, 0.000),
        rgba(255, 46, 159, 0.45) 12%,
        rgba(177, 74, 255, 0.55) 50%,
        rgba(94, 234, 255, 0.45) 88%,
        rgba(255, 255, 255, 0.000));
    }

    /* ============================================================
       Generic section styling.
       ============================================================ */
    section.card {
      background: var(--panel);
      border: 1px solid var(--border);
      border-radius: var(--r-lg);
      padding: 20px 22px;
      margin-bottom: 18px;
      box-shadow: var(--shadow-1);
    }
    .section-head {
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; flex-wrap: wrap;
      margin-bottom: 16px;
    }
    h2 {
      font-size: 11px; font-weight: 600; text-transform: uppercase;
      letter-spacing: 0.10em; color: var(--muted);
      margin: 0;
      /* Flex children default to a min-width equal to their content's
         intrinsic (unwrapped) width, which is what let a long .h2-sub
         string push past the viewport edge on narrow screens instead of
         wrapping — this is the fix, not a width on the child. */
      min-width: 0;
    }
    h2 .h2-sub {
      margin-left: 8px;
      color: var(--faint);
      font-weight: 500;
      text-transform: none;
      letter-spacing: 0.02em;
    }
    h3 {
      font-size: 11px; font-weight: 600; text-transform: uppercase;
      letter-spacing: 0.08em; color: var(--muted);
      margin: 0 0 10px;
    }

    /* ============================================================
       Period chips (and any other chip groups).
       ============================================================ */
    .chips {
      display: inline-flex; flex-wrap: wrap; gap: 2px;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-pill);
      padding: 3px;
    }
    .chip {
      background: transparent; border: 0;
      color: var(--muted);
      font: inherit; font-size: 11px; font-weight: 500;
      padding: 4px 12px; border-radius: var(--r-pill);
      cursor: pointer;
      transition: background var(--t-fast), color var(--t-fast);
      font-family: var(--ph-font-mono);
      letter-spacing: 0.04em;
    }
    .chip:hover { color: var(--text); }
    .chip[aria-pressed="true"] {
      background: var(--accent-dim);
      color: var(--accent-bright);
    }

    /* ============================================================
       Global range bar — ONE control (7d/30d/90d/all) that every
       panel on the page reads. Sits right under the header so it
       reads as governing everything below it.
       ============================================================ */
    .range-bar {
      display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
      margin: 0 0 18px; padding: 10px 14px;
      background: var(--bg-2); border: 1px solid var(--border);
      border-radius: var(--r-md);
    }
    .range-bar-label {
      font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted); font-weight: 600;
    }
    .range-bar .chip { font-size: 12px; padding: 5px 14px; }
    .range-bar-hint {
      font-size: 11.5px; color: var(--faint); margin-left: auto;
    }
    @media (max-width: 600px) {
      .range-bar { padding: 8px 10px; gap: 8px; }
      .range-bar-hint { margin-left: 0; flex-basis: 100%; }
    }

    /* ============================================================
       "Right now" KPI strip.
       ============================================================ */
    .kpi-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
      gap: 12px;
    }
    .kpi {
      position: relative;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      padding: 14px 16px;
      overflow: hidden;
      transition: border-color var(--t-base), transform var(--t-base);
    }
    .kpi:hover { border-color: var(--border-strong); }
    .kpi .label {
      color: var(--muted);
      font-size: 10.5px; text-transform: uppercase;
      letter-spacing: 0.08em; font-weight: 600;
    }
    .kpi .value {
      margin-top: 6px;
      font-size: 26px; font-weight: 700; line-height: 1.05;
      font-family: var(--ph-font-mono);
      letter-spacing: -0.02em;
      font-variant-numeric: tabular-nums;
      color: var(--text);
    }
    .kpi.is-hero .value {
      font-size: 32px;
      background: var(--ph-grad);
      -webkit-background-clip: text;
              background-clip: text;
      -webkit-text-fill-color: transparent;
              color: transparent;
    }
    /* A hero that cannot be answered must not look like a zero, and must not
       wear the brand gradient as if it were a result: muted, plain, and its
       caption carries the remedy rather than a unit. */
    .kpi.is-hero.is-unknown .value {
      background: none;
      -webkit-text-fill-color: initial;
      color: var(--muted, #8b93a7);
    }
    .kpi.is-unknown .delta { color: var(--warn, #d29922); }
    .kpi .deltas {
      display: flex; gap: 10px; flex-wrap: wrap;
      margin-top: 8px;
      font-size: 11px;
      font-family: var(--ph-font-mono);
    }
    .kpi .delta { color: var(--faint); display: inline-flex; gap: 4px; align-items: baseline; }
    .kpi .delta .lbl {
      color: var(--faint); text-transform: uppercase;
      font-size: 9.5px; letter-spacing: 0.06em;
    }
    .kpi .delta.up   { color: var(--success); }
    .kpi .delta.down { color: var(--danger); }
    .kpi .spark {
      position: absolute;
      left: 0; right: 0; bottom: 0;
      height: 38px; width: 100%;
      pointer-events: none;
      opacity: 0.95;
    }
    .kpi.has-spark { padding-bottom: 40px; }

    /* Health pulse — small colored dot + pulse ring. */
    .kpi-pulse {
      grid-column: span 1;
    }
    .pulse {
      display: inline-flex; align-items: center; gap: 8px;
      margin-top: 8px;
    }
    .pulse-dot {
      position: relative;
      width: 10px; height: 10px; border-radius: 50%;
      background: var(--muted);
      box-shadow: 0 0 0 0 currentColor;
    }
    .pulse-dot.good { background: var(--success); color: rgba(63,185,80,0.6); animation: pulseRing 2.4s ease-out infinite; }
    .pulse-dot.warn { background: var(--warning); color: rgba(210,153,34,0.6); }
    .pulse-dot.bad  { background: var(--danger);  color: rgba(248,81,73,0.6);  animation: pulseRing 2.4s ease-out infinite; }
    @keyframes pulseRing {
      0%   { box-shadow: 0 0 0 0   currentColor; }
      70%  { box-shadow: 0 0 0 8px transparent;  }
      100% { box-shadow: 0 0 0 0   transparent;  }
    }
    .pulse-label {
      font-size: 13px; font-weight: 600; color: var(--text);
    }
    .pulse-detail {
      margin-top: 6px;
      font-size: 11px; color: var(--muted);
      font-family: var(--ph-font-mono);
    }

    /* ============================================================
       Funnel — Views → Clones → Stars → Forks.
       ============================================================ */
    .funnel {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 8px;
      align-items: stretch;
    }
    .funnel-step {
      position: relative;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      padding: 14px 16px 14px 18px;
      min-height: 84px;
      display: flex; flex-direction: column; justify-content: space-between;
      overflow: hidden;
    }
    .funnel-step::before {
      /* Fill bar — width set inline based on conversion. */
      content: '';
      position: absolute;
      left: 0; top: 0; bottom: 0;
      width: var(--fill, 100%);
      background: linear-gradient(90deg,
        rgba(47, 129, 247, 0.14),
        rgba(47, 129, 247, 0.02) 90%);
      z-index: 0;
    }
    .funnel-step.is-hero::before {
      background: linear-gradient(90deg,
        rgba(177, 74, 255, 0.16),
        rgba(255, 255, 255, 0.040) 90%);
    }
    .funnel-step > * { position: relative; z-index: 1; }
    .funnel-stage {
      font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted); font-weight: 600;
    }
    .funnel-stage .scope {
      color: var(--faint); font-weight: 500; margin-left: 4px;
    }
    .funnel-value {
      margin-top: 4px;
      font-size: 24px; font-weight: 700; color: var(--text);
      font-family: var(--ph-font-mono); font-variant-numeric: tabular-nums;
      letter-spacing: -0.01em;
    }
    .funnel-arrow {
      position: absolute;
      right: -10px; top: 50%; transform: translateY(-50%);
      z-index: 2;
      width: 20px; height: 20px;
      background: var(--panel);
      border: 1px solid var(--border);
      border-radius: 50%;
      display: inline-flex; align-items: center; justify-content: center;
      color: var(--muted);
      font-family: var(--ph-font-mono); font-size: 11px;
    }
    .funnel-conv {
      margin-top: 6px;
      font-size: 10.5px; color: var(--muted);
      font-family: var(--ph-font-mono);
    }
    .funnel-conv .pct { color: var(--text); font-weight: 600; }
    @media (max-width: 760px) {
      .funnel { grid-template-columns: repeat(2, 1fr); }
      .funnel-step:nth-child(2) .funnel-arrow { display: none; }
    }
    @media (max-width: 420px) {
      .funnel { grid-template-columns: 1fr; }
      .funnel-arrow { display: none; }
    }

    /* ============================================================
       Charts.
       ============================================================ */
    .chart-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 14px;
    }
    .chart-row + .chart-row { margin-top: 14px; }
    @media (max-width: 760px) { .chart-row { grid-template-columns: 1fr; } }
    .chart-card {
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      padding: 14px 16px;
    }
    .chart-card h3 {
      display: flex; align-items: center; justify-content: space-between;
      gap: 8px;
    }
    .chart-card .legend {
      display: inline-flex; gap: 10px; flex-wrap: wrap;
      font-size: 10px; font-weight: 500; color: var(--muted);
      text-transform: none; letter-spacing: 0.01em;
      font-family: var(--ph-font-mono);
    }
    .chart-card .legend .swatch {
      display: inline-block; width: 8px; height: 8px;
      border-radius: 2px; margin-right: 5px;
      vertical-align: middle;
    }
    .chart-wrap {
      position: relative; height: 180px;
    }
    .chart-wrap.tall { height: 220px; }
    .chart-empty {
      position: absolute; inset: 0;
      display: flex; align-items: center; justify-content: center;
      padding: 0 12px; text-align: center;
      color: var(--faint);
      font-size: 12px; font-style: italic;
      pointer-events: none;
    }

    /* ============================================================
       Tables (referrers, paths, releases).
       ============================================================ */
    .two-col {
      display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
    }
    /* The actual grid items are the two plain <div> wrappers (each holds
       an <h3> + .table-wrap) — min-width:0 on .table-wrap alone didn't
       reach them, so a wide table still forced the GRID ITEM wide, which
       forced the page into horizontal scroll on a phone. */
    .two-col > div { min-width: 0; }
    @media (max-width: 760px) { .two-col { grid-template-columns: 1fr; } }
    .table-wrap {
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      overflow-x: auto; overflow-y: hidden;
      /* Grid items default to a min-width equal to their content's
         intrinsic width — the same trap as flex children (see h2 above).
         A table with several columns refused to shrink below that width
         and pushed the whole PAGE into horizontal scroll on a phone.
         overflow-x:auto is the fallback for content that still doesn't
         fit even at min-width:0. */
      min-width: 0;
    }
    table {
      width: 100%; border-collapse: collapse; font-size: 12.5px;
    }
    thead th {
      text-align: left; padding: 9px 12px;
      color: var(--muted);
      text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em;
      font-weight: 600;
      border-bottom: 1px solid var(--border);
      background: var(--panel);
    }
    tbody td {
      padding: 9px 12px;
      border-bottom: 1px solid var(--border-soft);
      color: var(--text);
      vertical-align: middle;
    }
    tbody tr:last-child td { border-bottom: 0; }
    tbody tr:hover { background: rgba(140, 160, 220, 0.03); }
    td.num, th.num {
      text-align: right;
      font-family: var(--ph-font-mono);
      font-variant-numeric: tabular-nums;
    }
    /* Inline bar visualization inside a cell. */
    .row-bar {
      position: relative;
      display: inline-block;
      width: 110px; height: 6px;
      background: rgba(140, 160, 220, 0.08);
      border-radius: var(--r-pill);
      vertical-align: middle;
      margin-left: 8px;
    }
    .row-bar > i {
      position: absolute; left: 0; top: 0; bottom: 0;
      width: var(--w, 0%);
      background: var(--accent);
      border-radius: var(--r-pill);
    }
    .row-bar.gradient > i {
      background: var(--ph-grad);
    }
    .trend {
      display: inline-block;
      font-family: var(--ph-font-mono);
      font-size: 10.5px;
      margin-left: 6px;
    }
    .trend.up   { color: var(--success); }
    .trend.down { color: var(--danger); }
    .trend.flat { color: var(--faint); }
    .empty {
      color: var(--faint); font-style: italic; padding: 22px 0;
      text-align: center;
    }
    code, .mono {
      font-family: var(--ph-font-mono);
      font-size: 12px;
    }
    code {
      background: var(--bg-2);
      border: 1px solid var(--border);
      padding: 1px 6px; border-radius: 4px;
    }

    /* ============================================================
       Open items board — the live "what needs attention" list.
       Two columns (issues | PRs), each a stack of rows. Newest first.
       ============================================================ */
    .board {
      display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
    }
    @media (max-width: 760px) { .board { grid-template-columns: 1fr; } }
    .board-col { min-width: 0; }
    .board-col > h3 {
      display: flex; align-items: center; gap: 8px;
    }
    .board-col .count-pill {
      display: inline-flex; align-items: center; justify-content: center;
      min-width: 20px; height: 18px; padding: 0 6px;
      border-radius: var(--r-pill);
      background: var(--bg-2); border: 1px solid var(--border);
      color: var(--muted); font-size: 10.5px; font-weight: 700;
      font-family: var(--ph-font-mono); font-variant-numeric: tabular-nums;
      letter-spacing: 0;
    }
    .board-list {
      display: flex; flex-direction: column; gap: 7px;
      list-style: none; margin: 0; padding: 0;
    }
    .item {
      position: relative;
      display: block;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-left-width: 3px;
      border-radius: var(--r-md);
      padding: 11px 13px 11px 12px;
      text-decoration: none;
      color: var(--text);
      transition: border-color var(--t-base), background var(--t-base), transform var(--t-fast);
    }
    .item:hover {
      background: var(--panel-2);
      border-color: var(--border-strong);
      text-decoration: none;
      transform: translateY(-1px);
    }
    .item.is-issue { border-left-color: var(--success); }
    .item.is-pr    { border-left-color: var(--purple, #B14AFF); }
    .item.is-draft { border-left-color: var(--faint); }
    .item-top {
      display: flex; align-items: baseline; gap: 8px;
    }
    .item-badge {
      flex-shrink: 0;
      display: inline-flex; align-items: center; gap: 4px;
      padding: 2px 7px; border-radius: var(--r-pill);
      font-size: 9.5px; font-weight: 700; text-transform: uppercase;
      letter-spacing: 0.06em;
      font-family: var(--ph-font-mono);
      border: 1px solid transparent;
    }
    .item-badge.issue {
      color: var(--success);
      background: rgba(63, 185, 80, 0.10);
      border-color: rgba(63, 185, 80, 0.30);
    }
    .item-badge.pr {
      color: #c99bff;
      background: rgba(177, 74, 255, 0.12);
      border-color: rgba(177, 74, 255, 0.32);
    }
    .item-badge.draft {
      color: var(--muted);
      background: rgba(140, 160, 220, 0.08);
      border-color: var(--border);
    }
    .item-num {
      flex-shrink: 0;
      color: var(--faint);
      font-family: var(--ph-font-mono); font-size: 11.5px; font-weight: 600;
      font-variant-numeric: tabular-nums;
    }
    .item-title {
      flex: 1 1 auto; min-width: 0;
      color: var(--text);
      font-size: 12.5px; font-weight: 500; line-height: 1.4;
      /* Clamp to 2 lines so a very long title can't blow up a row. */
      display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
      overflow: hidden;
    }
    .item:hover .item-title { color: var(--accent-bright); }
    .item-meta {
      display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
      margin-top: 7px;
      color: var(--faint);
      font-size: 10.5px;
      font-family: var(--ph-font-mono);
    }
    .item-meta .who { color: var(--muted); }
    .item-meta .dot { color: var(--faint); opacity: 0.6; }
    .item-meta .comments { display: inline-flex; align-items: center; gap: 3px; }
    .item-labels {
      display: inline-flex; align-items: center; gap: 5px; flex-wrap: wrap;
    }
    .item-label {
      display: inline-flex; align-items: center;
      padding: 1px 7px; border-radius: var(--r-pill);
      font-size: 9.5px; font-weight: 600; line-height: 1.5;
      border: 1px solid var(--lc, var(--border));
      color: var(--lc, var(--muted));
      background: color-mix(in srgb, var(--lc, var(--border)) 12%, transparent);
      white-space: nowrap;
    }
    .board-more, .list-more {
      margin-top: 8px;
      color: var(--faint); font-size: 10.5px;
      font-family: var(--ph-font-mono);
      display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
    }
    .list-toggle { font-size: 11.5px; }
    .board-empty {
      display: flex; align-items: center; gap: 8px;
      padding: 18px 14px;
      background: var(--bg-2);
      border: 1px dashed var(--border);
      border-radius: var(--r-md);
      color: var(--muted); font-size: 12px;
    }
    .board-empty .ok { color: var(--success); font-size: 14px; }

    /* ============================================================
       USAGE — anonymous panel telemetry. Two possible sources, one
       renderer: the local mirror (state/usage-log.jsonl, always
       available) or the PostHog fleet rollup when a personal API key
       is configured. Deliberately the same card / KPI / list language
       as the GitHub sections above so the page reads as one dashboard
       rather than two bolted together.
       ============================================================ */
    .usage-note {
      display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
      margin: 0 0 14px;
      padding: 9px 12px;
      background: var(--bg-2);
      border: 1px dashed var(--border);
      border-radius: var(--r-md);
      color: var(--muted); font-size: 11.5px;
    }
    .usage-note .src {
      font-family: var(--ph-font-mono); font-size: 10px; font-weight: 700;
      text-transform: uppercase; letter-spacing: 0.08em;
      padding: 2px 7px; border-radius: var(--r-pill);
      background: var(--accent-dim); color: var(--accent-bright);
    }
    .usage-note.is-local .src { background: rgba(210,153,34,0.16); color: var(--warning); }
    .usage-alert {
      display: flex; align-items: center; gap: 9px;
      margin: 14px 0 0; padding: 11px 13px;
      border-radius: var(--r-md);
      background: rgba(248, 81, 73, 0.08);
      border: 1px solid rgba(248, 81, 73, 0.34);
      color: var(--text); font-size: 12.5px;
    }
    .usage-alert.is-clear {
      background: rgba(63, 185, 80, 0.06);
      border-color: rgba(63, 185, 80, 0.26);
      color: var(--muted);
    }
    .usage-alert .n {
      font-family: var(--ph-font-mono); font-weight: 700; color: var(--danger);
    }
    .usage-alert.is-clear .n { color: var(--success); }
    .dist-grid {
      display: grid; gap: 14px; margin-top: 16px;
      grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
    }
    .dist-col { min-width: 0; }
    .dist-col > h3 { display: flex; align-items: center; gap: 8px; }
    .dist-list {
      list-style: none; margin: 8px 0 0; padding: 0 4px 0 0;
      display: flex; flex-direction: column; gap: 6px;
      /* Capped + scrollable — "Failures by version" and friends can carry
         up to 12 rows (one closed error/version/chip taxonomy each), and
         without a cap the tallest column stretched the whole dist-grid
         row, leaving huge empty space under every shorter column next
         to it. */
      max-height: 300px; overflow-y: auto;
    }
    .dist-row {
      position: relative; overflow: hidden;
      display: grid; grid-template-columns: 1fr auto; gap: 10px;
      align-items: center;
      padding: 7px 11px;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-sm);
      font-size: 12px;
      /* .dist-list (the flex column these rows sit in) got a max-height +
         scroll further down. A flex item with overflow:hidden loses its
         normal min-height:auto protection (CSS Flexbox spec, 4.5) — so
         without this, the flex algorithm shrank each row to fit the
         constrained container instead of letting the container scroll,
         and a two-line stacked row (mobile .is-err) got clipped to about
         one line, silently hiding whichever half didn't fit. */
      flex-shrink: 0;
    }
    /* Proportional fill behind each row — same "bar in a table cell"
       idea the Traffic sources tables use, so the eye reads them alike. */
    .dist-row .fill {
      position: absolute; top: 0; bottom: 0; left: 0;
      background: var(--accent-dim);
      z-index: 0;
    }
    .dist-row .name, .dist-row .n { position: relative; z-index: 1; min-width: 0; }
    .dist-row .name {
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
      color: var(--text);
    }
    .dist-row.is-err {
      /* The base 1fr/auto split starves the name column whenever the
         value is a long sentence ("failed · 6.1% of 1,109 · 65
         installs") — "auto" claims whatever it wants first, so a short
         name like "4.12.2" got squeezed into a sliver and word-break
         wrapped it one character per line. Give the name a guaranteed
         max-content column instead and let the (already-wrappable)
         value take the rest. */
      grid-template-columns: minmax(60px, max-content) 1fr;
    }
    .dist-row.is-err .name {
      font-family: var(--ph-font-mono); font-size: 11px; color: var(--muted);
      white-space: normal; word-break: break-word;
      /* The base .dist-row .name rule sets overflow:hidden for its
         single-line ellipsis truncation — irrelevant once wrapping is
         turned back on above, and left in place it collapsed this
         element to 0 height in the flex-column mobile layout below. */
      overflow: visible; text-overflow: clip;
    }
    .dist-row.is-err .fill { background: rgba(248, 81, 73, 0.14); }
    .dist-row .n small.sub { font-size: 11px; font-weight: 400; color: var(--faint); margin-left: 4px; }
    .dist-row .n {
      font-family: var(--ph-font-mono); font-variant-numeric: tabular-nums;
      font-weight: 700; color: var(--muted); font-size: 11px;
    }

    /* Small "?" tooltip marker — plain-words explanation of a metric,
       on hover/focus. Not a link, not a button; just a title attr host. */
    .info-dot {
      display: inline-flex; align-items: center; justify-content: center;
      width: 14px; height: 14px; border-radius: 50%;
      background: var(--bg-3, rgba(140,160,220,0.10));
      border: 1px solid var(--border);
      color: var(--faint); font-size: 10px; font-weight: 600;
      cursor: help; user-select: none;
    }
    .info-dot:hover { color: var(--accent-bright); border-color: var(--accent-dim); }

    /* ============================================================
       Errors — collapsible card. Collapsed by default; the header
       alone carries total count + trend so there's signal without
       opening it.
       ============================================================ */
    .errors-card {
      margin-top: 16px;
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      overflow: hidden;
    }
    .errors-header {
      width: 100%; display: flex; align-items: center; gap: 10px;
      background: transparent; border: 0; cursor: pointer;
      padding: 13px 16px; text-align: left; color: var(--text);
      font: inherit;
    }
    .errors-header:hover { background: rgba(140, 160, 220, 0.04); }
    .errors-header .chev {
      color: var(--faint); font-size: 11px;
      transition: transform var(--t-fast);
    }
    .errors-header[aria-expanded="true"] .chev { transform: rotate(90deg); }
    .errors-title { font-size: 14px; font-weight: 650; }
    .errors-trend {
      font-family: var(--ph-font-mono); font-size: 11.5px; font-weight: 600;
    }
    .errors-trend.up   { color: var(--danger); }
    .errors-trend.down { color: var(--success); }
    .errors-trend.flat { color: var(--faint); }
    .errors-header-hint {
      margin-left: auto; font-size: 11px; color: var(--faint);
    }
    .errors-body { padding: 4px 16px 16px; }
    .errors-empty { padding: 10px 2px; color: var(--faint); font-size: 12.5px; }
    .errors-groups {
      display: flex; flex-direction: column; gap: 8px; margin-top: 6px;
    }
    .error-group {
      background: var(--bg); border: 1px solid var(--border);
      border-radius: var(--r-sm); padding: 10px 12px;
    }
    .error-group-head {
      display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap;
    }
    .error-group-class {
      font-family: var(--ph-font-mono); font-size: 12.5px; font-weight: 700;
      color: var(--text);
    }
    .error-group-stat {
      font-size: 11px; color: var(--muted);
      font-variant-numeric: tabular-nums;
    }
    .error-group-stat strong { color: var(--text); font-weight: 700; }
    .error-group-meta {
      margin-left: auto; font-size: 10.5px; color: var(--faint);
      font-family: var(--ph-font-mono);
    }
    .error-group-msg {
      margin-top: 6px; font-family: var(--ph-font-mono); font-size: 11.5px;
      color: var(--muted); cursor: pointer;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    .error-group-msg:hover { color: var(--text); }
    .error-group-msg.is-expanded {
      white-space: normal; word-break: break-word;
    }
    .errors-showall {
      margin-top: 10px; width: 100%;
    }

    /* ============================================================
       Skeleton loading state.
       ============================================================ */
    @keyframes skel-pulse {
      0%, 100% { opacity: 0.55; }
      50%      { opacity: 0.85; }
    }
    .skel {
      background: linear-gradient(90deg,
        rgba(140, 160, 220, 0.04),
        rgba(140, 160, 220, 0.12) 50%,
        rgba(140, 160, 220, 0.04));
      background-size: 200% 100%;
      border-radius: 4px;
      display: inline-block;
      animation: skel-pulse 1.6s ease-in-out infinite;
    }
    .skel.line { width: 100%; height: 12px; }
    .skel-kpi {
      background: var(--bg-2);
      border: 1px solid var(--border);
      border-radius: var(--r-md);
      padding: 14px 16px;
      min-height: 96px;
    }
    .skel-kpi .skel.label { width: 55%; height: 9px; margin-bottom: 12px; }
    .skel-kpi .skel.value { width: 45%; height: 24px; margin-bottom: 8px; }
    .skel-kpi .skel.delta { width: 70%; height: 9px; }

    /* ============================================================
       Error card.
       ============================================================ */
    .error-card {
      background: var(--panel);
      border: 1px solid rgba(248, 81, 73, 0.55);
      border-radius: var(--r-lg);
      padding: 22px;
      box-shadow: var(--shadow-2);
    }
    .error-card .err-title {
      color: var(--danger);
      font-weight: 700; font-size: 15px;
      margin: 0 0 10px;
      display: flex; align-items: center; gap: 10px;
    }
    .error-card .err-msg {
      color: var(--muted); font-size: 12px;
      font-family: var(--ph-font-mono);
      margin: 0 0 8px;
      word-break: break-word;
    }
    .error-card .hint {
      color: var(--muted); font-size: 12px;
      margin: 12px 0;
    }
    .error-card .err-actions {
      display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px;
    }
    .btn {
      background: var(--accent);
      color: white; border: 0;
      padding: 8px 16px; border-radius: var(--r-sm);
      cursor: pointer; font: inherit; font-size: 12.5px; font-weight: 500;
      transition: filter var(--t-fast);
    }
    .btn:hover { filter: brightness(1.1); }
    .btn.ghost {
      background: transparent;
      color: var(--text);
      border: 1px solid var(--border-strong);
    }
    .btn.ghost:hover { background: var(--panel-2); filter: none; }

    /* ============================================================
       Footer.
       ============================================================ */
    footer {
      color: var(--faint); font-size: 11.5px; text-align: center;
      margin-top: 38px;
      line-height: 1.7;
    }
    footer a { color: var(--muted); }

    /* Mobile tweaks. */
    @media (max-width: 600px) {
      .wrap { padding: 22px 14px 60px; }
      .wordmark .mark { font-size: 26px; }
      section.card { padding: 16px 14px; }
      .kpi .value { font-size: 22px; }
      .kpi.is-hero .value { font-size: 28px; }
      .row-bar { width: 60px; }
      /* "Failures by version" / any other is-err row carries a long
         descriptive value ("failed · 6.1% of 1,109 · 65 installs") that
         has nowhere to shrink to next to a name in a 1fr/auto grid at
         this width — the two columns fought for space and the name
         wrapped into an unreadably narrow sliver. Stack instead — flex
         column rather than fighting the grid's implicit row sizing. */
      .dist-row.is-err {
        display: flex; flex-direction: column; align-items: stretch; gap: 3px;
      }
      .dist-row.is-err .n { text-align: left; }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <!-- ============================================================
         HEADER
         ============================================================ -->
    <header class="hero">
      <div class="hero-top">
        <a href="/" class="wordmark" title="Back to Phosphene panel">
          <span class="mark">Phosphene</span>
          <span class="sep">·</span>
          <span class="what">stats</span>
        </a>
        <div class="hero-actions">
          <a class="icon-btn" id="repo-link"
             href="https://github.com/mrbizarro/phosphene"
             target="_blank" rel="noopener"
             title="Open the public repo on GitHub">
             <span class="ico">↗</span> repo
          </a>
          <a class="icon-btn" id="raw-link"
             href="/stats/data"
             target="_blank" rel="noopener"
             title="View the raw JSONL data file (served locally — never on the public repo)">
             <span class="ico">{ }</span> raw JSONL
          </a>
          <button class="icon-btn" id="refresh-btn" type="button"
                  title="Manually trigger a refresh (best-effort — refreshes daily automatically)">
             <span class="ico">↻</span> refresh
          </button>
        </div>
      </div>
      <div class="sub-meta">
        <span class="lock"><span class="ico">●</span> private · localhost only</span>
        <span class="dot-sep">·</span>
        <span id="meta" aria-live="polite">
          <span class="skel" style="width:240px;height:11px"></span>
        </span>
      </div>
      <div class="hero-underline" aria-hidden="true"></div>
    </header>

    <!-- ============================================================
         GLOBAL RANGE — the one time-window control for the whole
         dashboard. Replaces the separate "Over time" (7/30/90/365/all)
         and "Clones date range" (30/90/365/all) chip groups — every
         chart and the Usage section now read this single value.
         Persisted per-browser (localStorage, wrapped in try/catch —
         private browsing can throw), default 30 days.
         ============================================================ -->
    <div class="range-bar" role="group" aria-label="Dashboard time range">
      <span class="range-bar-label">Range</span>
      <div class="chips" id="global-range-chips">
        <button class="chip" type="button" data-range="7"   aria-pressed="false">7 days</button>
        <button class="chip" type="button" data-range="30"  aria-pressed="true">30 days</button>
        <button class="chip" type="button" data-range="90"  aria-pressed="false">90 days (3 months)</button>
        <button class="chip" type="button" data-range="all" aria-pressed="false">All time</button>
      </div>
      <span class="range-bar-hint" id="range-bar-hint"></span>
    </div>

    <!-- Mount point for error state. Hidden unless fetch fails. -->
    <div id="error-mount" hidden></div>

    <!-- ============================================================
         RIGHT NOW — KPI strip with sparklines + health pulse.
         ============================================================ -->
    <!-- ============================================================
         USAGE — anonymous panel telemetry. Independent of /stats/data:
         it reads /stats/usage, which always answers (local aggregates
         from state/usage-log.jsonl) and upgrades to fleet-wide numbers
         when a PostHog personal API key is configured in Settings.
         Hidden only if the endpoint itself is missing — i.e. on a panel
         older than this feature.
         ============================================================ -->
    <section class="card" id="sec-usage" hidden>
      <div class="section-head">
        <h2>Usage <span class="h2-sub">anonymous panel telemetry · renders, errors, hardware</span></h2>
        <button class="icon-btn" id="usage-refresh" type="button"
                title="Re-query PostHog now (bypasses the 6h cache)">
          <span class="ico">↻</span> refresh
        </button>
      </div>
      <div class="usage-note" id="usage-note">
        <span class="src" id="usage-src">local</span>
        <span id="usage-note-text">loading…</span>
      </div>
      <div class="kpi-grid" id="usage-tiles" aria-label="Usage headline stats"></div>
      <!-- Growth: installs over time (cumulative, all-time) against renders
           per day (30d). One chart, two axes, so "is it growing" is one
           glance; weekly active installs ride the caption. -->
      <div class="usage-growth" id="usage-growth" hidden>
        <h3>Growth <span class="h2-sub" id="usage-growth-sub">installs, all time · renders per day, 30d</span></h3>
        <div class="chart-wrap" style="height:260px">
          <canvas id="chart-usage-growth" aria-label="Installs over time and renders per day"></canvas>
        </div>
      </div>
      <!-- Pack-flip alert. A pack going true→false across boots is the
           "my H3 vanished" bug class; red when it has happened at all. -->
      <div class="usage-alert is-clear" id="usage-packflip">
        <span class="n">0</span>
        <span>optional-pack regressions in the selected range.</span>
      </div>
      <div class="dist-grid">
        <div class="dist-col">
          <!-- Refusals, kept next to errors and never inside them: these are
               renders the panel declined on purpose, so they are not part of
               the error rate. A tall bar here is a UI bug (we offered a
               control that can never work), not an engine bug. -->
          <h3>Refused <span class="count-pill" id="usage-refusals-count">0</span>
            <span class="info-dot" title="Renders the panel declined before starting — not a crash, not counted in the error rate. A big number here means the UI is offering something this machine can't actually do.">?</span></h3>
          <ul class="dist-list" id="usage-refusals"></ul>
        </div>
        <div class="dist-col">
          <h3>Failures by version <span class="info-dot" title="Failed renders as a share of that version's total renders, in the selected range. A version failing MORE than the one before it is the signal to look for.">?</span></h3>
          <ul class="dist-list" id="usage-failures-by-version"></ul>
        </div>
        <div class="dist-col">
          <h3>Versions <span class="info-dot" title="Which release each install is running, by distinct installs seen in the selected range.">?</span></h3>
          <ul class="dist-list" id="usage-versions"></ul>
        </div>
        <div class="dist-col">
          <h3>Chip <span class="info-dot" title="Apple Silicon family (M1–M5, Pro/Max/Ultra) across installs seen in the selected range.">?</span></h3>
          <ul class="dist-list" id="usage-chips"></ul>
        </div>
        <div class="dist-col">
          <h3>Memory <span class="info-dot" title="Unified RAM tier across installs seen in the selected range — the single biggest driver of which engines/quality tiers an install can run.">?</span></h3>
          <ul class="dist-list" id="usage-ram"></ul>
        </div>
      </div>

      <!-- ==========================================================
           ERRORS — collapsible, collapsed by default (owner: "the
           error section is really not well designed... it should be
           collapsible, it's too big"). Header alone carries the total
           count + a trend arrow vs. the prior equal-length period, so
           there's signal without expanding. Expanded: grouped by the
           closed error_class taxonomy (not raw free-text messages),
           sorted by distinct installs affected, top 5 with "show all".
           ========================================================== -->
      <section class="errors-card" id="errors-card">
        <button class="errors-header" id="errors-toggle" type="button"
                aria-expanded="false" aria-controls="errors-body">
          <span class="chev" aria-hidden="true">▸</span>
          <span class="errors-title">Errors</span>
          <span class="count-pill" id="errors-total-count">0</span>
          <span class="errors-trend" id="errors-trend"></span>
          <span class="errors-header-hint">click to expand</span>
        </button>
        <div class="errors-body" id="errors-body" hidden>
          <div class="errors-empty" id="errors-empty" hidden>no render failures in this range.</div>
          <div class="errors-groups" id="errors-groups"></div>
          <button class="btn ghost errors-showall" id="errors-showall" type="button" hidden>
            show all error classes
          </button>
        </div>
      </section>
    </section>

    <!-- ============================================================
         FUNNEL — Views → Clones → Stars → Forks.
         ============================================================ -->
        <section class="card" id="sec-now">
      <div class="section-head">
        <h2>Right now <span class="h2-sub">snapshot from latest fetch</span></h2>
      </div>
      <div class="kpi-grid" id="kpi-grid" aria-busy="true" aria-label="Current repository stats">
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
        <div class="skel-kpi"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
      </div>
    </section>

    <!-- ============================================================
         NEEDS ATTENTION — live board of the actual open issues + PRs.
         Populated from the latest snapshot's `open_items` array (added
         by scripts/fetch_repo_stats.py). Hidden entirely if the fetcher
         predates the field (older snapshot) so old data degrades cleanly.
         ============================================================ -->
    <section class="card" id="sec-attention" hidden>
      <div class="section-head">
        <h2>Needs attention <span class="h2-sub">open issues &amp; pull requests · newest first</span></h2>
        <a class="icon-btn" id="attention-repo-link"
           href="https://github.com/mrbizarro/phosphene/issues"
           target="_blank" rel="noopener"
           title="Open the issues + PRs on GitHub">
           <span class="ico">↗</span> on GitHub
        </a>
      </div>
      <div class="board">
        <div class="board-col">
          <h3>Open issues <span class="count-pill" id="attn-issues-count">0</span></h3>
          <ul class="board-list" id="attn-issues-list"></ul>
          <div class="board-more" id="attn-issues-more" hidden></div>
        </div>
        <div class="board-col">
          <h3>Open PRs <span class="count-pill" id="attn-prs-count">0</span></h3>
          <ul class="board-list" id="attn-prs-list"></ul>
          <div class="board-more" id="attn-prs-more" hidden></div>
        </div>
      </div>
    </section>

<section class="card" id="sec-funnel">
      <div class="section-head">
        <h2>Discovery funnel <span class="h2-sub">how the repo converts pageviews to commitment</span></h2>
      </div>
      <!-- All-time install/user headline — the number GitHub can't show
           (it only keeps 14 days). Computed from the stitched clone archive
           in renderFunnel(). This is what "how many actual users" means. -->
      <div id="alltime-hero" style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:0 0 16px">
        <div style="background:rgba(63,185,80,0.06);border:1px solid rgba(63,185,80,0.28);border-radius:12px;padding:16px 18px">
          <div style="font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)" title="Installs that finished at least one render, all time, from the in-app analytics (the maintainer's own machines excluded). Our best count of real people: one person with two installs counts twice, and a check on 2026-10-14 put that overlap at about 3%.">Users · installs that rendered <span style="color:#3fb950;opacity:.85">· all-time</span></div>
          <div id="ath-users" style="font-size:34px;font-weight:680;color:var(--text);line-height:1.05;margin-top:5px">—</div>
          <div id="ath-users-sub" style="font-size:11.5px;color:var(--muted);margin-top:4px">from in-app analytics · loading…</div>
        </div>
        <div style="background:rgba(63,185,80,0.06);border:1px solid rgba(63,185,80,0.28);border-radius:12px;padding:16px 18px">
          <div style="font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)">Total clones <span style="color:#3fb950;opacity:.85">· all-time</span></div>
          <div id="ath-clones" style="font-size:34px;font-weight:680;color:var(--text);line-height:1.05;margin-top:5px">—</div>
          <div id="ath-clones-sub" style="font-size:11.5px;color:var(--muted);margin-top:4px">vs GitHub's 14-day window</div>
        </div>
      </div>
      <div class="funnel" id="funnel"
           aria-label="Funnel from views to clones to stars to forks">
        <!-- populated by JS -->
      </div>
    </section>

    <!-- ============================================================
         CLONES — dedicated all-time line chart with own period+bucket.
         Independent from the global over-time chips below so flipping
         it doesn't reset everything else.
         ============================================================ -->
    <section class="card" id="sec-clones-history">
      <div class="section-head">
        <h2>Clones <span class="h2-sub">accumulated history — follows the range above</span></h2>
        <div class="chips" role="group" aria-label="Clones bucketing">
          <button class="chip clones-chip-bucket" type="button" data-clones-bucket="daily" aria-pressed="false">daily</button>
          <button class="chip clones-chip-bucket" type="button" data-clones-bucket="weekly" aria-pressed="true">weekly</button>
          <button class="chip clones-chip-bucket" type="button" data-clones-bucket="monthly" aria-pressed="false">monthly</button>
        </div>
      </div>

      <div class="chart-card" style="margin-top:8px">
        <h3>
          Clones · per <span id="clones-bucket-label">week</span>
          <span class="legend">
            <span><i class="swatch" style="background:#3fb950"></i>total clones</span>
            <span><i class="swatch" style="background:#3fb950;opacity:0.45"></i>unique IPs</span>
          </span>
        </h3>
        <div class="chart-wrap" style="height:300px">
          <canvas id="chart-clones-history"
                  aria-label="Line chart of clones per day, week, or month over the selected date range — all-time history from the local archive"
                  role="img"></canvas>
        </div>
        <!-- Derived-metric KPI strip — what we can infer from the daily
             count + uniques pair. Populated by renderClonesHistoryChart. -->
        <div id="clones-derived" class="clones-kpi-strip">
          <div class="clones-kpi">
            <div class="lbl">total clones</div>
            <div class="val" id="ck-total">—</div>
            <div class="sub" id="ck-total-sub">in range</div>
          </div>
          <div class="clones-kpi">
            <div class="lbl">daily unique cloners, summed</div>
            <div class="val" id="ck-est">—</div>
            <div class="sub" title="GitHub only publishes unique cloners per day. Summed over the range this is an UPPER bound on distinct cloners: one person cloning on 3 days counts 3 times. For users, read the Usage section (installs that rendered).">upper bound · not users</div>
          </div>
          <div class="clones-kpi">
            <div class="lbl">retry pressure</div>
            <div class="val" id="ck-retry">—</div>
            <div class="sub" title="Daily count ÷ daily uniques. >1.5 means people are re-cloning (failed installs, Reset → Install cycles).">avg clones per IP/day</div>
          </div>
          <div class="clones-kpi">
            <div class="lbl">last 7d daily avg</div>
            <div class="val" id="ck-recent">—</div>
            <div class="sub">unique IPs/day · recent activity</div>
          </div>
        </div>
        <div class="clones-foot" id="clones-foot">
          <span class="lbl">limits:</span>
          GitHub returns only the last 14 days of clones (older data was never collected before the panel started archiving).
          Updates (<code>git pull</code> from Pinokio's Update button) <strong>do not</strong> show up here at all — only fresh <code>git clone</code> operations.
          <span id="clones-releases-marker"></span>
        </div>
      </div>
    </section>

    <style>
      .clones-kpi-strip {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        margin-top: 14px;
        padding: 12px;
        background: rgba(63, 185, 80, 0.04);
        border: 1px solid rgba(63, 185, 80, 0.15);
        border-radius: 8px;
      }
      .clones-kpi {
        padding: 8px 12px;
      }
      .clones-kpi .lbl {
        font-size: 11px;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: var(--faint);
        font-weight: 500;
        margin-bottom: 4px;
      }
      .clones-kpi .val {
        font-size: 22px;
        font-weight: 700;
        font-variant-numeric: tabular-nums;
        font-family: var(--ph-font-mono), 'SF Mono', Menlo, monospace;
        color: var(--fg);
        line-height: 1.2;
      }
      .clones-kpi .sub {
        font-size: 11px;
        color: var(--faint);
        margin-top: 2px;
        cursor: help;
      }
      .clones-foot {
        margin-top: 12px;
        padding: 10px 14px;
        background: rgba(140, 160, 220, 0.04);
        border-left: 3px solid rgba(140, 160, 220, 0.25);
        border-radius: 4px;
        font-size: 12px;
        color: var(--faint);
        line-height: 1.55;
      }
      .clones-foot .lbl {
        text-transform: uppercase;
        letter-spacing: 0.04em;
        font-size: 10.5px;
        font-weight: 600;
        color: var(--faint);
        margin-right: 6px;
      }
      .clones-foot code {
        background: rgba(140, 160, 220, 0.08);
        padding: 1px 5px;
        border-radius: 3px;
        font-size: 11px;
      }
      /* Fixed 4 equal columns had no floor — each needs ~90px minimum
         before the numbers/labels themselves start clipping, so at
         phone width the strip pushed the whole PAGE into horizontal
         scroll (found via a headless 390px-viewport pass). 2 columns
         keeps every value readable down to ~340px content width. */
      @media (max-width: 480px) {
        .clones-kpi-strip { grid-template-columns: repeat(2, 1fr); }
      }
    </style>

    <!-- ============================================================
         OVER TIME — period chips + 4 stacked charts.
         ============================================================ -->
    <section class="card" id="sec-over-time">
      <div class="section-head">
        <h2>Over time <span class="h2-sub">history from the local archive — follows the range above</span></h2>
      </div>

      <div class="chart-row">
        <div class="chart-card">
          <h3>
            Stars &amp; forks · cumulative
            <span class="legend">
              <span><i class="swatch" style="background:#58a6ff"></i>stars</span>
              <span><i class="swatch" style="background:#B14AFF"></i>forks</span>
            </span>
          </h3>
          <div class="chart-wrap">
            <canvas id="chart-growth"
                    aria-label="Dual-axis line chart of cumulative stars and forks over the selected date range"
                    role="img"></canvas>
          </div>
        </div>
        <div class="chart-card">
          <h3>
            Traffic · per day
            <span class="legend">
              <span><i class="swatch" style="background:#3fb950"></i>clones</span>
              <span><i class="swatch" style="background:#d29922"></i>views</span>
            </span>
          </h3>
          <div class="chart-wrap">
            <canvas id="chart-traffic"
                    aria-label="Grouped bar chart of git clones and page views per day"
                    role="img"></canvas>
          </div>
        </div>
      </div>

      <div class="chart-row">
        <div class="chart-card" id="card-velocity">
          <h3>
            Issue &amp; PR velocity · weekly
            <span class="legend">
              <span><i class="swatch" style="background:#58a6ff"></i>opened</span>
              <span><i class="swatch" style="background:#3fb950"></i>closed</span>
            </span>
          </h3>
          <div class="chart-wrap">
            <canvas id="chart-velocity"
                    aria-label="Diverging bar chart of issues and PRs opened versus closed per week"
                    role="img"></canvas>
          </div>
        </div>
        <div class="chart-card" id="card-commits">
          <h3>
            Commit activity · per day
            <span class="legend">
              <span><i class="swatch" style="background:#5EEAFF"></i>commits</span>
            </span>
          </h3>
          <div class="chart-wrap">
            <canvas id="chart-commits"
                    aria-label="Bar chart of commits per day over the selected date range"
                    role="img"></canvas>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================================================
         TRAFFIC SOURCES — referrers + paths tables.
         ============================================================ -->
    <section class="card" id="sec-traffic">
      <div class="section-head">
        <h2>Traffic sources <span class="h2-sub">last 14 days — GitHub Traffic API only retains this window</span></h2>
      </div>
      <div class="two-col">
        <div>
          <h3>Top referrers</h3>
          <div class="table-wrap">
            <table id="referrers-table">
              <thead><tr>
                <th>Source</th>
                <th class="num">Views</th>
                <th class="num">Uniques</th>
              </tr></thead>
              <tbody>
                <tr><td colspan="3" class="empty">loading…</td></tr>
              </tbody>
            </table>
          </div>
        </div>
        <div>
          <h3>Top paths</h3>
          <div class="table-wrap">
            <table id="paths-table">
              <thead><tr>
                <th>Path</th>
                <th class="num">Views</th>
                <th class="num">Uniques</th>
              </tr></thead>
              <tbody>
                <tr><td colspan="3" class="empty">loading…</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================================================
         RELEASES — only shown when release_timeline has rows.
         ============================================================ -->
    <section class="card" id="sec-releases" hidden>
      <div class="section-head">
        <h2>Releases <span class="h2-sub" id="releases-note">download volume per tag</span></h2>
      </div>
      <div class="table-wrap">
        <table id="releases-table">
          <thead><tr>
            <th>Tag</th>
            <th>Published</th>
            <th class="num" title="Downloads of files attached to the release. Code releases ship as git tags (Pinokio pulls them) and carry no files: those read source-only.">Downloads</th>
            <th class="num">Relative</th>
          </tr></thead>
          <tbody></tbody>
        </table>
      </div>
      <div class="list-more" id="releases-more" hidden></div>
    </section>

    <footer>
      Data lives at <code>state/stats-data.jsonl</code> on your Mac —
      never on the public repo. A daily launchd job
      (<code>com.mrbizarro.phosphene-stats-fetch</code>) appends to it via
      <code>scripts/fetch_repo_stats.py</code> whether or not a panel is
      running. A panel fetches too only when started with
      <code>PHOSPHENE_STATS_FETCH=1</code>.
      <br>
      The GitHub Traffic API only retains 14 days of clones / views /
      referrers / paths; this archive is how we keep the history.
    </footer>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
  <script>
  // =====================================================================
  //  Phosphene stats dashboard — vanilla JS, single file, no build.
  //
  //  Loads /stats/data (JSONL), renders KPI strip + funnel + 4 time-series
  //  charts + traffic-source tables + optional releases table. Period chip
  //  selection persists in localStorage. All optional JSONL fields are
  //  feature-detected so the dashboard renders cleanly even on a brand-
  //  new install with one row of data.
  // =====================================================================

  // Safe localStorage — private browsing (and some locked-down browser
  // profiles) throw on getItem/setItem rather than just failing quietly,
  // which used to be able to take the chip-init code down with it. Every
  // read/write in this file goes through these two now.
  function lsGet(key) {
    try { return localStorage.getItem(key); } catch (_) { return null; }
  }
  function lsSet(key, value) {
    try { localStorage.setItem(key, value); } catch (_) { /* ignore */ }
  }

  const LS_RANGE = 'phosphene.stats.range';
  const REPO_URL  = 'https://github.com/mrbizarro/phosphene';
  const JSONL_URL = '/stats/data';
  // Refresh endpoint is "coming soon" on the panel side — POST best-effort
  // and degrade silently when it 404s.
  const REFRESH_URL = '/stats/refresh';
  // Anonymous usage telemetry. Answers on every panel new enough to have
  // the endpoint; 404s on older ones (the Usage section stays hidden).
  const USAGE_URL = '/stats/usage';

  // Color tokens for charts (kept here so chart code is theme-agnostic).
  const C = {
    accent:    '#58a6ff',
    accent2:   '#2f81f7',
    purple:    '#B14AFF',
    pink:      '#FF2E9F',
    cyan:      '#5EEAFF',
    green:     '#3fb950',
    amber:     '#d29922',
    red:       '#f85149',
    text:      '#f4f4f5',
    muted:     '#b4b4bb',
    faint:     '#6b6b73',
    border:    '#2a2a2f',
    grid:      'rgba(140, 160, 220, 0.06)',
    gridStrong:'rgba(140, 160, 220, 0.12)',
    tooltipBg: 'rgba(14, 14, 15, 0.96)',
  };

  let allRows = [];
  // Global range: '7' | '30' | '90' | 'all' — client-side day-count form
  // (matches sliceByPeriod/sliceTimelineByPeriod). Drives every chart AND
  // the server fetch (?range=7d/30d/90d/all). ONE control now, replacing
  // the old independent currentPeriod + clonesAllTime.period pair.
  let globalRange = '30';
  const clonesAllTime = { bucket: 'weekly' };
  const LS_CLONES_BUCKET = 'phosphene-stats-clones-bucket';
  const charts = {};       // id -> Chart instance
  const sparkCharts = {};  // id -> mini Chart

  /** '7'/'30'/'90'/'all' (client slicing form) -> '7d'/'30d'/'90d'/'all'
   * (the server's ?range= form). */
  function serverRange(r) { return r === 'all' ? 'all' : `${r}d`; }

  // ===================================================================
  //  Helpers
  // ===================================================================
  const $ = (sel, root) => (root || document).querySelector(sel);
  const $$ = (sel, root) => Array.from((root || document).querySelectorAll(sel));

  function fmt(n) {
    return (n == null || Number.isNaN(n)) ? '—' : Number(n).toLocaleString();
  }
  function fmtShort(n) {
    if (n == null || Number.isNaN(n)) return '—';
    const abs = Math.abs(n);
    if (abs < 10000) return Number(n).toLocaleString();
    if (abs < 1e6)   return (n / 1e3).toFixed(n % 1e3 === 0 ? 0 : 1).replace(/\.0$/, '') + 'K';
    if (abs < 1e9)   return (n / 1e6).toFixed(n % 1e6 === 0 ? 0 : 1).replace(/\.0$/, '') + 'M';
    return (n / 1e9).toFixed(1).replace(/\.0$/, '') + 'B';
  }
  function fmtPct(v, opts) {
    if (v == null || !Number.isFinite(v)) return '—';
    const fixed = (opts && opts.fixed != null) ? opts.fixed : 1;
    const sign = (opts && opts.signed && v > 0) ? '+' : '';
    return sign + v.toFixed(fixed) + '%';
  }
  function dayAgo(iso) {
    const t = new Date(iso).getTime();
    if (!Number.isFinite(t)) return '—';
    const ms = Date.now() - t;
    if (ms < 60_000)         return 'just now';
    if (ms < 3_600_000)      return Math.floor(ms / 60_000)  + 'm ago';
    if (ms < 86_400_000)     return Math.floor(ms / 3_600_000) + 'h ago';
    const d = Math.floor(ms / 86_400_000);
    if (d === 1) return 'yesterday';
    if (d < 7)   return d + 'd ago';
    return Math.floor(d / 7) + 'w ago';
  }
  function escapeHtml(s) {
    return String(s ?? '').replace(/[&<>"']/g, c =>
      ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])
    );
  }
  function escapeAttr(s) { return escapeHtml(s); }
  function sum(arr) { return arr.reduce((a, b) => a + (Number(b) || 0), 0); }
  function avg(arr) { return arr.length ? sum(arr) / arr.length : 0; }

  /** Rows whose date falls in the last `period` days (by DATE, not by row
   * count: the archive has gaps, and "the last 30 rows" was 43 days once a
   * fetch had been skipped for two weeks). period ∈ {'7','30','90','all'}. */
  function sliceByPeriod(rows, period) {
    if (period === 'all' || !period) return rows;
    const n = parseInt(period, 10);
    if (!Number.isFinite(n) || n <= 0) return rows;
    const cutoff = isoDaysAgo(n);
    return rows.filter(r => (r.date || '') >= cutoff);
  }

  /** UTC YYYY-MM-DD for `n` days before `fromIso` (default: today, UTC). */
  function isoDaysAgo(n, fromIso) {
    const base = fromIso ? new Date(fromIso + 'T00:00:00Z') : new Date();
    const t = base.getTime() - n * 86_400_000;
    return new Date(t).toISOString().slice(0, 10);
  }

  /** The last row dated ON OR BEFORE `iso` (rows sorted ascending), or null.
   * Deltas ask "what was it N days ago", and with gaps in the archive the
   * row N places back is not N days back. */
  function rowOnOrBefore(rows, iso) {
    let hit = null;
    for (const r of rows) {
      if ((r.date || '') <= iso) hit = r; else break;
    }
    return hit;
  }

  /** Cumulative count on `iso` from a {date,count} cumulative timeline
   * (stars_timeline / forks_timeline: GitHub's full history, carried
   * forward over days with no change). 0 before its first entry; null
   * when there is no timeline. */
  function cumAt(timeline, iso) {
    if (!Array.isArray(timeline) || !timeline.length) return null;
    let v = 0;
    for (const p of timeline) {
      if ((p.date || '') <= iso) v = p.count; else break;
    }
    return v;
  }

  /** {date,count} point for exactly `iso` in a daily series, or null. */
  function pointOn(series, iso) {
    for (let i = series.length - 1; i >= 0; i--) {
      if (series[i].date === iso) return series[i];
      if (series[i].date < iso) break;
    }
    return null;
  }

  /** Slice a {date,count} timeline by period (matches sliceByPeriod). */
  function sliceTimelineByPeriod(timeline, period) {
    if (!Array.isArray(timeline) || !timeline.length) return [];
    if (period === 'all') return timeline;
    const n = parseInt(period, 10);
    if (!Number.isFinite(n) || n <= 0) return timeline;
    const cutoff = Date.now() - n * 86_400_000;
    return timeline.filter(p => {
      const t = new Date(p.date).getTime();
      return Number.isFinite(t) && t >= cutoff;
    });
  }

  /** Delta string: d/d + w/w, plus "vs N days ago" when the selected
   * range is longer than a week (7d and 'all' are covered by w/w and by
   * having no meaningful prior period, respectively — see renderKpiStrip). */
  function deltaHtml(today, yesterday, weekAgo, rangeAgo, rangeLabel) {
    const out = [];
    if (today != null && yesterday != null) {
      out.push(deltaPart(today - yesterday, 'd/d'));
    }
    if (today != null && weekAgo != null && weekAgo !== yesterday) {
      out.push(deltaPart(today - weekAgo, 'w/w'));
    }
    if (today != null && rangeAgo != null && rangeLabel) {
      out.push(deltaPart(today - rangeAgo, `${rangeLabel} ago`));
    }
    if (!out.length) return '';
    return `<div class="deltas">${out.join('')}</div>`;
  }
  function deltaPart(diff, label) {
    if (diff === 0) return `<span class="delta"><span class="lbl">${label}</span>±0</span>`;
    const sign = diff > 0 ? '+' : '';
    const cls  = diff > 0 ? 'up' : 'down';
    return `<span class="delta ${cls}"><span class="lbl">${label}</span>${sign}${diff.toLocaleString()}</span>`;
  }

  // ===================================================================
  //  Window-aware accessors. The fetcher ships rolling 15-day windows
  //  for clones+views even on day 1, so on a fresh install we have
  //  more granularity than the row history alone gives us.
  // ===================================================================

  /** Per-day clones / views. Both are the stitched all-snapshot series —
   * see trafficSeriesAllTime for why a row's top-level `clones` field is
   * never filed under the row's own date. */
  function clonesSeries(rows) { return clonesSeriesAllTime(rows); }
  function viewsSeries(rows)  { return viewsSeriesAllTime(rows); }

  /**
   *  All-time clones series. Unlike clonesSeries() which only overlays the
   *  LAST snapshot's clones_window, this iterates EVERY snapshot and unions
   *  every rolling window — so once the panel has been running long enough
   *  for non-overlapping windows, we still have continuous per-day history
   *  beyond the GitHub-API 14-day cutoff. Later snapshots win on overlap
   *  (their counts for a given day are more recently confirmed by GitHub).
   *  Returns [{date,count,uniques}] sorted ascending.
   */
  function clonesSeriesAllTime(rows) { return trafficSeriesAllTime(rows, 'clones'); }
  function viewsSeriesAllTime(rows)  { return trafficSeriesAllTime(rows, 'views'); }

  /** The stitched per-day series for 'clones' or 'views': the UNION of every
   * snapshot's 14-day window, later snapshots winning. Only window entries
   * count. A row's top-level `clones`/`views` field is NOT a reading for the
   * row's own date — it is the last entry of that row's window, i.e. a day or
   * more earlier — and filing it under the row's date double-counted it and
   * invented traffic for days GitHub never reported (Sep 24-28 2026 showed
   * Sep 23's 93 clones five times over). */
  function trafficSeriesAllTime(rows, kind) {
    if (!rows.length) return [];
    const map = new Map();
    const key = kind === 'views' ? 'views_window' : 'clones_window';
    for (const r of rows) {
      // The rolling 14-day window in each snapshot — union all of them.
      // Later snapshots win (more recent GitHub data for the same date).
      const win = Array.isArray(r[key]) ? r[key] : null;
      if (win) {
        for (const p of win) {
          if (!p.date) continue;
          map.set(p.date, {
            date: p.date,
            count: p.count ?? 0,
            uniques: p.uniques ?? 0,
          });
        }
      }
    }
    // Days only a DISCARDED same-day copy of a snapshot had (merged in from
    // other state dirs on 2026-10-14, kept on the surviving row as
    // `recovered_traffic`). Filled only where no window has the day.
    const rkey = kind === 'views' ? 'views' : 'clones';
    for (const r of rows) {
      const extra = r.recovered_traffic && Array.isArray(r.recovered_traffic[rkey])
        ? r.recovered_traffic[rkey] : [];
      for (const p of extra) {
        if (!p.date || map.has(p.date)) continue;
        map.set(p.date, { date: p.date, count: p.count ?? 0, uniques: p.uniques ?? 0 });
      }
    }
    return [...map.values()].sort((a, b) => a.date < b.date ? -1 : 1);
  }

  /**
   *  Bucket a daily timeline into weekly or monthly buckets by summing.
   *  bucket ∈ {'daily','weekly','monthly'}. Returns [{date,count,uniques}].
   *  Bucket key: daily=YYYY-MM-DD, weekly=YYYY-MM-DD (Monday start), monthly=YYYY-MM.
   */
  function bucketTimeline(timeline, bucket) {
    if (!Array.isArray(timeline) || !timeline.length) return [];
    const keyOf = (dateStr) => {
      if (bucket === 'monthly') return dateStr.slice(0, 7); // YYYY-MM
      if (bucket === 'weekly') {
        const d = new Date(dateStr);
        if (!Number.isFinite(d.getTime())) return dateStr.slice(0, 10);
        // ISO week — start Monday.
        const day = d.getUTCDay();
        const offset = (day + 6) % 7;
        const wk = new Date(d);
        wk.setUTCDate(d.getUTCDate() - offset);
        return wk.toISOString().slice(0, 10);
      }
      return dateStr.slice(0, 10);
    };
    const out = new Map();
    for (const p of timeline) {
      const k = keyOf(p.date);
      const prev = out.get(k) || { date: k, count: 0, uniques: 0 };
      prev.count += Number(p.count) || 0;
      prev.uniques += Number(p.uniques) || 0;
      out.set(k, prev);
    }
    return [...out.values()].sort((a, b) => a.date < b.date ? -1 : 1);
  }

  // ===================================================================
  //  KPI STRIP
  // ===================================================================

  function renderKpiStrip(rows) {
    const mount = $('#kpi-grid');
    mount.setAttribute('aria-busy', 'false');
    if (!rows.length) {
      mount.innerHTML =
        '<div class="empty" style="grid-column:1 / -1">no snapshots yet — panel will fetch one in the background within 90s</div>';
      return;
    }
    const last = rows[rows.length - 1];
    // Deltas by DATE: d/d is the snapshot from the day before, w/w the one
    // from 7 days before (or the latest one older than that). Row-index
    // arithmetic used to compare against whatever sat 1 or 7 places back,
    // which after a skipped fortnight was weeks away.
    const prev = rowOnOrBefore(rows, isoDaysAgo(1, last.date)) || {};
    const week = rowOnOrBefore(rows, isoDaysAgo(7, last.date));

    // "vs N days ago" — only for ranges longer than a week (7d duplicates
    // w/w; 'all' has no meaningful prior point to compare a single day
    // to), and only when the archive actually reaches back that far.
    const rangeDays = (globalRange !== 'all' && globalRange !== '7')
      ? parseInt(globalRange, 10) : null;
    const rangeRow = rangeDays ? rowOnOrBefore(rows, isoDaysAgo(rangeDays, last.date)) : null;
    const rangeLabel = rangeRow && rangeDays ? `${rangeDays}d` : null;

    // 30-day sparkline series (best-effort — uses raw rows).
    const sparkRows = rows.slice(-30);
    const sparkOf = pick => sparkRows.map(pick);
    // Clones + views: ONE daily series stitched from every snapshot's
    // 14-day window (later snapshots win). The tile shows its newest day —
    // GitHub reports traffic ~1-2 days late, so that is "the latest day
    // GitHub has published", never "today" — with deltas against the day
    // before and the same weekday a week earlier IN THAT SERIES. The old
    // tile read each snapshot's own last entry, so when GitHub's window
    // stalled (Sep 25-29 all ended on Sep 23) the tile and its deltas froze.
    const cAll = clonesSeriesAllTime(rows);
    const vAll = viewsSeriesAllTime(rows);
    const cLast = cAll[cAll.length - 1] || null;
    const vLast = vAll[vAll.length - 1] || null;
    const cDay = cLast ? cLast.date : null;
    const vDay = vLast ? vLast.date : null;
    const clonesS = cAll.slice(-30);
    const viewsS  = vAll.slice(-30);
    // Value of stars/forks N days before the latest snapshot: the GitHub
    // timeline when the snapshot has one, else the snapshot on/before then.
    const histAt = (kind, n) => {
      const iso = isoDaysAgo(n, last.date);
      const v = cumAt(last[kind + '_timeline'], iso);
      if (v != null) return v;
      const r = rowOnOrBefore(rows, iso);
      return r ? r[kind] : null;
    };
    const shortDay = iso => iso ? new Date(iso + 'T00:00:00Z').toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' }) : '—';

    // Health pulse — synthesized.
    const pulse = computeHealthPulse(rows);

    const cards = [
      // Stars / forks deltas come from the GitHub-side timelines (every
      // star and fork with its date), not from our snapshots: with a gap in
      // the archive, "the snapshot before today" was 15 days old and d/d
      // read +16 stars.
      {
        key: 'stars', label: 'Stars',
        title: 'Total GitHub stars on the repo right now. d/d and w/w from GitHub\'s own star dates.',
        value: last.stars,
        yday: histAt('stars', 1), wk: histAt('stars', 7),
        rangeAgo: rangeDays ? histAt('stars', rangeDays) : null,
        spark: sparkOf(r => r.stars), color: C.accent,
      },
      {
        key: 'forks', label: 'Forks',
        title: 'Copies of the repo other GitHub accounts have made. d/d and w/w from GitHub\'s own fork dates.',
        value: last.forks,
        yday: histAt('forks', 1), wk: histAt('forks', 7),
        rangeAgo: rangeDays ? histAt('forks', rangeDays) : null,
        spark: sparkOf(r => r.forks), color: C.purple,
      },
      {
        key: 'clones', label: `Clones · ${shortDay(cDay)}`, hero: true,
        title: `git clones of the repo on ${cDay || '—'} (UTC), the latest day `
          + 'GitHub\'s Traffic API has published — it reports a day or two late, '
          + 'and a day\'s count can still rise for ~48 h. Counts CI and re-clones '
          + 'after a failed install too. d/d = the day before; w/w = 7 days earlier.',
        value: cLast ? cLast.count : null,
        yday: cDay ? pointOn(cAll, isoDaysAgo(1, cDay))?.count : null,
        wk: cDay ? pointOn(cAll, isoDaysAgo(7, cDay))?.count : null,
        rangeAgo: (cDay && rangeDays) ? pointOn(cAll, isoDaysAgo(rangeDays, cDay))?.count : null,
        spark: clonesS.map(p => p.count), color: C.pink,
        sparkGradient: true,
      },
      {
        key: 'views', label: `Views · ${shortDay(vDay)}`,
        title: `Page views on the repo on ${vDay || '—'} (UTC), the latest day `
          + 'GitHub has published. d/d = the day before; w/w = 7 days earlier.',
        value: vLast ? vLast.count : null,
        yday: vDay ? pointOn(vAll, isoDaysAgo(1, vDay))?.count : null,
        wk: vDay ? pointOn(vAll, isoDaysAgo(7, vDay))?.count : null,
        rangeAgo: (vDay && rangeDays) ? pointOn(vAll, isoDaysAgo(rangeDays, vDay))?.count : null,
        spark: viewsS.map(p => p.count), color: C.amber,
      },
      {
        key: 'work', label: 'Open issues + PRs',
        title: 'Everything currently open on the repo — bug reports, '
          + 'feature requests, and pull requests waiting on review.',
        value: (last.open_issues ?? 0) + (last.open_prs ?? 0),
        yday: (prev.open_issues ?? 0) + (prev.open_prs ?? 0),
        wk:   (week?.open_issues ?? null) != null
              ? (week.open_issues + (week.open_prs ?? 0))
              : null,
        rangeAgo: (rangeRow?.open_issues ?? null) != null
              ? (rangeRow.open_issues + (rangeRow.open_prs ?? 0)) : null,
        sub: `${last.open_issues ?? 0} issues · ${last.open_prs ?? 0} prs`,
        spark: sparkOf(r => (r.open_issues ?? 0) + (r.open_prs ?? 0)),
        color: C.red,
      },
      {
        key: 'pulse', label: 'Health pulse',
        custom: renderPulseCard(pulse),
        klass: 'kpi-pulse',
      },
    ];

    mount.innerHTML = cards.map(c => {
      if (c.custom) {
        return `<div class="kpi ${c.klass || ''}" data-key="${c.key}" tabindex="0">${c.custom}</div>`;
      }
      const isBig = c.value != null && Math.abs(c.value) > 9999;
      const valHtml = isBig
        ? `<div class="value" title="${escapeAttr(fmt(c.value))}">${escapeHtml(fmtShort(c.value))}</div>`
        : `<div class="value">${fmt(c.value)}</div>`;
      const hero = c.hero ? ' is-hero' : '';
      const sparkOk = c.spark && c.spark.length >= 2 &&
                      c.spark.some(v => v != null && v !== 0);
      const sparkHtml = sparkOk
        ? `<canvas class="spark" id="spark-${c.key}" aria-hidden="true"></canvas>`
        : '';
      const subHtml = c.sub
        ? `<div class="deltas"><span class="delta" style="color:var(--muted)">${escapeHtml(c.sub)}</span></div>`
        : deltaHtml(c.value, c.yday, c.wk, c.rangeAgo, rangeLabel);
      const titleAttr = c.title ? ` title="${escapeAttr(c.title)}"` : '';
      return `
        <div class="kpi${hero}${sparkOk ? ' has-spark' : ''}" data-key="${c.key}" tabindex="0"${titleAttr}>
          <div class="label">${escapeHtml(c.label)}</div>
          ${valHtml}
          ${subHtml}
          ${sparkHtml}
        </div>`;
    }).join('');

    cards.forEach(c => {
      if (!c.spark) return;
      const sparkOk = c.spark.length >= 2 && c.spark.some(v => v != null && v !== 0);
      if (!sparkOk) return;
      drawSparkline('spark-' + c.key, c.spark, c.color, !!c.sparkGradient);
    });
  }

  /**
   * Health pulse — a synthesized "is this app catching on?" score.
   *
   * Combines:
   *  - clones-week-over-week change (weighted 0.4)
   *  - views-week-over-week change  (weighted 0.3)
   *  - new-stars in the last 7 days (weighted 0.3, normalized to expected)
   *
   * Returns { label, klass, detail } — label is short ("growing fast"),
   * klass is one of good/warn/bad/neutral, detail explains the inputs.
   */
  function computeHealthPulse(rows) {
    if (!rows.length) return { label: '—', klass: '', detail: 'not enough data' };

    const clonesS = clonesSeries(rows);
    const viewsS  = viewsSeries(rows);

    function pctChange(series, days) {
      if (series.length < days * 2) return null;
      const cur  = series.slice(-days).reduce((a, p) => a + (p.count || 0), 0);
      const prev = series.slice(-days * 2, -days).reduce((a, p) => a + (p.count || 0), 0);
      if (prev === 0) return cur > 0 ? 100 : 0;
      return ((cur - prev) / prev) * 100;
    }

    const clonesWow = pctChange(clonesS, 7);
    const viewsWow  = pctChange(viewsS,  7);

    // New stars in last 7d (from snapshot deltas — fast and good enough).
    let starsLast7 = null;
    if (rows.length >= 2) {
      const last = rows[rows.length - 1];
      const iso7 = isoDaysAgo(7, last.date);
      const fromTl = cumAt(last.stars_timeline, iso7);
      const past = fromTl != null ? fromTl : rowOnOrBefore(rows, iso7)?.stars;
      if (last.stars != null && past != null) {
        starsLast7 = last.stars - past;
      }
    }

    // Compose. Each component contributes a normalized score in [-1, 1].
    function norm(v, scale) {
      if (v == null) return null;
      return Math.max(-1, Math.min(1, v / scale));
    }
    const parts = [];
    let weightSum = 0;
    let sumScore = 0;
    const cN = norm(clonesWow, 50); // 50% w/w == 1.0
    if (cN != null) { parts.push(cN * 0.4); sumScore += cN * 0.4; weightSum += 0.4; }
    const vN = norm(viewsWow, 50);
    if (vN != null) { parts.push(vN * 0.3); sumScore += vN * 0.3; weightSum += 0.3; }
    if (starsLast7 != null) {
      // A solo-maintainer repo: 1 star/wk = neutral, 10/wk = healthy.
      const sN = norm(starsLast7 - 1, 10);
      sumScore += sN * 0.3; weightSum += 0.3;
    }
    if (weightSum === 0) {
      return { label: '—', klass: '', detail: 'collect 14+ days for a reading' };
    }
    const score = sumScore / weightSum;

    let label, klass;
    if      (score >  0.30) { label = 'growing fast'; klass = 'good'; }
    else if (score >  0.05) { label = 'growing';      klass = 'good'; }
    else if (score > -0.05) { label = 'steady';       klass = 'warn'; }
    else if (score > -0.30) { label = 'slowing';      klass = 'warn'; }
    else                    { label = 'declining';    klass = 'bad';  }

    const bits = [];
    if (clonesWow != null) bits.push(`clones ${fmtPct(clonesWow, {signed:true, fixed:0})} w/w`);
    if (viewsWow  != null) bits.push(`views ${fmtPct(viewsWow, {signed:true, fixed:0})} w/w`);
    if (starsLast7 != null) bits.push(`${starsLast7 >= 0 ? '+' : ''}${starsLast7} stars/7d`);
    return { label, klass, detail: bits.join(' · ') };
  }

  function renderPulseCard(p) {
    const arrow = p.klass === 'good' ? '↗' : p.klass === 'bad' ? '↘' : '→';
    return `
      <div class="label">Health pulse</div>
      <div class="pulse">
        <span class="pulse-dot ${p.klass}" aria-hidden="true"></span>
        <span class="pulse-label">${arrow} ${escapeHtml(p.label)}</span>
      </div>
      <div class="pulse-detail">${escapeHtml(p.detail || '')}</div>`;
  }

  function drawSparkline(canvasId, data, color, gradient) {
    const el = document.getElementById(canvasId);
    if (!el) return;
    if (sparkCharts[canvasId]) { sparkCharts[canvasId].destroy(); }
    const ctx = el.getContext('2d');
    let stroke = color;
    let fill = color + '33';
    if (gradient) {
      const grad = ctx.createLinearGradient(0, 0, el.width || 200, 0);
      grad.addColorStop(0, C.pink);
      grad.addColorStop(0.5, C.purple);
      grad.addColorStop(1, C.cyan);
      stroke = grad;
      const fgrad = ctx.createLinearGradient(0, 0, 0, 38);
      fgrad.addColorStop(0, 'rgba(177,74,255,0.30)');
      fgrad.addColorStop(1, 'rgba(255, 255, 255, 0.000)');
      fill = fgrad;
    }
    sparkCharts[canvasId] = new Chart(ctx, {
      type: 'line',
      data: {
        labels: data.map((_, i) => i),
        datasets: [{
          data, borderColor: stroke, backgroundColor: fill,
          fill: true, tension: 0.32,
          pointRadius: 0, pointHoverRadius: 3,
          borderWidth: 1.5,
        }]
      },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { display: false }, tooltip: { enabled: false } },
        scales: { x: { display: false }, y: { display: false } },
        animation: false,
      }
    });
  }

  // ===================================================================
  //  FUNNEL
  // ===================================================================

  function renderFunnel(rows) {
    const mount = $('#funnel');
    if (!rows.length) { mount.innerHTML = ''; return; }
    const last = rows[rows.length - 1];

    // Views (14d) — sum of views_window if available, else use today's count.
    const win14 = Array.isArray(last.views_window) ? last.views_window : null;
    const cwin14 = Array.isArray(last.clones_window) ? last.clones_window : null;
    const views14  = win14  ? sum(win14.map(p => p.count || 0))  : (last.views?.count ?? 0);
    const clones14 = cwin14 ? sum(cwin14.map(p => p.count || 0)) : (last.clones?.count ?? 0);
    const stars  = last.stars ?? 0;
    const forks  = last.forks ?? 0;

    const steps = [
      { stage: 'Views',  scope: '· 14d',    value: views14,  klass: '' },
      { stage: 'Clones', scope: '· 14d',    value: clones14, klass: 'is-hero' },
      { stage: 'Stars',  scope: '· lifetime', value: stars,  klass: '' },
      { stage: 'Forks',  scope: '· lifetime', value: forks,  klass: '' },
    ];
    const max = Math.max(...steps.map(s => s.value || 0), 1);
    // Conversion labels go between steps.
    function conv(a, b) {
      if (!a || a === 0) return '—';
      const pct = (b / a) * 100;
      // Cap displayed "very small" pcts at one decimal, very large at zero.
      if (pct >= 100) return Math.round(pct) + '%';
      if (pct >= 10)  return pct.toFixed(0) + '%';
      if (pct >= 1)   return pct.toFixed(1) + '%';
      return pct.toFixed(2) + '%';
    }
    mount.innerHTML = steps.map((s, i) => {
      const fill = Math.max(8, Math.min(100, (s.value / max) * 100));
      const last = i === steps.length - 1;
      const next = steps[i + 1];
      const convPct = !last ? conv(s.value, next.value) : '';
      const convLabel = !last ? `${escapeHtml(steps[i].stage.toLowerCase())} → ${escapeHtml(next.stage.toLowerCase())}` : '';
      return `
        <div class="funnel-step ${s.klass}" style="--fill:${fill}%">
          <div>
            <div class="funnel-stage">${escapeHtml(s.stage)}<span class="scope">${escapeHtml(s.scope)}</span></div>
            <div class="funnel-value">${escapeHtml(fmtShort(s.value))}</div>
          </div>
          ${!last ? `<div class="funnel-conv"><span class="pct">${escapeHtml(convPct)}</span> · ${convLabel}</div>` : ''}
          ${!last ? `<div class="funnel-arrow" aria-hidden="true">›</div>` : ''}
        </div>`;
    }).join('');

    // All-time clones — the number GitHub can't show (it only keeps 14
    // days). clonesSeriesAllTime() unions EVERY snapshot's window, and the
    // page always holds the WHOLE archive (the server no longer trims it by
    // range), so this is the same number on every range chip. Days the
    // archive never captured are counted and named, not papered over.
    //
    // The users tile next to it is filled by renderUsage() from the fleet:
    // installs that finished a render. It used to be "sum of daily unique
    // clone IPs ÷ 1.7" — a guess with a made-up divisor, summed only over
    // the rows the range trim left (971 on the 7-day view), that counted one
    // person cloning on three days as three.
    const _at = clonesSeriesAllTime(rows);
    const _atClones = _at.reduce((a, p) => a + (p.count || 0), 0);
    const _setTxt = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = v; };
    _setTxt('ath-clones', fmt(_atClones));
    if (_at.length) {
      const first = _at[0].date, lastD = _at[_at.length - 1].date;
      const span = Math.round((Date.parse(lastD) - Date.parse(first)) / 86_400_000) + 1;
      const missing = Math.max(0, span - _at.length);
      _setTxt('ath-clones-sub', `${_at.length} days archived since ${first}`
        + (missing ? ` · ${missing} day${missing === 1 ? '' : 's'} never captured` : '')
        + ' · GitHub only keeps 14');
    }
  }

  // ===================================================================
  //  CHARTS — common defaults + helpers.
  // ===================================================================

  Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif';
  Chart.defaults.font.size = 11;
  Chart.defaults.color = C.muted;
  Chart.defaults.borderColor = C.border;
  Chart.defaults.plugins.legend.display = false;

  function commonOpts(opts) {
    return Object.assign({
      responsive: true, maintainAspectRatio: false,
      interaction: { intersect: false, mode: 'index' },
      scales: {
        x: {
          grid: { color: C.grid, drawBorder: false },
          ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8, color: C.muted },
        },
        y: {
          grid: { color: C.grid, drawBorder: false },
          ticks: { precision: 0, color: C.muted, callback: v => fmtShort(v) },
          beginAtZero: true,
        },
      },
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: C.tooltipBg,
          borderColor: C.border, borderWidth: 1,
          titleColor: C.text, bodyColor: C.muted,
          titleFont: { weight: '600', size: 11.5 },
          bodyFont: { size: 11.5, family: '-apple-system, system-ui, sans-serif' },
          padding: 10, cornerRadius: 6,
          callbacks: {
            label: ctx => {
              const lbl = ctx.dataset.label || '';
              const v = ctx.parsed.y ?? ctx.parsed;
              const num = (v == null || Number.isNaN(v))
                ? '—' : Number(v).toLocaleString();
              return (lbl ? lbl + ':  ' : '') + num;
            }
          }
        },
      },
    }, opts || {});
  }

  function destroyChart(id) {
    if (charts[id]) { charts[id].destroy(); delete charts[id]; }
  }

  /**
   * Render an "empty / unavailable" message inside a chart-wrap WITHOUT
   * destroying the canvas. We hide the canvas and stamp an absolute-
   * positioned message on top; on the next render, removeEmpty() clears
   * the message and unhides the canvas. This way period changes can
   * re-fill a chart that was previously empty.
   */
  function chartEmpty(id, message) {
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    const wrap = el.parentElement;
    if (!wrap) return;
    el.style.display = 'none';
    let overlay = wrap.querySelector('.chart-empty');
    if (!overlay) {
      overlay = document.createElement('div');
      overlay.className = 'chart-empty';
      wrap.appendChild(overlay);
    }
    overlay.textContent = message;
    overlay.style.display = '';
  }
  function clearEmpty(id) {
    const el = document.getElementById(id);
    if (!el) return;
    el.style.display = '';
    const wrap = el.parentElement;
    const overlay = wrap && wrap.querySelector('.chart-empty');
    if (overlay) overlay.style.display = 'none';
  }

  // ===================================================================
  //  CHART — Stars + Forks growth (dual line, secondary axis).
  // ===================================================================

  function renderGrowthChart(slice, rows, period) {
    const id = 'chart-growth';
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    if (!slice.length) return;
    clearEmpty(id);

    const last = rows[rows.length - 1] || {};

    // Prefer the cumulative timelines (stars_timeline / forks_timeline) when
    // present — they're back-filled from the full GitHub history and give
    // useful resolution even when we only have one or two daily snapshots.
    // Fall back to the per-row sequence otherwise.
    const useTimelines =
      Array.isArray(last.stars_timeline) && last.stars_timeline.length >= 2 ||
      Array.isArray(last.forks_timeline) && last.forks_timeline.length >= 2;

    let labels, starsData, forksData;
    if (useTimelines) {
      const st = sliceTimelineByPeriod(last.stars_timeline || [], period);
      const ft = sliceTimelineByPeriod(last.forks_timeline || [], period);
      // Union of dates so both series line up.
      const dateSet = new Set([...st.map(p => p.date), ...ft.map(p => p.date)]);
      const dates = [...dateSet].sort();
      const sMap = new Map(st.map(p => [p.date, p.count]));
      const fMap = new Map(ft.map(p => [p.date, p.count]));
      // Carry-forward cumulative values (so a missing day doesn't dip the line).
      let lastS = null, lastF = null;
      labels    = dates.map(d => d.slice(5));
      starsData = dates.map(d => {
        if (sMap.has(d)) lastS = sMap.get(d);
        return lastS;
      });
      forksData = dates.map(d => {
        if (fMap.has(d)) lastF = fMap.get(d);
        return lastF;
      });
    } else {
      labels    = slice.map(r => (r.date || '').slice(5));
      starsData = slice.map(r => r.stars ?? null);
      forksData = slice.map(r => r.forks ?? null);
    }

    // If the magnitudes differ a lot (stars >> forks usually), use a
    // secondary axis so forks don't sit flat at the bottom.
    const starMax = Math.max(...starsData.filter(v => v != null), 0);
    const forkMax = Math.max(...forksData.filter(v => v != null), 0);
    const useDualAxis = starMax > 0 && forkMax > 0 && (starMax / Math.max(forkMax, 1)) > 4;

    charts[id] = new Chart(el.getContext('2d'), {
      type: 'line',
      data: {
        labels,
        datasets: [
          {
            label: 'stars',
            data: starsData,
            borderColor: C.accent,
            backgroundColor: C.accent + '22',
            yAxisID: 'y',
            fill: true, tension: 0.25, borderWidth: 2,
            pointRadius: 0, pointHoverRadius: 4,
          },
          {
            label: 'forks',
            data: forksData,
            borderColor: C.purple,
            backgroundColor: C.purple + '22',
            yAxisID: useDualAxis ? 'y1' : 'y',
            fill: !useDualAxis, tension: 0.25, borderWidth: 2,
            pointRadius: 0, pointHoverRadius: 4,
          },
        ],
      },
      options: commonOpts({
        scales: {
          x: { grid: { color: C.grid }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8, color: C.muted } },
          y: { position: 'left',  grid: { color: C.grid }, ticks: { precision: 0, color: C.muted, callback: v => fmtShort(v) }, beginAtZero: true },
          y1: useDualAxis
            ? { position: 'right', grid: { display: false }, ticks: { precision: 0, color: C.purple, callback: v => fmtShort(v) }, beginAtZero: true }
            : { display: false },
        },
      }),
    });
  }

  // ===================================================================
  //  CHART — Clones · history (dedicated line chart).
  //  Period comes from the global range control; only bucketing
  //  (clonesAllTime.bucket) is this chart's own state. Bucketing keeps
  //  long ranges readable (weekly default; monthly for multi-year).
  // ===================================================================

  function updateClonesDerivedKpis(rangeSeries) {
    // rangeSeries is the per-day series for the selected period (NOT bucketed).
    // We compute the derived metrics on the daily granularity so the
    // numbers don't change when the user flips daily↔weekly↔monthly.
    const totalClones = rangeSeries.reduce((a, p) => a + (p.count || 0), 0);
    const totalUniques = rangeSeries.reduce((a, p) => a + (p.uniques || 0), 0);
    const dayCount = rangeSeries.length;

    // GitHub publishes unique cloners PER DAY only, so the most this
    // archive can honestly say is the sum of those: an upper bound on
    // distinct cloners (one person cloning on 3 days counts 3x). The old
    // tile divided it by a made-up 1.7 and called it "installers".
    const estInstallers = totalUniques;

    // Retry pressure — across the range, weighted properly: total
    // clones / total uniques. >1.5 = people are re-cloning a lot.
    const retryRate = totalUniques > 0 ? (totalClones / totalUniques) : 0;

    // Recent 7-day avg of daily uniques (recent install activity).
    const recent7 = rangeSeries.slice(-7);
    const recent7Sum = recent7.reduce((a, p) => a + (p.uniques || 0), 0);
    const recent7Avg = recent7.length ? recent7Sum / recent7.length : 0;

    const $val = (id) => document.getElementById(id);
    const $set = (id, v) => { const e = $val(id); if (e) e.textContent = v; };
    $set('ck-total', fmt(totalClones));
    $set('ck-total-sub', `over ${dayCount} day${dayCount === 1 ? '' : 's'} in range`);
    $set('ck-est', fmt(estInstallers));
    $set('ck-retry', retryRate > 0 ? retryRate.toFixed(2) + '×' : '—');
    $set('ck-recent', recent7Avg > 0 ? Math.round(recent7Avg).toLocaleString() : '—');
  }

  function renderClonesHistoryChart(rows) {
    const id = 'chart-clones-history';
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    // Reset KPIs to em-dash before any early-return.
    ['ck-total','ck-est','ck-retry','ck-recent'].forEach(k => {
      const e = document.getElementById(k); if (e) e.textContent = '—';
    });
    if (!rows.length) {
      chartEmpty(id, 'no clones data yet — first snapshot fetches within 90s of panel boot');
      return;
    }
    let dailySeries = clonesSeriesAllTime(rows);
    dailySeries = sliceTimelineByPeriod(dailySeries, globalRange);
    if (!dailySeries.length) {
      chartEmpty(id, 'no clones data in this range');
      return;
    }
    // Compute derived KPIs from the DAILY series (before bucketing) so
    // the numbers are bucket-independent.
    updateClonesDerivedKpis(dailySeries);

    // Add a 7-day rolling average on top of the daily uniques for
    // smoother trend reading. Only meaningful when bucket=daily.
    let series = bucketTimeline(dailySeries, clonesAllTime.bucket);

    // Release markers — surface release dates in the footnote so users
    // can correlate spikes. Pulled from release_timeline if present in
    // the latest row.
    const lastRow = rows[rows.length - 1] || {};
    const releases = Array.isArray(lastRow.release_timeline)
      ? lastRow.release_timeline.slice().sort(
          (a, b) => (a.published_at || '') < (b.published_at || '') ? -1 : 1
        )
      : [];
    const relMarker = document.getElementById('clones-releases-marker');
    if (relMarker) {
      if (releases.length) {
        const txt = releases.slice(-4).map(r => {
          const date = (r.published_at || '').slice(0, 10);
          return `<code>${escapeHtml(r.tag || '?')}</code> ${escapeHtml(date)}`;
        }).join(' · ');
        relMarker.innerHTML = ` &nbsp;<span class="lbl">recent releases:</span> ${txt}`;
      } else {
        relMarker.innerHTML = '';
      }
    }

    clearEmpty(id);

    const labelEl = document.getElementById('clones-bucket-label');
    if (labelEl) {
      labelEl.textContent = ({ daily: 'day', weekly: 'week', monthly: 'month' })[clonesAllTime.bucket] || 'day';
    }

    // Label formatting depends on bucket: daily/weekly show MM-DD, monthly shows YYYY-MM.
    const labelFmt = (d) => clonesAllTime.bucket === 'monthly' ? d : d.slice(5);

    charts[id] = new Chart(el.getContext('2d'), {
      type: 'line',
      data: {
        labels: series.map(p => labelFmt(p.date)),
        datasets: [
          {
            label: 'total clones',
            data: series.map(p => p.count || 0),
            borderColor: C.green,
            backgroundColor: C.green + '22',
            fill: true,
            tension: 0.25,
            pointRadius: series.length < 60 ? 3 : 0,
            pointHoverRadius: 5,
            borderWidth: 2,
          },
          {
            label: 'unique IPs',
            data: series.map(p => p.uniques || 0),
            borderColor: C.green + 'aa',
            borderDash: [4, 4],
            backgroundColor: 'transparent',
            fill: false,
            tension: 0.25,
            pointRadius: 0,
            pointHoverRadius: 4,
            borderWidth: 1.5,
          },
        ],
      },
      options: commonOpts(),
    });
  }

  // ===================================================================
  //  CHART — Clones + Views per day (grouped bars).
  //  Uses clonesSeries / viewsSeries (window-aware) so day-1 has detail.
  // ===================================================================

  function renderTrafficChart(rows, period) {
    const id = 'chart-traffic';
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    if (!rows.length) return;

    let cs = clonesSeries(rows);
    let vs = viewsSeries(rows);
    if (!cs.length && !vs.length) {
      chartEmpty(id, 'no traffic data yet');
      return;
    }
    clearEmpty(id);
    cs = sliceTimelineByPeriod(cs, period);
    vs = sliceTimelineByPeriod(vs, period);

    // Union labels across both series (sorted).
    const dateSet = new Set([...cs.map(p => p.date), ...vs.map(p => p.date)]);
    const dates = [...dateSet].sort();
    const cMap = new Map(cs.map(p => [p.date, p.count || 0]));
    const vMap = new Map(vs.map(p => [p.date, p.count || 0]));

    charts[id] = new Chart(el.getContext('2d'), {
      type: 'bar',
      data: {
        labels: dates.map(d => d.slice(5)),
        datasets: [
          {
            label: 'clones',
            data: dates.map(d => cMap.get(d) ?? 0),
            backgroundColor: C.green + 'cc',
            borderRadius: 2,
            categoryPercentage: 0.8, barPercentage: 0.95,
          },
          {
            label: 'views',
            data: dates.map(d => vMap.get(d) ?? 0),
            backgroundColor: C.amber + 'cc',
            borderRadius: 2,
            categoryPercentage: 0.8, barPercentage: 0.95,
          },
        ],
      },
      options: commonOpts(),
    });
  }

  // ===================================================================
  //  CHART — Issue + PR velocity (weekly stacked).
  //  Opened above x-axis, closed below (negative). Stacks issues + PRs.
  // ===================================================================

  function rollupWeekly(daily) {
    // daily: [{date, count}]. Returns map weekStart -> count.
    const out = new Map();
    if (!Array.isArray(daily)) return out;
    for (const p of daily) {
      const d = new Date(p.date);
      if (!Number.isFinite(d.getTime())) continue;
      // Week starts Monday.
      const day = d.getUTCDay();
      const offset = (day + 6) % 7;
      d.setUTCDate(d.getUTCDate() - offset);
      const key = d.toISOString().slice(0, 10);
      out.set(key, (out.get(key) || 0) + (Number(p.count) || 0));
    }
    return out;
  }

  function renderVelocityChart(rows, period) {
    const id = 'chart-velocity';
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    const last = rows[rows.length - 1] || {};

    const haveAny = ['issues_opened', 'issues_closed', 'prs_opened', 'prs_closed']
      .some(k => Array.isArray(last[k]) && last[k].length);
    if (!haveAny) {
      chartEmpty(id, 'issue/PR velocity will appear once the fetcher emits the new fields');
      return;
    }

    const ioW = rollupWeekly(sliceTimelineByPeriod(last.issues_opened || [], period));
    const icW = rollupWeekly(sliceTimelineByPeriod(last.issues_closed || [], period));
    const poW = rollupWeekly(sliceTimelineByPeriod(last.prs_opened    || [], period));
    const pcW = rollupWeekly(sliceTimelineByPeriod(last.prs_closed    || [], period));

    const weekSet = new Set([
      ...ioW.keys(), ...icW.keys(), ...poW.keys(), ...pcW.keys(),
    ]);
    const weeks = [...weekSet].sort();
    if (!weeks.length) {
      chartEmpty(id, 'no velocity data in this range');
      return;
    }
    clearEmpty(id);
    const labels = weeks.map(w => w.slice(5));

    charts[id] = new Chart(el.getContext('2d'), {
      type: 'bar',
      data: {
        labels,
        datasets: [
          {
            label: 'issues opened',
            data: weeks.map(w => (ioW.get(w) || 0)),
            backgroundColor: C.accent + 'cc',
            stack: 'opened',
            borderRadius: 2,
          },
          {
            label: 'prs opened',
            data: weeks.map(w => (poW.get(w) || 0)),
            backgroundColor: C.purple + 'cc',
            stack: 'opened',
            borderRadius: 2,
          },
          {
            label: 'issues closed',
            data: weeks.map(w => -(icW.get(w) || 0)),
            backgroundColor: C.green + 'cc',
            stack: 'closed',
            borderRadius: 2,
          },
          {
            label: 'prs closed',
            data: weeks.map(w => -(pcW.get(w) || 0)),
            backgroundColor: C.cyan + 'aa',
            stack: 'closed',
            borderRadius: 2,
          },
        ],
      },
      options: commonOpts({
        scales: {
          x: { grid: { color: C.grid }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8, color: C.muted },
               stacked: true },
          y: { grid: { color: C.grid }, ticks: { color: C.muted, callback: v => fmtShort(Math.abs(v)) },
               stacked: true },
        },
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: C.tooltipBg, borderColor: C.border, borderWidth: 1,
            titleColor: C.text, bodyColor: C.muted, padding: 10, cornerRadius: 6,
            callbacks: {
              label: ctx => {
                const v = Math.abs(ctx.parsed.y || 0);
                return `${ctx.dataset.label}: ${v.toLocaleString()}`;
              }
            }
          },
        },
      }),
    });
  }

  // ===================================================================
  //  CHART — Commit activity (daily bars).
  // ===================================================================

  function renderCommitsChart(rows, period) {
    const id = 'chart-commits';
    const el = document.getElementById(id);
    if (!el) return;
    destroyChart(id);
    const last = rows[rows.length - 1] || {};

    let tl = Array.isArray(last.commits_timeline) ? last.commits_timeline : null;
    if (!tl || !tl.length) {
      chartEmpty(id, 'commit activity will appear once the fetcher emits commits_timeline');
      return;
    }
    tl = sliceTimelineByPeriod(tl, period);
    if (!tl.length) {
      chartEmpty(id, 'no commits in this range');
      return;
    }
    clearEmpty(id);
    const labels = tl.map(p => (p.date || '').slice(5));
    const data = tl.map(p => p.count || 0);

    charts[id] = new Chart(el.getContext('2d'), {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'commits', data,
          backgroundColor: C.cyan + 'cc',
          borderRadius: 2,
        }],
      },
      options: commonOpts(),
    });
  }

  // ===================================================================
  //  CHARTS — orchestration.
  // ===================================================================

  function renderAllCharts(rows, period) {
    const slice = sliceByPeriod(rows, period);
    renderGrowthChart(slice, rows, period);
    renderTrafficChart(rows, period);
    renderVelocityChart(rows, period);
    renderCommitsChart(rows, period);
  }

  // ===================================================================
  //  TABLES — referrers + paths.
  // ===================================================================

  function referrerHref(name) {
    if (!name) return null;
    const SEARCH_ENGINES = new Set(['google','bing','duckduckgo','yahoo','baidu','yandex','brave']);
    if (SEARCH_ENGINES.has(name.toLowerCase())) return null;
    if (/\s/.test(name)) return null;
    if (!/\./.test(name)) return null;
    const host = name.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    if (!host) return null;
    return 'https://' + host;
  }

  /** Previous-row map for a given table key, used for trend arrows. */
  function prevMap(rows, key, idKey) {
    if (rows.length < 2) return new Map();
    const prev = rows[rows.length - 2];
    const arr = Array.isArray(prev[key]) ? prev[key] : [];
    return new Map(arr.map(r => [r[idKey], r.count || 0]));
  }

  function trendArrow(today, yesterday) {
    if (yesterday == null) return '';
    const diff = (today || 0) - yesterday;
    if (diff === 0) return `<span class="trend flat" title="no change">·</span>`;
    if (diff > 0)  return `<span class="trend up"   title="+${diff.toLocaleString()} vs prior snapshot">↑</span>`;
    return `<span class="trend down" title="${diff.toLocaleString()} vs prior snapshot">↓</span>`;
  }

  // ===================================================================
  //  NEEDS ATTENTION — live board of the actual open issues + PRs.
  //  Reads last.open_items (added by the fetcher). Degrades to hidden
  //  when the field is absent (older snapshot / fetcher).
  // ===================================================================

  /** Terse age like "3d" / "2w" / "5mo" / "1y" for the board rows. */
  function ageShort(iso) {
    const t = new Date(iso).getTime();
    if (!Number.isFinite(t)) return '';
    const s = Math.max(0, (Date.now() - t) / 1000);
    if (s < 3600)      return Math.max(1, Math.floor(s / 60))   + 'm';
    if (s < 86400)     return Math.floor(s / 3600)  + 'h';
    const d = Math.floor(s / 86400);
    if (d < 14)  return d + 'd';
    if (d < 60)  return Math.floor(d / 7)   + 'w';
    if (d < 365) return Math.floor(d / 30)  + 'mo';
    return (d / 365).toFixed(d % 365 === 0 ? 0 : 1).replace(/\.0$/, '') + 'y';
  }

  /** One board row for an open issue / PR. */
  function openItemRow(it) {
    const isPr  = !!it.is_pr;
    const draft = isPr && !!it.draft;
    const kls   = draft ? 'is-draft' : (isPr ? 'is-pr' : 'is-issue');
    const badge = draft
      ? '<span class="item-badge draft">draft</span>'
      : (isPr ? '<span class="item-badge pr">PR</span>'
              : '<span class="item-badge issue">issue</span>');
    const href = it.html_url
      ? escapeAttr(it.html_url)
      : `https://github.com/mrbizarro/phosphene/issues/${encodeURIComponent(it.number)}`;
    const created = it.created_at || '';
    const age = ageShort(created);
    const ageHtml = age
      ? `<span class="dot" aria-hidden="true">·</span><span title="opened ${escapeAttr(created)}">${escapeHtml(age)}</span>`
      : '';
    const commentsHtml = (it.comments > 0)
      ? `<span class="dot" aria-hidden="true">·</span><span class="comments" title="${fmt(it.comments)} comment${it.comments === 1 ? '' : 's'}">💬 ${escapeHtml(String(it.comments))}</span>`
      : '';
    const labels = Array.isArray(it.labels) ? it.labels.slice(0, 4) : [];
    const labelsHtml = labels.length
      ? `<span class="item-labels">` + labels.map(l => {
          const raw = (l && l.color) ? String(l.color).replace(/[^0-9a-fA-F]/g, '') : '';
          const col = /^[0-9a-fA-F]{6}$/.test(raw) ? '#' + raw : 'var(--faint)';
          return `<span class="item-label" style="--lc:${col}">${escapeHtml(l.name || '')}</span>`;
        }).join('') + `</span>`
      : '';
    return `<li>
      <a class="item ${kls}" href="${href}" target="_blank" rel="noopener">
        <div class="item-top">
          ${badge}
          <span class="item-num">#${escapeHtml(String(it.number))}</span>
          <span class="item-title">${escapeHtml(it.title || '(untitled)')}</span>
        </div>
        <div class="item-meta">
          <span class="who">@${escapeHtml(it.author || 'ghost')}</span>
          ${ageHtml}
          ${commentsHtml}
          ${labelsHtml}
        </div>
      </a>
    </li>`;
  }

  function renderOpenItems(rows) {
    const sec = $('#sec-attention');
    if (!sec) return;
    const last = rows[rows.length - 1] || {};
    const items = Array.isArray(last.open_items) ? last.open_items : null;

    // Feature-detect: hide the whole section on a snapshot that predates
    // the fetcher field, so old archives don't show an empty board.
    if (items == null) { sec.hidden = true; return; }
    sec.hidden = false;

    const issues = items.filter(it => !it.is_pr);
    const prs    = items.filter(it =>  it.is_pr);

    // Prefer the authoritative counts (open_issues / open_prs) for the
    // pills — they're the true totals even if the list itself was capped.
    const issuesTotal = (last.open_issues != null) ? last.open_issues : issues.length;
    const prsTotal    = (last.open_prs    != null) ? last.open_prs    : prs.length;
    $('#attn-issues-count').textContent = fmt(issuesTotal);
    $('#attn-prs-count').textContent    = fmt(prsTotal);

    // 8 visible by default; the rest are rendered but hidden behind an
    // in-page "show all" (same pattern as Errors and Releases) — a long
    // backlog used to push every section below it off the screen.
    const SHOWN = 8;

    const paint = (list, listSel, moreSel, total, noun) => {
      const body = $(listSel);
      const more = $(moreSel);
      if (!list.length) {
        body.innerHTML = `<li><div class="board-empty">
          <span class="ok" aria-hidden="true">✓</span>
          <span>No open ${noun} — inbox zero.</span>
        </div></li>`;
        if (more) more.hidden = true;
        return;
      }
      body.innerHTML = list.map((it, i) =>
        openItemRow(it).replace(/^\s*<li/, i >= SHOWN ? '<li hidden' : '<li')).join('');
      const unfetched = Math.max(0, total - list.length);
      const capped = !!last.open_items_truncated;
      const ghNote = (unfetched > 0 || capped)
        ? ` <a href="${REPO_URL}/issues" target="_blank" rel="noopener">${unfetched > 0 ? `+${fmt(unfetched)} more` : 'more'} on GitHub ↗</a>` : '';
      if (!more) return;
      if (list.length > SHOWN) {
        more.hidden = false;
        more.innerHTML = `<button class="btn ghost list-toggle" type="button">show all ${fmt(list.length)} ${noun}</button>${ghNote}`;
        wireListToggle(more.querySelector('.list-toggle'), body, 'li', SHOWN, list.length, noun);
      } else if (ghNote) {
        more.hidden = false;
        more.innerHTML = ghNote.trim();
      } else {
        more.hidden = true;
      }
    };

    paint(issues, '#attn-issues-list', '#attn-issues-more', issuesTotal, 'issues');
    paint(prs,    '#attn-prs-list',    '#attn-prs-more',    prsTotal,    'PRs');
  }

  // ===================================================================
  //  USAGE — anonymous panel telemetry from /stats/usage.
  //
  //  Runs on its own fetch, independent of the GitHub snapshot archive:
  //  a fresh install with zero /stats/data rows still has usage numbers
  //  from its own boots, and a /stats/data failure must not blank this
  //  section out. One renderer serves both payload sources — the server
  //  hands back the same shape either way and only `source` differs.
  // ===================================================================

  /** Render one {name,count} distribution list with proportional fills. */
  function paintDist(sel, rows, nameKey, opts) {
    const el = $(sel);
    if (!el) return;
    const list = Array.isArray(rows) ? rows : [];
    if (!list.length) {
      el.innerHTML = `<li class="dist-row"><span class="name" style="color:var(--faint)">no data yet</span><span class="n">—</span></li>`;
      return;
    }
    const max = Math.max(1, ...list.map(r => Number(r.count) || 0));
    const cls = (opts && opts.err) ? ' is-err' : '';
    el.innerHTML = list.map(r => {
      const pct = Math.max(2, Math.round(100 * (Number(r.count) || 0) / max));
      const label = r[nameKey];
      const shown = (label === null || label === undefined || label === '')
        ? 'unknown' : String(label);
      const sub = (opts && typeof opts.sub === 'function') ? (opts.sub(r) || '') : '';
      return `<li class="dist-row${cls}">
        <span class="fill" style="width:${pct}%"></span>
        <span class="name" title="${escapeAttr(shown)}">${escapeHtml(shown)}</span>
        <span class="n">${fmt(r.count)}${sub ? `<small class="sub"> ${escapeHtml(sub)}</small>` : ''}</span>
      </li>`;
    }).join('');
  }

  const RANGE_TEXT = { '7': '7d', '30': '30d', '90': '90d', 'all': 'all time' };

  /** "+12%" / "−4%" pill, or '' when there's nothing to compare to
   * (matches _pct_delta on the server: None means no baseline, not 0). */
  function pctDeltaHtml(pct) {
    if (pct == null || !Number.isFinite(pct)) return '';
    if (pct === 0) return ` <span class="trend flat">±0%</span>`;
    const cls = pct > 0 ? 'up' : 'down';
    const sign = pct > 0 ? '+' : '';
    return ` <span class="trend ${cls}">${sign}${pct}%</span>`;
  }

  function renderUsage(u) {
    const sec = $('#sec-usage');
    if (!sec) return;
    sec.hidden = false;

    const isFleet = u.source === 'fleet';
    const rangeTxt = RANGE_TEXT[globalRange] || globalRange;
    const note = $('#usage-note');
    const srcEl = $('#usage-src');
    const noteText = $('#usage-note-text');
    if (note) note.classList.toggle('is-local', !isFleet);
    if (srcEl) srcEl.textContent = isFleet ? 'fleet' : 'this mac';
    if (noteText) {
      let msg;
      if (u.warning) {
        msg = u.warning;
      } else if (isFleet) {
        msg = 'every install that has pinged'
          + (u.cached ? ' · cached, refreshes every 6h' : ' · fresh')
          + (u.partial ? ' · some queries returned nothing' : '');
      } else {
        msg = u.note || 'this machine only — add a PostHog query key in Settings for fleet data';
      }
      noteText.textContent = msg;
    }

    // Headline tiles. Null values render as "—" rather than 0 so
    // "we have no data" never masquerades as "the number is zero".
    const t = u.tiles || {};
    const d = u.deltas || {};
    // "All time" is since the first install that ever pinged — the fleet
    // has a first day and the tile says which, so the number is not read
    // as "since the app existed".
    const firstDay = (((u.growth || {}).installs_by_day || [])[0] || {}).date;
    const since = firstDay ? 'since ' + firstDay : 'all time';
    // THE FLEET IS THE HEADLINE (owner, 2026-09-18: "when I ask you for total
    // renders, I mean total renders from the fleet too… one of the first
    // windows I want to see is total renders for all the fleet"). One tile
    // used to be called "Total renders" and mean the fleet's total or THIS
    // MAC's depending on whether a query key happened to be configured — a
    // number whose meaning moved under the same label. Now the hero is always
    // the fleet, it reads "—" with a remedy when the fleet cannot be reached,
    // and this machine's own total is its own tile that never pretends to be
    // anything else.
    const m = u.machine || {};
    const blocked = String(u.fleet_blocked || '');
    const fleetSub = blocked === 'no_key'
      ? 'add a PostHog read key in Settings'
      : (blocked ? 'PostHog query failed — check the key in Settings'
                 : 'completed · all installs · ' + since);
    const tiles = [
      { label: 'Total renders · fleet', value: isFleet ? fmt(t.total_renders) : '—',
        sub: fleetSub, hero: true, warn: !isFleet,
        title: 'Every render ever completed across every install that has ever reported in, all time — the fleet total, not this machine.' },
      { label: 'Total renders · this Mac',
        value: fmt(isFleet ? m.total_renders : t.total_renders),
        sub: 'completed' + (m.first_day || (!isFleet && firstDay)
             ? ' · since ' + (m.first_day || firstDay) : ''),
        title: 'Renders completed on THIS Mac only, all time.' },
      // THE USER NUMBERS (2026-10-14) — one definition each, the same words
      // everywhere on the page. An "install" is one anonymous install id.
      { label: 'Installs that rendered',
        value: isFleet ? fmt(t.rendered_installs) : '—',
        sub: isFleet ? 'all time · finished ≥1 render · ' + since : fleetSub,
        hero: true, warn: !isFleet,
        title: 'Installs that finished at least one render, all time. The best count of real users we have: '
          + 'an install that never rendered is a failed install, a reinstall that got a new id, or a test boot. '
          + (u.owner_excluded ? 'The maintainer\'s own machines are excluded.' : 'Owner exclusion list not configured — the maintainer\'s own machines are INCLUDED.') },
      { label: 'Installs that opened the app',
        value: isFleet ? fmt(t.total_installs) : '—',
        sub: isFleet
          ? (t.never_rendered_installs != null ? fmt(t.never_rendered_installs) + ' never rendered · ' : '') + 'all time'
          : fleetSub,
        title: 'Every install that ever opened Phosphene with analytics on, all time — including the ones that never finished a render. Always bigger than "installs that rendered"; the gap is failed installs, reinstalls and one-off opens.' },
      { label: globalRange === '7' ? 'Weekly active installs' : `Active installs · ${rangeTxt}`,
        value: fmt(t.active_in_range) + pctDeltaHtml(d.active_in_range_pct),
        sub: globalRange === '7'
          ? 'opened the app in the last 7 days'
          : `opened the app in the last ${rangeTxt}` + (t.weekly_active_installs != null ? ` · weekly ${fmt(t.weekly_active_installs)}` : ''),
        title: `Installs that opened Phosphene at least once in the selected range (${rangeTxt}), vs the same-length period before it. "Weekly active" is this number for 7 days; the growth chart's weekly line uses the same 7-day windows, so its last point equals it.` },
      { label: 'Renders', value: fmt(t.renders_in_range) + pctDeltaHtml(d.renders_in_range_pct),
        sub: 'completed + failed · ' + rangeTxt + ' · ' + (isFleet ? 'all installs' : 'this machine'),
        title: `Renders (successful and failed) in the selected range, vs the same-length period before it.` },
      { label: 'H3 share', value: fmtPct(t.h3_share_pct), sub: 'of renders · ' + rangeTxt,
        title: `Share of renders in the selected range (${rangeTxt}) that used the H3 engine rather than LTX.` },
      { label: 'Error rate', value: fmtPct(t.error_rate_pct)
          // Inverted vs the usual up=green/down=red: for an error rate, a
          // RISE is the bad direction and a FALL is the good one.
          + (d.error_rate_pp != null ? ` <span class="trend ${d.error_rate_pp > 0 ? 'down' : (d.error_rate_pp < 0 ? 'up' : 'flat')}">${d.error_rate_pp > 0 ? '+' : ''}${d.error_rate_pp}pp</span>` : ''),
        sub: 'failed renders · ' + rangeTxt,
        title: `Share of renders that failed in the selected range. The pp badge is the change in percentage points vs the prior period.` },
      { label: 'Refused', value: fmt(t.refusals_in_range), sub: 'declined on purpose · ' + rangeTxt,
        title: 'Renders the panel declined before starting (missing model, bad params, etc.) — never counted as a failure.' },
    ];
    const grid = $('#usage-tiles');
    if (grid) {
      grid.innerHTML = tiles.map(k => `
        <div class="kpi${k.hero ? ' is-hero' : ''}${k.warn ? ' is-unknown' : ''}"${k.title ? ` title="${escapeAttr(k.title)}"` : ''}>
          <div class="label">${escapeHtml(k.label)}</div>
          <div class="value">${k.value}</div>
          <div class="delta">${escapeHtml(k.sub)}</div>
        </div>`).join('');
    }

    renderUsageGrowth(u.growth || {}, isFleet, rangeTxt);

    // The GitHub section's users tile reads the same fleet number.
    const athU = document.getElementById('ath-users');
    const athS = document.getElementById('ath-users-sub');
    if (athU) athU.textContent = isFleet ? fmt(t.rendered_installs) : '—';
    if (athS) athS.textContent = isFleet
      ? `from in-app analytics · ${fmt(t.total_installs)} opened the app, ${fmt(t.never_rendered_installs)} never rendered`
        + (u.owner_excluded ? ' · owner excluded' : ' · owner NOT excluded')
      : fleetSub;

    // Pack-flip alert — the H3-vanished detector. Any true→false
    // transition on any pack counts; h3 is called out by name because
    // it is the one that has actually bitten a user.
    // Counted per INSTALL, split by what happened next. The old line counted
    // EVENTS ("H3 went from installed to missing 8x"): a pack missing at one
    // launch and back at the next is a launch that landed mid-Update, not a
    // broken install, and 6 of those 8 were exactly that. Only "still
    // missing after reopening" is the broken-install signal.
    const flips = u.pack_flips || {};
    const losses = flips.losses || {};
    const PACK_NAMES = { h3: 'H3', q8: 'Q8', sharp: 'Sharp upscale', qwen: 'Qwen image' };
    const lossPacks = Object.keys(losses).sort((a, b) => (a === 'h3' ? -1 : b === 'h3' ? 1 : a < b ? -1 : 1));
    const stillMissing = lossPacks.reduce((a, k) => a + (Number(losses[k].still_missing) || 0), 0);
    const alert = $('#usage-packflip');
    if (alert) {
      if (!lossPacks.length) {
        alert.classList.add('is-clear');
        alert.innerHTML = `<span class="n">0</span><span>installs lost an optional pack in ${escapeHtml(rangeTxt)}.</span>`;
      } else {
        alert.classList.toggle('is-clear', stillMissing === 0);
        const parts = lossPacks.map(k => {
          const b = losses[k];
          const bits = [];
          if (b.recovered) bits.push(`${fmt(b.recovered)} had it back by a later launch`);
          if (b.still_missing) bits.push(`<strong>${fmt(b.still_missing)} still missing after reopening</strong>`);
          if (b.not_seen_since) bits.push(`${fmt(b.not_seen_since)} not opened since`);
          if (b.unconfirmed) bits.push(`${fmt(b.unconfirmed)} not checked (query failed)`);
          return `${escapeHtml(PACK_NAMES[k] || k)} went missing on ${fmt(b.installs)} install${b.installs === 1 ? '' : 's'} (${bits.join(', ')})`;
        });
        alert.innerHTML = `<span class="n">${fmt(stillMissing)}</span><span>install${stillMissing === 1 ? '' : 's'} with a pack still missing · ${escapeHtml(rangeTxt)}. `
          + parts.join('; ') + '. '
          + 'Missing at one launch and back at the next is a launch during an Update, not a broken install; only "still missing after reopening" is.</span>';
      }
    }

    renderErrorGroups(u, rangeTxt);
    const fbv = Array.isArray(u.failures_by_version) ? u.failures_by_version : [];
    paintDist('#usage-failures-by-version', fbv, 'version', { err: true,
      sub: r => `failed · ${r.pct}% of ${fmt((Number(r.failed) || 0) + (Number(r.ok) || 0))} · ${fmt(r.people)} install${Number(r.people) === 1 ? '' : 's'}` });
    const refs2 = Array.isArray(u.top_refusals) ? u.top_refusals : [];
    const refCount = $('#usage-refusals-count');
    if (refCount) refCount.textContent = fmt(refs2.reduce((a, r) => a + (Number(r.count) || 0), 0));
    paintDist('#usage-refusals', refs2, 'refusal');
    paintDist('#usage-versions', u.versions, 'version');
    paintDist('#usage-chips', u.chips, 'chip');
    paintDist('#usage-ram', u.ram, 'ram_gb');
  }

  // ===================================================================
  //  ERRORS — collapsible, grouped by the closed error_class taxonomy.
  //  Collapsed by default; header carries total + trend so the owner
  //  gets signal without opening it. Top 5 groups (sorted by installs
  //  affected, server-side) with a "show all" for the rest.
  // ===================================================================

  const ERROR_CLASS_LABELS = {
    refused: 'Refused', oom_jetsam: 'OOM (jetsam)', metal_watchdog: 'Metal watchdog',
    metal_oom: 'Metal OOM', native_crash: 'Native crash',
    helper_start_timeout: 'Helper start timeout', helper_exit: 'Helper exited',
    model_missing: 'Model missing', model_corrupt: 'Model corrupt',
    download_failed: 'Download failed', venv_broken: 'Venv broken',
    bad_params: 'Bad parameters', input_missing: 'Input missing',
    file_missing: 'File missing', disk_full: 'Disk full',
    export_failed: 'Export failed', timeout: 'Timeout',
    cancelled_race: 'Cancelled (race)', other: 'Other / unclassified',
  };
  function prettyErrorClass(cls) {
    return ERROR_CLASS_LABELS[cls] || String(cls || 'other').replace(/_/g, ' ');
  }

  const ERRORS_SHOWN_DEFAULT = 5;
  let errorGroupsFull = [];

  function errorGroupRowHtml(g) {
    const installsTxt = `${fmt(g.installs)} install${Number(g.installs) === 1 ? '' : 's'}`;
    const firstAgo = g.first_seen ? dayAgo(g.first_seen) : '—';
    const lastAgo = g.last_seen ? dayAgo(g.last_seen) : '—';
    return `
      <div class="error-group">
        <div class="error-group-head">
          <span class="error-group-class">${escapeHtml(prettyErrorClass(g.error_class))}</span>
          <span class="error-group-stat"><strong>${fmt(g.count)}</strong> event${Number(g.count) === 1 ? '' : 's'}</span>
          <span class="error-group-stat"><strong>${installsTxt}</strong> affected</span>
          <span class="error-group-meta" title="first seen ${escapeAttr(g.first_seen || '—')} (UTC)&#10;last seen ${escapeAttr(g.last_seen || '—')} (UTC)">
            first ${escapeHtml(firstAgo)} · last ${escapeHtml(lastAgo)}
          </span>
        </div>
        <div class="error-group-msg" tabindex="0" role="button"
             aria-label="click to show the full message">${escapeHtml(g.top_message || 'unknown error')}</div>
      </div>`;
  }

  function renderErrorGroups(u, rangeTxt) {
    const groups = Array.isArray(u.error_groups) ? u.error_groups.slice() : [];
    errorGroupsFull = groups;
    const total = groups.reduce((a, g) => a + (Number(g.count) || 0), 0);
    const countEl = $('#errors-total-count');
    if (countEl) countEl.textContent = fmt(total);

    const trendEl = $('#errors-trend');
    if (trendEl) {
      const pct = (u.deltas || {}).errors_count_pct;
      if (pct == null || !Number.isFinite(pct)) {
        trendEl.textContent = '';
        trendEl.className = 'errors-trend';
      } else if (pct === 0) {
        trendEl.textContent = '±0% vs prior ' + rangeTxt;
        trendEl.className = 'errors-trend flat';
      } else {
        trendEl.textContent = (pct > 0 ? '+' : '') + pct + '% vs prior ' + rangeTxt;
        trendEl.className = 'errors-trend ' + (pct > 0 ? 'up' : 'down');
      }
    }

    const empty = $('#errors-empty');
    const body = $('#errors-groups');
    const showAll = $('#errors-showall');
    if (!body) return;
    if (!groups.length) {
      if (empty) empty.hidden = false;
      body.innerHTML = '';
      if (showAll) showAll.hidden = true;
      return;
    }
    if (empty) empty.hidden = true;
    body.innerHTML = groups.slice(0, ERRORS_SHOWN_DEFAULT).map(errorGroupRowHtml).join('');
    if (showAll) {
      const rest = groups.length - ERRORS_SHOWN_DEFAULT;
      if (rest > 0) {
        showAll.hidden = false;
        showAll.textContent = `show ${rest} more error class${rest === 1 ? '' : 'es'}`;
        showAll.dataset.expanded = '0';
      } else {
        showAll.hidden = true;
      }
    }
  }

  function initErrorsToggle() {
    const toggle = $('#errors-toggle');
    const body = $('#errors-body');
    if (toggle && body) {
      toggle.addEventListener('click', () => {
        const open = toggle.getAttribute('aria-expanded') === 'true';
        toggle.setAttribute('aria-expanded', String(!open));
        body.hidden = open;
      });
    }
    const showAll = $('#errors-showall');
    if (showAll) {
      showAll.addEventListener('click', () => {
        const body2 = $('#errors-groups');
        if (!body2) return;
        body2.innerHTML = errorGroupsFull.map(errorGroupRowHtml).join('');
        showAll.hidden = true;
      });
    }
    // Expand-on-click for a truncated message — event delegation so it
    // keeps working after re-renders replace the row markup.
    const groupsEl = $('#errors-groups');
    if (groupsEl) {
      groupsEl.addEventListener('click', (e) => {
        const msg = e.target.closest('.error-group-msg');
        if (msg) msg.classList.toggle('is-expanded');
      });
      groupsEl.addEventListener('keydown', (e) => {
        if (e.key !== 'Enter' && e.key !== ' ') return;
        const msg = e.target.closest('.error-group-msg');
        if (msg) { e.preventDefault(); msg.classList.toggle('is-expanded'); }
      });
    }
  }

  // Growth chart: cumulative installs (line, left axis) against renders per
  // day (bars, right axis). Installs are all-time so the line is the shape of
  // the whole project; renders are 30 days so the bars stay readable.
  function renderUsageGrowth(g, isFleet, rangeTxt) {
    const box = $('#usage-growth');
    const id = 'chart-usage-growth';
    const el = document.getElementById(id);
    if (!box || !el) return;
    const inst = Array.isArray(g.installs_by_day) ? g.installs_by_day : [];
    const rend = Array.isArray(g.renders_by_day) ? g.renders_by_day : [];
    const weeks = Array.isArray(g.active_by_week) ? g.active_by_week : [];
    if (!inst.length && !rend.length) { box.hidden = true; return; }
    box.hidden = false;
    destroyChart(id);
    // One date axis: the union of both series, cumulative installs carried
    // forward across days with no new install.
    const dates = [...new Set([...inst.map(p => p.date), ...rend.map(p => p.date)])].sort();
    const cum = new Map(inst.map(p => [p.date, p.cumulative]));
    const rmap = new Map(rend.map(p => [p.date, p.count]));
    let last = null;
    const instData = dates.map(d => { if (cum.has(d)) last = cum.get(d); return last; });
    const rendData = dates.map(d => rmap.has(d) ? rmap.get(d) : null);
    const sub = $('#usage-growth-sub');
    if (sub) {
      const first = weeks[0], now = weeks[weeks.length - 1];
      // Weekly active = installs that opened the app in a 7-day window; the
      // windows end now, so the last value is the "Weekly active" tile.
      const wau = (first && now && weeks.length > 1)
        ? ` · weekly active ${fmt(first.installs)} → ${fmt(now.installs)} (7-day windows ending ${first.week} → ${now.week})` : '';
      const rt = rangeTxt || '30d';
      sub.textContent = (isFleet ? `installs, all time · renders per day, ${rt}` : `this machine · renders per day, ${rt}`) + wau;
    }
    charts[id] = new Chart(el.getContext('2d'), {
      type: 'bar',
      data: {
        labels: dates.map(d => d.slice(5)),
        datasets: [
          { type: 'line', label: 'installs (cumulative)', data: instData, yAxisID: 'y',
            borderColor: '#7c9cff', backgroundColor: 'rgba(124,156,255,.15)', fill: true,
            tension: 0.25, pointRadius: 0, borderWidth: 2, spanGaps: true },
          { type: 'bar', label: 'renders / day', data: rendData, yAxisID: 'y2',
            backgroundColor: 'rgba(233,105,255,.55)', borderWidth: 0 },
        ],
      },
      options: {
        responsive: true, maintainAspectRatio: false, animation: false,
        interaction: { mode: 'index', intersect: false },
        plugins: { legend: { display: true, position: 'bottom' } },
        scales: {
          x: { ticks: { maxTicksLimit: 10, autoSkip: true }, grid: { display: false } },
          y: { position: 'left', beginAtZero: true, title: { display: true, text: 'installs' } },
          y2: { position: 'right', beginAtZero: true, grid: { drawOnChartArea: false },
                title: { display: true, text: 'renders / day' } },
        },
      },
    });
  }

  // 4.17.3 review: a range change while an older request is still in
  // flight let the OLDER response land last and paint 30-day totals under
  // 7-day labels. Each loader stamps its request; a superseded answer is
  // dropped.
  let _usageGen = 0;
  let _rowsGen = 0;
  async function loadUsage(force) {
    const gen = ++_usageGen;
    try {
      const qs = new URLSearchParams({ range: serverRange(globalRange) });
      if (force) qs.set('force', '1');
      const r = await fetch(USAGE_URL + '?' + qs.toString(), { cache: 'no-store' });
      if (!r.ok) throw new Error('HTTP ' + r.status);
      const u = await r.json();
      if (gen !== _usageGen) return;          // a newer range was asked for
      if (u && u.ok === false && !u.tiles) throw new Error(u.error || 'usage unavailable');
      renderUsage(u || {});
    } catch (e) {
      // A panel older than this endpoint 404s — leave the section hidden
      // rather than showing a broken card. Not an error worth surfacing.
      console.debug('usage unavailable:', e && e.message);
    }
  }

  function renderTables(rows) {
    const last = rows[rows.length - 1] || {};
    const refs = Array.isArray(last.referrers) ? last.referrers : [];
    const paths = Array.isArray(last.paths) ? last.paths : [];
    const refBody  = $('#referrers-table tbody');
    const pathBody = $('#paths-table tbody');

    // Bar reference: largest count in this set.
    const refMax  = Math.max(1, ...refs.map(r => r.count || 0));
    const pathMax = Math.max(1, ...paths.map(p => p.count || 0));

    const refPrev  = prevMap(rows, 'referrers', 'referrer');
    const pathPrev = prevMap(rows, 'paths', 'path');

    if (!refs.length) {
      refBody.innerHTML = '<tr><td colspan="3" class="empty">no referrer data yet</td></tr>';
    } else {
      refBody.innerHTML = refs.map(r => {
        const href = referrerHref(r.referrer);
        const name = href
          ? `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(r.referrer)}</a>`
          : escapeHtml(r.referrer);
        const w = Math.max(2, (r.count / refMax) * 100);
        const trend = trendArrow(r.count, refPrev.get(r.referrer));
        return `<tr>
          <td>${name}${trend}</td>
          <td class="num" title="${escapeAttr(fmt(r.count))}">
            ${escapeHtml(fmtShort(r.count))}
            <span class="row-bar" aria-hidden="true"><i style="--w:${w}%"></i></span>
          </td>
          <td class="num" title="${escapeAttr(fmt(r.uniques))}">${escapeHtml(fmtShort(r.uniques))}</td>
        </tr>`;
      }).join('');
    }

    if (!paths.length) {
      pathBody.innerHTML = '<tr><td colspan="3" class="empty">no path data yet</td></tr>';
    } else {
      pathBody.innerHTML = paths.map(p => {
        const w = Math.max(2, (p.count / pathMax) * 100);
        const trend = trendArrow(p.count, pathPrev.get(p.path));
        return `<tr>
          <td>
            <a href="https://github.com${escapeAttr(p.path)}" target="_blank" rel="noopener">${escapeHtml(p.path)}</a>
            ${trend}
          </td>
          <td class="num" title="${escapeAttr(fmt(p.count))}">
            ${escapeHtml(fmtShort(p.count))}
            <span class="row-bar gradient" aria-hidden="true"><i style="--w:${w}%"></i></span>
          </td>
          <td class="num" title="${escapeAttr(fmt(p.uniques))}">${escapeHtml(fmtShort(p.uniques))}</td>
        </tr>`;
      }).join('');
    }
  }

  /** "show all N" / "show fewer" for a list whose overflow rows carry the
   * `hidden` attribute. `keepVisible(el, i)` decides which rows stay
   * visible when collapsed (default: the first `shown`). */
  function wireListToggle(btn, container, rowSel, shown, total, noun, keepVisible) {
    if (!btn) return;
    const keep = keepVisible || ((el, i) => i < shown);
    let open = false;
    btn.addEventListener('click', () => {
      open = !open;
      container.querySelectorAll(rowSel).forEach((el, i) => { el.hidden = open ? false : !keep(el, i); });
      btn.textContent = open ? 'show fewer' : `show all ${fmt(total)} ${noun}`;
    });
  }

  // ===================================================================
  //  RELEASES — only renders when release_timeline is present.
  // ===================================================================

  function renderReleases(rows) {
    const last = rows[rows.length - 1] || {};
    const tl = Array.isArray(last.release_timeline) ? last.release_timeline : null;
    const sec = $('#sec-releases');
    if (!tl || !tl.length) { sec.hidden = true; return; }
    sec.hidden = false;
    // A weights pack is ~90 files per install; its raw file total is not
    // comparable with a code release. Chart and show the number of
    // complete pack downloads (median per-file count) for those rows, and
    // keep the raw file total in the tooltip.
    const shown = r => (String(r.tag || '').startsWith('weights-') && r.pack_downloads != null)
      ? r.pack_downloads : (r.total_downloads || 0);
    const max = Math.max(1, ...tl.map(shown));
    const body = $('#releases-table tbody');
    // Newest first. Collapsed view = the 8 most recent tags plus any older
    // tag whose downloads are notable (>= 10% of the biggest) — ~100 rows
    // of mostly-zero tags used to make up half the page.
    const RECENT = 8;
    const sorted = tl.slice().sort((a, b) => (b.published_at || '') < (a.published_at || '') ? -1 : 1);
    const notable = r => shown(r) > 0 && shown(r) >= max * 0.10;
    const keep = sorted.map((r, i) => i < RECENT || notable(r));
    const keptCount = keep.filter(Boolean).length;
    const note = $('#releases-note');
    if (note) note.textContent = keptCount < sorted.length
      ? `${RECENT} most recent + ${keptCount - Math.min(RECENT, sorted.length)} older with notable downloads · ${fmt(sorted.length)} tags total`
      : `${fmt(sorted.length)} tags`;
    const toggleWrap = $('#releases-more');
    if (toggleWrap) {
      toggleWrap.hidden = keptCount >= sorted.length;
      toggleWrap.innerHTML = `<button class="btn ghost list-toggle" type="button">show all ${fmt(sorted.length)} releases</button>`;
      wireListToggle(toggleWrap.querySelector('.list-toggle'), body, 'tr', RECENT, sorted.length, 'releases',
        (el) => el.dataset.keep === '1');
    }
    body.innerHTML = sorted.map((r, idx) => {
      const isPack = String(r.tag || '').startsWith('weights-') && r.pack_downloads != null;
      // A code tag with no attached files is "source-only": people get it by
      // Pinokio's git pull, which GitHub does not count as a download. A
      // bare "0" read as "nobody installed 4.19".
      const sourceOnly = !isPack && !(Number(r.asset_count) > 0);
      const w = Math.max(2, (shown(r) / max) * 100);
      const when = r.published_at ? new Date(r.published_at) : null;
      const whenStr = (when && Number.isFinite(when.getTime()))
        ? when.toISOString().slice(0, 10) : '—';
      return `<tr data-keep="${keep[idx] ? 1 : 0}"${keep[idx] ? '' : ' hidden'}>
        <td><code>${escapeHtml(r.tag || '—')}</code></td>
        <td class="mono" style="color:var(--muted)">${escapeHtml(whenStr)}</td>
        <td class="num" title="${escapeAttr(isPack
            ? `≈${fmt(r.pack_downloads)} complete downloads of the base pack (median per file). Per pack: ${Object.entries(r.packs || {}).map(([k, v]) => `${k} ≈${fmt(v)}`).join(', ') || '—'}. ${fmt(r.asset_count)} files, ${fmt(r.total_downloads)} file downloads in total — each install fetches every file of its pack.`
            : sourceOnly
              ? 'No files attached to this release: Phosphene installs and updates by git (Pinokio), which GitHub does not count as release downloads. Installs per version are in Usage → Versions.'
              : `${fmt(r.total_downloads)} downloads of ${fmt(r.asset_count)} attached file${Number(r.asset_count) === 1 ? '' : 's'}`)}">${isPack ? escapeHtml(`≈${fmtShort(r.pack_downloads)} packs`) : sourceOnly ? '<span style="color:var(--muted)">source-only</span>' : escapeHtml(fmtShort(r.total_downloads || 0))}</td>
        <td class="num" style="width:30%">
          <span class="row-bar gradient" style="width:100%"><i style="--w:${w}%"></i></span>
        </td>
      </tr>`;
    }).join('');
  }

  // ===================================================================
  //  META BAR — snapshot count + last refresh.
  // ===================================================================

  function renderMeta(rows) {
    const last = rows[rows.length - 1];
    const meta = $('#meta');
    if (!last) {
      meta.textContent = 'no data yet — panel will fetch one shortly';
      return;
    }
    const localStr = (() => {
      const d = new Date(last.fetched_at);
      return Number.isFinite(d.getTime()) ? d.toString() : last.fetched_at;
    })();
    // A stale archive must SAY so. When the daily fetch stopped (Sep 29 →
    // Oct 14 2026) this line read "last refresh 2w ago" in grey and every
    // number below it looked current.
    const ageH = (Date.now() - new Date(last.fetched_at).getTime()) / 3_600_000;
    const stale = Number.isFinite(ageH) && ageH > 36;
    meta.innerHTML = `
      fetched daily · <strong>${rows.length}</strong> ${rows.length === 1 ? 'snapshot' : 'snapshots'} since ${escapeHtml(rows[0].date || '—')} ·
      last refresh
      <strong title="${escapeAttr(last.fetched_at)} (UTC)&#10;${escapeAttr(localStr)} (local)"${stale ? ' style="color:var(--danger)"' : ''}>
        ${escapeHtml(dayAgo(last.fetched_at))}
      </strong>
      ${stale ? `<span class="stale-warn" role="status" style="color:var(--danger)"> · GitHub numbers are ${Math.floor(ageH / 24)} days old — the daily fetch has not run (launchd job com.mrbizarro.phosphene-stats-fetch; log in notes/stats/fetch.log). Traffic older than 14 days is lost for good each day it doesn't.</span>` : ''}
    `;
  }

  // ===================================================================
  //  GLOBAL RANGE — one control drives every chart + the Usage section.
  //  A range change re-fetches from the server (the archive is trimmed
  //  server-side per range, and the Usage tiles/errors are recomputed
  //  over the new window) rather than just re-slicing what's already in
  //  memory, so switching to "All time" after loading "30 days" actually
  //  gets the rest of the archive.
  // ===================================================================

  const RANGE_HINTS = {
    '7':   'last 7 days',
    '30':  'last 30 days',
    '90':  'last 90 days (3 months)',
    'all': 'all time — no delta comparisons (no prior period to compare to)',
  };

  function initGlobalRange() {
    const saved = lsGet(LS_RANGE);
    if (saved && ['7', '30', '90', 'all'].includes(saved)) globalRange = saved;
    const hint = $('#range-bar-hint');
    if (hint) hint.textContent = RANGE_HINTS[globalRange] || '';
    $$('#global-range-chips .chip[data-range]').forEach(b => {
      b.setAttribute('aria-pressed', String(b.dataset.range === globalRange));
      b.addEventListener('click', () => {
        if (b.dataset.range === globalRange) return;
        globalRange = b.dataset.range;
        lsSet(LS_RANGE, globalRange);
        $$('#global-range-chips .chip[data-range]').forEach(x =>
          x.setAttribute('aria-pressed', String(x === b)));
        if (hint) hint.textContent = RANGE_HINTS[globalRange] || '';
        loadAll();
      });
    });
  }

  function initClonesChart() {
    const sb = lsGet(LS_CLONES_BUCKET);
    if (sb && ['daily', 'weekly', 'monthly'].includes(sb)) clonesAllTime.bucket = sb;
    $$('.clones-chip-bucket').forEach(b => {
      b.setAttribute('aria-pressed', String(b.dataset.clonesBucket === clonesAllTime.bucket));
      b.addEventListener('click', () => {
        clonesAllTime.bucket = b.dataset.clonesBucket;
        lsSet(LS_CLONES_BUCKET, clonesAllTime.bucket);
        $$('.clones-chip-bucket').forEach(x =>
          x.setAttribute('aria-pressed', String(x.dataset.clonesBucket === clonesAllTime.bucket))
        );
        renderClonesHistoryChart(allRows);
      });
    });
  }

  // ===================================================================
  //  REFRESH — best-effort POST. Endpoint may 404; fall back to a reload.
  // ===================================================================

  // Usage refresh — busts the server's 6h fleet cache. Separate from the
  // GitHub refresh button because they hit completely different backends
  // (PostHog's query API vs the repo-stats fetcher) with different costs.
  function initUsageRefresh() {
    const btn = $('#usage-refresh');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      btn.classList.add('is-busy');
      btn.disabled = true;
      try { await loadUsage(true); }
      finally { btn.classList.remove('is-busy'); btn.disabled = false; }
    });
  }

  function initRefresh() {
    const btn = $('#refresh-btn');
    if (!btn) return;
    btn.addEventListener('click', async () => {
      btn.classList.add('is-busy');
      btn.disabled = true;
      try {
        // Try the manual endpoint first; if the panel hasn't shipped it
        // yet (404), fall back to just re-loading the data file.
        try {
          await fetch(REFRESH_URL, { method: 'POST', cache: 'no-store' });
        } catch (_) { /* network / 404 — fine, refetch anyway */ }
        // Small delay so any background job has time to land.
        await new Promise(r => setTimeout(r, 600));
        await main();
      } finally {
        btn.classList.remove('is-busy');
        btn.disabled = false;
      }
    });
  }

  // ===================================================================
  //  ERROR STATE
  // ===================================================================

  function showError(err) {
    ['sec-now', 'sec-attention', 'sec-funnel', 'sec-over-time', 'sec-traffic', 'sec-releases']
      .forEach(id => { const e = document.getElementById(id); if (e) e.hidden = true; });
    const meta = $('#meta');
    if (meta) meta.innerHTML = `<span style="color:var(--danger)">could not load stats</span>`;

    const mount = $('#error-mount');
    mount.hidden = false;
    mount.innerHTML = `
      <div class="error-card" role="alert">
        <p class="err-title"><span aria-hidden="true">⚠</span> could not load /stats/data</p>
        <p class="err-msg">${escapeHtml(err.message || String(err))}</p>
        <p class="hint">
          The panel might not have run its first fetch yet — give it about
          90 seconds and click <em>Try again</em>. The data file lives at
          <code>${escapeHtml(JSONL_URL)}</code>.
        </p>
        <div class="err-actions">
          <button class="btn" id="retry-btn" type="button">Try again</button>
          <a class="btn ghost" href="${REPO_URL}" target="_blank" rel="noopener">View repo ↗</a>
        </div>
      </div>`;
    $('#retry-btn').addEventListener('click', () => {
      mount.hidden = true;
      ['sec-now', 'sec-funnel', 'sec-over-time', 'sec-traffic']
        .forEach(id => { const e = document.getElementById(id); if (e) e.hidden = false; });
      main();
    });
  }

  // ===================================================================
  //  Lazy chart init via IntersectionObserver — keeps the first paint
  //  cheap by deferring chart construction until the section is near
  //  the viewport.
  // ===================================================================

  function lazyMountCharts() {
    const section = $('#sec-over-time');
    if (!section) return;
    let drawn = false;
    const draw = () => {
      if (drawn) return;
      drawn = true;
      renderAllCharts(allRows, globalRange);
    };
    if (!('IntersectionObserver' in window)) { draw(); return; }
    const io = new IntersectionObserver(entries => {
      for (const e of entries) {
        if (e.isIntersecting) { draw(); io.disconnect(); return; }
      }
    }, { rootMargin: '300px' });
    io.observe(section);
  }

  // ===================================================================
  //  DATA LOAD
  // ===================================================================

  async function loadRows() {
    const url = JSONL_URL + '?range=' + encodeURIComponent(serverRange(globalRange));
    const r = await fetch(url, { cache: 'no-store' });
    if (!r.ok) throw new Error('HTTP ' + r.status + ' on ' + url);
    const text = await r.text();
    const rows = text.split(/\n+/).filter(Boolean).map(l => {
      try { return JSON.parse(l); }
      catch (e) { console.warn('skipping bad row', e); return null; }
    }).filter(Boolean);
    rows.sort((a, b) => (a.date || '') < (b.date || '') ? -1 : 1);
    return rows;
  }

  // ===================================================================
  //  MAIN
  // ===================================================================

  async function main() {
    const gen = ++_rowsGen;
    try {
      const rows = await loadRows();
      if (gen !== _rowsGen) return;           // a newer range was asked for
      allRows = rows;
      renderMeta(allRows);
      if (!allRows.length) {
        $('#kpi-grid').setAttribute('aria-busy', 'false');
        $('#kpi-grid').innerHTML =
          '<div class="empty" style="grid-column:1 / -1">no snapshots yet — panel will fetch one in the background within 90s</div>';
        $('#funnel').innerHTML = '';
        return;
      }
      renderKpiStrip(allRows);
      renderOpenItems(allRows);
      renderFunnel(allRows);
      renderTables(allRows);
      renderReleases(allRows);
      // Render the clones-history chart immediately (small, cheap). The
      // bigger over-time grid is still lazy-mounted via intersection
      // observer below.
      renderClonesHistoryChart(allRows);
      lazyMountCharts();
    } catch (e) {
      console.error(e);
      showError(e);
    }
  }

  // Runs both data sources for the CURRENT globalRange. Called at boot and
  // every time the range chip changes — the archive and the usage
  // telemetry are independent sources (either can be empty or broken
  // without taking the other down), so they're kicked off together but
  // not awaited on each other.
  function loadAll() {
    main();
    loadUsage(false);
  }

  // ===================================================================
  //  BOOT
  // ===================================================================
  initGlobalRange();
  initClonesChart();
  initRefresh();
  initUsageRefresh();
  initErrorsToggle();
  loadAll();
  </script>
</body>
</html>