{
  "id": 136,
  "slug": "bento-crossfilter-analytics",
  "name": "Cross-Filtering Bento Analytics",
  "kind": "ui",
  "family": "Analytics & Data",
  "sourceSite": {
    "name": "Plausible Analytics",
    "url": "https://plausible.io/",
    "verifiedStatus": 200
  },
  "tagline": "Daylight bento analytics dashboard where clicking any chart bar, referrer, country, or device cross-filters every card live.",
  "whyUnique": "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.",
  "theme": "light",
  "mobileStrength": "high",
  "tags": [
    "analytics",
    "cross-filtering",
    "bento-grid",
    "dashboard",
    "data-viz",
    "interactive-charts"
  ],
  "bestFor": [
    "Web and product telemetry dashboards",
    "E-commerce conversion and funnel analytics",
    "Marketing attribution and campaign explorers",
    "SaaS usage and cohort reporting"
  ],
  "palette": [
    {
      "role": "canvas",
      "hex": "#F5F7FB",
      "name": "Cloud Canvas"
    },
    {
      "role": "surface",
      "hex": "#FFFFFF",
      "name": "Bento White"
    },
    {
      "role": "ink",
      "hex": "#111827",
      "name": "Graphite Ink"
    },
    {
      "role": "accent",
      "hex": "#4F46E5",
      "name": "Plausible Indigo"
    },
    {
      "role": "muted",
      "hex": "#6B7280",
      "name": "Metric Gray"
    }
  ],
  "typography": {
    "display": "Inter",
    "body": "Inter",
    "mono": "JetBrains Mono",
    "googleFontsUrl": "https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&family=JetBrains+Mono:wght@500;600&display=swap",
    "scaleNotes": "26px tabular-nums KPI figures, 13px breakdown row labels, 11px uppercase card headers."
  },
  "layoutNotes": "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.",
  "interactionNotes": "Clicking any Source, Country, Device, or Day bar toggles a live cross-filter that recalculates all KPIs, bars, and proportional background meters instantaneously.",
  "mobileNotes": "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.",
  "agentGuardrails": {
    "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."
    ],
    "dont": [
      "Never cross-filter silently without showing which filters are currently applied.",
      "Avoid tiny un-tappable SVG slices or bars on 390px mobile viewports."
    ]
  },
  "demoFile": "demos/bento-crossfilter-analytics.html",
  "thumbDesktop": "thumbs/bento-crossfilter-analytics-desktop.webp",
  "thumbMobile": "thumbs/bento-crossfilter-analytics-mobile.webp",
  "urls": {
    "page": "https://templates.michaelpitts.net/t/bento-crossfilter-analytics",
    "markdown": "https://templates.michaelpitts.net/t/bento-crossfilter-analytics.md",
    "api": "https://templates.michaelpitts.net/api/templates/bento-crossfilter-analytics",
    "demo": "https://templates.michaelpitts.net/demos/bento-crossfilter-analytics.html",
    "thumbDesktop": "https://templates.michaelpitts.net/thumbs/bento-crossfilter-analytics-desktop.webp",
    "thumbMobile": "https://templates.michaelpitts.net/thumbs/bento-crossfilter-analytics-mobile.webp"
  },
  "agentPrompt": "Design & build using template #136 \"Cross-Filtering Bento Analytics\" (ui / Analytics & Data, light theme).\nFull AI blueprint & standalone starter code: https://templates.michaelpitts.net/t/bento-crossfilter-analytics.md\nLive demo: https://templates.michaelpitts.net/demos/bento-crossfilter-analytics.html\nReal-world inspiration: Plausible Analytics (https://plausible.io/)\n\nCore aesthetic: 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.\nPalette: canvas: #F5F7FB (Cloud Canvas), surface: #FFFFFF (Bento White), ink: #111827 (Graphite Ink), accent: #4F46E5 (Plausible Indigo), muted: #6B7280 (Metric Gray)\nTypography: Display=\"Inter\", Body=\"Inter\", Mono=\"JetBrains Mono\"\nLayout: 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.\nInteractions: Clicking any Source, Country, Device, or Day bar toggles a live cross-filter that recalculates all KPIs, bars, and proportional background meters instantaneously.\nMobile: 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.\n\nGuardrails:\n- DO: Use font-variant-numeric: tabular-nums on all KPI metrics and table percentages so numbers never jitter.\n- DO: Surface active cross-filters as removable chips with a one-click Reset button.\n- DO: Make the interactive affordance obvious with hover/active states on clickable bars and rows.\n- DON'T: Never cross-filter silently without showing which filters are currently applied.\n- DON'T: Avoid tiny un-tappable SVG slices or bars on 390px mobile viewports.",
  "sourceCode": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <title>PulseMetrics — Cross-Filtering Bento Analytics</title>\n  <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n  <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n  <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;600&display=swap\" rel=\"stylesheet\">\n  <style>\n    :root {\n      --bg: #f6f8fc;\n      --card: #ffffff;\n      --card-subtle: #f8fafc;\n      --border: #e2e8f0;\n      --border-strong: #cbd5e1;\n      --ink: #0f172a;\n      --ink-muted: #64748b;\n      --indigo: #4f46e5;\n      --indigo-soft: #eef2ff;\n      --indigo-bar: rgba(79, 70, 229, 0.16);\n      --emerald: #059669;\n      --emerald-soft: #ecfdf5;\n      --rose: #e11d48;\n      --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;\n      --font-mono: 'JetBrains Mono', ui-monospace, monospace;\n    }\n\n    * { box-sizing: border-box; margin: 0; padding: 0; }\n\n    html, body {\n      min-height: 100%;\n      background: var(--bg);\n      color: var(--ink);\n      font-family: var(--font-sans);\n      -webkit-font-smoothing: antialiased;\n      overflow-x: hidden;\n    }\n\n    .page {\n      max-width: 1240px;\n      margin: 0 auto;\n      padding: 22px 20px 44px;\n      display: flex;\n      flex-direction: column;\n      gap: 16px;\n    }\n\n    /* Header */\n    .header {\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n      gap: 12px;\n      flex-wrap: wrap;\n    }\n\n    .site-id {\n      display: flex;\n      align-items: center;\n      gap: 11px;\n    }\n\n    .site-logo {\n      width: 36px;\n      height: 36px;\n      border-radius: 10px;\n      background: var(--indigo);\n      color: #fff;\n      display: grid;\n      place-items: center;\n      font-weight: 700;\n      font-size: 16px;\n      box-shadow: 0 4px 12px rgba(79, 70, 229, 0.28);\n    }\n\n    .site-id h1 {\n      font-size: 18px;\n      font-weight: 700;\n      letter-spacing: -0.02em;\n    }\n\n    .live-pill {\n      display: inline-flex;\n      align-items: center;\n      gap: 6px;\n      font-size: 12px;\n      font-weight: 500;\n      color: var(--emerald);\n      background: var(--emerald-soft);\n      padding: 4px 10px;\n      border-radius: 99px;\n      margin-top: 2px;\n    }\n\n    .live-dot {\n      width: 7px;\n      height: 7px;\n      border-radius: 50%;\n      background: var(--emerald);\n    }\n\n    .header-right {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n    }\n\n    .period-badge {\n      background: var(--card);\n      border: 1px solid var(--border);\n      padding: 8px 13px;\n      border-radius: 9px;\n      font-size: 13px;\n      font-weight: 500;\n      color: var(--ink-muted);\n    }\n\n    /* Active Filter Chips Bar */\n    .filter-bar {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      flex-wrap: wrap;\n      min-height: 36px;\n    }\n\n    .filter-hint {\n      font-size: 13px;\n      color: var(--ink-muted);\n    }\n\n    .chip {\n      appearance: none;\n      border: 1px solid #c7d2fe;\n      background: var(--indigo-soft);\n      color: #3730a3;\n      font-family: var(--font-sans);\n      font-size: 12.5px;\n      font-weight: 600;\n      padding: 0 12px;\n      min-height: 36px;\n      border-radius: 99px;\n      cursor: pointer;\n      display: inline-flex;\n      align-items: center;\n      gap: 7px;\n      transition: background 0.15s;\n    }\n    .chip:hover { background: #e0e7ff; }\n    .chip-x { font-size: 14px; opacity: 0.75; }\n\n    .clear-btn {\n      appearance: none;\n      border: 1px solid var(--border-strong);\n      background: var(--card);\n      color: var(--ink-muted);\n      font-size: 12.5px;\n      font-weight: 500;\n      padding: 0 12px;\n      min-height: 36px;\n      border-radius: 99px;\n      cursor: pointer;\n    }\n    .clear-btn:hover { color: var(--ink); background: var(--card-subtle); }\n\n    /* Bento Grid */\n    .bento {\n      display: grid;\n      grid-template-columns: repeat(12, minmax(0, 1fr));\n      gap: 16px;\n    }\n\n    .card {\n      background: var(--card);\n      border: 1px solid var(--border);\n      border-radius: 14px;\n      padding: 18px 20px;\n      box-shadow: 0 1px 3px rgba(15, 23, 42, 0.03);\n      display: flex;\n      flex-direction: column;\n      min-width: 0;\n    }\n\n    .span-12 { grid-column: span 12; }\n    .span-8 { grid-column: span 8; }\n    .span-6 { grid-column: span 6; }\n    .span-4 { grid-column: span 4; }\n    .span-3 { grid-column: span 3; }\n\n    /* KPI Strip */\n    .kpi-label {\n      font-size: 12px;\n      font-weight: 600;\n      text-transform: uppercase;\n      letter-spacing: 0.04em;\n      color: var(--ink-muted);\n      margin-bottom: 8px;\n    }\n\n    .kpi-value {\n      font-size: 28px;\n      font-weight: 700;\n      letter-spacing: -0.03em;\n      line-height: 1.1;\n      font-variant-numeric: tabular-nums;\n    }\n\n    .kpi-sub {\n      margin-top: 8px;\n      font-size: 12.5px;\n      font-weight: 500;\n      color: var(--emerald);\n      display: flex;\n      align-items: center;\n      gap: 5px;\n    }\n\n    .kpi-sub.muted { color: var(--ink-muted); }\n\n    /* Card Header */\n    .card-head {\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n      gap: 8px;\n      margin-bottom: 14px;\n    }\n\n    .card-title {\n      font-size: 14.5px;\n      font-weight: 600;\n      color: var(--ink);\n    }\n\n    .card-meta {\n      font-size: 12px;\n      color: var(--ink-muted);\n    }\n\n    /* Daily Bar Chart */\n    .chart-area {\n      display: grid;\n      grid-template-columns: repeat(14, minmax(0, 1fr));\n      align-items: end;\n      gap: 8px;\n      height: 196px;\n      padding-top: 24px;\n      border-bottom: 1px solid var(--border);\n    }\n\n    .bar-col {\n      appearance: none;\n      border: none;\n      background: transparent;\n      height: 100%;\n      display: flex;\n      flex-direction: column;\n      justify-content: flex-end;\n      align-items: center;\n      gap: 6px;\n      cursor: pointer;\n      padding: 0;\n      position: relative;\n    }\n\n    .bar-track {\n      width: 100%;\n      flex: 1;\n      display: flex;\n      align-items: flex-end;\n      justify-content: center;\n    }\n\n    .bar-fill {\n      width: 100%;\n      max-width: 34px;\n      min-height: 6px;\n      border-radius: 6px 6px 2px 2px;\n      background: #c7d2fe;\n      transition: height 0.25s ease, background 0.15s ease, transform 0.15s ease;\n    }\n\n    .bar-col:hover .bar-fill {\n      background: #818cf8;\n    }\n\n    .bar-col.selected .bar-fill {\n      background: var(--indigo);\n      box-shadow: 0 4px 12px rgba(79, 70, 229, 0.35);\n    }\n\n    .bar-val {\n      font-family: var(--font-mono);\n      font-size: 10.5px;\n      color: var(--ink-muted);\n      opacity: 0;\n      transition: opacity 0.15s;\n    }\n\n    .bar-col:hover .bar-val,\n    .bar-col.selected .bar-val {\n      opacity: 1;\n      color: var(--indigo);\n      font-weight: 600;\n    }\n\n    .bar-day {\n      font-size: 11px;\n      color: var(--ink-muted);\n      padding-bottom: 8px;\n      white-space: nowrap;\n    }\n\n    .bar-col.selected .bar-day {\n      color: var(--indigo);\n      font-weight: 700;\n    }\n\n    /* Breakdown Rows */\n    .list-table {\n      display: flex;\n      flex-direction: column;\n      gap: 7px;\n    }\n\n    .row-btn {\n      appearance: none;\n      border: 1px solid transparent;\n      background: transparent;\n      width: 100%;\n      min-height: 38px;\n      border-radius: 8px;\n      cursor: pointer;\n      position: relative;\n      overflow: hidden;\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n      padding: 0 11px;\n      text-align: left;\n      transition: border-color 0.15s, background 0.15s;\n    }\n\n    .row-btn:hover {\n      border-color: var(--border-strong);\n    }\n\n    .row-btn.selected {\n      border-color: var(--indigo);\n      background: rgba(79, 70, 229, 0.05);\n    }\n\n    .row-bg {\n      position: absolute;\n      left: 0;\n      top: 0;\n      bottom: 0;\n      background: var(--indigo-bar);\n      border-radius: 7px;\n      transition: width 0.28s ease;\n      pointer-events: none;\n    }\n\n    .row-btn.emerald .row-bg {\n      background: rgba(5, 150, 105, 0.15);\n    }\n\n    .row-label {\n      position: relative;\n      z-index: 1;\n      font-size: 13.5px;\n      font-weight: 500;\n      color: var(--ink);\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      min-width: 0;\n      overflow: hidden;\n      text-overflow: ellipsis;\n      white-space: nowrap;\n    }\n\n    .row-count {\n      position: relative;\n      z-index: 1;\n      font-family: var(--font-mono);\n      font-size: 12.5px;\n      font-weight: 600;\n      color: var(--ink);\n      margin-left: 10px;\n      flex-shrink: 0;\n    }\n\n    /* Device Segmented Cards */\n    .device-grid {\n      display: grid;\n      grid-template-columns: repeat(3, minmax(0, 1fr));\n      gap: 10px;\n      margin-top: 4px;\n    }\n\n    .device-card {\n      appearance: none;\n      border: 1px solid var(--border);\n      background: var(--card-subtle);\n      border-radius: 10px;\n      padding: 12px 10px;\n      cursor: pointer;\n      text-align: left;\n      min-height: 78px;\n      display: flex;\n      flex-direction: column;\n      justify-content: space-between;\n      transition: border-color 0.15s, background 0.15s, transform 0.1s;\n    }\n\n    .device-card:hover { border-color: var(--border-strong); }\n    .device-card.selected {\n      border-color: var(--indigo);\n      background: var(--indigo-soft);\n    }\n\n    .device-name {\n      font-size: 12.5px;\n      font-weight: 600;\n      color: var(--ink-muted);\n    }\n    .device-card.selected .device-name { color: var(--indigo); }\n\n    .device-pct {\n      font-family: var(--font-mono);\n      font-size: 18px;\n      font-weight: 700;\n      color: var(--ink);\n    }\n\n    .device-n {\n      font-size: 11.5px;\n      color: var(--ink-muted);\n    }\n\n    /* Responsive Mobile (390px) */\n    @media (max-width: 900px) {\n      .span-3 { grid-column: span 6; }\n      .span-4, .span-6, .span-8 { grid-column: span 12; }\n    }\n\n    @media (max-width: 560px) {\n      .page {\n        padding: 14px 12px 32px;\n        gap: 12px;\n      }\n\n      .bento { gap: 12px; }\n\n      .card { padding: 14px; }\n\n      .kpi-value { font-size: 22px; }\n\n      .chart-area {\n        gap: 4px;\n        height: 164px;\n      }\n\n      .bar-day {\n        font-size: 9.5px;\n      }\n\n      .row-btn {\n        min-height: 44px;\n      }\n\n      .chip, .clear-btn {\n        min-height: 44px;\n      }\n\n      .device-grid {\n        grid-template-columns: 1fr;\n      }\n\n      .device-card {\n        flex-direction: row;\n        align-items: center;\n        min-height: 52px;\n        padding: 10px 14px;\n      }\n    }\n  </style>\n</head>\n<body>\n  <div class=\"page\">\n    <header class=\"header\">\n      <div class=\"site-id\">\n        <div class=\"site-logo\" aria-hidden=\"true\">N</div>\n        <div>\n          <h1>docs.northstar.dev</h1>\n          <div class=\"live-pill\"><span class=\"live-dot\"></span>42 current visitors</div>\n        </div>\n      </div>\n      <div class=\"header-right\">\n        <span class=\"period-badge\">May 1 – May 14 · Cross-Filter Ready</span>\n      </div>\n    </header>\n\n    <section id=\"filterBar\" class=\"filter-bar\" aria-label=\"Active filters\"></section>\n\n    <main class=\"bento\">\n      <!-- 4 KPI Cards -->\n      <div class=\"card span-3\">\n        <div class=\"kpi-label\">Unique Visitors</div>\n        <div id=\"kpiVisitors\" class=\"kpi-value\">0</div>\n        <div id=\"kpiVisitorsSub\" class=\"kpi-sub\">100% of total traffic</div>\n      </div>\n      <div class=\"card span-3\">\n        <div class=\"kpi-label\">Total Pageviews</div>\n        <div id=\"kpiViews\" class=\"kpi-value\">0</div>\n        <div id=\"kpiViewsSub\" class=\"kpi-sub muted\">0.0 views / visit</div>\n      </div>\n      <div class=\"card span-3\">\n        <div class=\"kpi-label\">Bounce Rate</div>\n        <div id=\"kpiBounce\" class=\"kpi-value\">0%</div>\n        <div id=\"kpiBounceSub\" class=\"kpi-sub muted\">Target &lt; 42%</div>\n      </div>\n      <div class=\"card span-3\">\n        <div class=\"kpi-label\">Avg Visit Duration</div>\n        <div id=\"kpiDuration\" class=\"kpi-value\">0m 00s</div>\n        <div id=\"kpiDurationSub\" class=\"kpi-sub\">Engaged docs readers</div>\n      </div>\n\n      <!-- Daily Chart -->\n      <section class=\"card span-8\" aria-label=\"Daily visitors chart\">\n        <div class=\"card-head\">\n          <h2 class=\"card-title\">Daily Visitors</h2>\n          <span class=\"card-meta\">Click any bar to filter by day</span>\n        </div>\n        <div id=\"dailyChart\" class=\"chart-area\"></div>\n      </section>\n\n      <!-- Devices -->\n      <section class=\"card span-4\" aria-label=\"Device breakdown\">\n        <div class=\"card-head\">\n          <h2 class=\"card-title\">Devices</h2>\n          <span class=\"card-meta\">Click to slice</span>\n        </div>\n        <div id=\"deviceGrid\" class=\"device-grid\"></div>\n        <div style=\"margin-top:auto;padding-top:16px;font-size:12.5px;color:var(--ink-muted);line-height:1.5;\">\n          Filters combine across every card. Click an active item again or remove its chip above to reset.\n        </div>\n      </section>\n\n      <!-- Top Sources -->\n      <section class=\"card span-4\" aria-label=\"Top referral sources\">\n        <div class=\"card-head\">\n          <h2 class=\"card-title\">Top Sources</h2>\n          <span class=\"card-meta\">Visitors</span>\n        </div>\n        <div id=\"sourceList\" class=\"list-table\"></div>\n      </section>\n\n      <!-- Countries -->\n      <section class=\"card span-4\" aria-label=\"Top countries\">\n        <div class=\"card-head\">\n          <h2 class=\"card-title\">Countries</h2>\n          <span class=\"card-meta\">Visitors</span>\n        </div>\n        <div id=\"countryList\" class=\"list-table\"></div>\n      </section>\n\n      <!-- Top Pages -->\n      <section class=\"card span-4\" aria-label=\"Top pages\">\n        <div class=\"card-head\">\n          <h2 class=\"card-title\">Top Pages</h2>\n          <span class=\"card-meta\">Visitors</span>\n        </div>\n        <div id=\"pageList\" class=\"list-table\"></div>\n      </section>\n    </main>\n  </div>\n\n  <script>\n    // Deterministic seeded PRNG for realistic multi-dimensional traffic dataset\n    function mulberry32(seed) {\n      return function() {\n        let t = seed += 0x6D2B79F5;\n        t = Math.imul(t ^ (t >>> 15), t | 1);\n        t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n      };\n    }\n\n    const rand = mulberry32(20260514);\n    const DAYS = Array.from({ length: 14 }, (_, i) => `May ${i + 1}`);\n    const SOURCES = [\n      { name: 'GitHub', w: 0.31 },\n      { name: 'Google', w: 0.27 },\n      { name: 'Hacker News', w: 0.18 },\n      { name: 'Direct', w: 0.15 },\n      { name: 'Bluesky', w: 0.09 }\n    ];\n    const COUNTRIES = [\n      { name: 'United States', code: 'US', w: 0.39 },\n      { name: 'Germany', code: 'DE', w: 0.19 },\n      { name: 'United Kingdom', code: 'GB', w: 0.16 },\n      { name: 'Japan', code: 'JP', w: 0.14 },\n      { name: 'Canada', code: 'CA', w: 0.12 }\n    ];\n    const DEVICES = [\n      { name: 'Desktop', w: 0.67 },\n      { name: 'Mobile', w: 0.26 },\n      { name: 'Tablet', w: 0.07 }\n    ];\n    const PAGES = [\n      { name: '/docs/quickstart', w: 0.32 },\n      { name: '/api/webhooks', w: 0.24 },\n      { name: '/changelog', w: 0.18 },\n      { name: '/blog/edge-cache', w: 0.15 },\n      { name: '/pricing', w: 0.11 }\n    ];\n\n    function pickWeighted(items) {\n      let r = rand();\n      for (const item of items) {\n        r -= item.w;\n        if (r <= 0) return item.name;\n      }\n      return items[items.length - 1].name;\n    }\n\n    // Generate 1,420 visit sessions with realistic weekday peaks + HN spike on May 9\n    const SESSIONS = [];\n    DAYS.forEach((day, idx) => {\n      const base = idx === 8 ? 175 : (idx % 7 === 2 || idx % 7 === 3 ? 72 : 102);\n      const count = base + Math.round(rand() * 24);\n      for (let i = 0; i < count; i++) {\n        const source = idx === 8 && rand() < 0.42 ? 'Hacker News' : pickWeighted(SOURCES);\n        const country = pickWeighted(COUNTRIES);\n        const device = source === 'Bluesky' && rand() < 0.5 ? 'Mobile' : pickWeighted(DEVICES);\n        const page = source === 'Hacker News' && rand() < 0.45 ? '/blog/edge-cache' : pickWeighted(PAGES);\n        const bounceProb = device === 'Mobile' ? 0.46 : (source === 'GitHub' ? 0.26 : 0.35);\n        const bounced = rand() < bounceProb;\n        const pageviews = bounced ? 1 : 2 + Math.floor(rand() * 5);\n        const durationSec = bounced ? Math.round(12 + rand() * 35) : Math.round(85 + rand() * 310);\n        SESSIONS.push({ day, source, country, device, page, bounced, pageviews, durationSec });\n      }\n    });\n\n    const filters = {\n      day: null,\n      source: null,\n      country: null,\n      device: null,\n      page: null\n    };\n\n    function getFiltered(omitKey = null) {\n      return SESSIONS.filter(s => {\n        for (const [k, v] of Object.entries(filters)) {\n          if (k === omitKey || !v) continue;\n          if (s[k] !== v) return false;\n        }\n        return true;\n      });\n    }\n\n    function toggleFilter(key, val) {\n      filters[key] = filters[key] === val ? null : val;\n      render();\n    }\n\n    function countBy(rows, key, orderedKeys) {\n      const map = new Map();\n      if (orderedKeys) orderedKeys.forEach(k => map.set(k, 0));\n      rows.forEach(r => map.set(r[key], (map.get(r[key]) || 0) + 1));\n      const arr = Array.from(map.entries()).map(([name, count]) => ({ name, count }));\n      if (!orderedKeys) arr.sort((a, b) => b.count - a.count);\n      return arr;\n    }\n\n    function formatDuration(sec) {\n      const m = Math.floor(sec / 60);\n      const s = Math.round(sec % 60);\n      return `${m}m ${String(s).padStart(2, '0')}s`;\n    }\n\n    function renderFilterBar() {\n      const bar = document.getElementById('filterBar');\n      const active = Object.entries(filters).filter(([, v]) => v);\n      if (!active.length) {\n        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>`;\n        return;\n      }\n      const labels = { day: 'Day', source: 'Source', country: 'Country', device: 'Device', page: 'Page' };\n      bar.innerHTML = active\n        .map(([k, v]) => `<button class=\"chip\" type=\"button\" data-clear-key=\"${k}\"><span>${labels[k]}: ${v}</span><span class=\"chip-x\">×</span></button>`)\n        .join('') + `<button class=\"clear-btn\" type=\"button\" id=\"clearAllBtn\">Clear all</button>`;\n    }\n\n    function renderBreakdown(containerId, key, rows, variant = '') {\n      const el = document.getElementById(containerId);\n      const items = countBy(rows, key);\n      const max = Math.max(1, ...items.map(i => i.count));\n      el.innerHTML = items.map(item => {\n        const pct = Math.round((item.count / max) * 100);\n        const sel = filters[key] === item.name;\n        return `<button class=\"row-btn ${variant} ${sel ? 'selected' : ''}\" type=\"button\" data-key=\"${key}\" data-val=\"${item.name}\">\n          <span class=\"row-bg\" style=\"width:${pct}%\"></span>\n          <span class=\"row-label\">${item.name}</span>\n          <span class=\"row-count\">${item.count.toLocaleString()}</span>\n        </button>`;\n      }).join('');\n    }\n\n    function render() {\n      renderFilterBar();\n      const filtered = getFiltered();\n      const total = filtered.length;\n      const views = filtered.reduce((acc, s) => acc + s.pageviews, 0);\n      const bounces = filtered.filter(s => s.bounced).length;\n      const avgDur = total ? filtered.reduce((acc, s) => acc + s.durationSec, 0) / total : 0;\n      const bouncePct = total ? Math.round((bounces / total) * 100) : 0;\n      const sharePct = Math.round((total / SESSIONS.length) * 100);\n\n      document.getElementById('kpiVisitors').textContent = total.toLocaleString();\n      document.getElementById('kpiVisitorsSub').textContent = `${sharePct}% of ${SESSIONS.length.toLocaleString()} total`;\n      document.getElementById('kpiViews').textContent = views.toLocaleString();\n      document.getElementById('kpiViewsSub').textContent = `${total ? (views / total).toFixed(1) : '0.0'} views / visit`;\n      document.getElementById('kpiBounce').textContent = `${bouncePct}%`;\n      document.getElementById('kpiDuration').textContent = formatDuration(avgDur);\n\n      // Daily chart (omit day filter so user can switch days easily)\n      const dayRows = getFiltered('day');\n      const dayCounts = countBy(dayRows, 'day', DAYS);\n      const maxDay = Math.max(1, ...dayCounts.map(d => d.count));\n      const chartEl = document.getElementById('dailyChart');\n      chartEl.innerHTML = dayCounts.map(d => {\n        const hPct = Math.max(4, Math.round((d.count / maxDay) * 100));\n        const sel = filters.day === d.name;\n        const shortDay = d.name.replace('May ', '');\n        return `<button class=\"bar-col ${sel ? 'selected' : ''}\" type=\"button\" data-key=\"day\" data-val=\"${d.name}\" title=\"${d.name}: ${d.count} visitors\">\n          <span class=\"bar-val\">${d.count}</span>\n          <div class=\"bar-track\"><div class=\"bar-fill\" style=\"height:${hPct}%\"></div></div>\n          <span class=\"bar-day\">${shortDay}</span>\n        </button>`;\n      }).join('');\n\n      // Devices\n      const devRows = getFiltered('device');\n      const devTotal = Math.max(1, devRows.length);\n      const devCounts = countBy(devRows, 'device', DEVICES.map(d => d.name));\n      document.getElementById('deviceGrid').innerHTML = devCounts.map(d => {\n        const pct = Math.round((d.count / devTotal) * 100);\n        const sel = filters.device === d.name;\n        return `<button class=\"device-card ${sel ? 'selected' : ''}\" type=\"button\" data-key=\"device\" data-val=\"${d.name}\">\n          <span class=\"device-name\">${d.name}</span>\n          <span class=\"device-pct\">${pct}%</span>\n          <span class=\"device-n\">${d.count.toLocaleString()} visits</span>\n        </button>`;\n      }).join('');\n\n      renderBreakdown('sourceList', 'source', getFiltered('source'));\n      renderBreakdown('countryList', 'country', getFiltered('country'), 'emerald');\n      renderBreakdown('pageList', 'page', getFiltered('page'));\n    }\n\n    document.addEventListener('click', (e) => {\n      const target = e.target.closest('[data-key][data-val]');\n      if (target) {\n        toggleFilter(target.dataset.key, target.dataset.val);\n        return;\n      }\n      const chip = e.target.closest('[data-clear-key]');\n      if (chip) {\n        filters[chip.dataset.clearKey] = null;\n        render();\n        return;\n      }\n      if (e.target.closest('#clearAllBtn')) {\n        Object.keys(filters).forEach(k => filters[k] = null);\n        render();\n      }\n    });\n\n    render();\n  </script>\n</body>\n</html>\n"
}
