/* ───────────────────────── CEMETERY · CARE LOG + SALES ───────────────────────── */
const TASK_KINDS = ["Mowing","Restoration","Landscaping","Honors","Grounds","Cleaning"];
const REPEATS = ["One-time","Weekly","Monthly","Quarterly","Seasonal"];
const DEFAULT_CREW = [
  {name:"R. Tillman", role:"Superintendent"},
  {name:"Field Team", role:"Grounds crew"},
  {name:"M. Okafor", role:"Groundskeeper"},
  {name:"Tendmory Care crew", role:"Vetted contractor", ext:true},
];
function nextDueText(rep){ return {Weekly:"in 7 days",Monthly:"in ~30 days",Quarterly:"in ~90 days",Seasonal:"next season"}[rep]||""; }
function fmtDate(d){ return d.toLocaleDateString("en-US",{month:"short",day:"numeric"}); }
function addDays(n){ const d=new Date(); d.setDate(d.getDate()+n); return d; }
function nextOccur(rep){ return {Weekly:fmtDate(addDays(7)),Monthly:fmtDate(addDays(30)),Quarterly:fmtDate(addDays(90)),Seasonal:"Next season"}[rep]||""; }
const REPEAT_EVERY = {Weekly:"every 7 days",Monthly:"every month",Quarterly:"every 3 months",Seasonal:"each season"};

