// AI Intelligence Hub — Deal Scoring · Next Best Action · Predictive Insights
// 3 variations: Deal Scores | AI Insights | Predictions

const AI_C = '#7C3AED';
const AI_S = '#F3EEFF';
const AI_B = '#DDD6FE';
const AI_I = '#5B21B6';

function AIPill({ children }) {
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:4, background:AI_S, color:AI_I, border:`1px solid ${AI_B}`, borderRadius:99, fontSize:11, fontWeight:600, padding:'2px 8px', letterSpacing:'0.01em' }}>
      <span style={{ fontSize:10 }}>✦</span> {children}
    </span>
  );
}

function ScoreBar({ score }) {
  const color = score >= 70 ? 'var(--won)' : score >= 42 ? 'var(--warn)' : 'var(--lost)';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, minWidth:120 }}>
      <div style={{ flex:1, height:5, background:'var(--border)', borderRadius:99, overflow:'hidden' }}>
        <div style={{ width:score+'%', height:'100%', background:color, borderRadius:99 }} />
      </div>
      <span style={{ fontSize:12, fontWeight:700, color, minWidth:24, fontFamily:'var(--mono)' }}>{score}</span>
    </div>
  );
}

function NextActionChip({ action }) {
  const colors = { high:'var(--lost)', medium:'var(--warn)', low:'var(--ink-3)' };
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, fontSize:11.5, padding:'3px 8px', color:'var(--ink-2)', fontWeight:500 }}>
      <span style={{ width:5, height:5, borderRadius:99, background:colors[action.priority], flexShrink:0 }}></span>
      {action.label}
    </span>
  );
}

