// ======== COATING PAGE ========
function CoatingPage({proj, coatingDays, setCoatingDays, NavBar}) {
  const [view, setView] = useState("list");
  const [selDayId, setSelDayId] = useState(null);
  const [selRunId, setSelRunId] = useState(null);
  const [selEndType, setSelEndType] = useState(null);
  const [, setTick] = useState(0);

  // Tick every second to drive live run timer
  useEffect(() => {
    const t = setInterval(() => setTick(n => n + 1), 1000);
    return () => clearInterval(t);
  }, []);

  const selDay = coatingDays.find(d=>d.id===selDayId);
  const selRun = selDay?.runs?.find(r=>r.id===selRunId);

  const addDay = () => {
    const id = Date.now();
    const newDay = {id, date:Date.now(), label:`Coating Day ${coatingDays.length+1}`, runs:[]};
    setCoatingDays(prev=>[...prev,newDay]);
    setSelDayId(id); setView("day");
  };

  const addRun = () => {
    const id = Date.now();
    const newRun = {id, runNumber:(selDay.runs?.length||0)+1, launchWeights:[], receiveWeights:[], frontPig:"CCFS", rearPig:"None", launchTime:null, receiveTime:null};
    setCoatingDays(prev=>prev.map(d=>d.id===selDayId?{...d,runs:[...(d.runs||[]),newRun]}:d));
    setSelRunId(id); setSelEndType(null); setView("run");
  };

  const updateRun = (updates) => {
    setCoatingDays(prev=>prev.map(d=>d.id!==selDayId?d:{...d,runs:(d.runs||[]).map(r=>r.id!==selRunId?r:{...r,...updates})}));
  };

  const deleteCoatingRun = (dayId, runId) => {
    setCoatingDays(prev=>prev.map(d=>d.id!==dayId?d:{...d,runs:(d.runs||[]).filter(r=>r.id!==runId)}));
  };

  const deleteCoatingDay = (dayId) => {
    setCoatingDays(prev=>prev.filter(d=>d.id!==dayId));
  };

  const runCalc = (run) => {
    if(!run) return {};
    const lbs_loaded = run.totalLbsLoaded||0;
    const lbs_unloaded = run.totalLbsUnloaded||0;
    const lbs_applied = lbs_loaded - lbs_unloaded;
    const mils = Calc.coatingMils(proj, lbs_applied);
    return { lbs_loaded, lbs_unloaded, lbs_applied, mils };
  };

  const dayCalc = (day) => {
    let tl=0,tu=0;
    (day.runs||[]).forEach(r=>{const c=runCalc(r);tl+=c.lbs_loaded||0;tu+=c.lbs_unloaded||0});
    const ta=tl-tu;
    const mils=Calc.coatingMils(proj,ta);
    return {total_loaded:tl, total_unloaded:tu, total_applied:ta, mils};
  };

  const allDaysCalc = () => {
    let tl=0,tu=0;
    coatingDays.forEach(d=>{const c=dayCalc(d);tl+=c.total_loaded||0;tu+=c.total_unloaded||0});
    const ta=tl-tu;
    const mils=Calc.coatingMils(proj,ta);
    return {total_loaded:tl, total_unloaded:tu, total_applied:ta, mils};
  };

  if(view==="run"&&selRun) {
    const calc=runCalc(selRun);
    const dm=parseFloat(proj.actualID)||parseFloat(proj.diameter)||0;
    const pl=parseFloat(proj.length)||0;
    const sqFt=dm&&pl?(dm/2)*0.5233*pl:null;
    const galsPerMil=sqFt?sqFt/1283:null;
    const lbsPerMil=galsPerMil?galsPerMil*12.35:null;
    return (
      <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:80}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
          <button onClick={()=>setView("day")} style={{...S.bs,padding:"8px 14px",fontSize:12,width:"auto"}}>← Day</button>
          <div style={{fontSize:14,fontWeight:800,color:"var(--accent)"}}>Run #{selRun.runNumber}</div>
          <div style={{fontSize:11,color:"var(--muted)"}}>{selDay?.label}</div>
        </div>

        {/* Pig selectors */}
        <div style={{...S.card,marginBottom:8}}>
          <div style={S.ct}>Pig Configuration</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
            <div>
              <label style={S.lb}>Front Pig</label>
              <select value={selRun.frontPig||"CCFS"} onChange={e=>updateRun({frontPig:e.target.value})} style={{...S.inp,fontSize:13}}>
                {PIG_OPTIONS.map(p=><option key={p} value={p}>{p}</option>)}
              </select>
            </div>
            <div>
              <label style={S.lb}>Rear Pig</label>
              <select value={selRun.rearPig||"None"} onChange={e=>updateRun({rearPig:e.target.value})} style={{...S.inp,fontSize:13}}>
                {PIG_OPTIONS.map(p=><option key={p} value={p}>{p}</option>)}
              </select>
            </div>
          </div>
        </div>

        {/* Launch / Receive time buttons */}
        {(()=>{
          // Parse a "HH:MM" or "H:MM AM/PM" string into a today-based timestamp
          const parseTimeInput = (str) => {
            if(!str) return null;
            const now = new Date();
            // Try 24h first: HH:MM or HH:MM:SS
            let m = str.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
            if(m) {
              const d = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(m[1]), parseInt(m[2]), parseInt(m[3]||0));
              return isNaN(d.getTime()) ? null : d.getTime();
            }
            // Try 12h: H:MM AM/PM
            m = str.match(/^(\d{1,2}):(\d{2})\s*(am|pm)$/i);
            if(m) {
              let hr = parseInt(m[1]);
              const mn = parseInt(m[2]);
              const isPm = m[3].toLowerCase()==="pm";
              if(isPm && hr!==12) hr+=12;
              if(!isPm && hr===12) hr=0;
              const d = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hr, mn, 0);
              return isNaN(d.getTime()) ? null : d.getTime();
            }
            return null;
          };
          const toTimeInput = (ts) => {
            if(!ts) return "";
            const d = new Date(ts);
            return `${String(d.getHours()).padStart(2,"0")}:${String(d.getMinutes()).padStart(2,"0")}`;
          };
          const isRunning = selRun.launchTime && !selRun.receiveTime;
          const elapsed = selRun.launchTime ? (isRunning ? Date.now() - selRun.launchTime : (selRun.receiveTime - selRun.launchTime)) : 0;
          const h = Math.floor(elapsed/3600000), mm = Math.floor((elapsed%3600000)/60000), ss = Math.floor((elapsed%60000)/1000);
          const hhmm = `${String(h).padStart(2,"0")}:${String(mm).padStart(2,"0")}:${String(ss).padStart(2,"0")}`;
          return (
            <div style={{...S.card,marginBottom:8}}>
              <div style={S.ct}>Run Timing</div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
                <div>
                  {!selRun.launchTime
                    ? <button onClick={()=>updateRun({launchTime:Date.now()})} style={{...S.bp,padding:"14px 10px",fontSize:13}}>🚀 Launch</button>
                    : <div style={{textAlign:"center",background:"rgba(0,230,118,0.08)",border:"1px solid rgba(0,230,118,0.3)",borderRadius:12,padding:"12px 8px"}}>
                        <div style={{fontSize:9,color:"#00e676",fontWeight:800,textTransform:"uppercase",marginBottom:2}}>Launched</div>
                        <div style={{fontSize:13,fontWeight:900,color:"#00e676",fontFamily:"var(--mono)"}}>{Fmt.timeShort(selRun.launchTime)}</div>
                        <button onClick={()=>updateRun({launchTime:null})} style={{fontSize:10,color:"var(--muted)",background:"none",border:"none",cursor:"pointer",marginTop:4}}>Reset</button>
                      </div>
                  }
                </div>
                <div>
                  {!selRun.receiveTime
                    ? <button onClick={()=>updateRun({receiveTime:Date.now()})} disabled={!selRun.launchTime} style={{...S.bp,padding:"14px 10px",fontSize:13,opacity:selRun.launchTime?1:0.4,background:selRun.launchTime?"linear-gradient(135deg,var(--accent),var(--accent2))":"rgba(0,0,0,0.05)"}}>📥 Receive</button>
                    : <div style={{textAlign:"center",background:"rgba(255,165,0,0.08)",border:"1px solid rgba(255,165,0,0.3)",borderRadius:12,padding:"12px 8px"}}>
                        <div style={{fontSize:9,color:"var(--accent)",fontWeight:800,textTransform:"uppercase",marginBottom:2}}>Received</div>
                        <div style={{fontSize:13,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{Fmt.timeShort(selRun.receiveTime)}</div>
                        <button onClick={()=>updateRun({receiveTime:null})} style={{fontSize:10,color:"var(--muted)",background:"none",border:"none",cursor:"pointer",marginTop:4}}>Reset</button>
                      </div>
                  }
                </div>
              </div>

              {/* Manual time entry row */}
              <div style={{marginTop:10,display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
                <div>
                  <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Manual Launch Time</div>
                  <input type="time" defaultValue={toTimeInput(selRun.launchTime)}
                    key={"lt-"+selRun.launchTime}
                    onBlur={ev=>{const ts=parseTimeInput(ev.target.value); if(ts) updateRun({launchTime:ts});}}
                    style={{...S.inp,fontSize:14,textAlign:"center",fontFamily:"var(--mono)",fontWeight:700}} />
                </div>
                <div>
                  <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Manual Receive Time</div>
                  <input type="time" defaultValue={toTimeInput(selRun.receiveTime)}
                    key={"rt-"+selRun.receiveTime}
                    onBlur={ev=>{const ts=parseTimeInput(ev.target.value); if(ts) updateRun({receiveTime:ts});}}
                    style={{...S.inp,fontSize:14,textAlign:"center",fontFamily:"var(--mono)",fontWeight:700}} />
                </div>
              </div>
              <div style={{fontSize:9,color:"var(--dim)",textAlign:"center",marginTop:4}}>Use time pickers above to correct or backfill times</div>

              {/* Live / final timer display */}
              {selRun.launchTime&&<div style={{marginTop:10,textAlign:"center",background:isRunning?"rgba(0,230,118,0.06)":"rgba(255,165,0,0.06)",border:`1px solid ${isRunning?"rgba(0,230,118,0.25)":"rgba(255,165,0,0.25)"}`,borderRadius:12,padding:"10px 16px"}}>
                <div style={{fontSize:9,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.08em",color:isRunning?"#00e676":"var(--accent)",marginBottom:3}}>
                  {isRunning?"⏱ Live Timer":"✓ Run Time"}
                </div>
                <div style={{fontSize:28,fontWeight:900,fontFamily:"var(--mono)",color:isRunning?"#00e676":"var(--accent)",letterSpacing:"0.05em"}}>
                  {hhmm}
                </div>
                {isRunning&&<div style={{fontSize:9,color:"var(--muted)",marginTop:2,fontWeight:600}}>running…</div>}
                {!isRunning&&selRun.receiveTime&&pl>0&&elapsed>0&&(()=>{
                  const elapsedSec = elapsed / 1000;
                  const fps = pl / elapsedSec;
                  return (
                    <div style={{marginTop:8,paddingTop:8,borderTop:"1px solid rgba(255,165,0,0.2)"}}>
                      <div style={{fontSize:9,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.08em",color:"var(--muted)",marginBottom:2}}>Speed</div>
                      <div style={{fontSize:20,fontWeight:900,fontFamily:"var(--mono)",color:"var(--accent)"}}>
                        {fps.toFixed(2)} <span style={{fontSize:11,fontWeight:600}}>ft/sec</span>
                      </div>
                      <div style={{fontSize:9,color:"var(--muted)",marginTop:1}}>{pl.toLocaleString()} ft pipeline</div>
                    </div>
                  );
                })()}
              </div>}
            </div>
          );
        })()}

        {/* Pipe/coating metrics */}
        {(sqFt||galsPerMil||lbsPerMil)&&<div style={{...S.card,marginBottom:8,background:"rgba(255,165,0,0.04)",border:"1px solid rgba(255,165,0,0.15)"}}>
          <div style={S.ct}>Coating Metrics (Actual ID)</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"8px 12px"}}>
            {[["Sq Footage",sqFt?sqFt.toFixed(1)+" ft²":"N/A"],["Gals / Mil",galsPerMil?galsPerMil.toFixed(3):"N/A"],["Lbs / Mil",lbsPerMil?lbsPerMil.toFixed(2):"N/A"]].map(([l,v])=>(
              <div key={l}><div style={S.rl}>{l}</div><div style={S.rv}>{v}</div></div>
            ))}
          </div>
        </div>}

        <div style={{...S.card,padding:"8px 12px",marginBottom:8,display:"flex",gap:8}}>
          <button onClick={()=>setSelEndType("launch")} style={{...(selEndType==="launch"?S.bp:S.bs),flex:1,padding:"10px 12px",fontSize:13}}>⚖️ Launch Weight</button>
          <button onClick={()=>setSelEndType("receive")} style={{...(selEndType==="receive"?S.bp:S.bs),flex:1,padding:"10px 12px",fontSize:13}}>⚖️ Receive Weight</button>
        </div>

        {selEndType==="launch"&&(()=>{
          const entries = selRun.launchScaleEntries || [];
          const autoTotal = entries.reduce((sum,e)=>{
            const pre=parseFloat(e.pre)||0, post=parseFloat(e.post)||0;
            return sum+(pre-post);
          },0);
          const usingManual = selRun.launchTotalManual === true;
          const addEntry = () => {
            const newEntries=[...entries,{id:Date.now(),pre:"",post:"",label:`Item ${entries.length+1}`}];
            updateRun({launchScaleEntries:newEntries,launchTotalManual:false,totalLbsLoaded:0});
          };
          const updateEntryNumeric = (id,field,val) => {
            const updated=entries.map(e=>e.id===id?{...e,[field]:val}:e);
            const newTotal=updated.reduce((sum,e)=>{const pr=parseFloat(e.pre)||0,po=parseFloat(e.post)||0;return sum+(pr-po);},0);
            updateRun({launchScaleEntries:updated,launchTotalManual:false,totalLbsLoaded:Math.max(0,newTotal)});
          };
          const updateEntryLabel = (id,val) => {
            const updated=entries.map(e=>e.id===id?{...e,label:val}:e);
            updateRun({launchScaleEntries:updated});
          };
          const removeEntry = (id) => {
            const updated=entries.filter(e=>e.id!==id);
            const newTotal=updated.reduce((sum,e)=>{const pr=parseFloat(e.pre)||0,po=parseFloat(e.post)||0;return sum+(pr-po);},0);
            updateRun({launchScaleEntries:updated,launchTotalManual:false,totalLbsLoaded:Math.max(0,newTotal)});
          };
          return (
            <div style={S.card}>
              <div style={S.ct}>Launch End — Pre/Post Scale</div>
              {entries.map(e=>(
                <div key={e.id} style={{background:"var(--highlight)",borderRadius:10,padding:"10px 12px",marginBottom:8}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8}}>
                    <input value={e.label} onChange={ev=>updateEntryLabel(e.id,ev.target.value)}
                      style={{...S.inp,width:"auto",flex:1,fontSize:12,padding:"4px 8px",marginRight:8}} />
                    <button onClick={()=>removeEntry(e.id)} style={{background:"rgba(255,23,68,0.12)",border:"1px solid rgba(255,23,68,0.3)",borderRadius:8,color:"#ff1744",fontSize:11,fontWeight:800,padding:"4px 10px",cursor:"pointer",fontFamily:"var(--font)"}}>✕</button>
                  </div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,alignItems:"end"}}>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Pre (lbs)</div>
                      <input type="number" inputMode="decimal" value={e.pre} onChange={ev=>updateEntryNumeric(e.id,"pre",ev.target.value)}
                        style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:800}} placeholder="0" />
                    </div>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Post (lbs)</div>
                      <input type="number" inputMode="decimal" value={e.post} onChange={ev=>updateEntryNumeric(e.id,"post",ev.target.value)}
                        style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:800}} placeholder="0" />
                    </div>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"#00e676",textTransform:"uppercase",marginBottom:4}}>Loaded</div>
                      <div style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:900,color:"#00e676",background:"rgba(0,230,118,0.06)",border:"1px solid rgba(0,230,118,0.2)"}}>
                        {Math.max(0,(parseFloat(e.pre)||0)-(parseFloat(e.post)||0)).toLocaleString()}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              <button onClick={addEntry} style={{...S.bs,width:"100%",marginBottom:10,fontSize:13}}>+ Add Item</button>
              <div style={{background:"var(--highlight)",borderRadius:10,padding:"10px 12px",marginBottom:4}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                  <div style={{fontSize:10,fontWeight:800,textTransform:"uppercase",color:"var(--muted)"}}>Add Total (lbs)</div>
                  {entries.length>0&&<button onClick={()=>updateRun({launchTotalManual:!usingManual,totalLbsLoaded:usingManual?Math.max(0,autoTotal):(selRun.totalLbsLoaded||0)})}
                    style={{fontSize:10,padding:"3px 8px",borderRadius:6,border:"1px solid var(--border)",background:"transparent",color:"var(--muted)",cursor:"pointer",fontFamily:"var(--font)"}}>
                    {usingManual?"← Use entries":"✏ Enter manually"}
                  </button>}
                </div>
                <input type="number" inputMode="decimal"
                  value={usingManual?(selRun.totalLbsLoaded||""):(entries.length>0?Math.max(0,autoTotal)||"":selRun.totalLbsLoaded||"")}
                  readOnly={!usingManual&&entries.length>0}
                  onChange={e=>{if(usingManual||entries.length===0) updateRun({launchTotalManual:true,totalLbsLoaded:parseFloat(e.target.value)||0});}}
                  onClick={()=>{if(entries.length===0) updateRun({launchTotalManual:true});}}
                  style={{...S.inp,fontSize:24,textAlign:"center",fontFamily:"var(--mono)",fontWeight:900,
                    background:(usingManual||entries.length===0)?"":"rgba(255,165,0,0.04)",
                    color:(usingManual||entries.length===0)?"var(--text)":"var(--accent)",
                    border:(usingManual||entries.length===0)?"1px solid var(--border)":"1px solid rgba(255,165,0,0.3)",
                    cursor:(!usingManual&&entries.length>0)?"default":"text"}}
                  placeholder="0" />
                {!usingManual&&entries.length>0&&<div style={{fontSize:9,color:"var(--muted)",textAlign:"center",marginTop:3}}>Auto-calculated from entries above</div>}
                {(usingManual||entries.length===0)&&<div style={{fontSize:9,color:"var(--muted)",textAlign:"center",marginTop:3}}>Tap to enter total directly</div>}
              </div>
              <div style={{marginTop:8,background:"rgba(255,165,0,0.06)",border:"1px solid rgba(255,165,0,0.2)",borderRadius:10,padding:"12px 16px",textAlign:"center"}}>
                <div style={{fontSize:10,color:"var(--muted)",textTransform:"uppercase"}}>Total Pounds Loaded</div>
                <div style={{fontSize:32,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{(selRun.totalLbsLoaded||0).toLocaleString()} lbs</div>
              </div>
            </div>
          );
        })()}

        {selEndType==="receive"&&(()=>{
          const entries = selRun.receiveScaleEntries || [];
          const autoTotal = entries.reduce((sum,e)=>{
            const pre=parseFloat(e.pre)||0, post=parseFloat(e.post)||0;
            return sum+(post-pre);
          },0);
          const usingManual = selRun.receiveTotalManual === true;
          const addEntry = () => {
            const newEntries=[...entries,{id:Date.now(),pre:"",post:"",label:`Item ${entries.length+1}`}];
            updateRun({receiveScaleEntries:newEntries,receiveTotalManual:false,totalLbsUnloaded:0});
          };
          const updateEntryNumeric = (id,field,val) => {
            const updated=entries.map(e=>e.id===id?{...e,[field]:val}:e);
            const newTotal=updated.reduce((sum,e)=>{const pr=parseFloat(e.pre)||0,po=parseFloat(e.post)||0;return sum+(po-pr);},0);
            updateRun({receiveScaleEntries:updated,receiveTotalManual:false,totalLbsUnloaded:Math.max(0,newTotal)});
          };
          const updateEntryLabel = (id,val) => {
            const updated=entries.map(e=>e.id===id?{...e,label:val}:e);
            updateRun({receiveScaleEntries:updated});
          };
          const removeEntry = (id) => {
            const updated=entries.filter(e=>e.id!==id);
            const newTotal=updated.reduce((sum,e)=>{const pr=parseFloat(e.pre)||0,po=parseFloat(e.post)||0;return sum+(po-pr);},0);
            updateRun({receiveScaleEntries:updated,receiveTotalManual:false,totalLbsUnloaded:Math.max(0,newTotal)});
          };
          return (
            <div style={S.card}>
              <div style={S.ct}>Receiving End — Pre/Post Scale</div>
              {entries.map(e=>(
                <div key={e.id} style={{background:"var(--highlight)",borderRadius:10,padding:"10px 12px",marginBottom:8}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8}}>
                    <input value={e.label} onChange={ev=>updateEntryLabel(e.id,ev.target.value)}
                      style={{...S.inp,width:"auto",flex:1,fontSize:12,padding:"4px 8px",marginRight:8}} />
                    <button onClick={()=>removeEntry(e.id)} style={{background:"rgba(255,23,68,0.12)",border:"1px solid rgba(255,23,68,0.3)",borderRadius:8,color:"#ff1744",fontSize:11,fontWeight:800,padding:"4px 10px",cursor:"pointer",fontFamily:"var(--font)"}}>✕</button>
                  </div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,alignItems:"end"}}>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Pre (lbs)</div>
                      <input type="number" inputMode="decimal" value={e.pre} onChange={ev=>updateEntryNumeric(e.id,"pre",ev.target.value)}
                        style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:800}} placeholder="0" />
                    </div>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"var(--muted)",textTransform:"uppercase",marginBottom:4}}>Post (lbs)</div>
                      <input type="number" inputMode="decimal" value={e.post} onChange={ev=>updateEntryNumeric(e.id,"post",ev.target.value)}
                        style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:800}} placeholder="0" />
                    </div>
                    <div>
                      <div style={{fontSize:9,fontWeight:700,color:"#00e676",textTransform:"uppercase",marginBottom:4}}>Unloaded</div>
                      <div style={{...S.inp,fontSize:16,textAlign:"center",fontFamily:"var(--mono)",fontWeight:900,color:"#00e676",background:"rgba(0,230,118,0.06)",border:"1px solid rgba(0,230,118,0.2)"}}>
                        {Math.max(0,(parseFloat(e.post)||0)-(parseFloat(e.pre)||0)).toLocaleString()}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              <button onClick={addEntry} style={{...S.bs,width:"100%",marginBottom:10,fontSize:13}}>+ Add Item</button>
              <div style={{background:"var(--highlight)",borderRadius:10,padding:"10px 12px",marginBottom:4}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                  <div style={{fontSize:10,fontWeight:800,textTransform:"uppercase",color:"var(--muted)"}}>Add Total (lbs)</div>
                  {entries.length>0&&<button onClick={()=>updateRun({receiveTotalManual:!usingManual,totalLbsUnloaded:usingManual?Math.max(0,autoTotal):(selRun.totalLbsUnloaded||0)})}
                    style={{fontSize:10,padding:"3px 8px",borderRadius:6,border:"1px solid var(--border)",background:"transparent",color:"var(--muted)",cursor:"pointer",fontFamily:"var(--font)"}}>
                    {usingManual?"← Use entries":"✏ Enter manually"}
                  </button>}
                </div>
                <input type="number" inputMode="decimal"
                  value={usingManual?(selRun.totalLbsUnloaded||""):(entries.length>0?Math.max(0,autoTotal)||"":selRun.totalLbsUnloaded||"")}
                  readOnly={!usingManual&&entries.length>0}
                  onChange={e=>{if(usingManual||entries.length===0) updateRun({receiveTotalManual:true,totalLbsUnloaded:parseFloat(e.target.value)||0});}}
                  onClick={()=>{if(entries.length===0) updateRun({receiveTotalManual:true});}}
                  style={{...S.inp,fontSize:24,textAlign:"center",fontFamily:"var(--mono)",fontWeight:900,
                    background:(usingManual||entries.length===0)?"":"rgba(255,165,0,0.04)",
                    color:(usingManual||entries.length===0)?"var(--text)":"var(--accent)",
                    border:(usingManual||entries.length===0)?"1px solid var(--border)":"1px solid rgba(255,165,0,0.3)",
                    cursor:(!usingManual&&entries.length>0)?"default":"text"}}
                  placeholder="0" />
                {!usingManual&&entries.length>0&&<div style={{fontSize:9,color:"var(--muted)",textAlign:"center",marginTop:3}}>Auto-calculated from entries above</div>}
                {(usingManual||entries.length===0)&&<div style={{fontSize:9,color:"var(--muted)",textAlign:"center",marginTop:3}}>Tap to enter total directly</div>}
              </div>
              <div style={{marginTop:8,background:"rgba(255,165,0,0.06)",border:"1px solid rgba(255,165,0,0.2)",borderRadius:10,padding:"12px 16px",textAlign:"center"}}>
                <div style={{fontSize:10,color:"var(--muted)",textTransform:"uppercase"}}>Total Pounds Unloaded</div>
                <div style={{fontSize:32,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{(selRun.totalLbsUnloaded||0).toLocaleString()} lbs</div>
              </div>
            </div>
          );
        })()}

        {(calc.lbs_loaded>0||calc.lbs_unloaded>0)&&<div style={{...S.card,background:"linear-gradient(135deg,rgba(255,165,0,0.06),rgba(255,109,0,0.04))",border:"1px solid rgba(255,165,0,0.2)"}}>
          <div style={S.ct}>Run #{selRun.runNumber} Results</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px 16px"}}>
            {[["Lbs Loaded",(calc.lbs_loaded||0).toLocaleString()+" lbs"],["Lbs Unloaded",(calc.lbs_unloaded||0).toLocaleString()+" lbs"],["Lbs Applied",(calc.lbs_applied||0).toLocaleString()+" lbs"],["Sq Ft",calc.mils?calc.mils.sqFt+" ft²":"N/A"],["Gals / Mil",galsPerMil?galsPerMil.toFixed(3):"N/A"],["Lbs / Mil",lbsPerMil?lbsPerMil.toFixed(2):"N/A"],["Mils Applied",calc.mils?calc.mils.mils+" mils":"N/A"]].map(([l,v])=>(
              <div key={l}><div style={S.rl}>{l}</div><div style={S.rv}>{v}</div></div>
            ))}
          </div>
        </div>}
      </div>
    );
  }

  if(view==="day"&&selDay) {
    const dc=dayCalc(selDay);
    return (
      <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:80}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
          <button onClick={()=>setView("list")} style={{...S.bs,padding:"8px 14px",fontSize:12,width:"auto"}}>← Days</button>
          <div style={{fontSize:14,fontWeight:800}}>{selDay.label}</div>
          <div style={{fontSize:11,color:"var(--muted)"}}>{Fmt.date(selDay.date)}</div>
        </div>

        <button onClick={addRun} style={{...S.bp,marginBottom:16}}>+ Add Run</button>

        {(selDay.runs||[]).length===0&&<div style={{textAlign:"center",padding:24,color:"var(--dim)"}}>No runs yet</div>}
        {(selDay.runs||[]).map(r=>{
          const rc=runCalc(r);
          return (
            <SwipeRow key={r.id} onDelete={()=>deleteCoatingRun(selDayId,r.id)}>
              <div onClick={()=>{setSelRunId(r.id);setSelEndType(null);setView("run")}} style={{...S.card,cursor:"pointer",marginBottom:0,borderRadius:14}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:6}}>
                  <span style={{fontWeight:800,color:"var(--accent)"}}>Run #{r.runNumber}</span>
                  <span style={{fontSize:11,color:"var(--muted)"}}>{(r.launchWeights||[]).length} launch · {(r.receiveWeights||[]).length} receive sets</span>
                </div>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"4px 12px"}}>
                  {[["Lbs Loaded",(rc.lbs_loaded||0).toLocaleString()],["Lbs Applied",(rc.lbs_applied||0).toLocaleString()],["Mils",rc.mils?rc.mils.mils:"—"]].map(([l,v])=>(
                    <div key={l}><div style={S.rl}>{l}</div><div style={{...S.rv,fontSize:13}}>{v}</div></div>
                  ))}
                </div>
              </div>
            </SwipeRow>
          );
        })}

        {(selDay.runs||[]).length>0&&<div style={{...S.card,background:"linear-gradient(135deg,rgba(255,165,0,0.06),rgba(255,109,0,0.04))",border:"1px solid rgba(255,165,0,0.2)",marginTop:8}}>
          <div style={S.ct}>Day Totals</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"10px 16px"}}>
            {[["Total Loaded",dc.total_loaded.toLocaleString()+" lbs"],["Total Unloaded",dc.total_unloaded.toLocaleString()+" lbs"],["Total Applied",dc.total_applied.toLocaleString()+" lbs"],["Sq Ft",dc.mils?dc.mils.sqFt+" ft²":"N/A"],["Lbs/Mil",dc.mils?dc.mils.lbsPerMil:"N/A"],["Mils Applied",dc.mils?dc.mils.mils+" mils":"—"]].map(([l,v])=>(
              <div key={l}><div style={S.rl}>{l}</div><div style={S.rv}>{v}</div></div>
            ))}
          </div>
        </div>}
      </div>
    );
  }

  if(view==="report") {
    return <CoatingReportView proj={proj} coatingDays={coatingDays} onBack={()=>setView("list")} />;
  }

  const overall=allDaysCalc();
  return (
    <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:80}}>
      <div style={{fontSize:16,fontWeight:900,fontFamily:"var(--display)",textAlign:"center",marginBottom:16}}>COATING</div>

      <button onClick={addDay} style={{...S.bp,marginBottom:16}}>+ Add Coating Day</button>

      {coatingDays.length===0&&<div style={{textAlign:"center",padding:32,color:"var(--dim)"}}>No coating days yet</div>}

      {coatingDays.map(d=>{
        const dc=dayCalc(d);
        return (
          <SwipeRow key={d.id} onDelete={()=>deleteCoatingDay(d.id)}>
            <div onClick={()=>{setSelDayId(d.id);setView("day")}} style={{...S.card,cursor:"pointer",marginBottom:0,borderRadius:14}}>
              <div style={{display:"flex",justifyContent:"space-between",marginBottom:8}}>
                <span style={{fontWeight:800,color:"var(--accent)",fontSize:14}}>{d.label}</span>
                <span style={{fontSize:11,color:"var(--muted)"}}>{Fmt.date(d.date)} · {(d.runs||[]).length} runs</span>
              </div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"4px 12px"}}>
                {[["Lbs Loaded",dc.total_loaded.toLocaleString()],["Lbs Applied",dc.total_applied.toLocaleString()],["Mils",dc.mils?dc.mils.mils:"—"]].map(([l,v])=>(
                  <div key={l}><div style={S.rl}>{l}</div><div style={{...S.rv,fontSize:13}}>{v}</div></div>
                ))}
              </div>
            </div>
          </SwipeRow>
        );
      })}

      {coatingDays.length>0&&<div style={{...S.card,background:"linear-gradient(135deg,rgba(255,165,0,0.06),rgba(255,109,0,0.04))",border:"1px solid rgba(255,165,0,0.2)",marginTop:8}}>
        <div style={S.ct}>Total Coating Results</div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"10px 16px"}}>
          {[["Total Loaded",overall.total_loaded.toLocaleString()+" lbs"],["Total Unloaded",overall.total_unloaded.toLocaleString()+" lbs"],["Total Applied",overall.total_applied.toLocaleString()+" lbs"],["Sq Ft",overall.mils?overall.mils.sqFt+" ft²":"N/A"],["Lbs/Mil",overall.mils?overall.mils.lbsPerMil:"N/A"],["Total Mils",overall.mils?overall.mils.mils+" mils":"—"]].map(([l,v])=>(
            <div key={l}><div style={S.rl}>{l}</div><div style={S.rv}>{v}</div></div>
          ))}
        </div>
        <button onClick={()=>setView("report")} style={{...S.bp,marginTop:14,fontSize:13}}>🖨 Coating Report</button>
      </div>}
    </div>
  );
}

