﻿// SCREEN: Anomaly Detection

const AnomaliesScreen = ({ refreshKey = 0 }) => {
  const [items, setItems] = React.useState(MOCK.anomalies);
  const [sensitivity, setSensitivity] = React.useState(3.0);
  const [running, setRunning] = React.useState(false);
  const [selected, setSelected] = React.useState(null);
  const [filter, setFilter] = React.useState('all');
  const [timeRange, setTimeRange] = React.useState(24);

  // Pre-select anomaly navigated to from dashboard
  React.useEffect(() => {
    const id = window.AR_PENDING_ANOMALY_ID;
    if (id) {
      setSelected(items.find(a => a.id === id) || items[0] || null);
      window.AR_PENDING_ANOMALY_ID = null;
    }
  }, []);

  const mapAnomaly = (a, i) => ({
    id: a.anomaly_id || a.id || ('an_' + i),
    type: a.type || 'METRIC_SPIKE',
    sev: a.severity || a.sev || 'MEDIUM',
    title: a.description || a.title || 'Anomaly detected',
    desc: a.details || a.desc || '',
    metric: a.current_value != null ? String(a.current_value) : (a.metric || '—'),
    base: a.baseline_value != null ? String(a.baseline_value) : (a.base || '—'),
    delta: a.delta_pct != null ? (a.delta_pct > 0 ? '+' : '') + a.delta_pct.toFixed(1) + '%' : (a.delta || '—'),
    when: a.detected_at || a.when || 'recently',
  });

  const runDetection = () => {
    setRunning(true);
    arFetch('/v1/insights/anomalies', {
      method: 'POST',
      body: JSON.stringify({ time_range_hours: timeRange, baseline_hours: 168, sensitivity }),
    })
      .then(data => {
        if (data.anomalies && data.anomalies.length > 0) {
          setItems(data.anomalies.map(mapAnomaly));
        }
      })
      .catch(() => {})
      .finally(() => setRunning(false));
  };

  const sevOrder = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 };
  const sevColor = { CRITICAL: 'var(--rose)', HIGH: 'var(--amber)', MEDIUM: 'var(--cyan)', LOW: 'var(--text-3)' };
  const typeLabel = { METRIC_SPIKE: 'Spike', VOLUME_DROP: 'Volume', CHANNEL_SHIFT: 'Channel', LATENCY: 'Latency', ERROR_RATE: 'Errors' };

  const filtered = items
    .filter(a => filter === 'all' || a.sev === filter)
    .sort((a, b) => (sevOrder[a.sev] ?? 9) - (sevOrder[b.sev] ?? 9));

  const counts = { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0 };
  items.forEach(a => { if (counts[a.sev] !== undefined) counts[a.sev]++; });

  return (
    <div>
      <AICallout>
        <strong>{items.length} anomalies</strong> detected in the last {timeRange}h.
        {counts.CRITICAL > 0 && <span> <strong style={{color: 'var(--rose)'}}>{counts.CRITICAL} CRITICAL</strong> require immediate attention.</span>}
        {counts.HIGH > 0 && <span> <strong style={{color: 'var(--amber)'}}>{counts.HIGH} HIGH</strong> need review.</span>}
        {' '}Detection threshold: {sensitivity}σ above 7-day rolling baseline.
      </AICallout>

      {/* Controls */}
      <div style={{display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap'}}>
        <div className="seg">
          {[['all', 'All'], ['CRITICAL', 'Critical'], ['HIGH', 'High'], ['MEDIUM', 'Medium'], ['LOW', 'Low']].map(([id, label]) => (
            <button key={id} className={filter === id ? 'active' : ''} onClick={() => setFilter(id)}>
              {label}{id !== 'all' && counts[id] > 0 ? ` (${counts[id]})` : ''}
            </button>
          ))}
        </div>
        <div style={{display: 'flex', alignItems: 'center', gap: 8, marginLeft: 'auto'}}>
          <span style={{fontSize: 11, color: 'var(--text-3)'}}>Window</span>
          <div className="seg">
            {[[4,'4h'],[24,'24h'],[168,'7d']].map(([v,l]) => (
              <button key={v} className={timeRange === v ? 'active' : ''} onClick={() => setTimeRange(v)}>{l}</button>
            ))}
          </div>
          <span style={{fontSize: 11, color: 'var(--text-3)'}}>Sensitivity</span>
          <div className="seg">
            {[[2,'2σ'],[3,'3σ'],[4,'4σ']].map(([v,l]) => (
              <button key={v} className={sensitivity === v ? 'active' : ''} onClick={() => setSensitivity(v)}>{l}</button>
            ))}
          </div>
          <button className="btn primary" onClick={runDetection} disabled={running}>
            <Icon name="refresh" size={12} />{running ? 'Running…' : 'Run detection'}
          </button>
        </div>
      </div>

      {/* Severity summary strip */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 14}}>
        {[['CRITICAL', 'var(--rose)'], ['HIGH', 'var(--amber)'], ['MEDIUM', 'var(--cyan)'], ['LOW', 'var(--text-3)']].map(([sev, color]) => (
          <div key={sev} className="card" style={{padding: '14px 16px', borderLeft: `3px solid ${color}`, cursor: 'pointer'}}
               onClick={() => setFilter(filter === sev ? 'all' : sev)}>
            <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 6}}>{sev}</div>
            <div style={{fontSize: 28, fontWeight: 700, color, letterSpacing: '-0.02em'}}>{counts[sev]}</div>
          </div>
        ))}
      </div>

      {/* List + detail panel */}
      <div style={{display: 'grid', gridTemplateColumns: selected ? '1fr 360px' : '1fr', gap: 14}}>
        <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
          {filtered.length === 0 && (
            <div style={{textAlign: 'center', padding: 60, color: 'var(--text-4)', fontSize: 13}}>
              No anomalies match the current filter.
            </div>
          )}
          {filtered.map(a => {
            const color = sevColor[a.sev] || 'var(--text-3)';
            const sel = selected?.id === a.id;
            return (
              <div key={a.id}
                style={{
                  display: 'grid', gridTemplateColumns: '4px 1fr auto',
                  alignItems: 'center',
                  background: sel ? 'rgba(139,92,246,0.06)' : 'var(--bg-2)',
                  border: `1px solid ${sel ? 'rgba(139,92,246,0.4)' : 'var(--border)'}`,
                  borderRadius: 10, overflow: 'hidden', cursor: 'pointer',
                }}
                onClick={() => setSelected(sel ? null : a)}>
                <div style={{background: color, alignSelf: 'stretch'}} />
                <div style={{padding: '14px 16px'}}>
                  <div style={{display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6}}>
                    <SevBadge sev={a.sev} />
                    <span className="badge plain" style={{fontSize: 9}}>{typeLabel[a.type] || a.type}</span>
                    <span style={{fontSize: 11, color: 'var(--text-4)', marginLeft: 'auto'}}>{a.when}</span>
                  </div>
                  <div style={{fontSize: 14, fontWeight: 600, color: 'var(--text-1)', marginBottom: 4}}>{a.title}</div>
                  <div style={{fontSize: 12, color: 'var(--text-3)', lineHeight: 1.5}}>{a.desc}</div>
                </div>
                <div style={{textAlign: 'right', padding: '14px 16px', minWidth: 110}}>
                  <div style={{fontSize: 22, fontWeight: 700, color: (a.delta || '').startsWith('+') ? 'var(--emerald)' : 'var(--rose)', fontFamily: 'var(--mono)'}}>{a.delta}</div>
                  <div style={{fontSize: 10, color: 'var(--text-4)', marginTop: 2}}>
                    <span className="mono">{a.metric}</span>
                    <span style={{color: 'var(--text-4)'}}> vs </span>
                    <span className="mono">{a.base}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {selected && (
          <div className="card" style={{position: 'sticky', top: 0, alignSelf: 'start', padding: 0, overflow: 'hidden'}}>
            <div style={{padding: '14px 16px', borderBottom: '1px solid var(--border)', background: 'var(--bg-3)', display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
              <SevBadge sev={selected.sev} />
              <button className="btn ghost" style={{fontSize: 11, padding: '3px 8px'}} onClick={() => setSelected(null)}>✕</button>
            </div>
            <div style={{padding: 16}}>
              <div style={{fontSize: 16, fontWeight: 700, color: 'var(--text-1)', marginBottom: 8, lineHeight: 1.4}}>{selected.title}</div>
              <div style={{fontSize: 12, color: 'var(--text-3)', lineHeight: 1.6, marginBottom: 16}}>{selected.desc}</div>

              {[
                ['Anomaly ID', <span className="mono" style={{fontSize: 11}}>{selected.id}</span>],
                ['Type', <span className="badge plain" style={{fontSize: 10}}>{typeLabel[selected.type] || selected.type}</span>],
                ['Current value', <span className="mono" style={{color: 'var(--rose)'}}>{selected.metric}</span>],
                ['Baseline (7d)', <span className="mono">{selected.base}</span>],
                ['Delta', <span className="mono" style={{color: (selected.delta||'').startsWith('+') ? 'var(--emerald)' : 'var(--rose)', fontWeight: 600}}>{selected.delta}</span>],
                ['Detected', <span style={{color: 'var(--text-2)'}}>{selected.when}</span>],
              ].map(([label, val], i, arr) => (
                <div key={i} style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--border)' : 'none', fontSize: 12}}>
                  <span style={{color: 'var(--text-3)'}}>{label}</span>
                  <span>{val}</span>
                </div>
              ))}

              <div style={{marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8}}>
                <button className="btn primary" style={{width: '100%', justifyContent: 'center'}}
                  onClick={() => {
                    if (selected) {
                      window.AR_PENDING_DECISION = {
                        objective: 'Investigate: ' + (selected.title || selected.metric || ''),
                        evidence: (selected.desc || selected.description || '') + (selected.delta ? ' (delta: ' + selected.delta + ')' : '') + (selected.sev ? ' [severity: ' + selected.sev + ']' : ''),
                        _ts: Date.now(),
                      };
                    }
                    if (window.AR_NAVIGATE) window.AR_NAVIGATE('decisions');
                  }}>
                  <Icon name="brain" size={12} /> Create decision →
                </button>
                <button className="btn ghost" style={{width: '100%', justifyContent: 'center', fontSize: 12}}
                  onClick={() => {
                    setItems(prev => prev.map(a => a.id === selected.id ? { ...a, acknowledged: true } : a));
                    setSelected(null);
                    arFetch(`/v1/insights/anomalies/${selected.id}/acknowledge`, { method: 'POST', body: JSON.stringify({}) }).catch(() => {});
                  }}>
                  Acknowledge
                </button>
              </div>

              <div style={{padding: 10, background: 'rgba(139,92,246,0.06)', border: '1px solid rgba(139,92,246,0.2)', borderRadius: 8, marginTop: 14, fontSize: 11, color: 'var(--text-3)', lineHeight: 1.6}}>
                Detected at <strong style={{color: 'var(--text-1)'}}>{sensitivity}σ</strong> above the 7-day rolling baseline using Z-score analysis. Adjust sensitivity in controls above to surface earlier signals.
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.AnomaliesScreen = AnomaliesScreen;
