/* RC-MX-040 — Action telemetry.
   Lightweight in-browser event bus. Every emitted event carries:
     - featureId  (e.g. "RC-PAGE-012")  → the spec tag
     - action     (e.g. "granularity-change")
     - payload    (arbitrary)
     - ts         (epoch ms)
     - sessionId  (per page load)
   Real deployment swaps the sink for a fetch() to the telemetry endpoint.
   Here we push into window.__rcEvents and notify subscribers so the
   dev-only Events panel can render a live log.

   Usage:
     window.rcTrack('RC-PAGE-012', 'granularity-change', { to: 'week' });
*/

(function () {
  const MAX_EVENTS = 500;
  const sessionId = 'sess_' + Math.random().toString(36).slice(2, 10) + '_' + Date.now().toString(36);
  const events = [];
  const subscribers = new Set();

  function notify() {
    subscribers.forEach(fn => { try { fn(events); } catch (e) {} });
  }

  function track(featureId, action, payload) {
    if (!featureId) { console.warn('rcTrack: featureId required'); return; }
    const evt = {
      featureId,                // @rc:<feature-id>
      action: action || 'unknown',
      payload: payload || null,
      ts: Date.now(),
      sessionId,
    };
    events.push(evt);
    if (events.length > MAX_EVENTS) events.splice(0, events.length - MAX_EVENTS);
    // Also surface in console when a debug flag is on.
    if (window.__rcTelemetryDebug) {
      // Pretty one-liner so it's scannable.
      console.debug(
        `%c@rc:${featureId}%c ${action}`,
        'color:#2563eb;font-weight:600', 'color:inherit',
        payload || ''
      );
    }
    notify();
    return evt;
  }

  function subscribe(fn) {
    subscribers.add(fn);
    fn(events);
    return () => subscribers.delete(fn);
  }

  function clear() { events.length = 0; notify(); }

  window.rcTrack = track;
  window.__rcEvents = events;
  window.__rcTelemetry = { subscribe, clear, sessionId };

  // Common automatic tags — lightweight coverage without touching every handler.
  // Individual components can still emit richer events via rcTrack().
  document.addEventListener('click', (e) => {
    const el = e.target.closest('[data-rc-track]');
    if (!el) return;
    const spec = el.getAttribute('data-rc-track');
    const action = el.getAttribute('data-rc-action') || 'click';
    track(spec, action, {
      label: (el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 60) || undefined,
    });
  }, true);
})();

/* =============================================================
   Dev-only Events Panel — opens via ⌥E or the Tweaks panel.
   Not for production, but essential for verifying coverage during
   spec sign-off.
   ============================================================= */