// ---- Coating Report Print View ----
function CoatingReportView({proj, coatingDays, onBack}) {
  const avgOf = (vals) => { const ns=vals.map(v=>parseFloat(v)).filter(v=>!isNaN(v)); return ns.length>0?(ns.reduce((a,b)=>a+b,0)/ns.length):null; };
  const runCalcR = (run) => {
    const lbs_loaded = run.totalLbsLoaded||0;
    const lbs_unloaded = run.totalLbsUnloaded||0;
    const lbs_applied = lbs_loaded - lbs_unloaded;
    const mils = Calc.coatingMils(proj, lbs_applied);
    return { lbs_loaded, lbs_unloaded, lbs_applied, mils };
  };
  const dayCalcR = (day) => {
    let tl=0,tu=0;
    (day.runs||[]).forEach(r=>{const c=runCalcR(r);tl+=c.lbs_loaded||0;tu+=c.lbs_unloaded||0});
    const ta=tl-tu;
    const mils=Calc.coatingMils(proj,ta);
    return {tl,tu,ta,mils};
  };
  const overall = () => {
    let tl=0,tu=0;
    coatingDays.forEach(d=>{const c=dayCalcR(d);tl+=c.tl||0;tu+=c.tu||0});
    const ta=tl-tu;
    const mils=Calc.coatingMils(proj,ta);
    return {tl,tu,ta,mils};
  };
  const ov = overall();
  const dm = parseFloat(proj.diameter)||0;  // Fix 1: use reference diameter, not actualID
  const pl = parseFloat(proj.length)||0;
  const printStyle = `
    @media print {
      body { margin: 0; padding: 0; background: white !important; color: black !important; }
      .no-print { display: none !important; }
      .print-page { max-width: 100% !important; padding: 12px !important; }
    }
    .rpt-tbl { width:100%; border-collapse:collapse; font-size:11px; margin-bottom:6px; }
    .rpt-tbl th { background:#222; color:white; padding:4px 6px; text-align:left; font-weight:700; font-size:10px; }
    .rpt-tbl td { padding:4px 6px; border-bottom:1px solid #ddd; vertical-align:top; }
    .rpt-tbl tr:nth-child(even) td { background:#f7f7f7; }
    .rpt-tbl tfoot td { background:#eee; font-weight:800; border-top:2px solid #333; }
    .sect-hdr { background:#333; color:white; font-weight:900; font-size:11px; padding:5px 8px; margin:10px 0 0 0; border-radius:4px 4px 0 0; }
    .ov-grid { display:grid; grid-template-columns:repeat(6,1fr); gap:6px; margin:8px 0; }
    .ov-cell { border:1px solid #ccc; padding:6px 4px; text-align:center; border-radius:4px; }
    .ov-lbl { font-size:8px; color:#666; text-transform:uppercase; font-weight:700; }
    .ov-val { font-size:13px; font-weight:900; color:#111; }
  `;
  const handlePrint = () => window.print();
  return (
    <div className="print-page" style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",background:"#fff",color:"#111"}}>
      <style>{printStyle}</style>
      <div className="no-print" style={{display:"flex",gap:8,marginBottom:14}}>
        <button onClick={onBack} style={{...S.bs,padding:"8px 14px",fontSize:12,width:"auto"}}>← Back</button>
        <button onClick={handlePrint} style={{...S.bp,flex:1,fontSize:13}}>🖨 Print / Save PDF</button>
      </div>

      {/* Header */}
      <div style={{borderBottom:"3px solid #222",paddingBottom:8,marginBottom:10}}>
        <div style={{fontSize:18,fontWeight:900,color:"#111",letterSpacing:"0.05em"}}>COATING REPORT</div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"4px 12px",marginTop:6,fontSize:11}}>
          {[["Client",proj.client||"—"],["Location",proj.location||"—"],["Project #",proj.projectNumber||"—"],["Job #",proj.jobNumber||"—"],["Diameter",dm?dm+'"':"—"],["Length",pl?pl.toLocaleString()+" ft":"—"],["Product",proj.productType||"—"],["Date",new Date().toLocaleDateString()]].map(([l,v])=>(
            <div key={l}><span style={{fontSize:9,fontWeight:700,color:"#666",textTransform:"uppercase"}}>{l}: </span><span style={{fontWeight:700}}>{v}</span></div>
          ))}
        </div>
      </div>

      {/* Overall Totals */}
      <div style={{marginBottom:12}}>
        <div className="sect-hdr">OVERALL TOTALS — {coatingDays.length} Day{coatingDays.length!==1?"s":""} · {coatingDays.reduce((s,d)=>(s+(d.runs||[]).length),0)} Runs</div>
        <div style={{border:"1px solid #ccc",borderTop:"none",padding:"8px",borderRadius:"0 0 4px 4px"}}>
          <div className="ov-grid">
            {[["Total Loaded",(ov.tl||0).toLocaleString()+" lbs"],["Total Unloaded",(ov.tu||0).toLocaleString()+" lbs"],["Total Applied",(ov.ta||0).toLocaleString()+" lbs"],["Sq Footage",ov.mils?ov.mils.sqFt+" ft²":"N/A"],["Lbs / Mil",ov.mils?ov.mils.lbsPerMil:"N/A"],["Total Mils",ov.mils?ov.mils.mils+" mils":"—"]].map(([l,v])=>(
              <div key={l} className="ov-cell"><div className="ov-lbl">{l}</div><div className="ov-val" style={{fontSize:v.length>8?10:13}}>{v}</div></div>
            ))}
          </div>
        </div>
      </div>

      {/* Per-Day Breakdown — Fix 2: no sub-rows, just run totals */}
      {coatingDays.map((day,di)=>{
        const dc=dayCalcR(day);
        return (
          <div key={day.id} style={{marginBottom:12,pageBreakInside:"avoid"}}>
            <div className="sect-hdr">{day.label} — {Fmt.date(day.date)} — {(day.runs||[]).length} Run{(day.runs||[]).length!==1?"s":""}</div>
            <div style={{border:"1px solid #ccc",borderTop:"none",borderRadius:"0 0 4px 4px",overflow:"hidden"}}>
              {(day.runs||[]).length===0
                ? <div style={{padding:"8px 10px",fontSize:11,color:"#888",fontStyle:"italic"}}>No runs recorded</div>
                : <table className="rpt-tbl">
                    <thead><tr>
                      <th>Run</th><th>Front Pig</th><th>Rear Pig</th><th>Launch</th><th>Receive</th><th>Duration</th><th style={{textAlign:"right"}}>Loaded (lbs)</th><th style={{textAlign:"right"}}>Unloaded (lbs)</th><th style={{textAlign:"right"}}>Applied (lbs)</th><th style={{textAlign:"right"}}>Mils</th>
                    </tr></thead>
                    <tbody>
                      {(day.runs||[]).map(r=>{
                        const rc=runCalcR(r);
                        const dur = (r.launchTime&&r.receiveTime) ? Fmt.duration(r.receiveTime-r.launchTime) : "—";
                        return (
                          <tr key={r.id}>
                            <td style={{fontWeight:900}}>#{r.runNumber}</td>
                            <td>{r.frontPig||"—"}</td>
                            <td>{r.rearPig||"—"}</td>
                            <td style={{fontFamily:"monospace"}}>{r.launchTime?Fmt.timeShort(r.launchTime):"—"}</td>
                            <td style={{fontFamily:"monospace"}}>{r.receiveTime?Fmt.timeShort(r.receiveTime):"—"}</td>
                            <td style={{fontFamily:"monospace"}}>{dur}</td>
                            <td style={{textAlign:"right",fontFamily:"monospace"}}>{(rc.lbs_loaded||0).toLocaleString()}</td>
                            <td style={{textAlign:"right",fontFamily:"monospace"}}>{(rc.lbs_unloaded||0).toLocaleString()}</td>
                            <td style={{textAlign:"right",fontFamily:"monospace",fontWeight:800}}>{(rc.lbs_applied||0).toLocaleString()}</td>
                            <td style={{textAlign:"right",fontFamily:"monospace",fontWeight:900}}>{rc.mils?rc.mils.mils:"—"}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                    <tfoot><tr>
                      <td colSpan={6} style={{fontWeight:900,fontSize:11}}>Day Totals</td>
                      <td style={{textAlign:"right",fontFamily:"monospace"}}>{(dc.tl||0).toLocaleString()}</td>
                      <td style={{textAlign:"right",fontFamily:"monospace"}}>{(dc.tu||0).toLocaleString()}</td>
                      <td style={{textAlign:"right",fontFamily:"monospace",fontWeight:900}}>{(dc.ta||0).toLocaleString()}</td>
                      <td style={{textAlign:"right",fontFamily:"monospace",fontWeight:900}}>{dc.mils?dc.mils.mils:"—"}</td>
                    </tr></tfoot>
                  </table>
              }
            </div>
          </div>
        );
      })}

      <div style={{marginTop:16,fontSize:9,color:"#aaa",textAlign:"right"}}>Generated {new Date().toLocaleString()} · IPSproject</div>
    </div>
  );
}

// ======== COMPS PAGE ========
function CompsPage({compData, setCompData, NavBar}) {
  const [selected, setSelected] = useState(null);
  const [addModal, setAddModal] = useState(false);
  const [newName, setNewName] = useState("");
  const [startHoursModal, setStartHoursModal] = useState(null);
  const [startHoursInput, setStartHoursInput] = useState("");
  const [startDateModal, setStartDateModal] = useState(null);
  const [startDateInput, setStartDateInput] = useState("");
  const [showDailyLog, setShowDailyLog] = useState(false);
  const [showWeeklyLog, setShowWeeklyLog] = useState(false);
  const [selectedDay, setSelectedDay] = useState(getTodayKey());
  const [selectedWeek, setSelectedWeek] = useState(getWeekKey(null));
  const [, setTick] = useState(0);

  const defaultData = {comps:[]};
  const data = compData || defaultData;
  const comps = data.comps || [];

  // Tick every second so live timers update
  useEffect(() => {
    const iv = setInterval(() => setTick(t=>t+1), 1000);
    return () => clearInterval(iv);
  }, []);

  // ── Pure timestamp-based time calculation ──────────────────────────────────
  // Each compressor stores:
  //   runSince: timestamp when it was last turned on (null if off)
  //   sessions: [{start, end}] — completed sessions
  //   running: bool
  //
  // We never reset timers. We just compute hours from sessions + live segment.

  // Get all ms for a compressor within a date range [dayStart, dayEnd)
  const getMsInRange = (comp, rangeStart, rangeEnd) => {
    const now = Date.now();
    const sessions = comp.sessions || [];
    // Add live session if running
    const allSessions = comp.running && comp.runSince
      ? [...sessions, {start: comp.runSince, end: now}]
      : sessions;
    let total = 0;
    for (const s of allSessions) {
      const start = Math.max(s.start, rangeStart);
      const end = Math.min(s.end || now, rangeEnd);
      if (end > start) total += end - start;
    }
    return total;
  };

  // Get ms for a specific calendar day key like "3/7/2026"
  const getMsForDay = (comp, dayKey) => {
    const d = new Date(dayKey);
    const dayStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    const dayEnd = dayStart + 86400000;
    return getMsInRange(comp, dayStart, dayEnd);
  };

  // Get ms for a specific week starting on weekKey date
  const getMsForWeek = (comp, weekStartKey) => {
    const d = new Date(weekStartKey);
    const weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    const weekEnd = weekStart + 7 * 86400000;
    return getMsInRange(comp, weekStart, weekEnd);
  };

  // Get all-time ms
  const getAllTimeMs = (comp) => {
    const now = Date.now();
    const sessions = comp.sessions || [];
    const allSessions = comp.running && comp.runSince
      ? [...sessions, {start: comp.runSince, end: now}]
      : sessions;
    return allSessions.reduce((sum, s) => sum + ((s.end || now) - s.start), 0);
  };

  // Get all calendar days that have any activity
  const getAllDays = (comp) => {
    const now = Date.now();
    const sessions = comp.sessions || [];
    const allSessions = comp.running && comp.runSince
      ? [...sessions, {start: comp.runSince, end: now}]
      : sessions;
    const daySet = new Set();
    for (const s of allSessions) {
      const start = s.start;
      const end = s.end || now;
      // Walk through each calendar day this session spans
      let cursor = new Date(start);
      cursor.setHours(0,0,0,0);
      while (cursor.getTime() < end) {
        daySet.add(cursor.toLocaleDateString("en-US"));
        cursor.setDate(cursor.getDate() + 1);
      }
    }
    return [...daySet].sort((a,b) => new Date(b) - new Date(a));
  };

  // Get all weeks that have any activity
  const getAllWeeks = (comp) => {
    const now = Date.now();
    const sessions = comp.sessions || [];
    const allSessions = comp.running && comp.runSince
      ? [...sessions, {start: comp.runSince, end: now}]
      : sessions;
    const weekSet = new Set();
    for (const s of allSessions) {
      const start = s.start;
      const end = s.end || now;
      let cursor = new Date(start);
      cursor.setHours(0,0,0,0);
      while (cursor.getTime() < end) {
        // Find Monday of this week
        const day = cursor.getDay();
        const diff = cursor.getDate() - day + (day === 0 ? -6 : 1);
        const mon = new Date(cursor);
        mon.setDate(diff);
        mon.setHours(0,0,0,0);
        weekSet.add(mon.toLocaleDateString("en-US"));
        cursor.setDate(cursor.getDate() + 7);
      }
    }
    return [...weekSet].sort((a,b) => new Date(b) - new Date(a));
  };

  const fmtH = (h) => { const hrs=Math.floor(h),mins=Math.floor((h-hrs)*60); return `${hrs}h ${String(mins).padStart(2,"0")}m`; };
  const fmtMs = (ms) => fmtH(ms/3600000);
  const dailyColor  = (h) => h>=6?"#ff1744":h>=5?"#ffab00":"#00e676";
  const weeklyColor = (h) => h>=40?"#ff1744":h>=35?"#ffab00":"#00e676";

  const todayKey = getTodayKey();
  const todayMs = (comp) => getMsForDay(comp, todayKey);
  const todayH = (comp) => todayMs(comp)/3600000;

  const toggleComp = (id, on) => {
    const now = Date.now();
    setCompData(prev => {
      const p = prev || defaultData;
      return {...p, comps:(p.comps||[]).map(c => {
        if (c.id !== id) return c;
        if (on && !c.running) {
          return {...c, running:true, runSince:now};
        }
        if (!on && c.running) {
          const sessions = [...(c.sessions||[]), {start:c.runSince||now, end:now}];
          return {...c, running:false, runSince:null, sessions};
        }
        return c;
      })};
    });
  };

  const stopAll = () => {
    const now = Date.now();
    setCompData(prev => {
      const p = prev || defaultData;
      return {...p, comps:(p.comps||[]).map(c => {
        if (!c.running) return c;
        const sessions = [...(c.sessions||[]), {start:c.runSince||now, end:now}];
        return {...c, running:false, runSince:null, sessions};
      })};
    });
    setSelected(null);
  };

  const addComp = () => {
    if (!newName.trim()) return;
    const nc = {id:Date.now(), name:newName.trim(), startHours:0, startDate:"", running:false, runSince:null, sessions:[]};
    setCompData(prev => {const p=prev||defaultData; return {...p, comps:[...(p.comps||[]),nc]};});
    setNewName(""); setAddModal(false);
  };

  const saveStartHours = (id) => {
    const val=parseFloat(startHoursInput); if(isNaN(val)||val<0) return;
    setCompData(prev=>{const p=prev||defaultData;return{...p,comps:(p.comps||[]).map(c=>c.id===id?{...c,startHours:val}:c)};});
    setStartHoursModal(null); setStartHoursInput("");
  };

  const saveStartDate = (id) => {
    setCompData(prev=>{const p=prev||defaultData;return{...p,comps:(p.comps||[]).map(c=>c.id===id?{...c,startDate:startDateInput}:c)};});
    setStartDateModal(null); setStartDateInput("");
  };

  const deleteComp = (id) => {
    if (!window.confirm("Delete this compressor?")) return;
    setCompData(prev=>{const p=prev||defaultData;return{...p,comps:(p.comps||[]).filter(c=>c.id!==id)};});
    if (selected===id) setSelected(null);
  };

  const anyRunning = comps.some(c=>c.running);
  const selComp = comps.find(c=>c.id===selected);

  // All days/weeks across all comps for the date pickers
  const allDaysAcrossComps = [...new Set(comps.flatMap(c => getAllDays(c)))].sort((a,b)=>new Date(b)-new Date(a));
  const allWeeksAcrossComps = [...new Set(comps.flatMap(c => getAllWeeks(c)))].sort((a,b)=>new Date(b)-new Date(a));

  return (
    <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:100}}>
      <div style={{fontSize:16,fontWeight:900,fontFamily:"var(--display)",textAlign:"center",marginBottom:4}}>COMPRESSOR HOURS</div>
      <div style={{fontSize:11,color:"var(--muted)",textAlign:"center",marginBottom:14}}>Tap to select · ✕ to delete</div>

      {anyRunning&&<button onClick={stopAll} style={{width:"100%",padding:14,marginBottom:12,borderRadius:12,background:"rgba(255,23,68,0.15)",border:"1px solid rgba(255,23,68,0.4)",color:"#ff1744",fontSize:14,fontWeight:800,cursor:"pointer",fontFamily:"var(--font)"}}>⏹ STOP ALL COMPRESSORS</button>}

      {/* Compressor Cards Grid */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:14}}>
        {comps.map(comp=>{
          const dh=todayH(comp), wh=getMsForWeek(comp,getWeekKey(comp.startDate||null))/3600000, ah=getAllTimeMs(comp)/3600000;
          const dc=dailyColor(dh),wc=weeklyColor(wh),isSel=selected===comp.id;
          const dot=comp.running?dc:"#3a4050";
          return (
            <div key={comp.id} onClick={()=>setSelected(isSel?null:comp.id)}
              style={{borderRadius:14,padding:"12px 14px",cursor:"pointer",
                border:`2px solid ${comp.running?dc:isSel?"var(--accent)":"var(--border)"}`,
                background:comp.running?`${dc}18`:isSel?"rgba(255,165,0,0.08)":"var(--card)",
                transition:"all 0.15s"}}>
              <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:8}}>
                <div style={{width:9,height:9,borderRadius:"50%",background:dot,boxShadow:comp.running?`0 0 7px ${dot}`:"none",flexShrink:0}}/>
                <div style={{fontSize:11,fontWeight:800,color:comp.running?dc:"var(--text)",letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1}}>{comp.name}</div>
                <button onClick={e=>{e.stopPropagation();deleteComp(comp.id);}} style={{background:"rgba(255,23,68,0.12)",border:"1px solid rgba(255,23,68,0.25)",borderRadius:6,color:"#ff4444",fontSize:11,cursor:"pointer",padding:"2px 6px",lineHeight:1,fontFamily:"var(--font)",flexShrink:0}}>✕</button>
              </div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:4,marginBottom:8}}>
                {[["Today",fmtH(dh),dc],["Week",fmtH(wh),wc],["Total",fmtH(ah),"var(--muted)"],["Status",comp.running?"ON":"OFF",comp.running?"#00e676":"var(--dim)"]].map(([l,v,c])=>(
                  <div key={l} style={{background:"rgba(0,0,0,0.05)",borderRadius:6,padding:"4px 6px"}}>
                    <div style={{fontSize:8,color:"var(--dim)",fontWeight:700,textTransform:"uppercase"}}>{l}</div>
                    <div style={{fontSize:11,fontWeight:800,color:c,fontFamily:"var(--mono)"}}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{height:4,borderRadius:2,background:"rgba(0,0,0,0.06)",overflow:"hidden",marginBottom:2}}>
                <div style={{height:"100%",borderRadius:2,width:`${Math.min(100,(dh/8)*100)}%`,background:dc,transition:"width 0.5s"}}/>
              </div>
              <div style={{fontSize:8,color:"var(--dim)",textAlign:"right"}}>daily</div>
            </div>
          );
        })}
        <div onClick={()=>setAddModal(true)} style={{borderRadius:14,padding:"12px 14px",cursor:"pointer",border:"2px dashed var(--border)",background:"transparent",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,minHeight:130}}>
          <div style={{fontSize:22,color:"var(--muted)"}}>+</div>
          <div style={{fontSize:11,fontWeight:700,color:"var(--muted)"}}>Add Compressor</div>
        </div>
      </div>

      {/* Selected Compressor Detail Panel */}
      {selComp&&<div style={{...S.card,marginBottom:14,border:"1px solid var(--accent)",background:"rgba(255,165,0,0.04)"}}>
        <div style={{fontWeight:900,fontSize:15,color:"var(--accent)",marginBottom:2}}>{selComp.name}</div>
        <div style={{fontSize:11,color:"var(--muted)",marginBottom:12}}>
          Status: <span style={{fontWeight:800,color:selComp.running?"#00e676":"var(--dim)"}}>{selComp.running?"● RUNNING":"○ STOPPED"}</span>
          {selComp.startHours>0&&<span style={{marginLeft:8,color:"var(--muted)"}}>Start Hrs: {selComp.startHours}h</span>}
          {selComp.startDate&&<span style={{marginLeft:8,color:"var(--muted)"}}>Wk Start: {selComp.startDate}</span>}
        </div>
        <div style={{display:"flex",gap:10,marginBottom:10}}>
          <button onClick={()=>toggleComp(selComp.id,true)} disabled={selComp.running}
            style={{flex:1,padding:14,borderRadius:12,background:selComp.running?"rgba(0,230,118,0.08)":"rgba(0,230,118,0.18)",border:"1px solid rgba(0,230,118,0.4)",color:"#00e676",fontSize:15,fontWeight:900,cursor:selComp.running?"default":"pointer",fontFamily:"var(--font)"}}>▶ ON</button>
          <button onClick={()=>toggleComp(selComp.id,false)} disabled={!selComp.running}
            style={{flex:1,padding:14,borderRadius:12,background:!selComp.running?"rgba(255,23,68,0.04)":"rgba(255,23,68,0.18)",border:"1px solid rgba(255,23,68,0.4)",color:"#ff1744",fontSize:15,fontWeight:900,cursor:!selComp.running?"default":"pointer",fontFamily:"var(--font)",opacity:!selComp.running?0.4:1}}>■ OFF</button>
        </div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginBottom:12}}>
          {[["Today",fmtH(todayH(selComp)),dailyColor(todayH(selComp))],
            ["This Week",fmtH(getMsForWeek(selComp,getWeekKey(selComp.startDate||null))/3600000),weeklyColor(getMsForWeek(selComp,getWeekKey(selComp.startDate||null))/3600000)],
            ["All Time",fmtH(getAllTimeMs(selComp)/3600000),"var(--text)"]].map(([l,v,c])=>(
            <div key={l} style={{textAlign:"center",background:"rgba(0,0,0,0.04)",borderRadius:8,padding:"8px 4px"}}>
              <div style={{fontSize:9,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:2}}>{l}</div>
              <div style={{fontSize:12,fontWeight:800,color:c,fontFamily:"var(--mono)"}}>{v}</div>
            </div>
          ))}
        </div>

        {startHoursModal===selComp.id?(
          <div style={{display:"flex",gap:8,marginBottom:8}}>
            <input value={startHoursInput} onChange={e=>setStartHoursInput(e.target.value)} type="number" min="0" step="0.1" placeholder="Start hours (e.g. 1250)" style={{...S.inp,flex:1,marginBottom:0}}/>
            <button onClick={()=>saveStartHours(selComp.id)} style={{...S.bp,width:"auto",padding:"10px 14px",fontSize:12}}>Save</button>
            <button onClick={()=>setStartHoursModal(null)} style={{...S.bs,width:"auto",padding:"10px 12px",fontSize:12}}>✕</button>
          </div>
        ):(
          <button onClick={()=>{setStartHoursModal(selComp.id);setStartHoursInput(selComp.startHours||"");}}
            style={{...S.bs,width:"100%",fontSize:11,padding:9,marginBottom:8}}>
            ⚙ Set Start Hours{selComp.startHours>0?` (currently ${selComp.startHours}h)`:""}
          </button>
        )}

        {startDateModal===selComp.id?(
          <div style={{display:"flex",gap:8}}>
            <input value={startDateInput} onChange={e=>setStartDateInput(e.target.value)} type="date" style={{...S.inp,flex:1,marginBottom:0,colorScheme:"dark"}}/>
            <button onClick={()=>saveStartDate(selComp.id)} style={{...S.bp,width:"auto",padding:"10px 14px",fontSize:12}}>Save</button>
            <button onClick={()=>setStartDateModal(null)} style={{...S.bs,width:"auto",padding:"10px 12px",fontSize:12}}>✕</button>
          </div>
        ):(
          <button onClick={()=>{setStartDateModal(selComp.id);setStartDateInput(selComp.startDate||"");}}
            style={{...S.bs,width:"100%",fontSize:11,padding:9}}>
            📅 Start Date{selComp.startDate?` (${selComp.startDate})`:" — sets weekly period"}
          </button>
        )}
      </div>}

      {/* Daily Usage Bar Chart — today */}
      {comps.length>0&&<div style={{...S.card,marginBottom:12}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:2}}>DAILY USAGE</div>
        <div style={{fontSize:10,color:"var(--muted)",marginBottom:10}}>Max shown 8h · Yellow ≥5h · Red ≥6h</div>
        {comps.map(comp=>{const dh=todayH(comp),pct=Math.min(100,(dh/8)*100),col=dailyColor(dh);return(
          <div key={comp.id} style={{marginBottom:9}}>
            <div style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
              <div style={{fontSize:10,fontWeight:700,color:comp.running?col:"var(--muted)"}}>{comp.running?"● ":""}{comp.name}</div>
              <div style={{fontSize:10,fontWeight:800,color:col,fontFamily:"var(--mono)"}}>{fmtH(dh)}</div>
            </div>
            <div style={{height:7,borderRadius:4,background:"rgba(0,0,0,0.06)",overflow:"hidden"}}>
              <div style={{height:"100%",borderRadius:4,width:`${pct}%`,background:col,transition:"width 0.5s",boxShadow:comp.running?`0 0 5px ${col}`:"none"}}/>
            </div>
          </div>
        );})}
        <div style={{display:"flex",justifyContent:"space-between",marginTop:6}}>
          {["0h","5h","6h","8h"].map((l,i)=><span key={i} style={{fontSize:9,color:i===1?"#ffab00":i===2?"#ff1744":"var(--dim)"}}>{l}</span>)}
        </div>
      </div>}

      {/* Weekly Usage Bar Chart */}
      {comps.length>0&&<div style={{...S.card,marginBottom:12}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:2}}>WEEKLY USAGE</div>
        <div style={{fontSize:10,color:"var(--muted)",marginBottom:10}}>Max shown 48h · Yellow ≥35h · Red ≥40h</div>
        {comps.map(comp=>{const wh=getMsForWeek(comp,getWeekKey(comp.startDate||null))/3600000,pct=Math.min(100,(wh/48)*100),col=weeklyColor(wh);return(
          <div key={comp.id} style={{marginBottom:9}}>
            <div style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
              <div style={{fontSize:10,fontWeight:700,color:comp.running?col:"var(--muted)"}}>{comp.running?"● ":""}{comp.name}</div>
              <div style={{fontSize:10,fontWeight:800,color:col,fontFamily:"var(--mono)"}}>{fmtH(wh)}</div>
            </div>
            <div style={{height:7,borderRadius:4,background:"rgba(0,0,0,0.06)",overflow:"hidden"}}>
              <div style={{height:"100%",borderRadius:4,width:`${pct}%`,background:col,transition:"width 0.5s",boxShadow:comp.running?`0 0 5px ${col}`:"none"}}/>
            </div>
          </div>
        );})}
        <div style={{display:"flex",justifyContent:"space-between",marginTop:6}}>
          {["0h","35h","40h","48h"].map((l,i)=><span key={i} style={{fontSize:9,color:i===1?"#ffab00":i===2?"#ff1744":"var(--dim)"}}>{l}</span>)}
        </div>
      </div>}

      {/* Log Toggle Buttons */}
      <div style={{display:"flex",gap:8,marginBottom:8}}>
        <button onClick={()=>setShowDailyLog(v=>!v)} style={{...S.bs,flex:1,fontSize:11,padding:10}}>📋 Daily Log {showDailyLog?"▲":"▼"}</button>
        <button onClick={()=>setShowWeeklyLog(v=>!v)} style={{...S.bs,flex:1,fontSize:11,padding:10}}>📊 Weekly Log {showWeeklyLog?"▲":"▼"}</button>
      </div>

      {/* Daily Log — date picker */}
      {showDailyLog&&<div style={{...S.card,marginBottom:8}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:10}}>DAILY LOG</div>
        {allDaysAcrossComps.length===0&&<div style={{fontSize:11,color:"var(--dim)"}}>No history yet</div>}
        {allDaysAcrossComps.length>0&&<div>
          <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:12,flexWrap:"wrap"}}>
            <div style={{fontSize:10,color:"var(--muted)",fontWeight:700}}>Select Day:</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
              {allDaysAcrossComps.map(dk=>(
                <button key={dk} onClick={()=>setSelectedDay(dk)}
                  style={{padding:"4px 10px",borderRadius:8,border:`1px solid ${selectedDay===dk?"var(--accent)":"var(--border)"}`,background:selectedDay===dk?"rgba(255,165,0,0.15)":"transparent",color:selectedDay===dk?"var(--accent)":"var(--muted)",fontSize:10,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)"}}>
                  {dk}{dk===todayKey?" ⬤":""}
                </button>
              ))}
            </div>
          </div>
          {comps.map(comp=>{
            const ms=getMsForDay(comp,selectedDay), h=ms/3600000, col=dailyColor(h), pct=Math.min(100,(h/24)*100);
            return(
              <div key={comp.id} style={{marginBottom:10}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
                  <div style={{fontSize:11,fontWeight:800,color:"var(--accent)"}}>{comp.name}</div>
                  <div style={{fontSize:11,fontWeight:800,color:col,fontFamily:"var(--mono)"}}>{fmtH(h)}</div>
                </div>
                <div style={{height:6,borderRadius:3,background:"rgba(0,0,0,0.06)",overflow:"hidden"}}>
                  <div style={{height:"100%",borderRadius:3,width:`${pct}%`,background:col}}/>
                </div>
                <div style={{fontSize:9,color:"var(--dim)",textAlign:"right",marginTop:2}}>{pct.toFixed(0)}% of 24h</div>
              </div>
            );
          })}
        </div>}
      </div>}

      {/* Weekly Log — week picker */}
      {showWeeklyLog&&<div style={{...S.card,marginBottom:8}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:10}}>WEEKLY LOG</div>
        {allWeeksAcrossComps.length===0&&<div style={{fontSize:11,color:"var(--dim)"}}>No history yet</div>}
        {allWeeksAcrossComps.length>0&&<div>
          <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:12,flexWrap:"wrap"}}>
            <div style={{fontSize:10,color:"var(--muted)",fontWeight:700}}>Select Week:</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
              {allWeeksAcrossComps.map(wk=>{
                const we=new Date(wk); we.setDate(we.getDate()+6);
                const weStr=we.toLocaleDateString("en-US");
                const isCur=wk===getWeekKey(null);
                return(
                  <button key={wk} onClick={()=>setSelectedWeek(wk)}
                    style={{padding:"4px 10px",borderRadius:8,border:`1px solid ${selectedWeek===wk?"var(--accent)":"var(--border)"}`,background:selectedWeek===wk?"rgba(255,165,0,0.15)":"transparent",color:selectedWeek===wk?"var(--accent)":"var(--muted)",fontSize:10,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)"}}>
                    {wk}–{weStr}{isCur?" ⬤":""}
                  </button>
                );
              })}
            </div>
          </div>
          {comps.map(comp=>{
            const ms=getMsForWeek(comp,selectedWeek), h=ms/3600000, col=weeklyColor(h), pct=Math.min(100,(h/168)*100);
            return(
              <div key={comp.id} style={{marginBottom:10}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
                  <div style={{fontSize:11,fontWeight:800,color:"var(--accent)"}}>{comp.name}</div>
                  <div style={{fontSize:11,fontWeight:800,color:col,fontFamily:"var(--mono)"}}>{fmtH(h)}</div>
                </div>
                <div style={{height:6,borderRadius:3,background:"rgba(0,0,0,0.06)",overflow:"hidden"}}>
                  <div style={{height:"100%",borderRadius:3,width:`${pct}%`,background:col}}/>
                </div>
                <div style={{fontSize:9,color:"var(--dim)",textAlign:"right",marginTop:2}}>{pct.toFixed(0)}% of 168h</div>
              </div>
            );
          })}
        </div>}
      </div>}

      {/* Legend */}
      <div style={{...S.card,background:"rgba(0,0,0,0.03)"}}>
        <div style={{fontSize:10,fontWeight:800,color:"var(--muted)",textTransform:"uppercase",marginBottom:6}}>Hours Legend</div>
        <div style={{display:"flex",gap:12,flexWrap:"wrap",marginBottom:6}}>
          {[["#00e676","Daily < 5h"],["#ffab00","Daily ≥ 5h"],["#ff1744","Daily ≥ 6h"]].map(([c,l])=>(
            <div key={l} style={{display:"flex",alignItems:"center",gap:5}}><div style={{width:8,height:8,borderRadius:"50%",background:c}}/><span style={{fontSize:10,color:"var(--muted)"}}>{l}</span></div>
          ))}
        </div>
        <div style={{display:"flex",gap:12,flexWrap:"wrap"}}>
          {[["#00e676","Weekly < 35h"],["#ffab00","Weekly ≥ 35h"],["#ff1744","Weekly ≥ 40h"]].map(([c,l])=>(
            <div key={l} style={{display:"flex",alignItems:"center",gap:5}}><div style={{width:8,height:8,borderRadius:"50%",background:c}}/><span style={{fontSize:10,color:"var(--muted)"}}>{l}</span></div>
          ))}
        </div>
      </div>

      {/* Add Compressor Modal */}
      {addModal&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end"}} onClick={()=>setAddModal(false)}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)"}}>
          <div style={{fontSize:16,fontWeight:800,color:"var(--text)",marginBottom:16}}>Add Compressor</div>
          <label style={S.lb}>Compressor Name</label>
          <input value={newName} onChange={e=>setNewName(e.target.value)} placeholder="e.g. COMP 1, Unit A..." style={{...S.inp}} autoFocus onKeyDown={e=>e.key==="Enter"&&addComp()}/>
          <button onClick={addComp} style={{...S.bp,marginTop:12}} disabled={!newName.trim()}>Add Compressor</button>
          <button onClick={()=>{setAddModal(false);setNewName("");}} style={{...S.bs,marginTop:8,width:"100%"}}>Cancel</button>
        </div>
      </div>}
      <NavBar/>
    </div>
  );
}

