/* ── 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,lockPlanContext,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);
  // T/M/R étape 1 : mouvement rattaché à une case → la date du paiement doit
  // tomber DANS la semaine de la case (lundi → dimanche). La date précise le
  // jour à l'intérieur de la semaine ; une date hors semaine n'a pas de sens.
  const weekFin=form.weekIso?weekEndIso(form.weekIso):null;
  const dateHorsSemaine=!!(form.weekIso&&form.datePaiement&&(form.datePaiement<form.weekIso||form.datePaiement>weekFin));
  const valid=form.montant!==""&&form.datePaiement!==""&&!dateHorsSemaine&&(form.destinataireId||form.destinataireNom)&&(form.description||"").trim()!=="";

  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 mouvement":"✎ Modifier le mouvement"}</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,...(lockPlanContext?{background:"#f1f5f9",color:"#64748b"}:{})}} disabled={lockPlanContext}>
              <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",...(lockPlanContext?{background:"#f1f5f9",color:"#64748b"}:{})}} disabled={lockPlanContext||!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>

        {lockPlanContext&&form.weekIso&&(
          <div style={{background:"#eff6ff",borderRadius:8,border:"1px solid #bfdbfe",padding:"6px 12px",marginBottom:14,fontSize:11,color:"#1d4ed8"}}>
            ℹ️ Mouvement rattaché à la cellule éditée · semaine du <b>{fmtW(form.weekIso)}</b>. Programme et ligne verrouillés.
          </div>
        )}
        <div style={{marginBottom:14}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Destinataire <span style={{color:C.red}}>*</span> <span style={{color:"#94a3b8"}}>(qui reçoit l'argent — Beyond Green Is Blue pour une entrée)</span></div>
          <CRMSelect idKey="destinataireId" nomKey="destinataireNom" placeholder="Nom destinataire libre"/>
        </div>
        <div style={{marginBottom:14}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Description <span style={{color:C.red}}>*</span></div>
          <input value={form.description||""} onChange={e=>set("description",e.target.value)} placeholder="Ex: règlement travaux lot 3" style={inp}/>
        </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 <span style={{color:C.red}}>*</span>{form.weekIso&&<span style={{color:"#94a3b8"}}> (dans la semaine)</span>}</div>
            <input type="date" value={form.datePaiement} min={form.weekIso||undefined} max={weekFin||undefined} onChange={e=>set("datePaiement",e.target.value)} style={{...inp,...(dateHorsSemaine?{border:"1px solid #dc2626",background:"#fef2f2"}:{})}}/>
            {dateHorsSemaine&&<div style={{fontSize:10,color:"#dc2626",marginTop:2}}>⚠ La date doit être entre le {fmtW(form.weekIso)} et le {fmtW(weekFin)}</div>}
          </div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Montant précédent</div>
            <input value={(form.montantPrecedent!==""&&form.montantPrecedent!=null)?fmtEur(toN(form.montantPrecedent)):"—"} disabled style={{...inp,background:"#f1f5f9",color:"#64748b"}}/>
            <div style={{fontSize:10,color:C.muted,marginTop:2}}>Auto (si ajustement)</div>
          </div>
        </div>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:14}}>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>N° de facture <span style={{color:"#94a3b8"}}>(optionnel)</span></div>
            <input value={form.numeroFacture||""} onChange={e=>set("numeroFacture",e.target.value)} placeholder="Ex: F2026-0142" style={inp}/></div>
          <div><div style={{fontSize:11,color:C.muted,marginBottom:3}}>Référence facture <span style={{color:"#94a3b8"}}>(optionnel)</span></div>
            <input value={form.pdfName||""} onChange={e=>set("pdfName",e.target.value)} placeholder="Ex: prélèvement, chemin du scan…" style={inp}/></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:18}}>
          <div style={{fontSize:11,color:C.muted,marginBottom:3}}>Commentaire <span style={{color:"#94a3b8"}}>(optionnel)</span></div>
          <textarea value={form.notes} onChange={e=>set("notes",e.target.value)} style={{...inp,height:56,resize:"vertical"}}/>
        </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,destinataireName,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="Destinataire" val={destinataireName}/>
          <R label="Description" val={flux.description}/>
          <R label="Date" val={flux.datePaiement}/>
          <R label="Montant précédent" val={(flux.montantPrecedent!==""&&flux.montantPrecedent!=null)?fmtEur(toN(flux.montantPrecedent)):null}/>
          <R label="N° de facture" val={flux.numeroFacture}/>
          <R label="Référence facture" val={flux.pdfName}/>
          <R label="Commentaire" val={flux.notes}/>
        </div>
        <div style={{display:"flex",gap:8,justifyContent:"flex-end",marginTop:18}}>
          <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 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;
  });

  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);

  // Export Excel des mouvements filtrés (toutes colonnes) — génération côté serveur.
  const exportExcel=async()=>{
    const out=filtered.map(f=>{
      const prog=getProj(f.programmeId); const row=getRow(f.rowId);
      return {
        programme: prog?(prog.ville||prog.nom):"",
        ligne: row?`[${row.statut}] ${row.label}`:"",
        destinataire: getName(f.destinataireId,f.destinataireNom),
        description: f.description||"",
        montant: f.montant,
        montantPrecedent: f.montantPrecedent,
        date: f.datePaiement||"",
        numeroFacture: f.numeroFacture||"",
        reference: f.pdfName||"",
        commentaire: f.notes||"",
        statut: (FLUX_STATUTS.find(s=>s.key===(f.statutFlux||"New"))||{}).label||"",
        source: f.source||"",
      };
    });
    try{
      const r=await fetch("/api/export/journal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rows:out})});
      if(!r.ok){const d=await r.json().catch(()=>({}));alert("Erreur export : "+(d.error||r.status));return;}
      const blob=await r.blob();
      const url=URL.createObjectURL(blob);
      const a=document.createElement("a");a.href=url;a.download="Journal_mouvements.xlsx";document.body.appendChild(a);a.click();a.remove();URL.revokeObjectURL(url);
    }catch(e){alert("Erreur export : "+e.message);}
  };

  // Journal consultatif : aucune création/édition depuis cet onglet (alimenté par
  // l'édition d'une cellule réelle du plan + le log auto). FluxFormModal est défini
  // ici mais rendu/piloté ailleurs (App.jsx) pour la capture au fil de l'eau.

  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 des mouvements</div>
          <div style={{fontSize:12,color:C.muted,marginTop:2}}>Mouvements d'argent réels — consultation seule (alimenté automatiquement)</div>
        </div>
        <div style={{display:"flex",gap:8}}>
          {filtered.length>0&&(
            <button onClick={exportExcel}
              style={{background:"#15803d",color:"#fff",border:"none",borderRadius:8,padding:"8px 16px",fontSize:13,fontWeight:700,cursor:"pointer"}}>
              ⬇ Export Excel
            </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 mouvement enregistré — alimenté automatiquement par l'édition des cellules réelles du plan, les règlements de factures et les appels de fonds.":"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}}>Destinataire</th>
                <th style={{padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600}}>Description</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.destinataireId,flux.destinataireNom)}</td>
                    <td style={{padding:"9px 12px",color:C.text,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{flux.description||"—"}</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"}/>
                    </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}
          destinataireName={getName(detailFlux.destinataireId,detailFlux.destinataireNom)}
          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>
  );
}