const TelemetryEventsPanel = ({ open, onClose }) => {
  const [events, setEvents] = React.useState([]);
  const [filter, setFilter] = React.useState('');
  const [debugOn, setDebugOn] = React.useState(!!window.__rcTelemetryDebug);

  React.useEffect(() => {
    if (!open) return;
    return window.__rcTelemetry.subscribe((evts) => {
      // Shallow copy so React reconciles.
      setEvents([...evts]);
    });
  }, [open]);

  if (!open) return null;

  const q = filter.trim().toLowerCase();
  const filtered = q
    ? events.filter(e =>
        e.featureId.toLowerCase().includes(q) ||
        e.action.toLowerCase().includes(q) ||
        JSON.stringify(e.payload || '').toLowerCase().includes(q)
      )
    : events;

  // Count by featureId for the summary row.
  const byFeature = events.reduce((acc, e) => {
    acc[e.featureId] = (acc[e.featureId] || 0) + 1;
    return acc;
  }, {});
  const sortedFeatures = Object.entries(byFeature).sort((a, b) => b[1] - a[1]);

  const panelStyle = {
    position: 'fixed', bottom: 16, right: 16,
    width: 440, maxHeight: '70vh',
    background: 'var(--rc-card)',
    border: '1px solid var(--rc-border)',
    borderRadius: 10,
    boxShadow: '0 10px 32px rgba(15, 23, 42, 0.18)',
    display: 'flex', flexDirection: 'column',
    zIndex: 999,
    fontFamily: 'Inter',
    overflow: 'hidden',
  };

  return (
    <div style={panelStyle}>
      <div style={{
        padding: '10px 12px',
        borderBottom: '1px solid var(--rc-border-soft)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
        background: 'var(--rc-subtle)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            width: 8, height: 8, borderRadius: 4,
            background: '#22c55e',
            boxShadow: '0 0 8px rgba(34, 197, 94, 0.7)',
          }} />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--rc-text)' }}>
              Telemetry events
            </span>
            <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontFamily: 'JetBrains Mono' }}>
              {window.__rcTelemetry.sessionId}
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <button onClick={() => { window.__rcTelemetry.clear(); }} title="Clear"
            style={ghostBtn}>Clear</button>
          <button onClick={onClose} title="Close" style={ghostBtn}>✕</button>
        </div>
      </div>

      {/* Summary chips */}
      <div style={{
        padding: '8px 12px',
        borderBottom: '1px solid var(--rc-border-soft)',
        display: 'flex', flexWrap: 'wrap', gap: 4,
        maxHeight: 80, overflowY: 'auto',
      }}>
        {sortedFeatures.length === 0 ? (
          <span style={{ fontSize: 11, color: 'var(--rc-text-mute)', fontStyle: 'italic' }}>
            No events yet — interact with the report to emit events.
          </span>
        ) : sortedFeatures.map(([id, count]) => (
          <span key={id} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '2px 6px', borderRadius: 10,
            background: 'color-mix(in srgb, var(--rc-chart-1) 8%, transparent)',
            border: '1px solid color-mix(in srgb, var(--rc-chart-1) 25%, transparent)',
            fontSize: 10, fontFamily: 'JetBrains Mono',
            color: 'var(--rc-text)',
          }}>
            {id} <span style={{ color: 'var(--rc-text-mute)' }}>×{count}</span>
          </span>
        ))}
      </div>

      {/* Filter + debug */}
      <div style={{
        padding: '8px 12px',
        borderBottom: '1px solid var(--rc-border-soft)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <input type="text" value={filter} onChange={e => setFilter(e.target.value)}
          placeholder="Filter — feature id, action, payload"
          style={{
            flex: 1, padding: '5px 9px', borderRadius: 6,
            border: '1px solid var(--rc-border)',
            background: 'var(--rc-card)', color: 'var(--rc-text)',
            fontSize: 11, fontFamily: 'inherit', outline: 'none',
          }} />
        <label style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--rc-text-sub)' }}>
          <input type="checkbox" checked={debugOn} onChange={e => {
            setDebugOn(e.target.checked);
            window.__rcTelemetryDebug = e.target.checked;
          }} />
          console.debug
        </label>
      </div>

      {/* Events list */}
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--rc-card)' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: 20, textAlign: 'center', fontSize: 11, color: 'var(--rc-text-mute)' }}>
            {events.length === 0 ? 'Waiting for events…' : 'No events match the filter.'}
          </div>
        ) : (
          [...filtered].reverse().slice(0, 200).map((e, i) => (
            <div key={events.indexOf(e) + '_' + i} style={{
              padding: '6px 12px',
              borderTop: i === 0 ? 0 : '1px solid var(--rc-border-soft)',
              fontSize: 11,
              fontFamily: 'JetBrains Mono, monospace',
              display: 'flex', flexDirection: 'column', gap: 2,
            }}>
              <div style={{ display: 'flex', gap: 6, alignItems: 'baseline' }}>
                <span style={{ color: 'var(--rc-text-mute)', fontSize: 10, minWidth: 58 }}>
                  +{((e.ts - events[0].ts) / 1000).toFixed(1)}s
                </span>
                <span style={{ color: 'var(--rc-chart-1)', fontWeight: 600 }}>
                  @rc:{e.featureId}
                </span>
                <span style={{ color: 'var(--rc-text)' }}>{e.action}</span>
              </div>
              {e.payload && (
                <div style={{
                  color: 'var(--rc-text-sub)', fontSize: 10,
                  paddingLeft: 64,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                }}>
                  {JSON.stringify(e.payload)}
                </div>
              )}
            </div>
          ))
        )}
      </div>

      <div style={{
        padding: '6px 12px',
        borderTop: '1px solid var(--rc-border-soft)',
        fontSize: 10, color: 'var(--rc-text-mute)',
        display: 'flex', justifyContent: 'space-between',
        background: 'var(--rc-subtle)',
      }}>
        <span>{filtered.length} of {events.length} events</span>
        <span style={{ fontFamily: 'JetBrains Mono' }}>⌥E toggles panel</span>
      </div>
    </div>
  );
};

const ghostBtn = {
  padding: '3px 8px', fontSize: 11,
  background: 'transparent', border: '1px solid var(--rc-border)',
  color: 'var(--rc-text-sub)', borderRadius: 5,
  cursor: 'pointer', fontFamily: 'inherit',
};

Object.assign(window, { TelemetryEventsPanel });
