/* ───────────────────────── CEMETERY · SCHEDULE / INTERMENTS CALENDAR ───────────────────────── */
function buildWeek(){
  const base = new Date(); base.setHours(0,0,0,0);
  const days = [];
  for(let i=0;i<7;i++){ const d=new Date(base); d.setDate(base.getDate()+i); days.push(d); }
  return days;
}
const DOW = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

function Schedule(){
  const week = useMemo(buildWeek,[]);
  const [bump,setBump] = useState(0);
  const [sel,setSel] = useState(null);     // selected record → detail drawer
  const [leaving,setLeaving] = useState(null);

  const events = useMemo(()=>ALL_RECORDS.filter(r=>r.interment), [bump]);

  // incoming arrangements target reserved records that don't yet have a confirmed interment
  const pool = useMemo(()=>ALL_RECORDS.filter(r=>r.status==="reserved" && r.name && !r.interment).slice(0,2),[]);
  const [incoming,setIncoming] = useState(()=>pool.map((r,i)=>({
    id:r.id, rec:r,
    plan: i===0
      ? {day:1, time:"10:00 AM", type:"Burial", source:"Riverside Funeral Home", service:"Family requests veteran honors. Graveside service 30 min.", celebrant:"Rev. T. Hale", note:"Veteran honors + flag detail."}
      : {day:2, time:"11:30 AM", type:"Burial", source:"Hartwell Funeral Home", service:"Tent + 40 chairs requested. Reception off-site.", celebrant:"Rev. M. Doyle", note:"Tent + 40 chairs."}
  })));

  function dayLabel(d){ return d===0?"Today":d===1?"Tomorrow":DOW[week[d].getDay()]+" "+week[d].getDate(); }

  const accept = (item)=>{
    setLeaving(item.id);
    setTimeout(()=>{
      item.rec.interment = {...item.plan, status:"confirmed", dateText: intermentDayText(item.plan.day, item.plan.time)};
      setIncoming(list=>list.filter(x=>x.id!==item.id));
      setBump(b=>b+1); setLeaving(null);
      window.__toast && window.__toast({label:"Interment confirmed", title:item.rec.name+" · "+dayLabel(item.plan.day), sub:"Synced to "+item.plan.source+" · plot "+item.rec.plot+" reserved"});
    },300);
  };

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Schedule</h1>
          <div className="sub">{events.length} interments this week · {incoming.length} arrangement{incoming.length===1?"":"s"} awaiting confirmation</div>
        </div>
        <button className="btn primary">＋ Add interment</button>
      </div>

      <div className="arr-banner">
        <div className="ic">⇄</div>
        <div style={{flex:1}}>
          <b>Incoming from funeral homes</b>
          <p>Partner funeral homes send internment arrangements straight to your calendar — confirm to reserve the plot and lock the time.</p>
        </div>
      </div>

      {incoming.length>0 ? incoming.map(a=>(
        <div key={a.id} className={"arr-card"+(leaving===a.id?" leaving":"")}>
          <div className="arr-src">⚱</div>
          <div className="arr-main">
            <div className="arr-top">
              <span className="arr-when">{a.plan.day===1?"Tomorrow":a.plan.day===0?"Today":DOW[week[a.plan.day].getDay()]} · {a.plan.time}</span>
              <span className="arr-name">{a.rec.name}</span>
            </div>
            <div className="arr-meta">{a.plan.type} · plot {a.rec.plot} · {a.rec.section.name} — {a.plan.note}</div>
            <div className="arr-from">⇄ Sent by {a.plan.source}</div>
          </div>
          <div className="arr-acts">
            <button className="mod-btn approve" onClick={()=>accept(a)}>✓ Confirm</button>
            <button className="mod-btn reject" onClick={()=>setIncoming(list=>list.filter(x=>x.id!==a.id))}>Decline</button>
          </div>
        </div>
      )) : (
        <div className="card" style={{padding:"16px 18px",marginBottom:16,display:"flex",alignItems:"center",gap:10,color:"var(--muted)",fontSize:13.5}}>
          <span style={{color:"var(--ok)"}}>✓</span> All incoming arrangements confirmed.
        </div>
      )}

      <div className="sec-h"><h3>This week</h3><div className="ln"></div><span className="cnt">{week[0].toLocaleString("en-US",{month:"long"})}</span></div>
      <div className="cal">
        <div className="cal-grid">
          {week.map((d,i)=>{
            const dayEvents = events.filter(e=>e.interment.day===i).sort((a,b)=>a.interment.time.localeCompare(b.interment.time));
            return (
              <div key={i} className={"cal-day"+(i===0?" today":"")+(i===1?" tomorrow":"")}>
                <div className="cal-dh">
                  <div className="dow">{i===0?"Today":i===1?"Tomorrow":DOW[d.getDay()]}</div>
                  <div className="dnum">{d.getDate()}</div>
                </div>
                <div className="cal-body">
                  {dayEvents.length===0 && <div className="cal-empty">—</div>}
                  {dayEvents.map(r=>(
                    <div key={r.id} className={"cal-ev"+(r.interment.type==="Urn interment"?" urn":"")} onClick={()=>setSel(r)}>
                      <div className="et">{r.interment.time}</div>
                      <div className="en">{r.name}</div>
                      <div className="ep">{r.interment.type} · {r.plot}</div>
                      {r.interment.source && <div className="esync">⇄ Synced · {r.interment.source.split(" ")[0]}</div>}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {sel && <InternmentDrawer rec={sel} dayLabel={dayLabel} onClose={()=>setSel(null)} />}
    </div>
  );
}

function InternmentDrawer({rec, dayLabel, onClose}){
  const it = rec.interment;
  return (
    <div className="sheet" key={rec.id}>
      <div className="sheet-h">
        <div style={{flex:1}}>
          <div className="eyebrow">Interment · {dayLabel(it.day)}</div>
          <div style={{fontFamily:"var(--font-display)",fontWeight:700,fontSize:19,marginTop:6}}>{rec.name}</div>
          <div className="muted" style={{fontSize:12.5,marginTop:2}}>{rec.birth} – {rec.death} · plot {rec.plot}</div>
          <div className="rec-tags" style={{marginTop:9}}>
            <span className="pill" style={{color:"var(--brand)",borderColor:"color-mix(in oklab,var(--brand) 32%,transparent)"}}><i className="pd"></i>{it.type}</span>
            {rec.vet && <VetPill vet={rec.vet} />}
          </div>
        </div>
        <button className="x" onClick={onClose}>×</button>
      </div>
      <div className="sheet-b">
        <div style={{display:"flex",alignItems:"center",gap:11,padding:"13px 14px",borderRadius:12,background:"color-mix(in oklab,var(--brand) 8%,var(--paper))",border:"1px solid color-mix(in oklab,var(--brand) 22%,transparent)",marginBottom:6}}>
          <div style={{fontFamily:"var(--font-display)",fontWeight:700,fontSize:22,color:"var(--brand)",lineHeight:1}}>{it.time.split(" ")[0]}<span style={{fontSize:12,marginLeft:3}}>{it.time.split(" ")[1]}</span></div>
          <div style={{borderLeft:"1px solid var(--line)",paddingLeft:11}}>
            <div style={{fontWeight:600,fontSize:13.5}}>{dayLabel(it.day)}</div>
            <div className="muted" style={{fontSize:12}}>{rec.section.name}</div>
          </div>
        </div>

        <div className="sec-h"><h3>Arrangement</h3><div className="ln"></div></div>
        <div className="rec-rows" style={{borderTop:"none"}}>
          <div className="r"><span>Type</span><b>{it.type}</b></div>
          <div className="r"><span>Plot</span><b>{rec.plot} · {rec.section.name}</b></div>
          {it.source
            ? <div className="r"><span>Funeral home</span><b style={{color:"var(--info)"}}>⇄ {it.source}</b></div>
            : <div className="r"><span>Arranged</span><b>Direct with family</b></div>}
          <div className="r"><span>Officiant</span><b>{it.celebrant}</b></div>
          <div className="r"><span>Status</span><b style={{color:"var(--ok)"}}>● Confirmed</b></div>
        </div>

        <div className="sec-h"><h3>Service notes</h3><div className="ln"></div></div>
        <p style={{fontSize:13.5,color:"#34372E",lineHeight:1.55,background:"var(--paper)",border:"1px solid var(--line)",borderRadius:11,padding:"13px 14px"}}>{it.service}</p>

        {it.source && (
          <div className="arr-from" style={{marginTop:14}}>⇄ Synced from {it.source} via Tendmory</div>
        )}
      </div>
      <div className="sheet-foot">
        <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={()=>window.__openRecord&&window.__openRecord()}>Open record</button>
        <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={onClose}>Done</button>
      </div>
    </div>
  );
}

Object.assign(window, { Schedule });
