/* ── PlanTresorerieView : onglet Plan Hebdo (état local, mutations via props) ── */
function PlanTresorerieView({projects, rows, values, fiches, soldeInitial, setValues, setRows, setProjects, onNavigateToFiche, handleCellSave}) {

  /* ── État local Plan ── */
  const [startIdx,setStartIdx]=useState(Math.max(0,diffW-4));
  const [filterProjet,setFilterProjet]=useState("all");
  const [collapsed,setCollapsed]=useState(()=>{const o={};projects.forEach(p=>{o[p.id]=true;});return o;});
  const [collapsedGroups,setCollapsedGroups]=useState({});
  const toggleGroup=(key)=>setCollapsedGroups(g=>({...g,[key]:!g[key]}));
  const [deleteRowId,setDeleteRowId]=useState(null);
  const [addRowMenu,setAddRowMenu]=useState(null);
  const [newRowLabel,setNewRowLabel]=useState("");
  const [newRowStatut,setNewRowStatut]=useState("R");
  const [editingRowId,setEditingRowId]=useState(null);
  const [editingRowLabel,setEditingRowLabel]=useState("");
  const [cellModal,setCellModal]=useState(null);
  const [exporting,setExporting]=useState(false);

  /* ── Helpers de style ── */
  const inp={background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:8,color:"#1e293b",padding:"8px 12px",fontSize:13,width:"100%"};
  const btnS=(bg,sm)=>({background:bg||"#2563eb",color:"#fff",border:"none",borderRadius:7,padding:sm?"4px 10px":"8px 16px",cursor:"pointer",fontSize:sm?11:13,fontWeight:600});
  const sticky=(bg,z)=>({position:"sticky",left:0,zIndex:z||15,background:bg,borderRight:"2px solid #e2e8f0",whiteSpace:"nowrap"});

  /* ── Computed ── */
  const NUM_VIS=26;
  const weeks=useMemo(()=>weekDates.slice(startIdx,startIdx+NUM_VIS),[startIdx]);
  const getValue=useCallback((rowId,wk)=>{const v=values.find(v=>v.rowId===rowId&&v.weekIso===wk);return v?v.montant:null;},[values]);
  const setValue=useCallback((rowId,wk,montant)=>{
    setValues(vs=>{
      const idx=vs.findIndex(v=>v.rowId===rowId&&v.weekIso===wk);
      if(montant===null) return vs.filter((_,i)=>i!==idx);
      if(idx>=0) return vs.map((v,i)=>i===idx?{...v,montant}:v);
      return [...vs,{rowId,weekIso:wk,montant}];
    });
  },[setValues]);

  const localHandleCellSave=useCallback((rowId,weekIso,newVal,redistribution)=>{
    setValue(rowId,weekIso,newVal);
    if(redistribution){
      setValues(vs=>{
        const idx=vs.findIndex(v=>v.rowId===rowId&&v.weekIso===redistribution.weekIso);
        const existing=idx>=0?vs[idx].montant:0;
        const adjusted=existing+redistribution.adjustment;
        if(adjusted===0) return idx>=0?vs.filter((_,i)=>i!==idx):vs;
        if(idx>=0) return vs.map((v,i)=>i===idx?{...v,montant:adjusted}:v);
        return [...vs,{rowId,weekIso:redistribution.weekIso,montant:adjusted}];
      });
    }
  },[setValue,setValues]);

  const effectiveHandleCellSave = handleCellSave || localHandleCellSave;

  const setRowStatut=(rowId,s)=>setRows(rs=>rs.map(r=>r.id===rowId?{...r,statut:s}:r));
  const removeRow=(rowId)=>{setRows(rs=>rs.filter(r=>r.id!==rowId));setValues(vs=>vs.filter(v=>v.rowId!==rowId));setDeleteRowId(null);};
  const addRow=(projId)=>{if(!newRowLabel.trim())return;setRows(rs=>[...rs,{id:uid(),projetId:projId,label:newRowLabel.trim(),statut:newRowStatut}]);setNewRowLabel("");setAddRowMenu(null);};
  const nav=(d)=>setStartIdx(i=>Math.max(0,Math.min(weekDates.length-NUM_VIS,i+d)));
  const goToday=()=>setStartIdx(Math.max(0,Math.min(diffW-4,weekDates.length-NUM_VIS)));

  const exportPlanHebdo=async()=>{
    setExporting(true);
    try{
      const resp=await fetch("/api/export/plan-hebdo",{
        method:"POST",
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify({projects,rows,values,soldeInitial,fiches})
      });
      if(!resp.ok){
        const err=await resp.json().catch(()=>({}));
        alert("Erreur export : "+(err.error||resp.status));
        return;
      }
      const blob=await resp.blob();
      const url=URL.createObjectURL(blob);
      const a=document.createElement("a");
      const dateStr=new Date().toLocaleDateString("fr-FR",{year:"numeric",month:"2-digit",day:"2-digit"}).replace(/\//g,"-");
      a.href=url; a.download="Plan_Hebdo_"+dateStr+".xlsx";
      document.body.appendChild(a); a.click();
      document.body.removeChild(a); URL.revokeObjectURL(url);
    }catch(e){alert("Erreur export : "+e.message);}
    finally{setExporting(false);}
  };

  const commitRowLabel=(rowId)=>{
    if(editingRowLabel.trim()) setRows(rs=>rs.map(r=>r.id===rowId?{...r,label:editingRowLabel.trim()}:r));
    setEditingRowId(null);
  };
  const renderAddRow=(projId)=>{
    if(addRowMenu===projId) return (
      <tr style={{background:"#f0f9ff"}}>
        <td colSpan={weeks.length+1} style={{padding:0,background:"#f0f9ff"}}>
          <div style={{position:"sticky",left:0,display:"inline-flex",gap:6,alignItems:"center",flexWrap:"wrap",padding:"6px 12px 8px 28px",background:"#f0f9ff",zIndex:14}}>
            <input autoFocus value={newRowLabel} onChange={e=>setNewRowLabel(e.target.value)}
              onKeyDown={e=>{if(e.key==="Enter")addRow(projId);if(e.key==="Escape")setAddRowMenu(null);}}
              placeholder="Libellé de la ligne..."
              style={{background:"#f0f9ff",border:"1px solid "+C.accent,borderRadius:6,color:C.text,padding:"4px 10px",fontSize:12,width:220}}/>
            <select value={newRowStatut} onChange={e=>setNewRowStatut(e.target.value)}
              style={{background:"#f8fafc",border:"1px solid "+C.border,borderRadius:6,color:C.text,padding:"4px 8px",fontSize:12}}>
              <option value="R">R — Réel</option>
              <option value="F">F — Forecast</option>
            </select>
            <button onClick={()=>addRow(projId)} style={btnS(C.green,true)}>✓ Ajouter</button>
            <button onClick={()=>{setAddRowMenu(null);setNewRowLabel("");}} style={btnS("#334155",true)}>✕</button>
          </div>
        </td>
      </tr>
    );
    return (
      <tr style={{background:"#f0f9ff"}}>
        <td colSpan={weeks.length+1} style={{padding:0,background:"#f0f9ff"}}>
          <div style={{position:"sticky",left:0,display:"inline-block",padding:"4px 12px 6px 28px",background:"#f0f9ff",zIndex:14}}>
            <button onClick={()=>{setAddRowMenu(projId);setNewRowLabel("");}}
              style={{background:"none",border:"1px dashed #334155",borderRadius:6,color:C.muted,fontSize:11,padding:"3px 12px",cursor:"pointer"}}>
              + ajouter une ligne
            </button>
          </div>
        </td>
      </tr>
    );
  };

  /* ── Computed : soldes cumulés ── */
  const filteredProjects=useMemo(()=>{
    const projs=filterProjet==="all"?projects:projects.filter(p=>p.id===filterProjet);
    return [...projs].sort((a,b)=>{
      const sa=(fiches[a.id]||EMPTY_FICHE()).statut;
      const sb=(fiches[b.id]||EMPTY_FICHE()).statut;
      const oa=STATUS_ORDER.indexOf(sa); const ob=STATUS_ORDER.indexOf(sb);
      return (oa<0?99:oa)-(ob<0?99:ob);
    });
  },[filterProjet,projects,fiches]);

  const allTotalsRF=useMemo(()=>{
    const fRows=(filterProjet==="all"?rows:rows.filter(r=>r.projetId===filterProjet)).filter(r=>!r.hidden);
    return weekDates.map(wk=>{
      let reel=0,forecast=0;
      fRows.forEach(r=>{const v=getValue(r.id,wk)||0;if(r.statut==="R")reel+=v;else forecast+=v;});
      return{reel,forecast};
    });
  },[rows,values,filterProjet,getValue]);

  const soldePre=useMemo(()=>{
    let r=soldeInitial,rf=soldeInitial;
    for(let i=0;i<startIdx&&i<allTotalsRF.length;i++){r+=allTotalsRF[i].reel;rf+=allTotalsRF[i].reel+allTotalsRF[i].forecast;}
    return{r,rf};
  },[allTotalsRF,startIdx,soldeInitial]);

  const cumulReel=useMemo(()=>{let s=soldePre.r;return weeks.map((_,i)=>{const t=allTotalsRF[startIdx+i];if(t)s+=t.reel;return s;});},[allTotalsRF,startIdx,weeks,soldePre]);
  const cumulTotal=useMemo(()=>{let s=soldePre.rf;return weeks.map((_,i)=>{const t=allTotalsRF[startIdx+i];if(t){s+=t.reel+t.forecast;}return s;});},[allTotalsRF,startIdx,weeks,soldePre]);

  const projWeekTotals=useMemo(()=>{
    const res={};
    projects.forEach(p=>{const pRows=rows.filter(r=>r.projetId===p.id&&!r.hidden);res[p.id]=weeks.map(wk=>pRows.reduce((s,r)=>s+(getValue(r.id,wk)||0),0));});
    return res;
  },[projects,rows,values,weeks,getValue]);

  /* ── Rendu ── */
  return (
    <div>
      <div className="plan-filter-bar" style={{padding:"10px 16px",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",borderBottom:"1px solid "+C.border,background:C.card}}>
        <div style={{display:"flex",gap:3}}>
          {[["◀◀",-12],["◀",-1],["Auj.",0],["▶",1],["▶▶",12]].map(([lbl,d])=>(
            <button key={lbl} style={btnS("#334155",true)} onClick={()=>lbl==="Auj."?goToday():nav(d)}>{lbl}</button>
          ))}
        </div>
        <select value={filterProjet} onChange={e=>setFilterProjet(e.target.value)} style={{...inp,width:"auto",fontSize:12,padding:"5px 10px"}}>
          <option value="all">Tous les projets</option>
          <GroupedProgrammeOptions projects={projects} fiches={fiches}/>
        </select>
        <span style={{fontSize:11,color:C.muted}}>{weeks[0]} → {weeks[weeks.length-1]}</span>
        <div style={{display:"flex",gap:8,alignItems:"center"}}>
          <span style={{fontSize:11,background:STATUT_STYLE.R.bg,color:STATUT_STYLE.R.color,borderRadius:4,padding:"1px 6px",fontWeight:700}}>R</span>
          <span style={{fontSize:11,color:C.muted}}>Réel</span>
          <span style={{fontSize:11,background:STATUT_STYLE.F.bg,color:STATUT_STYLE.F.color,borderRadius:4,padding:"1px 6px",fontWeight:700}}>F</span>
          <span style={{fontSize:11,color:C.muted}}>Forecast</span>
        </div>
        <span style={{fontSize:10,color:"#94a3b8",marginLeft:"auto"}}>💡 Double-clic sur une ligne pour renommer un poste · Clic sur une cellule pour saisir</span>
        <button onClick={exportPlanHebdo} disabled={exporting}
          style={{background:"#16a34a",color:"#fff",border:"none",borderRadius:7,padding:"5px 14px",fontSize:12,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:5,whiteSpace:"nowrap",opacity:exporting?.6:1}}>
          {exporting?"⏳ Export…":"📥 Export Excel"}
        </button>
      </div>
      <div className="plan-scroll">
        <table className="plan-table" style={{borderCollapse:"separate",borderSpacing:0,minWidth:"max-content",fontSize:12}}>
          <thead>
            <tr style={{background:C.card}}>
              <th style={{...sticky(C.card,22),padding:"8px 12px",textAlign:"left",color:C.muted,fontWeight:600,minWidth:240}}>Projet / Poste</th>
              {weeks.map(wk=>(
                <th key={wk} style={{minWidth:84,padding:"6px 3px",textAlign:"center",background:wk===todayIso?"#dbeafe":C.card,color:wk===todayIso?"#1d4ed8":C.muted,fontWeight:wk===todayIso?700:400,borderBottom:"1px solid "+C.border}}>
                  <div style={{fontSize:9}}>{new Date(wk+"T12:00:00Z").toLocaleDateString("fr-FR",{month:"short",year:"2-digit"})}</div>
                  <div>{fmtW(wk)}</div>
                </th>
              ))}
            </tr>
            <tr className="row-reel" style={{background:"#f0fdf4"}}>
              <td style={{...sticky("#f0fdf4",25),padding:"6px 12px",fontWeight:700}}>
                <span style={{fontSize:10,background:STATUT_STYLE.R.bg,color:STATUT_STYLE.R.color,borderRadius:4,padding:"1px 5px",marginRight:6,fontWeight:700}}>R</span>
                Solde réel cumulé
              </td>
              {cumulReel.map((v,i)=>(
                <td key={i} style={{textAlign:"right",padding:"5px 6px",fontWeight:700,color:v>=0?C.green:C.red,background:weeks[i]===todayIso?"#bfdbfe":"#f0fdf4",borderBottom:"1px solid "+C.border}}>
                  {fmtEur(v,true)}
                </td>
              ))}
            </tr>
            <tr className="row-proj" style={{background:"#f0f9ff"}}>
              <td style={{...sticky("#f0f9ff",25),padding:"6px 12px",fontWeight:700}}>
                <span style={{fontSize:10,background:"#dbeafe",color:"#1d4ed8",borderRadius:4,padding:"1px 5px",marginRight:6,fontWeight:700}}>R+F</span>
                Solde projeté cumulé
              </td>
              {cumulTotal.map((v,i)=>(
                <td key={i} style={{textAlign:"right",padding:"5px 6px",fontWeight:700,color:v>=0?"#2563eb":C.red,background:weeks[i]===todayIso?"#bfdbfe":"#f0f9ff",borderBottom:"2px solid "+C.border}}>
                  {fmtEur(v,true)}
                </td>
              ))}
            </tr>
          </thead>
          <tbody>
            {STATUT_GROUPES.map(sg=>{
              const groupProjs=filteredProjects.filter(p=>{const f=fiches[p.id]||EMPTY_FICHE();return f.statut===sg.key;});
              if(groupProjs.length===0) return null;
              const isGroupCol=collapsedGroups[sg.key];
              return (
                <React.Fragment key={sg.key}>
                  <tr className="row-group" style={{background:sg.bg,cursor:"pointer"}} onClick={()=>toggleGroup(sg.key)}>
                    <td colSpan={weeks.length+1} style={{...sticky(sg.bg,19),padding:"5px 12px",fontWeight:700,fontSize:12,color:sg.color}}>
                      <span style={{marginRight:6}}>{isGroupCol?"▶":"▼"}</span>
                      <span style={{width:9,height:9,borderRadius:"50%",background:sg.dot,display:"inline-block",marginRight:5,verticalAlign:"middle"}}/>
                      {sg.label}
                      <span style={{marginLeft:8,fontSize:11,borderRadius:10,padding:"0 7px",border:"1px solid "+sg.color+"66"}}>{groupProjs.length}</span>
                    </td>
                  </tr>
                  {!isGroupCol&&groupProjs.map(proj=>{
                    const pTotals=projWeekTotals[proj.id]||[];
                    const pRows=rows.filter(r=>r.projetId===proj.id);
                    const isCol=collapsed[proj.id];
                    return (
                      <React.Fragment key={proj.id}>
                        <tr style={{background:"#f1f5f9",cursor:"pointer"}} onClick={()=>setCollapsed(c=>({...c,[proj.id]:!c[proj.id]}))}>
                          <td style={{...sticky("#f1f5f9",18),borderTop:"2px solid "+proj.color+"50",padding:"6px 12px 6px 22px",fontWeight:700,fontSize:12}}>
                            <div style={{display:"flex",alignItems:"center",gap:5}}>
                              <span style={{display:"inline-block",width:8,height:8,borderRadius:"50%",background:proj.color,flexShrink:0}}/>
                              <span>{proj.ville?proj.ville+" – ":""}{proj.nom}</span>
                              {!proj.isGlobal&&(
                                <span onClick={e=>{e.stopPropagation();onNavigateToFiche(proj.id);}}
                                  style={{marginLeft:2,fontSize:10,color:C.muted,cursor:"pointer"}} title="Voir la fiche">📋</span>
                              )}
                              <span style={{marginLeft:4,fontSize:10,color:C.muted,fontWeight:400}}>{isCol?"▶":"▼"}</span>
                            </div>
                          </td>
                          {pTotals.map((v,i)=>(
                            <td key={i} style={{textAlign:"right",padding:"6px",fontWeight:600,fontSize:11,color:v>0?C.green:v<0?C.red:"transparent",background:weeks[i]===todayIso?"#bfdbfe":"transparent"}}>
                              {v!==0?fmtEur(v,true):""}
                            </td>
                          ))}
                        </tr>
                        {!isCol&&pRows.filter(r=>!r.hidden).map(row=>(
                          <tr key={row.id} style={{background:C.bg}}
                            onMouseEnter={e=>e.currentTarget.style.background="#f1f5f9"}
                            onMouseLeave={e=>e.currentTarget.style.background=C.bg}>
                            <td style={{...sticky("inherit",15),padding:"3px 8px 3px 32px"}}>
                              <div style={{display:"flex",alignItems:"center",gap:5}}>
                                <StatutBadge statut={row.statut} onChange={s=>setRowStatut(row.id,s)}/>
                                {editingRowId===row.id ? (
                                  <input autoFocus value={editingRowLabel}
                                    onChange={e=>setEditingRowLabel(e.target.value)}
                                    onBlur={()=>commitRowLabel(row.id)}
                                    onKeyDown={e=>{if(e.key==="Enter"||e.key==="Tab")commitRowLabel(row.id);if(e.key==="Escape")setEditingRowId(null);}}
                                    style={{background:"#f0f9ff",border:"1px solid "+C.accent,borderRadius:4,color:C.text,padding:"2px 6px",fontSize:11,flex:1,minWidth:0}}/>
                                ) : (
                                  <span style={{fontSize:11,color:row.statut==="R"?C.green:C.blue,flex:1,cursor:"text"}}
                                    onDoubleClick={()=>{setEditingRowId(row.id);setEditingRowLabel(row.label);}}
                                    title="Double-clic pour renommer">
                                    {row.label}
                                  </span>
                                )}
                                <button onClick={e=>{e.stopPropagation();setDeleteRowId(row.id);}} style={{background:"none",border:"none",color:"#4b5563",cursor:"pointer",fontSize:11,padding:"0 2px"}}>✕</button>
                              </div>
                            </td>
                            {weeks.map(wk=>(
                              <td key={wk} style={{padding:"2px 3px",background:wk===todayIso?"#eff6ff":"transparent"}}>
                                <CellDisplay
                                  value={getValue(row.id,wk)}
                                  statut={row.statut}
                                  onClick={()=>setCellModal({rowId:row.id,weekIso:wk})}
                                />
                              </td>
                            ))}
                          </tr>
                        ))}
                        {!isCol&&renderAddRow(proj.id)}
                      </React.Fragment>
                    );
                  })}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Modale suppression ligne */}
      {deleteRowId&&(()=>{
        const rowToDel = rows.find(r=>r.id===deleteRowId);
        const rowVals  = values.filter(v=>v.rowId===deleteRowId && v.montant);
        const total    = rowVals.reduce((s,v)=>s+v.montant,0);
        const nbCells  = rowVals.length;
        const hasData  = nbCells>0;
        const btnSD=(bg,sm)=>({background:bg||"#2563eb",color:"#fff",border:"none",borderRadius:7,padding:sm?"4px 10px":"8px 16px",cursor:"pointer",fontSize:sm?11:13,fontWeight:600});
        return (
          <div style={{position:"fixed",inset:0,background:"#000c",display:"flex",alignItems:"center",justifyContent:"center",zIndex:50}}>
            <div style={{background:C.card,borderRadius:12,border:"1px solid "+C.border,padding:24,width:360,textAlign:"center"}}>
              <div style={{fontSize:28,marginBottom:8}}>{hasData?"⚠️":"🗑"}</div>
              <div style={{fontWeight:700,marginBottom:6,fontSize:15}}>Supprimer cette ligne ?</div>
              {rowToDel && (
                <div style={{fontSize:12,color:C.muted,marginBottom:10}}>
                  <span style={{fontSize:10,background:STATUT_STYLE[rowToDel.statut]?.bg||"#e2e8f0",color:STATUT_STYLE[rowToDel.statut]?.color||C.muted,borderRadius:4,padding:"1px 5px",marginRight:6,fontWeight:700}}>{rowToDel.statut}</span>
                  <b style={{color:C.text}}>{rowToDel.label}</b>
                </div>
              )}
              {hasData ? (
                <div style={{background:"#fef2f2",border:"1px solid #fecaca",borderRadius:8,padding:"10px 12px",marginBottom:16,textAlign:"left"}}>
                  <div style={{fontSize:12,color:"#b91c1c",fontWeight:700,marginBottom:4}}>Cette ligne contient déjà des données</div>
                  <div style={{fontSize:12,color:C.text,display:"flex",justifyContent:"space-between",marginBottom:2}}><span>Cellules renseignées :</span><b>{nbCells}</b></div>
                  <div style={{fontSize:12,color:C.text,display:"flex",justifyContent:"space-between"}}><span>Montant total :</span><b style={{color:total>=0?C.green:C.red}}>{fmtEur(total)}</b></div>
                  <div style={{fontSize:11,color:C.muted,marginTop:8,fontStyle:"italic"}}>Toutes ces valeurs seront définitivement perdues.</div>
                </div>
              ) : (
                <div style={{fontSize:12,color:C.muted,marginBottom:16}}>Cette ligne ne contient aucune donnée.</div>
              )}
              <div style={{display:"flex",gap:8,justifyContent:"center"}}>
                <button style={btnSD(C.red)} onClick={()=>removeRow(deleteRowId)}>{hasData?"Supprimer quand même":"Supprimer"}</button>
                <button style={btnSD("#334155")} onClick={()=>setDeleteRowId(null)}>Annuler</button>
              </div>
            </div>
          </div>
        );
      })()}

      {/* Modale édition cellule */}
      {cellModal&&rows.find(r=>r.id===cellModal.rowId)&&(
        <CellEditModal
          row={rows.find(r=>r.id===cellModal.rowId)}
          weekIso={cellModal.weekIso}
          currentValue={getValue(cellModal.rowId,cellModal.weekIso)}
          allValues={values}
          onSave={(newVal,redist)=>effectiveHandleCellSave(cellModal.rowId,cellModal.weekIso,newVal,redist)}
          onClose={()=>setCellModal(null)}
        />
      )}
    </div>
  );
}
