// ============================================================
// ANALYTICS — Intelligence Command Center
// Grid of 18 live modules → click any → 7-tab Intelligence Center
// Tabs: Overview · Breakdown · Attribution · Forecasting · AI Insights · Reports · Logs
// ============================================================

const ANALYTICS_MODULES = [
  // Revenue & money
  { id: 'revenue',     name: 'Revenue',                 group: 'money',     metric: '£487.2k', unit: '/ 30d', delta: '+18.4%', deltaDir: 'up', vs: '£412k prev', confidence: 94, anomaly: false, hue: '#5dffb0', icon: 'Up',        ai: 'Revenue velocity strong. Continue current channel mix.' },
  { id: 'pipeline',    name: 'Sales Pipeline',          group: 'money',     metric: '£1.84M',  unit: 'open',  delta: '+£412k', deltaDir: 'up', vs: 'vs prev 30d', confidence: 92, anomaly: false, hue: '#e8c98a', icon: 'Funnel',    ai: '142 deals expected to close this week. Atlas confidence 88%.' },
  { id: 'ltv',         name: 'Lifetime Value',          group: 'money',     metric: '£8,412',  unit: 'avg',   delta: '+8%',    deltaDir: 'up', vs: '£7,800 prev', confidence: 88, anomaly: false, hue: '#e8c98a', icon: 'Chart',     ai: 'LTV expanding faster than CAC — payback period now 4.2 months.' },
  { id: 'forecasting', name: 'Forecasting',             group: 'money',     metric: '£612k',   unit: '60d',   delta: '+24%',   deltaDir: 'up', vs: 'projected',   confidence: 78, anomaly: false, hue: '#8b6bff', icon: 'Sparkles',  ai: 'Best case £742k if TikTok spend reallocated. Worst £482k.' },

  // Acquisition
  { id: 'leads',       name: 'Leads',                   group: 'acquisition', metric: '4,218', unit: '/ 30d', delta: '+24%',   deltaDir: 'up', vs: '3,402 prev', confidence: 96, anomaly: false, hue: '#4be8ff', icon: 'People',    ai: 'Lead quality up · ICP-fit increased 8pp this period.' },
  { id: 'cac',         name: 'Customer Acquisition',    group: 'acquisition', metric: '£184',  unit: 'CAC',   delta: '-12%',   deltaDir: 'up', vs: '£210 prev', confidence: 91, anomaly: false, hue: '#5dffb0', icon: 'Target',    ai: 'CAC dropping. TikTok delivers leads at £84 — 54% below blended.' },
  { id: 'channels',    name: 'Channel Performance',     group: 'acquisition', metric: '6.2x',  unit: 'ROAS',  delta: '+0.8x',  deltaDir: 'up', vs: '5.4x prev', confidence: 89, anomaly: false, hue: '#4be8ff', icon: 'Globe',     ai: 'TikTok 8.4x · Meta 5.2x · Google 6.4x — shift £1.2k to TikTok.' },
  { id: 'social',      name: 'Social Growth',           group: 'acquisition', metric: '+812k', unit: 'reach', delta: '+18%',   deltaDir: 'up', vs: 'vs avg', confidence: 87, anomaly: false, hue: '#ff7ad9', icon: 'Megaphone', ai: 'Instagram + TikTok driving 72% of new reach. Continue cadence.' },

  // Conversion
  { id: 'funnels',     name: 'Funnel Performance',      group: 'conversion', metric: '18.4%', unit: 'avg CVR', delta: '+2.1pp', deltaDir: 'up', vs: '16.3% prev', confidence: 93, anomaly: false, hue: '#8b6bff', icon: 'Funnel',    ai: 'Belmont funnel up · Iyer Studio bottleneck at qualification.' },
  { id: 'attribution', name: 'Conversion Attribution',  group: 'conversion', metric: '£38.4k',unit: 'top path', delta: '+£12k', deltaDir: 'up', vs: 'IG → SMS → AI', confidence: 84, anomaly: false, hue: '#ff7ad9', icon: 'Flow',     ai: '"Instagram → SMS → AI booking" path generated £38k this month.' },
  { id: 'appointments',name: 'Appointments',            group: 'conversion', metric: '1,284', unit: 'booked',  delta: '+24%',   deltaDir: 'up', vs: '1,038 prev', confidence: 95, anomaly: false, hue: '#5dffb0', icon: 'Calendar', ai: 'Show-up rate 87% · Hermes recovers 41 no-shows / week.' },

  // Retention
  { id: 'retention',   name: 'Retention / Churn',       group: 'retention', metric: '92.1%', unit: 'NRR',   delta: '+0.4pp', deltaDir: 'up', vs: '91.7% prev', confidence: 86, anomaly: false, hue: '#5dffb0', icon: 'Refresh',   ai: 'Churn at 2.4% — under target. Expansion driving 142% NRR.' },

  // AI & Ops
  { id: 'ai_agents',   name: 'AI Operator Performance', group: 'ai',        metric: '14,802',unit: 'actions/s', delta: '+18%',  deltaDir: 'up', vs: 'vs avg',  confidence: 99, anomaly: false, hue: '#4be8ff', icon: 'Agent',     ai: 'All 6 operators nominal. Mercury handled 84 calls in 4m peak.' },
  { id: 'crm',         name: 'CRM Activity',            group: 'ai',        metric: '8,412', unit: 'events/24h', delta: '+8%',   deltaDir: 'up', vs: 'vs avg',  confidence: 97, anomaly: false, hue: '#8b6bff', icon: 'Database',  ai: 'CRM sync healthy. 18 errors in 30d — all auto-recovered.' },
  { id: 'ops',         name: 'Operations Health',       group: 'ops',       metric: '99.97%',unit: 'uptime',    delta: '+0.02pp', deltaDir: 'up', vs: 'vs SLA', confidence: 99, anomaly: false, hue: '#5dffb0', icon: 'Bolt',      ai: 'All systems nominal. Latency 38ms · throughput within band.' },
  { id: 'team',        name: 'Team Performance',        group: 'ops',       metric: '94%',   unit: 'capacity',  delta: '+4pp',  deltaDir: 'up', vs: 'utilization', confidence: 84, anomaly: false, hue: '#e8c98a', icon: 'People',   ai: 'Team handling 12x accounts per strategist. Capacity for +3 clients.' },

  // Intelligence
  { id: 'geography',   name: 'Geographic Heatmap',      group: 'intel',     metric: 'UK · 62%', unit: 'top region', delta: '+8pp UK', deltaDir: 'up', vs: 'concentration', confidence: 90, anomaly: false, hue: '#8b6bff', icon: 'Globe', ai: 'London + Manchester drive 48% of pipeline. US-E expanding.' },
  { id: 'risk',        name: 'Risk Detection',          group: 'intel',     metric: '3 ⚠',    unit: 'active',    delta: '-2',     deltaDir: 'up', vs: 'this week',  confidence: 88, anomaly: true,  hue: '#ffb14b', icon: 'Bell',      ai: '3 funnels above acceptable drop-off. 1 account flagged for churn risk.' },
  { id: 'opportunity', name: 'Opportunity Score',       group: 'intel',     metric: '8.4 / 10', unit: 'index',   delta: '+0.6',   deltaDir: 'up', vs: 'vs target',  confidence: 82, anomaly: false, hue: '#e8c98a', icon: 'Sparkles', ai: 'Top opportunity: shift £1.2k Meta → TikTok. Projected +£18k/mo.' }
];