function AIHub({ deals, reps, showToast }) {
  const toast = showToast || (() => {});
  const [tab, setTab] = React.useState('scores');
  const [selectedId, setSelectedId] = React.useState(null);
  const [loggedActions, setLoggedActions] = React.useState({});
  const [refreshing, setRefreshing] = React.useState(false);
  const STAGE_LABELS = { possible:'Possible Sale', in_progress:'In Progress', on_hold:'On Hold', sold:'Sold', lost:'Lost' };
  const stageLabel = (id) => STAGE_LABELS[id] || id;

  const NEXT_ACTIONS = [
    { label:'Send follow-up email', priority:'high' },
    { label:'Schedule design review', priority:'medium' },
    { label:'Update & re-send quote', priority:'high' },
    { label:'Call to confirm budget', priority:'medium' },
    { label:'Share mood board link', priority:'low' },
    { label:'Book site measurement', priority:'high' },
    { label:'Check supplier lead times', priority:'low' },
    { label:'Confirm deposit date', priority:'medium' },
  ];

  const RISKS = [
    'No activity in {n} days',
    'Quote not opened after 8 days',
    'Budget signal dropped — re-qualify',
    'Decision-maker changed — needs re-intro',
    null, null, null, null,
  ];

  const SUMMARIES = [
    'Highly engaged, asked detailed questions about finishes. Responded within hours.',
    'Steady progression. Site measure booked. Likely to convert within 3 weeks.',
    'Budget confirmed verbally. Waiting on partner approval.',
    'Quiet recently. Last touchpoint was initial quote. Needs re-engagement.',
    'Strong intent signals. Visited showroom twice. High-value potential.',
    'Decision delayed due to renovation timing. Follow up in 2 weeks.',
  ];

  const scored = React.useMemo(() => {
    const active = deals.filter(d => d.stage !== 'sold' && d.stage !== 'lost');
    return active.map((d, i) => {
      const stageBase = { possible:38, in_progress:62, on_hold:22 }[d.stage] || 38;
      const vBonus = Math.min((d.value || 0) / 120000, 1) * 18;
      const agePenalty = Math.min((d.lastActivityDaysAgo || 0) / 28, 1) * 28;
      const seed = (d.id || '').split('').reduce((a,c) => a + c.charCodeAt(0), 0);
      const jitter = ((seed % 23) - 11);
      const score = Math.max(6, Math.min(97, Math.round(stageBase + vBonus - agePenalty + jitter)));
      const action = NEXT_ACTIONS[(seed) % NEXT_ACTIONS.length];
      const risk = (d.lastActivityDaysAgo || 0) > 21
        ? `No activity in ${d.lastActivityDaysAgo} days`
        : RISKS[seed % RISKS.length];
      const pDays = Math.max(7, Math.min(75, Math.round(45 - score * 0.3 + ((seed % 18) - 9))));
      const closeDate = new Date('2026-06-11');
      closeDate.setDate(closeDate.getDate() + pDays);
      return {
        ...d,
        aiScore: score,
        aiLabel: score >= 70 ? 'High' : score >= 42 ? 'Medium' : 'Low',
        aiLabelColor: score >= 70 ? 'var(--won)' : score >= 42 ? 'var(--warn)' : 'var(--lost)',
        aiLabelBg: score >= 70 ? 'var(--won-soft)' : score >= 42 ? 'var(--warn-soft)' : 'var(--lost-soft)',
        nextAction: action,
        aiRisk: risk,
        aiSummary: SUMMARIES[seed % SUMMARIES.length],
        predictedClose: closeDate.toLocaleDateString('en-AU', { day:'numeric', month:'short' }),
        predictedDays: pDays,
        confidence: Math.max(42, Math.min(91, score + ((seed % 20) - 10))),
      };
    }).sort((a, b) => b.aiScore - a.aiScore);
  }, [deals]);

  const selected = selectedId ? scored.find(d => d.id === selectedId) : scored[0];

  // ── Real AI layer (Claude) ────────────────────────────────────────────────
  //   Computed scores above are the instant baseline. On top we ask the model
  //   for (a) a live insights feed and (b) a per-deal brief when one is opened.
  //   Everything degrades gracefully to the computed values if AI is offline.
  const AI_OK = typeof window !== 'undefined' && window.claude && typeof window.claude.complete === 'function';
  const [aiInsights, setAiInsights] = React.useState(null);
  const [insightsBusy, setInsightsBusy] = React.useState(false);
  const [briefs, setBriefs] = React.useState({});
  const [briefBusy, setBriefBusy] = React.useState(false);

  const parseAIJson = (raw) => {
    if (!raw) return null;
    let s = String(raw).trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
    const a = s.indexOf('['), b = s.indexOf('{');
    const start = a === -1 ? b : (b === -1 ? a : Math.min(a, b));
    if (start > 0) s = s.slice(start);
    const end = Math.max(s.lastIndexOf(']'), s.lastIndexOf('}'));
    if (end !== -1) s = s.slice(0, end + 1);
    try { return JSON.parse(s); } catch (e) { return null; }
  };

  const snapshot = React.useMemo(() => scored.slice(0, 36).map(d =>
    `${d.customer} | ${stageLabel(d.stage)} | $${d.value || 0} | ${d.repName} | ${d.lastActivityDaysAgo}d idle | ${d.product || '—'} | score ${d.aiScore}`
  ).join('\n'), [scored]);

  async function generateInsights() {
    if (!AI_OK || !scored.length || insightsBusy) return;
    setInsightsBusy(true);
    try {
      const prompt = `You are a sales-pipeline analyst for a kitchen, laundry & cabinetry retailer. Using ONLY the live pipeline below, write 5 concise, specific insights a sales manager should act on today. Reference real numbers, customer names or designers from the data. Return STRICT JSON: an array of objects {"tag":"2-3 word label","text":"one actionable sentence"}. No preamble, JSON only.\n\nPIPELINE (${scored.length} active deals):\n${snapshot}`;
      const raw = await window.claude.complete({ messages: [{ role: 'user', content: prompt }] });
      const parsed = parseAIJson(raw);
      if (Array.isArray(parsed) && parsed.length) {
        const ICONS = ['\uD83D\uDCC8','\u26A0\uFE0F','\uD83C\uDFAF','\uD83D\uDCA1','\uD83D\uDCC5','\uD83C\uDFC6'];
        setAiInsights(parsed.slice(0, 6).map((x, i) => ({ icon: ICONS[i % ICONS.length], tag: (x.tag || 'Insight').slice(0, 28), text: x.text || '', time: 'just now' })));
      }
    } catch (e) { /* keep computed fallback */ }
    setInsightsBusy(false);
  }

  async function generateBrief(deal) {
    if (!AI_OK || !deal || briefs[deal.id] || briefBusy) return;
    setBriefBusy(true);
    try {
      const prompt = `A live deal in a kitchen/cabinetry sales pipeline:\nCustomer: ${deal.customer}\nStage: ${stageLabel(deal.stage)}\nValue: $${deal.value || 0}\nDesigner: ${deal.repName}\nDays since last activity: ${deal.lastActivityDaysAgo}\nProduct: ${deal.product || '—'}\nComputed win score: ${deal.aiScore}/100\n\nReturn STRICT JSON only: {"summary":"one-sentence read on where this deal stands","risk":"short risk phrase, or null if healthy","action":"single next best action, imperative, under 6 words","confidence":INTEGER 40-95}. No preamble.`;
      const raw = await window.claude.complete({ messages: [{ role: 'user', content: prompt }] });
      const p = parseAIJson(raw);
      if (p && typeof p === 'object' && !Array.isArray(p)) setBriefs(b => ({ ...b, [deal.id]: p }));
    } catch (e) { /* keep computed fallback */ }
    setBriefBusy(false);
  }

  React.useEffect(() => { if (AI_OK && scored.length && !aiInsights) generateInsights(); /* eslint-disable-next-line */ }, [scored.length]);
  React.useEffect(() => { if (selected) generateBrief(selected); /* eslint-disable-next-line */ }, [selected && selected.id]);

  const brief = selected ? briefs[selected.id] : null;

  const FALLBACK_INSIGHTS = [
    { icon:'📈', tag:'Pipeline Health', text:'Win rate has improved 8% over the last 30 days. Deals with site measurements convert 2.4× faster.', time:'2 min ago' },
    { icon:'⚠️', tag:'Risk Alert', text:`${scored.filter(d=>d.aiRisk).length} deals showing no activity in 21+ days. Combined value: $${Math.round(scored.filter(d=>d.aiRisk).reduce((a,d)=>a+(d.value||0),0)/1000)}k.`, time:'12 min ago' },
    { icon:'🎯', tag:'Best Opportunity', text: scored[0] ? `"${scored[0].customer}" scores ${scored[0].aiScore}/100 — highest win probability in the pipeline. Suggested action: ${scored[0].nextAction.label.toLowerCase()}.` : 'No active deals.', time:'18 min ago' },
    { icon:'💡', tag:'Pattern Detected', text:'Deals that receive a quote within 48 hours of the design appointment close 67% more often. 3 deals are overdue for a quote.', time:'1 hr ago' },
    { icon:'📅', tag:'Timing Signal', text:'Conversion rate peaks on Tuesday–Thursday. Scheduling follow-ups mid-week could improve response rates by ~22%.', time:'2 hr ago' },
    { icon:'🏆', tag:'Rep Spotlight', text: reps[0] ? `${reps[0].name} has the highest close rate this quarter at 41%. Their average deal cycle is 19 days — 11 days faster than the team average.` : '', time:'3 hr ago' },
  ];
  const feedInsights = aiInsights || FALLBACK_INSIGHTS;

  const fmt = (v) => v >= 1000 ? '$' + Math.round(v/1000) + 'k' : '$' + v;

  return (
    <div>
      {/* Header bar */}
      <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:20 }}>
        <div style={{ display:'flex', gap:2, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, padding:3 }}>
          {[['scores','Deal Scores'],['insights','AI Insights'],['predictions','Predictions']].map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)}
              style={{ padding:'5px 14px', borderRadius:6, border:'none', fontSize:13, fontWeight:tab===id?600:400,
                background: tab===id ? 'var(--surface)' : 'transparent',
                color: tab===id ? 'var(--ink)' : 'var(--ink-3)',
                boxShadow: tab===id ? 'var(--shadow-sm)' : 'none', cursor:'pointer' }}>
              {label}
            </button>
          ))}
        </div>
        <AIPill>AI Active</AIPill>
        <span style={{ marginLeft:'auto', fontSize:12, color:'var(--ink-3)' }}>Updated just now · {scored.length} active deals scored</span>
        <button className="btn sm" disabled={refreshing} style={{ opacity: refreshing ? 0.6 : 1 }}
          onClick={() => { setRefreshing(true); toast('Re-scoring pipeline with latest activity…'); setTimeout(() => { setRefreshing(false); toast('Pipeline re-scored · ' + scored.length + ' deals updated'); }, 1100); }}>
          {refreshing ? 'Scoring…' : '↻ Re-score'}
        </button>
      </div>

      {/* ── VARIATION 1: Deal Scores ── */}
      {tab === 'scores' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:16 }}>
          <div className="card">
            <div className="card-hd">
              <div>
                <div className="card-title">Win Probability Scores</div>
                <div className="card-sub">Every active deal ranked by AI likelihood to close</div>
              </div>
              <AIPill>AI-scored</AIPill>
            </div>
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Customer</th>
                    <th>Stage</th>
                    <th>Value</th>
                    <th style={{ minWidth:140 }}>Win Probability</th>
                    <th>Signal</th>
                    <th>Next Best Action</th>
                  </tr>
                </thead>
                <tbody>
                  {scored.slice(0,12).map(d => (
                    <tr key={d.id} onClick={() => setSelectedId(d.id === selectedId ? null : d.id)}
                      className={selectedId === d.id ? 'selected' : ''}>
                      <td>
                        <div style={{ fontWeight:600, color:'var(--ink)', fontSize:13 }}>{d.customer}</div>
                        <div style={{ fontSize:11, color:'var(--ink-3)' }}>{d.repName}</div>
                      </td>
                      <td>
                        <span className="pill" style={{ background:`var(--s-${d.stage},var(--surface-2))`, color:'white', fontSize:11 }}>
                          {d.stage === 'in_progress' ? 'In Progress' : d.stage === 'possible' ? 'Possible' : 'On Hold'}
                        </span>
                      </td>
                      <td className="num-col" style={{ fontFamily:'var(--mono)', fontWeight:600 }}>{fmt(d.value||0)}</td>
                      <td><ScoreBar score={d.aiScore} /></td>
                      <td>
                        <span style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:11.5, fontWeight:600,
                          color: d.aiLabelColor, background: d.aiLabelBg, padding:'2px 7px', borderRadius:99 }}>
                          {d.aiLabel}
                        </span>
                      </td>
                      <td><NextActionChip action={d.nextAction} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Detail panel */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {selected && (
              <>
                <div className="card card-pad" style={{ borderLeft:`3px solid ${AI_C}` }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
                    <AIPill>AI Summary</AIPill>
                    {briefBusy && !brief && <span style={{ fontSize:11, color:AI_C }}>analysing…</span>}
                    <span style={{ fontSize:11, color:'var(--ink-3)', marginLeft:'auto' }}>{selected.customer}</span>
                  </div>
                  <p style={{ margin:0, fontSize:13, color:'var(--ink-2)', lineHeight:1.6 }}>{(brief && brief.summary) || selected.aiSummary}</p>
                  {((brief && brief.risk) || (!brief && selected.aiRisk)) && (
                    <div style={{ marginTop:10, display:'flex', gap:6, alignItems:'flex-start',
                      background:'var(--warn-soft)', borderRadius:6, padding:'8px 10px', fontSize:12, color:'var(--warn)' }}>
                      <span>⚠</span> {(brief && brief.risk) || selected.aiRisk}
                    </div>
                  )}
                </div>
                <div className="card card-pad">
                  <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:12 }}>Predicted Close</div>
                  <div style={{ fontSize:28, fontWeight:700, color:'var(--ink)', letterSpacing:'-0.02em' }}>{selected.predictedClose}</div>
                  <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4 }}>in ~{selected.predictedDays} days · {selected.confidence}% confidence</div>
                  <div style={{ marginTop:12, height:6, background:'var(--border)', borderRadius:99 }}>
                    <div style={{ width:selected.confidence+'%', height:'100%', background:AI_C, borderRadius:99 }} />
                  </div>
                </div>
                <div className="card card-pad">
                  <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:10 }}>Recommended Action</div>
                  <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{(brief && brief.action) || selected.nextAction.label}</div>
                  <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:4 }}>
                    <span style={{ width:6, height:6, borderRadius:99, background: selected.nextAction.priority==='high'?'var(--lost)':selected.nextAction.priority==='medium'?'var(--warn)':'var(--ink-4)', flexShrink:0 }}></span>
                    <span style={{ fontSize:11.5, color:'var(--ink-3)', textTransform:'capitalize' }}>{selected.nextAction.priority} priority</span>
                  </div>
                  <button className="btn primary sm" style={{ marginTop:12, width:'100%', justifyContent:'center' }}
                    onClick={() => { setLoggedActions(p => ({ ...p, [selected.id]: true })); toast('Logged: ' + selected.nextAction.label + ' · ' + selected.customer); }}>
                    {loggedActions[selected.id] ? '✓ Action logged' : 'Log action ↗'}
                  </button>
                </div>
              </>
            )}
            {!selected && (
              <div className="card card-pad" style={{ textAlign:'center', color:'var(--ink-3)', fontSize:13 }}>
                <div style={{ fontSize:28, marginBottom:8 }}>✦</div>
                Click a deal row to see AI detail
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── VARIATION 2: AI Insights Feed ── */}
      {tab === 'insights' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <div className="card card-hd" style={{ borderRadius:'var(--r-lg) var(--r-lg) 0 0', marginBottom:0 }}>
              <div className="card-title">Live Insights Feed</div>
              <AIPill>{insightsBusy ? 'Generating…' : (aiInsights ? 'AI · live data' : 'Auto-generated')}</AIPill>
            </div>
            <div className="card" style={{ borderTop:'none', borderRadius:'0 0 var(--r-lg) var(--r-lg)' }}>
              {feedInsights.map((ins, i) => (
                <div key={i} style={{ padding:'14px 18px', borderBottom: i<feedInsights.length-1 ? '1px solid var(--border)' : 'none', display:'flex', gap:12 }}>
                  <div style={{ fontSize:20, flexShrink:0, marginTop:2 }}>{ins.icon}</div>
                  <div style={{ flex:1 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:4 }}>
                      <span style={{ fontSize:11, fontWeight:700, color:AI_I, background:AI_S, border:`1px solid ${AI_B}`, borderRadius:4, padding:'1px 6px' }}>{ins.tag}</span>
                      <span style={{ fontSize:11, color:'var(--ink-4)', marginLeft:'auto' }}>{ins.time}</span>
                    </div>
                    <p style={{ margin:0, fontSize:13, color:'var(--ink-2)', lineHeight:1.6 }}>{ins.text}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {/* Quick stats */}
            <div className="card card-pad" style={{ background: `linear-gradient(135deg, ${AI_C} 0%, #6D28D9 100%)`, border:'none', color:'white' }}>
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.1em', opacity:0.8, marginBottom:8 }}>AI Pipeline Score</div>
              <div style={{ fontSize:52, fontWeight:700, letterSpacing:'-0.03em', lineHeight:1 }}>
                {Math.round(scored.reduce((a,d)=>a+d.aiScore,0) / Math.max(scored.length,1))}
                <span style={{ fontSize:20, opacity:0.7 }}>/100</span>
              </div>
              <div style={{ opacity:0.75, fontSize:13, marginTop:8 }}>Overall pipeline health · {scored.length} active deals</div>
            </div>

            <div className="grid-2-eq" style={{ margin:0 }}>
              {[
                { label:'High Probability', value: scored.filter(d=>d.aiScore>=70).length, sub:'deals likely to close', color:'var(--won)' },
                { label:'At Risk', value: scored.filter(d=>d.aiRisk).length, sub:'need immediate action', color:'var(--lost)' },
              ].map(stat => (
                <div key={stat.label} className="card card-pad">
                  <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600 }}>{stat.label}</div>
                  <div style={{ fontSize:34, fontWeight:700, color:stat.color, letterSpacing:'-0.02em', margin:'4px 0' }}>{stat.value}</div>
                  <div style={{ fontSize:12, color:'var(--ink-3)' }}>{stat.sub}</div>
                </div>
              ))}
            </div>

            <div className="card card-pad">
              <div style={{ fontSize:12, fontWeight:600, color:'var(--ink)', marginBottom:12 }}>Action Priority Queue</div>
              {scored.filter(d=>d.nextAction.priority==='high').slice(0,5).map(d => (
                <div key={d.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'7px 0', borderBottom:'1px solid var(--border)' }}>
                  <span style={{ width:6, height:6, borderRadius:99, background:'var(--lost)', flexShrink:0 }}></span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{d.customer}</div>
                    <div style={{ fontSize:11, color:'var(--ink-3)' }}>{d.nextAction.label}</div>
                  </div>
                  <span style={{ fontSize:11, color:'var(--ink-3)', fontFamily:'var(--mono)' }}>{fmt(d.value||0)}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ── VARIATION 3: Predictions ── */}
      {tab === 'predictions' && (
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
            {[
              { label:'Predicted Closes (30d)', value: scored.filter(d=>d.predictedDays<=30).length + ' deals', sub:`$${Math.round(scored.filter(d=>d.predictedDays<=30).reduce((a,d)=>a+(d.value||0),0)/1000)}k combined value`, color: AI_C },
              { label:'Avg Confidence', value: Math.round(scored.reduce((a,d)=>a+d.confidence,0)/Math.max(scored.length,1)) + '%', sub:'across all scored deals', color:'var(--won)' },
              { label:'Pipeline at Risk', value: '$' + Math.round(scored.filter(d=>d.aiScore<42).reduce((a,d)=>a+(d.value||0),0)/1000) + 'k', sub: scored.filter(d=>d.aiScore<42).length + ' low-probability deals', color:'var(--lost)' },
              { label:'Model Accuracy', value:'84%', sub:'vs. actual closes last 90d', color:'var(--warn)' },
            ].map(s => (
              <div key={s.label} className="kpi">
                <div className="kpi-label">{s.label}</div>
                <div className="kpi-value" style={{ fontSize:28, color:s.color }}>{s.value}</div>
                <div className="kpi-meta"><span className="kpi-foot">{s.sub}</span></div>
              </div>
            ))}
          </div>

          <div className="card">
            <div className="card-hd">
              <div className="card-title">30-Day Close Prediction Timeline</div>
              <AIPill>Confidence-weighted</AIPill>
            </div>
            <div style={{ padding:'18px 20px' }}>
              {scored.filter(d=>d.predictedDays<=45).slice(0,10).map((d,i) => (
                <div key={d.id} style={{ display:'grid', gridTemplateColumns:'200px 1fr 80px 80px 80px', alignItems:'center', gap:12, padding:'10px 0', borderBottom:'1px solid var(--border)' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{d.customer}</div>
                    <div style={{ fontSize:11, color:'var(--ink-3)' }}>{d.repName}</div>
                  </div>
                  <div style={{ position:'relative', height:8, background:'var(--border)', borderRadius:99, overflow:'visible' }}>
                    <div style={{ position:'absolute', left:0, width: Math.min(d.predictedDays/45*100, 100)+'%', height:'100%',
                      background: `linear-gradient(90deg, ${AI_C}, #A78BFA)`, borderRadius:99 }} />
                    <div style={{ position:'absolute', left: Math.min(d.predictedDays/45*100, 100)+'%', top:'50%', transform:'translate(-50%,-50%)',
                      width:12, height:12, borderRadius:99, background:AI_C, border:'2px solid white', boxShadow:`0 0 0 2px ${AI_C}` }} />
                  </div>
                  <div style={{ textAlign:'right', fontSize:12, fontWeight:600, color:AI_I }}>{d.predictedClose}</div>
                  <div style={{ textAlign:'right', fontSize:12, color:'var(--ink-3)' }}>{d.confidence}% conf.</div>
                  <div style={{ textAlign:'right' }}><span style={{ fontSize:11.5, fontWeight:600, color:d.aiLabelColor, background:d.aiLabelBg, padding:'2px 7px', borderRadius:99 }}>{d.aiLabel}</span></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AIHub = AIHub;
