// ─── PARÇA 6: TaskCard, CostTab, MarketTab, SoilTab, LogTab, AIPanel, renderHome, renderDetail, return ───

  // ── TASK CARD ──────────────────────────────────────────────────────────────
  function TaskCard({task, f, sd, daysSince, nextTask, wx}){
    const cx = CAT_COLORS[task.cat] || CAT_COLORS.monitoring;
    const taskDate = new Date(sd);
    taskDate.setDate(taskDate.getDate() + task.d);

    // Match weather to task date
    let wxDay = null;
    if(wx?.time){
      const ds = taskDate.toISOString().split("T")[0];
      const idx = wx.time.indexOf(ds);
      if(idx >= 0) wxDay = {
        min:  wx.temperature_2m_min?.[idx],
        max:  wx.temperature_2m_max?.[idx],
        rain: wx.precipitation_sum?.[idx],
        wind: wx.windspeed_10m_max?.[idx],
        code: wx.weathercode?.[idx],
      };
    }

    const wxAlerts   = wxDay ? buildAlerts(wxDay, t) : [];
    const postponed  = wxDay ? isPostponed(task, wxDay) : false;
    const isPast     = daysSince > task.d;
    const isCurr     = nextTask && nextTask.d === task.d;
    const isDorm     = task.cat === "monitoring" && task.icon === "❄️";

    // PHI harvest check
    const fao        = f ? faoData[f.id] : null;
    const fieldAuth  = getAuth(f?.country || country);

    // Calculate days-to-harvest for PHI warning
    const harvestTask = null; // will be checked per dose
    const hasDose    = task.dose && task.dose.length > 0;
    const hasWx      = wxAlerts.length > 0 && wxDay;

    return(
      <div style={{
        background: isDorm ? "#EFF6FF" : postponed ? "#FFF7ED" : cx.bg,
        border: `1px solid ${isDorm?"#93C5FD":postponed?"#FDBA74":isCurr?"#F59E0B":cx.border}`,
        borderRadius: 12, padding: "8px 10px", marginBottom: 5,
        opacity: isPast ? 0.55 : 1,
      }}>
        {/* Header row */}
        <div style={{display:"flex",alignItems:"center",gap:5}}>
          <div style={{width:6,height:6,borderRadius:"50%",background:isPast?"#9CA3AF":isCurr?"#F59E0B":cx.dot,flexShrink:0}}/>
          <span style={{fontSize:12,fontWeight:700,color:isDorm?"#1E3A8A":cx.text,flex:1}}>
            {isPast?"✓ ":isCurr?"⚡ ":""}{task.icon} {task.name}
          </span>
          <span style={{fontSize:9,color:"#64748B",flexShrink:0,marginRight:4}}>{fmtDate(taskDate)}</span>
          <span style={{fontSize:10,fontWeight:800,color:"#fff",
            background:isPast?"#9CA3AF":isCurr?"#F59E0B":cx.dot,
            borderRadius:5,padding:"1px 6px",flexShrink:0}}>{task.d}d</span>
        </div>

        {/* Detail */}
        {task.detail && (
          <div style={{fontSize:11,color:isDorm?"#1E40AF":cx.text,paddingLeft:11,marginTop:2,lineHeight:1.4}}>
            {task.detail}
          </div>
        )}

        {/* Postponed badge */}
        {postponed && (
          <div style={{marginTop:4,paddingLeft:11,display:"flex",alignItems:"center",gap:5}}>
            <span style={{fontSize:10,fontWeight:800,color:"#92400E",background:"#FEF3C7",
              border:"1px solid #FCD34D",borderRadius:6,padding:"2px 8px"}}>
              ⏸ {t.postponed} — {t.weatherDelay}
            </span>
          </div>
        )}

        {/* Dose rows with unit/total */}
        {hasDose && (
          <div style={{display:"flex",gap:4,paddingLeft:11,marginTop:3,flexWrap:"wrap"}}>
            {task.dose.map((d,di)=>(
              <div key={di} style={{fontSize:10,background:"rgba(0,0,0,.07)",borderRadius:6,
                padding:"3px 7px",color:cx.text,fontWeight:600,lineHeight:1.4}}>
                💊 <strong>{d.item}</strong>: {d.per100}
                {d.phi!=null&&(
                  <span style={{marginLeft:4,color:"#7F1D1D",fontWeight:800,
                    background:"#FEF2F2",borderRadius:4,padding:"1px 4px",fontSize:9}}>
                    PHI: {d.phi}d
                  </span>
                )}
              </div>
            ))}
          </div>
        )}

        {/* PHI harvest warning */}
        {task.phi != null && task.cat !== "harvest" && (
          <div style={{paddingLeft:11,marginTop:3}}>
            <span style={{fontSize:9,fontWeight:800,color:"#7F1D1D",
              background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:5,padding:"2px 6px"}}>
              ⏳ {t.phiLabel}: {task.phi} days — {fieldAuth.lic}
            </span>
          </div>
        )}

        {/* BBCH stage */}
        {task.bbch && (
          <div style={{paddingLeft:11,marginTop:2}}>
            <span style={{fontSize:9,color:"#6366F1",fontWeight:600}}>
              🌿 BBCH {task.bbch} — {getBBCH(f?.crop||"wheat", task.bbch)}
            </span>
          </div>
        )}

        {/* Weather alerts + action advice */}
        {hasWx && (
          <div style={{marginTop:4,paddingLeft:11}}>
            {wxAlerts.map((a,ai)=>{
              const action = getWxAction(a.type, task.cat);
              return(
                <div key={ai} style={{background:a.bg,border:`1px solid ${a.border}`,
                  borderRadius:7,padding:"3px 7px",marginBottom:2}}>
                  <div style={{display:"flex",alignItems:"center",gap:4}}>
                    <span style={{fontSize:10}}>{wxIcon(wxDay.code)}</span>
                    <span style={{fontSize:10,fontWeight:700,color:a.tc}}>{a.title} {a.val}</span>
                  </div>
                  {action && <div style={{fontSize:9,color:a.tc,marginTop:1}}>⚠️ {t.wxMeasure}: {action}</div>}
                </div>
              );
            })}
          </div>
        )}

        {/* Authority badges */}
        <div style={{display:"flex",justifyContent:"flex-end",gap:3,marginTop:4,flexWrap:"wrap"}}>
          {task.source && (
            <span style={{fontSize:8,fontWeight:700,color:"#065F46",
              background:"#DCFCE7",border:"1px solid #86EFAC",borderRadius:4,padding:"1px 5px"}}>
              {task.source}
            </span>
          )}
          {(task.cat==="spray"||task.cat==="fertilize") && (
            <span style={{fontSize:8,fontWeight:700,color:"#7F1D1D",
              background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:4,padding:"1px 5px"}}>
              EPPO
            </span>
          )}
          {fao?.isReal && (
            <span style={{fontSize:8,fontWeight:700,color:"#1E3A8A",
              background:"#EFF6FF",border:"1px solid #BFDBFE",borderRadius:4,padding:"1px 5px"}}>
              {fieldAuth.sci}
            </span>
          )}
          {task.phi != null && (
            <span style={{fontSize:8,fontWeight:700,color:"#92400E",
              background:"#FFF7ED",border:"1px solid #FED7AA",borderRadius:4,padding:"1px 5px"}}>
              {fieldAuth.lic}
            </span>
          )}
        </div>
      </div>
    );
  }

  // ── COST TAB ───────────────────────────────────────────────────────────────
  function CostTab({f}){
    const fd  = getFD(f.id);
    const exp = fd.expenses||[], inc = fd.incomes||[], sub = fd.subsidies||[], byp = fd.byproducts||[];
    const fUnit = GEO[f.country||country]?.unit || geo.unit;
    const ha    = toHa(f.size, fUnit);
    const totalExp = sumArr(exp, e=>+e.amount);
    const totalInc = sumArr(inc, i=>+i.total) + sumArr(byp, b=>+b.total);
    const totalSub = sumArr(sub, s=>+s.amount) +
      sumArr((fd.officialGrants||[]).filter(g=>g.approved), g=>+(g.amount_total||0));
    const profit   = totalInc + totalSub - totalExp;
    const fao = faoData[f.id];
    const md  = MD[f.crop];

    const[lE,setLE]=useState({type:"seed",amount:"",note:""});
    const[lI,setLI]=useState({qty:"",priceKg:"",note:""});
    const[lS,setLS]=useState({name:"",amount:""});
    const[lB,setLB]=useState({name:"",unit:"kg",qty:"",priceUnit:""});

    const expTypes=[["seed",t.seed],["fertilizer",t.fertilizer],["pesticide",t.pesticide],
      ["fuel",t.fuel],["labor",t.labor],["water",t.water],["other",t.other]];

    const officialGrants=(OFFICIAL_GRANTS[f.country||country]||OFFICIAL_GRANTS.default)
      .filter(g=>!g.crop||g.crop.includes(f.crop));
    const savedOG = fd.officialGrants||[];
    function getOG(id){return savedOG.find(x=>x.id===id)||{applied:false,approved:false,amount_total:0};}
    function setOG(id,upd){
      const prev=getOG(id);
      const next={...prev,...upd};
      const list=[...savedOG.filter(x=>x.id!==id),next];
      setFD(f.id,{officialGrants:list});
    }

    return(
      <div>
        {/* FAO data badge */}
        {fao&&(
          <div style={{background:fao.isReal?"#F0FDF4":fao.isFallback?"#EFF6FF":"#F8FAFC",
            border:`1px solid ${fao.isReal?"#86EFAC":fao.isFallback?"#93C5FD":"#E2E8F0"}`,
            borderRadius:12,padding:"8px 12px",marginBottom:8,display:"flex",alignItems:"center",gap:8}}>
            <span style={{fontSize:18}}>{fao.loading?"⏳":fao.isReal?"✅":fao.isFallback?"📊":"—"}</span>
            <div style={{flex:1}}>
              <div style={{fontSize:11,fontWeight:700,color:fao.isReal?"#166534":fao.isFallback?"#1E40AF":"#64748B"}}>
                {fao.loading?t.faoLoading:fao.isReal?t.realData:fao.isFallback?t.fallbackData:"—"}
              </div>
              {fao.yield&&<div style={{fontSize:10,color:"#6B7280"}}>📊 {t.faoYield}: {fao.yield} kg/ha</div>}
            </div>
          </div>
        )}

        {/* Net profit hero */}
        <div style={{background:profit>=0?"linear-gradient(135deg,#16A34A,#15803D)":"linear-gradient(135deg,#DC2626,#B91C1C)",
          borderRadius:18,padding:"16px",marginBottom:10,color:"#fff",textAlign:"center"}}>
          <div style={{fontSize:10,opacity:0.8,marginBottom:2}}>{t.netProfit}</div>
          <div style={{fontSize:34,fontWeight:900}}>{profit>=0?"+":""}{profit.toFixed(0)}</div>
          <div style={{fontSize:10,opacity:0.65}}>{geo.currency}</div>
        </div>

        {/* Summary row */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:7,marginBottom:10}}>
          {[["-"+totalExp.toFixed(0),t.totalExp,"#EF4444","#FFF1F2"],
            ["+"+totalInc.toFixed(0),t.totalInc,"#22C55E","#F0FDF4"],
            ["+"+totalSub.toFixed(0),t.subsidyTotal,"#0369A1","#EFF6FF"]
          ].map(([val,lbl,c,bg],i)=>(
            <div key={i} style={{background:bg,borderRadius:12,padding:"9px 11px"}}>
              <div style={{fontSize:13,fontWeight:800,color:c}}>{val}</div>
              <div style={{fontSize:9,color:"#8E8E93",marginTop:1}}>{lbl}</div>
            </div>
          ))}
        </div>

        {/* Projection */}
        {md&&fao?.yield&&(()=>{
          const cp=md.monthly[curMonth-1];
          const yRef=fao.yield*ha;
          return(
            <div style={{...S.card,marginBottom:10}}>
              <div style={{fontWeight:700,fontSize:12,marginBottom:7}}>
                {t.projTitle} {fao.isReal
                  ?<span style={{fontSize:9,color:"#065F46",background:"#DCFCE7",borderRadius:4,padding:"1px 5px"}}>✓ FAO</span>
                  :<span style={{fontSize:9,color:"#1E40AF",background:"#DBEAFE",borderRadius:4,padding:"1px 5px"}}>📊 Ref</span>}
              </div>
              {[[0.8,t.projBad,"#EF4444"],[1.0,t.projNorm,"#F59E0B"],[1.2,t.projGood,"#22C55E"]].map(([fac,lbl,c],i)=>{
                const rev=yRef*fac*cp, proj=rev+totalSub-totalExp;
                return(
                  <div key={i} style={{display:"flex",gap:8,padding:"5px 0",borderBottom:i<2?"1px solid #F2F2F7":"none"}}>
                    <div style={{fontSize:11,fontWeight:600,color:c,minWidth:55}}>{lbl}</div>
                    <div style={{flex:1,fontSize:10,color:"#8E8E93"}}>{Math.round(yRef*fac).toLocaleString()} kg</div>
                    <div style={{fontWeight:700,fontSize:12,color:proj>=0?"#16A34A":"#DC2626"}}>
                      {proj>=0?"+":""}{proj.toFixed(0)}
                    </div>
                  </div>
                );
              })}
            </div>
          );
        })()}

        {/* Income */}
        <div style={{...S.card,marginBottom:8}}>
          <div style={{fontSize:12,fontWeight:700,color:"#22C55E",marginBottom:8}}>📈 {t.addIncome}</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:5,marginBottom:5}}>
            <input style={S.sInp} type="number" placeholder={t.yieldKg} value={lI.qty} onChange={e=>setLI({...lI,qty:e.target.value})}/>
            <input style={S.sInp} type="number" placeholder={t.priceKg} value={lI.priceKg} onChange={e=>setLI({...lI,priceKg:e.target.value})}/>
            <input style={S.sInp} placeholder={t.note} value={lI.note} onChange={e=>setLI({...lI,note:e.target.value})}/>
          </div>
          {lI.qty&&lI.priceKg&&(
            <div style={{background:"#F0FDF4",borderRadius:7,padding:"3px 7px",marginBottom:5,fontSize:10,color:"#166534",fontWeight:700}}>
              = {(+lI.qty*+lI.priceKg).toFixed(0)} {geo.currency}
            </div>
          )}
          <button style={{...S.btn("#22C55E"),marginTop:0,padding:"9px"}} onClick={()=>{
            if(!lI.qty||!lI.priceKg)return;
            setFD(f.id,{incomes:[...inc,{...lI,total:+lI.qty*+lI.priceKg,id:Date.now()}]});
            setLI({qty:"",priceKg:"",note:""});
          }}>+ {t.addIncome}</button>
          {inc.map((x,i)=>(
            <div key={x.id||i} style={{display:"flex",gap:7,padding:"5px 0",borderTop:"1px solid #F2F2F7"}}>
              <div style={{flex:1,fontSize:12}}>
                <strong style={{color:"#16A34A"}}>{Number(x.total||0).toFixed(0)} {geo.currency}</strong>
                {x.note&&<span style={{color:"#6B7280",fontSize:10}}> — {x.note}</span>}
              </div>
              <button onClick={()=>setFD(f.id,{incomes:inc.filter((_,j)=>j!==i)})}
                style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:14,padding:0}}>🗑</button>
            </div>
          ))}
        </div>

        {/* Expense */}
        <div style={{...S.card,marginBottom:8}}>
          <div style={{fontSize:12,fontWeight:700,color:"#EF4444",marginBottom:8}}>💸 {t.addExpense}</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:5,marginBottom:5}}>
            <select style={S.sSel} value={lE.type} onChange={e=>setLE({...lE,type:e.target.value})}>
              {expTypes.map(([v,l])=><option key={v} value={v}>{l}</option>)}
            </select>
            <input style={S.sInp} type="number" placeholder={t.amount} value={lE.amount} onChange={e=>setLE({...lE,amount:e.target.value})}/>
            <input style={S.sInp} placeholder={t.note} value={lE.note} onChange={e=>setLE({...lE,note:e.target.value})}/>
          </div>
          <button style={{...S.btn("#EF4444"),marginTop:0,padding:"9px"}} onClick={()=>{
            if(!lE.amount)return;
            setFD(f.id,{expenses:[...exp,{...lE,id:Date.now()}]});
            setLE({...lE,amount:"",note:""});
          }}>+ {t.addExpense}</button>
          {exp.map((x,i)=>(
            <div key={x.id||i} style={{display:"flex",gap:7,padding:"5px 0",borderBottom:i<exp.length-1?"1px solid #F2F2F7":"none"}}>
              <div style={{flex:1,fontSize:12}}>
                <strong>{x.amount}</strong>
                {x.note&&<span style={{color:"#6B7280",fontSize:10}}> — {x.note}</span>}
                {x.type&&<span style={{fontSize:9,color:"#fff",background:"#94A3B8",borderRadius:4,padding:"1px 4px",marginLeft:4}}>{x.type}</span>}
              </div>
              <button onClick={()=>setFD(f.id,{expenses:exp.filter((_,j)=>j!==i)})}
                style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:14,padding:0}}>🗑</button>
            </div>
          ))}
        </div>

        {/* By-product */}
        <div style={{...S.card,marginBottom:8,border:"2px solid #D8B4FE"}}>
          <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:8}}>
            <span style={{fontSize:20}}>🌿</span>
            <div style={{fontWeight:800,fontSize:12,color:"#6B21A8"}}>{t.byproductTitle}</div>
          </div>
          <input style={{...S.sInp,marginBottom:5}} placeholder={t.byproductName} value={lB.name}
            onChange={e=>setLB({...lB,name:e.target.value})}/>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:5,marginBottom:5}}>
            <select style={S.sSel} value={lB.unit} onChange={e=>setLB({...lB,unit:e.target.value})}>
              {["kg","ton","bale","unit","lt"].map(u=><option key={u} value={u}>{u}</option>)}
            </select>
            <input style={S.sInp} type="number" placeholder={t.byproductQty} value={lB.qty}
              onChange={e=>setLB({...lB,qty:e.target.value})}/>
            <input style={S.sInp} type="number" placeholder={`${t.byproductPrice}/${lB.unit}`} value={lB.priceUnit}
              onChange={e=>setLB({...lB,priceUnit:e.target.value})}/>
          </div>
          {lB.qty&&lB.priceUnit&&(
            <div style={{background:"#F5F3FF",borderRadius:7,padding:"3px 7px",marginBottom:5,fontSize:10,color:"#6B21A8",fontWeight:700}}>
              = {(+lB.qty*+lB.priceUnit).toFixed(0)} {geo.currency}
            </div>
          )}
          <button style={{...S.btn("#7C3AED"),marginTop:0,padding:"9px"}} onClick={()=>{
            if(!lB.name||!lB.qty||!lB.priceUnit)return;
            setFD(f.id,{byproducts:[...byp,{...lB,total:+lB.qty*+lB.priceUnit,id:Date.now()}]});
            setLB({name:"",unit:"kg",qty:"",priceUnit:""});
          }}>{t.addByproduct}</button>
          {byp.map((x,i)=>(
            <div key={x.id||i} style={{display:"flex",gap:7,padding:"5px 0",borderTop:"1px solid #F2F2F7"}}>
              <div style={{flex:1,fontSize:12}}>
                <strong style={{color:"#7C3AED"}}>{x.name}</strong> · {x.qty} {x.unit} × {x.priceUnit} = <strong>{Number(x.total||0).toFixed(0)} {geo.currency}</strong>
              </div>
              <button onClick={()=>setFD(f.id,{byproducts:byp.filter((_,j)=>j!==i)})}
                style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:14,padding:0}}>🗑</button>
            </div>
          ))}
        </div>

        {/* Manual grant */}
        <div style={{...S.card,border:"2px solid #BAE6FD",marginBottom:8}}>
          <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:8}}>
            <span style={{fontSize:20}}>🏛️</span>
            <div style={{fontWeight:800,fontSize:12,color:"#0C4A6E"}}>{t.addGrant}</div>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"2fr 1fr",gap:5,marginBottom:5}}>
            <input style={S.sInp} placeholder={t.grantName} value={lS.name} onChange={e=>setLS({...lS,name:e.target.value})}/>
            <input style={S.sInp} type="number" placeholder={t.amount} value={lS.amount} onChange={e=>setLS({...lS,amount:e.target.value})}/>
          </div>
          <button style={{...S.btn("#0369A1"),marginTop:0,padding:"9px"}} onClick={()=>{
            if(!lS.amount)return;
            setFD(f.id,{subsidies:[...sub,{...lS,id:Date.now()}]});
            setLS({name:"",amount:""});
          }}>+ {t.addGrant}</button>
          {sub.map((x,i)=>(
            <div key={x.id||i} style={{display:"flex",gap:7,padding:"5px 0",borderTop:"1px solid #F2F2F7"}}>
              <div style={{flex:1,fontSize:12}}>{x.name||"Grant"}: <strong>{x.amount}</strong></div>
              <button onClick={()=>setFD(f.id,{subsidies:sub.filter((_,j)=>j!==i)})}
                style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:14,padding:0}}>🗑</button>
            </div>
          ))}
        </div>

        {/* Official grants */}
        <div style={{...S.card,border:"2px solid #FCD34D"}}>
          <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:10}}>
            <span style={{fontSize:20}}>📋</span>
            <div>
              <div style={{fontWeight:800,fontSize:12,color:"#92400E"}}>{t.officialGrantsTitle} — {geo.name}</div>
              <div style={{fontSize:9,color:"#6B7280",marginTop:1}}>{t.officialGrantsDesc} · {f.size} {fUnit}</div>
            </div>
          </div>
          {officialGrants.map(g=>{
            const og=getOG(g.id);
            const amtTotal=g.amount_ha>0?(g.amount_ha*ha).toFixed(0):"—";
            return(
              <div key={g.id} style={{background:og.approved?"#F0FDF4":og.applied?"#FFFBEB":"#FAFAFA",
                border:`1px solid ${og.approved?"#86EFAC":og.applied?"#FCD34D":"#E5E7EB"}`,
                borderRadius:12,padding:"10px 12px",marginBottom:8}}>
                <div style={{display:"flex",alignItems:"flex-start",gap:8}}>
                  <div style={{flex:1}}>
                    <div style={{fontSize:12,fontWeight:700,color:"#1C1C1E",marginBottom:2}}>{g.name}</div>
                    <div style={{fontSize:10,fontWeight:600,color:"#0369A1",marginBottom:3}}>🏛 {g.org}</div>
                    <div style={{fontSize:9,color:"#6B7280",lineHeight:1.5,marginBottom:4}}>📌 {g.condition}</div>
                    <div style={{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"}}>
                      {g.amount_ha>0&&(
                        <span style={{fontSize:10,fontWeight:700,color:"#065F46",background:"#DCFCE7",borderRadius:5,padding:"2px 7px"}}>
                          {g.amount_ha} {geo.currency}/ha → ~{amtTotal} {geo.currency}
                        </span>
                      )}
                      {g.amount_ha===0&&(
                        <span style={{fontSize:10,color:"#6B7280",background:"#F3F4F6",borderRadius:5,padding:"2px 7px"}}>{t.projectBased}</span>
                      )}
                    </div>
                  </div>
                  <div style={{display:"flex",flexDirection:"column",gap:5,flexShrink:0}}>
                    <button onClick={()=>setOG(g.id,{applied:!og.applied,approved:og.applied?false:og.approved})}
                      style={{background:og.applied?"#FEF3C7":"#F9FAFB",border:`1px solid ${og.applied?"#F59E0B":"#D1D5DB"}`,
                        borderRadius:8,padding:"4px 8px",fontSize:10,fontWeight:700,
                        color:og.applied?"#92400E":"#374151",cursor:"pointer",whiteSpace:"nowrap"}}>
                      {og.applied?t.appliedDone:t.applied}
                    </button>
                    {og.applied&&(
                      <button onClick={()=>{
                        const amt=g.amount_ha>0?+(g.amount_ha*ha).toFixed(0):0;
                        setOG(g.id,{approved:!og.approved,amount_total:!og.approved?amt:0});
                      }} style={{background:og.approved?"#DCFCE7":"#F9FAFB",
                        border:`1px solid ${og.approved?"#22C55E":"#D1D5DB"}`,
                        borderRadius:8,padding:"4px 8px",fontSize:10,fontWeight:700,
                        color:og.approved?"#166534":"#374151",cursor:"pointer",whiteSpace:"nowrap"}}>
                        {og.approved?t.approvedDone:t.approved}
                      </button>
                    )}
                  </div>
                </div>
                {og.approved&&g.amount_ha>0&&(
                  <div style={{marginTop:6,background:"#F0FDF4",borderRadius:7,padding:"4px 8px",fontSize:11,fontWeight:700,color:"#166534"}}>
                    ✅ {t.addedToTotal}: +{amtTotal} {geo.currency}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── MARKET TAB ─────────────────────────────────────────────────────────────
  function MarketTab({f}){
    const md  = MD[f.crop];
    const fao = faoData[f.id];
    if(!md) return <div style={{color:"#8E8E93",padding:20,textAlign:"center"}}>—</div>;
    const best = md.best.includes(curMonth);
    const cp   = md.monthly[curMonth-1];
    const maxP = Math.max(...md.monthly), minP = Math.min(...md.monthly);
    const ha   = toHa(f.size, GEO[f.country||country]?.unit||geo.unit);
    const advice = md.advice[lang]||md.advice.en||"";
    const yRef = fao?.yield ? fao.yield*ha : (md.yieldRef||400)*ha;

    return(
      <div>
        <div style={{background:best?"linear-gradient(135deg,#16A34A,#15803D)":"linear-gradient(135deg,#D97706,#B45309)",
          borderRadius:18,padding:"16px",marginBottom:10,color:"#fff",textAlign:"center"}}>
          <div style={{fontSize:28,marginBottom:4}}>{best?"💰":"⏳"}</div>
          <div style={{fontSize:18,fontWeight:900,marginBottom:2}}>{best?t.sellNow:t.waitSell}</div>
          <div style={{fontSize:12,opacity:0.9}}>{cp.toFixed(2)} {geo.currency}/kg</div>
        </div>
        <div style={S.card}>
          <div style={{fontWeight:700,fontSize:12,marginBottom:7}}>
            📅 {t.bestMonth}: {md.best.map(m=>mn[m-1]).join(", ")}
          </div>
          <div style={{display:"flex",alignItems:"flex-end",gap:2,height:50,marginBottom:4}}>
            {md.monthly.map((p,i)=>{
              const pct=((p-minP)/(maxP-minP)||0)*100;
              const h=Math.max(4,pct*0.4);
              const isCur=i===curMonth-1, isBest=md.best.includes(i+1);
              return(
                <div key={i} style={{flex:1}}>
                  <div style={{width:"100%",height:(h+4)+"px",
                    background:isCur?"#1D4ED8":isBest?"#16A34A":"#D1FAE5",
                    borderRadius:"2px 2px 0 0"}}/>
                </div>
              );
            })}
          </div>
          <div style={{display:"flex",marginBottom:8}}>
            {mn.map((m2,i)=>(
              <div key={i} style={{flex:1,textAlign:"center",
                fontSize:i===curMonth-1?7:6,
                fontWeight:i===curMonth-1?700:400,
                color:i===curMonth-1?"#1D4ED8":"#9CA3AF"}}>{m2}</div>
            ))}
          </div>
          <div style={{fontSize:11,color:"#92400E",background:"#FFF7ED",borderRadius:9,padding:"7px 10px"}}>{advice}</div>
        </div>
        <div style={S.card}>
          <div style={{fontWeight:700,fontSize:12,marginBottom:6}}>
            {t.estRevenue} {fao?.isReal
              ?<span style={{fontSize:9,color:"#065F46",background:"#DCFCE7",borderRadius:4,padding:"1px 5px"}}>✓ FAO</span>
              :fao?.isFallback
                ?<span style={{fontSize:9,color:"#1E40AF",background:"#DBEAFE",borderRadius:4,padding:"1px 5px"}}>📊 Ref</span>
                :null}
          </div>
          {[[0.8,"Low","#EF4444"],[1.0,"Avg","#F59E0B"],[1.2,"High","#22C55E"]].map(([fac,lbl,c],i)=>{
            const kg=yRef*fac, rev=(kg*cp).toFixed(0);
            return(
              <div key={i} style={{display:"flex",gap:8,padding:"5px 0",borderBottom:i<2?"1px solid #F2F2F7":"none"}}>
                <div style={{fontSize:11,fontWeight:600,color:c,minWidth:45}}>{lbl}</div>
                <div style={{flex:1,fontSize:10,color:"#8E8E93"}}>{Math.round(kg).toLocaleString()} kg</div>
                <div style={{fontSize:12,fontWeight:800,color:c}}>{Number(rev).toLocaleString()} {geo.currency}</div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── SOIL TAB ───────────────────────────────────────────────────────────────
  function SoilTab({f}){
    const fd   = getFD(f.id);
    const saved= fd.soil||{type:f.soilType||"loamy",ph:"6.5",organic:"2"};
    const[local,setLocal]=useState({type:saved.type||"loamy",ph:saved.ph||"6.5",organic:saved.organic||"2"});
    const[histLocal,setHL]=useState({crop:"wheat",year:"2024"});
    const history = fd.history||[];
    const interval=({sandy:2,loamy:4,clay:6,silty:5,chalky:3,peaty:5,volcanic:3,saline:3,laterite:4,alluvial:4})[local.type]||4;
    const lastHist= history.length>0?history[history.length-1]:null;
    const rotOk   = !lastHist||CROP_FAMILY[f.crop]!==CROP_FAMILY[lastHist.crop];
    const meta    = SOIL_META[local.type]||{emoji:"🌍",color:"#64748B"};

    return(
      <div>
        <div style={S.card}>
          <div style={{fontWeight:700,fontSize:13,marginBottom:10}}>🌍 {t.soilTitle}</div>
          <div style={{background:meta.color+"18",borderRadius:10,padding:"9px 12px",marginBottom:10,display:"flex",alignItems:"center",gap:10}}>
            <span style={{fontSize:24}}>{meta.emoji}</span>
            <div>
              <div style={{fontWeight:700,color:meta.color}}>{t[local.type]||local.type}</div>
              <div style={{fontSize:10,color:"#64748B",marginTop:2}}>
                {t.irrigInterval}: {interval}d
                {" · "}{t.irrigMethod}:
                <select style={{...S.sSel,display:"inline",width:"auto",marginLeft:4,fontSize:10,padding:"2px 6px"}}
                  value={irrigMethod} onChange={e=>setIrrigMethod(e.target.value)}>
                  {["drip","sprinkler","flood","furrow"].map(m=><option key={m} value={m}>{m}</option>)}
                </select>
              </div>
            </div>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:10}}>
            <div>
              <label style={S.lbl}>{t.soilPh}</label>
              <input style={S.sInp} type="number" step="0.1" value={local.ph} onChange={e=>setLocal({...local,ph:e.target.value})}/>
            </div>
            <div>
              <label style={S.lbl}>{t.soilOrganic}</label>
              <input style={S.sInp} type="number" step="0.1" value={local.organic} onChange={e=>setLocal({...local,organic:e.target.value})}/>
            </div>
          </div>
          <button style={S.btn(soilSaved?"#22C55E":"#065F46")} onClick={()=>{
            setFD(f.id,{soil:local});setSoilSaved(true);setTimeout(()=>setSoilSaved(false),2000);
          }}>{soilSaved?t.soilSaved:t.saveSoil}</button>
        </div>
        <div style={S.card}>
          <div style={{fontWeight:700,fontSize:12,marginBottom:8}}>🔁 {t.rotHistory}</div>
          {!rotOk&&(
            <div style={{background:"#FFF1F2",border:"1px solid #FDA4AF",borderRadius:9,padding:"8px 10px",marginBottom:8,fontSize:11,fontWeight:700,color:"#9F1239"}}>
              {t.rotWarn}
            </div>
          )}
          {rotOk&&history.length>0&&(
            <div style={{background:"#F0FDF4",border:"1px solid #86EFAC",borderRadius:9,padding:"8px 10px",marginBottom:8,fontSize:11,fontWeight:700,color:"#166534"}}>
              {t.rotOk}
            </div>
          )}
          <div style={{display:"grid",gridTemplateColumns:"2fr 1fr",gap:7,marginBottom:7}}>
            <select style={S.sSel} value={histLocal.crop} onChange={e=>setHL({...histLocal,crop:e.target.value})}>
              {Object.keys(CROPS).map(k=><option key={k} value={k}>{CROPS[k].emoji} {getCropName(k,lang)}</option>)}
            </select>
            <select style={S.sSel} value={histLocal.year} onChange={e=>setHL({...histLocal,year:e.target.value})}>
              {"2020,2021,2022,2023,2024,2025".split(",").map(y=><option key={y} value={y}>{y}</option>)}
            </select>
          </div>
          <button style={S.btn("#6366F1")} onClick={()=>setFD(f.id,{history:[...history,{...histLocal,id:Date.now()}]})}>
            + {t.addHistory}
          </button>
          {[...history].reverse().map((h,i)=>(
            <div key={h.id||i} style={{display:"flex",gap:7,padding:"6px 0",borderBottom:i<history.length-1?"1px solid #F2F2F7":"none"}}>
              <span style={{fontSize:16}}>{CROPS[h.crop]?.emoji}</span>
              <div style={{flex:1}}>
                <div style={{fontSize:12,fontWeight:600}}>{getCropName(h.crop,lang)}
                  {h.auto&&<span style={{fontSize:8,color:"#6366F1",background:"#EEF2FF",borderRadius:4,padding:"1px 4px",marginLeft:4}}>auto</span>}
                </div>
                <div style={{fontSize:10,color:"#8E8E93"}}>{h.year}</div>
              </div>
              <button onClick={()=>setFD(f.id,{history:history.filter(x=>x.id!==h.id)})}
                style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:13,padding:0}}>🗑</button>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── LOG TAB ────────────────────────────────────────────────────────────────
  function LogTab({f}){
    const fd   = getFD(f.id);
    const logs = fd.logs||[];
    const[note,setNote]=useState("");
    function addLog(){
      if(!note.trim())return;
      const d=new Date();
      setFD(f.id,{logs:[{
        id:Date.now(),note,
        date:d.toLocaleDateString("en",{day:"numeric",month:"short",year:"numeric"}),
        time:d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),
      },...logs]});
      setNote("");
    }
    return(
      <div>
        <div style={S.card}>
          <textarea style={{...S.sInp,minHeight:68,resize:"vertical",lineHeight:1.5,marginBottom:7}}
            placeholder={t.logNote} value={note} onChange={e=>setNote(e.target.value)}/>
          <button style={S.btn("#6366F1")} onClick={addLog}>+ {t.addLog}</button>
        </div>
        {logs.length===0
          ?<div style={{textAlign:"center",padding:"20px",color:"#8E8E93",fontSize:12}}>{t.noLogs}</div>
          :logs.map((l,i)=>(
            <div key={l.id||i} style={S.card}>
              <div style={{display:"flex",justifyContent:"space-between",marginBottom:5}}>
                <div style={{fontSize:10,fontWeight:600,color:"#8E8E93"}}>{l.date} · {l.time}</div>
                <button onClick={()=>setFD(f.id,{logs:logs.filter((_,j)=>j!==i)})}
                  style={{background:"none",border:"none",color:"#FF3B30",cursor:"pointer",fontSize:13,padding:0}}>🗑</button>
              </div>
              <div style={{fontSize:13,color:"#1C1C1E",lineHeight:1.6}}>{l.note}</div>
            </div>
          ))
        }
      </div>
    );
  }

  // ── AI PANEL ───────────────────────────────────────────────────────────────
  function AIPanel(){
    if(!showAI)return null;
    return(
      <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.55)",zIndex:500,
        display:"flex",alignItems:"flex-end",justifyContent:"center"}}
        onClick={()=>setShowAI(false)}>
        <div style={{background:"#fff",borderRadius:"20px 20px 0 0",width:"100%",maxWidth:480,
          height:"78vh",display:"flex",flexDirection:"column"}}
          onClick={e=>e.stopPropagation()}>
          <div style={{background:"linear-gradient(135deg,#7C3AED,#4F46E5)",borderRadius:"20px 20px 0 0",
            padding:"14px 16px",flexShrink:0,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <div style={{fontSize:15,fontWeight:800,color:"#fff"}}>🧑‍🌾 {t.aiAdvisor}</div>
            <button onClick={()=>setShowAI(false)}
              style={{background:"rgba(255,255,255,.2)",border:"none",borderRadius:50,
                width:30,height:30,fontSize:18,cursor:"pointer",color:"#fff"}}>×</button>
          </div>
          <div style={{flex:1,overflowY:"auto",padding:"12px 14px",background:"#F8F9FC"}}>
            {aiMessages.map((m,i)=>(
              <div key={i} style={{display:"flex",justifyContent:m.role==="user"?"flex-end":"flex-start",marginBottom:10}}>
                {m.role==="assistant"&&(
                  <div style={{width:28,height:28,borderRadius:50,
                    background:"linear-gradient(135deg,#7C3AED,#4F46E5)",
                    display:"flex",alignItems:"center",justifyContent:"center",
                    fontSize:14,flexShrink:0,marginRight:8,marginTop:2}}>🧑‍🌾</div>
                )}
                <div style={{maxWidth:"82%",
                  background:m.role==="user"?"linear-gradient(135deg,#7C3AED,#4F46E5)":"#fff",
                  color:m.role==="user"?"#fff":"#1C1C1E",
                  borderRadius:m.role==="user"?"16px 16px 4px 16px":"16px 16px 16px 4px",
                  padding:"9px 12px",fontSize:12,lineHeight:1.6,
                  boxShadow:"0 1px 4px rgba(0,0,0,.08)",whiteSpace:"pre-wrap"}}>
                  {m.content}
                </div>
              </div>
            ))}
            {aiLoading&&(
              <div style={{display:"flex",alignItems:"center",gap:8}}>
                <div style={{width:28,height:28,borderRadius:50,background:"linear-gradient(135deg,#7C3AED,#4F46E5)",
                  display:"flex",alignItems:"center",justifyContent:"center",fontSize:14}}>🧑‍🌾</div>
                <div style={{background:"#fff",borderRadius:"16px 16px 16px 4px",padding:"9px 14px"}}>
                  <div style={{display:"flex",gap:4}}>
                    {[0,1,2].map(j=><div key={j} style={{width:6,height:6,borderRadius:3,background:"#7C3AED",opacity:0.5+j*0.2}}/>)}
                  </div>
                </div>
              </div>
            )}
            <div ref={aiEndRef}/>
          </div>
          <div style={{padding:"10px 14px",borderTop:"1px solid #F0F0F5",background:"#fff",flexShrink:0,display:"flex",gap:8}}>
            <input style={{flex:1,background:"#F2F5F9",border:"none",borderRadius:20,padding:"10px 14px",fontSize:13,outline:"none"}}
              placeholder={t.aiPlaceholder} value={aiInput}
              onChange={e=>setAiInput(e.target.value)}
              onKeyDown={e=>{if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();sendAI();}}}/>
            <button onClick={sendAI} disabled={aiLoading||!aiInput.trim()}
              style={{background:"linear-gradient(135deg,#7C3AED,#4F46E5)",border:"none",borderRadius:50,
                width:40,height:40,cursor:"pointer",color:"#fff",
                opacity:(aiLoading||!aiInput.trim())?0.5:1,fontSize:16,flexShrink:0}}>▶</button>
          </div>
        </div>
      </div>
    );
  }

  // ── RENDER HOME ────────────────────────────────────────────────────────────
  function renderHome(){
    const recs    = getMonthRecs(cz, curMonth);
    const ideal   = recs.filter(r=>r.s==="ideal");
    const poss    = recs.filter(r=>r.s==="possible");
    const dormInfo= DORMANCY[cz];
    const isDormNow=dormInfo&&isDormMonth(cz,curMonth);

    return(
      <div>
        {unsuitableWarn&&(
          <div style={{background:"#FFF1F2",border:"2px solid #EF4444",borderRadius:14,
            padding:"10px 14px",marginBottom:10,fontSize:12,fontWeight:700,color:"#DC2626"}}>
            {unsuitableWarn}
          </div>
        )}
        {isDormNow&&(
          <div style={{background:"linear-gradient(135deg,#1E3A8A,#1E40AF)",borderRadius:18,
            padding:"12px 14px",marginBottom:10,color:"#fff"}}>
            <div style={{fontWeight:800,fontSize:13}}>❄️ Dormancy — {dormInfo.label}</div>
          </div>
        )}

        {/* Season planting suggestions */}
        <div style={{background:"linear-gradient(135deg,#1D4ED8,#1E40AF)",borderRadius:18,padding:"14px",marginBottom:12,color:"#fff"}}>
          <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:10}}>
            <span style={{fontSize:20}}>🌱</span>
            <div style={{fontSize:14,fontWeight:800}}>{t.seasonTitle}</div>
          </div>
          {ideal.length>0&&(
            <div style={{marginBottom:8}}>
              <div style={{fontSize:10,fontWeight:700,opacity:0.7,marginBottom:5}}>✅ IDEAL</div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:5}}>
                {ideal.map(r=>{
                  const cr=CROPS[r.k]; if(!cr)return null;
                  return(
                    <button key={r.k} onClick={()=>{setForm(f=>({...f,crop:r.k}));navTo("add");}}
                      style={{background:"rgba(255,255,255,.18)",border:"1px solid rgba(255,255,255,.3)",
                        borderRadius:12,padding:"8px 6px",cursor:"pointer",textAlign:"center"}}>
                      <div style={{fontSize:20}}>{cr.emoji}</div>
                      <div style={{fontSize:9,fontWeight:700,color:"#fff",marginTop:3}}>{getCropName(r.k,lang)}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}
          {poss.length>0&&(
            <div style={{overflowX:"auto"}}>
              <div style={{display:"flex",gap:5,width:"max-content"}}>
                {poss.map(r=>{
                  const cr=CROPS[r.k]; if(!cr)return null;
                  return(
                    <button key={r.k} onClick={()=>{setForm(f=>({...f,crop:r.k}));navTo("add");}}
                      style={{flexShrink:0,background:"rgba(255,255,255,.1)",
                        border:"1px solid rgba(255,255,255,.2)",borderRadius:10,
                        padding:"5px 10px",fontSize:11,fontWeight:600,
                        color:"rgba(255,255,255,.85)",cursor:"pointer",
                        display:"flex",alignItems:"center",gap:5}}>
                      <span>{cr.emoji}</span><span>{getCropName(r.k,lang)}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* Field cards */}
        {countryFields.length===0
          ?<div style={{textAlign:"center",padding:"32px 16px"}}>
            <div style={{fontSize:52,marginBottom:12}}>🌾</div>
            <div style={{fontSize:16,fontWeight:700,color:"#1C1C1E",marginBottom:5}}>{t.noFields}</div>
            <div style={{fontSize:13,color:"#8E8E93"}}>{t.addFirst}</div>
          </div>
          :countryFields.map(f=>{
            const cr   = CROPS[f.crop];
            const fd   = getFD(f.id);
            const exp  = sumArr(fd.expenses||[],e=>+e.amount);
            const inc  = sumArr(fd.incomes||[],i=>+i.total);
            const sub  = sumArr(fd.subsidies||[],s=>+s.amount);
            const profit = inc+sub-exp;
            const fa   = globalAlerts.filter(a=>a.fieldId===f.id);
            const sm   = SOIL_META[f.soilType]||null;
            const rc   = f.prevCrop?getRotConseq(CROP_FAMILY[f.crop],CROP_FAMILY[f.prevCrop]):null;
            const faoInfo = faoData[f.id];

            // Upcoming tasks for this field (next 3 days)
            const today2=new Date();today2.setHours(0,0,0,0);
            const in3=new Date(today2);in3.setDate(in3.getDate()+3);
            const sd=new Date(`${f.y}-${f.m}-${f.d}`);
            const fClim=getFieldClim(f);
            const upcomingForField=buildCropTasks(f.crop,sd,fClim,null,null,null,f.size,geo.unit)
              .filter(task=>{const td=new Date(sd);td.setDate(td.getDate()+task.d);return td>=today2&&td<=in3;})
              .slice(0,2);

            return(
              <div key={f.id} style={{...S.card,cursor:"pointer",
                border:fa.length>0?`2px solid ${fa[0].alert.sev==="red"?"#EF4444":"#F59E0B"}`:
                  f.unsuitableSeason?"2px solid #F59E0B":undefined}}
                onClick={()=>navTo("detail",{fieldId:f.id})}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start"}}>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:15,fontWeight:700,color:"#1C1C1E",marginBottom:3}}>
                      {f.name}
                      {f.unsuitableSeason&&<span style={{fontSize:10,marginLeft:6,color:"#D97706",
                        background:"#FFF7ED",borderRadius:5,padding:"1px 5px"}}>⚠️</span>}
                    </div>
                    <div style={{fontSize:11,color:"#8E8E93"}}>{f.region}{f.zone?" · "+f.zone.label:""}</div>
                    <div style={{fontSize:10,color:"#8E8E93",marginTop:1}}>
                      {f.size} {geo.unit}
                      {sm?" · "+sm.emoji:""}
                      {f.variety?" · "+f.variety:""}
                      {f.nadas?" · 🌿 "+t.fallow:""}
                      {f.seedKg?" · 🌾 "+f.seedKg+"kg":""}
                    </div>
                    {f.prevCrop&&(
                      <div style={{fontSize:10,color:"#6B7280",marginTop:1,display:"flex",alignItems:"center",gap:4}}>
                        ↩ {CROPS[f.prevCrop]?.emoji} {getCropName(f.prevCrop,lang)}
                        {rc&&<span style={{fontSize:10,fontWeight:800,
                          color:rc.pct<0?"#DC2626":"#16A34A",
                          background:rc.pct<0?"#FFF1F2":"#F0FDF4",
                          borderRadius:5,padding:"0 5px"}}>{rc.icon} {rc.pct>0?"+":""}{rc.pct}%</span>}
                      </div>
                    )}
                    {fa.length>0&&fa.slice(0,2).map((ga,gi)=>(
                      <div key={gi} style={{marginTop:4,background:ga.alert.sev==="red"?"#FFF1F2":"#FFFBEB",
                        borderRadius:8,padding:"5px 8px",
                        border:`1px solid ${ga.alert.sev==="red"?"#FDA4AF":"#FCD34D"}`}}>
                        <div style={{fontSize:10,fontWeight:700,
                          color:ga.alert.sev==="red"?"#DC2626":"#D97706"}}>
                          {ga.alert.sev==="red"?"🔴":"🟠"} {ga.alert.title} {ga.alert.val} — {ga.day}
                        </div>
                      </div>
                    ))}
                    {upcomingForField.length>0&&(
                      <div style={{marginTop:4}}>
                        {upcomingForField.map((task,ti)=>(
                          <div key={ti} style={{background:"#FFFBEB",borderRadius:6,
                            padding:"3px 7px",marginBottom:2,fontSize:9,color:"#92400E",fontWeight:600}}>
                            🔔 {task.icon} {task.name}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                  <div style={{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:3,marginLeft:8,flexShrink:0}}>
                    <div style={{background:(cr?.color||"#8E8E93")+"18",color:cr?.color||"#8E8E93",
                      borderRadius:10,padding:"2px 8px",fontSize:11,fontWeight:700}}>
                      {cr?.emoji} {getCropName(f.crop,lang)}
                    </div>
                    {f.nadas&&(
                      <div style={{background:"#FEF3C7",color:"#92400E",borderRadius:8,
                        padding:"2px 7px",fontSize:9,fontWeight:700}}>🌿 {t.fallow}</div>
                    )}
                    {(exp>0||inc>0)&&(
                      <div style={{fontSize:12,fontWeight:800,color:profit>=0?"#16A34A":"#DC2626"}}>
                        {profit>=0?"▲":"▼"} {Math.abs(profit).toFixed(0)}
                      </div>
                    )}
                    {faoInfo?.isReal&&(
                      <div style={{fontSize:8,fontWeight:700,color:"#065F46",
                        background:"#DCFCE7",border:"1px solid #86EFAC",borderRadius:5,padding:"2px 6px"}}>✓ FAO</div>
                    )}
                    {faoInfo?.isFallback&&!faoInfo.isReal&&(
                      <div style={{fontSize:8,fontWeight:700,color:"#1E40AF",
                        background:"#DBEAFE",border:"1px solid #93C5FD",borderRadius:5,padding:"2px 6px"}}>📊 Ref</div>
                    )}
                  </div>
                </div>
              </div>
            );
          })
        }

        {countryFields.length>0&&(
          <button onClick={()=>openAI(null)}
            style={{width:"100%",background:"linear-gradient(135deg,#7C3AED,#6D28D9)",
              border:"none",borderRadius:14,padding:"12px",fontSize:12,fontWeight:700,
              color:"#fff",cursor:"pointer",marginBottom:8}}>
            🧑‍🌾 {t.aiAdvisor}
          </button>
        )}
        <button style={S.addBtn} onClick={()=>{setForm(emptyForm());setErrors([]);navTo("add");}}>
          + {t.add}
        </button>
      </div>
    );
  }

  // ── RENDER DETAIL ──────────────────────────────────────────────────────────
  function renderDetail(fieldId){
    const f = fields.find(x=>x.id===fieldId);
    if(!f)return null;
    const crop = CROPS[f.crop]; if(!crop)return null;
    const clim = getFieldClim(f);
    const sd   = new Date(`${f.y}-${f.m}-${f.d}`);
    const fao  = faoData[f.id];
    const fUnit= GEO[f.country||country]?.unit||geo.unit;
    const fieldAuth = getAuth(f.country||country);
    const tasks= buildCropTasks(f.crop,sd,clim,f.seedKg,fao?.yield,fao?.fert,f.size,fUnit);
    const last = tasks.length?tasks[tasks.length-1].d:0;
    const today3=new Date();today3.setHours(0,0,0,0);
    const daysSince=Math.max(0,Math.round((today3-sd)/86400000));
    const progress=last>0?Math.min(100,Math.round((daysSince/last)*100)):0;
    const nextTask=tasks.find(task=>task.d>daysSince);
    const daysToNext=nextTask?nextTask.d-daysSince:null;
    const wx   = getFieldWx(f);
    const safeH= SAFE_HARVEST[clim];
    const dormInfo=DORMANCY[clim];
    const isDormNow=dormInfo&&isDormMonth(clim,curMonth);
    const sm   = SOIL_META[f.soilType]||null;
    const rc   = f.prevCrop?getRotConseq(CROP_FAMILY[f.crop],CROP_FAMILY[f.prevCrop]):null;

    const tabs=[
      ["timeline","📅 "+t.tabTimeline],
      ["cost","💰 "+t.tabCost],
      ["market","📈 "+t.tabMarket],
      ["soil","🌍 "+t.tabSoil],
      ["log","📝 "+t.tabLog],
    ];

    return(
      <div>
        {/* Hero card */}
        <div style={S.hero(crop.color)}>
          <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:8}}>
            <div style={{fontSize:34,lineHeight:1,flexShrink:0}}>{crop.emoji}</div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:20,fontWeight:800,lineHeight:1.1}}>
                {f.name}
                {f.unsuitableSeason&&<span style={{fontSize:10,marginLeft:6,
                  background:"rgba(255,255,255,.2)",borderRadius:5,padding:"1px 5px"}}>⚠️</span>}
              </div>
              <div style={{fontSize:12,opacity:0.82,marginTop:3}}>
                {getCropName(f.crop,lang)}{f.variety?" · "+f.variety:""} · {f.region}{f.zone?" · "+f.zone.label:""}
              </div>
              <div style={{fontSize:10,opacity:0.7,marginTop:1}}>
                🌍 {clim}{sm?" · "+sm.emoji:""}{f.altitude?" · "+f.altitude+"m":""}
                {f.nadas?" · 🌿 "+t.fallow+" "+t.fallowBadge:""}
                {f.seedKg?" · 🌾 "+f.seedKg+"kg":""}
              </div>
            </div>
            <button onClick={()=>setWxVisible(v=>!v)}
              style={{flexShrink:0,background:"rgba(30,120,255,.4)",
                border:"2px solid rgba(100,180,255,.7)",borderRadius:12,
                width:44,height:44,display:"flex",flexDirection:"column",
                alignItems:"center",justifyContent:"center",cursor:"pointer",gap:1}}>
              <span style={{fontSize:18,lineHeight:1}}>⛅</span>
              <span style={{fontSize:8,fontWeight:700,color:"#dbeafe"}}>{wx?(wxVisible?"▲":"▼"):"..."}</span>
            </button>
          </div>

          {/* Stats row */}
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:4,marginBottom:6}}>
            {[[f.size+" "+fUnit,geo.unit],[tasks.length,t.ops],[last,t.days],[safeH?safeH.month+"/"+safeH.day:"—","Harvest"]].map(([val,lbl],i)=>(
              <div key={i} style={{background:"rgba(255,255,255,.18)",borderRadius:8,padding:"5px 3px",textAlign:"center"}}>
                <div style={{fontSize:i===0?9:12,fontWeight:800}}>{val}</div>
                <div style={{fontSize:7,opacity:0.7,marginTop:1}}>{lbl}</div>
              </div>
            ))}
          </div>

          {/* FAO badge */}
          {fao&&(
            <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:4}}>
              {fao.loading
                ?<span style={{fontSize:10,color:"rgba(255,255,255,.8)"}}>⏳ {t.faoLoading}</span>
                :fao.isReal
                  ?<span style={{fontSize:10,fontWeight:700,background:"rgba(34,197,94,.3)",
                    borderRadius:6,padding:"2px 8px",color:"#fff"}}>
                    ✅ FAO {t.realData}{fao.yield?" · "+fao.yield+" kg/ha":""}
                  </span>
                  :fao.isFallback
                    ?<span style={{fontSize:10,fontWeight:700,background:"rgba(59,130,246,.3)",
                      borderRadius:6,padding:"2px 8px",color:"#fff"}}>
                      📊 {t.fallbackData}{fao.yield?" · "+fao.yield+" kg/ha":""}
                    </span>
                    :null
              }
            </div>
          )}

          {/* 14-day weather strip */}
          {wx&&wxVisible&&(
            <div style={{borderTop:"1px solid rgba(255,255,255,.2)",paddingTop:8,marginTop:4}}>
              <div style={{display:"flex",gap:3,overflowX:"auto",paddingBottom:2}}>
                {(wx.time||[]).map((date,i)=>{
                  const mn2=wx.temperature_2m_min?.[i]??10;
                  const mx2=wx.temperature_2m_max?.[i]??20;
                  const rn =wx.precipitation_sum?.[i]??0;
                  const cd =wx.weathercode?.[i]??0;
                  const isTod=i===0;
                  const fA=buildAlerts({min:mn2,max:mx2,rain:rn,wind:wx.windspeed_10m_max?.[i]??10},t);
                  const hC=fA.some(a=>a.sev==="red");
                  const hW=!hC&&fA.some(a=>a.sev==="orange");
                  return(
                    <div key={i} style={{flexShrink:0,width:42,
                      background:hC?"rgba(239,68,68,.35)":hW?"rgba(245,158,11,.3)":isTod?"rgba(255,255,255,.25)":"rgba(255,255,255,.12)",
                      borderRadius:8,padding:"4px 2px",textAlign:"center",
                      border:isTod?"1px solid rgba(255,255,255,.5)":"1px solid rgba(255,255,255,.15)"}}>
                      <div style={{fontSize:6,color:"#fff",opacity:isTod?0.95:0.6,marginBottom:1}}>
                        {isTod?t.today:new Date(date).toLocaleDateString("en",{weekday:"short"})}
                      </div>
                      <div style={{fontSize:16}}>{wxIcon(cd)}</div>
                      <div style={{fontSize:8,fontWeight:800,color:"#fca5a5"}}>{Math.round(mx2)}°</div>
                      <div style={{fontSize:7,color:"#bfdbfe"}}>{Math.round(mn2)}°</div>
                      {rn>0&&<div style={{fontSize:6,color:"#e0f2fe"}}>💧{Math.round(rn)}</div>}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
          {!wx&&wxVisible&&(
            <div style={{fontSize:10,color:"rgba(255,255,255,.7)",textAlign:"center",padding:"8px 0"}}>
              ⏳ {t.noWeatherData}
            </div>
          )}
        </div>

        {/* Fallow/rotation notice */}
        {f.nadas
          ?<div style={{background:"#F0FDF4",border:"2px solid #86EFAC",borderRadius:12,
            padding:"9px 13px",marginBottom:10,display:"flex",alignItems:"center",gap:8}}>
            <span style={{fontSize:22}}>🌿</span>
            <div style={{flex:1}}>
              <div style={{fontSize:11,fontWeight:700,color:"#166534"}}>{t.fallowNote}</div>
              <div style={{fontSize:9,color:"#6B7280"}}>{t.fallowBenefit}</div>
            </div>
            <span style={{fontSize:18,fontWeight:900,color:"#16A34A"}}>+10%</span>
          </div>
          :rc&&<div style={{background:rc.pct<0?"#FFF1F2":"#F0FDF4",
            border:`2px solid ${rc.pct<0?"#FDA4AF":"#86EFAC"}`,
            borderRadius:12,padding:"9px 13px",marginBottom:10,display:"flex",alignItems:"center",gap:8}}>
            <span style={{fontSize:22}}>{rc.icon}</span>
            <div style={{flex:1}}>
              <div style={{fontSize:11,fontWeight:700,color:rc.pct<0?"#9F1239":"#166534"}}>{rc.label}</div>
              <div style={{fontSize:9,color:"#6B7280"}}>📜 {rc.source}</div>
            </div>
            <span style={{fontSize:18,fontWeight:900,color:rc.pct<0?"#DC2626":"#16A34A"}}>{rc.pct>0?"+":""}{rc.pct}%</span>
          </div>
        }

        {isDormNow&&(
          <div style={{background:"#EFF6FF",border:"2px solid #93C5FD",borderRadius:12,
            padding:"8px 13px",marginBottom:10}}>
            <div style={{fontWeight:800,fontSize:12,color:"#1E3A8A"}}>❄️ Dormancy — {dormInfo.label}</div>
          </div>
        )}

        {/* Tab bar */}
        <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:4,marginBottom:10}}>
          {tabs.map(([key,label])=>(
            <button key={key} onClick={()=>setActiveTab(key)}
              style={{background:activeTab===key?"#1C1C1E":"#fff",
                color:activeTab===key?"#fff":"#555",
                border:`1px solid ${activeTab===key?"#1C1C1E":"#E5E5EA"}`,
                borderRadius:10,padding:"7px 2px",fontSize:9,fontWeight:700,
                cursor:"pointer",lineHeight:1.3}}>{label}</button>
          ))}
        </div>

        {/* Tab content */}
        {activeTab==="timeline"&&(
          <div>
            {daysSince>=0&&daysSince<=last&&(
              <div style={{...S.card,padding:"11px 13px",marginBottom:8}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:5}}>
                  <div style={{fontSize:11,fontWeight:700}}>{t.seasonProg}</div>
                  <div style={{fontSize:12,fontWeight:800,color:"#1D4ED8"}}>{progress}%</div>
                </div>
                <div style={{background:"#F2F5F9",borderRadius:99,height:7,overflow:"hidden",marginBottom:5}}>
                  <div style={{width:progress+"%",background:"linear-gradient(90deg,#22C55E,#1D4ED8)",height:"100%",borderRadius:99}}/>
                </div>
                <div style={{display:"flex",justifyContent:"space-between",fontSize:9,color:"#8E8E93"}}>
                  <span>Day {daysSince}</span>
                  {daysToNext!=null&&<span style={{color:"#F59E0B",fontWeight:700}}>⚡ {t.nextTask} {daysToNext}d</span>}
                  <span>{last}d</span>
                </div>
              </div>
            )}
            {tasks.map((task,i)=>(
              <TaskCard key={i} task={task} f={f} sd={sd} daysSince={daysSince} nextTask={nextTask} wx={wx}/>
            ))}
          </div>
        )}
        {activeTab==="cost"   &&<CostTab   f={f}/>}
        {activeTab==="market" &&<MarketTab f={f}/>}
        {activeTab==="soil"   &&<SoilTab   f={f}/>}
        {activeTab==="log"    &&<LogTab    f={f}/>}

        {/* AI button */}
        <button onClick={()=>openAI(f)}
          style={{width:"100%",background:"linear-gradient(135deg,#7C3AED,#6D28D9)",
            border:"none",borderRadius:12,padding:"11px",fontSize:13,fontWeight:700,
            color:"#fff",cursor:"pointer",marginTop:6}}>
          🧑‍🌾 {t.aiAdvisor}
        </button>

        {/* Edit button */}
        <button style={S.editB} onClick={()=>{
          const fd2=fields.find(x=>x.id===f.id);
          setForm({
            name:fd2.name,size:fd2.size,altitude:fd2.altitude||"",crop:fd2.crop,
            variety:fd2.variety||"",region:fd2.region||"",zone:fd2.zone||null,
            d:fd2.d,m:fd2.m,y:fd2.y,parcel:fd2.parcel||"",
            prevCrop:fd2.prevCrop||"",prevYearM:fd2.prevYearM||todayM,
            prevYearY:fd2.prevYearY||String(parseInt(todayY)-1),
            soilType:fd2.soilType||"loamy",nadas:fd2.nadas||false,
            seedKg:fd2.seedKg||"",seedManual:!!fd2.seedKg,
          });
          setErrors([]);navTo("edit",{fieldId:f.id});
        }}>✏️ {t.edit}</button>

        {/* Delete */}
        {confirmDelete===f.id
          ?<div style={{display:"flex",gap:8,marginTop:8}}>
            <button style={{flex:1,background:"#EF4444",border:"none",borderRadius:12,
              padding:"12px",fontSize:13,fontWeight:700,color:"#fff",cursor:"pointer"}}
              onClick={()=>deleteField(f.id)}>✓ Yes</button>
            <button style={{flex:1,background:"#F2F5F9",border:"none",borderRadius:12,
              padding:"12px",fontSize:13,fontWeight:700,color:"#374151",cursor:"pointer"}}
              onClick={()=>setConfirmDelete(null)}>✕ Cancel</button>
          </div>
          :<button style={S.delB} onClick={()=>setConfirmDelete(f.id)}>🗑 {t.deleteField}</button>
        }

        {/* Authority footer */}
        <div style={{background:"#F0F9FF",border:"1px solid #BAE6FD",borderRadius:12,
          padding:"8px 13px",marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
          <div style={{fontSize:10,color:"#0369A1"}}>{fieldAuth.name}</div>
          <div style={{display:"flex",gap:4,alignItems:"center"}}>
            <span style={{fontSize:8,fontWeight:700,color:"#065F46",background:"#DCFCE7",border:"1px solid #86EFAC",borderRadius:4,padding:"1px 5px"}}>FAO</span>
            <span style={{fontSize:8,fontWeight:700,color:"#7F1D1D",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:4,padding:"1px 5px"}}>EPPO</span>
            <span style={{fontSize:8,fontWeight:700,color:"#1E3A8A",background:"#EFF6FF",border:"1px solid #BFDBFE",borderRadius:4,padding:"1px 5px"}}>{fieldAuth.sci}</span>
            <span style={{fontSize:8,fontWeight:700,color:"#92400E",background:"#FFF7ED",border:"1px solid #FED7AA",borderRadius:4,padding:"1px 5px"}}>{fieldAuth.lic}</span>
          </div>
        </div>
      </div>
    );
  }

  // ── MAIN RETURN ────────────────────────────────────────────────────────────
  return(
    <div style={S.wrap}>
      {/* Header */}
      <div style={S.hdr}>
        <button style={S.hBtn} onClick={()=>{setSearchQ("");setModal("country");}}>
          <span>{geo.flag}</span>
          <span style={{fontSize:11,maxWidth:60,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{geo.name}</span>
          <span style={{color:"#C7C7CC",fontSize:10}}>›</span>
        </button>
        <div style={{fontSize:16,fontWeight:700,letterSpacing:-0.4,color:"#1C1C1E"}}>
          Agro<span style={{color:"#34C759"}}>Log</span>{" "}
          <span style={{fontSize:9,color:"#8E8E93",fontWeight:600}}>{APP_VERSION}</span>
        </div>
        <div style={{display:"flex",gap:6,alignItems:"center"}}>
          {globalAlerts.length>0&&(
            <div style={{background:"#EF4444",borderRadius:99,minWidth:18,height:18,
              display:"flex",alignItems:"center",justifyContent:"center",
              fontSize:9,fontWeight:800,color:"#fff",padding:"0 5px"}}>
              {globalAlerts.length}
            </div>
          )}
          {page!=="home"&&(
            <button style={S.hBtn} onClick={()=>{
              if(page==="add")navTo("home");
              else if(page==="edit")navTo("detail",{fieldId:pageParams.fieldId});
              else navTo("home");
            }}>‹ {t.back}</button>
          )}
        </div>
      </div>

      {/* Page content */}
      <div style={S.cont}>
        {page==="home"   && renderHome()}
        {page==="add"    && renderForm(null)}
        {page==="edit"   && renderForm(pageParams.fieldId)}
        {page==="detail" && renderDetail(pageParams.fieldId)}
      </div>

      <ModalView/>
      <AIPanel/>
    </div>
  );
} // ← export default AgroLog son