const { useState, useEffect, useCallback } = React;
const API = "api";

const TYPES = [
  { key:"surgical", label:"Surgical" }, { key:"icd10", label:"ICD-10" },
  { key:"theatre_time", label:"Theatre time" }, { key:"anaesthetic", label:"Anaesthetic" },
  { key:"asa", label:"ASA" }, { key:"other", label:"Other" },
];
const STAGES = [
  { key:"st_detail", short:"Detail" }, { key:"st_ms", short:"MS" },
  { key:"st_cv", short:"CV" }, { key:"st_rp", short:"RP" },
];

// ---- code reference for the readable summary + quick-picks ----
const CODE_REF = {
  "0039":{t:"anaesthetic",d:"General anaesthetic"},"0023":{t:"anaesthetic",d:"Sedation"},
  "1218":{t:"surgical",d:"Appendicectomy"},"2814":{t:"surgical",d:"Lap cholecystectomy"},
  "3092":{t:"surgical",d:"Knee arthroscopy"},"0147":{t:"theatre_time",d:"Theatre time"},
  "543":{t:"asa",d:"ASA modifier"},"K35.8":{t:"icd10",d:"Acute appendicitis"},
  "K80.2":{t:"icd10",d:"Gallstones"},"M23.2":{t:"icd10",d:"Meniscus tear"},
};
const lookup = raw => {
  const code = raw.trim().toUpperCase();
  const h = CODE_REF[code] || CODE_REF[raw.trim()];
  return h ? { code, code_type:h.t, description:h.d } : { code, code_type:"surgical", description:null };
};

// ===========================================================================
// Case-number generator (runs entirely in the browser — no data leaves here)
//   Structure: first 3 letters of SURNAME + 2-digit MONTH + first 3 of HOSPITAL
//   e.g. Mabitsela, July, Milpark -> MAB07MIL
// ===========================================================================
function makeCaseNumber(surname, hospital, dateStr) {
  const s = (surname||"").replace(/[^a-z]/gi,"").toUpperCase().slice(0,3).padEnd(3,"X");
  const h = (hospital||"").replace(/[^a-z]/gi,"").toUpperCase().slice(0,3).padEnd(3,"X");
  let mm = "00";
  if (dateStr) { const d = new Date(dateStr); if(!isNaN(d)) mm = String(d.getMonth()+1).padStart(2,"0"); }
  return s + mm + h;
}

async function api(path, opts={}) {
  const res = await fetch(`${API}/${path}`, {
    credentials:"same-origin",
    headers: opts.body && !(opts.body instanceof FormData) ? {"Content-Type":"application/json"} : undefined,
    ...opts });
  let d; try { d = await res.json(); } catch { d = {ok:false,error:"Bad response"}; }
  if (!res.ok || d.ok===false) throw new Error(d.error||`Error ${res.status}`);
  return d;
}

// ===========================================================================
function Login({ onIn }) {
  const [pw,setPw]=useState(""); const [err,setErr]=useState(""); const [busy,setBusy]=useState(false);
  const go=async()=>{ setBusy(true); setErr("");
    try{ await api("auth.php",{method:"POST",body:JSON.stringify({action:"login",password:pw})}); onIn(); }
    catch(e){ setErr(e.message); setBusy(false); } };
  return (
    <div className="login">
      <div className="logo">B</div>
      <h1>Black Book</h1><p>Anaesthetic case workflow</p>
      <div className="err">{err}</div>
      <input type="password" placeholder="Password" value={pw} onChange={e=>setPw(e.target.value)}
        onKeyDown={e=>e.key==="Enter"&&go()} autoFocus />
      <button onClick={go} disabled={busy||!pw}>{busy?"Checking…":"Open"}</button>
    </div>
  );
}

function Dot({ s }) { return <span className={`d ${s!=="grey"?s:""}`} />; }

