// Admin — supporting screens: Integrations health, Programs index, Audit log

function AdminIntegrations() {
  return (
    <div>
      <div className="admin-page-head">
        <div>
          <div className="label-eyebrow">Platform</div>
          <h2 className="h2" style={{marginTop:4}}>Integrations health</h2>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost sm"><Icon name="refresh" size={13}/> Refresh</button>
          <button className="btn dark-on-light sm"><Icon name="plus" size={13}/> Connect new</button>
        </div>
      </div>

      <div className="integ-grid">
        {window.OHB_DATA.integrations.map((i) => (
          <div key={i.id} className="card card-pad integ-tile">
            <div className="row" style={{justifyContent:"space-between"}}>
              <div className="row" style={{gap:10}}>
                <div className={`integ-status ${i.status}`}/>
                <div>
                  <div className="text-14" style={{fontWeight:600}}>{i.name}</div>
                  <div className="tiny muted">{i.status === "healthy" ? "All systems normal" : "Elevated latency"}</div>
                </div>
              </div>
              <Icon name="more" size={16} style={{color:"var(--muted)"}}/>
            </div>
            <div className="row" style={{justifyContent:"space-between", marginTop:14}}>
              <div>
                <div className="tiny muted">p95 latency</div>
                <div className="text-14" style={{fontWeight:700}}>{i.latency}ms</div>
              </div>
              <div>
                <div className="tiny muted">Calls 24h</div>
                <div className="text-14" style={{fontWeight:700}}>{i.calls24h.toLocaleString()}</div>
              </div>
              <Spark values={generateSparkLine(i.id)} color={i.status === "healthy" ? "var(--brand-teal)" : "var(--warn)"}/>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function generateSparkLine(seed) {
  // deterministic pseudo-random
  let s = 0;
  for (let i = 0; i < seed.length; i++) s = (s + seed.charCodeAt(i)) % 1000;
  const out = [];
  for (let i = 0; i < 12; i++) {
    s = (s * 1103515245 + 12345) % 2147483647;
    out.push(60 + (s % 60));
  }
  return out;
}

function AdminPrograms({ setMode }) {
  return (
    <div>
      <div className="admin-page-head">
        <div>
          <div className="label-eyebrow">Configuration</div>
          <h2 className="h2" style={{marginTop:4}}>Housing programs</h2>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost"><Icon name="download" size={14}/> Export all</button>
          <button className="btn dark-on-light" onClick={() => setMode("builder")}>
            <Icon name="plus" size={14}/> New program in Studio
          </button>
        </div>
      </div>

      <div className="program-grid">
        {window.OHB_DATA.programs.map((p) => (
          <div key={p.id} className="program-card card">
            <div className="program-card-head" style={{
              background: p.id === "iskan" ? "linear-gradient(135deg, #1b4149, #2a5e68)"
                : p.id === "ohb-loan" ? "linear-gradient(135deg, #1c1b3b, #2a285a)"
                : "linear-gradient(135deg, #26262a, #3d3a36)"
            }}>
              <div>
                <div className="program-eyebrow">{p.type}</div>
                <div className="program-name">{p.name}</div>
                <div className="program-name-ar">{p.nameAr}</div>
              </div>
              <span className={`pill ${p.status === "Active" ? "ok" : "navy"}`} style={{background:"rgba(255,255,255,0.16)", color:"#fff", borderColor:"rgba(255,255,255,0.24)"}}>
                {p.status} · {p.version}
              </span>
            </div>
            <div className="card-pad">
              <div className="grid-3" style={{gap:10}}>
                <ProgramStat label="Active cases" value={p.activeCases.toLocaleString()}/>
                <ProgramStat label="STP rate" value={`${Math.round(p.stpRate * 100)}%`}/>
                <ProgramStat label="Avg decision" value={p.avgDecisionMs ? `${(p.avgDecisionMs/1000).toFixed(1)}s` : "—"}/>
              </div>
              <div className="hr" style={{margin:"12px 0"}}/>
              <div className="text-12 muted">Income band</div>
              <div className="text-13" style={{fontWeight:600}}>
                OMR {p.incomeMin.toLocaleString()} – {p.incomeMax > 99999 ? "no cap" : p.incomeMax.toLocaleString()}
              </div>
              <div className="text-12 muted" style={{marginTop:8}}>Available in</div>
              <div className="row" style={{gap:4, flexWrap:"wrap", marginTop:4}}>
                {p.governorates.slice(0,3).map((g) => <span key={g} className="chip-soft">{g}</span>)}
                {p.governorates.length > 3 && <span className="chip-soft">+{p.governorates.length - 3}</span>}
              </div>
              <button className="btn ghost" style={{width:"100%", marginTop:14}} onClick={() => setMode("builder")}>
                <Icon name="edit" size={13}/> Open in Studio
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProgramStat({ label, value }) {
  return (
    <div>
      <div className="tiny muted">{label}</div>
      <div className="text-14" style={{fontWeight:700, marginTop:2}}>{value}</div>
    </div>
  );
}

function AdminAudit() {
  const events = [
    { ts: "10:24", who: "Hassan F.", action: "Approved case", target: "C-50281", reason: "All rules passed; auto-routing to Bank Muscat" },
    { ts: "10:21", who: "Layla M.", action: "Requested documents", target: "C-50278", reason: "Salary certificate older than 90 days" },
    { ts: "10:18", who: "System", action: "Decision computed", target: "C-50280", reason: "Manual review · DTI 41%" },
    { ts: "09:56", who: "Sara A.", action: "Updated program", target: "ISKAN v4.2 → v4.3 (draft)", reason: "Raised income ceiling for Sohar" },
    { ts: "09:42", who: "Hassan F.", action: "Maker-checker · approved", target: "C-50276", reason: "Approved Aisha's submitted decision" },
    { ts: "09:18", who: "System", action: "Integration alert", target: "Income & Employment API", reason: "Latency above 1500ms · automatic retry succeeded" },
  ];
  return (
    <div>
      <div className="admin-page-head">
        <div>
          <div className="label-eyebrow">Compliance</div>
          <h2 className="h2" style={{marginTop:4}}>Audit log</h2>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn ghost"><Icon name="filter" size={14}/> Filter</button>
          <button className="btn ghost"><Icon name="download" size={14}/> Export (CBO format)</button>
        </div>
      </div>
      <div className="card" style={{padding:0}}>
        {events.map((e, i) => (
          <div key={i} className="audit-row">
            <span className="mono text-12 muted" style={{width:48}}>{e.ts}</span>
            <span className="text-13" style={{fontWeight:600, width:120}}>{e.who}</span>
            <span className="text-13" style={{width:180}}>{e.action}</span>
            <span className="mono text-12 muted" style={{width:200}}>{e.target}</span>
            <span className="text-13 muted" style={{flex:1}}>{e.reason}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.AdminIntegrations = AdminIntegrations;
window.AdminPrograms = AdminPrograms;
window.AdminAudit = AdminAudit;
