// SCREEN: Decisions + Anomalies

const DecisionsScreen = () => {
  const [allDecisions, setAllDecisions] = React.useState(MOCK.decisions);
  const [selectedId, setSelectedId] = React.useState(MOCK.decisions[0] ? MOCK.decisions[0].id : '');
  const [statusFilter, setStatusFilter] = React.useState('ALL');
  const [accepting, setAccepting] = React.useState(false);

  React.useEffect(() => {
    arFetch('/v1/decisions?limit=20')
      .then(data => {
        const list = Array.isArray(data) ? data : (data.decisions || []);
        const mapped = list.map(window.mapDecision);
        if (mapped.length > 0) {
          setAllDecisions(mapped);
          setSelectedId(mapped[0].id);
        }
      })
      .catch(() => {}); // keep MOCK.decisions
  }, []);

  const handleAccept = async (decisionId) => {
    if (accepting) return;
    setAccepting(true);
    const d = allDecisions.find(x => x.id === decisionId);
    const actions = d && d._raw && d._raw.actions;
    const aid = (actions && actions[0] && actions[0].action_id) || 'default';
    let success = false;
    try {
      await arFetch(`/v1/decisions/${decisionId}/actions/${aid}/approve`, { method: 'POST', body: JSON.stringify({}) });
      success = true;
    } catch (e) {
      success = true; // fallback: accept locally even if API unavailable (MOCK mode)
    } finally {
      setAccepting(false);
    }
    if (success) {
      setAllDecisions(prev => prev.map(x => x.id === decisionId ? { ...x, status: 'ACCEPTED' } : x));
    }
  };

  const handleReject = async (decisionId) => {
    const d = allDecisions.find(x => x.id === decisionId);
    const actions = d && d._raw && d._raw.actions;
    const aid = (actions && actions[0] && actions[0].action_id) || 'default';
    try {
      await arFetch(`/v1/decisions/${decisionId}/actions/${aid}/reject`, { method: 'POST', body: JSON.stringify({}) });
    } catch (e) {
      // fallback: update locally even if API unavailable
    }
    setAllDecisions(prev => prev.map(x => x.id === decisionId ? { ...x, status: 'REJECTED' } : x));
  };

  // FIX: only reset selection if the current selection is no longer visible in the new filter
  React.useEffect(() => {
    const inFilter = statusFilter === 'ALL' ? allDecisions : allDecisions.filter(d => d.status === statusFilter);
    const stillVisible = inFilter.find(d => d.id === selectedId);
    if (!stillVisible && inFilter.length > 0) setSelectedId(inFilter[0].id);
  }, [statusFilter]);

  const filtered = statusFilter === 'ALL' ? allDecisions : allDecisions.filter(d => d.status === statusFilter);
  const selected = allDecisions.find(d => d.id === selectedId) || filtered[0] || null;

  return (
    <div style={{display: 'grid', gridTemplateColumns: '340px 1fr', gap: 14, height: '100%'}}>
      <div style={{display: 'flex', flexDirection: 'column', gap: 10, minHeight: 0}}>
        <button className="btn primary" style={{justifyContent: 'center'}}
          onClick={() => {
            let prefill = {};
            try { prefill = JSON.parse(sessionStorage.getItem('ar_decision_prefill') || '{}'); sessionStorage.removeItem('ar_decision_prefill'); } catch(e) {}
            const title = prefill.title || '';
            const desc = prefill.description || '';
            const input = prompt('New decision objective:' + (title ? '\n\nSuggested: ' + title : ''), title || '');
            if (!input || !input.trim()) return;
            const newD = {
              id: 'dec_' + Date.now().toString(36),
              type: 'OPTIMIZATION',
              status: 'PENDING',
              objective: input.trim() + (desc ? '\n\nContext: ' + desc : ''),
              created: 'just now',
              reflexions: 0,
              _raw: {},
            };
            setAllDecisions(prev => [newD, ...prev]);
            setSelectedId(newD.id);
          }}>
          <Icon name="plus" size={12} /> New decision
        </button>
        <div style={{display: 'flex', gap: 4}}>
          {['ALL', 'PENDING', 'ACCEPTED', 'REJECTED'].map(s => (
            <button key={s} className={`filter-chip ${statusFilter===s?'active':''}`} onClick={() => setStatusFilter(s)}>{s}</button>
          ))}
        </div>
        <div style={{flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8}}>
          {filtered.map(d => (
            <div key={d.id}
                 onClick={() => setSelectedId(d.id)}
                 style={{padding: 12, background: 'var(--bg-2)', border: '1px solid ' + (d.id === selectedId ? 'var(--accent)' : 'var(--border)'), borderLeft: d.id === selectedId ? '3px solid var(--accent)' : '1px solid var(--border)', borderRadius: 8, cursor: 'pointer'}}>
              <div style={{display: 'flex', gap: 6, alignItems: 'center', marginBottom: 6}}>
                <span className="badge violet" style={{fontSize: 9}}>{d.type}</span>
                <StatusBadge status={d.status} />
                {((Array.isArray(d.reflexions) ? d.reflexions.length : d.reflexions) > 0) && (
                  <span className="badge" style={{marginLeft: 'auto', fontSize: 9}}>🧠 {Array.isArray(d.reflexions) ? d.reflexions.length : d.reflexions}</span>
                )}
              </div>
              <div style={{fontSize: 12, color: 'var(--text-1)', lineHeight: 1.45, marginBottom: 6, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden'}}>{d.objective}</div>
              <div className="mono" style={{fontSize: 10, color: 'var(--text-4)'}}>{d.id} · {d.created}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{overflowY: 'auto'}}>
        {!selected ? (
          <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: 'var(--text-4)', fontSize: 13}}>No decisions match the current filter.</div>
        ) : (
        <React.Fragment>
        <div className="card">
          <div style={{display: 'flex', gap: 8, alignItems: 'center', marginBottom: 14}}>
            <span className="badge violet">{selected.type}</span>
            <StatusBadge status={selected.status} />
            <span className="mono" style={{fontSize: 11, color: 'var(--text-3)', marginLeft: 'auto'}}>{selected.id} · created {selected.created}</span>
          </div>
          <div style={{fontSize: 18, fontWeight: 600, color: 'var(--text-1)', lineHeight: 1.4, marginBottom: 20, letterSpacing: '-0.01em'}}>{selected.objective}</div>

          <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14}}>
            <div>
              <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8}}>Context</div>
              <div className="json-view">
                <div>{`{`}</div>
                <div>  <span className="k">"campaign"</span>: <span className="s">"spring_24"</span>,</div>
                <div>  <span className="k">"current_cpa"</span>: <span className="n">42.18</span>,</div>
                <div>  <span className="k">"target_cpa"</span>: <span className="n">35.00</span>,</div>
                <div>  <span className="k">"budget_weekly"</span>: <span className="n">18000</span>,</div>
                <div>  <span className="k">"window_days"</span>: <span className="n">14</span></div>
                <div>{`}`}</div>
              </div>
            </div>
            <div>
              <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8}}>Evidence (retrieved from memory)</div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
                {[
                  { title: 'Last Q budget reallocation result', sim: 0.91, type: 'decision_context' },
                  { title: 'Google Shopping ROAS benchmark', sim: 0.84, type: 'world_state' },
                  { title: 'Meta auction saturation signal', sim: 0.78, type: 'observation' },
                  { title: 'Mobile checkout optimization win', sim: 0.72, type: 'decision_context' },
                ].map((e, i) => (
                  <div key={i} style={{padding: 8, background: 'var(--bg-3)', borderRadius: 6, border: '1px solid var(--border)'}}>
                    <div style={{display: 'flex', gap: 6, alignItems: 'center', marginBottom: 2}}>
                      <span className="mono" style={{fontSize: 10, color: '#6ee7b7'}}>{e.sim.toFixed(2)}</span>
                      <span className="badge" style={{fontSize: 9}}>{e.type}</span>
                    </div>
                    <div style={{fontSize: 11, color: 'var(--text-1)'}}>{e.title}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div style={{padding: 16, background: 'linear-gradient(90deg, rgba(139,92,246,0.08), rgba(139,92,246,0.02))', border: '1px solid rgba(139,92,246,0.3)', borderRadius: 10, marginBottom: 14}}>
            <div style={{fontSize: 10, color: '#c4b5fd', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6}}>
              <Icon name="sparkle" size={12} /> AI proposal
            </div>
            <div style={{fontSize: 14, color: 'var(--text-1)', lineHeight: 1.65}}>
              Reduce Meta Advantage+ budget by 15% (-$2,700/wk) and redirect to Google Shopping bottom-funnel campaigns targeting the "premium intent" segment. Based on 3 prior similar reallocations, expected CPA improvement is <strong style={{color: '#6ee7b7'}}>-18% to -24%</strong> with 86% confidence.
            </div>
          </div>

          <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10}}>Expected impact</div>
          <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 18}}>
            {[
              { label: 'CPA',  value: '$34.20', delta: '-19%', conf: 86 },
              { label: 'ROAS', value: '3.8×',   delta: '+14%', conf: 82 },
              { label: 'Conv volume', value: '+128/wk', delta: '+8%', conf: 74 },
            ].map(s => (
              <div key={s.label} style={{padding: 12, background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8}}>
                <div style={{fontSize: 10, color: 'var(--text-3)', marginBottom: 4}}>{s.label}</div>
                <div style={{fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em'}}>{s.value}</div>
                <div style={{display: 'flex', alignItems: 'center', gap: 6, marginTop: 4}}>
                  <span className="badge green" style={{fontSize: 9}}>{s.delta}</span>
                  <span className="mono" style={{fontSize: 10, color: 'var(--text-3)'}}>conf {s.conf}%</span>
                </div>
              </div>
            ))}
          </div>

          <div style={{display: 'flex', gap: 8, borderTop: '1px solid var(--border)', paddingTop: 14}}>
            <button className="btn primary" onClick={() => handleAccept(selected.id)} disabled={accepting}><Icon name="check" size={12} /> {accepting ? 'Accepting…' : 'Accept'}</button>
            <button className="btn" onClick={() => handleReject(selected.id)}><Icon name="x" size={12} /> Reject</button>
            <button className="btn" onClick={async () => {
              const note = prompt('Describe what needs to change:');
              if (!note || !note.trim()) return;
              try {
                await arFetch(`/v1/decisions/${selected.id}/revise`, { method: 'POST', body: JSON.stringify({ feedback: note.trim() }) });
              } catch(e) { /* API may not be live — update locally */ }
              setAllDecisions(prev => prev.map(d => d.id === selected.id ? {
                ...d,
                reflexions: [...(Array.isArray(d.reflexions) ? d.reflexions : []), { id: 'r_' + Date.now(), text: '📝 Revision requested: ' + note.trim(), ts: new Date().toLocaleString() }]
              } : d));
            }}>Request revision</button>
            <button className="btn ghost" style={{marginLeft: 'auto'}} onClick={() => {
              const note = prompt('Add a reflexion note:');
              if (note && selected) {
                setAllDecisions(prev => prev.map(d => d.id === selected.id ? {
                  ...d,
                  reflexions: [...(d.reflexions || []), { id: 'r_' + Date.now(), text: note, ts: new Date().toLocaleString() }]
                } : d));
              }
            }}>+ Add reflexion</button>
          </div>
        </div>

        <div className="card" style={{marginTop: 14}}>
          <div className="card-title" style={{marginBottom: 14}}>Reflexion timeline</div>
          <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            {(() => {
              const staticItems = [
                { when: '2d ago', who: 'AR', delta: '+0.08', what: 'Similar tCPA switch on shopping campaigns delivered -21% CPA within 7d.', why: 'Audience was already warm from Meta; Google reclaimed bottom-funnel efficiency.' },
                { when: '5d ago', who: 'You', delta: '-0.12', what: 'Prior attempt failed — budget shifted too aggressively, caused impression volatility.', why: 'Step changes >20% of baseline spend trigger auction re-learning on both platforms.' },
              ];
              const dynamicItems = Array.isArray(selected.reflexions) ? selected.reflexions.map(r => ({
                when: r.ts || 'just now',
                who: 'You',
                delta: '',
                what: r.text || '',
                why: '',
              })) : [];
              const allItems = [...dynamicItems, ...staticItems];
              return allItems.map((r, i) => (
                <div key={i} style={{display: 'grid', gridTemplateColumns: '28px 1fr', gap: 12}}>
                  <div style={{width: 28, height: 28, borderRadius: 6, background: r.who === 'AR' ? 'var(--accent)' : 'var(--bg-4)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600}}>{r.who}</div>
                  <div>
                    <div style={{display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6}}>
                      <span style={{fontSize: 12, color: 'var(--text-2)'}}>{r.when}</span>
                      {r.delta && <span className={`badge ${r.delta.startsWith('+') ? 'green' : 'rose'}`} style={{fontSize: 9}}>Δconf {r.delta}</span>}
                    </div>
                    <div style={{fontSize: 12, color: 'var(--text-1)', marginBottom: 4, lineHeight: 1.55}}>{r.what && <><strong style={{color: 'var(--text-3)', fontWeight: 500}}>what happened:</strong> {r.what}</>}</div>
                    {r.why && <div style={{fontSize: 11, color: 'var(--text-3)', fontStyle: 'italic', lineHeight: 1.5}}>{r.why}</div>}
                  </div>
                </div>
              ));
            })()}
          </div>
        </div>
        </React.Fragment>
        )}
      </div>
    </div>
  );
};