function CareLog(){
  const [crew,setCrew] = useState(DEFAULT_CREW);
  const [tasks,setTasks] = useState(()=>[
    {id:1, status:"open", title:"Mow & edge — Section H, Garden of Honor", meta:"Recurs weekly · due today", assignee:"Field Team", kind:"Mowing", repeat:"Weekly", prio:false, nextDue:"Due today", history:[{when:"Jun 20", by:"Field Team", hours:"2.0", note:"Mowed & edged section H, blew clippings off paths."}]},
    {id:2, status:"progress", title:"Reset sunken headstone — Plot C-042", meta:"Reported by family", assignee:"Tendmory Care crew", kind:"Restoration", repeat:"One-time", prio:true},
    {id:3, status:"done", title:"Place flags — all veteran plots", meta:"Memorial Day · 218 plots", assignee:"Field Team", kind:"Honors", repeat:"One-time", prio:false,
      report:{by:"Field Team", when:"Jun 24, 2:40 PM", note:"All 218 veteran plots flagged. Replaced 6 weather-worn flag holders in Garden of Honor. Photos attached.", hours:5.5, photos:2}},
    {id:4, status:"open", title:"Trim hedges — Founders' Rest entrance", meta:"Recurs each season", assignee:"M. Okafor", kind:"Landscaping", repeat:"Seasonal", prio:false, nextDue:"Next season", history:[]},
    {id:5, status:"open", title:"Clean & seal monument — Whitfield, A-118", meta:"Care plan · quarterly", assignee:"Tendmory Care crew", kind:"Restoration", repeat:"Quarterly", prio:false, nextDue:fmtDate(addDays(12)), history:[{when:"Mar 18", by:"Tendmory Care crew", hours:"3.5", note:"Cleaned biological staining, applied breathable sealant."}]},
    {id:6, status:"open", title:"Irrigation check — Memorial Ridge", meta:"Recurs monthly", assignee:"M. Okafor", kind:"Grounds", repeat:"Monthly", prio:false, nextDue:fmtDate(addDays(8)),
      history:[{when:"Jun 22", by:"M. Okafor", hours:"1.5", note:"Tested all zones. Zone 3 head was clogged — cleared and re-tested. System nominal."},{when:"May 21", by:"M. Okafor", hours:"1.0", note:"Routine check, all zones nominal."}]},
  ]);
  const [sel,setSel] = useState(null);
  const [adding,setAdding] = useState(false);
  const [managingCrew,setManagingCrew] = useState(false);
  const open = tasks.filter(t=>t.status!=="done").length;
  const selTask = sel!=null ? tasks.find(t=>t.id===sel) : null;
  const recurring = (t)=>t.repeat && t.repeat!=="One-time";

  const addTask = (t)=>{ const id=Math.max(0,...tasks.map(x=>x.id))+1; const rec=t.repeat&&t.repeat!=="One-time"; setTasks(ts=>[{...t,id,status:"open",history:[],nextDue:rec?nextOccur(t.repeat):null,meta:rec?("Recurs "+t.repeat.toLowerCase()):t.meta}, ...ts]); setAdding(false); window.__toast&&window.__toast({label:"Task created",title:t.title,sub:"Assigned to "+t.assignee}); };
  const setStatus = (id,status)=>setTasks(ts=>ts.map(t=>t.id===id?{...t,status}:t));
  // log one completed cycle of a recurring task → roll to next occurrence
  const logCycle = (id, entry)=>{
    let nd="";
    setTasks(ts=>ts.map(t=>{
      if(t.id!==id) return t;
      nd = nextOccur(t.repeat);
      return {...t, status:"open", report:null, lastDone:entry.when, nextDue:nd, history:[entry,...(t.history||[])], meta:"Recurs "+t.repeat.toLowerCase()+" · next "+nd};
    }));
    window.__toast&&window.__toast({label:"Cycle logged",title:entry.note==="Marked complete"?"Marked done this cycle":"Completion report filed",sub:"Next due "+nd});
  };
  const completeTask = (t)=>{
    if(!recurring(t)){ setStatus(t.id, t.status==="done"?"open":"done"); return; }
    logCycle(t.id, {when:fmtDate(new Date()), by:t.assignee, hours:"—", note:"Marked complete"});
  };
  const addReport = (id,report)=>{
    const t = tasks.find(x=>x.id===id);
    if(t && recurring(t)){ logCycle(id, {when:report.when, by:report.by, hours:report.hours, note:report.note}); return; }
    setTasks(ts=>ts.map(x=>x.id===id?{...x,status:"done",report}:x));
    window.__toast&&window.__toast({label:"Report received",title:"Completion logged",sub:report.by+" · "+report.hours+"h"});
  };
  const addWorker = (w)=>{ setCrew(c=>[...c,w]); window.__toast&&window.__toast({label:"Crew updated",title:w.name+" added",sub:w.role+" · now assignable"}); };

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Care Log</h1>
          <div className="sub">{open} open tasks · {crew.length} crew members · grounds, restoration &amp; seasonal work</div>
        </div>
        <div style={{display:"flex",gap:10}}>
          <button className="btn ghost" onClick={()=>setManagingCrew(true)}>✿ Manage crew</button>
          <button className="btn primary" onClick={()=>setAdding(true)}>＋ New task</button>
        </div>
      </div>

      {/* Tendmory Care promo */}
      <div className="care-promo">
        <div className="ci">✿</div>
        <div style={{flex:1}}>
          <h3>Short-staffed this season? Let <em>Tendmory Care</em> handle it.</h3>
          <p>From full headstone restoration to simple seasonal cleanup — our vetted local crews mow, reset stones, seal monuments and place veteran flags, scheduled and tracked right here, billed by the visit.</p>
          <div style={{display:"inline-flex",alignItems:"center",gap:8,marginTop:11,padding:"6px 12px",borderRadius:999,background:"color-mix(in oklab,var(--ok) 14%,var(--paper))",border:"1px solid color-mix(in oklab,var(--ok) 30%,transparent)",color:"var(--ok)",fontFamily:"var(--font-mono)",fontSize:11.5,fontWeight:700,letterSpacing:".02em"}}>
            ＄ You earn 15% of every Care job booked through your grounds
          </div>
        </div>
        <button className="btn gold" style={{flex:"none"}}>Get a Care quote →</button>
      </div>

      <div className="card" style={{overflow:"hidden"}}>
        {tasks.map(t=>(
          <div key={t.id} className="task" onClick={()=>setSel(t.id)}>
            <div className="cb" onClick={(e)=>{e.stopPropagation(); completeTask(t);}} style={{cursor:"pointer",display:"grid",placeItems:"center",color:"#fff",fontSize:11,background:t.status==="done"?"var(--ok)":"transparent",borderColor:t.status==="done"?"var(--ok)":"var(--line)"}}>{t.status==="done"?"✓":""}</div>
            <div style={{flex:1,minWidth:0}}>
              <div className="tn" style={t.status==="done"?{textDecoration:"line-through",color:"var(--faint)"}:null}><span className="tnt">{t.title}</span> {t.prio&&<span className="tk-prio">High</span>}{recurring(t)&&<span className="tk-rep">↻ {t.repeat}</span>}</div>
              <div className="tm">{t.kind} · {t.meta}{t.report?" · report filed":""}</div>
            </div>
            <span className={"tk-stat tk-"+t.status}>{t.status==="progress"?"In progress":t.status}</span>
            <div className="asn"><div className="av"></div><span className="asn-n">{t.assignee}</span></div>
          </div>
        ))}
      </div>

      {selTask && <TaskDrawer task={selTask} onClose={()=>setSel(null)} onStatus={setStatus} onReport={addReport} recurring={recurring(selTask)} />}
      {adding && <NewTaskModal crew={crew} onClose={()=>setAdding(false)} onAdd={addTask} />}
      {managingCrew && <CrewModal crew={crew} onClose={()=>setManagingCrew(false)} onAdd={addWorker} />}
    </div>
  );
}