// Live client-side mirror of the server's recompute(), so tab dots react
// immediately as the user edits (server remains the source of truth on save).
function liveStages(c) {
  const req=["hospital","medical_aid","procedure_type"];
  const missing=req.some(r=>!c[r]); const hasCodes=(c.codes||[]).length>0;
  let st_detail="grey";
  if(hasCodes||c.hospital||c.medical_aid){ st_detail=(missing||!hasCodes)?"yellow":"green"; if(c.codes_more)st_detail="yellow"; }
  const ms=c.ms_filed&&c.ms_scanned&&c.ms_uploaded&&c.ms_submitted;
  const msAny=c.ms_filed||c.ms_scanned||c.ms_uploaded||c.ms_submitted;
  const st_ms=ms?"green":(msAny?"yellow":"grey");
  const surg=(c.codes||[]).filter(x=>x.code_type==="surgical"), anaes=(c.codes||[]).filter(x=>x.code_type==="anaesthetic");
  const anyQ=(c.codes||[]).some(x=>x.code_status==="query"), anyV=(c.codes||[]).some(x=>x.verified);
  let st_cv="grey";
  if(anyV||anyQ){ const surgOk=surg.length?surg.some(x=>x.verified):true; const anOk=anaes.every(x=>x.verified);
    st_cv=(surgOk&&anOk&&!anyQ)?"green":"yellow"; }
  return { st_detail, st_ms, st_cv, st_rp:c.st_rp||"grey" };
}

function CaseCard({ c, onOpen }) {
  const codes = c.codes||[];
  const summary = [c.hospital, c.procedure_type].filter(Boolean).join(" · ");
  return (
    <div className="case" onClick={()=>onOpen(c.id)}>
      <div className="top">
        <span className="cn mono">{c.case_number}</span>
        <span className="date">{c.theatre_date||"—"}</span>
      </div>
      <div className="meta">{summary||"No detail yet"}</div>
      <div className="codes">
        {codes.length===0 && <span style={{fontSize:13,color:"var(--ink3)"}}>No codes</span>}
        {codes.map((cd,i)=><span key={i} className={`cpill t-${cd.code_type}`}>{cd.code}</span>)}
      </div>
      <div className="stages">
        {STAGES.map(s=>(
          <div className="stage" key={s.key}><Dot s={c[s.key]} /><span className="lbl">{s.short}</span></div>
        ))}
      </div>
    </div>
  );
}

// ===========================================================================
// New-case private capture -> generates case number
// ===========================================================================
function PrivateCapture({ onDone, onClose }) {
  const [firsts,setFirsts]=useState(""); const [surname,setSurname]=useState("");
  const [hospital,setHospital]=useState(""); const [date,setDate]=useState(new Date().toISOString().slice(0,10));
  const cn = (surname||hospital) ? makeCaseNumber(surname,hospital,date) : "";
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={e=>e.stopPropagation()}>
        <div className="grab" />
        <div className="private">
          <span className="lock">🔒 Private — stays on this device</span>
          <h2>New case</h2>
          <p className="hint">Used only to build a case number. The name is not saved or sent anywhere.</p>
          <div className="row2">
            <div className="field"><label>First name(s)</label>
              <input value={firsts} onChange={e=>setFirsts(e.target.value)} placeholder="e.g. Thabo" /></div>
            <div className="field"><label>Surname</label>
              <input value={surname} onChange={e=>setSurname(e.target.value)} placeholder="e.g. Mabitsela" /></div>
          </div>
          <div className="row2">
            <div className="field"><label>Hospital</label>
              <input value={hospital} onChange={e=>setHospital(e.target.value)} placeholder="e.g. Milpark" /></div>
            <div className="field"><label>Theatre date</label>
              <input type="date" value={date} onChange={e=>setDate(e.target.value)} /></div>
          </div>
          <div className="cngen">
            <div className="lab">Case number</div>
            {cn ? <div className="val">{cn}</div> : <div className="empty">— — —</div>}
          </div>
          <p className="privacy-note">Structure: first 3 of surname · month · first 3 of hospital.
            You'll write this number next to the sticker in your book. Only this number is stored.</p>
        </div>
        <div className="actions">
          <button className="btn-primary" disabled={!cn} onClick={()=>onDone({ case_number:cn, theatre_date:date, hospital })}>
            Create case {cn}
          </button>
        </div>
      </div>
    </div>
  );
}

