function HistoriqueScreen() {
  const tr = (key) => typeof t !== "undefined" ? t(key) : key;
  const { state, notify } = useStore();
  const { currency, shop, printer } = state;
  const [historique, setHistorique] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('pos_historique') || '[]'); }
    catch(e) { return []; }
  });
  const [selected, setSelected]               = React.useState(null);
  const [showSuperviseur, setShowSuperviseur] = React.useState(false);
  const [ligneAnnuler, setLigneAnnuler]       = React.useState(null);
  const [ligneRemplacer, setLigneRemplacer]   = React.useState(null);
  const [showRemplacer, setShowRemplacer]     = React.useState(false);
  const [searchProd, setSearchProd]           = React.useState('');
  const [superviseurData, setSuperviseurData] = React.useState(null);

  const today         = new Date().toLocaleDateString('fr-FR');
  const ventesActives = historique.filter(v => !v.annulee);
  const totalJour     = historique.filter(v => v.date===today && !v.annulee).reduce((s,v)=>s+v.total,0);
  const ventesJour    = historique.filter(v => v.date===today && !v.annulee).length;

  function clearHistorique() {
    if (!window.confirm(tr('confirm_effacer')||"Effacer tout l'historique ?")) return;
    localStorage.removeItem('pos_historique');
    setHistorique([]); setSelected(null);
  }

  function saveHistorique(updated) {
    setHistorique(updated);
    localStorage.setItem('pos_historique', JSON.stringify(updated));
  }

  function annulerVente(vente, { superviseur, raison }) {
    const updated = historique.map(v => v.id===vente.id ? {
      ...v, annulee:true, annuleeParNom:superviseur.nom,
      annuleeRaison:raison,
      annuleeDate:new Date().toLocaleDateString('fr-FR'),
      annuleeHeure:new Date().toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit'}),
    } : v);
    saveHistorique(updated);
    setShowSuperviseur(false); setSelected(null); setLigneAnnuler(null);
    notify('✅ Vente annulée par ' + superviseur.nom);
  }

  function annulerLigne(vente, ligne, { superviseur, raison }) {
    const newCart  = vente.cart.filter(i => i.id !== ligne.id);
    const newTotal = newCart.reduce((s,i) => s+i.qty*i.price, 0);
    const updated  = historique.map(v => v.id===vente.id ? {
      ...v, cart:newCart, total:newTotal, articles:newCart.length,
      lignesAnnulees: [...(v.lignesAnnulees||[]), {
        ...ligne,
        annuleeParNom: superviseur.nom,
        annuleeRaison: raison,
        annuleeDate:   new Date().toLocaleDateString('fr-FR'),
        annuleeHeure:  new Date().toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit'}),
        remboursement: ligne.qty*ligne.price,
      }],
    } : v);
    saveHistorique(updated);
    setShowSuperviseur(false); setLigneAnnuler(null);
    setSelected(updated.find(v => v.id===vente.id));
    notify('✅ Ligne annulée — Remboursement : '+fmtN(ligne.qty*ligne.price,currency));
  }

  function remplacerLigne(vente, ligne, nouveauProd) {
    const newCart = vente.cart.map(i => i.id===ligne.id ? {
      ...i, cid:nouveauProd.id, barcode:nouveauProd.barcode,
      name:nouveauProd.name, price:nouveauProd.price, tva:nouveauProd.tva,
      remplace:true, ancienNom:ligne.name,
      remplaceParNom: superviseurData?.nom||'',
      remplaceDate: new Date().toLocaleDateString('fr-FR'),
    } : i);
    const newTotal = newCart.reduce((s,i) => s+i.qty*i.price, 0);
    const updated  = historique.map(v => v.id===vente.id ? {...v, cart:newCart, total:newTotal} : v);
    saveHistorique(updated);
    setSelected(updated.find(v => v.id===vente.id));
    setShowRemplacer(false); setLigneRemplacer(null); setSuperviseurData(null); setSearchProd('');
    notify('✅ Ligne remplacée par '+nouveauProd.name);
  }

  function reimprimer(v) {
    const html = buildTicketHTML({
      shop, cart:v.cart, currency, printer,
      cashier:{id:v.caissierId||'', name:v.caissier},
      payMode:v.payMode, cashGiven:v.cashGiven||0,
      ticketNum:v.id, now:new Date(v.timestamp||Date.now()), logoUrl:state.logoUrl,
    });
    const win = window.open('','_blank');
    win.document.write(html+'<scr'+'ipt>window.onload=function(){window.print();window.close();}<\/scr'+'ipt>');
    win.document.close();
  }

  const payLabel = p => p==='cash'?'Espèces':p==='card'?'Carte bancaire':p==='mobile'?'Mobile Money':'Chèque';

  return (
    <div className="screen" style={{background:'#f0f4f8'}}>

      {/* Modal superviseur */}
      {showSuperviseur && selected && (
        <SuperviseurModal
          onValide={data => {
            if (ligneRemplacer) {
              setSuperviseurData(data.superviseur);
              setShowSuperviseur(false);
              setShowRemplacer(true);
            } else if (ligneAnnuler) {
              annulerLigne(selected, ligneAnnuler, data);
            } else {
              annulerVente(selected, data);
            }
          }}
          onAnnule={() => { setShowSuperviseur(false); setLigneAnnuler(null); setLigneRemplacer(null); }}
        />
      )}

      {/* Modal remplacement produit */}
      {showRemplacer && selected && ligneRemplacer && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.75)',zIndex:9000,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
          <div style={{background:'#fff',borderRadius:20,width:'100%',maxWidth:500,maxHeight:'80vh',display:'flex',flexDirection:'column',boxShadow:'0 25px 60px rgba(0,0,0,0.4)'}}>
            <div style={{background:'linear-gradient(135deg,#1e40af,#2563eb)',padding:'20px 24px',borderRadius:'20px 20px 0 0',textAlign:'center'}}>
              <div style={{fontSize:32,marginBottom:6}}>🔄</div>
              <div style={{fontFamily:"'Playfair Display',serif",fontSize:18,color:'#fff',fontWeight:700}}>Remplacer la ligne</div>
              <div style={{fontSize:12,color:'#bfdbfe',marginTop:4}}>
                Remplacer : <strong style={{color:'#fff'}}>{ligneRemplacer.name}</strong>
              </div>
            </div>
            <div style={{padding:18,flex:1,overflowY:'auto'}}>
              <input value={searchProd} onChange={e=>setSearchProd(e.target.value)}
                placeholder="🔍 Rechercher le bon produit…" autoFocus style={{marginBottom:14}}/>
              {state.catalog
                .filter(p => !searchProd || p.name.toLowerCase().includes(searchProd.toLowerCase()) || p.barcode.includes(searchProd))
                .slice(0,10)
                .map(p => (
                  <div key={p.id} onClick={()=>remplacerLigne(selected, ligneRemplacer, p)}
                    style={{display:'flex',alignItems:'center',gap:12,padding:'12px 14px',borderRadius:10,marginBottom:8,border:'1.5px solid #e2e8f0',cursor:'pointer',background:'#f8fafc',transition:'all .15s'}}
                    onMouseEnter={e=>e.currentTarget.style.borderColor='#2563eb'}
                    onMouseLeave={e=>e.currentTarget.style.borderColor='#e2e8f0'}>
                    <div style={{flex:1}}>
                      <div style={{fontSize:13,color:'#1e293b',fontWeight:600}}>{p.name}</div>
                      <div style={{fontFamily:"'DM Mono',monospace",fontSize:10,color:'#94a3b8',marginTop:2}}>{p.barcode}</div>
                    </div>
                    <div style={{fontFamily:"'DM Mono',monospace",fontSize:14,color:'#2563eb',fontWeight:700}}>{fmtN(p.price,currency)}</div>
                  </div>
                ))
              }
            </div>
            <div style={{padding:'14px 18px',borderTop:'1px solid #e2e8f0'}}>
              <button className="btn-ghost" style={{width:'100%',padding:'11px'}}
                onClick={()=>{ setShowRemplacer(false); setLigneRemplacer(null); setSuperviseurData(null); }}>
                Annuler
              </button>
            </div>
          </div>
        </div>
      )}

      <div style={{flex:1,display:'grid',gridTemplateColumns:selected?'1fr 440px':'1fr',overflow:'hidden',minHeight:0}}>

        {/* GAUCHE */}
        <div style={{display:'flex',flexDirection:'column',overflow:'hidden'}}>
          <div style={{flex:1,overflowY:'auto',padding:18}}>

            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:14,marginBottom:18}}>
              {[
                {label:tr('ventes_aujourdhui')||"Ventes aujourd'hui", val:ventesJour,           color:'#2563eb', fmt:false},
                {label:tr('ca_aujourdhui')||"CA aujourd'hui",     val:totalJour,            color:'#16a34a', fmt:true},
                {label:tr('total_ventes')||'Total ventes',       val:ventesActives.length, color:'#f59e0b', fmt:false},
              ].map((s,i) => (
                <div key={i} style={{background:'#fff',borderRadius:13,padding:18,borderTop:'4px solid '+s.color,boxShadow:'0 1px 4px #0000000a'}}>
                  <div style={{fontSize:11,color:'#94a3b8',fontWeight:700,textTransform:'uppercase',letterSpacing:1,marginBottom:8}}>{s.label}</div>
                  <div style={{fontFamily:"'Playfair Display',serif",fontSize:s.fmt?20:28,color:s.color,fontWeight:700}}>
                    {s.fmt ? fmtN(s.val,currency) : s.val}
                  </div>
                </div>
              ))}
            </div>

            <div className="card">
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:16}}>
                <div className="stitle" style={{marginBottom:0}}>{tr('historique_ventes')||'📋 Historique des ventes'}</div>
                {historique.length > 0 && <button className="btn-danger btn-sm" onClick={clearHistorique}>{tr("effacer")}</button>}
              </div>

              {historique.length === 0 ? (
                <div style={{textAlign:'center',color:'#94a3b8',padding:'40px 0'}}>
                  <div style={{fontSize:48,marginBottom:12}}>📊</div>
                  tr('aucune_vente')||'Aucune vente enregistrée'
                </div>
              ) : (
                <div>
                  <div style={{display:'grid',gridTemplateColumns:'100px 90px 80px 1fr 60px 110px',gap:10,padding:'8px 14px',background:'#f8fafc',borderRadius:8,marginBottom:8,fontSize:10,fontWeight:700,textTransform:'uppercase',letterSpacing:.8,color:'#94a3b8'}}>
                    <span>{tr("ticket")}</span><span>{tr("date")}</span><span>{tr("heure")}</span><span>{tr("caissier")}</span><span style={{textAlign:'center'}}>{tr("art")}</span><span style={{textAlign:'right'}}>{tr("total")}</span>
                  </div>
                  {historique.map((v,i) => (
                    <div key={i} onClick={()=>setSelected(selected?.id===v.id?null:v)}
                      style={{display:'grid',gridTemplateColumns:'100px 90px 80px 1fr 60px 110px',gap:10,padding:'11px 14px',borderRadius:9,marginBottom:6,alignItems:'center',cursor:'pointer',transition:'all .15s',
                        background: v.annulee?'#fff1f2':selected?.id===v.id?'#eff6ff':i%2===0?'#f8fafc':'#fff',
                        border: selected?.id===v.id?'1.5px solid #2563eb':v.annulee?'1px solid #fecaca':'1px solid #e2e8f0',
                      }}>
                      <div style={{display:'flex',alignItems:'center',gap:4}}>
                        {v.annulee && <span style={{fontSize:9,color:'#dc2626',fontWeight:700}}>❌</span>}
                        <span style={{fontFamily:"'DM Mono',monospace",fontSize:11,color:v.annulee?'#dc2626':'#2563eb',fontWeight:700}}>#{v.id}</span>
                      </div>
                      <span style={{fontSize:12,color:'#475569',fontWeight:500}}>{v.date}</span>
                      <span style={{fontFamily:"'DM Mono',monospace",fontSize:11,color:'#64748b'}}>{v.heure}</span>
                      <span style={{fontSize:12,color:'#1e293b',fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{v.caissier}</span>
                      <span style={{fontSize:12,color:'#64748b',textAlign:'center'}}>{v.articles}</span>
                      <span style={{fontFamily:"'DM Mono',monospace",fontSize:13,color:v.annulee?'#dc2626':'#16a34a',fontWeight:700,textAlign:'right',textDecoration:v.annulee?'line-through':'none'}}>{fmtN(v.total,currency)}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* DROITE */}
        {selected && (
          <div style={{display:'flex',flexDirection:'column',overflow:'hidden',background:'#fff',borderLeft:'1px solid #e2e8f0'}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #e2e8f0',flexShrink:0}}>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <div>
                  <div style={{fontFamily:"'Playfair Display',serif",fontSize:15,color:'#1e293b',fontWeight:700}}>
                    {selected.annulee && <span style={{color:'#dc2626',fontSize:12,marginRight:8}}>❌</span>}
                    Ticket #{selected.id}
                  </div>
                  <div style={{fontSize:11,color:'#94a3b8',marginTop:2}}>{selected.date} à {selected.heure}</div>
                </div>
                <div style={{display:'flex',gap:8}}>
                  {selected.cart && !selected.annulee && (
                    <button className="btn-primary btn-sm" onClick={()=>reimprimer(selected)} style={{padding:'7px 14px'}}>🖨 Réimprimer</button>
                  )}
                  {!selected.annulee && (
                    <button className="btn-danger btn-sm" onClick={()=>{ setLigneAnnuler(null); setLigneRemplacer(null); setShowSuperviseur(true); }} style={{padding:'7px 14px'}}>❌ Annuler tout</button>
                  )}
                  <button className="btn-ghost btn-sm" onClick={()=>setSelected(null)} style={{padding:'7px 14px'}}>✕</button>
                </div>
              </div>
            </div>

            <div style={{flex:1,overflowY:'auto',padding:16}}>

              {/* Info annulation vente */}
              {selected.annulee && (
                <div style={{background:'#fff1f2',border:'1.5px solid #fecaca',borderRadius:11,padding:'14px 16px',marginBottom:14}}>
                  <div style={{fontWeight:700,color:'#dc2626',fontSize:13,marginBottom:8}}>❌ Vente annulée</div>
                  {[[tr('annulee_par')||'Annulée par',selected.annuleeParNom],[tr('date')||'Date',selected.annuleeDate+' à '+selected.annuleeHeure],[tr('raison')||'Raison',selected.annuleeRaison]].map(([k,v])=>(
                    <div key={k} style={{display:'flex',justifyContent:'space-between',fontSize:12,padding:'4px 0',borderBottom:'1px solid #fecaca'}}>
                      <span style={{color:'#94a3b8',fontWeight:600}}>{k}</span>
                      <span style={{color:'#dc2626',fontWeight:600}}>{v}</span>
                    </div>
                  ))}
                </div>
              )}

              {/* Infos */}
              <div className="card">
                <div className="stitle" style={{fontSize:13}}>Informations</div>
                {[[tr('caissier')||tr('caissier')||'Caissier',selected.caissier],[tr('date')||'Date',selected.date],[tr('heure')||'Heure',selected.heure],[tr('reglement_label')||'Règlement',payLabel(selected.payMode)],[tr('montant')||'Montant remis',selected.cashGiven?fmtN(selected.cashGiven,currency):'—'],[tr('rendu')||'Rendu',selected.cashGiven?fmtN(Math.max(0,selected.cashGiven-selected.total),currency):'—']].map(([k,v])=>(
                  <div key={k} style={{display:'flex',justifyContent:'space-between',padding:'8px 0',borderBottom:'1px solid #f1f5f9',fontSize:13}}>
                    <span style={{color:'#94a3b8',fontWeight:600}}>{k}</span>
                    <span style={{color:'#1e293b',fontWeight:600,fontFamily:"'DM Mono',monospace",fontSize:12}}>{v}</span>
                  </div>
                ))}
              </div>

              {/* Articles */}
              {selected.cart && selected.cart.length > 0 && (
                <div className="card">
                  <div className="stitle" style={{fontSize:13}}>
                    Articles ({selected.articles})
                    {!selected.annulee && <span style={{fontSize:10,color:'#94a3b8',fontWeight:400,marginLeft:8}}>🔄 Remplacer · ❌ Annuler ligne</span>}
                  </div>
                  {selected.cart.map((item,i)=>{
                    const tv = TVA_RATES.find(r=>r.key===item.tva);
                    return (
                      <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'9px 12px',borderRadius:8,marginBottom:6,background: item.remplace?'#fffbf0':'#f8fafc',border:'1px solid '+(item.remplace?'#fde68a':'#e2e8f0')}}>
                        <span className="badge" style={{background:(tv?.color||'#888')+'18',borderColor:(tv?.color||'#888')+'44',color:tv?.color||'#888',flexShrink:0}}>{item.tva}</span>
                        <div style={{flex:1,minWidth:0}}>
                          <div style={{fontSize:12,color:'#1e293b',fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                            {item.remplace && <span style={{fontSize:9,color:'#f59e0b',fontWeight:700,marginRight:4}}>🔄</span>}
                            {item.name}
                          </div>
                          {item.remplace && <div style={{fontSize:9,color:'#94a3b8'}}>Remplacé : {item.ancienNom}</div>}
                          <div style={{fontSize:10,color:'#94a3b8',marginTop:1}}>x{item.qty} · {fmtN(item.price,currency)}</div>
                        </div>
                        <span style={{fontFamily:"'DM Mono',monospace",fontSize:13,color:'#2563eb',fontWeight:700,flexShrink:0}}>{fmtN(item.qty*item.price,currency)}</span>
                        {!selected.annulee && (
                          <div style={{display:'flex',gap:4,flexShrink:0}}>
                            <button className="btn-ghost btn-sm" style={{padding:'4px 8px',fontSize:11}}
                              onClick={()=>{ setLigneRemplacer(item); setLigneAnnuler(null); setShowSuperviseur(true); }}
                              title="Remplacer ce produit">🔄</button>
                            <button className="btn-danger btn-sm" style={{padding:'4px 8px',fontSize:11}}
                              onClick={()=>{ setLigneAnnuler(item); setLigneRemplacer(null); setShowSuperviseur(true); }}
                              title="Annuler cette ligne">❌</button>
                          </div>
                        )}
                      </div>
                    );
                  })}

                  {/* Lignes annulées */}
                  {selected.lignesAnnulees && selected.lignesAnnulees.length > 0 && (
                    <div style={{marginTop:10}}>
                      <div style={{fontSize:11,color:'#dc2626',fontWeight:700,marginBottom:6}}>Lignes annulées :</div>
                      {selected.lignesAnnulees.map((ligne,i)=>(
                        <div key={i} style={{background:'#fff1f2',border:'1px solid #fecaca',borderRadius:8,padding:'8px 12px',marginBottom:6,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                          <div>
                            <div style={{fontSize:12,color:'#dc2626',fontWeight:600,textDecoration:'line-through'}}>{ligne.name}</div>
                            <div style={{fontSize:10,color:'#94a3b8'}}>{ligne.annuleeParNom} · {ligne.annuleeDate} · {ligne.annuleeRaison}</div>
                          </div>
                          <span style={{fontFamily:"'DM Mono',monospace",fontSize:12,color:'#dc2626',fontWeight:700}}>-{fmtN(ligne.remboursement,currency)}</span>
                        </div>
                      ))}
                    </div>
                  )}

                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:12,padding:'12px 14px',background:'linear-gradient(135deg,#1e40af,#2563eb)',borderRadius:10}}>
                    <span style={{color:'#fff',fontWeight:700,fontSize:14}}>TOTAL TTC</span>
                    <span style={{fontFamily:"'DM Mono',monospace",fontSize:18,color:'#fff',fontWeight:700}}>{fmtN(selected.total,currency)}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