function CrewModal({crew, onClose, onAdd}){
  const [name,setName] = useState("");
  const [role,setRole] = useState("Groundskeeper");
  return (
    <div className="overlay" onClick={(e)=>{if(e.target.classList.contains("overlay"))onClose();}}>
      <div className="modal" style={{width:"min(480px,100%)"}}>
        <div className="modal-h">
          <div style={{width:34,height:34,borderRadius:9,background:"color-mix(in oklab,var(--brand) 12%,var(--paper))",color:"var(--brand)",display:"grid",placeItems:"center",flex:"none"}}>✿</div>
          <h3>Care crew</h3>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="modal-b">
          <p className="muted" style={{fontSize:13,marginBottom:14}}>Your grounds crew — anyone here can be assigned care tasks and file completion reports.</p>
          {crew.map((c,i)=>(
            <div key={i} className="doc-row">
              <div className="doc-ic" style={{background:"color-mix(in oklab,var(--brand) 10%,var(--paper))",color:"var(--brand)",borderColor:"color-mix(in oklab,var(--brand) 22%,transparent)",height:34,width:34,borderRadius:"50%"}}>{c.name[0]}</div>
              <div className="doc-meta"><div className="dn">{c.name}</div><div className="dm" style={{fontFamily:"var(--font-body)",letterSpacing:0}}>{c.role}</div></div>
              {c.ext && <span className="doc-stat uploaded">Contractor</span>}
            </div>
          ))}
          <div style={{borderTop:"1px solid var(--line)",margin:"14px 0",paddingTop:14}}>
            <label className="flbl">Add a worker</label>
            <div style={{display:"flex",gap:10,marginTop:2}}>
              <input className="finp" value={name} onChange={e=>setName(e.target.value)} placeholder="Full name" style={{flex:1.4}} />
              <input className="finp" value={role} onChange={e=>setRole(e.target.value)} placeholder="Role" style={{flex:1}} />
            </div>
            <button className="btn primary" style={{width:"100%",justifyContent:"center",marginTop:12,opacity:name.trim()?1:.5,pointerEvents:name.trim()?"auto":"none"}} onClick={()=>{onAdd({name:name.trim(),role:role||"Crew"}); setName("");}}>＋ Add to crew</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function TaskDrawer({task, onClose, onStatus, onReport, recurring}){
  const [logging,setLogging] = useState(false);
  const [note,setNote] = useState("");
  const [hours,setHours] = useState("");
  const submit = ()=>{ if(!note.trim())return; onReport(task.id,{by:task.assignee||"Crew", when:recurring?fmtDate(new Date()):"Just now", note:note.trim(), hours:hours||"2", photos:2}); setLogging(false); if(!recurring) onClose(); else { setNote(""); setHours(""); } };
  return (
    <div className="sheet" key={task.id}>
      <div className="sheet-h">
        <div style={{flex:1}}>
          <div className="eyebrow">{task.kind}{recurring?" · ↻ "+task.repeat:""}</div>
          <div style={{fontFamily:"var(--font-display)",fontWeight:700,fontSize:18,marginTop:6,lineHeight:1.2}}>{task.title}</div>
          <div className="rec-tags" style={{marginTop:9}}><span className={"tk-stat tk-"+task.status}>{task.status==="progress"?"In progress":task.status}</span>{task.prio&&<span className="tk-prio">High priority</span>}{recurring&&<span className="tk-rep">↻ {task.repeat}</span>}</div>
        </div>
        <button className="x" onClick={onClose}>×</button>
      </div>
      <div className="sheet-b">
        <div className="rec-rows" style={{borderTop:"none"}}>
          <div className="r"><span>Assigned to</span><b>{task.assignee}</b></div>
          {recurring
            ? <><div className="r"><span>Repeats</span><b>{REPEAT_EVERY[task.repeat]||task.repeat}</b></div><div className="r"><span>Next due</span><b style={{color:"var(--accent)"}}>{task.nextDue||nextOccur(task.repeat)}</b></div><div className="r"><span>Completed</span><b>{(task.history||[]).length}×</b></div></>
            : <><div className="r"><span>Schedule</span><b>{task.meta}</b></div><div className="r"><span>Status</span><b style={{textTransform:"capitalize"}}>{task.status==="progress"?"In progress":task.status}</b></div></>}
        </div>

        {recurring ? (
          <>
            <div style={{display:"flex",alignItems:"center",gap:10,marginTop:16,padding:"12px 14px",borderRadius:11,background:"color-mix(in oklab,var(--accent) 8%,var(--paper))",border:"1px solid color-mix(in oklab,var(--accent) 26%,transparent)"}}>
              <span style={{color:"var(--accent)",fontSize:16}}>↻</span>
              <span style={{fontSize:12.5,color:"var(--muted)"}}>This task repeats automatically. Log each visit and it rolls forward to <b style={{color:"var(--ink)"}}>{task.nextDue||nextOccur(task.repeat)}</b> — no need to recreate it.</span>
            </div>

            <div className="sec-h"><h3>Log this cycle</h3><div className="ln"></div></div>
            {logging ? (
              <div className="report-box" style={{background:"var(--paper)",borderColor:"var(--line)"}}>
                <label className="flbl">What was done</label>
                <textarea className="finp" rows={3} value={note} onChange={e=>setNote(e.target.value)} placeholder="Describe this visit…" style={{resize:"vertical",marginBottom:10}} />
                <label className="flbl">Hours logged</label>
                <input className="finp" value={hours} onChange={e=>setHours(e.target.value)} placeholder="e.g. 2.0" style={{marginBottom:10}} />
                <div className="doc-up">⊕ Attach photos</div>
                <button className="btn primary" style={{width:"100%",justifyContent:"center",marginTop:12}} onClick={submit}>Log cycle &amp; reschedule</button>
              </div>
            ) : (
              <div style={{display:"flex",gap:10}}>
                <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={()=>{onReport(task.id,{by:task.assignee,when:fmtDate(new Date()),hours:"—",note:"Marked complete"}); onClose();}}>✓ Mark done this cycle</button>
                <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={()=>setLogging(true)}>✎ Log a report</button>
              </div>
            )}

            <div className="sec-h"><h3>Completion history</h3><div className="ln"></div><span className="cnt">{(task.history||[]).length}</span></div>
            {(task.history||[]).length===0
              ? <p className="muted" style={{fontSize:13}}>No visits logged yet.</p>
              : <div className="timeline">{task.history.map((h,i)=>(
                  <div key={i} className={"tl "+(i===0?"now":"done")}>
                    <div className="tlt">{h.note}</div>
                    <div className="tld">{h.by} · {h.when}{h.hours&&h.hours!=="—"?" · "+h.hours+"h":""}</div>
                  </div>
                ))}</div>}
          </>
        ) : (
          <>
            <div className="sec-h"><h3>Status</h3><div className="ln"></div></div>
            <div className="seg" style={{width:"100%"}}>
              {[["open","Open"],["progress","In progress"],["done","Done"]].map(([k,l])=>(
                <button key={k} className={task.status===k?"on":""} style={{flex:1}} onClick={()=>onStatus(task.id,k)}>{l}</button>
              ))}
            </div>

            <div className="sec-h"><h3>Crew report</h3><div className="ln"></div></div>
            {task.report ? (
              <div className="report-box">
                <div className="rb-h"><div className="ic">✓</div><b>Work completed</b><span>{task.report.when}</span></div>
                <div className="rb-note">{task.report.note}</div>
                <div className="rb-photos">
                  <div className="rb-ph"><img src="/images/grounds-rows.jpg" alt="" /><span className="lbl">Before</span></div>
                  <div className="rb-ph"><img src="/images/grounds-hero.jpg" alt="" /><span className="lbl">After</span></div>
                </div>
                <div className="rb-meta"><span>By <b>{task.report.by}</b></span><span><b>{task.report.hours}h</b> logged</span><span><b>{task.report.photos}</b> photos</span></div>
              </div>
            ) : logging ? (
              <div className="report-box" style={{background:"var(--paper)",borderColor:"var(--line)"}}>
                <label className="flbl">What was done</label>
                <textarea className="finp" rows={3} value={note} onChange={e=>setNote(e.target.value)} placeholder="Describe the completed work…" style={{resize:"vertical",marginBottom:10}} />
                <label className="flbl">Hours logged</label>
                <input className="finp" value={hours} onChange={e=>setHours(e.target.value)} placeholder="e.g. 2.5" style={{marginBottom:10}} />
                <div className="doc-up">⊕ Attach before / after photos</div>
                <button className="btn primary" style={{width:"100%",justifyContent:"center",marginTop:12}} onClick={submit}>Submit report</button>
              </div>
            ) : (
              <div style={{textAlign:"center",padding:"18px",border:"1px dashed var(--line)",borderRadius:12,color:"var(--faint)"}}>
                <p style={{fontSize:13.5,marginBottom:12}}>No completion report yet. The crew files one when the work is done.</p>
                <button className="btn ghost" style={{justifyContent:"center"}} onClick={()=>setLogging(true)}>＋ Log completion report</button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function NewTaskModal({crew, onClose, onAdd}){
  const [title,setTitle] = useState("");
  const [kind,setKind] = useState("Mowing");
  const [assignee,setAssignee] = useState((crew[1]||crew[0]).name);
  const [repeat,setRepeat] = useState("One-time");
  const [meta,setMeta] = useState("");
  const [prio,setPrio] = useState(false);
  return (
    <div className="overlay" onClick={(e)=>{if(e.target.classList.contains("overlay"))onClose();}}>
      <div className="modal" style={{width:"min(520px,100%)"}}>
        <div className="modal-h">
          <div style={{width:34,height:34,borderRadius:9,background:"color-mix(in oklab,var(--brand) 12%,var(--paper))",color:"var(--brand)",display:"grid",placeItems:"center",flex:"none"}}>✿</div>
          <h3>New care task</h3>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="modal-b">
          <label className="flbl">Task</label>
          <input className="finp" value={title} onChange={e=>setTitle(e.target.value)} placeholder="e.g. Mow & edge — Section B" style={{marginBottom:14}} autoFocus />
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12,marginBottom:14}}>
            <div><label className="flbl">Type</label>
              <select className="finp" value={kind} onChange={e=>setKind(e.target.value)}>{TASK_KINDS.map(k=><option key={k} value={k}>{k}</option>)}</select>
            </div>
            <div><label className="flbl">Assign to</label>
              <select className="finp" value={assignee} onChange={e=>setAssignee(e.target.value)}>{crew.map((c,i)=><option key={i} value={c.name}>{c.name}</option>)}</select>
            </div>
            <div><label className="flbl">Repeats</label>
              <select className="finp" value={repeat} onChange={e=>setRepeat(e.target.value)}>{REPEATS.map(r=><option key={r} value={r}>{r}</option>)}</select>
            </div>
          </div>
          <label className="flbl">{repeat==="One-time"?"Schedule / note":"Note"}</label>
          <input className="finp" value={meta} onChange={e=>setMeta(e.target.value)} placeholder={repeat==="One-time"?"e.g. due Friday":"e.g. covers all of Section H"} style={{marginBottom:14}} />
          <label className="fpick" style={{display:"inline-flex",width:"auto"}} onClick={()=>setPrio(p=>!p)}>
            <span className="cbx" style={prio?{background:"var(--hold)",borderColor:"var(--hold)"}:null}>{prio?"✓":""}</span>High priority
          </label>
          <button className="btn primary" style={{width:"100%",justifyContent:"center",marginTop:18,opacity:title.trim()?1:.5,pointerEvents:title.trim()?"auto":"none"}} onClick={()=>onAdd({title:title.trim(),kind,assignee,repeat,meta:meta||(repeat==="One-time"?"Unscheduled":""),prio})}>Create task</button>
        </div>
      </div>
    </div>
  );
}

function Sales(){
  const available = useMemo(()=>ALL_RECORDS.filter(r=>r.status==="available"),[]);
  const reserved  = useMemo(()=>ALL_RECORDS.filter(r=>r.status==="reserved"),[]);
  const [deals,setDeals] = useState([
    {id:1, name:"Galloway, pre-need", plot:"R-204", who:"Margaret Galloway", total:2850, paid:950, kind:"Pre-need", monthsLeft:8, overdue:true},
    {id:2, name:"Sutton family", plot:"B-031", who:"Estate of J. Sutton", total:3400, paid:3400, kind:"At-need", monthsLeft:0, overdue:false},
    {id:3, name:"Abbott, pre-need", plot:"C-110", who:"Earl Abbott", total:2400, paid:600, kind:"Pre-need", monthsLeft:12, overdue:false},
  ]);
  const [payContract,setPayContract] = useState(null);
  const inventoryValue = available.reduce((s,r)=>s+(r.listPrice||0),0);
  const collectedYTD = deals.reduce((s,d)=>s+d.paid,0);
  const overdue = deals.filter(d=>d.overdue && d.paid<d.total);

  const stageOf = (d)=> d.paid>=d.total?"Paid in full": d.paid===0?"Contract sent": d.overdue?"Overdue":"On installments";
  const applyPayment = (contract,amt)=>{
    setDeals(ds=>ds.map(d=>d.id===contract.id?{...d, paid:Math.min(d.total,d.paid+amt), overdue:false, monthsLeft:Math.max(0,d.monthsLeft-1)}:d));
    setPayContract(null);
  };
  const remind = (d)=>window.__toast&&window.__toast({label:"Reminder sent",title:"Payment reminder emailed",sub:d.who+" · balance $"+(d.total-d.paid).toLocaleString()});

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Sales &amp; Pre-need</h1>
          <div className="sub">{available.length} plots available · {reserved.length} reserved</div>
        </div>
        <button className="btn primary" onClick={()=>window.__startSale&&window.__startSale(available[0])}>＋ New sale</button>
      </div>

      {overdue.length>0 && (
        <div className="arr-card" style={{borderLeftColor:"var(--hold)",borderColor:"color-mix(in oklab,var(--hold) 26%,var(--line))",background:"color-mix(in oklab,var(--hold) 5%,var(--card))"}}>
          <div className="arr-src" style={{background:"color-mix(in oklab,var(--hold) 14%,var(--paper))",color:"var(--hold)"}}>!</div>
          <div className="arr-main">
            <div className="arr-top"><span className="arr-name">{overdue.length} payment{overdue.length>1?"s":""} overdue</span></div>
            <div className="arr-meta">{overdue.map(d=>d.who).join(", ")} — installment past due. Send a reminder or collect now.</div>
          </div>
          <div className="arr-acts">
            <button className="mod-btn approve" onClick={()=>setPayContract(overdue[0])}>Collect</button>
            <button className="mod-btn reject" onClick={()=>remind(overdue[0])}>Remind</button>
          </div>
        </div>
      )}

      <div className="grid stat-row" style={{marginBottom:20}}>
        <div className="card stat"><div className="k">Available inventory</div><div className="v">{available.length}</div><div className="d">across {SECTIONS.length} sections</div></div>
        <div className="card stat"><div className="k">Inventory value</div><div className="v">${(inventoryValue/1000).toFixed(0)}<span className="u">k</span></div><div className="d">at list price</div></div>
        <div className="card stat"><div className="k">Pre-need active</div><div className="v">{deals.filter(d=>d.kind==="Pre-need"&&d.paid<d.total).length}</div><div className="d">on installment plans</div></div>
        <div className="card stat"><div className="k">Collected to date</div><div className="v">${(collectedYTD/1000).toFixed(1)}<span className="u">k</span></div><div className="d">across open contracts</div></div>
      </div>

      <div className="sec-h"><h3>Open contracts</h3><div className="ln"></div><span className="cnt">{deals.length}</span></div>
      <div className="card" style={{overflow:"hidden"}}>
        <table className="tbl">
          <thead><tr><th>Contract</th><th>Plot</th><th>Type</th><th>Stage</th><th>Balance</th><th></th></tr></thead>
          <tbody>
            {deals.map(d=>{
              const paidUp = d.paid>=d.total;
              return (
              <tr key={d.id}>
                <td><div className="nm" style={{fontSize:14}}>{d.name}</div><div className="sub">{d.who}</div></td>
                <td className="mono" style={{fontSize:12.5}}>{d.plot}</td>
                <td><span className="tag">{d.kind}</span></td>
                <td>{d.overdue&&!paidUp ? <span style={{color:"var(--hold)",fontWeight:600}}>● Overdue</span> : stageOf(d)}</td>
                <td>
                  <b>${(d.total-d.paid).toLocaleString()}</b> <span className="muted" style={{fontSize:11.5}}>/ ${d.total.toLocaleString()}</span>
                  <div className="kbar" style={{marginTop:5,width:110}}><i style={{width:`${d.paid/d.total*100}%`,background:paidUp?"var(--ok)":d.overdue?"var(--hold)":"var(--brand)"}}></i></div>
                </td>
                <td style={{textAlign:"right"}}>{paidUp ? <span className="muted" style={{fontSize:12}}>✓ Settled</span> : <button className="chip" onClick={()=>setPayContract(d)}>＄ Collect</button>}</td>
              </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="sec-h"><h3>Available plots</h3><div className="ln"></div><span className="cnt">{available.length}</span></div>
      <div className="card" style={{overflow:"hidden"}}>
        <table className="tbl">
          <thead><tr><th>Plot</th><th>Section</th><th>Type</th><th>List price</th><th></th></tr></thead>
          <tbody>
            {available.slice(0,8).map(r=>(
              <tr key={r.id}>
                <td className="mono" style={{fontSize:12.5}}>{r.plot}</td>
                <td>{r.section.name}</td>
                <td><span className="tag">Single lawn</span></td>
                <td><b>${r.listPrice.toLocaleString()}</b></td>
                <td style={{textAlign:"right"}}><button className="chip" onClick={()=>window.__startSale&&window.__startSale(r)}>Start sale →</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {payContract && <PaymentModal contract={payContract} onClose={()=>setPayContract(null)} onPaid={applyPayment} />}
    </div>
  );
}

Object.assign(window, { CareLog, Sales });
