// Admin — Case detail (the analyst workspace).
// Three-pane: citizen facts (left), decision trace (center), action rail (right).

function AdminCase({ caseId, setView, tweaks }) {
  const c = window.OHB_DATA.cases.find((x) => x.id === caseId) || window.OHB_DATA.cases[1];
  const citizen = window.OHB_DATA.citizens.find((p) => p.id === c.citizenId) || window.OHB_DATA.citizens[1];
  const decision = window.evaluateProgram(citizen, window.OHB_DATA.iskanProgram, window.OHB_DATA.ruleLibrary);
  const [tab, setTab] = React.useState("trace");

  return (
    <div className="admin-case">
      <div className="admin-case-head">
        <div className="row" style={{gap:14}}>
          <button className="text-13 muted" onClick={() => setView("queue")}>
            <Icon name="arrow_left" size={13}/> Queue
          </button>
          <span className="muted">·</span>
          <span className="mono text-13">{c.id}</span>
          <span className={`pill ${c.outcome === "eligible" ? "ok" : c.outcome === "manual_review" ? "warn" : "bad"}`}>
            {c.outcome === "eligible" ? "Eligible · STP" : c.outcome === "manual_review" ? "Needs review · Non-STP" : "Rejected"}
          </span>
          <span className="pill ghost"><Icon name="clock" size={11}/> SLA: 32h left</span>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost sm"><Icon name="message" size={13}/> Message citizen</button>
          <button className="btn ghost sm"><Icon name="phone_icon" size={13}/> Call</button>
          <button className="btn danger sm" style={{opacity: 0.75}}><Icon name="x" size={13}/> Reject</button>
          <button className="btn teal sm"><Icon name="check" size={13}/> Approve & route to bank</button>
        </div>
      </div>

      <div className="admin-case-body">
        <div className="admin-case-left-col">
          <CaseCitizen citizen={citizen} c={c}/>

          <div className="admin-case-center card" style={{minWidth:0}}>
            <div className="admin-tabs">
              {[
                ["trace", "Decision trace", "shield"],
                ["timeline", "Timeline", "clock"],
                ["docs", "Documents", "doc"],
                ["integrations", "Data sources", "database"],
                ["notes", "Notes", "edit"],
              ].map(([id, label, icon]) => (
                <button key={id} className={`admin-tab ${tab === id ? "active" : ""}`} onClick={() => setTab(id)}>
                  <Icon name={icon} size={13}/> {label}
                </button>
              ))}
            </div>
            <div className="admin-tab-body">
              {tab === "trace" && <CaseTrace decision={decision}/>}
              {tab === "timeline" && <CaseTimeline citizen={citizen}/>}
              {tab === "docs" && <CaseDocs citizen={citizen}/>}
              {tab === "integrations" && <CaseIntegrations/>}
              {tab === "notes" && <CaseNotes/>}
            </div>
          </div>
        </div>

        <CaseActions decision={decision} citizen={citizen}/>
      </div>
    </div>
  );
}

function CaseCitizen({ citizen, c }) {
  return (
    <aside className="admin-case-left card">
      {/* Identity row */}
      <div style={{display:"flex", gap:14, alignItems:"center", marginBottom:14}}>
        <div className="avatar-xl" style={{flexShrink:0}}>{citizen.avatar}</div>
        <div style={{flex:1, minWidth:0}}>
          <div className="title" style={{fontSize:16}}>{citizen.name}</div>
          <div className="tiny muted">{citizen.nameAr} <span className="mono" style={{marginLeft:8}}>{citizen.nationalId}</span></div>
        </div>
        <div className="row" style={{gap:6, flexShrink:0}}>
          {citizen.existingProperty && <span className="pill bad" title="Existing property"><Icon name="home" size={11}/></span>}
          {citizen.activeBenefit && <span className="pill bad" title="Active benefit"><Icon name="shield" size={11}/></span>}
          {citizen.missingDocs.length > 0 && <span className="pill warn" title="Missing docs"><Icon name="doc" size={11}/></span>}
          {citizen.dti > 40 && <span className="pill warn" title="DTI above 40%"><Icon name="scale" size={11}/></span>}
          {!citizen.existingProperty && !citizen.activeBenefit && citizen.missingDocs.length === 0 && citizen.dti <= 40 && <span className="pill ok"><Icon name="check" size={11}/> Clean</span>}
        </div>
      </div>

      {/* KV facts — two column grid */}
      <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:"8px 20px"}}>
        <KV label="Age" value={`${citizen.age} · ${citizen.maritalStatus}`}/>
        <KV label="Family size" value={citizen.familySize}/>
        <KV label="Location" value={`${citizen.wilayat}, ${citizen.governorate}`}/>
        <KV label="Employer" value={citizen.employer}/>
        <KV label="Income" value={`OMR ${citizen.monthlyIncomeOmr.toLocaleString()}/mo`} strong/>
        <KV label="DTI" value={<span><strong>{citizen.dti}%</strong> <span className="muted text-12">· {citizen.creditBand}</span></span>}/>
        <KV label="Waiting list" value={`#${citizen.waitingPosition.toLocaleString()}`}/>
        <KV label="Expected turn" value={citizen.expectedTurn}/>
      </div>

      {/* Flags row */}
      {(citizen.existingProperty || citizen.activeBenefit || citizen.spousePriorSupport || citizen.employerGrant || citizen.missingDocs.length > 0 || citizen.dti > 40) && (
        <div style={{display:"flex", gap:6, flexWrap:"wrap", marginTop:12, paddingTop:12, borderTop:"1px solid var(--hairline)"}}>
          {citizen.existingProperty && <Flag bad icon="home">Existing residential property</Flag>}
          {citizen.activeBenefit && <Flag bad icon="shield">Active housing benefit</Flag>}
          {citizen.spousePriorSupport && <Flag bad icon="users">Spouse prior support</Flag>}
          {citizen.employerGrant && <Flag bad icon="briefcase">Employer grant conflict</Flag>}
          {citizen.missingDocs.length > 0 && <Flag warn icon="doc">Missing: {citizen.missingDocs[0]}</Flag>}
          {citizen.dti > 40 && <Flag warn icon="scale">DTI above 40%</Flag>}
        </div>
      )}
    </aside>
  );
}

