const { useState, useEffect, useRef } = React;

// ─── API helper ───────────────────────────────────────────────────────────────
const API = "/api";
function token() { return localStorage.getItem("agh_token") || ""; }
function setToken(t) { t ? localStorage.setItem("agh_token", t) : localStorage.removeItem("agh_token"); }
async function api(path, { method = "GET", body, form } = {}) {
  const headers = {};
  if (token()) headers.Authorization = "Bearer " + token();
  let payload;
  if (form) payload = form;
  else if (body) { headers["Content-Type"] = "application/json"; payload = JSON.stringify(body); }
  const res = await fetch(API + path, { method, headers, body: payload });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || "Something went wrong");
  return data;
}

// ─── Styles (blue clinical theme) ──────────────────────────────────────────────
const S = {
  page:{minHeight:"100vh",background:"#F0F4F8",fontFamily:"'Inter','Segoe UI',sans-serif",color:"#1A2B3C",paddingBottom:40},
  hdr:{background:"#0A5C8F",color:"#fff",padding:"13px 20px",display:"flex",justifyContent:"space-between",alignItems:"center"},
  hdrL:{display:"flex",alignItems:"center",gap:10},
  logo:{background:"#fff",color:"#0A5C8F",fontWeight:800,fontSize:13,padding:"5px 9px",borderRadius:7,letterSpacing:1},
  hdrTitle:{fontWeight:700,fontSize:15},
  hdrSub:{fontSize:11,opacity:.75,marginTop:1},
  proTag:{background:"rgba(255,255,255,.12)",border:"1px solid rgba(255,255,255,.2)",borderRadius:8,padding:"7px 12px",display:"flex",gap:8,alignItems:"center",fontSize:13},
  proName:{fontWeight:600},
  proUnit:{fontSize:11,opacity:.7},
  logout:{background:"transparent",border:"1px solid rgba(255,255,255,.3)",color:"#fff",borderRadius:8,padding:"6px 12px",fontSize:12,cursor:"pointer"},
  body:{maxWidth:760,margin:"0 auto",padding:"0 16px"},
  sec:{background:"#fff",borderRadius:14,marginTop:16,boxShadow:"0 1px 4px rgba(0,0,0,.06)"},
  secHdr:{background:"#FAFCFE",borderBottom:"1px solid #D1DCE8",padding:"12px 18px",display:"flex",alignItems:"center",gap:8,borderRadius:"14px 14px 0 0"},
  secIcon:{fontSize:17},
  secTitle:{fontWeight:700,fontSize:13,color:"#0A5C8F",letterSpacing:.3},
  secBody:{padding:"16px 18px"},
  lbl:{fontSize:12,fontWeight:600,color:"#6B7E93",marginBottom:4,marginTop:13},
  req:{color:"#C0392B"},
  inp:{width:"100%",padding:"9px 12px",border:"1.5px solid #D1DCE8",borderRadius:9,fontSize:13,color:"#1A2B3C",background:"#fff",outline:"none",boxSizing:"border-box"},
  inpErr:{borderColor:"#C0392B",background:"#FFF8F7"},
  sel:{width:"100%",padding:"9px 12px",border:"1.5px solid #D1DCE8",borderRadius:9,fontSize:13,color:"#1A2B3C",background:"#fff",outline:"none",boxSizing:"border-box"},
  ta:{width:"100%",padding:"9px 12px",border:"1.5px solid #D1DCE8",borderRadius:9,fontSize:13,color:"#1A2B3C",background:"#fff",outline:"none",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit"},
  errMsg:{color:"#C0392B",fontSize:11,marginTop:3},
  hint:{fontSize:11,color:"#6B7E93",marginTop:3},
  row:{display:"flex",gap:14},
  col:{flex:1,minWidth:0},
  srchWrap:{position:"relative"},
  srchRow:{display:"flex",gap:8},
  clrBtn:{padding:"0 12px",background:"#F0F4F8",border:"1.5px solid #D1DCE8",borderRadius:9,cursor:"pointer",fontSize:13,color:"#6B7E93"},
  dropdown:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,background:"#fff",border:"1.5px solid #D1DCE8",borderRadius:10,boxShadow:"0 6px 20px rgba(0,0,0,.12)",zIndex:100,maxHeight:280,overflowY:"auto"},
  dropItem:{padding:"10px 14px",borderBottom:"1px solid #F0F4F8",cursor:"pointer"},
  dropName:{fontWeight:600,fontSize:13},
  dropMeta:{fontSize:11,color:"#6B7E93",marginTop:2},
  catBadge:{background:"#E8F4FB",color:"#0A5C8F",padding:"1px 7px",borderRadius:20,fontSize:10,fontWeight:600,display:"inline-block"},
  noResult:{padding:"12px 14px",fontSize:12,color:"#6B7E93",textAlign:"center"},
  addLink:{padding:"10px 14px",fontSize:12,color:"#1AABDE",cursor:"pointer",fontWeight:600,borderTop:"1px solid #F0F4F8",display:"flex",alignItems:"center",gap:5},
  chip:{display:"flex",alignItems:"center",gap:10,background:"#E8F4FB",border:"1.5px solid #1AABDE",borderRadius:10,padding:"9px 13px",marginTop:10},
  chipName:{fontWeight:700,fontSize:13},
  chipMeta:{fontSize:11,color:"#6B7E93",marginTop:2},
  modal:{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",zIndex:1000,display:"flex",alignItems:"center",justifyContent:"center",padding:20},
  modalCard:{background:"#fff",borderRadius:16,padding:24,width:"100%",maxWidth:420,boxShadow:"0 8px 32px rgba(0,0,0,.2)"},
  modalTitle:{fontWeight:700,fontSize:16,color:"#0A5C8F",marginBottom:4},
  modalSub:{fontSize:12,color:"#6B7E93",marginBottom:18},
  modalActions:{display:"flex",gap:10,marginTop:20},
  btnPrim:{background:"#0A5C8F",color:"#fff",border:"none",borderRadius:9,padding:"10px 20px",fontWeight:700,fontSize:13,cursor:"pointer"},
  btnSec:{background:"#F0F4F8",color:"#1A2B3C",border:"1.5px solid #D1DCE8",borderRadius:9,padding:"10px 16px",fontWeight:600,fontSize:13,cursor:"pointer"},
  footer:{background:"#fff",borderRadius:14,marginTop:16,padding:"16px 20px",display:"flex",justifyContent:"space-between",alignItems:"center",boxShadow:"0 1px 4px rgba(0,0,0,.06)"},
  footLbl:{fontSize:11,color:"#6B7E93",fontWeight:600,width:80},
  footVal:{fontSize:12,fontWeight:600},
  btnSubmit:{background:"#0A5C8F",color:"#fff",border:"none",borderRadius:10,padding:"12px 28px",fontWeight:700,fontSize:14,cursor:"pointer"},
  uploadArea:{border:"2px dashed #D1DCE8",borderRadius:10,padding:16,textAlign:"center",cursor:"pointer",color:"#6B7E93",fontSize:13,marginTop:4,display:"flex",alignItems:"center",justifyContent:"center",gap:8},
  successCard:{maxWidth:500,margin:"30px auto",background:"#fff",borderRadius:18,padding:32,textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,.08)"},
  sucIcon:{width:60,height:60,background:"#1B8A4B",color:"#fff",fontSize:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 14px"},
  sucGrid:{display:"grid",gridTemplateColumns:"auto 1fr",gap:"7px 16px",textAlign:"left",margin:"18px 0 24px"},
  sgLbl:{fontSize:11,color:"#6B7E93",fontWeight:600,paddingTop:1},
  sgVal:{fontSize:13,fontWeight:600},
  // login
  loginWrap:{minHeight:"100vh",background:"#0A5C8F",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"'Inter','Segoe UI',sans-serif",padding:16},
  loginCard:{background:"#fff",borderRadius:18,padding:34,width:"100%",maxWidth:360,boxShadow:"0 12px 40px rgba(0,0,0,.25)"},
  // admin
  tabs:{display:"flex",gap:8,marginBottom:14},
  card:{background:"#fff",borderRadius:14,padding:18,boxShadow:"0 1px 4px rgba(0,0,0,.06)"},
  th:{textAlign:"left",fontSize:11,color:"#6B7E93",textTransform:"uppercase",padding:"6px 8px",borderBottom:"1px solid #E3EAF2"},
  td:{fontSize:13,padding:"8px 8px",borderBottom:"1px solid #F0F4F8"},
};

function unitLabel(cfg, code) { const u = cfg.units.find((x) => x.code === code); return u ? u.name + " (" + u.code + ")" : code; }

// ─── Login (with show password) ────────────────────────────────────────────────
function Login({ onLogin }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [show, setShow] = useState(false);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  async function submit() {
    setErr(""); setBusy(true);
    try { const d = await api("/auth/login", { method: "POST", body: { username, password } }); setToken(d.token); onLogin(d.user); }
    catch (e) { setErr(e.message); } finally { setBusy(false); }
  }
  return (
    <div style={S.loginWrap}>
      <div style={S.loginCard} className="fade-in">
        <div style={{textAlign:"center",marginBottom:22}}>
          <div style={{...S.logo,display:"inline-block",fontSize:18,padding:"8px 12px"}}>AGH</div>
          <div style={{fontWeight:800,fontSize:18,marginTop:10,color:"#0A5C8F"}}>PRO Referral Entry</div>
          <div style={{fontSize:12,color:"#6B7E93"}}>AAYUSH Group of Hospitals</div>
        </div>
        <div style={S.lbl}>Username</div>
        <input style={S.inp} value={username} autoFocus
          onChange={(e) => setUsername(e.target.value)} onKeyDown={(e) => e.key === "Enter" && submit()} />
        <div style={S.lbl}>Password</div>
        <div style={{position:"relative"}}>
          <input style={{...S.inp,paddingRight:60}} type={show ? "text" : "password"} value={password}
            onChange={(e) => setPassword(e.target.value)} onKeyDown={(e) => e.key === "Enter" && submit()} />
          <button type="button" onClick={() => setShow(!show)}
            style={{position:"absolute",right:8,top:7,background:"none",border:"none",color:"#0A5C8F",fontSize:12,fontWeight:700,cursor:"pointer"}}>
            {show ? "Hide" : "Show"}
          </button>
        </div>
        {err && <div style={{...S.errMsg,marginTop:8}}>⚠ {err}</div>}
        <button onClick={submit} disabled={busy}
          style={{...S.btnSubmit,width:"100%",marginTop:18,opacity:busy?.6:1}}>
          {busy ? "Signing in…" : "Sign in"}
        </button>
      </div>
    </div>
  );
}

// ─── Header (reused) ───────────────────────────────────────────────────────────
function Header({ user, cfg, onLogout }) {
  return (
    <div style={S.hdr}>
      <div style={S.hdrL}>
        <span style={S.logo}>AGH</span>
        <div><div style={S.hdrTitle}>{user.role === "admin" ? "Referral Admin" : "PRO Referral Entry"}</div>
          <div style={S.hdrSub}>AAYUSH Group of Hospitals</div></div>
      </div>
      <div style={{display:"flex",gap:12,alignItems:"center"}}>
        <div style={S.proTag}>
          <span>👤</span>
          <div><div style={S.proName}>{user.name}</div>
            <div style={S.proUnit}>{user.role === "admin" ? "Administrator" : unitLabel(cfg, user.unit)}</div></div>
        </div>
        <button style={S.logout} onClick={onLogout}>Log out</button>
      </div>
    </div>
  );
}

// ─── Referral search ───────────────────────────────────────────────────────────
// display label in (): Con. Dr → speciality, else → sub-category/qualification
function qualLabel(r) {
  if (r.category === "Con. Dr") return r.speciality || r.subCategory || "";
  return r.subCategory || r.qualification || "";
}

function ReferralSearch({ cfg, selected, onSelect, onToast }) {
  const [q, setQ] = useState("");
  const [groups, setGroups] = useState({ mine: [], others: [] });
  const [open, setOpen] = useState(false);
  const [showAdd, setShowAdd] = useState(false);
  const timer = useRef(null);

  function search(v) {
    setQ(v); clearTimeout(timer.current);
    if (v.trim().length < 2) { setGroups({ mine: [], others: [] }); setOpen(false); return; }
    timer.current = setTimeout(async () => {
      try { const d = await api("/databank/search?q=" + encodeURIComponent(v)); setGroups({ mine: d.mine || [], others: d.others || [] }); setOpen(true); } catch (e) {}
    }, 250);
  }
  function pick(r) { onSelect(r); setQ(r.name); setGroups({ mine: [], others: [] }); setOpen(false); }

  const Item = (r) => {
    const ql = qualLabel(r);
    return (
      <div key={r.id} style={S.dropItem} onClick={() => pick(r)}
        onMouseEnter={(e)=>e.currentTarget.style.background="#F5F9FF"} onMouseLeave={(e)=>e.currentTarget.style.background=""}>
        <div style={S.dropName}>{r.name}</div>
        <div style={S.dropMeta}>{r.mobile} · <span style={S.catBadge}>{r.category}</span>{ql ? " ("+ql+")" : ""}</div>
      </div>
    );
  };
  const total = groups.mine.length + groups.others.length;

  return (
    <div style={S.srchWrap}>
      <div style={S.lbl}>Search Referral by Name <span style={S.req}>*</span></div>
      {selected ? (
        <div style={S.chip}>
          <span style={{color:"#1B8A4B",fontSize:10}}>●</span>
          <div><div style={S.chipName}>{selected.name}</div>
            <div style={S.chipMeta}>{selected.mobile || "—"} · {selected.category}{qualLabel(selected) ? " ("+qualLabel(selected)+")" : ""}</div></div>
          <button style={{...S.clrBtn,marginLeft:"auto"}} onClick={() => { onSelect(null); setQ(""); }}>✕</button>
        </div>
      ) : (
        <>
          <div style={S.srchRow}>
            <input style={S.inp} placeholder="Type referral name or mobile…"
              value={q} onChange={(e) => search(e.target.value)} onFocus={() => total && setOpen(true)} />
          </div>
          {open && (
            <div style={S.dropdown}>
              {total ? (
                <>
                  {groups.mine.length > 0 && <div style={{padding:"6px 14px",fontSize:10,fontWeight:800,letterSpacing:.5,color:"#1B8A4B",background:"#F0FAF4",textTransform:"uppercase"}}>★ Mine ({groups.mine.length})</div>}
                  {groups.mine.map(Item)}
                  {groups.others.length > 0 && <div style={{padding:"6px 14px",fontSize:10,fontWeight:800,letterSpacing:.5,color:"#6B7E93",background:"#F7F9FC",textTransform:"uppercase"}}>Others ({groups.others.length})</div>}
                  {groups.others.map(Item)}
                </>
              ) : <div style={S.noResult}>"{q}" not found in databank</div>}
              <div style={S.addLink} onClick={() => { setOpen(false); setShowAdd(true); }}>＋ Not in databank? Add referral</div>
            </div>
          )}
          {q.length < 2 && <div style={S.hint}>Your unit's databank — ★ Mine = aapke naam se, Others = baaki</div>}
        </>
      )}
      {showAdd && <AddReferral cfg={cfg} prefill={q} onClose={() => setShowAdd(false)}
        onSaved={(entry, dup) => { pick(entry); setShowAdd(false); onToast(dup ? "Already in databank" : "Added to databank"); }} />}
    </div>
  );
}

function AddReferral({ cfg, prefill, onClose, onSaved }) {
  const [name, setName] = useState(prefill || "");
  const [mobile, setMobile] = useState("");
  const [category, setCategory] = useState("");
  const [subCategory, setSubCategory] = useState("");
  const [speciality, setSpeciality] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const isConDr = category === "Con. Dr";
  async function save() {
    if (!name.trim()) { setErr("Enter a name"); return; }
    if (!category) { setErr("Select a category"); return; }
    setBusy(true); setErr("");
    try { const d = await api("/databank", { method: "POST", body: { name, mobile, category, subCategory, speciality } }); onSaved(d.entry, d.duplicate); }
    catch (e) { setErr(e.message); } finally { setBusy(false); }
  }
  return (
    <div style={S.modal} onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div style={S.modalCard}>
        <div style={S.modalTitle}>Add Referral</div>
        <div style={S.modalSub}>Not found in databank — add and it will be saved (aapke naam se) for next time.</div>
        <div style={S.lbl}>Mobile No.</div>
        <input style={S.inp} type="tel" maxLength={10} value={mobile} onChange={(e) => setMobile(e.target.value.replace(/\D/g, "").slice(0,10))} />
        <div style={S.lbl}>Referral Name <span style={S.req}>*</span></div>
        <input style={S.inp} value={name} onChange={(e) => setName(e.target.value)} />
        <div style={S.lbl}>Category <span style={S.req}>*</span></div>
        <select style={S.sel} value={category} onChange={(e) => setCategory(e.target.value)}>
          <option value="">Select category</option>
          {cfg.referralCategories.map((c) => <option key={c}>{c}</option>)}
        </select>
        <div style={S.lbl}>{isConDr ? "Sub Category" : "Sub Category / Qualification"}</div>
        <input style={S.inp} placeholder={isConDr ? "e.g. Speciality" : "e.g. BHMS, MBBS, Asha, Private…"} value={subCategory} onChange={(e) => setSubCategory(e.target.value)} />
        {isConDr && <>
          <div style={S.lbl}>Speciality (Con. Dr)</div>
          <input style={S.inp} placeholder="e.g. Physician, Gynac., Ortho…" value={speciality} onChange={(e) => setSpeciality(e.target.value)} />
        </>}
        {err && <div style={{...S.errMsg,marginTop:8}}>⚠ {err}</div>}
        <div style={S.modalActions}>
          <button style={S.btnSec} onClick={onClose}>Cancel</button>
          <button style={S.btnPrim} onClick={save} disabled={busy}>{busy ? "Saving…" : "Save & Select →"}</button>
        </div>
      </div>
    </div>
  );
}

// ─── PRO Referral Form ─────────────────────────────────────────────────────────
function ReferralForm({ user, cfg, onToast }) {
  const blank = { pName:"", pSurname:"", pMob:"", spec:"", arrival:"", diag:"", payer:"", unit:user.unit || cfg.units[0].code, remarks:"" };
  const [ref, setRef] = useState(null);
  const [f, setF] = useState(blank);
  const [file, setFile] = useState(null);
  const [errors, setErrors] = useState({});
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(null);
  const fileRef = useRef(null);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const clearErr = (k) => setErrors((e) => ({ ...e, [k]: "" }));

  function validate() {
    const e = {};
    if (!ref) e.ref = "Select or add a referral";
    if (!f.pName.trim()) e.pName = "Required";
    if (!f.spec) e.spec = "Required";
    if (!f.arrival) e.arrival = "Required";
    setErrors(e); return Object.keys(e).filter(k=>e[k]).length === 0;
  }
  async function submit() {
    if (!validate()) { onToast("Please fill required fields", "error"); return; }
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append("patientFirstName", f.pName); fd.append("patientSurname", f.pSurname); fd.append("patientMobile", f.pMob);
      fd.append("speciality", f.spec); fd.append("arrivalTime", f.arrival); fd.append("diagnosis", f.diag);
      fd.append("payerType", f.payer); fd.append("unit", f.unit); fd.append("remarks", f.remarks);
      if (ref) { fd.append("referralName", ref.name); fd.append("referralMobile", ref.mobile||""); fd.append("referralCategory", ref.category||""); fd.append("referralQualification", ref.qualification||""); fd.append("referralSubCategory", ref.subCategory||""); fd.append("referralSpeciality", ref.speciality||""); fd.append("referralAddedBy", ref.addedBy||""); }
      if (file) fd.append("document", file);
      await api("/referrals", { method: "POST", form: fd });
      setDone({ patient:(f.pName+" "+f.pSurname).trim(), mobile:f.pMob, ref, spec:f.spec, payer:f.payer, unit:unitLabel(cfg,f.unit), pro:user.name, time:new Date().toLocaleString("en-IN",{timeZone:"Asia/Kolkata"}) });
    } catch (e) { onToast(e.message, "error"); } finally { setBusy(false); }
  }
  function reset() { setRef(null); setF(blank); setFile(null); setErrors({}); setDone(null); if (fileRef.current) fileRef.current.value=""; }

  if (done) {
    return (
      <div style={S.body}>
        <div style={S.successCard} className="fade-in">
          <div style={S.sucIcon}>✓</div>
          <div style={{fontSize:20,fontWeight:800}}>Entry Submitted!</div>
          <div style={{color:"#6B7E93",fontSize:13}}>Referral detail successfully saved.</div>
          <div style={S.sucGrid}>
            <span style={S.sgLbl}>Patient</span><span style={S.sgVal}>{done.patient}</span>
            <span style={S.sgLbl}>Mobile</span><span style={S.sgVal}>{done.mobile || "—"}</span>
            <span style={S.sgLbl}>Referral</span><span style={S.sgVal}>{done.ref?.name} <span style={{...S.catBadge,fontSize:11}}>{done.ref?.category}</span></span>
            <span style={S.sgLbl}>Speciality</span><span style={S.sgVal}>{done.spec}</span>
            <span style={S.sgLbl}>Payer</span><span style={S.sgVal}>{done.payer || "—"}</span>
            <span style={S.sgLbl}>Unit</span><span style={S.sgVal}>{done.unit}</span>
            <span style={S.sgLbl}>PRO</span><span style={S.sgVal}>{done.pro}</span>
            <span style={S.sgLbl}>Entry Time</span><span style={S.sgVal}>{done.time}</span>
          </div>
          <button style={S.btnPrim} onClick={reset}>New Entry →</button>
        </div>
      </div>
    );
  }

  return (
    <div style={S.body} className="fade-in">
      <div style={S.sec}>
        <div style={S.secHdr}><span style={S.secIcon}>🔗</span><span style={S.secTitle}>1. Referral Detail</span></div>
        <div style={{...S.secBody,minHeight:120}}>
          <ReferralSearch cfg={cfg} selected={ref} onSelect={setRef} onToast={onToast} />
          {errors.ref && <div style={S.errMsg}>⚠ {errors.ref}</div>}
        </div>
      </div>

      <div style={S.sec}>
        <div style={S.secHdr}><span style={S.secIcon}>🏥</span><span style={S.secTitle}>2. Patient Detail</span></div>
        <div style={S.secBody}>
          <div style={S.row}>
            <div style={S.col}>
              <div style={S.lbl}>First Name <span style={S.req}>*</span></div>
              <input style={{...S.inp,...(errors.pName?S.inpErr:{})}} placeholder="Ramesh" value={f.pName} onChange={(e)=>{set("pName",e.target.value);clearErr("pName");}} />
            </div>
            <div style={S.col}>
              <div style={S.lbl}>Surname</div>
              <input style={S.inp} placeholder="Patel" value={f.pSurname} onChange={(e)=>set("pSurname",e.target.value)} />
            </div>
          </div>
          <div style={S.lbl}>Mobile No.</div>
          <input style={{...S.inp,maxWidth:220}} type="tel" maxLength={10} placeholder="9876543210" value={f.pMob} onChange={(e)=>set("pMob",e.target.value.replace(/\D/g,"").slice(0,10))} />
        </div>
      </div>

      <div style={S.sec}>
        <div style={S.secHdr}><span style={S.secIcon}>🩺</span><span style={S.secTitle}>3. Clinical Info</span></div>
        <div style={S.secBody}>
          <div style={S.row}>
            <div style={S.col}>
              <div style={S.lbl}>Speciality <span style={S.req}>*</span></div>
              <select style={{...S.sel,...(errors.spec?S.inpErr:{})}} value={f.spec} onChange={(e)=>{set("spec",e.target.value);clearErr("spec");}}>
                <option value="">Select speciality</option>
                {cfg.specialities.map((s)=><option key={s}>{s}</option>)}
              </select>
            </div>
            <div style={S.col}>
              <div style={S.lbl}>Patient Arrival Type <span style={S.req}>*</span></div>
              <select style={{...S.sel,...(errors.arrival?S.inpErr:{})}} value={f.arrival} onChange={(e)=>{set("arrival",e.target.value);clearErr("arrival");}}>
                <option value="">Select type</option>
                {cfg.arrivalTimes.map((a)=><option key={a}>{a}</option>)}
              </select>
            </div>
          </div>
          <div style={S.lbl}>Diagnosis</div>
          <input style={S.inp} placeholder="e.g. ACS, Hip Fracture…" value={f.diag} onChange={(e)=>set("diag",e.target.value)} />
          <div style={S.lbl}>Payer Type</div>
          <select style={{...S.sel,maxWidth:280}} value={f.payer} onChange={(e)=>set("payer",e.target.value)}>
            <option value="">Select payer type</option>
            {cfg.payerTypes.map((p)=><option key={p}>{p}</option>)}
          </select>
        </div>
      </div>

      <div style={S.sec}>
        <div style={S.secHdr}><span style={S.secIcon}>🏨</span><span style={S.secTitle}>4. Facility & Remarks</span></div>
        <div style={S.secBody}>
          <div style={S.lbl}>Facility / Unit</div>
          <select style={{...S.sel,maxWidth:260}} value={f.unit} onChange={(e)=>set("unit",e.target.value)}>
            {cfg.units.map((u)=><option key={u.code} value={u.code}>{u.name} ({u.code})</option>)}
          </select>
          <div style={S.hint}>Default: your unit. Change if patient went to another unit.</div>
          <div style={S.lbl}>Remarks</div>
          <textarea style={S.ta} rows={3} placeholder="Any additional notes…" value={f.remarks} onChange={(e)=>set("remarks",e.target.value)} />
          <div style={S.lbl}>Upload Document (Optional)</div>
          <div style={S.uploadArea} onClick={()=>fileRef.current.click()}>
            <span>⬆</span>{file ? file.name : "Click to upload (PDF, JPG, PNG)"}
            <input ref={fileRef} type="file" accept=".pdf,.jpg,.jpeg,.png" style={{display:"none"}} onChange={(e)=>setFile(e.target.files[0]||null)} />
          </div>
        </div>
      </div>

      <div style={S.footer}>
        <div>
          <div style={{display:"flex",gap:10}}><span style={S.footLbl}>PRO Name</span><span style={S.footVal}>{user.name}</span></div>
          <div style={{display:"flex",gap:10,marginTop:4}}><span style={S.footLbl}>Entry Time</span><span style={{...S.footVal,color:"#6B7E93"}}>Auto on submit</span></div>
        </div>
        <button style={{...S.btnSubmit,opacity:busy?.6:1}} onClick={submit} disabled={busy}>{busy ? "Submitting…" : "Submit Entry →"}</button>
      </div>
    </div>
  );
}

// ─── Admin ─────────────────────────────────────────────────────────────────────
function Admin({ user, cfg, onToast }) {
  const [tab, setTab] = useState("logins");
  const TabBtn = ({ id, children }) => (
    <button onClick={() => setTab(id)}
      style={{padding:"9px 16px",borderRadius:9,fontSize:13,fontWeight:700,cursor:"pointer",border:"1px solid "+(tab===id?"#0A5C8F":"#D1DCE8"),background:tab===id?"#0A5C8F":"#fff",color:tab===id?"#fff":"#6B7E93"}}>{children}</button>
  );
  return (
    <div style={{...S.body,maxWidth:1000}} className="fade-in">
      <div style={{...S.tabs,marginTop:16}}>
        <TabBtn id="logins">Login Master</TabBtn>
        <TabBtn id="entries">Entries</TabBtn>
        <TabBtn id="databank">Databank</TabBtn>
      </div>
      {tab==="logins" && <LoginMaster cfg={cfg} onToast={onToast} />}
      {tab==="entries" && <Entries cfg={cfg} onToast={onToast} />}
      {tab==="databank" && <DatabankAdmin cfg={cfg} onToast={onToast} />}
    </div>
  );
}

function LoginMaster({ cfg, onToast }) {
  const [users, setUsers] = useState([]);
  const [show, setShow] = useState(false);
  const [resetFor, setResetFor] = useState(null);
  async function load() { try { const d = await api("/users"); setUsers(d.users); } catch (e) { onToast(e.message,"error"); } }
  useEffect(() => { load(); }, []);
  async function toggle(u) { try { await api("/users/"+u.id, { method:"PATCH", body:{ active:!u.active } }); load(); } catch (e) { onToast(e.message,"error"); } }
  return (
    <div style={S.card}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
        <div style={{fontWeight:700,color:"#0A5C8F"}}>PRO Logins</div>
        <button style={S.btnPrim} onClick={() => setShow(true)}>+ New login</button>
      </div>
      <div style={{overflowX:"auto"}}>
        <table style={{width:"100%",borderCollapse:"collapse"}}>
          <thead><tr><th style={S.th}>Name</th><th style={S.th}>Username</th><th style={S.th}>Unit</th><th style={S.th}>Role</th><th style={S.th}>Status</th><th style={S.th}></th></tr></thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id}>
                <td style={{...S.td,fontWeight:600}}>{u.name}</td><td style={S.td}>{u.username}</td><td style={S.td}>{u.unit||"—"}</td>
                <td style={S.td}><span style={S.catBadge}>{u.role}</span></td>
                <td style={S.td}>{u.active?<span style={{color:"#1B8A4B",fontWeight:600}}>Active</span>:<span style={{color:"#C0392B",fontWeight:600}}>Disabled</span>}</td>
                <td style={{...S.td,whiteSpace:"nowrap",textAlign:"right"}}>
                  <button style={{background:"none",border:"none",color:"#0A5C8F",fontWeight:700,fontSize:12,cursor:"pointer",marginRight:12}} onClick={()=>setResetFor(u)}>Reset pwd</button>
                  <button style={{background:"none",border:"none",color:"#6B7E93",fontWeight:700,fontSize:12,cursor:"pointer"}} onClick={()=>toggle(u)}>{u.active?"Disable":"Enable"}</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {show && <NewLogin cfg={cfg} onClose={()=>setShow(false)} onSaved={()=>{setShow(false);load();onToast("Login created");}} onToast={onToast} />}
      {resetFor && <ResetPwd user={resetFor} onClose={()=>setResetFor(null)} onDone={()=>{setResetFor(null);onToast("Password reset");}} onToast={onToast} />}
    </div>
  );
}

function NewLogin({ cfg, onClose, onSaved, onToast }) {
  const [f, setF] = useState({ name:"", username:"", password:"", unit:cfg.units[0].code, role:"pro" });
  const [busy, setBusy] = useState(false);
  const set = (k,v) => setF((s)=>({...s,[k]:v}));
  async function save() { setBusy(true); try { await api("/users", { method:"POST", body:f }); onSaved(); } catch (e) { onToast(e.message,"error"); } finally { setBusy(false); } }
  return (
    <div style={S.modal} onClick={(e)=>e.target===e.currentTarget&&onClose()}>
      <div style={S.modalCard}>
        <div style={S.modalTitle}>New Login</div>
        <div style={S.lbl}>Full Name <span style={S.req}>*</span></div><input style={S.inp} value={f.name} onChange={(e)=>set("name",e.target.value)} />
        <div style={S.lbl}>Username <span style={S.req}>*</span></div><input style={S.inp} value={f.username} onChange={(e)=>set("username",e.target.value)} />
        <div style={S.lbl}>Password <span style={S.req}>*</span></div><input style={S.inp} value={f.password} onChange={(e)=>set("password",e.target.value)} />
        <div style={S.row}>
          <div style={S.col}><div style={S.lbl}>Role</div>
            <select style={S.sel} value={f.role} onChange={(e)=>set("role",e.target.value)}><option value="pro">PRO</option><option value="admin">Admin</option></select></div>
          <div style={S.col}><div style={S.lbl}>Unit</div>
            <select style={S.sel} value={f.unit} disabled={f.role==="admin"} onChange={(e)=>set("unit",e.target.value)}>
              {cfg.units.map((u)=><option key={u.code} value={u.code}>{u.name} ({u.code})</option>)}</select></div>
        </div>
        <div style={S.modalActions}><button style={S.btnSec} onClick={onClose}>Cancel</button><button style={S.btnPrim} onClick={save} disabled={busy}>{busy?"Saving…":"Create"}</button></div>
      </div>
    </div>
  );
}

function ResetPwd({ user, onClose, onDone, onToast }) {
  const [pwd, setPwd] = useState(""); const [busy, setBusy] = useState(false);
  async function save() { setBusy(true); try { await api("/users/"+user.id+"/reset-password", { method:"POST", body:{ password:pwd } }); onDone(); } catch (e) { onToast(e.message,"error"); } finally { setBusy(false); } }
  return (
    <div style={S.modal} onClick={(e)=>e.target===e.currentTarget&&onClose()}>
      <div style={S.modalCard}>
        <div style={S.modalTitle}>Reset password</div><div style={S.modalSub}>{user.name}</div>
        <div style={S.lbl}>New Password <span style={S.req}>*</span></div><input style={S.inp} value={pwd} autoFocus onChange={(e)=>setPwd(e.target.value)} />
        <div style={S.modalActions}><button style={S.btnSec} onClick={onClose}>Cancel</button><button style={S.btnPrim} onClick={save} disabled={busy}>{busy?"Saving…":"Reset"}</button></div>
      </div>
    </div>
  );
}

function Entries({ cfg, onToast }) {
  const [items, setItems] = useState([]);
  const [unit, setUnit] = useState(""); const [from, setFrom] = useState(""); const [to, setTo] = useState("");
  function qs() { const p = new URLSearchParams(); if (unit) p.set("unit",unit); if (from) p.set("from",from); if (to) p.set("to",to); return p.toString(); }
  async function load() { try { const d = await api("/referrals?"+qs()); setItems(d.items); } catch (e) { onToast(e.message,"error"); } }
  useEffect(() => { load(); }, []);
  function exportXlsx() {
    fetch("/api/referrals/export?"+qs(), { headers:{ Authorization:"Bearer "+token() } }).then((r)=>r.blob()).then((b)=>{
      const url=URL.createObjectURL(b); const a=document.createElement("a"); a.href=url; a.download="referrals.xlsx"; a.click(); URL.revokeObjectURL(url);
    }).catch(()=>onToast("Export failed","error"));
  }
  return (
    <div style={S.card}>
      <div style={{display:"flex",flexWrap:"wrap",gap:10,alignItems:"flex-end",marginBottom:12}}>
        <div><div style={S.lbl}>Unit</div><select style={{...S.sel,width:120}} value={unit} onChange={(e)=>setUnit(e.target.value)}><option value="">All</option>{cfg.units.map((u)=><option key={u.code} value={u.code}>{u.code}</option>)}</select></div>
        <div><div style={S.lbl}>From</div><input type="date" style={{...S.inp,width:150}} value={from} onChange={(e)=>setFrom(e.target.value)} /></div>
        <div><div style={S.lbl}>To</div><input type="date" style={{...S.inp,width:150}} value={to} onChange={(e)=>setTo(e.target.value)} /></div>
        <button style={{...S.btnSec,padding:"9px 16px"}} onClick={load}>Filter</button>
        <button style={S.btnPrim} onClick={exportXlsx}>Export Excel</button>
        <span style={{...S.hint,marginLeft:"auto"}}>{items.length} entries</span>
      </div>
      <div style={{overflowX:"auto"}}>
        <table style={{width:"100%",borderCollapse:"collapse"}}>
          <thead><tr><th style={S.th}>Date</th><th style={S.th}>PRO</th><th style={S.th}>Unit</th><th style={S.th}>Patient</th><th style={S.th}>Referral</th><th style={S.th}>Speciality</th><th style={S.th}>Doc</th></tr></thead>
          <tbody>
            {items.map((r)=>(
              <tr key={r._id}>
                <td style={{...S.td,whiteSpace:"nowrap"}}>{new Date(r.createdAt).toLocaleString("en-IN",{timeZone:"Asia/Kolkata"})}</td>
                <td style={S.td}>{r.proName}</td><td style={S.td}>{r.unit}</td>
                <td style={S.td}>{r.patientFirstName} {r.patientSurname}</td><td style={S.td}>{r.referralName||"—"}</td><td style={S.td}>{r.speciality||"—"}</td>
                <td style={S.td}>{r.documentPath?<a style={{color:"#0A5C8F",fontWeight:700,fontSize:12}} href={"/api/referrals/"+r._id+"/document?t="+token()} target="_blank">view</a>:<span style={{color:"#B7C4D2"}}>—</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DatabankAdmin({ cfg, onToast }) {
  const [counts, setCounts] = useState({ total:0, byUnit:[] });
  const [unit, setUnit] = useState("");
  const [replace, setReplace] = useState(true);
  const [file, setFile] = useState(null);
  const [busy, setBusy] = useState(false);
  const [results, setResults] = useState([]);
  const [q, setQ] = useState("");
  const fileRef = useRef(null);
  async function loadCounts() { try { const d = await api("/databank/count"); setCounts(d); } catch (e) {} }
  useEffect(() => { loadCounts(); }, []);
  async function doImport() {
    if (!file) { onToast("Choose an Excel file", "error"); return; }
    setBusy(true);
    try { const fd = new FormData(); fd.append("file", file); fd.append("unit", unit); fd.append("replace", replace ? "true" : "false");
      const d = await api("/databank/import", { method:"POST", form:fd });
      onToast("Imported " + d.imported + " records (" + (d.units||[]).join(", ") + ")"); setFile(null); if (fileRef.current) fileRef.current.value=""; loadCounts();
    } catch (e) { onToast(e.message, "error"); } finally { setBusy(false); }
  }
  async function search(v) { setQ(v); if (v.trim().length<2) { setResults([]); return; } try { const d = await api("/databank/search?q="+encodeURIComponent(v)); setResults([...(d.mine||[]), ...(d.others||[])]); } catch (e) {} }
  return (
    <div style={{display:"grid",gap:16}}>
      <div style={S.card}>
        <div style={{fontWeight:700,color:"#0A5C8F",marginBottom:8}}>Import Databank (Excel)</div>
        <div style={S.hint}>Excel row 1 me headers hone chahiye: <b>Name</b>, <b>Mobile</b>, <b>Category</b>, <b>Unit</b>, <b>Qualification</b>. "All units" chuno to har row ka unit file ke <b>Unit</b> column se lega.</div>
        <div style={{display:"flex",gap:12,alignItems:"flex-end",flexWrap:"wrap",marginTop:10}}>
          <div><div style={S.lbl}>Unit</div><select style={{...S.sel,width:230}} value={unit} onChange={(e)=>setUnit(e.target.value)}>
            <option value="">All units (file ke Unit column se)</option>
            {cfg.units.map((u)=><option key={u.code} value={u.code}>{u.name} ({u.code})</option>)}</select></div>
          <div><div style={S.lbl}>Excel file (.xlsx)</div><input ref={fileRef} type="file" accept=".xlsx,.xls" style={{fontSize:12}} onChange={(e)=>setFile(e.target.files[0]||null)} /></div>
          <label style={{display:"flex",alignItems:"center",gap:6,fontSize:12,color:"#6B7E93",fontWeight:600,paddingBottom:9}}>
            <input type="checkbox" checked={replace} onChange={(e)=>setReplace(e.target.checked)} /> Replace existing (purana clear karo)
          </label>
          <button style={{...S.btnPrim,opacity:busy?.6:1}} onClick={doImport} disabled={busy}>{busy?"Importing…":"Import"}</button>
        </div>
      </div>
      <div style={S.card}>
        <div style={{fontWeight:700,color:"#0A5C8F",marginBottom:8}}>Databank size — {counts.total} total</div>
        <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
          {counts.byUnit.map((b)=><span key={b._id||"none"} style={{...S.catBadge,fontSize:12,padding:"4px 10px"}}>{b._id||"—"}: {b.n}</span>)}
        </div>
        <div style={S.lbl}>Search databank</div>
        <input style={{...S.inp,maxWidth:320}} placeholder="name or mobile…" value={q} onChange={(e)=>search(e.target.value)} />
        <div style={{marginTop:8}}>
          {results.map((r)=><div key={r.id} style={{fontSize:13,padding:"5px 0",borderBottom:"1px solid #F0F4F8"}}>
            <b>{r.name}</b> <span style={{color:"#6B7E93"}}>· {r.mobile} · </span><span style={S.catBadge}>{r.category}</span>{qualLabel(r)?" ("+qualLabel(r)+")":""} <span style={{color:"#B7C4D2"}}>[{r.unit}]</span>{r.addedBy?<span style={{color:"#1B8A4B",fontSize:11}}> · {r.addedBy}</span>:null}
          </div>)}
        </div>
      </div>
    </div>
  );
}

// ─── PRO area: tabs (New Entry | My Referrals) ─────────────────────────────────
function ProArea({ user, cfg, onToast }) {
  const [tab, setTab] = useState("new");
  const TabBtn = ({ id, children }) => (
    <button onClick={() => setTab(id)}
      style={{padding:"9px 16px",borderRadius:9,fontSize:13,fontWeight:700,cursor:"pointer",border:"1px solid "+(tab===id?"#0A5C8F":"#D1DCE8"),background:tab===id?"#0A5C8F":"#fff",color:tab===id?"#fff":"#6B7E93"}}>{children}</button>
  );
  return (
    <>
      <div style={{...S.body,display:"flex",gap:8,marginTop:16}}>
        <TabBtn id="new">＋ New Entry</TabBtn>
        <TabBtn id="mine">My Referrals</TabBtn>
      </div>
      {tab === "new" ? <ReferralForm user={user} cfg={cfg} onToast={onToast} />
                     : <MyReferrals user={user} cfg={cfg} onToast={onToast} />}
    </>
  );
}

function MyReferrals({ user, cfg, onToast }) {
  const [items, setItems] = useState([]);
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [loading, setLoading] = useState(true);
  const [detail, setDetail] = useState(null);
  function qs() { const p = new URLSearchParams(); if (from) p.set("from", from); if (to) p.set("to", to); return p.toString(); }
  async function load() {
    setLoading(true);
    try { const d = await api("/referrals?" + qs()); setItems(d.items); } catch (e) { onToast(e.message, "error"); } finally { setLoading(false); }
  }
  useEffect(() => { load(); }, []);

  return (
    <div style={S.body} className="fade-in">
      {detail && <ReferralDetail r={detail} cfg={cfg} onClose={() => setDetail(null)} />}
      <div style={{...S.sec,marginTop:16}}>
        <div style={S.secHdr}><span style={S.secIcon}>📋</span><span style={S.secTitle}>My Referrals</span>
          <span style={{marginLeft:"auto",fontSize:12,color:"#6B7E93",fontWeight:600}}>{items.length} total</span></div>
        <div style={S.secBody}>
          <div style={{display:"flex",gap:10,alignItems:"flex-end",flexWrap:"wrap",marginBottom:12}}>
            <div><div style={S.lbl}>From</div><input type="date" style={{...S.inp,width:150}} value={from} onChange={(e)=>setFrom(e.target.value)} /></div>
            <div><div style={S.lbl}>To</div><input type="date" style={{...S.inp,width:150}} value={to} onChange={(e)=>setTo(e.target.value)} /></div>
            <button style={{...S.btnPrim,padding:"9px 18px"}} onClick={load}>Filter</button>
            {(from||to) && <button style={S.btnSec} onClick={()=>{setFrom("");setTo("");setTimeout(load,0);}}>Clear</button>}
          </div>
          {loading ? <div style={{...S.hint,padding:"20px 0",textAlign:"center"}}>Loading…</div>
           : items.length === 0 ? <div style={{...S.hint,padding:"24px 0",textAlign:"center"}}>No entries yet. Add your first from "New Entry".</div>
           : (
            <>
            <div style={S.hint}>Kisi bhi row pe click karo — poori entry dikhegi.</div>
            <div style={{overflowX:"auto",marginTop:6}}>
              <table style={{width:"100%",borderCollapse:"collapse"}}>
                <thead><tr><th style={S.th}>Date</th><th style={S.th}>Patient</th><th style={S.th}>Referral</th><th style={S.th}>Speciality</th><th style={S.th}>Payer</th><th style={S.th}>Doc</th></tr></thead>
                <tbody>
                  {items.map((r)=>(
                    <tr key={r._id} style={{cursor:"pointer"}} onClick={()=>setDetail(r)}
                      onMouseEnter={(e)=>e.currentTarget.style.background="#F5F9FF"} onMouseLeave={(e)=>e.currentTarget.style.background=""}>
                      <td style={{...S.td,whiteSpace:"nowrap"}}>{new Date(r.createdAt).toLocaleString("en-IN",{timeZone:"Asia/Kolkata"})}</td>
                      <td style={S.td}>{r.patientFirstName} {r.patientSurname}</td>
                      <td style={S.td}>{r.referralName||"—"}{r.referralCategory?<span style={{...S.catBadge,marginLeft:6}}>{r.referralCategory}</span>:null}</td>
                      <td style={S.td}>{r.speciality||"—"}</td>
                      <td style={S.td}>{r.payerType||"—"}</td>
                      <td style={S.td} onClick={(e)=>e.stopPropagation()}>{r.documentPath?<a style={{color:"#0A5C8F",fontWeight:700,fontSize:12}} href={"/api/referrals/"+r._id+"/document?t="+token()} target="_blank">view</a>:<span style={{color:"#B7C4D2"}}>—</span>}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function ReferralDetail({ r, cfg, onClose }) {
  const Row = ({ l, v }) => (
    <><span style={S.sgLbl}>{l}</span><span style={S.sgVal}>{v || "—"}</span></>
  );
  return (
    <div style={S.modal} onClick={(e)=>e.target===e.currentTarget&&onClose()}>
      <div style={{...S.modalCard,maxWidth:460}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}>
          <div style={S.modalTitle}>Entry detail</div>
          <button style={S.clrBtn} onClick={onClose}>✕</button>
        </div>
        <div style={{...S.sucGrid,margin:0}}>
          <Row l="Date" v={new Date(r.createdAt).toLocaleString("en-IN",{timeZone:"Asia/Kolkata"})} />
          <Row l="Unit" v={unitLabel(cfg, r.unit)} />
          <Row l="Patient" v={(r.patientFirstName+" "+(r.patientSurname||"")).trim()} />
          <Row l="Patient Mobile" v={r.patientMobile} />
          <Row l="Referral" v={r.referralName} />
          <Row l="Ref Mobile" v={r.referralMobile} />
          <Row l="Ref Category" v={r.referralCategory} />
          <Row l="Ref Qualification" v={r.referralQualification} />
          <Row l="Speciality" v={r.speciality} />
          <Row l="Arrival" v={r.arrivalTime} />
          <Row l="Diagnosis" v={r.diagnosis} />
          <Row l="Payer" v={r.payerType} />
          <Row l="Remarks" v={r.remarks} />
          <span style={S.sgLbl}>Document</span>
          <span style={S.sgVal}>{r.documentPath?<a style={{color:"#0A5C8F",fontWeight:700}} href={"/api/referrals/"+r._id+"/document?t="+token()} target="_blank">view / download</a>:"—"}</span>
        </div>
      </div>
    </div>
  );
}

// ─── Toast + Root ──────────────────────────────────────────────────────────────
function Toast({ msg, type, onClose }) {
  useEffect(() => { const t = setTimeout(onClose, 3200); return () => clearTimeout(t); }, []);
  return <div style={{position:"fixed",bottom:24,left:"50%",transform:"translateX(-50%)",zIndex:2000,background:type==="error"?"#C0392B":"#1B8A4B",color:"#fff",padding:"11px 20px",borderRadius:12,fontSize:13,fontWeight:600,boxShadow:"0 6px 20px rgba(0,0,0,.2)"}} className="fade-in">{msg}</div>;
}

function App() {
  const [user, setUser] = useState(null);
  const [cfg, setCfg] = useState(null);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState(null);
  const showToast = (msg, type) => setToast({ msg, type });
  async function boot() {
    try { setCfg(await api("/config")); } catch (e) {}
    if (token()) { try { const d = await api("/auth/me"); setUser(d.user); } catch (e) { setToken(""); } }
    setLoading(false);
  }
  useEffect(() => { boot(); }, []);
  function logout() { setToken(""); setUser(null); }

  if (loading || !cfg) return <div style={{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",color:"#6B7E93",fontFamily:"'Inter',sans-serif"}}>Loading…</div>;
  if (!user) return <><Login onLogin={setUser} />{toast && <Toast {...toast} onClose={()=>setToast(null)} />}</>;
  return (
    <div style={S.page}>
      <Header user={user} cfg={cfg} onLogout={logout} />
      {user.role==="admin" ? <Admin user={user} cfg={cfg} onToast={showToast} /> : <ProArea user={user} cfg={cfg} onToast={showToast} />}
      {toast && <Toast {...toast} onClose={()=>setToast(null)} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
