/* ───────────────────────── CEMETERY · RECORDS ARCHIVE + MEMORIAL ───────────────────────── */
function plotValue(rec){
  const secIdx = SECTIONS.findIndex(s=>s.id===rec.section.id);
  const base = 1800 + secIdx*220 + (rec.vet?400:0);
  return base + (rec.id % 9)*150;
}

function RecordsArchive({query}){
  const [sel, setSel] = useState(null);
  const [vetOnly, setVetOnly] = useState(false);
  const [sort, setSort] = useState("name");
  const [secFilter, setSecFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [bump, setBump] = useState(0);

  const interred = useMemo(()=>ALL_RECORDS.filter(r=>r.name),[]);
  const rows = useMemo(()=>{
    let list = interred;
    const q = (query||"").trim().toLowerCase();
    if(q) list = list.filter(r=> r.name.toLowerCase().includes(q) || r.plot.toLowerCase().includes(q) || r.sur.toLowerCase().includes(q) || String(r.birth).includes(q) || String(r.death).includes(q) || (r.notes||"").toLowerCase().includes(q));
    if(vetOnly) list = list.filter(r=>r.vet);
    if(secFilter!=="all") list = list.filter(r=>r.section.id===secFilter);
    if(statusFilter!=="all") list = list.filter(r=>r.status===statusFilter);
    list = [...list].sort((a,b)=> sort==="name"? a.sur.localeCompare(b.sur) : sort==="death"? b.death-a.death : sort==="value"? plotValue(b)-plotValue(a) : a.plot.localeCompare(b.plot));
    return list.slice(0,140);
  },[interred,query,vetOnly,sort,secFilter,statusFilter,bump]);

  const clearable = vetOnly||secFilter!=="all"||statusFilter!=="all";

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Records</h1>
          <div className="sub">{interred.length.toLocaleString()} interments · every name searchable in seconds</div>
        </div>
        <button className="btn primary" onClick={()=>window.__openImport&&window.__openImport()}>＋ Import records</button>
      </div>

      <div className="toolbar">
        <div className="seg">
          <button className={sort==="name"?"on":""} onClick={()=>setSort("name")}>Name</button>
          <button className={sort==="death"?"on":""} onClick={()=>setSort("death")}>Year</button>
          <button className={sort==="plot"?"on":""} onClick={()=>setSort("plot")}>Plot</button>
          <button className={sort==="value"?"on":""} onClick={()=>setSort("value")}>Value</button>
        </div>
        <select className="finp" style={{width:"auto",padding:"8px 12px",fontSize:13}} value={secFilter} onChange={e=>setSecFilter(e.target.value)}>
          <option value="all">All sections</option>
          {SECTIONS.map(s=><option key={s.id} value={s.id}>{s.id} · {s.name}</option>)}
        </select>
        <select className="finp" style={{width:"auto",padding:"8px 12px",fontSize:13}} value={statusFilter} onChange={e=>setStatusFilter(e.target.value)}>
          <option value="all">Any status</option>
          {Object.keys(STATUS_META).filter(k=>k!=="available").map(k=><option key={k} value={k}>{STATUS_META[k].label}</option>)}
        </select>
        <button className={"chip"+(vetOnly?" on":"")} onClick={()=>setVetOnly(v=>!v)}><span className="sw" style={{background:"var(--accent)"}}></span>★ Veterans</button>
        {clearable && <button className="chip" onClick={()=>{setVetOnly(false);setSecFilter("all");setStatusFilter("all");}}>Clear ✕</button>}
        <div className="spacer"></div>
        <span className="mono" style={{fontSize:12,color:"var(--faint)"}}>{rows.length} shown</span>
      </div>

      <div className="card" style={{overflow:"hidden"}}>
        <table className="tbl">
          <thead><tr><th>Name</th><th>Lifespan</th><th>Plot</th><th>Section</th><th>Status</th><th>Service</th><th style={{textAlign:"right"}}>Plot value</th></tr></thead>
          <tbody>
            {rows.map(r=>(
              <tr key={r.id} className={sel&&sel.id===r.id?"sel":""} onClick={()=>setSel(r)}>
                <td><div className="nm">{r.name}</div><div className="sub">{r.sur} family · {FAMILY_COUNTS[r.sur]} linked</div></td>
                <td>{r.birth} – {r.death}</td>
                <td className="mono" style={{fontSize:12.5}}>{r.plot}</td>
                <td>{r.section.name}</td>
                <td><Pill status={r.status} /></td>
                <td>{r.vet? <VetPill vet={r.vet} small/> : <span className="muted">—</span>}</td>
                <td style={{textAlign:"right",fontWeight:600}}>${plotValue(r).toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {sel && <RecordSheet rec={sel} onClose={()=>setSel(null)} onChange={()=>setBump(b=>b+1)} />}
    </div>
  );
}

function recordDocs(rec){
  const docs = [
    {n:"Right of Interment Deed", t:"Deed", pages:2, stat:"verified", when:"Imported"},
    {n:"Burial Permit", t:"Permit", pages:1, stat:"verified", when:"Imported"},
  ];
  if(rec.id % 2===0) docs.push({n:"Death Certificate", t:"Certificate", pages:1, stat:"verified", when:"Imported"});
  if(rec.vet) docs.push({n:"DD‑214 Service Record", t:"Military", pages:3, stat:"verified", when:"Imported"});
  if(rec.id % 3===0) docs.push({n:"Obituary clipping", t:"Obituary", pages:1, stat:"uploaded", when:"Family upload"});
  return docs;
}

function RecordSheet({rec, onClose, onChange}){
  const [hist,setHist] = useState(()=>editHistory(rec));
  const [editing,setEditing] = useState(false);
  const [docs,setDocs] = useState(()=>recordDocs(rec));
  const [photos,setPhotos] = useState(()=> rec.id % 2===0 ? ["/images/grounds-rows.jpg"] : []);
  const [notes,setNotes] = useState(rec.notes||"");
  const [noteDraft,setNoteDraft] = useState(rec.notes||"");
  const [noteEdit,setNoteEdit] = useState(false);
  const saveNote = ()=>{ rec.notes = noteDraft.trim(); setNotes(rec.notes); setNoteEdit(false); setHist(h=>[{who:"R. Tillman", what:"Note updated", when:new Date().toISOString().slice(0,10)}, ...h]); onChange&&onChange(); window.__toast&&window.__toast({label:"Saved", title:"Note updated", sub:rec.name}); };
  const [form,setForm] = useState(()=>({name:rec.name,birth:rec.birth,death:rec.death,status:rec.status,plot:rec.plot,sectionId:rec.section.id,vetBranch:rec.vet?rec.vet.branch:"",vetConflict:rec.vet?rec.vet.conflict:""}));
  const fam = FAMILY_COUNTS[rec.sur]||1;
  const setF = (k,v)=>setForm(f=>({...f,[k]:v}));

  const uploadPhoto = ()=>{
    const pool=["/images/grounds-hero.jpg","/images/grounds-rows.jpg","/images/church-cross.jpg"];
    const p=pool[photos.length % pool.length];
    setPhotos(ps=>[...ps,p]);
    setHist(h=>[{who:"R. Tillman", what:"Photo added to record", when:new Date().toISOString().slice(0,10)}, ...h]);
    window.__toast && window.__toast({label:"Uploaded", title:"Photo added", sub:rec.name});
  };

  const uploadDoc = ()=>{
    const names=["Funeral program","Headstone photo","Plot survey","Correspondence"];
    const n=names[docs.length % names.length];
    setDocs(d=>[...d,{n, t:"Scan", pages:1, stat:"uploaded", when:"Just now"}]);
    setHist(h=>[{who:"R. Tillman", what:"Document uploaded: "+n, when:new Date().toISOString().slice(0,10)}, ...h]);
    window.__toast && window.__toast({label:"Uploaded", title:"Document attached", sub:n+" · "+rec.name});
  };

  const save = ()=>{
    rec.name = form.name;
    rec.birth = +form.birth; rec.death = +form.death;
    rec.status = form.status; rec.plot = form.plot;
    const sec = SECTIONS.find(s=>s.id===form.sectionId); if(sec) rec.section = sec;
    rec.vet = form.vetBranch ? {branch:form.vetBranch, conflict:form.vetConflict||""} : null;
    rec.sur = (form.name||"").trim().split(" ").slice(-1)[0] || rec.sur;
    setHist(h=>[{who:"R. Tillman", what:"Record edited", when:new Date().toISOString().slice(0,10)}, ...h]);
    setEditing(false);
    onChange && onChange();
  };

  return (
    <div className="sheet" key={rec.id}>
      <div className="sheet-h">
        <div className="rec-port" style={{position:"static",width:54,height:54}}></div>
        <div style={{flex:1}}>
          <div style={{fontFamily:"var(--font-display)",fontWeight:600,fontSize:20}}>{rec.name}</div>
          <div className="muted" style={{fontSize:12.5}}>{rec.birth} – {rec.death} · {rec.plot}</div>
          <div className="rec-tags" style={{marginTop:8}}><Pill status={rec.status}/>{rec.vet&&<VetPill vet={rec.vet}/>}</div>
        </div>
        <button className="x" onClick={onClose}>×</button>
      </div>
      <div className="sheet-b">
        {!editing && (
          <div style={{display:"flex",justifyContent:"flex-end",marginBottom:6}}>
            <button className="edit-pencil" onClick={()=>setEditing(true)}>✎ Edit information</button>
          </div>
        )}

        {editing ? (
          <div className="fade-in">
            <div className="edit-grid">
              <div className="full"><label className="flbl">Full name</label><input className="finp" value={form.name||""} onChange={e=>setF("name",e.target.value)} /></div>
              <div><label className="flbl">Born</label><input className="finp" value={form.birth} onChange={e=>setF("birth",e.target.value)} /></div>
              <div><label className="flbl">Died</label><input className="finp" value={form.death} onChange={e=>setF("death",e.target.value)} /></div>
              <div><label className="flbl">Plot</label><input className="finp" value={form.plot} onChange={e=>setF("plot",e.target.value)} /></div>
              <div><label className="flbl">Section</label>
                <select className="finp" value={form.sectionId} onChange={e=>setF("sectionId",e.target.value)}>
                  {SECTIONS.map(s=><option key={s.id} value={s.id}>{s.id} · {s.name}</option>)}
                </select>
              </div>
              <div className="full"><label className="flbl">Status</label>
                <select className="finp" value={form.status} onChange={e=>setF("status",e.target.value)}>
                  {Object.keys(STATUS_META).map(k=><option key={k} value={k}>{STATUS_META[k].label}</option>)}
                </select>
              </div>
              <div><label className="flbl">Veteran — branch</label>
                <select className="finp" value={form.vetBranch} onChange={e=>setF("vetBranch",e.target.value)}>
                  <option value="">— Not a veteran —</option>
                  {BRANCHES.map(b=><option key={b} value={b}>{b}</option>)}
                </select>
              </div>
              <div><label className="flbl">Conflict / era</label>
                <select className="finp" value={form.vetConflict} onChange={e=>setF("vetConflict",e.target.value)} disabled={!form.vetBranch}>
                  <option value="">—</option>
                  {CONFLICTS.map(c=><option key={c} value={c}>{c}</option>)}
                </select>
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="rec-rows" style={{borderTop:"none"}}>
              <div className="r"><span>Section</span><b>{rec.section.name} · {rec.section.id}</b></div>
              <div className="r"><span>Interred</span><b>{rec.interred}</b></div>
              {rec.vet&&<div className="r"><span>Service</span><b>{rec.vet.branch} · {rec.vet.conflict}</b></div>}
              <div className="r"><span>Family</span><b>{rec.sur} · {fam} linked</b></div>
              <div className="r"><span>Memorial</span><b>{rec.candles} candles · {rec.tributes} tributes</b></div>
            </div>

            <div className="sec-h"><h3>Family</h3><div className="ln"></div></div>
            <div className="fam" style={{marginTop:4}}>
              {Array.from({length:Math.min(6,fam)}).map((_,i)=><div key={i} className="fa"></div>)}
              <span className="fm">{fam} linked in {rec.sur} tree</span>
            </div>

            {rec.interment && (
              <>
                <div className="sec-h"><h3>Interment &amp; service</h3><div className="ln"></div><span className="cnt" style={{color:"var(--brand)"}}>Scheduled</span></div>
                <div className="report-box" style={{background:"color-mix(in oklab,var(--brand) 6%,var(--paper))",borderColor:"color-mix(in oklab,var(--brand) 26%,var(--line))"}}>
                  <div className="rb-h"><div className="ic" style={{background:"var(--brand)"}}>◳</div><b>{rec.interment.dateText}</b></div>
                  <div className="rec-rows" style={{borderTop:"none"}}>
                    <div className="r"><span>Type</span><b>{rec.interment.type}</b></div>
                    {rec.interment.source
                      ? <div className="r"><span>Funeral home</span><b style={{color:"var(--info)"}}>⇄ {rec.interment.source}</b></div>
                      : <div className="r"><span>Arranged</span><b>Direct with family</b></div>}
                    <div className="r"><span>Officiant</span><b>{rec.interment.celebrant}</b></div>
                  </div>
                  <div className="rb-note" style={{marginTop:10}}>{rec.interment.service}</div>
                </div>
              </>
            )}

            <div className="sec-h"><h3>Photos</h3><div className="ln"></div><span className="cnt">{photos.length}</span></div>
            <div className="rec-photos">
              {photos.map((p,i)=>(<div key={i} className="rec-photo"><img src={p} alt="" /></div>))}
              <button className="rec-photo add" onClick={uploadPhoto}>＋<span>Add photo</span></button>
            </div>

            <div className="sec-h"><h3>Scanned documents</h3><div className="ln"></div><span className="cnt">{docs.length}</span></div>
            {docs.map((d,i)=>(
              <div key={i} className="doc-row">
                <div className="doc-ic">{d.t==="Military"?"★":d.t==="Obituary"?"❝":"▤"}</div>
                <div className="doc-meta"><div className="dn">{d.n}</div><div className="dm">{d.pages} page{d.pages>1?"s":""} · PDF · {d.when}</div></div>
                <span className={"doc-stat "+d.stat}>{d.stat}</span>
                <button className="doc-dl" title="Download PDF" onClick={()=>window.__toast&&window.__toast({label:"Download",title:d.n,sub:"PDF · "+rec.name})}>⤓</button>
              </div>
            ))}
            <button className="doc-up" onClick={uploadDoc}>⊕ Upload a scanned document</button>
          </>
        )}

        <div className="sec-h"><h3>Notes</h3><div className="ln"></div>{!noteEdit && <span className="edit-pencil" onClick={()=>{setNoteDraft(notes);setNoteEdit(true);}}>✎ Edit</span>}</div>
        {noteEdit ? (
          <div>
            <textarea className="finp" rows={3} value={noteDraft} onChange={e=>setNoteDraft(e.target.value)} placeholder="Add a note — family contact, marker condition, special instructions… (searchable)" style={{resize:"vertical"}} />
            <div style={{display:"flex",gap:8,marginTop:8}}>
              <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={()=>setNoteEdit(false)}>Cancel</button>
              <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={saveNote}>Save note</button>
            </div>
          </div>
        ) : (
          notes
            ? <p style={{fontSize:13.5,color:"#34372E",lineHeight:1.55,background:"var(--paper)",border:"1px solid var(--line)",borderRadius:11,padding:"12px 14px",whiteSpace:"pre-wrap"}}>{notes}</p>
            : <p className="muted" style={{fontSize:13,fontStyle:"italic"}}>No notes yet. Notes are searchable across records.</p>
        )}

        <div className="sec-h"><h3>Change history</h3><div className="ln"></div><span className="cnt">{hist.length}</span></div>
        <div className="timeline">
          {hist.map((h,i)=>(
            <div key={i} className={"tl"+(i===0?" now":" done")}>
              <div className="tlt">{h.what}</div>
              <div className="tld">{h.who} · {h.when}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="sheet-foot">
        {editing ? (
          <>
            <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={()=>setEditing(false)}>Cancel</button>
            <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={save}>Save changes</button>
          </>
        ) : (
          <>
            <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={()=>window.__openMemorial&&window.__openMemorial(rec)}>View memorial</button>
            <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={()=>setEditing(true)}>✎ Edit record</button>
          </>
        )}
      </div>
    </div>
  );
}

/* ───── DIGITAL MEMORIAL PAGE (family-facing) ───── */
function MemorialPage({rec, onClose}){
  const [candles,setCandles] = useState(rec.candles);
  const [lit,setLit] = useState(false);
  const fam = FAMILY_COUNTS[rec.sur]||1;
  const rnd = mulberry32(rec.id+3);
  const NOTES = [
    {by:`The ${rec.sur} family`, txt:"Forever in our hearts. We carry your stories with us every single day."},
    {by:"A neighbor", txt:"A kind soul who knew everyone on the street by name. Sorely missed."},
    {by:"Grandchild", txt:"Sunday dinners will never be the same. Thank you for everything."},
  ];
  return (
    <div className="overlay" onClick={(e)=>{if(e.target.classList.contains("overlay"))onClose();}}>
      <div className="modal" style={{width:"min(620px,100%)",maxHeight:"92vh",overflowY:"auto"}}>
        <div style={{height:150,background:"repeating-linear-gradient(135deg,color-mix(in oklab,var(--brand) 24%,var(--paper)) 0 10px,color-mix(in oklab,var(--brand) 12%,var(--paper)) 10px 20px)",position:"relative"}}>
          <button className="x" style={{position:"absolute",top:12,right:14,color:"#fff",background:"rgba(0,0,0,.25)",border:0,width:30,height:30,borderRadius:8,fontSize:18}} onClick={onClose}>×</button>
          <div style={{position:"absolute",left:24,bottom:-34,width:84,height:84,borderRadius:18,border:"4px solid var(--card)",background:"repeating-linear-gradient(135deg,#7e9485 0 7px,#6d8576 7px 14px)"}}></div>
        </div>
        <div style={{padding:"44px 24px 24px"}}>
          <div className="eyebrow">In loving memory</div>
          <h2 style={{fontSize:28,marginTop:6}}>{rec.name}</h2>
          <div className="muted" style={{marginTop:4}}>{rec.birth} — {rec.death} · A life well lived</div>
          <div className="rec-tags" style={{marginTop:12}}>
            {rec.vet&&<VetPill vet={rec.vet}/>}
            <span className="pill">🕯 {candles} candles</span>
            <span className="pill">{rec.tributes} tributes</span>
          </div>

          <div style={{display:"flex",gap:10,marginTop:18}}>
            <button className="btn gold" style={{flex:1,justifyContent:"center"}} disabled={lit}
              onClick={()=>{if(!lit){setCandles(c=>c+1);setLit(true);}}}>
              🕯 {lit?"Candle lit":"Light a candle"}
            </button>
            <button className="btn ghost" style={{flex:1,justifyContent:"center"}}>＋ Add tribute</button>
          </div>

          <div className="sec-h"><h3>Tributes</h3><div className="ln"></div><span className="cnt">{rec.tributes}</span></div>
          {NOTES.map((n,i)=>(
            <div key={i} className="card" style={{padding:"13px 15px",marginBottom:10,display:"flex",gap:12}}>
              <div className="fa" style={{width:36,height:36,borderRadius:"50%",flex:"none"}}></div>
              <div>
                <b style={{fontSize:13.5}}>{n.by}</b>
                <p className="muted" style={{fontSize:13.5,marginTop:3,fontFamily:"var(--font-display)",fontStyle:"italic"}}>“{n.txt}”</p>
              </div>
            </div>
          ))}

          <div className="sec-h"><h3>Gallery</h3><div className="ln"></div></div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}}>
            {Array.from({length:4}).map((_,i)=>(
              <div key={i} style={{aspectRatio:"1",borderRadius:9,border:"1px solid var(--line)",background:`repeating-linear-gradient(${30+i*25}deg,color-mix(in oklab,var(--brand) ${14+i*3}%,var(--paper)) 0 7px,color-mix(in oklab,var(--brand) 7%,var(--paper)) 7px 14px)`}}></div>
            ))}
          </div>
          <p className="muted center" style={{fontSize:12,marginTop:16,fontFamily:"var(--font-mono)"}}>tendmory.com/m/{rec.sur.toLowerCase()}-{rec.id}</p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RecordsArchive, RecordSheet, MemorialPage });
