/* ── Helpers CRM pour le journal ── */
function buildCRMList(crm) {
  return [
    ...((crm.clients)||[]).map(x=>({id:x.id,type:"client",name:`${x.prenom||""} ${x.nom||""}`.trim()||"(sans nom)"})),
    ...((crm.cgps)||[]).map(x=>({id:x.id,type:"cgp",name:(x.societe?x.societe+" – ":"")+(`${x.nom||""} ${x.prenom||""}`.trim()||"CGP")})),
    ...((crm.entreprises)||[]).map(x=>({id:x.id,type:"entreprise",name:x.nom||"(sans nom)"})),
    ...((crm.banques)||[]).map(x=>({id:x.id,type:"banque",name:x.nom||"(sans nom)"})),
  ];
}
const CRM_TYPE_LABELS={client:"Clients",cgp:"Gestionnaires",entreprise:"Entreprises",banque:"Banques"};

/* ── FluxStatutBadge ── */
function FluxStatutBadge({statut,onChange}){
  const s=FLUX_STATUTS.find(x=>x.key===statut)||FLUX_STATUTS[0];
  if(!onChange) return <span style={{background:s.bg,color:s.color,borderRadius:4,padding:"2px 8px",fontSize:11,fontWeight:700,whiteSpace:"nowrap"}}>{s.label}</span>;
  return (
    <select value={statut} onChange={e=>onChange(e.target.value)}
      style={{background:s.bg,color:s.color,border:"none",borderRadius:6,padding:"4px 8px",fontSize:12,fontWeight:700,cursor:"pointer",outline:"none"}}>
      {FLUX_STATUTS.map(x=><option key={x.key} value={x.key}>{x.label}</option>)}
    </select>
  );
}

/* ── LoginScreen — Microsoft OAuth ── */
function LoginScreen(){
  // Vérifier si une erreur OAuth est dans l'URL (après redirection Microsoft)
  const params=new URLSearchParams(window.location.search);
  const authError=params.get('auth_error');
  // Nettoyer l'URL sans recharger la page
  if(authError) window.history.replaceState({},'','/');
  const handleMicrosoftLogin=()=>{ window.location.href='/auth/microsoft'; };
  return (
    <div style={{minHeight:"100vh",background:"#f0f4ff",display:"flex",alignItems:"center",justifyContent:"center"}}>
      <div style={{background:"#fff",borderRadius:20,padding:40,width:380,boxShadow:"0 8px 40px #0002",border:"1px solid #e2e8f0",textAlign:"center"}}>
        <div style={{fontSize:36,marginBottom:8}}>🏗</div>
        <div style={{fontWeight:800,fontSize:22,color:"#1e293b",marginBottom:4}}>TrésoImmo</div>
        <div style={{fontSize:13,color:"#64748b",marginBottom:28}}>Connexion à votre espace</div>
        {authError&&(
          <div style={{background:"#fee2e2",border:"1px solid #fca5a5",borderRadius:10,padding:"10px 14px",marginBottom:16,fontSize:12,color:"#dc2626"}}>
            ⚠️ Erreur de connexion Microsoft : {decodeURIComponent(authError)}
          </div>
        )}
        <button onClick={handleMicrosoftLogin}
          style={{display:"flex",alignItems:"center",justifyContent:"center",gap:12,width:"100%",background:"#0078d4",color:"#fff",border:"none",borderRadius:10,padding:"13px 0",fontSize:14,fontWeight:700,cursor:"pointer",boxShadow:"0 2px 8px #0078d440"}}>
          <svg width="20" height="20" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="1" y="1" width="9" height="9" fill="#f25022"/>
            <rect x="11" y="1" width="9" height="9" fill="#7fba00"/>
            <rect x="1" y="11" width="9" height="9" fill="#00a4ef"/>
            <rect x="11" y="11" width="9" height="9" fill="#ffb900"/>
          </svg>
          Se connecter avec Microsoft
        </button>
        <div style={{fontSize:11,color:"#94a3b8",marginTop:16}}>
          Connectez-vous avec votre compte @beyondgreenisblue.fr
        </div>
      </div>
    </div>
  );
}