function KV({ label, value, strong }) {
  return (
    <div className="kv-row">
      <div className="tiny muted">{label}</div>
      <div className={`text-13 ${strong ? "kv-strong" : ""}`} style={{fontWeight: strong ? 700 : 500}}>{value}</div>
    </div>
  );
}

function Flag({ children, icon, ok, warn, bad }) {
  const cls = ok ? "ok" : warn ? "warn" : "bad";
  return (
    <div className={`case-flag ${cls}`}>
      <Icon name={icon} size={13}/> <span>{children}</span>
    </div>
  );
}

/* Center tabs */

function CaseTrace({ decision }) {
  const [open, setOpen] = React.useState(null);
  return (
    <div className="case-trace">
      <div className="case-trace-head">
        <div>
          <div className="label-eyebrow">Decision · ISKAN v4.2 · {decision.routing}</div>
          <div className="title" style={{marginTop:4, fontSize:17}}>
            {decision.trace.filter(r=>r.status==="passed").length} of {decision.trace.length} rules passed
          </div>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost sm"><Icon name="refresh" size={12}/> Re-run</button>
          <button className="btn ghost sm"><Icon name="download" size={12}/> Trace JSON</button>
        </div>
      </div>
      <div className="case-trace-list">
        {decision.trace.map((r) => (
          <TraceRow key={r.ruleId} rule={r} open={open === r.ruleId} onToggle={() => setOpen(open === r.ruleId ? null : r.ruleId)}/>
        ))}
      </div>
    </div>
  );
}

