# #136 — Cross-Filtering Bento Analytics

> Daylight bento analytics dashboard where clicking any chart bar, referrer, country, or device cross-filters every card live.

## Metadata

- **Index**: #136
- **Slug**: `bento-crossfilter-analytics`
- **Kind**: `ui`
- **Family**: Analytics & Data
- **Theme**: `light`
- **Mobile Strength**: `high`
- **Tags**: `analytics`, `cross-filtering`, `bento-grid`, `dashboard`, `data-viz`, `interactive-charts`
- **Best For**: Web and product telemetry dashboards, E-commerce conversion and funnel analytics, Marketing attribution and campaign explorers, SaaS usage and cohort reporting
- **Real-World Inspiration**: [Plausible Analytics](https://plausible.io/)
- **Detail Page**: https://templates.michaelpitts.net/t/bento-crossfilter-analytics
- **Live Demo**: https://templates.michaelpitts.net/demos/bento-crossfilter-analytics.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/bento-crossfilter-analytics

## Why This Aesthetic Is Unique

Eliminates separate filter dropdown forms by turning every chart bar and breakdown row into a direct cross-filter toggle with removable active filter chips at the top.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Cloud Canvas | `#F5F7FB` |
| `surface` | Bento White | `#FFFFFF` |
| `ink` | Graphite Ink | `#111827` |
| `accent` | Plausible Indigo | `#4F46E5` |
| `muted` | Metric Gray | `#6B7280` |

## Typography

- **Display**: `Inter`
- **Body**: `Inter`
- **Mono**: `JetBrains Mono`
- **Scale Notes**: 26px tabular-nums KPI figures, 13px breakdown row labels, 11px uppercase card headers.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&family=JetBrains+Mono:wght@500;600&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&family=JetBrains+Mono:wght@500;600&display=swap">
  ```

## Layout Architecture

Responsive 4-up KPI strip + full-width interactive traffic chart + 2-column bento breakdown cards on desktop; graceful 2-up KPI grid and single-column bento stack on mobile.

## Interaction & Micro-Motion Rules

Clicking any Source, Country, Device, or Day bar toggles a live cross-filter that recalculates all KPIs, bars, and proportional background meters instantaneously.

## Mobile & Responsive Rules

Every filterable breakdown row maintains >=44px height with clear active-state borders and a sticky/top active-filter chip bar with one-tap Clear All.

## Agent Guardrails

### DO
- Use font-variant-numeric: tabular-nums on all KPI metrics and table percentages so numbers never jitter.
- Surface active cross-filters as removable chips with a one-click Reset button.
- Make the interactive affordance obvious with hover/active states on clickable bars and rows.

### DON'T
- Never cross-filter silently without showing which filters are currently applied.
- Avoid tiny un-tappable SVG slices or bars on 390px mobile viewports.

## Complete Standalone Starter Code

File: `demos/bento-crossfilter-analytics.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PulseMetrics — Cross-Filtering Bento Analytics</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #f6f8fc;
      --card: #ffffff;
      --card-subtle: #f8fafc;
      --border: #e2e8f0;
      --border-strong: #cbd5e1;
      --ink: #0f172a;
      --ink-muted: #64748b;
      --indigo: #4f46e5;
      --indigo-soft: #eef2ff;
      --indigo-bar: rgba(79, 70, 229, 0.16);
      --emerald: #059669;
      --emerald-soft: #ecfdf5;
      --rose: #e11d48;
      --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      --font-mono: 'JetBrains Mono', ui-monospace, monospace;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    html, body {
      min-height: 100%;
      background: var(--bg);
      color: var(--ink);
      font-family: var(--font-sans);
      -webkit-font-smoothing: antialiased;
      overflow-x: hidden;
    }

    .page {
      max-width: 1240px;
      margin: 0 auto;
      padding: 22px 20px 44px;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    /* Header */
    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      flex-wrap: wrap;
    }

    .site-id {
      display: flex;
      align-items: center;
      gap: 11px;
    }

    .site-logo {
      width: 36px;
      height: 36px;
      border-radius: 10px;
      background: var(--indigo);
      color: #fff;
      display: grid;
      place-items: center;
      font-weight: 700;
      font-size: 16px;
      box-shadow: 0 4px 12px rgba(79, 70, 229, 0.28);
    }

    .site-id h1 {
      font-size: 18px;
      font-weight: 700;
      letter-spacing: -0.02em;
    }

    .live-pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      font-weight: 500;
      color: var(--emerald);
      background: var(--emerald-soft);
      padding: 4px 10px;
      border-radius: 99px;
      margin-top: 2px;
    }

    .live-dot {
      width: 7px;
      height: 7px;
      border-radius: 50%;
      background: var(--emerald);
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .period-badge {
      background: var(--card);
      border: 1px solid var(--border);
      padding: 8px 13px;
      border-radius: 9px;
      font-size: 13px;
      font-weight: 500;
      color: var(--ink-muted);
    }

    /* Active Filter Chips Bar */
    .filter-bar {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-wrap: wrap;
      min-height: 36px;
    }

    .filter-hint {
      font-size: 13px;
      color: var(--ink-muted);
    }

    .chip {
      appearance: none;
      border: 1px solid #c7d2fe;
      background: var(--indigo-soft);
      color: #3730a3;
      font-family: var(--font-sans);
      font-size: 12.5px;
      font-weight: 600;
      padding: 0 12px;
      min-height: 36px;
      border-radius: 99px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 7px;
      transition: background 0.15s;
    }
    .chip:hover { background: #e0e7ff; }
    .chip-x { font-size: 14px; opacity: 0.75; }

    .clear-btn {
      appearance: none;
      border: 1px solid var(--border-strong);
      background: var(--card);
      color: var(--ink-muted);
      font-size: 12.5px;
      font-weight: 500;
      padding: 0 12px;
      min-height: 36px;
      border-radius: 99px;
      cursor: pointer;
    }
    .clear-btn:hover { color: var(--ink); background: var(--card-subtle); }

    /* Bento Grid */
    .bento {
      display: grid;
      grid-template-columns: repeat(12, minmax(0, 1fr));
      gap: 16px;
    }

    .card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 14px;
      padding: 18px 20px;
      box-shadow: 0 1px 3px rgba(15, 23, 42, 0.03);
      display: flex;
      flex-direction: column;
      min-width: 0;
    }

    .span-12 { grid-column: span 12; }
    .span-8 { grid-column: span 8; }
    .span-6 { grid-column: span 6; }
    .span-4 { grid-column: span 4; }
    .span-3 { grid-column: span 3; }

    /* KPI Strip */
    .kpi-label {
      font-size: 12px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.04em;
      color: var(--ink-muted);
      margin-bottom: 8px;
    }

    .kpi-value {
      font-size: 28px;
      font-weight: 700;
      letter-spacing: -0.03em;
      line-height: 1.1;
      font-variant-numeric: tabular-nums;
    }

    .kpi-sub {
      margin-top: 8px;
      font-size: 12.5px;
      font-weight: 500;
      color: var(--emerald);
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .kpi-sub.muted { color: var(--ink-muted); }

    /* Card Header */
    .card-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
      margin-bottom: 14px;
    }

    .card-title {
      font-size: 14.5px;
      font-weight: 600;
      color: var(--ink);
    }

    .card-meta {
      font-size: 12px;
      color: var(--ink-muted);
    }

    /* Daily Bar Chart */
    .chart-area {
      display: grid;
      grid-template-columns: repeat(14, minmax(0, 1fr));
      align-items: end;
      gap: 8px;
      height: 196px;
      padding-top: 24px;
      border-bottom: 1px solid var(--border);
    }

    .bar-col {
      appearance: none;
      border: none;
      background: transparent;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      align-items: center;
      gap: 6px;
      cursor: pointer;
      padding: 0;
      position: relative;
    }

    .bar-track {
      width: 100%;
      flex: 1;
      display: flex;
      align-items: flex-end;
      justify-content: center;
    }

    .bar-fill {
      width: 100%;
      max-width: 34px;
      min-height: 6px;
      border-radius: 6px 6px 2px 2px;
      background: #c7d2fe;
      transition: height 0.25s ease, background 0.15s ease, transform 0.15s ease;
    }

    .bar-col:hover .bar-fill {
      background: #818cf8;
    }

    .bar-col.selected .bar-fill {
      background: var(--indigo);
      box-shadow: 0 4px 12px rgba(79, 70, 229, 0.35);
    }

    .bar-val {
      font-family: var(--font-mono);
      font-size: 10.5px;
      color: var(--ink-muted);
      opacity: 0;
      transition: opacity 0.15s;
    }

    .bar-col:hover .bar-val,
    .bar-col.selected .bar-val {
      opacity: 1;
      color: var(--indigo);
      font-weight: 600;
    }

    .bar-day {
      font-size: 11px;
      color: var(--ink-muted);
      padding-bottom: 8px;
      white-space: nowrap;
    }

    .bar-col.selected .bar-day {
      color: var(--indigo);
      font-weight: 700;
    }

    /* Breakdown Rows */
    .list-table {
      display: flex;
      flex-direction: column;
      gap: 7px;
    }

    .row-btn {
      appearance: none;
      border: 1px solid transparent;
      background: transparent;
      width: 100%;
      min-height: 38px;
      border-radius: 8px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 11px;
      text-align: left;
      transition: border-color 0.15s, background 0.15s;
    }

    .row-btn:hover {
      border-color: var(--border-strong);
    }

    .row-btn.selected {
      border-color: var(--indigo);
      background: rgba(79, 70, 229, 0.05);
    }

    .row-bg {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      background: var(--indigo-bar);
      border-radius: 7px;
      transition: width 0.28s ease;
      pointer-events: none;
    }

    .row-btn.emerald .row-bg {
      background: rgba(5, 150, 105, 0.15);
    }

    .row-label {
      position: relative;
      z-index: 1;
      font-size: 13.5px;
      font-weight: 500;
      color: var(--ink);
      display: flex;
      align-items: center;
      gap: 8px;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .row-count {
      position: relative;
      z-index: 1;
      font-family: var(--font-mono);
      font-size: 12.5px;
      font-weight: 600;
      color: var(--ink);
      margin-left: 10px;
      flex-shrink: 0;
    }

    /* Device Segmented Cards */
    .device-grid {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 10px;
      margin-top: 4px;
    }

    .device-card {
      appearance: none;
      border: 1px solid var(--border);
      background: var(--card-subtle);
      border-radius: 10px;
      padding: 12px 10px;
      cursor: pointer;
      text-align: left;
      min-height: 78px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      transition: border-color 0.15s, background 0.15s, transform 0.1s;
    }

    .device-card:hover { border-color: var(--border-strong); }
    .device-card.selected {
      border-color: var(--indigo);
      background: var(--indigo-soft);
    }

    .device-name {
      font-size: 12.5px;
      font-weight: 600;
      color: var(--ink-muted);
    }
    .device-card.selected .device-name { color: var(--indigo); }

    .device-pct {
      font-family: var(--font-mono);
      font-size: 18px;
      font-weight: 700;
      color: var(--ink);
    }

    .device-n {
      font-size: 11.5px;
      color: var(--ink-muted);
    }

    /* Responsive Mobile (390px) */
    @media (max-width: 900px) {
      .span-3 { grid-column: span 6; }
      .span-4, .span-6, .span-8 { grid-column: span 12; }
    }

    @media (max-width: 560px) {
      .page {
        padding: 14px 12px 32px;
        gap: 12px;
      }

      .bento { gap: 12px; }

      .card { padding: 14px; }

      .kpi-value { font-size: 22px; }

      .chart-area {
        gap: 4px;
        height: 164px;
      }

      .bar-day {
        font-size: 9.5px;
      }

      .row-btn {
        min-height: 44px;
      }

      .chip, .clear-btn {
        min-height: 44px;
      }

      .device-grid {
        grid-template-columns: 1fr;
      }

      .device-card {
        flex-direction: row;
        align-items: center;
        min-height: 52px;
        padding: 10px 14px;
      }
    }
  </style>
</head>
<body>
  <div class="page">
    <header class="header">
      <div class="site-id">
        <div class="site-logo" aria-hidden="true">N</div>
        <div>
          <h1>docs.northstar.dev</h1>
          <div class="live-pill"><span class="live-dot"></span>42 current visitors</div>
        </div>
      </div>
      <div class="header-right">
        <span class="period-badge">May 1 – May 14 · Cross-Filter Ready</span>
      </div>
    </header>

    <section id="filterBar" class="filter-bar" aria-label="Active filters"></section>

    <main class="bento">
      <!-- 4 KPI Cards -->
      <div class="card span-3">
        <div class="kpi-label">Unique Visitors</div>
        <div id="kpiVisitors" class="kpi-value">0</div>
        <div id="kpiVisitorsSub" class="kpi-sub">100% of total traffic</div>
      </div>
      <div class="card span-3">
        <div class="kpi-label">Total Pageviews</div>
        <div id="kpiViews" class="kpi-value">0</div>
        <div id="kpiViewsSub" class="kpi-sub muted">0.0 views / visit</div>
      </div>
      <div class="card span-3">
        <div class="kpi-label">Bounce Rate</div>
        <div id="kpiBounce" class="kpi-value">0%</div>
        <div id="kpiBounceSub" class="kpi-sub muted">Target &lt; 42%</div>
      </div>
      <div class="card span-3">
        <div class="kpi-label">Avg Visit Duration</div>
        <div id="kpiDuration" class="kpi-value">0m 00s</div>
        <div id="kpiDurationSub" class="kpi-sub">Engaged docs readers</div>
      </div>

      <!-- Daily Chart -->
      <section class="card span-8" aria-label="Daily visitors chart">
        <div class="card-head">
          <h2 class="card-title">Daily Visitors</h2>
          <span class="card-meta">Click any bar to filter by day</span>
        </div>
        <div id="dailyChart" class="chart-area"></div>
      </section>

      <!-- Devices -->
      <section class="card span-4" aria-label="Device breakdown">
        <div class="card-head">
          <h2 class="card-title">Devices</h2>
          <span class="card-meta">Click to slice</span>
        </div>
        <div id="deviceGrid" class="device-grid"></div>
        <div style="margin-top:auto;padding-top:16px;font-size:12.5px;color:var(--ink-muted);line-height:1.5;">
          Filters combine across every card. Click an active item again or remove its chip above to reset.
        </div>
      </section>

      <!-- Top Sources -->
      <section class="card span-4" aria-label="Top referral sources">
        <div class="card-head">
          <h2 class="card-title">Top Sources</h2>
          <span class="card-meta">Visitors</span>
        </div>
        <div id="sourceList" class="list-table"></div>
      </section>

      <!-- Countries -->
      <section class="card span-4" aria-label="Top countries">
        <div class="card-head">
          <h2 class="card-title">Countries</h2>
          <span class="card-meta">Visitors</span>
        </div>
        <div id="countryList" class="list-table"></div>
      </section>

      <!-- Top Pages -->
      <section class="card span-4" aria-label="Top pages">
        <div class="card-head">
          <h2 class="card-title">Top Pages</h2>
          <span class="card-meta">Visitors</span>
        </div>
        <div id="pageList" class="list-table"></div>
      </section>
    </main>
  </div>

  <script>
    // Deterministic seeded PRNG for realistic multi-dimensional traffic dataset
    function mulberry32(seed) {
      return function() {
        let t = seed += 0x6D2B79F5;
        t = Math.imul(t ^ (t >>> 15), t | 1);
        t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
      };
    }

    const rand = mulberry32(20260514);
    const DAYS = Array.from({ length: 14 }, (_, i) => `May ${i + 1}`);
    const SOURCES = [
      { name: 'GitHub', w: 0.31 },
      { name: 'Google', w: 0.27 },
      { name: 'Hacker News', w: 0.18 },
      { name: 'Direct', w: 0.15 },
      { name: 'Bluesky', w: 0.09 }
    ];
    const COUNTRIES = [
      { name: 'United States', code: 'US', w: 0.39 },
      { name: 'Germany', code: 'DE', w: 0.19 },
      { name: 'United Kingdom', code: 'GB', w: 0.16 },
      { name: 'Japan', code: 'JP', w: 0.14 },
      { name: 'Canada', code: 'CA', w: 0.12 }
    ];
    const DEVICES = [
      { name: 'Desktop', w: 0.67 },
      { name: 'Mobile', w: 0.26 },
      { name: 'Tablet', w: 0.07 }
    ];
    const PAGES = [
      { name: '/docs/quickstart', w: 0.32 },
      { name: '/api/webhooks', w: 0.24 },
      { name: '/changelog', w: 0.18 },
      { name: '/blog/edge-cache', w: 0.15 },
      { name: '/pricing', w: 0.11 }
    ];

    function pickWeighted(items) {
      let r = rand();
      for (const item of items) {
        r -= item.w;
        if (r <= 0) return item.name;
      }
      return items[items.length - 1].name;
    }

    // Generate 1,420 visit sessions with realistic weekday peaks + HN spike on May 9
    const SESSIONS = [];
    DAYS.forEach((day, idx) => {
      const base = idx === 8 ? 175 : (idx % 7 === 2 || idx % 7 === 3 ? 72 : 102);
      const count = base + Math.round(rand() * 24);
      for (let i = 0; i < count; i++) {
        const source = idx === 8 && rand() < 0.42 ? 'Hacker News' : pickWeighted(SOURCES);
        const country = pickWeighted(COUNTRIES);
        const device = source === 'Bluesky' && rand() < 0.5 ? 'Mobile' : pickWeighted(DEVICES);
        const page = source === 'Hacker News' && rand() < 0.45 ? '/blog/edge-cache' : pickWeighted(PAGES);
        const bounceProb = device === 'Mobile' ? 0.46 : (source === 'GitHub' ? 0.26 : 0.35);
        const bounced = rand() < bounceProb;
        const pageviews = bounced ? 1 : 2 + Math.floor(rand() * 5);
        const durationSec = bounced ? Math.round(12 + rand() * 35) : Math.round(85 + rand() * 310);
        SESSIONS.push({ day, source, country, device, page, bounced, pageviews, durationSec });
      }
    });

    const filters = {
      day: null,
      source: null,
      country: null,
      device: null,
      page: null
    };

    function getFiltered(omitKey = null) {
      return SESSIONS.filter(s => {
        for (const [k, v] of Object.entries(filters)) {
          if (k === omitKey || !v) continue;
          if (s[k] !== v) return false;
        }
        return true;
      });
    }

    function toggleFilter(key, val) {
      filters[key] = filters[key] === val ? null : val;
      render();
    }

    function countBy(rows, key, orderedKeys) {
      const map = new Map();
      if (orderedKeys) orderedKeys.forEach(k => map.set(k, 0));
      rows.forEach(r => map.set(r[key], (map.get(r[key]) || 0) + 1));
      const arr = Array.from(map.entries()).map(([name, count]) => ({ name, count }));
      if (!orderedKeys) arr.sort((a, b) => b.count - a.count);
      return arr;
    }

    function formatDuration(sec) {
      const m = Math.floor(sec / 60);
      const s = Math.round(sec % 60);
      return `${m}m ${String(s).padStart(2, '0')}s`;
    }

    function renderFilterBar() {
      const bar = document.getElementById('filterBar');
      const active = Object.entries(filters).filter(([, v]) => v);
      if (!active.length) {
        bar.innerHTML = `<span class="filter-hint">Showing all <strong>${SESSIONS.length.toLocaleString()}</strong> visits · Click any bar, source, country, device, or page to cross-filter.</span>`;
        return;
      }
      const labels = { day: 'Day', source: 'Source', country: 'Country', device: 'Device', page: 'Page' };
      bar.innerHTML = active
        .map(([k, v]) => `<button class="chip" type="button" data-clear-key="${k}"><span>${labels[k]}: ${v}</span><span class="chip-x">×</span></button>`)
        .join('') + `<button class="clear-btn" type="button" id="clearAllBtn">Clear all</button>`;
    }

    function renderBreakdown(containerId, key, rows, variant = '') {
      const el = document.getElementById(containerId);
      const items = countBy(rows, key);
      const max = Math.max(1, ...items.map(i => i.count));
      el.innerHTML = items.map(item => {
        const pct = Math.round((item.count / max) * 100);
        const sel = filters[key] === item.name;
        return `<button class="row-btn ${variant} ${sel ? 'selected' : ''}" type="button" data-key="${key}" data-val="${item.name}">
          <span class="row-bg" style="width:${pct}%"></span>
          <span class="row-label">${item.name}</span>
          <span class="row-count">${item.count.toLocaleString()}</span>
        </button>`;
      }).join('');
    }

    function render() {
      renderFilterBar();
      const filtered = getFiltered();
      const total = filtered.length;
      const views = filtered.reduce((acc, s) => acc + s.pageviews, 0);
      const bounces = filtered.filter(s => s.bounced).length;
      const avgDur = total ? filtered.reduce((acc, s) => acc + s.durationSec, 0) / total : 0;
      const bouncePct = total ? Math.round((bounces / total) * 100) : 0;
      const sharePct = Math.round((total / SESSIONS.length) * 100);

      document.getElementById('kpiVisitors').textContent = total.toLocaleString();
      document.getElementById('kpiVisitorsSub').textContent = `${sharePct}% of ${SESSIONS.length.toLocaleString()} total`;
      document.getElementById('kpiViews').textContent = views.toLocaleString();
      document.getElementById('kpiViewsSub').textContent = `${total ? (views / total).toFixed(1) : '0.0'} views / visit`;
      document.getElementById('kpiBounce').textContent = `${bouncePct}%`;
      document.getElementById('kpiDuration').textContent = formatDuration(avgDur);

      // Daily chart (omit day filter so user can switch days easily)
      const dayRows = getFiltered('day');
      const dayCounts = countBy(dayRows, 'day', DAYS);
      const maxDay = Math.max(1, ...dayCounts.map(d => d.count));
      const chartEl = document.getElementById('dailyChart');
      chartEl.innerHTML = dayCounts.map(d => {
        const hPct = Math.max(4, Math.round((d.count / maxDay) * 100));
        const sel = filters.day === d.name;
        const shortDay = d.name.replace('May ', '');
        return `<button class="bar-col ${sel ? 'selected' : ''}" type="button" data-key="day" data-val="${d.name}" title="${d.name}: ${d.count} visitors">
          <span class="bar-val">${d.count}</span>
          <div class="bar-track"><div class="bar-fill" style="height:${hPct}%"></div></div>
          <span class="bar-day">${shortDay}</span>
        </button>`;
      }).join('');

      // Devices
      const devRows = getFiltered('device');
      const devTotal = Math.max(1, devRows.length);
      const devCounts = countBy(devRows, 'device', DEVICES.map(d => d.name));
      document.getElementById('deviceGrid').innerHTML = devCounts.map(d => {
        const pct = Math.round((d.count / devTotal) * 100);
        const sel = filters.device === d.name;
        return `<button class="device-card ${sel ? 'selected' : ''}" type="button" data-key="device" data-val="${d.name}">
          <span class="device-name">${d.name}</span>
          <span class="device-pct">${pct}%</span>
          <span class="device-n">${d.count.toLocaleString()} visits</span>
        </button>`;
      }).join('');

      renderBreakdown('sourceList', 'source', getFiltered('source'));
      renderBreakdown('countryList', 'country', getFiltered('country'), 'emerald');
      renderBreakdown('pageList', 'page', getFiltered('page'));
    }

    document.addEventListener('click', (e) => {
      const target = e.target.closest('[data-key][data-val]');
      if (target) {
        toggleFilter(target.dataset.key, target.dataset.val);
        return;
      }
      const chip = e.target.closest('[data-clear-key]');
      if (chip) {
        filters[chip.dataset.clearKey] = null;
        render();
        return;
      }
      if (e.target.closest('#clearAllBtn')) {
        Object.keys(filters).forEach(k => filters[k] = null);
        render();
      }
    });

    render();
  </script>
</body>
</html>
```
