function DashboardScreen() {
  const { state } = useStore();
  const { catalog, currency } = state;
  const tr = (key) => typeof t !== 'undefined' ? t(key) : key;

  const historique = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem('pos_historique') || '[]'); }
    catch(e) { return []; }
  }, []);

  async function analyserIA() {
   const btn = document.getElementById('ia-btn');
   const result = document.getElementById('ia-result');
   if (!btn || !result) return;
   btn.textContent = 'Analyse en cours...';
   btn.disabled = true;
   result.textContent = 'Analyse de vos donnees...';
   try {
     const historique = JSON.parse(localStorage.getItem('pos_historique') || '[]');
     const clients    = JSON.parse(localStorage.getItem('pos_clients') || '[]');
     const catalog    = JSON.parse(localStorage.getItem('pos_catalog') || '[]');
     const shop       = JSON.parse(localStorage.getItem('pos_shop') || '{}');
     const today      = new Date().toLocaleDateString('fr-FR');
     const ventesAujourdhui = historique.filter(function(v){ return v.date === today && !v.annulee; });
     const totalAujourdhui  = ventesAujourdhui.reduce(function(s,v){ return s+(v.total||0); }, 0);
     const topProduits = {};
     historique.filter(function(v){ return !v.annulee; }).slice(0,50).forEach(function(v){ (v.cart||[]).forEach(function(p){ topProduits[p.name] = (topProduits[p.name]||0) + p.qty; }); });
     const top3 = Object.entries(topProduits).sort(function(a,b){ return b[1]-a[1]; }).slice(0,3).map(function(e){ return e[0]+' ('+e[1]+' vendus)'; }).join(', ');
     const stockBas = catalog.filter(function(p){ return p.stock !== undefined && p.stock < 5; }).map(function(p){ return p.name; }).slice(0,3).join(', ');
     const clientsInactifs = clients.filter(function(c){ return c.nbVisites > 0; }).length;
     const prompt = "Tu es un conseiller expert pour les boutiques en Afrique. Analyse ces donnees et donne 4-5 conseils concrets en francais. Boutique: "+(shop.name||'')+". Ventes aujourd'hui: "+totalAujourdhui+" "+(shop.currency ? shop.currency.symbol : 'CFA')+" ("+ventesAujourdhui.length+" transactions). Top produits: "+(top3||'aucun')+". Stock bas: "+(stockBas||'aucun')+". Clients: "+clients.length+". Sois direct et pratique avec des emojis.";
     const res = await fetch('https://api.anthropic.com/v1/messages', {
       method: 'POST',
       headers: { 'Content-Type': 'application/json' },
       body: JSON.stringify({ model: 'claude-sonnet-4-20250514', max_tokens: 1000, messages: [{ role: 'user', content: prompt }] })
     });
     const data = await res.json();
     const texte = data.content && data.content[0] ? data.content[0].text : 'Erreur analyse';
     result.innerHTML = texte.replace(/\n/g, '<br>');
   } catch(e) {
     result.textContent = 'Erreur: ' + e.message;
   }
   btn.textContent = 'Analyser ma boutique';
   btn.disabled = false;
 }

  const todayStr   = new Date().toLocaleDateString('fr-FR');
  const ventesJour = historique.filter(v => v.date === todayStr && !v.annulee);
  const totalCA    = ventesJour.reduce((s,v) => s + (v.total||0), 0);
  const totalTrans = ventesJour.length;
  const panier     = totalTrans > 0 ? totalCA / totalTrans : 0;

  // Stats 7 jours
  const days7 = Array.from({length:7}, (_,i) => {
    const d = new Date(); d.setDate(d.getDate() - (6-i));
    return d.toLocaleDateString('fr-FR');
  });

  const dayLabels = [
    tr('dim')||'dim.', tr('lun')||'lun.', tr('mar')||'mar.',
    tr('mer')||'mer.', tr('jeu')||'jeu.', tr('ven')||'ven.', tr('sam')||'sam.',
  ];

  const ventes7 = days7.map(d => ({
    date: d,
    label: dayLabels[new Date(d.split('/').reverse().join('-')).getDay()],
    total: historique.filter(v => v.date===d && !v.annulee).reduce((s,v)=>s+(v.total||0),0),
    nb:    historique.filter(v => v.date===d && !v.annulee).length,
  }));

  const maxCA = Math.max(...ventes7.map(d=>d.total), 1);

  // Top produits
  const prodStats = {};
  historique.filter(v=>!v.annulee).forEach(v => {
    (v.cart||[]).forEach(item => {
      if (!prodStats[item.name]) prodStats[item.name] = { name:item.name, qty:0, ca:0 };
      prodStats[item.name].qty += item.qty;
      prodStats[item.name].ca  += item.qty * item.price;
    });
  });
  const topProd = Object.values(prodStats).sort((a,b)=>b.ca-a.ca).slice(0,5);

  // Caissiers
  const caissStats = {};
  ventesJour.forEach(v => {
    if (!caissStats[v.caissier]) caissStats[v.caissier] = { name:v.caissier, ventes:0, ca:0 };
    caissStats[v.caissier].ventes++;
    caissStats[v.caissier].ca += v.total||0;
  });
  const topCaiss = Object.values(caissStats).sort((a,b)=>b.ca-a.ca).slice(0,5);
  const maxCaissCA = Math.max(...topCaiss.map(c=>c.ca), 1);

  // Modes paiement
  const payStats = {};
  ventesJour.forEach(v => {
    const pm = v.payMode || 'cash';
    if (!payStats[pm]) payStats[pm] = { label:pm, nb:0, ca:0 };
    payStats[pm].nb++;
    payStats[pm].ca += v.total||0;
  });
  const payList = Object.values(payStats).sort((a,b)=>b.nb-a.nb);
  const maxPayNb = Math.max(...payList.map(p=>p.nb), 1);

  // Alertes stock
  const alertesStock = catalog.filter(p => p.stock <= (p.seuil||10));

  const [sending, setSending] = React.useState(false);
  const [sent, setSent]       = React.useState(false);

  async function envoyerRapport() {
    const user  = JSON.parse(localStorage.getItem('pos_auth_user') || '{}');
    const email = user.email;
    if (!email) { alert('Email non trouvé'); return; }

    setSending(true);

    const prodStats2 = {};
    historique.filter(v=>!v.annulee&&v.date===todayStr).forEach(v => {
      (v.cart||[]).forEach(item => {
        if (!prodStats2[item.name]) prodStats2[item.name] = { name:item.name, qty:0, ca:0 };
        prodStats2[item.name].qty += item.qty;
        prodStats2[item.name].ca  += item.qty * item.price;
      });
    });

    const caissStats2 = {};
    ventesJour.forEach(v => {
      if (!caissStats2[v.caissier]) caissStats2[v.caissier] = { name:v.caissier, ventes:0, ca:0 };
      caissStats2[v.caissier].ventes++;
      caissStats2[v.caissier].ca += v.total||0;
    });

    const payload = {
      to:    email,
      shop:  state.shop,
      currency: currency.code,
      stats: {
        date:         new Date().toLocaleDateString('fr-FR'),
        ca:           totalCA.toLocaleString('fr-FR'),
        transactions: totalTrans,
        panier:       Math.round(panier).toLocaleString('fr-FR'),
        articles:     ventesJour.reduce((s,v)=>s+(v.articles||0),0),
        topProduits:  Object.values(prodStats2).sort((a,b)=>b.ca-a.ca).slice(0,5).map(p=>({...p,ca:p.ca.toLocaleString('fr-FR')})),
        alertes:      catalog.filter(p=>p.stock<=(p.seuil||10)),
        caissiers:    Object.values(caissStats2).sort((a,b)=>b.ca-a.ca).map(c=>({...c,ca:c.ca.toLocaleString('fr-FR')})),
      }
    };

    try {
      const res = await fetch('/api/send-report', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.success) { setSent(true); setTimeout(()=>setSent(false), 3000); }
      else alert('Erreur: ' + (data.error?.message || data.error));
    } catch(e) { alert('Erreur: ' + e.message); }
    setSending(false);
  }

  const kpis = [
    { label:tr('ca_aujourdhui_kpi')||"CA AUJOURD'HUI", val:fmtN(totalCA,currency), icon:'💰', color:'#2563eb' },
    { label:tr('transactions')||'TRANSACTIONS',         val:totalTrans,              icon:'🛒', color:'#16a34a' },
    { label:tr('panier_moyen')||'PANIER MOYEN',         val:fmtN(panier,currency),  icon:'🧺', color:'#f59e0b' },
    { label:tr('nb_produits')||'NB PRODUITS',           val:catalog.length,          icon:'📦', color:'#8b5cf6' },
  ];

  return (
    <div className="screen" style={{background:'#f0f4f8'}}>
      <div style={{flex:1, overflowY:'auto', padding:22}}>

        {/* Bouton rapport */}
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:4}}>
          <div style={{fontFamily:"'Playfair Display',serif",fontSize:26,color:'#1e293b',fontWeight:700}}>
            📊 {tr('dashboard_titre')||'Tableau de bord'}
          </div>
          <button onClick={envoyerRapport} disabled={sending}
            style={{background:'linear-gradient(135deg,#16a34a,#22c55e)',color:'#fff',border:'none',borderRadius:10,padding:'10px 20px',fontSize:13,fontWeight:700,cursor:'pointer',display:'flex',alignItems:'center',gap:8}}>
            {sending ? '⏳ Envoi...' : sent ? '✅ Envoyé !' : '📧 Envoyer rapport'}
          </button>
        </div>


        <div style={{fontSize:12,color:'#94a3b8',marginBottom:22}}>
          {new Date().toLocaleDateString(tr('locale')||'fr-FR', {weekday:'long',day:'numeric',month:'long',year:'numeric'})}
        </div>

        {/* KPIs */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:16,marginBottom:22}}>
          {kpis.map((k,i) => (
            <div key={i} style={{background:'#fff',borderRadius:14,padding:18,borderTop:'4px solid '+k.color,boxShadow:'0 1px 4px #0000000a'}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:10}}>
                <div style={{fontSize:11,color:'#94a3b8',fontWeight:700,textTransform:'uppercase',letterSpacing:.8}}>{k.label}</div>
                <span style={{fontSize:22}}>{k.icon}</span>
              </div>
              <div style={{fontFamily:"'Playfair Display',serif",fontSize:22,color:k.color,fontWeight:700}}>{k.val}</div>
            </div>
          ))}
        </div>

        {/* Graphique 7 jours */}
        <div className="card" style={{marginBottom:20}}>
          <div className="stitle">📈 {tr('ventes_7j')||'Ventes — 7 derniers jours'}</div>
          <div style={{display:'flex',alignItems:'flex-end',gap:10,height:120,padding:'10px 0'}}>
            {ventes7.map((d,i) => (
              <div key={i} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:4}}>
                <div style={{fontSize:9,color:'#94a3b8',fontFamily:"'DM Mono',monospace",fontWeight:700}}>
                  {d.total > 0 ? fmtN(d.total,currency) : ''}
                </div>
                <div style={{width:'100%',borderRadius:'4px 4px 0 0',background:d.date===todayStr?'#2563eb':'#bfdbfe',minHeight:4,height:Math.max(4,(d.total/maxCA)*80),transition:'height .3s'}}/>
                <div style={{fontSize:10,color:d.date===todayStr?'#2563eb':'#94a3b8',fontWeight:d.date===todayStr?700:400}}>{d.label}</div>
                {d.nb > 0 && <div style={{fontSize:9,color:'#94a3b8'}}>{d.nb}</div>}
              </div>
            ))}
          </div>
        </div>

        {/* Grille bas */}
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:16}}>

          {/* Top produits */}
          <div className="card">
            <div className="stitle">🏆 {tr('top_produits')||'Top produits'}</div>
            {topProd.length === 0 ? (
              <div style={{color:'#94a3b8',fontSize:13,textAlign:'center',padding:'20px 0'}}>{tr('aucune_vente_auj')||'Aucune vente'}</div>
            ) : topProd.map((p,i) => (
              <div key={i} style={{display:'flex',alignItems:'center',gap:10,marginBottom:10}}>
                <div style={{width:24,height:24,borderRadius:12,background:['#f59e0b','#94a3b8','#cd7c3b','#2563eb','#8b5cf6'][i]+'22',display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,fontWeight:700,color:['#f59e0b','#94a3b8','#cd7c3b','#2563eb','#8b5cf6'][i],flexShrink:0}}>{i+1}</div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:12,color:'#1e293b',fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{p.name}</div>
                  <div style={{fontSize:10,color:'#94a3b8'}}>{tr('qte_vendue')||'Qté vendue :'} {p.qty}</div>
                </div>
                <div style={{fontFamily:"'DM Mono',monospace",fontSize:12,color:'#2563eb',fontWeight:700,flexShrink:0}}>{fmtN(p.ca,currency)}</div>
              </div>
            ))}
          </div>

          {/* Performance caissiers */}
          <div className="card">
            <div className="stitle">👤 {tr('perf_caissiers')||'Performance caissiers'}</div>
            {topCaiss.length === 0 ? (
              <div style={{color:'#94a3b8',fontSize:13,textAlign:'center',padding:'20px 0'}}>{tr('aucune_vente_auj')||'Aucune vente'}</div>
            ) : topCaiss.map((c,i) => (
              <div key={i} style={{marginBottom:12}}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:4}}>
                  <div style={{display:'flex',alignItems:'center',gap:8}}>
                    <div style={{width:28,height:28,borderRadius:14,background:'#eff6ff',display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,fontWeight:700,color:'#2563eb'}}>{c.name.charAt(0)}</div>
                    <div style={{fontSize:12,color:'#1e293b',fontWeight:600}}>{c.name}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div style={{fontFamily:"'DM Mono',monospace",fontSize:12,color:'#2563eb',fontWeight:700}}>{fmtN(c.ca,currency)}</div>
                    <div style={{fontSize:10,color:'#94a3b8'}}>{c.ventes} {tr('vente_unite2')||'vente(s)'}</div>
                  </div>
                </div>
                <div style={{height:4,borderRadius:2,background:'#e2e8f0',overflow:'hidden'}}>
                  <div style={{height:'100%',borderRadius:2,background:'#2563eb',width:(c.ca/maxCaissCA*100)+'%'}}/>
                </div>
              </div>
            ))}
          </div>

          {/* Modes paiement */}
          <div className="card">
            <div className="stitle">💳 {tr('modes_paiement')||'Modes de paiement'}</div>
            {payList.length === 0 ? (
              <div style={{color:'#94a3b8',fontSize:13,textAlign:'center',padding:'20px 0'}}>{tr('aucune_vente_auj')||'Aucune vente'}</div>
            ) : payList.map((p,i) => (
              <div key={i} style={{marginBottom:12}}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:4}}>
                  <div style={{fontSize:12,color:'#1e293b',fontWeight:600,textTransform:'capitalize'}}>{p.label}</div>
                  <div style={{fontSize:12,color:'#64748b'}}>{p.nb} · {Math.round(p.nb/maxPayNb*100)}%</div>
                </div>
                <div style={{height:4,borderRadius:2,background:'#e2e8f0',overflow:'hidden'}}>
                  <div style={{height:'100%',borderRadius:2,background:'#16a34a',width:(p.nb/maxPayNb*100)+'%'}}/>
                </div>
              </div>
            ))}

            {/* Alertes stock */}
            {alertesStock.length > 0 && (
              <div style={{marginTop:16,paddingTop:16,borderTop:'1px solid #e2e8f0'}}>
                <div style={{fontSize:12,color:'#dc2626',fontWeight:700,marginBottom:8}}>⚠️ {tr('alertes_stock')||'Alertes stock'} ({alertesStock.length})</div>
                {alertesStock.slice(0,4).map((p,i) => (
                  <div key={i} style={{display:'flex',justifyContent:'space-between',fontSize:11,padding:'4px 0',borderBottom:'1px solid #f1f5f9'}}>
                    <span style={{color:'#64748b',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',flex:1}}>{p.name}</span>
                    <span style={{color:'#dc2626',fontWeight:700,fontFamily:"'DM Mono',monospace",marginLeft:8}}>{p.stock}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

     {/* Section IA */}
     <div style={{marginTop:20,marginBottom:20}}>
       <div style={{background:'linear-gradient(135deg,#1e3a8a,#2563eb)',borderRadius:16,padding:24,color:'#fff'}}>
         <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:16}}>
           <span style={{fontSize:28}}>🤖</span>
           <div>
             <div style={{fontFamily:"'Playfair Display',serif",fontSize:18,fontWeight:700}}>Assistant IA</div>
             <div style={{fontSize:12,opacity:.8}}>Analyse intelligente de votre boutique</div>
           </div>
         </div>
         <div id="ia-result" style={{background:'rgba(255,255,255,.1)',borderRadius:12,padding:16,fontSize:13,lineHeight:'1.8',minHeight:60,marginBottom:16}}>
           Cliquez sur Analyser pour obtenir des conseils personnalises pour votre boutique.
         </div>
         <button id="ia-btn" onClick={analyserIA} style={{background:'#fff',color:'#2563eb',border:'none',borderRadius:10,padding:'11px 24px',fontWeight:700,fontSize:14,cursor:'pointer'}}>
           Analyser ma boutique
         </button>
       </div>
     </div>
      </div>
    </div>
  );
}
