// screens/Dashboard.jsx — Executive analytics dashboard with KPIs, heatmap, AI insights, scenarios.

const HEATMAP_DATA = {
  rows: ['Casablanca','Rabat','Marrakech','Tanger','Fès','Agadir'],
  cols: ['Janv','Févr','Mars','Avril','Mai'],
  values: [
    [482, 510, 540, 612, 684],
    [248, 261, 290, 318, 342],
    [312, 295, 348, 392, 428],
    [184, 192, 178, 220, 248],
    [148, 162, 174, 168, 196],
    [ 92, 108,  88, 124, 132],
  ],
};

const SCENARIOS = {
  hist:   [0.92, 1.08, 1.24],
  optim:  [1.24, 1.42, 1.62, 1.82, 2.04, 2.30],
  real:   [1.24, 1.32, 1.40, 1.46, 1.50, 1.54],
  pess:   [1.24, 1.16, 1.08, 0.98, 0.88, 0.80],
};

const AI_INSIGHTS = [
  { tone:'success', icon:'trending-up', title:'Casablanca dépasse l\u2019objectif', body:'Le hub Casablanca a généré +24% vs la prévision. Capacité de stock à renforcer avant juin.' },
  { tone:'warning', icon:'alert-triangle', title:'Hausse du churn segment SMB', body:'Le segment TPE/PME montre un churn +1,2 pt sur 30j. Action onboarding recommandée.' },
  { tone:'primary', icon:'sparkles',    title:'Opportunité — Tanger',           body:'Demande artisanat +38% à Tanger. Réallocation de 15% du budget Ads suggérée.' },
];

const AI_RECOS = [
  { icon:'badge-percent', title:'Ajuster pricing Caftan',     body:'Réduire le prix de 4% pour capter la demande pré-Aïd.', cta:'Simuler l\u2019impact' },
  { icon:'megaphone',     title:'Boost campagne Marrakech',   body:'Allouer 12 000 MAD au canal Instagram pour le segment Décoration.', cta:'Voir les détails' },
  { icon:'package-search',title:'Réapprovisionner Tapis BO',  body:'Stock projeté en rupture sous 9 jours. Commande de 80 unités conseillée.', cta:'Créer l\u2019ordre' },
];

const CHANNELS = [
  { name:'Mai',   direct: 88, organique: 142, payant: 124 },
  { name:'Avril', direct: 76, organique: 124, payant: 108 },
  { name:'Mars',  direct: 64, organique: 108, payant: 92  },
];