// ======== FINAL INSPECTION PAGE ========
function FinalInspectionPage({inspections, setInspections, NavBar}) {
  const [view, setView] = useState("main");
  const [locName, setLocName] = useState("");
  const [locDate, setLocDate] = useState(new Date().toLocaleDateString("en-US"));
  const [readings, setReadings] = useState({"12 o'clock":["","",""],"3 o'clock":["","",""],"6 o'clock":["","",""],"9 o'clock":["","",""]});
  const [selectedLocation, setSelectedLocation] = useState(null);
  const [showLocationPicker, setShowLocationPicker] = useState(false);
  const ORIENTATIONS = ["12 o'clock","3 o'clock","6 o'clock","9 o'clock"];
  const locs = inspections || [];
  const avgOf = (vals) => { const ns=vals.map(v=>parseFloat(v)).filter(v=>!isNaN(v)); return ns.length>0?(ns.reduce((a,b)=>a+b,0)/ns.length):null; };
  const fmtAvg = (v) => v!=null?v.toFixed(2):"—";
  const calcLocAvg = (loc) => { const avgs=ORIENTATIONS.map(o=>avgOf(loc.readings[o]||[])).filter(v=>v!=null); return avgs.length>0?avgs.reduce((a,b)=>a+b,0)/avgs.length:null; };
  const calcOverallAvg = () => { const avgs=locs.map(l=>calcLocAvg(l)).filter(v=>v!=null); return avgs.length>0?avgs.reduce((a,b)=>a+b,0)/avgs.length:null; };

  const saveLocation = () => {
    if(!locName.trim()) return;
    setInspections(prev=>[...(prev||[]),{id:Date.now(),name:locName.trim(),date:locDate,readings:{...readings}}]);
    setLocName(""); setLocDate(new Date().toLocaleDateString("en-US"));
    setReadings({"12 o'clock":["","",""],"3 o'clock":["","",""],"6 o'clock":["","",""],"9 o'clock":["","",""]});
    setView("main");
  };
  const deleteLocation = (id) => { if(window.confirm("Delete this location?")) setInspections(prev=>(prev||[]).filter(l=>l.id!==id)); };
  const viewLoc = selectedLocation ? locs.find(l=>l.id===selectedLocation) : null;

  return (
    <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:100}}>
      <div style={{fontSize:16,fontWeight:900,fontFamily:"var(--display)",textAlign:"center",marginBottom:16}}>FINAL INSPECTION</div>

      {view==="main"&&<>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:16}}>
          <button onClick={()=>setView("newLocation")} style={{...S.bp,padding:"18px 12px",fontSize:14}}>+ New Location</button>
          <button onClick={()=>setView("data")} style={{...S.ba,padding:"18px 12px",fontSize:14}}>📊 Data</button>
        </div>
        {locs.length>0&&<div style={S.card}>
          <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:10}}>LOCATION SUMMARY</div>
          {locs.map(l=>{const a=calcLocAvg(l);return(
            <div key={l.id} style={{display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid var(--border)",paddingBottom:8,marginBottom:8}}>
              <div><div style={{fontSize:13,fontWeight:800,color:"var(--text)"}}>{l.name}</div><div style={{fontSize:10,color:"var(--muted)"}}>{l.date}</div></div>
              <div style={{fontSize:16,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{fmtAvg(a)} <span style={{fontSize:10,color:"var(--muted)"}}>mils</span></div>
            </div>
          );})}
          {locs.length>1&&<div style={{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:4}}>
            <div style={{fontSize:12,fontWeight:900,color:"var(--text)"}}>Total Average DFT</div>
            <div style={{fontSize:18,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)",border:"2px solid var(--accent)",padding:"4px 10px",borderRadius:8}}>{fmtAvg(calcOverallAvg())} mils</div>
          </div>}
          {locs.length>0&&<button onClick={()=>setView("dftreport")} style={{...S.bp,marginTop:14,fontSize:13}}>🖨 DFT Report</button>}
        </div>}
        {locs.length===0&&<div style={{textAlign:"center",padding:40,color:"var(--dim)"}}>No inspection locations recorded yet</div>}
      </>}

      {view==="newLocation"&&<>
        <button onClick={()=>setView("main")} style={{...S.bs,marginBottom:14,padding:"8px 14px",fontSize:12,width:"auto"}}>← Back</button>
        <div style={S.card}>
          <div style={{fontSize:14,fontWeight:900,color:"var(--text)",marginBottom:14}}>New Inspection Location</div>
          <label style={S.lb}>Location Name</label>
          <input value={locName} onChange={e=>setLocName(e.target.value)} placeholder="e.g. Receiving End, Launch End..." style={{...S.inp,marginBottom:12}}/>
          <label style={S.lb}>Date Inspected</label>
          <input value={locDate} onChange={e=>setLocDate(e.target.value)} placeholder="MM/DD/YYYY" style={{...S.inp,marginBottom:16}}/>
          <div style={{fontSize:13,fontWeight:800,color:"var(--text)",marginBottom:10}}>DFT Readings (mils)</div>
          {ORIENTATIONS.map(ori=>{
            const avg=avgOf(readings[ori]);
            return(<div key={ori} style={{marginBottom:14}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                <div style={{fontSize:12,fontWeight:800,color:"var(--accent)"}}>{ori}</div>
                <div style={{fontSize:11,color:"var(--muted)"}}>Avg: <span style={{fontWeight:800,color:"var(--text)"}}>{fmtAvg(avg)}</span></div>
              </div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6}}>
                {[0,1,2].map(i=>(
                  <input key={i} type="number" step="0.1" value={readings[ori][i]} onChange={e=>{const nv=[...readings[ori]];nv[i]=e.target.value;setReadings(pr=>({...pr,[ori]:nv}));}} placeholder={`R${i+1}`} style={{...S.inp,textAlign:"center",padding:"10px 6px"}}/>
                ))}
              </div>
            </div>);
          })}
          <button onClick={saveLocation} disabled={!locName.trim()} style={{...S.bp,marginTop:8}}>Save Location</button>
          <button onClick={()=>setView("main")} style={{...S.bs,marginTop:8,width:"100%"}}>Cancel</button>
        </div>
      </>}

      {view==="data"&&<>
        <button onClick={()=>setView("main")} style={{...S.bs,marginBottom:14,padding:"8px 14px",fontSize:12,width:"auto"}}>← Back</button>
        <div style={S.card}>
          <div style={{fontSize:13,fontWeight:900,color:"var(--text)",marginBottom:12}}>INSPECTION DATA</div>
          <button onClick={()=>setShowLocationPicker(true)} style={{...S.ba,width:"100%",marginBottom:14,padding:"12px",fontSize:13}}>📍 {viewLoc?viewLoc.name:"Select Location"} ▼</button>
          {showLocationPicker&&<PopupMenu title="Select Location" options={locs.map(l=>l.name)} onSelect={name=>{const l=locs.find(x=>x.name===name);if(l)setSelectedLocation(l.id);setShowLocationPicker(false);}} onClose={()=>setShowLocationPicker(false)}/>}
          {locs.length>0&&<div style={{marginBottom:14}}>
            <div style={{fontSize:11,fontWeight:800,color:"var(--muted)",textTransform:"uppercase",marginBottom:8}}>All Locations</div>
            {locs.map(l=>{const a=calcLocAvg(l);return(
              <div key={l.id} style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6,padding:"8px 10px",borderRadius:8,background:"rgba(0,0,0,0.04)",border:"1px solid var(--border)"}}>
                <div><div style={{fontSize:12,fontWeight:800,color:"var(--text)"}}>{l.name}</div><div style={{fontSize:10,color:"var(--muted)"}}>{l.date}</div></div>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  <div style={{fontSize:15,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{fmtAvg(a)}</div>
                  <button onClick={()=>deleteLocation(l.id)} style={{background:"rgba(255,23,68,0.1)",border:"1px solid rgba(255,23,68,0.2)",color:"#ff1744",borderRadius:6,padding:"4px 8px",fontSize:11,cursor:"pointer",fontFamily:"var(--font)"}}>🗑</button>
                </div>
              </div>
            );})}
            {locs.length>1&&<div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:10,padding:10,borderRadius:8,background:"rgba(255,165,0,0.06)",border:"1px solid rgba(255,165,0,0.2)"}}>
              <div style={{fontSize:12,fontWeight:900,color:"var(--text)"}}>Total Average DFT</div>
              <div style={{fontSize:18,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)",border:"2px solid var(--accent)",padding:"4px 10px",borderRadius:8}}>{fmtAvg(calcOverallAvg())} mils</div>
            </div>}
          </div>}
          {viewLoc&&<div style={{borderTop:"1px solid var(--border)",paddingTop:14}}>
            <div style={{fontSize:12,fontWeight:900,color:"var(--accent)",marginBottom:8}}>Inspection Location: {viewLoc.name}</div>
            <div style={{fontSize:10,color:"var(--muted)",marginBottom:12}}>Date Inspected: {viewLoc.date}</div>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:11}}>
              <thead><tr style={{background:"rgba(255,165,0,0.08)"}}>
                <th style={{padding:"8px 6px",textAlign:"left",color:"var(--muted)",fontWeight:700}}>Orientation</th>
                <th style={{padding:"8px 4px",textAlign:"center",color:"var(--muted)",fontWeight:700}}>R1</th>
                <th style={{padding:"8px 4px",textAlign:"center",color:"var(--muted)",fontWeight:700}}>R2</th>
                <th style={{padding:"8px 4px",textAlign:"center",color:"var(--muted)",fontWeight:700}}>R3</th>
                <th style={{padding:"8px 6px",textAlign:"right",color:"var(--accent)",fontWeight:700}}>Avg</th>
              </tr></thead>
              <tbody>
                {ORIENTATIONS.map(ori=>{const rv=viewLoc.readings[ori]||["","",""],a=avgOf(rv);return(
                  <tr key={ori} style={{borderBottom:"1px solid var(--border)"}}>
                    <td style={{padding:"8px 6px",color:"var(--text)",fontWeight:700}}>{ori}</td>
                    {rv.map((v,i)=><td key={i} style={{padding:"8px 4px",textAlign:"center",color:"var(--text)"}}>{v||"—"}</td>)}
                    <td style={{padding:"8px 6px",textAlign:"right",fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{fmtAvg(a)}</td>
                  </tr>
                );})}
              </tbody>
              <tfoot><tr style={{background:"rgba(255,165,0,0.05)"}}>
                <td colSpan={4} style={{padding:"10px 6px",fontWeight:900,color:"var(--text)",fontSize:12}}>Location Average</td>
                <td style={{padding:"10px 6px",textAlign:"right",fontWeight:900,color:"var(--accent)",fontSize:14,fontFamily:"var(--mono)",borderTop:"2px solid var(--accent)"}}>{fmtAvg(calcLocAvg(viewLoc))}</td>
              </tr></tfoot>
            </table>
          </div>}
        </div>
      </>}

      {view==="dftreport"&&<DFTReportView locs={locs} calcLocAvg={calcLocAvg} calcOverallAvg={calcOverallAvg} fmtAvg={fmtAvg} ORIENTATIONS={ORIENTATIONS} avgOf={avgOf} onBack={()=>setView("main")} />}

      <NavBar/>
    </div>
  );
}