// ===========================================================================
// Case detail sheet with staged tabs
// ===========================================================================
function CaseSheet({ id, prefill, onClose, onSaved, toast }) {
  const [c,setC]=useState(null);
  const [saving,setSaving]=useState(false);
  // amend: which section is being edited (null = read-only view). New cases start on Detail.
  const [amend,setAmend]=useState(id ? null : "st_detail");

  useEffect(()=>{
    if (id) api(`cases.php?action=get&id=${id}`).then(r=>setC(normalise(r.case))).catch(e=>toast(e.message));
    else setC(blank(prefill));
  },[id]);

  function normalise(x){ return { ...x,
    codes:(x.codes||[]).map(cd=>({ ...cd, verified:!!+cd.verified,
      code_status:cd.code_status||"none", comment:cd.comment||"" })),
    ms_filed:!!+x.ms_filed, ms_scanned:!!+x.ms_scanned, ms_uploaded:!!+x.ms_uploaded, ms_submitted:!!+x.ms_submitted,
    codes_more:!!+x.codes_more }; }
  function blank(p){ return { id:null, case_number:p.case_number, theatre_date:p.theatre_date||"",
    hospital:p.hospital||"", procedure_date:"", theatre_start:"", theatre_end:"", surgeon:"", medical_aid:"",
    plan:"", procedure_type:"", codes_more:false, notes:"", codes:[],
    ms_filed:false, ms_scanned:false, ms_uploaded:false, ms_submitted:false, ms_submitted_date:"",
    st_detail:"grey", st_ms:"grey", st_cv:"grey", st_rp:"grey" }; }

  if (!c) return <div className="scrim" onClick={onClose}><div className="sheet"><div className="grab"/><div className="spinner"/></div></div>;

  const set=(k,v)=>setC(o=>({...o,[k]:v}));
  const setCode=(i,patch)=>setC(o=>({...o,codes:o.codes.map((x,j)=>j===i?{...x,...patch}:x)}));
  const addCode=(cd={code:"",code_type:"surgical",description:""})=>setC(o=>({...o,codes:[...o.codes,cd]}));
  const delCode=i=>setC(o=>({...o,codes:o.codes.filter((_,j)=>j!==i)}));
  const merge=list=>setC(o=>{ const seen=new Set(o.codes.map(x=>x.code+"|"+x.code_type));
    return {...o,codes:[...o.codes,...list.filter(x=>x.code&&!seen.has(x.code+"|"+x.code_type))]}; });

  const REQUIRED=["hospital","medical_aid","procedure_type"];
  const missing=k=>REQUIRED.includes(k)&&!c[k];

  const save=async()=>{
    setSaving(true);
    const payload={ action:id?"update":"create", id:id||undefined,
      case_number:c.case_number, theatre_date:c.theatre_date, procedure_date:c.procedure_date,
      theatre_start:c.theatre_start, theatre_end:c.theatre_end, hospital:c.hospital, surgeon:c.surgeon,
      medical_aid:c.medical_aid, plan:c.plan, procedure_type:c.procedure_type, codes_more:c.codes_more,
      notes:c.notes, codes:c.codes, ms_filed:c.ms_filed, ms_scanned:c.ms_scanned, ms_uploaded:c.ms_uploaded,
      ms_submitted:c.ms_submitted, ms_submitted_date:c.ms_submitted_date, st_rp:c.st_rp };
    try{ await api("cases.php",{method:"POST",body:JSON.stringify(payload)});
      toast(id?"Saved":"Case created"); onSaved(); }
    catch(e){ toast(e.message); setSaving(false); }
  };
  const del=async()=>{ if(!confirm(`Delete ${c.case_number}?`))return;
    try{ await api("cases.php",{method:"POST",body:JSON.stringify({action:"delete",id})}); toast("Deleted"); onSaved(); }
    catch(e){ toast(e.message); } };

  // amend: which section is being edited (null = read-only view). New cases start editing Detail.
  const saveSection=async()=>{ await save(); setAmend(null); };

  const ls=liveStages(c);
  const fv=(v)=> (v===null||v===undefined||v==="") ? <span className="v empty">—</span> : <span className="v">{v}</span>;

  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={e=>e.stopPropagation()}>
        <div className="grab" />
        <div className="sheet-h">
          <div><h2 className="mono">{c.case_number}</h2><div className="cnbig">{c.theatre_date||"no date"}</div></div>
          <button className="x" onClick={onClose}>{amend?"Cancel":"Close"}</button>
        </div>
        <div className="sheet-body">

          {/* ---------- DETAIL ---------- */}
          {amend==="st_detail" ? (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_detail}`} />Case detail</div></div>
              <DetailTab c={c} set={set} setCode={setCode} addCode={addCode} delCode={delCode} merge={merge} missing={missing} />
              <div className="amend-actions">
                <button className="cancel" onClick={()=>id?setAmend(null):onClose()}>Cancel</button>
                <button className="save" onClick={saveSection} disabled={saving}>{saving?"Saving…":"Save"}</button>
              </div>
            </div>
          ) : (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_detail}`} />Case detail</div>
                <button className="amend" onClick={()=>setAmend("st_detail")}>Amend</button></div>
              <div className="frow"><span className="k">Hospital</span>{fv(c.hospital)}</div>
              <div className="frow"><span className="k">Surgeon</span>{fv(c.surgeon)}</div>
              <div className="frow"><span className="k">Medical aid</span>{fv(c.medical_aid)}</div>
              <div className="frow"><span className="k">Plan</span>{fv(c.plan)}</div>
              <div className="frow"><span className="k">Procedure</span>{fv(c.procedure_type)}</div>
              <div className="frow"><span className="k">Theatre time</span>{(c.theatre_start||c.theatre_end)?<span className="v">{(c.theatre_start||"—")+" – "+(c.theatre_end||"—")}</span>:<span className="v empty">—</span>}</div>
              <div style={{paddingTop:9}}>
                <span className="fcodesummary">Codes {c.codes_more?"(more to add)":""}</span>
                <div className="fcodes">
                  {c.codes.length===0 && <span className="v empty">none</span>}
                  {c.codes.map((cd,i)=><span key={i} className={`cpill t-${cd.code_type}`}>{cd.code}</span>)}
                </div>
              </div>
              {c.notes && <div className="fnote">{c.notes}</div>}
            </div>
          )}

          {/* ---------- MS ---------- */}
          {amend==="st_ms" ? (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_ms}`} />MedCore submission</div></div>
              <MSTab c={c} set={set} />
              <div className="amend-actions">
                <button className="cancel" onClick={()=>setAmend(null)}>Cancel</button>
                <button className="save" onClick={saveSection} disabled={saving}>{saving?"Saving…":"Save"}</button>
              </div>
            </div>
          ) : (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_ms}`} />MedCore submission</div>
                <button className="amend" onClick={()=>setAmend("st_ms")}>Amend</button></div>
              {[["ms_filed","Filed"],["ms_scanned","Scanned"],["ms_uploaded","Uploaded"],["ms_submitted","Submitted"]].map(([k,l])=>(
                <div className="frow" key={k}><span className="k">{l}</span>
                  <span className={`v ${c[k]?"":"empty"}`}>{c[k]?"✓ done":"—"}</span></div>
              ))}
              {c.ms_submitted_date && <div className="frow"><span className="k">Submitted date</span><span className="v">{c.ms_submitted_date}</span></div>}
            </div>
          )}

          {/* ---------- CV ---------- */}
          {amend==="st_cv" ? (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_cv}`} />Code verification</div></div>
              <CVTab c={c} setCode={setCode} />
              <div className="amend-actions">
                <button className="cancel" onClick={()=>setAmend(null)}>Cancel</button>
                <button className="save" onClick={saveSection} disabled={saving}>{saving?"Saving…":"Save"}</button>
              </div>
            </div>
          ) : (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_cv}`} />Code verification</div>
                <button className="amend" onClick={()=>setAmend("st_cv")}>Amend</button></div>
              {c.codes.length===0 && <div className="frow"><span className="k">No codes to verify</span></div>}
              {c.codes.map((cd,i)=>(
                <div className="frow" key={i}>
                  <span className="k mono">{cd.code} <span style={{color:"var(--ink3)",fontSize:11}}>{TYPES.find(t=>t.key===cd.code_type)?.label}</span></span>
                  {cd.code_status==="query"
                    ? <span className="v fver-q">⚑ query</span>
                    : <span className={`v ${cd.verified?"fver-ok":"empty"}`}>{cd.verified?"✓ verified":"—"}</span>}
                </div>
              ))}
              {c.codes.some(x=>x.code_status==="query"&&x.comment) &&
                c.codes.filter(x=>x.code_status==="query"&&x.comment).map((x,i)=>
                  <div className="fnote" key={i}>⚑ {x.code}: {x.comment}</div>)}
            </div>
          )}

          {/* ---------- RP ---------- */}
          {amend==="st_rp" ? (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_rp}`} />Remittance &amp; payment</div></div>
              <RPTab c={c} set={set} />
              <div className="amend-actions">
                <button className="cancel" onClick={()=>setAmend(null)}>Cancel</button>
                <button className="save" onClick={saveSection} disabled={saving}>{saving?"Saving…":"Save"}</button>
              </div>
            </div>
          ) : (
            <div className="filecard">
              <div className="fh"><div className="ft"><span className={`fd ${ls.st_rp}`} />Remittance &amp; payment</div>
                <button className="amend" onClick={()=>setAmend("st_rp")}>Amend</button></div>
              <div className="frow"><span className="k">Status</span>
                <span className="v">{c.st_rp==="green"?"Done":c.st_rp==="yellow"?"Query":"Pending"}</span></div>
            </div>
          )}

          {id && !amend && <button className="btn-danger-text" onClick={del}>Delete case</button>}
        </div>
      </div>
    </div>
  );
}

function DetailTab({ c,set,setCode,addCode,delCode,merge,missing }) {
  return (
    <>
      <div className="row2">
        <div className={`field req ${missing("hospital")?"missing":""}`}><label>Hospital{missing("hospital")&&<span className="req-flag">needed</span>}</label>
          <input value={c.hospital||""} onChange={e=>set("hospital",e.target.value)} /></div>
        <div className="field"><label>Surgeon</label>
          <input value={c.surgeon||""} onChange={e=>set("surgeon",e.target.value)} /></div>
      </div>
      <div className="row2">
        <div className={`field req ${missing("medical_aid")?"missing":""}`}><label>Medical aid{missing("medical_aid")&&<span className="req-flag">needed</span>}</label>
          <input value={c.medical_aid||""} onChange={e=>set("medical_aid",e.target.value)} /></div>
        <div className="field"><label>Plan</label>
          <input value={c.plan||""} onChange={e=>set("plan",e.target.value)} /></div>
      </div>
      <div className={`field req ${missing("procedure_type")?"missing":""}`}><label>Procedure{missing("procedure_type")&&<span className="req-flag">needed</span>}</label>
        <input value={c.procedure_type||""} onChange={e=>set("procedure_type",e.target.value)} placeholder="e.g. Appendicectomy" /></div>
      <div className="row2">
        <div className="field"><label>Theatre start</label><input type="time" value={c.theatre_start||""} onChange={e=>set("theatre_start",e.target.value)} /></div>
        <div className="field"><label>Theatre end</label><input type="time" value={c.theatre_end||""} onChange={e=>set("theatre_end",e.target.value)} /></div>
      </div>

      <div className="field">
        <label>Codes</label>
        <div className="code-list">
          {c.codes.map((cd,i)=>(
            <div className="code-row" key={i}>
              <input className="c mono" placeholder="Code" value={cd.code}
                onChange={e=>{ const v=e.target.value; const look=lookup(v); setCode(i,{code:v, code_type:cd.code_type||look.code_type, description:cd.description||look.description}); }} />
              <select value={cd.code_type} onChange={e=>setCode(i,{code_type:e.target.value})}>
                {TYPES.map(t=><option key={t.key} value={t.key}>{t.label}</option>)}
              </select>
              <button className="del" onClick={()=>delCode(i)}>✕</button>
            </div>
          ))}
        </div>
        <div className="quick">
          {["0039","0147","543","2814"].map(q=><button key={q} className="qp" onClick={()=>merge([lookup(q)])}>+ {q}</button>)}
        </div>
        <button className="add-code" onClick={()=>addCode()}>+ Add a code</button>
      </div>
      <label style={{display:"flex",alignItems:"center",gap:10,fontSize:14,margin:"2px 0 14px",color:"var(--ink2)"}}>
        <input type="checkbox" checked={c.codes_more} onChange={e=>set("codes_more",e.target.checked)} style={{width:20,height:20}} />
        More codes to add later (keeps this amber)
      </label>
      <div className="field"><label>Notes</label>
        <textarea value={c.notes||""} onChange={e=>set("notes",e.target.value)} placeholder="Case notes…" /></div>
    </>
  );
}

function MSTab({ c,set }) {
  const ticks=[["ms_filed","Filed (physical)"],["ms_scanned","Scanned"],["ms_uploaded","Uploaded"],["ms_submitted","Submitted"]];
  return (
    <>
      <div className="rule">Tick each step as the case moves to the billing company. Green when all four are done.</div>
      <div className="ticks">
        {ticks.map(([k,l])=>(
          <div className="tick" key={k} onClick={()=>set(k,!c[k])}>
            <div className={`box ${c[k]?"on":""}`}>{c[k]?"✓":""}</div>
            <span className="tl">{l}</span>
          </div>
        ))}
      </div>
      {c.ms_submitted && (
        <div className="field" style={{marginTop:14}}><label>Submitted date</label>
          <input type="date" value={c.ms_submitted_date||""} onChange={e=>set("ms_submitted_date",e.target.value)} /></div>
      )}
    </>
  );
}

function CVTab({ c,setCode }) {
  const surg=c.codes.filter(x=>x.code_type==="surgical");
  const anaes=c.codes.filter(x=>x.code_type==="anaesthetic");
  return (
    <>
      <div className="rule">Tick each code that appears on GoodX. Surgical: any one is enough. Anaesthetic: all must be there. Flag a query on any code that's wrong.</div>
      {c.codes.length===0 && <div className="placeholder"><div className="pi">No codes yet</div>Add codes on the Detail tab first.</div>}
      {c.codes.map((cd,idx)=>{
        const i=c.codes.indexOf(cd);
        return (
          <div className="vrow" key={idx}>
            <div className="vtop">
              <div className={`check ${cd.verified?"on":""}`} onClick={()=>setCode(i,{verified:!cd.verified})}>{cd.verified?"✓":""}</div>
              <div><div className="vcode">{cd.code}</div><div className="vtype">{TYPES.find(t=>t.key===cd.code_type)?.label}</div></div>
              <button className={`qbtn ${cd.code_status==="query"?"on":""}`}
                onClick={()=>setCode(i,{code_status:cd.code_status==="query"?"none":"query"})}>
                {cd.code_status==="query"?"⚑ query":"Flag query"}
              </button>
            </div>
            {cd.code_status==="query" && (
              <input className="vcomment" placeholder="What's the issue? (e.g. positioning code not captured)"
                value={cd.comment||""} onChange={e=>setCode(i,{comment:e.target.value})} />
            )}
          </div>
        );
      })}
      {surg.length>0 && <div className="rule" style={{marginTop:6}}>Surgical verified: {surg.some(x=>x.verified)?"✓ yes":"— none yet"} · Anaesthetic all verified: {anaes.every(x=>x.verified)&&anaes.length>0?"✓ yes":"— not yet"}</div>}
    </>
  );
}

function RPTab({ c,set }) {
  return (
    <div className="placeholder">
      <div className="pi">Remittance &amp; payment</div>
      <p style={{fontSize:14,maxWidth:280,margin:"0 auto 16px"}}>This stage is being designed with the payment scenarios (nothing / partial / paid to patient / paid). For now you can set its status manually.</p>
      <div className="seg" style={{maxWidth:300,margin:"0 auto"}}>
        {[["grey","Pending"],["yellow","Query"],["green","Done"]].map(([k,l])=>(
          <button key={k} className={c.st_rp===k?"on":""} onClick={()=>set("st_rp",k)}>{l}</button>
        ))}
      </div>
    </div>
  );
}

// ===========================================================================
function Dashboard({ onLogout }) {
  const [cases,setCases]=useState(null);
  const [q,setQ]=useState(""); const [flagged,setFlagged]=useState(false);
  const [sheet,setSheet]=useState(null);      // null | {new:true,prefill} | {id}
  const [toastMsg,setToastMsg]=useState("");
  const toast=m=>{ setToastMsg(m); setTimeout(()=>setToastMsg(""),2100); };

  const load=useCallback(async()=>{
    const p=new URLSearchParams({action:"list"});
    if(q.trim())p.set("q",q.trim()); if(flagged)p.set("flagged","1");
    try{ const r=await api(`cases.php?${p}`); setCases(r.cases); }catch(e){ toast(e.message); setCases([]); }
  },[q,flagged]);
  useEffect(()=>{ load(); },[load]);

  const seed=async()=>{ try{ await api("seed.php"); toast("Mock cases loaded"); load(); }catch(e){ toast(e.message); } };

  return (
    <>
      <div className="bar">
        <div>
          <h1><span className="dot" />Black Book</h1>
          <div className="sub">{cases?`${cases.length} case${cases.length!==1?"s":""}`:"…"}</div>
        </div>
        <div className="actions">
          <button onClick={()=>window.open(`${API}/export.php`,"_blank")}>Export</button>
          <button onClick={onLogout}>Lock</button>
        </div>
      </div>

      <div className="controls">
        <div className="search"><input placeholder="Search case #, hospital, code…" value={q} onChange={e=>setQ(e.target.value)} /></div>
        <div className="filters">
          <button className={`chip ${!flagged?"on":""}`} onClick={()=>setFlagged(false)}>All</button>
          <button className={`chip ${flagged?"on":""}`} onClick={()=>setFlagged(true)}>Queries only</button>
          <button className="chip" onClick={seed}>Load mock data</button>
        </div>
      </div>
      <div className="legend">
        <span><i style={{background:"#c4bfb4"}} />Not started</span>
        <span><i style={{background:"#2c6e49"}} />Done</span>
        <span><i style={{background:"#c99a2e"}} />Query / attention</span>
      </div>

      <div className="list">
        {cases===null && <div className="spinner" />}
        {cases && cases.length===0 && (
          <div className="empty"><div className="big">{q||flagged?"Nothing matches":"No cases yet"}</div>
            <div>{q||flagged?"Clear the search or filter.":'Tap "Load mock data" or New case.'}</div></div>
        )}
        {cases && cases.map(c=><CaseCard key={c.id} c={c} onOpen={id=>setSheet({id})} />)}
      </div>

      <button className="fab" onClick={()=>setSheet({new:true})}>+ New case</button>

      {sheet?.new && !sheet.prefill && (
        <PrivateCapture onClose={()=>setSheet(null)} onDone={p=>setSheet({new:true,prefill:p})} />
      )}
      {sheet?.new && sheet.prefill && (
        <CaseSheet id={null} prefill={sheet.prefill} onClose={()=>setSheet(null)} onSaved={()=>{setSheet(null);load();}} toast={toast} />
      )}
      {sheet?.id && (
        <CaseSheet id={sheet.id} prefill={{}} onClose={()=>setSheet(null)} onSaved={()=>{setSheet(null);load();}} toast={toast} />
      )}
      {toastMsg && <div className="toast">{toastMsg}</div>}
    </>
  );
}

function App() {
  const [authed,setAuthed]=useState(null);
  useEffect(()=>{ api("auth.php",{method:"POST",body:JSON.stringify({action:"check"})})
    .then(d=>setAuthed(!!d.authed)).catch(()=>setAuthed(false)); },[]);
  const logout=async()=>{ try{ await api("auth.php",{method:"POST",body:JSON.stringify({action:"logout"})}); }catch{} setAuthed(false); };
  if(authed===null) return <div className="spinner" />;
  return authed ? <Dashboard onLogout={logout} /> : <Login onIn={()=>setAuthed(true)} />;
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