/* ── FluxFormModal ── */
function FluxFormModal({flux,projects,rows,crm,fiches,onSave,onClose}) {
  const isNew=!flux;
  const [form,setForm]=useState(flux||EMPTY_FLUX());
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const inp={background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"6px 10px",fontSize:13,width:"100%"};
  const crmList=buildCRMList(crm);
  const crmGroups=["client","cgp","entreprise","banque"].map(t=>({type:t,label:CRM_TYPE_LABELS[t],items:crmList.filter(x=>x.type===t)})).filter(g=>g.items.length>0);
  const progRows=form.programmeId?rows.filter(r=>r.projetId===form.programmeId):[];
  const weekPreview=form.datePaiement?shiftWeek(form.datePaiement,0):null;
  const rowPreview=rows.find(r=>r.id===form.rowId);
  const valid=form.montant!==""&&form.datePaiement!=="";

  const CRMSelect=({idKey,nomKey,placeholder})=>{
    const selVal=form[idKey];
    const onSel=e=>{
      const id=e.target.value;
      set(idKey,id);
      if(id){const ent=crmList.find(x=>x.id===id);if(ent)set(nomKey,ent.name);}
      else set(nomKey,"");
    };
    return (
      <div style={{display:"flex",flexDirection:"column",gap:4}}>
        <select value={selVal} onChange={onSel} style={inp}>
          <option value="">— Choisir dans le CRM —</option>
          {crmGroups.map(g=>(
            <optgroup key={g.type} label={g.label}>
              {g.items.map(item=><option key={item.id} value={item.id}>{item.name}</option>)}
            </optgroup>
          ))}
        </select>
        {!selVal&&<input value={form[nomKey]} onChange={e=>set(nomKey,e.target.value)} placeholder={placeholder||"ou saisir librement"} style={{...inp,fontSize:12,padding:"4px 8px"}}/>}
      </div>
    );
  };

  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",zIndex:2000,display:"flex",alignItems:"center",justifyContent:"center",padding:16}} onClick={onClose}>
      <div style={{background:"#fff",borderRadius:16,padding:28,width:660,maxWidth:"96vw",maxHeight:"92vh",overflowY:"auto",boxShadow:"0 8px 40px #0003",border:"1px solid #e2e8f0"}} onClick={e=>e.stopPropagation()}>
        <div style={{fontWeight:800,fontSize:17,marginBottom:20}}>{isNew?"📒 Nouveau flux":"✎ Modifier le flux"}</div>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:14}}>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Programme</div>
            <select value={form.programmeId} onChange={e=>{set("programmeId",e.target.value);set("rowId","");}} style={inp}>
              <option value="">— Choisir —</option>
              <GroupedProgrammeOptions projects={projects} fiches={fiches}/>
            </select>
          </div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Ligne Plan Hebdo</div>
            <select value={form.rowId} onChange={e=>set("rowId",e.target.value)} style={{...inp,color:form.programmeId?C.text:"#94a3b8"}} disabled={!form.programmeId}>
              <option value="">— Choisir une ligne —</option>
              {progRows.map(r=><option key={r.id} value={r.id}>[{r.statut}] {r.label}</option>)}
            </select>
          </div>
        </div>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:14}}>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Émetteur</div><CRMSelect idKey="emetteurId" nomKey="emetteurNom" placeholder="Nom émetteur libre"/></div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Récepteur</div><CRMSelect idKey="recepteurId" nomKey="recepteurNom" placeholder="Nom récepteur libre"/></div>
        </div>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12,marginBottom:14}}>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Montant (€) <span style={{color:C.red}}>*</span></div>
            <input type="number" step="any" value={form.montant} onChange={e=>set("montant",e.target.value)} placeholder="Ex: -35000" style={{...inp,color:toN(form.montant)>=0?C.green:C.red,fontWeight:700}}/>
            <div style={{fontSize:10,color:C.muted,marginTop:2}}>Négatif = sortie, positif = entrée</div>
          </div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Date de réception</div><input type="date" value={form.dateReception} onChange={e=>set("dateReception",e.target.value)} style={inp}/></div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Date de paiement <span style={{color:C.red}}>*</span></div><input type="date" value={form.datePaiement} onChange={e=>set("datePaiement",e.target.value)} style={inp}/></div>
        </div>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:14}}>
          {[["compteDebit","Compte à débiter"],["compteCredit","Compte à créditer"]].map(([field,label])=>(
            <div key={field}><div style={{fontSize:11,color:C.muted,marginBottom:3}}>{label}</div>
              {(crm.comptes||[]).length>0?(
                <select value={form[field]} onChange={e=>set(field,e.target.value)} style={inp}>
                  <option value="">— Choisir un compte —</option>
                  {(crm.comptes||[]).map(c=><option key={c.id} value={c.id}>{c.numero?c.numero+" – ":""}{c.libelle||"(sans libellé)"}</option>)}
                </select>
              ):(
                <div style={{display:"flex",flexDirection:"column",gap:4}}>
                  <input value={form[field]} onChange={e=>set(field,e.target.value)} placeholder="Ex: 401, 512…" style={inp}/>
                  <div style={{fontSize:10,color:"#94a3b8"}}>Ajoutez des comptes dans CRM → Comptes pour les sélectionner ici</div>
                </div>
              )}
            </div>
          ))}
        </div>

        <div style={{marginBottom:14}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Statut</div>
          <select value={form.statutFlux||"New"} onChange={e=>set("statutFlux",e.target.value)} style={inp}>
            {FLUX_STATUTS.map(s=><option key={s.key} value={s.key}>{s.label}</option>)}
          </select>
        </div>
        <div style={{marginBottom:14}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Référence PDF / chemin du scan</div>
          <input value={form.pdfName} onChange={e=>set("pdfName",e.target.value)} placeholder="Ex: 2026/03/facture_gfa_001.pdf" style={inp}/>
        </div>
        <div style={{marginBottom:18}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Notes</div>
          <textarea value={form.notes} onChange={e=>set("notes",e.target.value)} style={{...inp,height:56,resize:"vertical"}}/>
        </div>

        {form.rowId&&weekPreview&&(
          <div style={{background:"#eff6ff",borderRadius:8,border:"1px solid #bfdbfe",padding:"8px 12px",marginBottom:14,fontSize:12,color:"#1d4ed8"}}>
            ℹ️ Ce flux sera inséré dans le Plan Hebdo · ligne <b>{rowPreview?.label}</b> · semaine du <b>{weekPreview}</b>
            {" "}<span style={{fontSize:11,color:"#64748b"}}>(valeur existante écrasée si présente)</span>
          </div>
        )}

        <div style={{display:"flex",gap:10,justifyContent:"flex-end"}}>
          <button onClick={onClose} style={{background:"#f1f5f9",border:"1px solid "+C.border,borderRadius:8,padding:"8px 18px",fontSize:13,cursor:"pointer",color:C.text}}>Annuler</button>
          <button onClick={()=>{if(valid)onSave(form);}} disabled={!valid}
            style={{background:valid?"#2563eb":"#94a3b8",color:"#fff",border:"none",borderRadius:8,padding:"8px 22px",fontSize:13,fontWeight:700,cursor:valid?"pointer":"default"}}>
            {isNew?"Enregistrer →":"Mettre à jour →"}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── FluxDetailModal ── */
function FluxDetailModal({flux,project,rowLabel,rowStatut,emetteurName,recepteurName,compteDebitName,compteCreditName,onEdit,onDelete,onClose}) {
  const montant=toN(flux.montant);
  const R=({label,val})=>val?(
    <div style={{display:"flex",gap:8,padding:"6px 0",borderBottom:"1px solid #f1f5f9"}}>
      <span style={{fontSize:11,color:C.muted,minWidth:140,flexShrink:0}}>{label}</span>
      <span style={{fontSize:12,color:C.text,flex:1,wordBreak:"break-all"}}>{val}</span>
    </div>
  ):null;
  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.45)",zIndex:2000,display:"flex",alignItems:"center",justifyContent:"center",padding:16}} onClick={onClose}>
      <div style={{background:"#fff",borderRadius:16,padding:28,width:500,maxWidth:"95vw",boxShadow:"0 8px 40px #0003",border:"1px solid #e2e8f0"}} onClick={e=>e.stopPropagation()}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:16}}>
          <div>
            <div style={{display:"flex",alignItems:"center",gap:10}}>
            <div style={{fontWeight:800,fontSize:16}}>Détail du flux</div>
            <FluxStatutBadge statut={flux.statutFlux||"New"}/>
          </div>
            {project&&<div style={{display:"flex",alignItems:"center",gap:6,marginTop:4}}>
              <span style={{width:8,height:8,borderRadius:"50%",background:project.color,display:"inline-block"}}/>
              <span style={{fontSize:12,color:C.muted}}>{project.ville||project.nom}</span>
            </div>}
          </div>
          <div style={{fontWeight:800,fontSize:22,color:montant>=0?C.green:C.red}}>{fmtEur(montant)}</div>
        </div>
        <div>
          <R label="Programme" val={project?(project.ville||project.nom):null}/>
          <R label="Ligne Plan Hebdo" val={rowLabel?`[${rowStatut||"F"}] ${rowLabel}`:null}/>
          <R label="Émetteur" val={emetteurName}/>
          <R label="Récepteur" val={recepteurName}/>
          <R label="Date de réception" val={flux.dateReception}/>
          <R label="Date de paiement" val={flux.datePaiement}/>
          <R label="Compte débité" val={compteDebitName||flux.compteDebit}/>
          <R label="Compte crédité" val={compteCreditName||flux.compteCredit}/>
          <R label="Référence PDF" val={flux.pdfName}/>
          <R label="Notes" val={flux.notes}/>
        </div>
        <div style={{display:"flex",gap:8,justifyContent:"flex-end",marginTop:18}}>
          <button onClick={onDelete} style={{background:"none",border:"1px solid #f87171",borderRadius:6,color:C.red,cursor:"pointer",padding:"6px 14px",fontSize:12}}>🗑 Supprimer</button>
          <button onClick={onEdit} style={{background:"#334155",color:"#fff",border:"none",borderRadius:8,padding:"6px 16px",fontSize:12,fontWeight:600,cursor:"pointer"}}>✎ Modifier</button>
          <button onClick={onClose} style={{background:"#f1f5f9",border:"1px solid "+C.border,borderRadius:8,padding:"6px 16px",fontSize:12,cursor:"pointer"}}>Fermer</button>
        </div>
      </div>
    </div>
  );
}