// SCREEN: Anomalies
const AnomaliesScreen = () => {
  const [sev, setSev] = React.useState('ALL');
  const [sensitivity, setSensitivity] = React.useState(3.0);
  const extra = [
    { id: 'an_004', type: 'TIME_PATTERN', sev: 'MEDIUM', title: 'Unusual late-night traffic surge',  desc: 'App session volume between 02:00–04:00 UTC is 3.2× the 14d baseline; may indicate bot activity or campaign in APAC.', metric: '4,210', base: '1,310', delta: '+221%', when: '6h ago' },
    { id: 'an_005', type: 'METRIC_SPIKE', sev: 'HIGH', title: 'Cart abandonment spike on mobile',     desc: 'Mobile web abandonment at checkout step jumped from 61% to 78% over the last 2h.', metric: '78%', base: '61%', delta: '+17pp', when: '2h ago' },
    { id: 'an_006', type: 'VOLUME_DROP',  sev: 'MEDIUM', title: 'Google Shopping clicks down 14%',    desc: 'Branded shopping campaign clicks fell below 1σ; quality score for "premium" query group dropped.', metric: '8,412', base: '9,785', delta: '-14%', when: '8h ago' },
  ];
  const [anomalyList, setAnomalyList] = React.useState([...MOCK.anomalies, ...extra]);
  const [detecting, setDetecting] = React.useState(false);
  const [timeWindow, setTimeWindow] = React.useState(48);

  const runDetection = async () => {
    setDetecting(true);
    try {
      const res = await arFetch('/v1/insights/anomalies', {
        method: 'POST',
        body: JSON.stringify({ time_range_hours: timeWindow, baseline_hours: 168, sensitivity: sensitivity }),
      });
      const mapped = (res.anomalies || []).map(window.mapAnomaly);
      setAnomalyList(mapped);
      if (mapped.length === 0) {
        // show empty state — handled by render
      }
    } catch (e) { /* keep existing anomalyList */ }
    finally { setDetecting(false); }
  };

  const filtered = sev === 'ALL' ? anomalyList : anomalyList.filter(a => a.sev === sev);

  return (
    <div>
      <div style={{display: 'flex', gap: 10, marginBottom: 14, alignItems: 'center', flexWrap: 'wrap'}}>
        <button className="btn primary" onClick={runDetection} disabled={detecting}><Icon name="refresh" size={12} /> {detecting ? 'Detecting…' : 'Run detection'}</button>
        <div style={{display: 'flex', gap: 6, alignItems: 'center', marginLeft: 8}}>
          <span style={{fontSize: 11, color: 'var(--text-3)'}}>Sensitivity</span>
          <input type="range" min="1" max="5" step="0.5" value={sensitivity}
            onChange={e => setSensitivity(+e.target.value)} style={{accentColor: 'var(--accent)'}} />
          <span className="mono" style={{fontSize: 11, color: 'var(--text-2)'}}>{sensitivity.toFixed(1)}σ</span>
        </div>
        <div className="seg" style={{marginLeft: 'auto'}}>
          {[['24h',24], ['48h',48], ['7d',168]].map(([label, hrs]) => (
            <button key={label} className={timeWindow===hrs?'active':''} onClick={() => setTimeWindow(hrs)}>{label}</button>
          ))}
        </div>
      </div>

      <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 14}}>
        {(() => {
          const critCount = anomalyList.filter(a => a.sev === 'CRITICAL').length;
          const highCount = anomalyList.filter(a => a.sev === 'HIGH').length;
          const medCount  = anomalyList.filter(a => a.sev === 'MEDIUM').length;
          return [
            { label: 'Total anomalies', value: anomalyList.length, color: 'var(--text-1)' },
            { label: 'Critical',        value: critCount,           color: 'var(--rose)' },
            { label: 'High',            value: highCount,           color: 'var(--amber)' },
            { label: 'Medium',          value: medCount,            color: 'var(--cyan)' },
          ];
        })().map(s => (
          <div key={s.label} className="card" style={{padding: '14px 16px'}}>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>{s.label}</div>
            <div style={{fontSize: 28, fontWeight: 600, color: s.color, letterSpacing: '-0.02em'}}>{s.value}</div>
          </div>
        ))}
      </div>

      <div style={{display: 'flex', gap: 6, marginBottom: 14}}>
        {['ALL', 'CRITICAL', 'HIGH', 'MEDIUM'].map(s => (
          <button key={s} className={`filter-chip ${sev===s?'active':''}`} onClick={() => setSev(s)}>{s}</button>
        ))}
      </div>

      <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14}}>
        {filtered.length === 0 && !detecting && (
          <div style={{padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 12, gridColumn: '1 / -1'}}>
            No anomalies detected for the selected time window.
          </div>
        )}
        {filtered.map(a => (
          <div key={a.id} className="card">
            <div style={{display: 'flex', gap: 6, alignItems: 'center', marginBottom: 10}}>
              <SevBadge sev={a.sev} />
              <span className="mono" style={{fontSize: 10, color: 'var(--text-4)'}}>{a.type}</span>
              <span className="mono" style={{fontSize: 10, color: 'var(--text-3)', marginLeft: 'auto'}}>{a.when}</span>
            </div>
            <div style={{fontSize: 14, fontWeight: 600, color: 'var(--text-1)', marginBottom: 6, lineHeight: 1.4}}>{a.title}</div>
            <div style={{fontSize: 12, color: 'var(--text-2)', lineHeight: 1.55, marginBottom: 14}}>{a.desc}</div>

            <div style={{display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10}}>
              <span style={{fontSize: 22, fontWeight: 600, color: a.delta.startsWith('-') || a.delta.startsWith('+') && a.sev !== 'MEDIUM' ? 'var(--rose)' : 'var(--amber)'}}>{a.metric}</span>
              <span style={{fontSize: 11, color: 'var(--text-3)'}}>vs baseline <span className="mono" style={{color: 'var(--text-2)'}}>{a.base}</span></span>
              <span className="badge rose" style={{marginLeft: 'auto'}}>{a.delta}</span>
            </div>

            <svg viewBox="0 0 240 50" width="100%" height="50">
              {(() => {
                const pts = MOCK.spark(a.id.charCodeAt(4), 0.6);
                const d = pts.map((v, i) => (i===0?'M':'L') + (i*(240/29)).toFixed(1) + ' ' + (45 - v*0.35).toFixed(1)).join(' ');
                return <g>
                  <rect x={210} y="5" width="28" height="42" fill="#F43F5E" opacity="0.15" />
                  <path d={d} stroke="var(--text-3)" strokeWidth="1.5" fill="none" />
                </g>;
              })()}
            </svg>

            <button className="btn" style={{width: '100%', justifyContent: 'center', marginTop: 10}}
              onClick={() => { if (window.AR_NAVIGATE) window.AR_NAVIGATE('decisions'); }}>
              Recommended action <Icon name="arrow-right" size={11} />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
};

window.DecisionsScreen = DecisionsScreen;
window.AnomaliesScreen = AnomaliesScreen;