const GROUP_LABELS = {
  money:       'Revenue & Money',
  acquisition: 'Acquisition',
  conversion:  'Conversion & Pipeline',
  retention:   'Retention & LTV',
  ai:          'AI & CRM',
  ops:         'Operations',
  intel:       'Intelligence'
};

function MiniSparkline({ data, color, height = 30 }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 100}`).join(' ');
  const id = `as-grad-${color.replace('#', '')}-${Math.random().toString(36).slice(2, 7)}`;
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{width: '100%', height, opacity: 0.9}}>
      <defs>
        <linearGradient id={id} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={color} stopOpacity="0.4"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={`0,100 ${pts} 100,100`} fill={`url(#${id})`}/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
}

function AnalyticsModuleCard({ module, onOpen }) {
  const sparkData = React.useMemo(
    () => Array.from({length: 30}, (_, i) => 30 + Math.sin(i * 0.4 + module.id.charCodeAt(0)) * 18 + Math.random() * 12),
    [module.id]
  );
  const dirColor = module.deltaDir === 'up' ? 'var(--good)' : 'var(--danger)';

  return (
    <div
      className={`as-card ${module.anomaly ? 'anomaly' : ''}`}
      role="button"
      tabIndex={0}
      onClick={() => onOpen(module)}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(module); }}}
    >
      <span className="as-sash" style={{background: module.hue}}/>
      <span className="br-bl"></span>
      <span className="br-br"></span>

      <div className="as-hd">
        <div className="as-icon" style={{color: module.hue, background: `${module.hue}10`, borderColor: `${module.hue}30`}}>
          {Icon[module.icon] ? React.createElement(Icon[module.icon], {style: {width: 16, height: 16}}) : null}
        </div>
        <div className="as-info">
          <div className="as-name">{module.name}</div>
          <div className="as-group">{GROUP_LABELS[module.group]}</div>
        </div>
        {module.anomaly && (
          <span className="as-anomaly" title="Anomaly detected">⚠</span>
        )}
      </div>

      <div className="as-metric">
        <div className="as-metric-val" style={{color: module.hue}}>{module.metric}</div>
        <div className="as-metric-unit">{module.unit}</div>
      </div>

      <div className="as-delta-row">
        <span className="as-delta" style={{color: dirColor, background: `${dirColor.includes('good') ? '#5dffb0' : '#ff5d6e'}12`}}>
          {module.deltaDir === 'up' ? '▲' : '▼'} {module.delta}
        </span>
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.08em'}}>{module.vs}</span>
      </div>

      <div className="as-spark"><MiniSparkline data={sparkData} color={module.hue}/></div>

      <div className="as-ai">
        <span className="as-ai-pip"/>
        <span className="as-ai-txt">{module.ai}</span>
      </div>

      <div className="as-foot">
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.1em'}}>
          confidence <span style={{color: module.confidence > 90 ? 'var(--good)' : module.confidence > 75 ? 'var(--cyan)' : 'var(--warn)'}}>{module.confidence}</span>
          {' · '}refreshed <span style={{color: 'var(--text-dim)'}}>2m ago</span>
        </span>
        <span className="as-open">Open intelligence center <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M9 6l6 6-6 6"/></svg></span>
      </div>
      <div className="as-hover-glow"></div>
    </div>
  );
}