function Dashboard() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1>Tableau de bord</h1>
          <div className="sub">Bienvenue Anas. Aperçu décisionnel des performances · 09 mai 2026.</div>
        </div>
        <div className="spacer"></div>
        <div style={{ display:'flex', gap:0, padding:3, background:'var(--app-surface-2)', border:'1px solid var(--app-border)', borderRadius:8 }}>
          <button className="btn btn-ghost" style={{ height:28, padding:'0 12px', borderRadius:6, font:'600 11px/1 var(--m-font-sans)' }}>Aujourd'hui</button>
          <button className="btn btn-ghost" style={{ height:28, padding:'0 12px', borderRadius:6, font:'600 11px/1 var(--m-font-sans)' }}>7 jours</button>
          <button style={{ height:28, padding:'0 12px', borderRadius:6, border:'none', background:'var(--app-surface)', boxShadow:'var(--m-shadow-sm)', font:'700 11px/1 var(--m-font-sans)', color:'var(--app-text)' }}>Mois en cours</button>
        </div>
        <button className="btn btn-ghost"><i data-lucide="download" style={{width:14,height:14}}></i> Rapport</button>
        <button className="btn btn-warm"><i data-lucide="plus" style={{width:14,height:14}}></i> Nouveau widget</button>
      </div>

      {/* Strategic AI Alert */}
      <StrategicAlert />

      {/* KPI grid with sparkbars */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:20 }}>
        <KpiCardPro label="Chiffre d'affaires (MRR)"   value="3,28 M" unit="MAD" delta="+12,4%" deltaPositive sub="vs M-1 (2,92 M)"  bars={[14,18,22,28,34,42,52]} color="#1379F0" />
        <KpiCardPro label="Nouveaux clients"           value="432"    unit="ce mois" delta="+8,2%" deltaPositive sub="vs M-1 (399)"  bars={[18,22,20,26,28,32,36]} color="#19C781" />
        <KpiCardPro label="Taux d'attrition"           value="3,8%"   unit="" delta="+1,1%" deltaPositive={false} sub="vs moy. 3 mois (2,7%)" bars={[8,10,9,12,15,16,18]} color="#F8285A" alert />
        <KpiCardPro label="Coût d'acquisition (CAC)"   value="845"    unit="MAD" delta="-2,5%" deltaPositive sub="vs M-1 (867)"      bars={[24,22,21,19,18,17,16]} color="#C2410C" />
      </div>

      {/* MRR chart + AI recos */}
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:20 }}>
        <Widget title="Croissance MRR vs Objectif (YTD)"
          action={<button className="btn btn-ghost btn-icon"><i data-lucide="more-horizontal" style={{width:14,height:14}}></i></button>}>
          <div style={{ display:'flex', alignItems:'baseline', gap:14, marginBottom:10 }}>
            <span style={{ font:'700 26px/1 var(--m-font-sans)', letterSpacing:'-.02em', color:'var(--app-text)' }}>3 276 800 MAD</span>
            <span className="pill" style={{ background:'rgba(25,199,129,.10)', color:'#19C781' }}>
              <i data-lucide="trending-up" style={{ width:11, height:11, strokeWidth:2.4 }}></i> +12,4% vs cible
            </span>
            <div style={{ flex:1 }}></div>
            <div style={{ display:'flex', gap:14, font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>
              <span><span style={{ display:'inline-block', width:10, height:2, background:'#1379F0', verticalAlign:'middle', marginRight:6 }}></span>MRR Réel</span>
              <span><span style={{ display:'inline-block', width:10, height:0, borderTop:'2px dashed var(--app-text-4)', verticalAlign:'middle', marginRight:6 }}></span>Objectif</span>
            </div>
          </div>
          <MrrProjectionChart />
        </Widget>

        <Widget title="Recommandations IA"
          action={<span className="pill" style={{ background:'linear-gradient(135deg, rgba(194,65,12,.12), rgba(217,119,6,.10))', color:'#C2410C', border:'1px solid rgba(194,65,12,.20)' }}><i data-lucide="sparkles" style={{ width:11, height:11 }}></i> 3 actions</span>}>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {AI_RECOS.map((r,i)=>(
              <div key={i} style={{ padding:14, borderRadius:9, background:'var(--app-surface-2)', border:'1px solid var(--app-border)' }}>
                <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
                  <div style={{ width:30, height:30, borderRadius:7, background:'var(--app-surface)', border:'1px solid var(--app-border)', color:'#C2410C', display:'grid', placeItems:'center', flexShrink:0 }}>
                    <i data-lucide={r.icon} style={{ width:14, height:14 }}></i>
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ font:'700 12px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{r.title}</div>
                    <div style={{ font:'500 11px/1.45 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:4 }}>{r.body}</div>
                    <button className="btn btn-warm" style={{ marginTop:10, height:26, padding:'0 10px', font:'700 11px/1 var(--m-font-sans)' }}>{r.cta} <i data-lucide="arrow-right" style={{ width:11, height:11 }}></i></button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Widget>
      </div>

      {/* Heatmap + Scenarios */}
      <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:20 }}>
        <Widget title="Performance par Ville"
          action={
            <div style={{ display:'flex', gap:8, alignItems:'center' }}>
              <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>Janv → Mai 2026</span>
              <button className="btn btn-ghost btn-icon"><i data-lucide="more-horizontal" style={{width:14,height:14}}></i></button>
            </div>
          }>
          <Heatmap data={HEATMAP_DATA} />
        </Widget>

        <Widget title="Scénarios prévisionnels"
          action={<button className="btn btn-ghost" style={{ height:30, padding:'0 12px', font:'600 12px/1 var(--m-font-sans)' }}><i data-lucide="settings-2" style={{width:12,height:12}}></i> Hypothèses</button>}>
          <div style={{ display:'flex', alignItems:'baseline', gap:10, marginBottom:6 }}>
            <span style={{ font:'700 22px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>2,12 M MAD</span>
            <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>scénario optimiste · Q3</span>
          </div>
          <ScenariosChart />
          <div style={{ display:'flex', gap:14, marginTop:10, font:'600 10px/1 var(--m-font-sans)' }}>
            <span style={{ color:'#19C781', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, borderRadius:99, background:'#19C781' }}></span>Optimiste</span>
            <span style={{ color:'var(--app-text-3)', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, borderRadius:99, background:'var(--app-text-4)' }}></span>Réaliste</span>
            <span style={{ color:'#F8285A', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, borderRadius:99, background:'#F8285A' }}></span>Pessimiste</span>
          </div>
        </Widget>
      </div>

      {/* AI Insights row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:20 }}>
        {AI_INSIGHTS.map((s,i)=>(
          <AIInsightCard key={i} {...s} />
        ))}
      </div>

      {/* Bottom: Donut + Top products + Channels */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1.2fr 1fr', gap:20 }}>
        <Widget title="Répartition CA">
          <Donut
            label="3,28 M"
            sub="MAD"
            segments={[
              { label:'Textile',      value: 38, color: '#C2410C' },
              { label:'Électronique', value: 24, color: '#1379F0' },
              { label:'Cosmétique',   value: 18, color: '#19C781' },
              { label:'Services',     value: 14, color: '#0F766E' },
              { label:'Autres',       value:  6, color: '#D97706' },
            ]}
          />
        </Widget>

        <Widget title="Top produits"
          action={<a href="#/produits" style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-primary)' }}>Tout voir</a>}>
          <table className="m-table">
            <thead><tr>
              <th>Produit</th><th>Performance</th><th style={{textAlign:'right'}}>CA</th>
            </tr></thead>
            <tbody>
              {TOP_PRODUCTS.map((p, i) => (
                <tr key={i}>
                  <td style={{ color:'var(--app-text)', fontWeight:700 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <div style={{ width:30, height:30, borderRadius:7, background: 'var(--app-warm-soft)', display:'grid', placeItems:'center', color:'#C2410C' }}>
                        <i data-lucide={['shirt','flask-conical','cloud','coffee','lamp'][i]} style={{ width:14, height:14 }}></i>
                      </div>
                      <div>
                        <div style={{ font:'700 12px/1.2 var(--m-font-sans)' }}>{p.name}</div>
                        <div style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:3 }}>{p.cat}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ width:120 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <div style={{ flex:1, height:5, background:'var(--app-border)', borderRadius:99 }}>
                        <div style={{ width: `${p.share*100}%`, height:5, borderRadius:99, background: i===0 ? '#C2410C' : i===1 ? '#D97706' : '#1379F0' }}></div>
                      </div>
                      <span style={{ font:'700 10px/1 var(--m-font-sans)', color:'var(--app-text-2)' }}>{Math.round(p.share*100)}%</span>
                    </div>
                  </td>
                  <td style={{ textAlign:'right', color:'var(--app-text)', fontWeight:700, fontSize:12 }}>{fmtMAD(p.revenue, {compact:true})}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Widget>

        <Widget title="Acquisition par canal"
          action={<span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>Mars → Mai</span>}>
          <ChannelBars />
          <div style={{ display:'flex', gap:14, marginTop:10, justifyContent:'center', font:'600 10px/1 var(--m-font-sans)' }}>
            <span style={{ color:'var(--app-text-2)', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, background:'#A5C8FF', borderRadius:2 }}></span>Direct</span>
            <span style={{ color:'var(--app-text-2)', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, background:'#1379F0', borderRadius:2 }}></span>Organique</span>
            <span style={{ color:'var(--app-text-2)', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:8, height:8, background:'#0F1729', borderRadius:2 }}></span>Payant</span>
          </div>
        </Widget>
      </div>

      {/* Notifications + Activity */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 2fr', gap:20 }}>
        <Widget title="Notifications"
          action={<a href="#" style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-primary)' }}>Voir tout</a>}>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {NOTIFICATIONS.slice(0,4).map((n,i)=>{
              const tones = {
                danger:['#F8285A','rgba(248,40,90,.10)'], warning:['#B57200','rgba(255,168,0,.14)'],
                primary:['#1379F0','rgba(19,121,240,.10)'], success:['#19C781','rgba(25,199,129,.10)'],
                warm:['#C2410C','rgba(194,65,12,.10)']
              };
              const [fg,bg] = tones[n.tone];
              return (
                <div key={i} style={{ display:'flex', gap:10, padding:10, borderRadius:8, background:'var(--app-surface-2)', border:'1px solid var(--app-border)' }}>
                  <div style={{ width:28, height:28, borderRadius:7, background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}>
                    <i data-lucide={n.icon} style={{ width:14, height:14, strokeWidth:1.8 }}></i>
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ font:'700 12px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{n.title}</div>
                    <div style={{ font:'500 11px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:2 }}>{n.body}</div>
                    <div style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-4)', marginTop:5 }}>{n.when}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Widget>

        <Widget title="Activité récente"
          action={
            <div style={{ display:'flex', gap:6 }}>
              <button className="btn btn-soft" style={{ height:28, padding:'0 10px', font:'600 11px/1 var(--m-font-sans)' }}>Tout</button>
              <button className="btn btn-ghost" style={{ height:28, padding:'0 10px', font:'600 11px/1 var(--m-font-sans)' }}>Appels</button>
              <button className="btn btn-ghost" style={{ height:28, padding:'0 10px', font:'600 11px/1 var(--m-font-sans)' }}>Emails</button>
              <button className="btn btn-ghost" style={{ height:28, padding:'0 10px', font:'600 11px/1 var(--m-font-sans)' }}>Réunions</button>
            </div>
          }>
          <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
            {INTERACTIONS.map((it, i) => (
              <div key={i} style={{ display:'flex', gap:14, padding:'12px 0', borderBottom: i<INTERACTIONS.length-1 ? '1px solid var(--app-border)' : 'none', alignItems:'center' }}>
                <div style={{ width:32, height:32, borderRadius:8, background:'var(--app-warm-soft)', color:'#C2410C', display:'grid', placeItems:'center' }}>
                  <i data-lucide={it.icon} style={{ width:14, height:14 }}></i>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <span style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{it.client}</span>
                    <span className="pill" style={{ background:'var(--app-surface-2)', color:'var(--app-text-2)', border:'1px solid var(--app-border)' }}>{it.kind}</span>
                  </div>
                  <div style={{ font:'500 11px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:3 }}>{it.note}</div>
                </div>
                <div style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-4)' }}>{it.when}</div>
              </div>
            ))}
          </div>
        </Widget>
      </div>
    </div>
  );
}

// — Strategic AI alert banner ————————————————————————————————————————
function StrategicAlert() {
  const [dismissed, setDismissed] = React.useState(false);
  if (dismissed) return null;
  return (
    <div style={{
      position:'relative', padding:'18px 22px 18px 26px',
      background:'linear-gradient(90deg, rgba(248,40,90,.06), rgba(248,40,90,0) 70%), var(--app-surface)',
      border:'1px solid var(--app-border)', borderLeft:'3px solid #F8285A',
      borderRadius:12, display:'flex', alignItems:'flex-start', gap:16,
    }}>
      <div style={{ width:40, height:40, borderRadius:10, background:'rgba(248,40,90,.10)', color:'#F8285A', display:'grid', placeItems:'center', flexShrink:0 }}>
        <i data-lucide="alert-triangle" style={{ width:20, height:20 }}></i>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:4 }}>
          <span className="pill" style={{ background:'rgba(248,40,90,.10)', color:'#F8285A', textTransform:'uppercase', letterSpacing:'.06em' }}>Alerte IA</span>
          <span style={{ font:'700 14px/1 var(--m-font-sans)', color:'var(--app-text)' }}>Baisse de marge — Segment Premium</span>
        </div>
        <div style={{ font:'500 12px/1.55 var(--m-font-sans)', color:'var(--app-text-2)', maxWidth:760 }}>
          La marge opérationnelle sur le segment Premium (Casablanca) a chuté de <b>4,2%</b> par rapport au M-1. Risque projeté de <b>-12% sur le Q3</b> si aucune action n'est prise. Recommandation IA : revoir le pricing du caftan haut de gamme et auditer les coûts logistiques de Tanger.
        </div>
        <div style={{ display:'flex', gap:8, marginTop:12 }}>
          <button className="btn" style={{ background:'#F8285A', color:'#fff', border:'1px solid #F8285A' }}><i data-lucide="zap" style={{width:13,height:13}}></i> Action requise</button>
          <button className="btn btn-ghost">Voir l'analyse détaillée</button>
        </div>
      </div>
      <button className="btn btn-ghost btn-icon" onClick={()=>setDismissed(true)} style={{ flexShrink:0 }}>
        <i data-lucide="x" style={{ width:14, height:14 }}></i>
      </button>
    </div>
  );
}

// — KPI card with mini bar trend ————————————————————————————————————————
function KpiCardPro({ label, value, unit, delta, deltaPositive=true, sub, bars, color, alert }) {
  const max = Math.max(...bars);
  return (
    <div className="card" style={{ padding:18, position:'relative', borderColor: alert ? '#F8285A' : 'var(--app-border)' }}>
      <div style={{ display:'flex', alignItems:'flex-start', marginBottom:8 }}>
        <div style={{ flex:1, font:'700 10px/1.3 var(--m-font-sans)', color:'var(--app-text-3)', textTransform:'uppercase', letterSpacing:'.07em' }}>{label}</div>
      </div>
      <div style={{ display:'flex', alignItems:'baseline', gap:6, marginBottom:10 }}>
        <span style={{ font:'700 28px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.025em' }}>{value}</span>
        {unit && <span style={{ font:'600 12px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{unit}</span>}
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:14 }}>
        <span className="pill" style={{
          background: deltaPositive ? 'rgba(25,199,129,.10)' : 'rgba(248,40,90,.10)',
          color: deltaPositive ? '#19C781' : '#F8285A',
        }}>
          <i data-lucide={deltaPositive?'trending-up':'trending-down'} style={{ width:11, height:11, strokeWidth:2.4 }}></i> {delta}
        </span>
        <span style={{ font:'500 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{sub}</span>
      </div>
      {/* sparkbars */}
      <div style={{ display:'flex', alignItems:'flex-end', gap:4, height:30 }}>
        {bars.map((b,i)=>(
          <div key={i} style={{
            flex:1,
            height: `${(b/max)*100}%`,
            background: color,
            opacity: 0.30 + (i/bars.length)*0.70,
            borderRadius:'3px 3px 0 0',
            minHeight:2,
          }}></div>
        ))}
      </div>
    </div>
  );
}

// — MRR projection chart with target line and projection band ————————————
function MrrProjectionChart() {
  const W = 720, H = 220, PAD_L = 36, PAD_R = 14, PAD_T = 14, PAD_B = 28;
  const months = ['Janv','Févr','Mars','Avril','Mai','Juin','Juil','Août','Sept','Oct','Nov','Déc'];
  const actualEnd = 8; // through Sept
  const actual    = [0.62, 0.78, 1.18, 1.04, 1.28, 1.42, 1.58, 1.74, 1.92];
  const target    = [0.70, 0.85, 1.00, 1.15, 1.30, 1.45, 1.60, 1.75, 1.90, 2.05, 2.20, 2.35];
  const projected = [1.92, 2.04, 2.14, 2.24];
  const yMax = 3.0;
  const innerW = W - PAD_L - PAD_R, innerH = H - PAD_T - PAD_B;
  const x = i => PAD_L + (i/(months.length-1))*innerW;
  const y = v => PAD_T + (1 - v/yMax) * innerH;

  const actualPath = actual.map((v,i)=> `${i?'L':'M'}${x(i)},${y(v)}`).join(' ');
  const targetPath = target.map((v,i)=> `${i?'L':'M'}${x(i)},${y(v)}`).join(' ');
  const projPath   = projected.map((v,i)=> `${i?'L':'M'}${x(actualEnd+i)},${y(v)}`).join(' ');
  const fillPath   = `${actualPath} L${x(actual.length-1)},${y(0)} L${x(0)},${y(0)} Z`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block' }}>
      <defs>
        <linearGradient id="mrrFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#1379F0" stopOpacity=".18" />
          <stop offset="100%" stopColor="#1379F0" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* gridlines */}
      {[0, 1, 2, 3].map(v=>(
        <g key={v}>
          <line x1={PAD_L} x2={W-PAD_R} y1={y(v)} y2={y(v)} stroke="var(--app-border)" strokeDasharray="2 4" />
          <text x={PAD_L-8} y={y(v)+3} textAnchor="end" fill="var(--app-text-4)" fontSize="10" fontFamily="var(--m-font-sans)">{v}M</text>
        </g>
      ))}
      {/* projection band */}
      <rect x={x(actualEnd)} y={PAD_T} width={W-PAD_R - x(actualEnd)} height={innerH} fill="rgba(19,121,240,.05)" />
      <line x1={x(actualEnd)} x2={x(actualEnd)} y1={PAD_T} y2={H-PAD_B} stroke="var(--app-text-4)" strokeDasharray="3 3" />
      <text x={x(actualEnd)+8} y={PAD_T+12} fill="var(--app-text-3)" fontSize="10" fontFamily="var(--m-font-sans)" fontWeight="600">Projection Q4</text>

      {/* target dashed */}
      <path d={targetPath} fill="none" stroke="var(--app-text-4)" strokeWidth="1.5" strokeDasharray="5 4" />

      {/* actual fill + line */}
      <path d={fillPath} fill="url(#mrrFill)" />
      <path d={actualPath} fill="none" stroke="#1379F0" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {/* dots */}
      {actual.map((v,i)=>(
        <circle key={i} cx={x(i)} cy={y(v)} r="3.5" fill="var(--app-surface)" stroke="#1379F0" strokeWidth="2" />
      ))}
      {/* projection extension */}
      <path d={projPath} fill="none" stroke="#1379F0" strokeOpacity=".55" strokeWidth="2" strokeDasharray="4 3" />

      {/* x labels */}
      {months.map((m,i)=>(
        i % 2 === 0 ? <text key={i} x={x(i)} y={H-10} textAnchor="middle" fill="var(--app-text-4)" fontSize="10" fontFamily="var(--m-font-sans)">{m}</text> : null
      ))}
    </svg>
  );
}

// — Scenarios chart (3 lines from cur point) ———————————————————————————
function ScenariosChart() {
  const W = 360, H = 160, PAD_L = 8, PAD_R = 8, PAD_T = 10, PAD_B = 22;
  const labels = ['Q1','Q2','Q3*','Q4','Q1\u201927','Q2\u201927','Q3\u201927'];
  const innerW = W-PAD_L-PAD_R, innerH = H-PAD_T-PAD_B;
  const yMax = 2.4;
  const x = i => PAD_L + (i/(labels.length-1))*innerW;
  const y = v => PAD_T + (1 - v/yMax)*innerH;
  const histX = 2;
  const hist = SCENARIOS.hist;
  const lineFor = (vals, startIdx=histX) => vals.map((v,i)=>`${i?'L':'M'}${x(startIdx+i)},${y(v)}`).join(' ');
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block' }}>
      {/* historical (black) */}
      <path d={hist.map((v,i)=>`${i?'L':'M'}${x(i)},${y(v)}`).join(' ')}
        fill="none" stroke="var(--app-text)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {/* split line */}
      <line x1={x(histX)} x2={x(histX)} y1={PAD_T} y2={H-PAD_B} stroke="var(--app-text-4)" strokeDasharray="3 3" />
      {/* scenarios */}
      <path d={lineFor(SCENARIOS.optim, histX)} fill="none" stroke="#19C781" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      <path d={lineFor(SCENARIOS.real, histX)}  fill="none" stroke="var(--app-text-4)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="5 4" />
      <path d={lineFor(SCENARIOS.pess, histX)}  fill="none" stroke="#F8285A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {/* x labels */}
      {labels.map((l,i)=>(
        <text key={i} x={x(i)} y={H-6} textAnchor="middle" fill={i===histX?'var(--app-text-2)':'var(--app-text-4)'} fontSize="9" fontFamily="var(--m-font-sans)" fontWeight={i===histX?700:500}>{l}</text>
      ))}
    </svg>
  );
}

// — Heatmap grid ————————————————————————————————————————————————————————
function Heatmap({ data }) {
  const flat = data.values.flat();
  const min = Math.min(...flat), max = Math.max(...flat);
  // green→amber→red palette but inverted (high=green, low=red) per screenshot
  const colorFor = (v) => {
    const t = (v - min) / (max - min); // 0..1
    if (t > 0.66) {
      const k = (t - 0.66) / 0.34;
      // mid-green to deep green
      return `rgba(25,199,129,${0.18 + k*0.55})`;
    }
    if (t > 0.33) {
      const k = (t - 0.33) / 0.33;
      // amber to mid green
      return k > 0.5 ? `rgba(25,199,129,${0.18 + (k-0.5)*0.4})` : `rgba(255,193,7,${0.20 + k*0.30})`;
    }
    // red to amber
    return `rgba(248,40,90,${0.34 - t*0.6})`;
  };
  const textFor = (v) => {
    const t = (v - min) / (max - min);
    if (t > 0.66) return '#0E6B45';
    if (t > 0.33) return 'var(--app-text)';
    return '#B0153B';
  };
  return (
    <div>
      <div style={{
        display:'grid',
        gridTemplateColumns: `120px repeat(${data.cols.length}, 1fr)`,
        gap:6,
        font:'600 11px/1 var(--m-font-sans)',
      }}>
        <div></div>
        {data.cols.map(c=>(
          <div key={c} style={{ textAlign:'center', color:'var(--app-text-3)', textTransform:'uppercase', letterSpacing:'.05em', fontSize:10 }}>{c}</div>
        ))}
        {data.rows.map((r, ri)=>(
          <React.Fragment key={r}>
            <div style={{ display:'flex', alignItems:'center', font:'700 12px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{r}</div>
            {data.values[ri].map((v, ci)=>(
              <div key={ci} style={{
                height:38, borderRadius:7,
                background: colorFor(v),
                color: textFor(v),
                display:'flex', alignItems:'center', justifyContent:'center',
                font:'700 12px/1 var(--m-font-sans)',
                border:'1px solid var(--app-border)',
                whiteSpace:'nowrap',
              }}>
                {`${v} K`}
              </div>
            ))}
          </React.Fragment>
        ))}
      </div>
      {/* Legend */}
      <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:14, font:'600 10px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>
        <span style={{ whiteSpace:'nowrap' }}>Basse perf.</span>
        <div style={{
          flex:1, height:6, borderRadius:99,
          background: 'linear-gradient(90deg, rgba(248,40,90,.45), rgba(255,193,7,.45) 50%, rgba(25,199,129,.65))',
        }}></div>
        <span style={{ whiteSpace:'nowrap' }}>Haute perf.</span>
      </div>
    </div>
  );
}

// — AI insight summary card —————————————————————————————————————————
function AIInsightCard({ tone, icon, title, body }) {
  const tones = {
    success: { bg:'rgba(25,199,129,.08)', fg:'#19C781', accent:'#19C781' },
    warning: { bg:'rgba(248,40,90,.08)',  fg:'#F8285A', accent:'#F8285A' },
    primary: { bg:'rgba(19,121,240,.08)', fg:'#1379F0', accent:'#1379F0' },
  }[tone];
  return (
    <div className="card" style={{ padding:18, borderLeft:`3px solid ${tones.accent}`, display:'flex', gap:14 }}>
      <div style={{ width:34, height:34, borderRadius:9, background:tones.bg, color:tones.fg, display:'grid', placeItems:'center', flexShrink:0 }}>
        <i data-lucide={icon} style={{ width:16, height:16 }}></i>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ font:'700 13px/1.3 var(--m-font-sans)', color:'var(--app-text)' }}>{title}</div>
        <div style={{ font:'500 12px/1.5 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:5 }}>{body}</div>
      </div>
    </div>
  );
}

// — Acquisition channels stacked bars ————————————————————————————————
function ChannelBars() {
  const max = Math.max(...CHANNELS.flatMap(c => [c.direct, c.organique, c.payant]));
  const colors = { direct:'#A5C8FF', organique:'#1379F0', payant:'#0F1729' };
  return (
    <div style={{ display:'flex', gap:18, height:160, alignItems:'flex-end', padding:'10px 6px 0' }}>
      {CHANNELS.map((c,ci)=>(
        <div key={ci} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8, height:'100%' }}>
          <div style={{ flex:1, display:'flex', alignItems:'flex-end', gap:5, width:'100%', justifyContent:'center' }}>
            {['direct','organique','payant'].map(k=>(
              <div key={k} style={{
                width:18, height: `${(c[k]/max)*100}%`,
                background: colors[k], borderRadius:'4px 4px 0 0', minHeight:6
              }}></div>
            ))}
          </div>
          <div style={{ font:'600 11px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{c.name}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Dashboard });
