// SCREEN: Insights
const InsightsScreen = () => {
  const [tab, setTab] = React.useState('summaries');
  const [insights, setInsights] = React.useState(MOCK.insights);
  const [actorId, setActorId] = React.useState('act_7d1e8');
  const [timeWindow, setTimeWindow] = React.useState('30d');
  const [generating, setGenerating] = React.useState(false);
  const [genToast, setGenToast] = React.useState(null);
  const [pathLimit, setPathLimit] = React.useState(10);
  const [sevFilter, setSevFilter] = React.useState('ALL');

  React.useEffect(() => {
    arFetch('/v1/world/journey_graph/insights')
      .then(data => {
        const rawPaths = data.top_paths || data.conversion_paths || [];
        const topPaths = rawPaths.map(p => ({
          steps: p.path || p.steps || [],
          rate: typeof p.conversion_rate === 'number'
            ? Math.round(p.conversion_rate * 100) / 100
            : (p.rate || 0),
          count: p.count || 0,
        }));
        if (topPaths.length > 0) {
          setInsights(prev => ({ ...prev, topPaths }));
        }
      })
      .catch(() => {}); // keep MOCK.insights on error
  }, []);

  return (
    <div>
      <div style={{display: 'flex', gap: 2, marginBottom: 20, borderBottom: '1px solid var(--border)'}}>
        {[
          { id: 'summaries', label: 'Journey summaries' },
          { id: 'paths',     label: 'Conversion paths' },
          { id: 'bottle',    label: 'Bottlenecks' },
        ].map(t => (
          <button key={t.id}
            style={{padding: '10px 16px', fontSize: 12, color: tab === t.id ? 'var(--text-1)' : 'var(--text-3)', borderBottom: tab === t.id ? '2px solid var(--accent)' : '2px solid transparent', fontWeight: 500, marginBottom: -1}}
            onClick={() => setTab(t.id)}>{t.label}</button>
        ))}
      </div>

      {tab === 'summaries' && (
        <div>
          <div style={{display: 'flex', gap: 10, marginBottom: 14, alignItems: 'center'}}>
            <input
              placeholder="Enter actor ID — e.g. act_7d1e8"
              value={actorId}
              onChange={e => setActorId(e.target.value)}
              style={{flex: 1, maxWidth: 300, padding: '8px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text-1)', fontSize: 12, outline: 'none', fontFamily: 'var(--mono)'}}
            />
            <div className="seg">{['7d','30d','90d'].map(w => <button key={w} className={timeWindow === w ? 'active' : ''} onClick={() => setTimeWindow(w)}>{w}</button>)}</div>
            <button className="btn primary" style={{marginLeft: 'auto'}} disabled={generating} onClick={() => {
              if (!actorId.trim()) return;
              setGenerating(true);
              const days = timeWindow === '7d' ? 7 : timeWindow === '90d' ? 90 : 30;
              arFetch(`/v1/identities/actor/${actorId.trim()}?days=${days}`)
                .then(data => {
                  if (data && (data.summary || data.patterns || data.recs)) {
                    setInsights(prev => ({
                      ...prev,
                      summary: data.summary || prev.summary,
                      patterns: data.patterns || prev.patterns,
                      recs: data.recs || prev.recs,
                    }));
                    setGenToast('Summary generated for ' + actorId.trim());
                  } else {
                    setGenToast('Demo mode — showing AI-generated summary for ' + actorId.trim());
                  }
                  setTimeout(() => setGenToast(null), 4000);
                })
                .catch(() => {
                  setGenToast('Demo mode — AI summary ready for ' + actorId.trim() + ' (' + timeWindow + ')');
                  setTimeout(() => setGenToast(null), 4000);
                })
                .finally(() => setGenerating(false));
            }}><Icon name="sparkle" size={12} /> {generating ? 'Generating…' : 'Generate summary'}</button>
          </div>

          <div className="card">
            <div style={{display: 'flex', gap: 8, alignItems: 'center', marginBottom: 14}}>
              <span className="badge violet">USER</span>
              <span className="mono" style={{fontSize: 12}}>{actorId}</span>
              <span style={{fontSize: 11, color: 'var(--text-3)'}}>created 2025-11-03 · 42 events · 3 sessions</span>
            </div>

            <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8}}>AI Summary</div>
            <div style={{fontSize: 14, lineHeight: 1.7, color: 'var(--text-1)', marginBottom: 24}}>{insights.summary}</div>

            <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10}}>Key touchpoints</div>
            <div style={{display: 'flex', gap: 2, marginBottom: 24, alignItems: 'center', position: 'relative', padding: '14px 0'}}>
              <div style={{position: 'absolute', left: 0, right: 0, top: '50%', height: 2, background: 'linear-gradient(90deg, transparent, var(--border), var(--border), transparent)'}} />
              {[
                { label: 'meta_ad', c: '#8B5CF6', t: 'Apr 12' },
                { label: 'pdp',     c: '#22D3EE', t: 'Apr 12' },
                { label: 'search',  c: '#22D3EE', t: 'Apr 14' },
                { label: 'atc',     c: '#F59E0B', t: 'Apr 14' },
                { label: 'checkout',c: '#F59E0B', t: 'Apr 15' },
                { label: 'purchase',c: '#10B981', t: 'Apr 15' },
                { label: 'pdp',     c: '#22D3EE', t: 'Apr 18' },
                { label: 'atc',     c: '#F59E0B', t: 'Apr 18' },
              ].map((p, i) => (
                <div key={i} style={{flex: 1, textAlign: 'center', position: 'relative'}}>
                  <div style={{width: 28, height: 28, borderRadius: '50%', background: 'var(--bg-1)', border: `2px solid ${p.c}`, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, color: p.c, position: 'relative', zIndex: 1}}>●</div>
                  <div style={{fontSize: 10, color: 'var(--text-2)', marginTop: 6, fontFamily: 'var(--mono)'}}>{p.label}</div>
                  <div style={{fontSize: 9, color: 'var(--text-4)'}}>{p.t}</div>
                </div>
              ))}
            </div>

            <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10}}>Behavior patterns</div>
            <div style={{display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 24}}>
              {insights.patterns.map(p => (
                <span key={p} className="badge violet" style={{fontSize: 11, padding: '4px 10px', textTransform: 'none', letterSpacing: 0}}>{p}</span>
              ))}
            </div>

            <div style={{padding: 14, 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}}>
              <div style={{fontSize: 10, color: '#c4b5fd', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6}}>
                <Icon name="sparkle" size={12} />Recommendations
              </div>
              <ul style={{margin: 0, paddingLeft: 18, fontSize: 13, color: 'var(--text-1)', lineHeight: 1.8}}>
                {insights.recs.map((r, i) => <li key={i}>{r}</li>)}
              </ul>
            </div>
          </div>
        </div>
      )}

      {tab === 'paths' && (
        <div>
          <AICallout>Paths through <strong>Email → Direct</strong> convert 2.3× higher than <strong>Paid → Social</strong>. Consider reallocating budget toward email nurture.</AICallout>
          <div className="card">
            <div className="card-header">
              <div className="card-title">Top conversion paths (30d)</div>
              <div className="seg">
                {[10, 25, 0].map(n => (
                  <button key={n} className={pathLimit === n ? 'active' : ''} onClick={() => setPathLimit(n)}>
                    {n === 0 ? 'All' : `Top ${n}`}
                  </button>
                ))}
              </div>
            </div>
            <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
              {(pathLimit === 0 ? insights.topPaths : insights.topPaths.slice(0, pathLimit)).map((p, i) => (
                <div key={i} style={{display: 'grid', gridTemplateColumns: '30px 1fr 100px 80px 50px', gap: 14, alignItems: 'center', padding: '10px 14px', background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8}}>
                  <span className="mono" style={{color: 'var(--text-4)', fontSize: 14, fontWeight: 600}}>#{i+1}</span>
                  <div style={{display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center'}}>
                    {p.steps.map((s, j) => (
                      <React.Fragment key={j}>
                        <span className="mono" style={{fontSize: 11, padding: '3px 8px', background: 'var(--bg-1)', borderRadius: 4, color: 'var(--text-1)'}}>{s}</span>
                        {j < p.steps.length - 1 && <span style={{color: 'var(--text-4)'}}>›</span>}
                      </React.Fragment>
                    ))}
                  </div>
                  <div style={{fontSize: 11, color: 'var(--text-3)'}}>conv rate</div>
                  <div>
                    <div style={{height: 4, background: 'var(--bg-1)', borderRadius: 2, overflow: 'hidden'}}>
                      <div style={{width: Math.min(100, p.rate * 12) + '%', height: '100%', background: 'var(--emerald)'}} />
                    </div>
                    <div style={{fontSize: 11, color: '#6ee7b7', marginTop: 2, fontWeight: 600}}>{p.rate}%</div>
                  </div>
                  <span className="mono" style={{fontSize: 11, color: 'var(--text-3)', textAlign: 'right'}}>{p.count}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {tab === 'bottle' && (
        <div>
          <div style={{display: 'flex', gap: 6, marginBottom: 14}}>
            {['ALL', 'CRITICAL', 'HIGH', 'MEDIUM'].map((s) => (
              <button key={s} onClick={() => setSevFilter(s)} className={`filter-chip ${sevFilter===s?'active':''}`}>{s}</button>
            ))}
          </div>
          <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14}}>
            {[
              { stage: 'checkout → purchase', sev: 'CRITICAL', drop: 61, hyp: 'Guest checkout friction on mobile is likely driving abandonment. The "create account or continue as guest" prompt shows 2.1s delay.', fix: ['Enable 1-tap guest checkout on mobile', 'Defer account creation to post-purchase', 'Pre-fill form from identity graph'] },
              { stage: 'atc → checkout', sev: 'HIGH', drop: 55, hyp: 'Shipping cost reveal at cart step correlates with the drop-off spike seen on mobile web.', fix: ['Display shipping estimate on PDP', 'Add free-shipping progress bar', 'Test flat-rate shipping cohort'] },
              { stage: 'search → pdp', sev: 'MEDIUM', drop: 38, hyp: 'Search ranking for premium queries returns too few results (median = 4).', fix: ['Expand premium product taxonomy', 'Add semantic search fallback', 'Merchandise top premium SKUs'] },
            ].filter(b => sevFilter === 'ALL' || b.sev === sevFilter).map((b, i) => (
              <div key={i} className="card">
                <div style={{display: 'flex', gap: 6, alignItems: 'center', marginBottom: 10}}>
                  <SevBadge sev={b.sev} />
                  <span className="mono" style={{fontSize: 11, color: 'var(--text-2)', marginLeft: 'auto'}}>{b.stage}</span>
                </div>
                <div style={{fontSize: 30, fontWeight: 600, color: 'var(--rose)', letterSpacing: '-0.02em', marginBottom: 4}}>{b.drop}%</div>
                <div style={{fontSize: 11, color: 'var(--text-3)', marginBottom: 10}}>drop-off rate</div>
                <div style={{fontSize: 12, color: 'var(--text-2)', fontStyle: 'italic', lineHeight: 1.6, marginBottom: 14, paddingLeft: 10, borderLeft: '2px solid var(--accent)'}}>{b.hyp}</div>
                <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8}}>Suggested fix</div>
                <ol style={{margin: 0, paddingLeft: 18, fontSize: 12, color: 'var(--text-1)', lineHeight: 1.7}}>
                  {b.fix.map((f, j) => <li key={j}>{f}</li>)}
                </ol>
                <button className="btn" style={{marginTop: 14, width: '100%', justifyContent: 'center'}}
                  onClick={() => {
                    try { sessionStorage.setItem('ar_decision_prefill', JSON.stringify({title: 'Fix bottleneck: ' + b.stage, description: b.hyp, severity: b.sev, fixes: b.fix})); } catch(e) {}
                    if (window.AR_NAVIGATE) window.AR_NAVIGATE('decisions');
                  }}>
                  <Icon name="plus" size={11} /> Create decision
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
      {genToast && (
        <div style={{position:'fixed',bottom:24,right:24,zIndex:2000,padding:'10px 18px',background:'rgba(139,92,246,0.9)',color:'#fff',borderRadius:8,fontSize:12,fontWeight:500,boxShadow:'0 4px 20px rgba(0,0,0,0.4)'}}>
          ✅ {genToast}
        </div>
      )}
    </div>
  );
};

window.InsightsScreen = InsightsScreen;