function Analytics() {
  const [filter, setFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(null);
  const [query, setQuery] = React.useState('');

  React.useEffect(() => {
    if (!selected) return;
    const onKey = (e) => { if (e.key === 'Escape') setSelected(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [selected]);

  if (selected) {
    return (
      <div className="ch-fade-in">
        <AnalyticsIntelligenceCenter module={selected} onBack={() => setSelected(null)}/>
      </div>
    );
  }

  const filtered = ANALYTICS_MODULES.filter(m => {
    if (filter !== 'all' && m.group !== filter) return false;
    if (query && !`${m.name} ${m.group} ${m.ai}`.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });

  const grouped = {};
  filtered.forEach(m => {
    if (!grouped[m.group]) grouped[m.group] = [];
    grouped[m.group].push(m);
  });

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Intelligence · {ANALYTICS_MODULES.length} modules · real-time</div>
          <h1 className="page-title"><em>Intelligence</em> <strong>& analytics</strong></h1>
          <div className="page-sub">Every signal across revenue, acquisition, conversion, retention, operations, and risk — instrumented, attributed, forecast. Click any module for its intelligence center.</div>
        </div>
        <div className="page-hd-r">
          <button className="btn" data-handled="1" onClick={() => window.toast('Refreshing all metrics…', 'info', 'Pulling 90 days · all channels · all segments')}><Icon.Refresh className="icon"/>Refresh all</button>
          <button className="btn" data-handled="1" onClick={() => window.runAction('generateReport')}><Icon.Filter className="icon"/>Schedule report</button>
          <button className="btn primary" data-handled="1" onClick={() => window.demiurgeOpenAI?.()}><Icon.Sparkles className="icon"/>Ask Demiurge</button>
        </div>
      </div>

      {/* AI command bar */}
      <div style={{padding: '20px 32px 0'}}>
        <div className="as-cmd">
          <Icon.Sparkles style={{width: 16, height: 16, color: 'var(--brass-bright, #e8c98a)'}}/>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Ask Demiurge Intelligence  ·  e.g. &quot;Compare Meta vs TikTok ROAS&quot;  ·  &quot;Show funnel drop-off in clinics&quot;  ·  &quot;Why are conversions falling?&quot;"
            style={{flex: 1, fontSize: 13, padding: '6px 0', fontFamily: 'var(--font-mono)', color: 'var(--text)'}}
          />
          <span className="kbd">⌘ I</span>
        </div>
      </div>

      {/* Group filter pills */}
      <div style={{padding: '20px 32px 0', display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center'}}>
        <button className={`ccc-pill ${filter === 'all' ? 'on' : ''}`} onClick={() => setFilter('all')}>All</button>
        {Object.entries(GROUP_LABELS).map(([k, l]) => (
          <button key={k} className={`ccc-pill ${filter === k ? 'on' : ''}`} onClick={() => setFilter(k)}>{l}</button>
        ))}
        <span style={{flex: 1}}/>
        <span className="mono faint" style={{fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase'}}>
          {filtered.length} modules · streaming
        </span>
      </div>

      {/* Modules grouped */}
      <div style={{padding: '24px 32px 36px', display: 'flex', flexDirection: 'column', gap: 28}}>
        {Object.entries(grouped).map(([groupKey, mods]) => (
          <div key={groupKey}>
            {filter === 'all' && (
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                marginBottom: 14,
                fontFamily: 'var(--font-mono)',
                fontSize: 10.5,
                letterSpacing: '0.2em',
                textTransform: 'uppercase',
                color: 'var(--brass-bright, #e8c98a)'
              }}>
                <span>/ {GROUP_LABELS[groupKey]}</span>
                <span style={{flex: 1, height: 1, background: 'linear-gradient(90deg, rgba(232,201,138,0.3), transparent)'}}/>
                <span style={{color: 'var(--text-faint)'}}>{mods.length}</span>
              </div>
            )}
            <div className="as-grid">
              {mods.map(m => <AnalyticsModuleCard key={m.id} module={m} onOpen={setSelected}/>)}
            </div>
          </div>
        ))}
        {filtered.length === 0 && (
          <div className="empty" style={{padding: 80}}>
            <span className="mono faint" style={{letterSpacing: '0.16em', textTransform: 'uppercase'}}>No intelligence modules match this query</span>
          </div>
        )}
      </div>
    </div>
  );
}

window.Analytics = Analytics;
window.ANALYTICS_MODULES = ANALYTICS_MODULES;
window.GROUP_LABELS = GROUP_LABELS;
window.MiniSparkline = MiniSparkline;