function CaseTimeline({ citizen }) {
  const events = [
    { ts: "Just now", who: "System", what: "Decision recomputed after document upload", icon: "refresh", color: "var(--brand-teal)" },
    { ts: "12 min ago", who: "Hassan F. (Analyst)", what: "Assigned to case", icon: "user", color: "var(--brand-navy)" },
    { ts: "27 min ago", who: "System", what: "Routed to Non-STP queue (DTI > 40%)", icon: "branch", color: "var(--brand-copper)" },
    { ts: "27 min ago", who: "System", what: "Eligibility evaluated · 8 integrations queried in 1.4s", icon: "zap", color: "var(--brand-teal)" },
    { ts: "32 min ago", who: citizen.name, what: "Submitted application from web portal", icon: "send", color: "var(--brand-navy)" },
    { ts: "1 day ago", who: citizen.name, what: "Account verified via OTP", icon: "phone_icon", color: "var(--muted)" },
  ];
  return (
    <div className="timeline">
      {events.map((e, i) => (
        <div key={i} className="timeline-entry">
          <div className="timeline-pip" style={{background: e.color, color: "#fff"}}>
            <Icon name={e.icon} size={11}/>
          </div>
          <div>
            <div className="text-13" style={{fontWeight:600}}>{e.what}</div>
            <div className="tiny muted" style={{marginTop:2}}>{e.who} · {e.ts}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function CaseDocs({ citizen }) {
  const docs = [
    { name: "National ID", status: "verified", source: "Civil Registry · auto-fetched" },
    { name: "Six-month bank statement", status: "verified", source: "Uploaded · OCR validated" },
    { name: "Marriage certificate", status: "verified", source: "Civil Registry · auto-fetched" },
    { name: "Salary certificate (recent)", status: citizen.missingDocs.length > 0 ? "missing" : "verified", source: "Citizen upload" },
    { name: "Existing loan liability statement", status: "verified", source: "Credit Bureau · auto-fetched" },
  ];
  return (
    <div style={{display:"flex", flexDirection:"column", gap:10}}>
      {docs.map((d) => (
        <div key={d.name} className="case-doc-row">
          <div className={`doc-icon status-${d.status}`}><Icon name={d.status === "verified" ? "doc_check" : "doc"} size={16}/></div>
          <div style={{flex:1}}>
            <div className="text-13" style={{fontWeight:600}}>{d.name}</div>
            <div className="tiny muted">{d.source}</div>
          </div>
          {d.status === "verified" ? <span className="pill ok"><Icon name="check" size={11}/> Verified</span> : <span className="pill warn">Missing</span>}
          <button className="btn ghost sm"><Icon name="eye" size={12}/></button>
        </div>
      ))}
    </div>
  );
}

function CaseIntegrations() {
  return (
    <div style={{display:"flex", flexDirection:"column", gap:10}}>
      {window.OHB_DATA.integrations.slice(0, 8).map((i) => (
        <div key={i.id} className="integ-row big">
          <div className="row" style={{gap:10}}>
            <span className={`statusdot ${i.status === "healthy" ? "ok" : "warn"}`}/>
            <div>
              <div className="text-13" style={{fontWeight:600}}>{i.name}</div>
              <div className="tiny muted">Called in this case · 200 OK</div>
            </div>
          </div>
          <div className="row" style={{gap:14}}>
            <span className="mono tiny muted">{i.latency}ms</span>
            <button className="btn ghost sm"><Icon name="eye" size={12}/> Payload</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function CaseNotes() {
  return (
    <div style={{display:"flex", flexDirection:"column", gap:14}}>
      <div className="note">
        <div className="row" style={{gap:8, marginBottom:4}}>
          <div className="avatar-sm" style={{background:"var(--brand-teal)"}}>HF</div>
          <span className="text-13" style={{fontWeight:600}}>Hassan F.</span>
          <span className="tiny muted">12 min ago</span>
        </div>
        <div className="text-13">Citizen confirmed via SMS they're uploading the salary cert today. Will reassess once received.</div>
      </div>
      <textarea className="textarea" placeholder="Add a note… visible to OHB analysts. Mentions trigger notifications."></textarea>
      <div className="row" style={{gap:8, justifyContent:"flex-end"}}>
        <button className="btn ghost sm">Attach</button>
        <button className="btn dark-on-light sm"><Icon name="send" size={13}/> Post</button>
      </div>
    </div>
  );
}

function CaseActions({ decision, citizen }) {
  return (
    <aside className="admin-case-right">
      <div className="card card-pad" data-showcase="MAKER-CHECKER">
        <div className="label-eyebrow">Recommended action</div>
        <div className="title" style={{marginTop:6, fontSize:16}}>
          {decision.outcome === "eligible" ? "Approve & route to chosen bank" :
           decision.outcome === "manual_review" ? "Request missing documents" :
           "Reject with alternative offer"}
        </div>
        <div className="muted text-13" style={{marginTop:6}}>
          Decision will be queued for a second approver per maker-checker policy.
        </div>
        <div className="row" style={{gap:8, marginTop:14}}>
          <button className="btn teal" style={{flex:1}}><Icon name="check" size={13}/> Approve</button>
          <button className="btn ghost" style={{flex:1}}><Icon name="user" size={13}/> Assign</button>
        </div>
        <div className="row text-12 muted" style={{gap:6, marginTop:10}}>
          <Icon name="info" size={11}/> Second approver: any senior in Ops
        </div>
      </div>

      <div className="card card-pad">
        <div className="label-eyebrow">Citizen contact</div>
        <div style={{marginTop:8, display:"flex", flexDirection:"column", gap:8}}>
          <ContactRow icon="phone_icon" label="Mobile" value={citizen.phone}/>
          <ContactRow icon="message" label="Last SMS" value="Yesterday · OTP sent"/>
          <ContactRow icon="globe" label="Preferred channel" value="Mobile app"/>
        </div>
      </div>

    </aside>
  );
}

function ContactRow({ icon, label, value }) {
  return (
    <div className="row" style={{gap:10, justifyContent:"space-between"}}>
      <div className="row" style={{gap:8}}>
        <Icon name={icon} size={13} style={{color:"var(--muted)"}}/>
        <span className="text-13">{label}</span>
      </div>
      <span className="text-13" style={{fontWeight:600}}>{value}</span>
    </div>
  );
}

window.AdminCase = AdminCase;
