// analytics.jsx — ScreenAnalytics: shell + tab routing + drawer + tweaks
// ────────────────────────────────────────────────────────────
(function () {
  if (typeof window === 'undefined' || !window.React) return;

  const _S = React.useState, _E = React.useEffect, _M = React.useMemo;

  function ScreenAnalytics({ go, payload }) {
    const E = window.ANALYTICS_ENGINE;
    const C = window.AnalyticsCharts;
    const T = window.AnalyticsTabs;
    const Drawer = window.AnalyticsDrawer;
    const PageHeader = window.PageHeader;

    if (!E || !C || !T) {
      return React.createElement('div', { style: { padding: 40, color: 'var(--ink-3)' } }, 'Analytics engine loading…');
    }
    const Mono = C.Mono;

    // ─── period ──────────────────────────────
    const [period, setPeriod] = _S(payload?.period || '90d');
    const [tab, setTab] = _S(payload?.tab || 'market');
    const [drawer, setDrawer] = _S(null);
    const [, force] = _S(0);

    // subscribe to cross-filter changes
    _E(() => E.subscribeXFilter(() => force(x => x + 1)), []);

    // tweaks
    const [tweaks, setTweaks] = _S({ density: 'regular', palette: 'mono', chartStyle: 'clean' });

    const ctx = _M(() => ({
      days: E.periodToDays(period),
      period,
      periodLabel: ({ '30d': 'Last 30 days', '90d': 'Last 90 days', ytd: 'Year to date', ttm: 'Trailing 12 mo' })[period] || period,
      go,
    }), [period, go]);

    const onDrill = (dim, entity) => setDrawer({ dim, entity });

    const TABS = [
      { k: 'market',    l: 'Market',    Comp: T.MarketTab },
      { k: 'artist',    l: 'Artist',    Comp: T.ArtistTab },
      { k: 'work',      l: 'Work',      Comp: T.WorkTab },
      { k: 'recording', l: 'Recording', Comp: T.RecordingTab },
      { k: 'release',   l: 'Release',   Comp: T.ReleaseTab },
      { k: 'video',     l: 'Video',     Comp: T.VideoTab },
      { k: 'platform',  l: 'Platform',  Comp: T.PlatformTab },
      { k: 'royalties', l: 'Royalties',  Comp: RoyaltiesAnalyticsTab },
    ];
    const ActiveTab = TABS.find(t => t.k === tab)?.Comp || T.MarketTab;

    return React.createElement('div', null,
      PageHeader && React.createElement(PageHeader, {
        eyebrow: ['ANALYTICS', '7 DIMENSIONS', ctx.periodLabel.toUpperCase()],
        title: 'analytics.',
        highlight: 'analytics.',
        sub: 'Cross-dimensional view of catalog performance. Earnings + streams across markets, artists, works, recordings, releases, videos and platforms — with cross-filtering, anomaly overlays, and drill-through detail.',
      }),

      // period selector
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, flexWrap: 'wrap' } },
        React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)' }, 'PERIOD'),
        ['30d', '90d', 'ytd', 'ttm'].map(p => React.createElement('button', {
          key: p, onClick: () => setPeriod(p),
          style: { padding: '5px 11px', fontSize: 11, border: '1px solid ' + (period === p ? 'var(--ink)' : 'var(--rule)'), background: period === p ? 'var(--ink)' : 'transparent', color: period === p ? 'var(--bg)' : 'var(--ink-2)', cursor: 'pointer', fontFamily: 'var(--font-mono, ui-monospace)', letterSpacing: '.06em', textTransform: 'uppercase' }
        }, ({ '30d': 'Last 30d', '90d': 'Last 90d', ytd: 'YTD', ttm: 'TTM' })[p])),
        React.createElement('span', { style: { flex: 1 } }),

        // cross-filter chip
        E.xfilter.dim && React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '4px 10px', background: 'var(--bg-2)', border: '1px solid var(--rule)' } },
          React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)' }, 'FILTER · ' + E.xfilter.dim),
          React.createElement('span', { style: { fontSize: 11, color: 'var(--ink)' } }, E.xfilter.label),
          React.createElement('button', {
            onClick: () => E.setXFilter(null),
            style: { background: 'transparent', border: 0, fontSize: 14, color: 'var(--ink-3)', cursor: 'pointer', lineHeight: 1, padding: 0 }
          }, '×')
        ),

        React.createElement('button', {
          onClick: () => {
            try {
              const rows = E.buildDim(tab, ctx);
              const csv = ['dim,id,label,total,streams,pop'].concat(rows.map(r => `${tab},${r.id},"${(r.label || '').replace(/"/g, '""')}",${r.total.toFixed(2)},${Math.round(r.streams)},${r.pop.toFixed(4)}`)).join('\n');
              const blob = new Blob([csv], { type: 'text/csv' });
              const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `analytics-${tab}-${period}.csv`; a.click();
            } catch (e) { console.warn(e); }
          },
          style: { padding: '5px 11px', fontSize: 11, border: '1px solid var(--rule)', background: 'transparent', cursor: 'pointer' }
        }, 'Export CSV'),

        go && React.createElement('button', {
          onClick: () => go('insights'),
          style: { padding: '5px 11px', fontSize: 11, border: '1px solid var(--rule)', background: 'transparent', cursor: 'pointer' }
        }, 'Insights →')
      ),

      // tab bar
      React.createElement('div', { style: { borderBottom: '1px solid var(--rule)', display: 'flex', gap: 0, marginBottom: 24, flexWrap: 'wrap' } },
        TABS.map(t => React.createElement('button', {
          key: t.k, onClick: () => setTab(t.k),
          style: { padding: '14px 18px', background: 'transparent', border: 0, borderBottom: '2px solid ' + (tab === t.k ? 'var(--ink)' : 'transparent'), cursor: 'pointer', color: tab === t.k ? 'var(--ink)' : 'var(--ink-3)', fontSize: 13, fontWeight: tab === t.k ? 600 : 400 }
        }, t.l))
      ),

      // active tab
      React.createElement(ActiveTab, { ctx, onDrill }),

      // drawer
      Drawer && React.createElement(Drawer, {
        open: !!drawer,
        onClose: () => setDrawer(null),
        dim: drawer?.dim,
        entity: drawer?.entity,
        ctx,
        go,
      })
    );
  }

  // ─── Royalties tab — embeds the Visualizer overview ─────────
  function RoyaltiesAnalyticsTab({ ctx }) {
    const RVE = window.RVE, RVC = window.RVCharts;
    if (!RVE || !RVC) return React.createElement('div', { style: { padding: 40, color: 'var(--ink-3)' } }, 'Royalty viz engine not loaded.');
    const lines = RVE.fetchLines();
    const ts = RVE.timeSeries(lines, { granularity: 'month' });
    const stack = RVE.stackedBar(lines, 'sourceKind', { granularity: 'month' });
    const tree = RVE.treemap(lines, 'work', { limit: 24 });
    const par = RVE.pareto(lines, 'work').rows.slice(0, 24);
    const territories = RVE.choropleth(lines);
    const ds = RVE.dataSource();

    return React.createElement('div', null,
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18, padding: '12px 14px', background: 'var(--bg-2)', border: '1px solid var(--rule)' } },
        React.createElement('span', { className: 'ff-mono upper', style: { fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.08em' } }, 'DATA · ' + ds.toUpperCase()),
        React.createElement('span', { style: { fontSize: 12, color: 'var(--ink-2)' } }, ds === 'real' ? lines.length.toLocaleString() + ' real income lines from your statement inbox.' : 'No statements imported yet — synthetic earnings shown.'),
        React.createElement('span', { style: { flex: 1 } }),
        React.createElement('button', {
          onClick: () => ctx.go && ctx.go('royalty-viz'),
          style: { padding: '6px 12px', border: '1px solid var(--ink)', background: 'var(--ink)', color: 'var(--bg)', fontSize: 11, cursor: 'pointer', textTransform: 'uppercase', letterSpacing: '.06em' }
        }, 'Open full visualizer →')
      ),
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16 } },
        React.createElement(MiniCard, { title: 'EARNINGS · OVER TIME' },
          React.createElement(RVC.TimeSeries, { points: ts, w: 620, h: 220 })
        ),
        React.createElement(MiniCard, { title: 'STACK · BY SOURCE TYPE' },
          React.createElement(RVC.StackedBar, { matrix: stack, w: 460, h: 220 })
        ),
        React.createElement(MiniCard, { title: 'TOP WORKS · TREEMAP', span: 2 },
          React.createElement(RVC.Treemap, { rows: tree, w: 1100, h: 280 })
        ),
        React.createElement(MiniCard, { title: 'PARETO · CONCENTRATION', span: 2 },
          React.createElement(RVC.Pareto, { rows: par, w: 1100, h: 260 })
        ),
        React.createElement(MiniCard, { title: 'GEOGRAPHY · BUBBLE MAP', span: 2 },
          React.createElement(RVC.Choropleth, { rows: territories, w: 1100, h: 380 })
        ),
      )
    );
  }
  function MiniCard({ title, span, children }) {
    return React.createElement('section', { style: { border: '1px solid var(--rule)', background: 'var(--bg)', gridColumn: span ? `span ${span}` : 'auto' } },
      React.createElement('header', { style: { padding: '12px 16px', borderBottom: '1px solid var(--rule-soft)' } },
        React.createElement('span', { className: 'ff-mono upper', style: { fontSize: 9, color: 'var(--ink-3)', letterSpacing: '.08em' } }, title)
      ),
      React.createElement('div', { style: { padding: 14, overflowX: 'auto' } }, children)
    );
  }

  window.ScreenAnalytics = ScreenAnalytics;
})();