/* ── JournalFluxView ── */
function JournalFluxView({journal,onSave,onDelete,projects,rows,crm,fiches}) {
  const [showForm,setShowForm]=useState(false);
  const [editFlux,setEditFlux]=useState(null);
  const [detailFlux,setDetailFlux]=useState(null);
  const [filterProg,setFilterProg]=useState("all");
  const [filterMonth,setFilterMonth]=useState("");
  const [filterStatut,setFilterStatut]=useState("all");
  const [importing,setImporting]=useState(false);
  const inp={background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"6px 10px",fontSize:13,width:"100%"};

  const crmList=buildCRMList(crm);
  const getName=(id,nom)=>{if(!id)return nom||"—";return crmList.find(x=>x.id===id)?.name||nom||"—";};
  const getCompte=(id)=>{if(!id)return null;const c=(crm.comptes||[]).find(x=>x.id===id);return c?(c.numero?c.numero+" – ":"")+c.libelle:null;};
  const getProj=(id)=>projects.find(p=>p.id===id);
  const getRow=(id)=>rows.find(r=>r.id===id);

  const sorted=[...journal].sort((a,b)=>(b.datePaiement||"").localeCompare(a.datePaiement||""));
  const filtered=sorted.filter(f=>{
    if(filterProg!=="all"&&f.programmeId!==filterProg) return false;
    if(filterMonth&&f.datePaiement&&!f.datePaiement.startsWith(filterMonth)) return false;
    if(filterStatut!=="all"&&(f.statutFlux||"New")!==filterStatut) return false;
    return true;
  });

  /* Récupère les imports en attente déposés par l'agent email (/api/agent/imports) */
  const handleImportEmails=async()=>{
    setImporting(true);
    try{
      const r=await fetch('/api/agent/imports');
      if(!r.ok){
        const err=await r.json().catch(()=>({}));
        alert("Erreur : "+(err.error||r.status));
        setImporting(false);return;
      }
      const data=await r.json();
      if(!Array.isArray(data)||data.length===0){
        alert("Aucune nouvelle facture en attente d'import.\n\n(L'agent email dépose automatiquement les factures détectées dans votre boîte.)");
        setImporting(false);return;
      }
      for(const entry of data){
        onSave({...EMPTY_FLUX(),...entry});
      }
      /* Vider la liste des imports en attente */
      await fetch('/api/agent/imports',{method:'DELETE'}).catch(()=>{});
      alert(`✅ ${data.length} facture(s) importée(s) avec succès.`);
    }catch(e){alert("Erreur lors de l'import : "+e.message);}
    setImporting(false);
  };

  const months=[...new Set(journal.map(f=>f.datePaiement?f.datePaiement.slice(0,7):"").filter(Boolean))].sort((a,b)=>b.localeCompare(a));

  const totalFiltered=filtered.reduce((s,f)=>s+toN(f.montant),0);

  if(showForm||editFlux){
    return <FluxFormModal flux={editFlux} projects={projects} rows={rows} crm={crm} fiches={fiches}
      onSave={f=>{onSave(f);setShowForm(false);setEditFlux(null);}}
      onClose={()=>{setShowForm(false);setEditFlux(null);}}/>;
  }

  return (
    <div style={{padding:20,maxWidth:1100,margin:"0 auto"}}>
      {/* Header */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,flexWrap:"wrap",gap:8}}>
        <div>
          <div style={{fontWeight:700,fontSize:16}}>📒 Journal de flux</div>
          <div style={{fontSize:12,color:C.muted,marginTop:2}}>Historique des paiements réels — entrées et sorties de trésorerie</div>
        </div>
        <div style={{display:"flex",gap:8}}>
          <button onClick={handleImportEmails} disabled={importing}
            style={{background:"#0f766e",color:"#fff",border:"none",borderRadius:8,padding:"8px 16px",fontSize:13,fontWeight:600,cursor:"pointer",opacity:importing?.6:1}}>
            {importing?"⏳ Import…":"📧 Import emails"}
          </button>
          <button onClick={()=>setShowForm(true)}
            style={{background:"#2563eb",color:"#fff",border:"none",borderRadius:8,padding:"8px 20px",fontSize:13,fontWeight:700,cursor:"pointer"}}>
            + Nouveau flux
          </button>
        </div>
      </div>

      {/* Filtres */}
      <div style={{display:"flex",gap:8,marginBottom:14,flexWrap:"wrap",alignItems:"center"}}>
        <select value={filterProg} onChange={e=>setFilterProg(e.target.value)} style={{...inp,width:"auto",padding:"5px 10px",fontSize:12}}>
          <option value="all">Tous les programmes</option>
          <GroupedProgrammeOptions projects={projects} fiches={fiches}/>
        </select>
        <select value={filterMonth} onChange={e=>setFilterMonth(e.target.value)} style={{...inp,width:"auto",padding:"5px 10px",fontSize:12}}>
          <option value="">Tous les mois</option>
          {months.map(m=><option key={m} value={m}>{m}</option>)}
        </select>
        <select value={filterStatut} onChange={e=>setFilterStatut(e.target.value)} style={{...inp,width:"auto",padding:"5px 10px",fontSize:12}}>
          <option value="all">Tous les statuts</option>
          {FLUX_STATUTS.map(s=><option key={s.key} value={s.key}>{s.label}</option>)}
        </select>
        {filtered.length>0&&(
          <div style={{marginLeft:"auto",display:"flex",gap:16,alignItems:"center"}}>
            <span style={{fontSize:12,color:C.muted}}>{filtered.length} flux</span>
            <span style={{fontWeight:700,fontSize:13,color:totalFiltered>=0?C.green:C.red}}>{fmtEur(totalFiltered)}</span>
          </div>
        )}
      </div>

      {/* Table */}
      {filtered.length===0?(
        <div style={{textAlign:"center",color:C.muted,fontSize:13,padding:60,background:C.card,borderRadius:12,border:"1px solid "+C.border}}>
          {journal.length===0?"Aucun flux enregistré — cliquez sur \"+ Nouveau flux\" pour commencer.":"Aucun flux pour ces filtres."}
        </div>
      ):(
        <div style={{background:C.card,borderRadius:12,border:"1px solid "+C.border,overflow:"hidden"}}>
          <table style={{borderCollapse:"collapse",width:"100%",fontSize:12}}>
            <thead>
              <tr style={{background:"#f1f5f9",borderBottom:"2px solid "+C.border}}>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Programme</th>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Ligne</th>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Émetteur</th>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Récepteur</th>
                <th style={{padding:"8px 12px",textAlign:"right",color:C.muted,fontWeight:600}}>Montant</th>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Date paiement</th>
                <th style={{padding:"8px 12px",textAlign:"center",color:C.muted,fontWeight:600}}>Statut</th>
                <th style={{padding:"8px 8px",textAlign:"center",color:C.muted,fontWeight:600,width:40}}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((flux,i)=>{
                const prog=getProj(flux.programmeId);
                const row=getRow(flux.rowId);
                const montant=toN(flux.montant);
                const rowBg=i%2===0?C.card:"#fafbfc";
                return (
                  <tr key={flux.id} style={{borderBottom:"1px solid #f1f5f9",background:rowBg,cursor:"default"}}
                    onMouseEnter={e=>e.currentTarget.style.background="#f0f9ff"}
                    onMouseLeave={e=>e.currentTarget.style.background=rowBg}>
                    <td style={{padding:"9px 12px"}}>
                      <div style={{display:"flex",alignItems:"center",gap:6}}>
                        {prog&&<span style={{width:8,height:8,borderRadius:"50%",background:prog.color,display:"inline-block",flexShrink:0}}/>}
                        <span style={{fontWeight:600,fontSize:12}}>{prog?prog.ville||prog.nom:"—"}</span>
                      </div>
                    </td>
                    <td style={{padding:"9px 12px"}}>
                      {row&&<span style={{background:row.statut==="R"?STATUT_STYLE.R.bg:STATUT_STYLE.F.bg,color:row.statut==="R"?STATUT_STYLE.R.color:STATUT_STYLE.F.color,borderRadius:3,padding:"1px 5px",fontSize:9,fontWeight:700,marginRight:4}}>{row.statut}</span>}
                      <span style={{color:C.text}}>{row?row.label:"—"}</span>
                    </td>
                    <td style={{padding:"9px 12px",color:C.text,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{getName(flux.emetteurId,flux.emetteurNom)}</td>
                    <td style={{padding:"9px 12px",color:C.text,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{getName(flux.recepteurId,flux.recepteurNom)}</td>
                    <td style={{padding:"9px 12px",textAlign:"right",fontWeight:700,fontSize:13,color:montant>=0?C.green:C.red,whiteSpace:"nowrap"}}>{fmtEur(montant)}</td>
                    <td style={{padding:"9px 12px",color:C.muted,whiteSpace:"nowrap"}}>{flux.datePaiement||"—"}</td>
                    <td style={{padding:"9px 12px",textAlign:"center"}}>
                      <FluxStatutBadge statut={flux.statutFlux||"New"} onChange={v=>onSave({...flux,statutFlux:v})}/>
                    </td>
                    <td style={{padding:"9px 8px",textAlign:"center"}}>
                      <button onClick={()=>setDetailFlux(flux)}
                        style={{background:"none",border:"1px solid "+C.border,borderRadius:6,color:C.muted,cursor:"pointer",padding:"3px 8px",fontSize:13,lineHeight:1}}
                        title="Voir tous les détails">⋯</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr style={{background:"#f8fafc",borderTop:"2px solid "+C.border}}>
                <td colSpan={4} style={{padding:"8px 12px",fontSize:11,color:C.muted,fontStyle:"italic"}}>Total ({filtered.length} flux)</td>
                <td style={{padding:"8px 12px",textAlign:"right",fontWeight:700,fontSize:13,color:totalFiltered>=0?C.green:C.red}}>{fmtEur(totalFiltered)}</td>
                <td colSpan={3}/>
              </tr>
            </tfoot>
          </table>
        </div>
      )}

      {/* Modale détail */}
      {detailFlux&&(()=>{
        const row=getRow(detailFlux.rowId);
        return <FluxDetailModal
          flux={detailFlux}
          project={getProj(detailFlux.programmeId)}
          rowLabel={row?.label}
          rowStatut={row?.statut}
          emetteurName={getName(detailFlux.emetteurId,detailFlux.emetteurNom)}
          recepteurName={getName(detailFlux.recepteurId,detailFlux.recepteurNom)}
          compteDebitName={getCompte(detailFlux.compteDebit)}
          compteCreditName={getCompte(detailFlux.compteCredit)}
          onEdit={()=>{setEditFlux(detailFlux);setDetailFlux(null);}}
          onDelete={()=>{onDelete(detailFlux.id);setDetailFlux(null);}}
          onClose={()=>setDetailFlux(null)}/>;
      })()}
    </div>
  );
}

function ImportScreen({onImport,onCancel}) {
  const [csv,setCsv]=useState("");
  const [solde,setSolde]=useState("30000");
  const [error,setError]=useState("");
  const handle=()=>{
    if (!csv.trim()){setError("Collez votre CSV ci-dessus.");return;}
    const result=parseCSV(csv);
    if (!result){setError("Impossible de parser le CSV. Vérifiez le format.");return;}
    const s=parseFloat(solde.replace(/\s/g,"").replace(",","."));
    onImport(result,isNaN(s)?0:s);
  };
  const inp={background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"8px 12px",fontSize:13,width:"100%"};
  return (
    <div style={{minHeight:"100vh",background:"#f8fafc",display:"flex",alignItems:"center",justifyContent:"center",padding:24}}>
      <div style={{background:"#ffffff",borderRadius:16,border:"1px solid #e2e8f0",boxShadow:"0 4px 24px #0001",padding:32,width:"100%",maxWidth:700}}>
        <div style={{fontWeight:800,fontSize:24,marginBottom:4,color:"#1e293b"}}>🏗 TrésoImmo</div>
        <div style={{color:"#64748b",fontSize:14,marginBottom:24}}>Importez votre fichier de trésorerie au format CSV</div>
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,color:"#64748b",marginBottom:6}}>Solde initial (€)</div>
          <input value={solde} onChange={e=>setSolde(e.target.value)} style={{background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"8px 12px",fontSize:13,width:180}}/>
        </div>
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,color:"#64748b",marginBottom:6}}>Contenu CSV <span style={{fontSize:11}}>(Ville, Nom, Statut, dates...)</span></div>
          <textarea value={csv} onChange={e=>{setCsv(e.target.value);setError("");}}
            placeholder="Ville,Nom,Statut,22/04/2024,29/04/2024,..."
            style={{background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"10px 12px",width:"100%",height:200,fontFamily:"monospace",fontSize:11,resize:"vertical"}}/>
        </div>
        {error&&<div style={{color:"#dc2626",fontSize:13,marginBottom:12}}>⚠ {error}</div>}
        <div style={{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"}}>
          <button onClick={handle} style={{background:"#2563eb",color:"#fff",border:"none",borderRadius:8,padding:"10px 28px",fontSize:15,fontWeight:700,cursor:"pointer"}}>
            Importer →
          </button>
          {onCancel&&<button onClick={onCancel} style={{background:"#f1f5f9",border:"1px solid #cbd5e1",borderRadius:8,padding:"10px 20px",fontSize:15,cursor:"pointer",color:"#334155"}}>Annuler</button>}
        </div>
        <div style={{marginTop:20,fontSize:11,color:"#64748b",lineHeight:1.8}}>
          <b style={{color:"#1e293b"}}>Format attendu :</b><br/>
          • Col 1-3 : Ville, Nom, Statut (S=Réel, L=Forecast)<br/>
          • Dates : JJ/MM/AAAA ou AAAA-MM-JJ ou W1..W52 (semaines 2026)<br/>
          • Les lignes sans statut S/L sont ignorées automatiquement
        </div>
      </div>
    </div>
  );
}