// ---- DFT Report Print View ----
function DFTReportView({locs, calcLocAvg, calcOverallAvg, fmtAvg, ORIENTATIONS, avgOf, onBack}) {
  const [sigName, setSigName] = useState("");
  const [sigDate, setSigDate] = useState(new Date().toLocaleDateString("en-US"));
  const printStyle = `
    @media print {
      body { margin: 0; padding: 0; background: white !important; color: black !important; }
      .no-print { display: none !important; }
      .sig-input { border: none !important; border-bottom: 1px solid #333 !important; background: transparent !important; }
    }
    .dft-tbl { width:100%; border-collapse:collapse; font-size:11px; margin-bottom:4px; }
    .dft-tbl th { background:#222; color:white; padding:4px 6px; text-align:center; font-weight:700; font-size:10px; }
    .dft-tbl th:first-child { text-align:left; }
    .dft-tbl td { padding:4px 6px; border-bottom:1px solid #ddd; text-align:center; }
    .dft-tbl td:first-child { text-align:left; font-weight:700; }
    .dft-tbl tfoot td { background:#eee; font-weight:800; border-top:2px solid #333; }
    .loc-hdr { background:#333; color:white; font-weight:900; font-size:11px; padding:5px 8px; margin:10px 0 0 0; border-radius:4px 4px 0 0; display:flex; justify-content:space-between; }
    .sig-area { border:1px solid #ccc; border-radius:6px; padding:14px 16px; margin-top:16px; }
    .sig-line { border-bottom: 1.5px solid #333; min-width:200px; display:none; height:20px; margin-bottom:2px; vertical-align:bottom; }
    @media print {
      .sig-input { display: none !important; }
      .sig-line { display: inline-block !important; }
    }
  `;
  return (
    <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",background:"#fff",color:"#111"}}>
      <style>{printStyle}</style>
      <div className="no-print" style={{display:"flex",gap:8,marginBottom:14}}>
        <button onClick={onBack} style={{...S.bs,padding:"8px 14px",fontSize:12,width:"auto"}}>← Back</button>
        <button onClick={()=>window.print()} style={{...S.bp,flex:1,fontSize:13}}>🖨 Print / Save PDF</button>
      </div>

      {/* Header */}
      <div style={{borderBottom:"3px solid #222",paddingBottom:8,marginBottom:10}}>
        <div style={{fontSize:18,fontWeight:900,color:"#111",letterSpacing:"0.05em"}}>DFT INSPECTION REPORT</div>
        <div style={{fontSize:11,color:"#555",marginTop:3}}>Dry Film Thickness — All Locations · {locs.length} Location{locs.length!==1?"s":""} · Generated {new Date().toLocaleDateString()}</div>
      </div>

      {/* Per-Location Tables */}
      {locs.map((loc,li)=>{
        const locAvg = calcLocAvg(loc);
        return (
          <div key={loc.id} style={{marginBottom:10,pageBreakInside:"avoid"}}>
            <div className="loc-hdr">
              <span>Location {li+1}: {loc.name}</span>
              <span style={{fontWeight:700,fontSize:10,opacity:0.9}}>{loc.date}</span>
            </div>
            <div style={{border:"1px solid #ccc",borderTop:"none",borderRadius:"0 0 4px 4px",overflow:"hidden"}}>
              <table className="dft-tbl">
                <thead><tr>
                  <th>Orientation</th><th>Reading 1</th><th>Reading 2</th><th>Reading 3</th><th>Avg (mils)</th>
                </tr></thead>
                <tbody>
                  {ORIENTATIONS.map(ori=>{
                    const rv = loc.readings[ori]||["","",""];
                    const a = avgOf(rv);
                    return (
                      <tr key={ori}>
                        <td>{ori}</td>
                        {rv.map((v,i)=><td key={i} style={{fontFamily:"monospace"}}>{v||"—"}</td>)}
                        <td style={{fontFamily:"monospace",fontWeight:800}}>{fmtAvg(a)}</td>
                      </tr>
                    );
                  })}
                </tbody>
                <tfoot><tr>
                  <td colSpan={4} style={{textAlign:"left"}}>Location Average DFT</td>
                  <td style={{fontFamily:"monospace",fontSize:13,fontWeight:900}}>{fmtAvg(locAvg)}</td>
                </tr></tfoot>
              </table>
            </div>
          </div>
        );
      })}

      {/* Overall Average */}
      {locs.length>1&&<div style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 12px",background:"#222",color:"white",borderRadius:6,marginBottom:16,fontWeight:900}}>
        <span style={{fontSize:13}}>TOTAL AVERAGE DFT — ALL LOCATIONS</span>
        <span style={{fontSize:18,fontFamily:"monospace"}}>{fmtAvg(calcOverallAvg())} mils</span>
      </div>}

      {/* Client Acceptance Signature */}
      <div className="sig-area" style={{pageBreakInside:"avoid"}}>
        <div style={{fontSize:12,fontWeight:900,color:"#111",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:10,borderBottom:"1px solid #ddd",paddingBottom:6}}>Client Acceptance</div>
        <div style={{fontSize:11,color:"#555",marginBottom:12,lineHeight:1.5}}>
          By signing below, the client accepts the above DFT inspection results as complete and satisfactory per project specifications.
        </div>
        <div style={{display:"grid",gridTemplateColumns:"2fr 1fr",gap:"16px 24px",alignItems:"end"}}>
          <div>
            <div style={{fontSize:10,fontWeight:700,color:"#666",textTransform:"uppercase",marginBottom:4}}>Client Representative Name</div>
            <input className="sig-input no-print" value={sigName} onChange={e=>setSigName(e.target.value)} placeholder="Print name..." style={{...S.inp,background:"transparent",border:"1px solid #ccc"}}/>
            <div className="sig-line" style={{display:"none"}}>{sigName}&nbsp;</div>
          </div>
          <div>
            <div style={{fontSize:10,fontWeight:700,color:"#666",textTransform:"uppercase",marginBottom:4}}>Date</div>
            <input className="sig-input no-print" value={sigDate} onChange={e=>setSigDate(e.target.value)} style={{...S.inp,background:"transparent",border:"1px solid #ccc"}}/>
            <div className="sig-line" style={{display:"none"}}>{sigDate}&nbsp;</div>
          </div>
          <div>
            <div style={{fontSize:10,fontWeight:700,color:"#666",textTransform:"uppercase",marginBottom:4}}>Client Signature</div>
            <div style={{borderBottom:"1.5px solid #333",height:40,width:"100%"}}></div>
          </div>
          <div>
            <div style={{fontSize:10,fontWeight:700,color:"#666",textTransform:"uppercase",marginBottom:4}}>IPS Representative</div>
            <div style={{borderBottom:"1.5px solid #333",height:40,width:"100%"}}></div>
          </div>
        </div>
      </div>
      <div style={{marginTop:10,fontSize:9,color:"#aaa",textAlign:"right"}}>Generated {new Date().toLocaleString()} · IPSproject · Internal Pipeline Services</div>
    </div>
  );
}
function DeliveriesPage({deliveries, setDeliveries, NavBar}) {
  const [modal, setModal] = useState(null);
  const [activePanel, setActivePanel] = useState(null); // "equipment" | "events" | "summary"
  const [formType, setFormType] = useState("");
  const [manualEntry, setManualEntry] = useState("");
  const [quantity, setQuantity] = useState("");
  const [viewItem, setViewItem] = useState(null);
  const [fuelQty, setFuelQty] = useState("");
  const [fuelNote, setFuelNote] = useState("");

  const addDelivery = (type, custom) => {
    const item = {
      id: Date.now(),
      kind: "delivery",
      type: custom || type,
      deliveredAt: Date.now(),
      pickedUpAt: null,
    };
    setDeliveries(prev => [...prev, item]);
    setModal(null); setManualEntry(""); setFormType("");
  };

  const addPickup = (type, qty, custom) => {
    const item = {
      id: Date.now(),
      kind: "pickup",
      type: custom || type,
      quantity: qty,
      recordedAt: Date.now(),
    };
    setDeliveries(prev => [...prev, item]);
    setModal(null); setManualEntry(""); setQuantity(""); setFormType("");
  };

  const addFuel = (qty, note) => {
    const item = {id:Date.now(), kind:"fuel", type:"Fuel", quantity:qty, notes:note, recordedAt:Date.now()};
    setDeliveries(prev=>[...prev,item]);
    setModal(null); setFuelQty(""); setFuelNote("");
  };

  const markPickedUp = (id) => {
    setDeliveries(prev => prev.map(d => d.id===id ? {...d, pickedUpAt: Date.now()} : d));
    setViewItem(null);
  };

  const deleteItem = (id) => {
    if(confirm("Delete this entry?")) setDeliveries(prev => prev.filter(d => d.id!==id));
    setViewItem(null);
  };

  const daysOnSite = (ts) => {
    const diff = Date.now() - ts;
    const d = Math.floor(diff / (1000*60*60*24));
    return d === 0 ? "Today" : `${d} day${d!==1?"s":""} on site`;
  };

  const totalFuelGal = (deliveries||[]).filter(d=>d.kind==="fuel").reduce((sum,d)=>sum+(parseFloat(d.quantity)||0),0);
  const onSiteEquipment = (deliveries||[]).filter(d=>d.kind==="delivery"&&!d.pickedUpAt);
  const allItems = [...(deliveries||[])].sort((a,b)=>(b.deliveredAt||b.recordedAt||0)-(a.deliveredAt||a.recordedAt||0));

  const kindCounts = {};
  (deliveries||[]).forEach(d=>{ kindCounts[d.kind]=(kindCounts[d.kind]||0)+1; });

  return (
    <div style={{padding:"12px 16px",maxWidth:CONTAINER_MAX,margin:"0 auto",paddingBottom:80}}>
      <div style={{fontSize:16,fontWeight:900,fontFamily:"var(--display)",textAlign:"center",marginBottom:16}}>DELIVERIES & PICK-UPS</div>

      {/* 5 main action buttons */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:12}}>
        <button onClick={()=>setModal("type")} style={{...S.bp,padding:"14px 10px",fontSize:13}}>+ New Event</button>
        <button onClick={()=>setModal("fuel")} style={{padding:"14px 10px",borderRadius:12,background:"rgba(255,165,0,0.12)",border:"1px solid rgba(255,165,0,0.3)",color:"var(--accent)",fontSize:13,fontWeight:800,cursor:"pointer",fontFamily:"var(--font)"}}>⛽ Log Fuel</button>
        <button onClick={()=>setActivePanel(activePanel==="equipment"?null:"equipment")} style={{...S.bs,padding:"12px 10px",fontSize:12,border:activePanel==="equipment"?"1px solid var(--accent)":"1px solid var(--border)",color:activePanel==="equipment"?"var(--accent)":"var(--muted)"}}>🚛 Equipment {onSiteEquipment.length>0&&<span style={{background:"#ffab00",color:"#000",borderRadius:10,padding:"1px 6px",fontSize:10,fontWeight:900,marginLeft:4}}>{onSiteEquipment.length}</span>}</button>
        <button onClick={()=>setActivePanel(activePanel==="events"?null:"events")} style={{...S.bs,padding:"12px 10px",fontSize:12,border:activePanel==="events"?"1px solid var(--accent)":"1px solid var(--border)",color:activePanel==="events"?"var(--accent)":"var(--muted)"}}>📋 All Events {deliveries.length>0&&<span style={{background:"var(--border)",color:"var(--text)",borderRadius:10,padding:"1px 6px",fontSize:10,fontWeight:900,marginLeft:4}}>{deliveries.length}</span>}</button>
      </div>
      <button onClick={()=>setActivePanel(activePanel==="summary"?null:"summary")} style={{...S.bs,width:"100%",marginBottom:14,fontSize:12,padding:11,border:activePanel==="summary"?"1px solid var(--accent)":"1px solid var(--border)",color:activePanel==="summary"?"var(--accent)":"var(--muted)"}}>📊 Summary {activePanel==="summary"?"▲":"▼"}</button>

      {/* Modals */}
      {viewItem&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end"}} onClick={()=>setViewItem(null)}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)"}}>
          <div style={{fontWeight:900,fontSize:18,color:"var(--accent)",marginBottom:4}}>{viewItem.type}</div>
          <div style={{fontSize:12,color:"var(--muted)",marginBottom:12,textTransform:"uppercase",fontWeight:700}}>{viewItem.kind==="delivery"?"🚛 Delivery":viewItem.kind==="fuel"?"⛽ Fuel":"📤 Pick-Up"}</div>
          {viewItem.kind==="delivery"&&<div style={{marginBottom:12}}>
            <div style={{fontSize:13,color:"var(--text)"}}>Delivered: {new Date(viewItem.deliveredAt).toLocaleString()}</div>
            {!viewItem.pickedUpAt&&<div style={{fontSize:13,color:"#ffab00",fontWeight:700,marginTop:4}}>⏱ {daysOnSite(viewItem.deliveredAt)}</div>}
            {viewItem.pickedUpAt&&<div style={{fontSize:13,color:"#00e676",marginTop:4}}>✓ Picked up: {new Date(viewItem.pickedUpAt).toLocaleString()}</div>}
          </div>}
          {(viewItem.kind==="pickup"||viewItem.kind==="fuel")&&<div style={{marginBottom:12}}>
            <div style={{fontSize:13,color:"var(--text)"}}>Recorded: {new Date(viewItem.recordedAt).toLocaleString()}</div>
            {viewItem.quantity&&<div style={{fontSize:13,color:"var(--text)",marginTop:4}}>Quantity: {viewItem.quantity}{viewItem.kind==="fuel"?" gal":""}</div>}
            {viewItem.notes&&<div style={{fontSize:12,color:"var(--muted)",marginTop:4}}>Notes: {viewItem.notes}</div>}
          </div>}
          <div style={{display:"flex",gap:10,marginTop:8}}>
            {viewItem.kind==="delivery"&&!viewItem.pickedUpAt&&<button onClick={()=>markPickedUp(viewItem.id)} style={{...S.bp,flex:1,padding:"12px 16px",fontSize:14}}>✓ Mark Picked Up</button>}
            <button onClick={()=>deleteItem(viewItem.id)} style={{...S.bs,background:"rgba(255,23,68,0.1)",color:"#ff1744",border:"1px solid rgba(255,23,68,0.2)",width:"auto",padding:"12px 20px",fontSize:14,borderRadius:12}}>🗑 Delete</button>
            <button onClick={()=>setViewItem(null)} style={{...S.bs,width:"auto",padding:"12px 20px",fontSize:14}}>Close</button>
          </div>
        </div>
      </div>}

      {modal==="type"&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end"}} onClick={()=>setModal(null)}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)"}}>
          <div style={{fontSize:16,fontWeight:800,color:"var(--text)",marginBottom:16,textAlign:"center"}}>What type of event?</div>
          <div style={{display:"flex",gap:12}}>
            <button onClick={()=>setModal("delivery")} style={{...S.bp,flex:1,padding:"18px 12px",fontSize:15}}>🚛 Delivery</button>
            <button onClick={()=>setModal("pickup")} style={{...S.ba,flex:1,padding:"18px 12px",fontSize:15}}>📤 Pick-Up</button>
          </div>
          <button onClick={()=>setModal(null)} style={{...S.bs,marginTop:12,width:"100%",fontSize:14}}>Cancel</button>
        </div>
      </div>}

      {modal==="delivery"&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end",overflowY:"auto"}} onClick={()=>{setModal(null);setFormType("")}}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)",maxHeight:"80vh",overflowY:"auto"}}>
          <div style={{fontSize:16,fontWeight:800,color:"var(--text)",marginBottom:16}}>🚛 New Delivery</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:12}}>
            {DELIVERY_TYPES.filter(t=>t!=="Other (Manual Entry)").map(t=>(
              <button key={t} onClick={()=>setFormType(t)} style={{padding:"12px 8px",borderRadius:10,border:`1px solid ${formType===t?"var(--accent)":"var(--border)"}`,background:formType===t?"rgba(255,165,0,0.15)":"transparent",color:formType===t?"var(--accent)":"var(--text)",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)",textAlign:"center"}}>{t}</button>
            ))}
            <button onClick={()=>setFormType("manual")} style={{padding:"12px 8px",borderRadius:10,border:`1px solid ${formType==="manual"?"var(--accent)":"var(--border)"}`,background:formType==="manual"?"rgba(255,165,0,0.15)":"transparent",color:formType==="manual"?"var(--accent)":"var(--text)",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)"}}>✏️ Manual Entry</button>
          </div>
          {formType==="manual"&&<div style={{marginBottom:12}}><label style={S.lb}>Description</label><input value={manualEntry} onChange={e=>setManualEntry(e.target.value)} placeholder="Describe the delivery..." style={{...S.inp}}/></div>}
          <button onClick={()=>{if(!formType)return;addDelivery(formType,formType==="manual"?manualEntry:null)}} style={{...S.bp,marginTop:4}} disabled={!formType||(formType==="manual"&&!manualEntry.trim())}>Record Delivery</button>
          <button onClick={()=>{setModal(null);setFormType("");setManualEntry("")}} style={{...S.bs,marginTop:8,width:"100%"}}>Cancel</button>
        </div>
      </div>}

      {modal==="pickup"&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end",overflowY:"auto"}} onClick={()=>{setModal(null);setFormType("")}}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)",maxHeight:"80vh",overflowY:"auto"}}>
          <div style={{fontSize:16,fontWeight:800,color:"var(--text)",marginBottom:16}}>📤 New Pick-Up</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:12}}>
            {PICKUP_TYPES.filter(t=>t!=="Other (Manual Entry)").map(t=>(
              <button key={t} onClick={()=>setFormType(t)} style={{padding:"12px 8px",borderRadius:10,border:`1px solid ${formType===t?"var(--accent)":"var(--border)"}`,background:formType===t?"rgba(255,165,0,0.15)":"transparent",color:formType===t?"var(--accent)":"var(--text)",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)"}}>{t}</button>
            ))}
            <button onClick={()=>setFormType("manual")} style={{padding:"12px 8px",borderRadius:10,border:`1px solid ${formType==="manual"?"var(--accent)":"var(--border)"}`,background:formType==="manual"?"rgba(255,165,0,0.15)":"transparent",color:formType==="manual"?"var(--accent)":"var(--text)",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"var(--font)"}}>✏️ Manual Entry</button>
          </div>
          {formType==="manual"&&<div style={{marginBottom:12}}><label style={S.lb}>Description</label><input value={manualEntry} onChange={e=>setManualEntry(e.target.value)} placeholder="Describe the pickup..." style={{...S.inp}}/></div>}
          <div style={{marginBottom:12}}><label style={S.lb}>Quantity (optional)</label><input value={quantity} onChange={e=>setQuantity(e.target.value)} placeholder="e.g. 500 gal, 2 drums..." style={{...S.inp}}/></div>
          <button onClick={()=>{if(!formType)return;addPickup(formType,quantity,formType==="manual"?manualEntry:null)}} style={{...S.bp,marginTop:4}} disabled={!formType||(formType==="manual"&&!manualEntry.trim())}>Record Pick-Up</button>
          <button onClick={()=>{setModal(null);setFormType("");setQuantity("");setManualEntry("")}} style={{...S.bs,marginTop:8,width:"100%"}}>Cancel</button>
        </div>
      </div>}

      {modal==="fuel"&&<div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",zIndex:400,display:"flex",alignItems:"flex-end"}} onClick={()=>{setModal(null);setFuelQty("");setFuelNote("")}}>
        <div onClick={e=>e.stopPropagation()} style={{background:"var(--card)",borderRadius:"20px 20px 0 0",padding:24,width:"100%",maxWidth:460,margin:"0 auto",border:"1px solid var(--border)"}}>
          <div style={{fontSize:16,fontWeight:800,color:"var(--text)",marginBottom:4}}>⛽ Log Fuel</div>
          {totalFuelGal>0&&<div style={{fontSize:12,color:"var(--muted)",marginBottom:14}}>Project total so far: <span style={{color:"var(--accent)",fontWeight:800}}>{totalFuelGal.toLocaleString()} gal</span></div>}
          <label style={S.lb}>Quantity (gallons)</label>
          <input value={fuelQty} onChange={e=>setFuelQty(e.target.value)} type="number" min="0" step="1" placeholder="e.g. 500" style={{...S.inp}} autoFocus/>
          <label style={S.lb}>Notes (optional)</label>
          <input value={fuelNote} onChange={e=>setFuelNote(e.target.value)} placeholder="Truck #, supplier, etc." style={{...S.inp,marginBottom:14}}/>
          <button onClick={()=>{if(!fuelQty||parseFloat(fuelQty)<=0)return;addFuel(fuelQty,fuelNote)}} style={{...S.bp}} disabled={!fuelQty||parseFloat(fuelQty)<=0}>Record Fuel</button>
          <button onClick={()=>{setModal(null);setFuelQty("");setFuelNote("")}} style={{...S.bs,marginTop:8,width:"100%"}}>Cancel</button>
        </div>
      </div>}

      {/* Equipment panel */}
      {activePanel==="equipment"&&<div style={{...S.card,marginBottom:12}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:10}}>⚠️ EQUIPMENT ON SITE</div>
        {onSiteEquipment.length===0&&<div style={{fontSize:12,color:"var(--muted)",textAlign:"center",padding:12}}>No equipment currently on site</div>}
        {onSiteEquipment.map(d=>(
          <div key={d.id} onClick={()=>setViewItem(d)} style={{...S.card,cursor:"pointer",marginBottom:8,border:"1px solid rgba(255,171,0,0.2)",background:"rgba(255,171,0,0.04)"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div><div style={{fontWeight:800,fontSize:13,color:"var(--text)"}}>{d.type}</div><div style={{fontSize:10,color:"var(--muted)",marginTop:2}}>{new Date(d.deliveredAt).toLocaleDateString()}</div></div>
              <div style={{textAlign:"right"}}><div style={{fontSize:11,fontWeight:800,color:"#ffab00"}}>{daysOnSite(d.deliveredAt)}</div><div style={{fontSize:9,color:"var(--dim)"}}>tap for details</div></div>
            </div>
          </div>
        ))}
      </div>}

      {/* All events panel */}
      {activePanel==="events"&&<div style={{...S.card,marginBottom:12}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:10}}>ALL EVENTS ({allItems.length})</div>
        {allItems.length===0&&<div style={{fontSize:12,color:"var(--muted)",textAlign:"center",padding:12}}>No events recorded yet</div>}
        {allItems.map(d=>(
          <div key={d.id} onClick={()=>setViewItem(d)} style={{...S.card,cursor:"pointer",marginBottom:8,opacity:d.kind==="delivery"&&d.pickedUpAt?0.6:1}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  <span style={{fontSize:10,color:d.kind==="delivery"?"var(--accent)":d.kind==="fuel"?"#ffab00":"#7ec8e3",fontWeight:800,textTransform:"uppercase"}}>{d.kind==="delivery"?"🚛":d.kind==="fuel"?"⛽":"📤"} {d.kind}</span>
                  {d.kind==="delivery"&&d.pickedUpAt&&<span style={{fontSize:9,color:"#00e676",fontWeight:700}}>✓ Picked Up</span>}
                </div>
                <div style={{fontWeight:800,fontSize:13,color:"var(--text)",marginTop:1}}>{d.type}</div>
                {d.quantity&&<div style={{fontSize:10,color:"var(--muted)"}}>Qty: {d.quantity}{d.kind==="fuel"?" gal":""}</div>}
                <div style={{fontSize:9,color:"var(--dim)",marginTop:1}}>{new Date(d.deliveredAt||d.recordedAt).toLocaleString()}</div>
              </div>
              {d.kind==="delivery"&&!d.pickedUpAt&&<div style={{fontSize:11,fontWeight:800,color:"#ffab00"}}>{daysOnSite(d.deliveredAt)}</div>}
            </div>
          </div>
        ))}
      </div>}

      {/* Summary panel */}
      {activePanel==="summary"&&<div style={{...S.card,marginBottom:12}}>
        <div style={{fontSize:12,fontWeight:900,color:"var(--text)",marginBottom:12}}>PROJECT SUMMARY</div>

        {/* Fuel */}
        <div style={{background:"rgba(255,165,0,0.06)",borderRadius:10,padding:12,border:"1px solid rgba(255,165,0,0.15)",marginBottom:10}}>
          <div style={{fontSize:10,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:6}}>⛽ Fuel Usage</div>
          <div style={{fontSize:22,fontWeight:900,color:"var(--accent)",fontFamily:"var(--mono)"}}>{totalFuelGal.toLocaleString()} <span style={{fontSize:12,fontWeight:600}}>gal</span></div>
          <div style={{fontSize:10,color:"var(--muted)"}}>{(deliveries||[]).filter(d=>d.kind==="fuel").length} load{(deliveries||[]).filter(d=>d.kind==="fuel").length!==1?"s":""} of fuel</div>
        </div>

        {/* Equipment on site by type */}
        <div style={{background:"rgba(255,171,0,0.06)",borderRadius:10,padding:12,border:"1px solid rgba(255,171,0,0.15)",marginBottom:10}}>
          <div style={{fontSize:10,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:8}}>🚛 Equipment On Site — {onSiteEquipment.length} Total</div>
          {(()=>{
            const byType={};
            onSiteEquipment.forEach(d=>{byType[d.type]=(byType[d.type]||0)+1;});
            const keys=Object.keys(byType);
            if(keys.length===0) return <div style={{fontSize:11,color:"var(--muted)"}}>No equipment currently on site</div>;
            return keys.map(t=>(
              <div key={t} style={{display:"flex",justifyContent:"space-between",alignItems:"center",paddingBottom:5,marginBottom:5,borderBottom:"1px solid rgba(0,0,0,0.06)"}}>
                <span style={{fontSize:12,color:"var(--text)"}}>{t}</span>
                <span style={{fontSize:14,fontWeight:900,color:"#ffab00",fontFamily:"var(--mono)"}}>{byType[t]}</span>
              </div>
            ));
          })()}
          {(()=>{
            const allDel=(deliveries||[]).filter(d=>d.kind==="delivery");
            const byType={};
            allDel.forEach(d=>{byType[d.type]=(byType[d.type]||0)+1;});
            const keys=Object.keys(byType);
            if(keys.length===0||allDel.length===onSiteEquipment.length) return null;
            return <div style={{marginTop:8,paddingTop:8,borderTop:"1px solid rgba(0,0,0,0.06)"}}>
              <div style={{fontSize:9,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:5}}>All Deliveries (incl. picked up)</div>
              {keys.map(t=>(
                <div key={t} style={{display:"flex",justifyContent:"space-between",alignItems:"center",paddingBottom:3,marginBottom:3}}>
                  <span style={{fontSize:11,color:"var(--muted)"}}>{t}</span>
                  <span style={{fontSize:12,fontWeight:800,color:"var(--text)",fontFamily:"var(--mono)"}}>{byType[t]}</span>
                </div>
              ))}
            </div>;
          })()}
        </div>

        {/* Pickups by type */}
        <div style={{background:"rgba(126,200,227,0.06)",borderRadius:10,padding:12,border:"1px solid rgba(126,200,227,0.15)",marginBottom:10}}>
          <div style={{fontSize:10,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:8}}>📤 Pick-Ups by Type — {(deliveries||[]).filter(d=>d.kind==="pickup").length} Total</div>
          {(()=>{
            const pickups=(deliveries||[]).filter(d=>d.kind==="pickup");
            const byType={};
            pickups.forEach(d=>{byType[d.type]=(byType[d.type]||0)+1;});
            const keys=Object.keys(byType);
            if(keys.length===0) return <div style={{fontSize:11,color:"var(--muted)"}}>No pick-ups recorded</div>;
            return keys.map(t=>(
              <div key={t} style={{display:"flex",justifyContent:"space-between",alignItems:"center",paddingBottom:5,marginBottom:5,borderBottom:"1px solid rgba(0,0,0,0.06)"}}>
                <span style={{fontSize:12,color:"var(--text)"}}>{t}</span>
                <span style={{fontSize:14,fontWeight:900,color:"#7ec8e3",fontFamily:"var(--mono)"}}>{byType[t]}</span>
              </div>
            ));
          })()}
        </div>

        {/* Picked up equipment */}
        <div style={{background:"rgba(0,230,118,0.06)",borderRadius:10,padding:12,border:"1px solid rgba(0,230,118,0.15)"}}>
          <div style={{fontSize:10,color:"var(--muted)",fontWeight:700,textTransform:"uppercase",marginBottom:4}}>✓ Equipment Picked Up</div>
          <div style={{fontSize:20,fontWeight:900,color:"#00e676",fontFamily:"var(--mono)"}}>{(deliveries||[]).filter(d=>d.kind==="delivery"&&d.pickedUpAt).length} <span style={{fontSize:12,fontWeight:600}}>item{(deliveries||[]).filter(d=>d.kind==="delivery"&&d.pickedUpAt).length!==1?"s":""}</span></div>
        </div>
      </div>}

      {deliveries.length===0&&activePanel===null&&<div style={{textAlign:"center",padding:32,color:"var(--dim)"}}>No deliveries or pick-ups recorded yet.<br/>Use the buttons above to log events.</div>}
    </div>
  );
}

