// analytics-drawer.jsx — entity drill-through drawer
// Side panel with mini-charts. "Open full" link routes to the existing detail page.
// ────────────────────────────────────────────────────────────
(function () {
  if (typeof window === 'undefined' || !window.React) return;
  if (window.AnalyticsDrawer) return;

  const E = window.ANALYTICS_ENGINE;
  const C = window.AnalyticsCharts;
  const Mono = C.Mono;

  function AnalyticsDrawer({ open, onClose, dim, entity, ctx, go }) {
    if (!open || !entity) return null;
    const series = entity.series || [];
    const k = E.kpiFromSeries(series);
    const flagged = E.flagSeries(series);
    const anomalies = E.getAnomaliesFor(dim, entity.id);
    const byPlat = E.allocByPlatform(dim + ':' + entity.id, k.total);
    const byMkt = E.allocByMarket(dim + ':' + entity.id, k.total);

    const navTo = () => {
      onClose && onClose();
      if (!go) return;
      if (dim === 'recording') go('recording-detail', { id: entity.id });
      else if (dim === 'work') go('catalog', { focus: entity.id });
      else if (dim === 'release') go('release-detail', { id: entity.id });
      else if (dim === 'artist') go('directory', { focus: entity.id });
      else if (dim === 'video') go('audio-fp', { id: entity.id });
      else if (dim === 'platform') go('integrations', { focus: entity.id });
      else if (dim === 'market') go('audience', { market: entity.id });
    };

    return React.createElement('div', null,
      // backdrop
      React.createElement('div', {
        onClick: onClose,
        style: { position: 'fixed', inset: 0, background: 'rgba(20,18,14,0.32)', zIndex: 99 }
      }),
      // drawer
      React.createElement('div', {
        style: { position: 'fixed', top: 0, right: 0, bottom: 0, width: 580, background: 'var(--bg)', borderLeft: '1px solid var(--rule)', boxShadow: '-12px 0 32px rgba(0,0,0,0.08)', zIndex: 100, overflowY: 'auto' }
      },
        // header
        React.createElement('div', { style: { padding: '20px 24px 14px', borderBottom: '1px solid var(--rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 } },
          React.createElement('div', null,
            React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)', style: { display: 'block', marginBottom: 4 } }, dim.toUpperCase() + ' · DRILL'),
            React.createElement('div', { className: 'ff-display', style: { fontSize: 22, fontWeight: 600, letterSpacing: '-0.015em', lineHeight: 1.15 } }, entity.label || entity.id),
            (entity.iswc || entity.isrc || entity.upc || entity.code) && React.createElement(Mono, { size: 11, color: 'var(--ink-3)', style: { marginTop: 4, display: 'block' } }, entity.iswc || entity.isrc || entity.upc || entity.code)
          ),
          React.createElement('button', { onClick: onClose, style: { background: 'transparent', border: 0, fontSize: 20, color: 'var(--ink-3)', cursor: 'pointer', lineHeight: 1 } }, '×')
        ),

        React.createElement('div', { style: { padding: 24 } },
          // KPI mini-strip
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', marginBottom: 22 } },
            React.createElement(C.KPI, { label: 'EARNINGS', value: C.fmt$(k.total), sub: ctx.periodLabel, pop: k.pop }),
            React.createElement(C.KPI, { label: 'STREAMS', value: C.fmtN(k.totalStreams), sub: 'plays' }),
            React.createElement(C.KPI, { label: 'PoP', value: C.fmtPct(k.pop), tone: k.pop >= 0 ? '#0a8754' : '#a32a18', sub: 'period over period' })
          ),

          // anomaly badge
          anomalies && anomalies.length > 0 && React.createElement('div', { style: { padding: '10px 12px', background: '#fff5ec', border: '1px solid #d4881f', marginBottom: 18 } },
            React.createElement(Mono, { upper: true, size: 9, color: '#d4881f', style: { display: 'block', marginBottom: 4 } }, anomalies.length + ' ANOMALY · LEAKS ENGINE'),
            anomalies.slice(0, 3).map((a, i) => React.createElement('div', { key: i, style: { fontSize: 11, color: 'var(--ink-2)' } }, '· ' + (a.title || a.kind || 'flagged')))
          ),

          // trend
          React.createElement('div', { style: { marginBottom: 22 } },
            React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)', style: { display: 'block', marginBottom: 6 } }, 'TREND · 7-day MA'),
            React.createElement(C.LineChart, { series: E.smooth(series), w: 530, h: 180, anomalies: flagged.map(p => p.anomaly) })
          ),

          // platform mix mini-bars
          React.createElement('div', { style: { marginBottom: 22 } },
            React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)', style: { display: 'block', marginBottom: 6 } }, 'PLATFORM MIX'),
            React.createElement(C.BarsH, { rows: byPlat.map(p => ({ ...p, total: p.value, label: E.pf(p.platform).l, color: E.pf(p.platform).c, id: p.platform })).sort((a, b) => b.total - a.total).slice(0, 8), w: 530, h: 200 })
          ),

          // market mix mini-bars
          React.createElement('div', { style: { marginBottom: 22 } },
            React.createElement(Mono, { upper: true, size: 9, color: 'var(--ink-3)', style: { display: 'block', marginBottom: 6 } }, 'MARKET MIX'),
            React.createElement(C.BarsH, { rows: byMkt.map(m => ({ ...m, total: m.value, label: E.mk(m.market).l, id: m.market })).sort((a, b) => b.total - a.total).slice(0, 8), w: 530, h: 200 })
          ),

          // actions
          React.createElement('div', { style: { display: 'flex', gap: 10, paddingTop: 18, borderTop: '1px solid var(--rule)' } },
            React.createElement('button', {
              onClick: navTo,
              style: { padding: '8px 14px', border: '1px solid var(--ink)', background: 'var(--ink)', color: 'var(--bg)', fontSize: 12, cursor: 'pointer' }
            }, 'Open full ' + dim + ' page →'),
            React.createElement('button', {
              onClick: () => { E.setXFilter({ dim, id: entity.id, label: entity.label }); onClose && onClose(); },
              style: { padding: '8px 14px', border: '1px solid var(--rule)', fontSize: 12, cursor: 'pointer' }
            }, 'Cross-filter all tabs by this'),
            React.createElement('button', {
              onClick: () => { try { const blob = new Blob([JSON.stringify({ dim, entity, kpi: k, byPlat, byMkt }, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `analytics-${dim}-${entity.id}.json`; a.click(); URL.revokeObjectURL(url); } catch (e) {} },
              style: { padding: '8px 14px', border: '1px solid var(--rule)', fontSize: 12, cursor: 'pointer' }
            }, 'Export JSON')
          )
        )
      )
    );
  }

  window.AnalyticsDrawer = AnalyticsDrawer;
})();
