// ============================================================================
// public/screens/admin.jsx — Super-Admin Panel (Phase 8)
// ============================================================================

// ═══════════════════ Admin Overview ══════════════════════════════════════
function AdminOverviewScreen() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { VoaisAPI.get("/api/admin/overview").then(r => { if (r.ok) setData(r.data.overview); }); }, []);
  if (!data) return <DashboardSkeleton/>;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10 }}>
        <AKpiCard label="Total tenants" value={data.tenants.total}/>
        <AKpiCard label="Active" value={data.tenants.active} color="var(--ok)"/>
        <AKpiCard label="Trial" value={data.tenants.trial} color="var(--accent)"/>
        <AKpiCard label="Suspended" value={data.tenants.suspended} color="var(--err)"/>
        <AKpiCard label="Calls today" value={data.calls.today}/>
        <AKpiCard label="Active calls" value={data.calls.active_now} color="var(--warn)"/>
        <AKpiCard label="Total minutes" value={data.calls.total_minutes.toLocaleString("en-IN")}/>
        <AKpiCard label="MRR" value={"₹" + Number(data.revenue.mrr_inr).toLocaleString("en-IN")} color="var(--ok)"/>
      </div>
      {data.health?.length > 0 && (
        <Card><div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>System health</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 8 }}>
            {data.health.map((h, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 12px", background: "var(--surface-2)", borderRadius: 8 }}>
                <div style={{ width: 10, height: 10, borderRadius: "50%", background: h.status === "healthy" ? "var(--ok)" : h.status === "degraded" ? "var(--warn)" : "var(--err)" }}/>
                <div style={{ flex: 1, fontSize: 13 }}>{h.name}</div>
                {h.latency_ms && <span style={{ fontSize: 11, color: "var(--ink-3)" }}>{h.latency_ms}ms</span>}
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}

// ═══════════════════ Clients ═════════════════════════════════════════════
function AdminClientsScreen() {
  const [clients, setClients] = React.useState(null); const [pag, setPag] = React.useState({}); const [search, setSearch] = React.useState("");
  const [detail, setDetail] = React.useState(null); const [showCreate, setShow] = React.useState(false);
  const load = async (page = 1) => {
    const p = new URLSearchParams({ page, limit: 25 }); if (search) p.set("search", search);
    const r = await VoaisAPI.get("/api/admin/clients?" + p.toString());
    if (r.ok) { setClients(r.data.clients); setPag(r.data.pagination); }
  };
  React.useEffect(() => { load(); }, []);
  const openDetail = async (id) => { const r = await VoaisAPI.get("/api/admin/clients/" + id); if (r.ok) setDetail(r.data); };
  const updateClient = async (id, fields) => { await VoaisAPI.patch("/api/admin/clients/" + id, fields); load(); if (detail?.tenant?.id === id) openDetail(id); };

  if (!clients) return <DashboardSkeleton/>;
  return (<div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
      <input className="input" style={{ flex: 1, maxWidth: 300 }} placeholder="Search clients..." value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => { if (e.key === "Enter") load(); }}/>
      <Btn kind="ghost" size="sm" onClick={() => load()}>Search</Btn>
      <div style={{ flex: 1 }}/><Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShow(true)}>Add client</Btn>
    </div>
    <Card padded={false}><table className="data-table" style={{ width: "100%", fontSize: 13 }}>
      <thead><tr><th style={{paddingLeft:16}}>Client</th><th>Plan</th><th>Status</th><th>Calls</th><th>Users</th><th>MRR</th><th>Joined</th></tr></thead>
      <tbody>{clients.map(c => (
        <tr key={c.id} onClick={() => openDetail(c.id)} style={{ cursor: "pointer" }}>
          <td style={{paddingLeft:16}}><div style={{fontWeight:500}}>{c.name}</div><div style={{fontSize:11,color:"var(--ink-3)"}}>{c.slug} · {c.email || "—"}</div></td>
          <td><Badge tone="blue">{c.plan_name || "—"}</Badge></td>
          <td><Badge tone={c.status==="active"?"green":c.status==="trial"?"blue":c.status==="suspended"?"red":"gray"}>{c.status}</Badge></td>
          <td className="tabular">{+c.total_calls}</td>
          <td className="tabular">{+c.user_count}</td>
          <td className="tabular">{c.mrr_inr ? "₹"+Number(c.mrr_inr).toLocaleString("en-IN") : "—"}</td>
          <td style={{fontSize:11,color:"var(--ink-3)"}}>{new Date(c.created_at).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}</td>
        </tr>
      ))}</tbody>
    </table>
    {pag.pages > 1 && <div style={{display:"flex",justifyContent:"center",gap:8,padding:12}}><Btn kind="ghost" size="sm" disabled={pag.page<=1} onClick={()=>load(pag.page-1)}>Prev</Btn><span style={{fontSize:12,color:"var(--ink-3)"}}>Page {pag.page}/{pag.pages}</span><Btn kind="ghost" size="sm" disabled={pag.page>=pag.pages} onClick={()=>load(pag.page+1)}>Next</Btn></div>}
    </Card>

    {detail && <Modal title={detail.tenant.name} onClose={() => setDetail(null)} width={620}>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, fontSize: 13 }}>
          <div><span style={{color:"var(--ink-3)"}}>Slug:</span> {detail.tenant.slug}</div>
          <div><span style={{color:"var(--ink-3)"}}>Industry:</span> {detail.tenant.industry || "—"}</div>
          <div><span style={{color:"var(--ink-3)"}}>Status:</span> <Badge tone={detail.tenant.status==="active"?"green":"red"}>{detail.tenant.status}</Badge></div>
        </div>
        {detail.subscription && <div style={{fontSize:13}}>Plan: <Badge tone="blue">{detail.subscription.plan_name}</Badge> · {detail.subscription.status} · MRR ₹{Number(detail.subscription.mrr_inr||0).toLocaleString("en-IN")}</div>}
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8}}>
          <div style={{padding:"8px 12px",background:"var(--surface-2)",borderRadius:8,textAlign:"center"}}><div style={{fontSize:18,fontWeight:600}}>{+detail.stats.total_calls}</div><div style={{fontSize:11,color:"var(--ink-3)"}}>Calls</div></div>
          <div style={{padding:"8px 12px",background:"var(--surface-2)",borderRadius:8,textAlign:"center"}}><div style={{fontSize:18,fontWeight:600}}>{+detail.stats.agents}</div><div style={{fontSize:11,color:"var(--ink-3)"}}>Agents</div></div>
          <div style={{padding:"8px 12px",background:"var(--surface-2)",borderRadius:8,textAlign:"center"}}><div style={{fontSize:18,fontWeight:600}}>{+detail.stats.contacts}</div><div style={{fontSize:11,color:"var(--ink-3)"}}>Contacts</div></div>
        </div>
        <div style={{fontSize:13,fontWeight:600,marginTop:8}}>Team ({detail.users?.length})</div>
        {detail.users?.map(u => <div key={u.id} style={{fontSize:12,display:"flex",gap:8}}><span>{u.name || u.email}</span><Badge tone="gray">{u.role}</Badge></div>)}
        <div style={{display:"flex",gap:8,marginTop:8}}>
          {detail.tenant.status !== "suspended" && <Btn kind="ghost" size="sm" style={{color:"var(--err)"}} onClick={() => updateClient(detail.tenant.id, {status:"suspended"})}>Suspend</Btn>}
          {detail.tenant.status === "suspended" && <Btn kind="primary" size="sm" onClick={() => updateClient(detail.tenant.id, {status:"active"})}>Unsuspend</Btn>}
        </div>
      </div>
    </Modal>}

    {showCreate && <Modal title="Add client" onClose={() => setShow(false)} width={460}>
      <AdminCreateClient onCreated={() => { setShow(false); load(); }}/>
    </Modal>}
  </div>);
}

function AdminCreateClient({ onCreated }) {
  const [f, setF] = React.useState({ name: "", slug: "", email: "", plan_code: "starter" }); const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!f.name.trim()||!f.slug.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/admin/clients", f); setSub(false); if (r.ok) onCreated(); else alert(r.data?.msg); };
  return (<div style={{display:"flex",flexDirection:"column",gap:14}}>
    <Field label="Company name *"><input className="input" autoFocus value={f.name} onChange={e => setF({...f, name: e.target.value})}/></Field>
    <Field label="Slug *"><input className="input" value={f.slug} onChange={e => setF({...f, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")})}/></Field>
    <Field label="Email"><input className="input" value={f.email} onChange={e => setF({...f, email: e.target.value})}/></Field>
    <Field label="Plan"><select className="select" value={f.plan_code} onChange={e => setF({...f, plan_code: e.target.value})}><option value="starter">Starter</option><option value="growth">Growth</option><option value="pro">Pro</option><option value="enterprise">Enterprise</option></select></Field>
    <Btn kind="primary" onClick={submit} disabled={sub}>{sub ? "Creating..." : "Create"}</Btn>
  </div>);
}

// ═══════════════════ SIP Trunks ══════════════════════════════════════════
function AdminSipScreen() {
  const [trunks, setTrunks] = React.useState(null);
  const load = () => VoaisAPI.get("/api/admin/sip").then(r => { if (r.ok) setTrunks(r.data.trunks); });
  React.useEffect(() => { load(); }, []);
  if (!trunks) return <DashboardSkeleton/>;
  return (<Card padded={false}><table className="data-table" style={{width:"100%",fontSize:13}}>
    <thead><tr><th style={{paddingLeft:16}}>Trunk</th><th>Provider</th><th>Server</th><th>Channels</th><th>Status</th><th>Tenant</th></tr></thead>
    <tbody>{trunks.map(t => (
      <tr key={t.id}><td style={{paddingLeft:16,fontWeight:500}}>{t.name}</td><td><Badge tone="gray">{t.provider}</Badge></td>
      <td style={{fontSize:11,fontFamily:"var(--font-mono)"}}>{t.server}:{t.port}</td>
      <td className="tabular">{t.channel_capacity}</td>
      <td><Badge tone={t.status==="healthy"?"green":t.status==="degraded"?"yellow":"red"}>{t.status}</Badge></td>
      <td style={{fontSize:12}}>{t.tenant_name || "Platform"}</td></tr>
    ))}{trunks.length===0&&<tr><td colSpan={6} style={{textAlign:"center",padding:32,color:"var(--ink-3)"}}>No SIP trunks configured.</td></tr>}</tbody>
  </table></Card>);
}

// ═══════════════════ Agent Library ═══════════════════════════════════════
function AdminAgentLibScreen() {
  const [agents, setAgents] = React.useState(null);
  React.useEffect(() => { VoaisAPI.get("/api/admin/agents").then(r => { if (r.ok) setAgents(r.data.agents); }); }, []);
  if (!agents) return <DashboardSkeleton/>;
  return (<Card padded={false}><table className="data-table" style={{width:"100%",fontSize:13}}>
    <thead><tr><th style={{paddingLeft:16}}>Agent</th><th>Role</th><th>Language</th><th>LLM</th><th>Status</th><th>Calls</th></tr></thead>
    <tbody>{agents.map(a => (
      <tr key={a.id}><td style={{paddingLeft:16}}><div style={{fontWeight:500}}>{a.name}</div><div style={{fontSize:11,color:"var(--ink-3)"}}>{a.code}</div></td>
      <td>{a.role||"—"}</td><td><Badge tone="blue">{a.language}</Badge></td><td style={{fontSize:12}}>{a.llm_provider}/{a.llm_model}</td>
      <td><Badge tone={a.status==="active"?"green":"gray"}>{a.status}</Badge></td><td className="tabular">{a.total_calls}</td></tr>
    ))}{agents.length===0&&<tr><td colSpan={6} style={{textAlign:"center",padding:32,color:"var(--ink-3)"}}>No global agent templates.</td></tr>}</tbody>
  </table></Card>);
}

// ═══════════════════ Billing Overview ════════════════════════════════════
function AdminBillingScreen() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { VoaisAPI.get("/api/admin/billing").then(r => { if (r.ok) setData(r.data); }); }, []);
  if (!data) return <DashboardSkeleton/>;
  return (<div style={{display:"flex",flexDirection:"column",gap:"var(--gap-grid)"}}>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
      <AKpiCard label="MRR" value={"₹"+Number(data.mrr).toLocaleString("en-IN")} color="var(--ok)"/>
      <AKpiCard label="ARR" value={"₹"+Number(data.arr).toLocaleString("en-IN")}/>
    </div>
    <Card><div style={{fontSize:14,fontWeight:600,marginBottom:12}}>Subscribers by plan</div>
      {data.byPlan?.map(p => <div key={p.code} style={{display:"flex",gap:12,padding:"6px 0",fontSize:13,borderBottom:"1px solid var(--line)"}}>
        <span style={{flex:1,fontWeight:500}}>{p.name}</span><span className="tabular">{p.count} clients</span><span className="tabular" style={{fontWeight:600}}>₹{Number(p.revenue).toLocaleString("en-IN")}/mo</span>
      </div>)}
    </Card>
    <Card><div style={{fontSize:14,fontWeight:600,marginBottom:12}}>Recent invoices</div>
      <table className="data-table" style={{width:"100%",fontSize:13}}><thead><tr><th style={{paddingLeft:16}}>Invoice</th><th>Tenant</th><th>Amount</th><th>Status</th></tr></thead>
      <tbody>{(data.recentInvoices||[]).map((inv,i) => (
        <tr key={i}><td style={{paddingLeft:16}}>{inv.invoice_number}</td><td>{inv.tenant_name}</td>
        <td className="tabular">₹{Number(inv.total_inr).toLocaleString("en-IN")}</td>
        <td><Badge tone={inv.status==="paid"?"green":"red"}>{inv.status}</Badge></td></tr>
      ))}</tbody></table>
    </Card>
  </div>);
}

// ═══════════════════ Compliance ══════════════════════════════════════════
function AdminComplianceScreen() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { VoaisAPI.get("/api/admin/compliance").then(r => { if (r.ok) setData(r.data); }); }, []);
  if (!data) return <DashboardSkeleton/>;
  return (<div style={{display:"flex",flexDirection:"column",gap:"var(--gap-grid)"}}>
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
      <AKpiCard label="Global DNC numbers" value={data.dnc.global}/>
      <AKpiCard label="Tenant DNC numbers" value={data.dnc.tenant}/>
    </div>
    {data.recentViolations?.length > 0 && <Card><div style={{fontSize:14,fontWeight:600,marginBottom:12}}>Recent compliance events</div>
      {data.recentViolations.map((v,i) => <div key={i} style={{fontSize:13,padding:"6px 0",borderBottom:"1px solid var(--line)",display:"flex",gap:10}}>
        <span style={{flex:1}}>{v.tenant_name || "Platform"}</span><Badge tone="gray">{v.action}</Badge>
        <span style={{fontSize:11,color:"var(--ink-3)"}}>{new Date(v.created_at).toLocaleString("en-IN")}</span>
      </div>)}
    </Card>}
  </div>);
}

// ═══════════════════ System Health ═══════════════════════════════════════
function AdminHealthScreen() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { VoaisAPI.get("/api/admin/health").then(r => { if (r.ok) setData(r.data); }); }, []);
  if (!data) return <DashboardSkeleton/>;
  return (<div style={{display:"flex",flexDirection:"column",gap:"var(--gap-grid)"}}>
    <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:10}}>
      {data.checks?.map((c,i) => (
        <div key={i} style={{padding:"12px 14px",background:"var(--surface-2)",borderRadius:10}}>
          <div style={{display:"flex",alignItems:"center",gap:8}}>
            <div style={{width:10,height:10,borderRadius:"50%",background:c.status==="healthy"?"var(--ok)":c.status==="degraded"?"var(--warn)":"var(--err)"}}/>
            <span style={{fontSize:13,fontWeight:500,flex:1}}>{c.name}</span>
          </div>
          <div style={{fontSize:12,color:"var(--ink-3)",marginTop:4}}>
            {c.category} · {c.latency_ms ? c.latency_ms + "ms" : "—"}
            {c.success_rate != null && <span> · {Number(c.success_rate).toFixed(1)}%</span>}
          </div>
          {c.last_error && <div style={{fontSize:11,color:"var(--err)",marginTop:4}}>{c.last_error}</div>}
        </div>
      ))}
    </div>
    <Card><div style={{fontSize:14,fontWeight:600,marginBottom:12}}>AI providers</div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(200px, 1fr))",gap:8}}>
        {data.aiProviders?.map(p => (
          <div key={p.id} style={{padding:"10px 12px",background:"var(--surface-2)",borderRadius:8,fontSize:13}}>
            <div style={{fontWeight:500}}>{p.display_name}</div>
            <div style={{fontSize:12,color:"var(--ink-3)"}}>{p.category} · {p.default_model}</div>
            <Badge tone={p.enabled ? "green" : "gray"}>{p.enabled ? "Enabled" : "Disabled"}</Badge>
          </div>
        ))}
      </div>
    </Card>
    <Card>
      <div style={{fontSize:14,fontWeight:600,marginBottom:8}}>Jobs queue</div>
      <div style={{display:"flex",gap:16,fontSize:13}}>
        <span>Total: <strong>{data.jobs.total}</strong></span>
        <span>Pending: <strong style={{color:"var(--warn)"}}>{data.jobs.pending}</strong></span>
        <span>Running: <strong style={{color:"var(--accent)"}}>{data.jobs.running}</strong></span>
        <span>Failed: <strong style={{color:"var(--err)"}}>{data.jobs.failed}</strong></span>
      </div>
    </Card>
  </div>);
}

// ═══════════════════ Audit Logs ══════════════════════════════════════════
function AdminAuditScreen() {
  const [entries, setEntries] = React.useState(null); const [pag, setPag] = React.useState({}); const [actionF, setActionF] = React.useState("");
  const load = async (page = 1) => {
    const p = new URLSearchParams({ page, limit: 50 }); if (actionF) p.set("action", actionF);
    const r = await VoaisAPI.get("/api/admin/audit?" + p.toString());
    if (r.ok) { setEntries(r.data.entries); setPag(r.data.pagination); }
  };
  React.useEffect(() => { load(); }, []);
  if (!entries) return <DashboardSkeleton/>;
  return (<div style={{display:"flex",flexDirection:"column",gap:"var(--gap-grid)"}}>
    <div style={{display:"flex",gap:8}}>
      <input className="input" style={{maxWidth:240}} placeholder="Filter by action..." value={actionF} onChange={e => setActionF(e.target.value)} onKeyDown={e => {if(e.key==="Enter")load();}}/>
      <Btn kind="ghost" size="sm" onClick={() => load()}>Filter</Btn>
    </div>
    <Card padded={false}><table className="data-table" style={{width:"100%",fontSize:13}}>
      <thead><tr><th style={{paddingLeft:16}}>Action</th><th>Actor</th><th>Tenant</th><th>Entity</th><th>When</th></tr></thead>
      <tbody>{entries.map(e => (
        <tr key={e.id}><td style={{paddingLeft:16,fontWeight:500}}>{e.action}</td>
        <td><div style={{fontSize:12}}>{e.actor_email || e.actor_type}</div></td>
        <td style={{fontSize:12}}>{e.tenant_name || "—"}</td>
        <td style={{fontSize:12}}>{e.entity_type ? e.entity_type + " #" + e.entity_id : "—"}</td>
        <td style={{fontSize:11,color:"var(--ink-3)"}}>{new Date(e.created_at).toLocaleString("en-IN")}</td></tr>
      ))}</tbody>
    </table>
    {pag.pages>1&&<div style={{display:"flex",justifyContent:"center",gap:8,padding:12}}><Btn kind="ghost" size="sm" disabled={pag.page<=1} onClick={()=>load(pag.page-1)}>Prev</Btn><span style={{fontSize:12,color:"var(--ink-3)"}}>Page {pag.page}/{pag.pages} ({pag.total} entries)</span><Btn kind="ghost" size="sm" disabled={pag.page>=pag.pages} onClick={()=>load(pag.page+1)}>Next</Btn></div>}
    </Card>
  </div>);
}

// ── Shared ───────────────────────────────────────────────────────────────
function AKpiCard({ label, value, color }) {
  return (<div style={{ padding: "14px 16px", background: "var(--surface-2)", borderRadius: 10 }}>
    <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{label}</div>
    <div style={{ fontSize: 22, fontWeight: 700, color: color || "var(--ink-1)", marginTop: 2 }} className="tabular">{value}</div>
  </div>);
}

// ═══════════════════ Platform Telephony (BYOI defaults) ══════════════════
// Super-admin sets the shared Asterisk / Dinstar config that every tenant on
// "platform" mode falls back to. Secrets are masked on read; sending "" on
// save means "leave as-is", a non-empty string replaces, null clears.
function AdminTelephonyScreen() {
  const [cfg, setCfg] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [testing, setTesting] = React.useState(false);
  const [status, setStatus] = React.useState(null);
  const [testResult, setTestResult] = React.useState(null);
  const [touched, setTouched] = React.useState({ ami_secret: false, ari_password: false });
  const [secrets, setSecrets] = React.useState({ ami_secret: "", ari_password: "" });

  const load = React.useCallback(() => {
    VoaisAPI.get("/api/admin/telephony-defaults").then(r => {
      if (r.ok && r.data?.ok) setCfg(r.data.config);
    });
  }, []);
  React.useEffect(() => { load(); }, [load]);

  if (!cfg) return <DashboardSkeleton/>;
  const setField = (k, v) => setCfg({ ...cfg, [k]: v });

  const save = async () => {
    setSaving(true); setStatus(null);
    const payload = {
      ami_host: cfg.ami_host, ami_port: cfg.ami_port, ami_user: cfg.ami_user,
      ari_url: cfg.ari_url, ari_user: cfg.ari_user, ari_app: cfg.ari_app,
      external_media_host: cfg.external_media_host, external_media_port: cfg.external_media_port,
      trunk: cfg.trunk, ai_context: cfg.ai_context, dial_context: cfg.dial_context,
      dinstar_ip: cfg.dinstar_ip, gsm_ports: cfg.gsm_ports, gsm_prefix_template: cfg.gsm_prefix_template,
    };
    if (touched.ami_secret)  payload.ami_secret  = secrets.ami_secret;
    if (touched.ari_password) payload.ari_password = secrets.ari_password;
    const r = await VoaisAPI.patch("/api/admin/telephony-defaults", payload);
    setSaving(false);
    if (r.ok) {
      setStatus({ ok: true, msg: "Saved" });
      setSecrets({ ami_secret: "", ari_password: "" });
      setTouched({ ami_secret: false, ari_password: false });
      load();
    } else {
      setStatus({ ok: false, msg: r.data?.msg || "Save failed" });
    }
    setTimeout(() => setStatus(null), 3000);
  };

  const runTest = async () => {
    setTesting(true); setTestResult(null);
    const r = await VoaisAPI.post("/api/admin/telephony-defaults/test");
    setTesting(false);
    setTestResult({ ok: r.ok && r.data?.ok, msg: r.data?.msg || (r.ok ? "OK" : "Test failed"), ms: r.data?.ms });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <Card>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Platform Asterisk defaults</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>
              Tenants on "Use Platform Asterisk" mode fall back to these values. Secrets are AES-256-GCM encrypted at rest.
            </div>
          </div>
          {status && <Badge tone={status.ok ? "green" : "red"}>{status.msg}</Badge>}
        </div>
      </Card>

      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Asterisk AMI</div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field label="AMI host">
            <input className="input" placeholder="127.0.0.1 or asterisk.platform.in"
              value={cfg.ami_host || ""} onChange={e => setField("ami_host", e.target.value)}/>
          </Field>
          <Field label="AMI port">
            <input className="input" type="number" value={cfg.ami_port || 5038}
              onChange={e => setField("ami_port", Number(e.target.value))}/>
          </Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="AMI username">
            <input className="input" placeholder="voiceapp" value={cfg.ami_user || ""}
              onChange={e => setField("ami_user", e.target.value)}/>
          </Field>
          <Field label="AMI secret" hint={cfg.ami_secret_set ? "Saved · " + cfg.ami_secret_mask : "Not set"}>
            <input className="input" type="password" autoComplete="new-password"
              placeholder={cfg.ami_secret_set ? "•••• saved ••••" : ""}
              value={secrets.ami_secret}
              onChange={e => { setSecrets({ ...secrets, ami_secret: e.target.value }); setTouched({ ...touched, ami_secret: true }); }}/>
          </Field>
        </div>
      </Card>

      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Asterisk ARI</div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field label="ARI URL">
            <input className="input" placeholder="http://127.0.0.1:8088" value={cfg.ari_url || ""}
              onChange={e => setField("ari_url", e.target.value)}/>
          </Field>
          <Field label="ARI app">
            <input className="input" placeholder="voicegsm" value={cfg.ari_app || ""}
              onChange={e => setField("ari_app", e.target.value)}/>
          </Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="ARI user">
            <input className="input" placeholder="voiceari" value={cfg.ari_user || ""}
              onChange={e => setField("ari_user", e.target.value)}/>
          </Field>
          <Field label="ARI password" hint={cfg.ari_password_set ? "Saved · " + cfg.ari_password_mask : "Not set"}>
            <input className="input" type="password" autoComplete="new-password"
              placeholder={cfg.ari_password_set ? "•••• saved ••••" : ""}
              value={secrets.ari_password}
              onChange={e => { setSecrets({ ...secrets, ari_password: e.target.value }); setTouched({ ...touched, ari_password: true }); }}/>
          </Field>
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 12, marginBottom: 10 }}>External media</div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field label="Host" hint="Where Asterisk sends RTP audio for AI calls.">
            <input className="input" placeholder="media.platform.in" value={cfg.external_media_host || ""}
              onChange={e => setField("external_media_host", e.target.value)}/>
          </Field>
          <Field label="Port">
            <input className="input" type="number" value={cfg.external_media_port || 12000}
              onChange={e => setField("external_media_port", Number(e.target.value))}/>
          </Field>
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 12, marginBottom: 10 }}>Dialplan contexts</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <Field label="Trunk">
            <input className="input" placeholder="1111" value={cfg.trunk || ""}
              onChange={e => setField("trunk", e.target.value)}/>
          </Field>
          <Field label="AI context">
            <input className="input" placeholder="gsm-ai-out" value={cfg.ai_context || ""}
              onChange={e => setField("ai_context", e.target.value)}/>
          </Field>
          <Field label="Dial context">
            <input className="input" placeholder="gsm-out" value={cfg.dial_context || ""}
              onChange={e => setField("dial_context", e.target.value)}/>
          </Field>
        </div>
      </Card>

      <Card>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Dinstar GSM gateway (platform default)</div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
          <Field label="Dinstar IP">
            <input className="input" placeholder="192.168.1.220" value={cfg.dinstar_ip || ""}
              onChange={e => setField("dinstar_ip", e.target.value)}/>
          </Field>
          <Field label="GSM ports" hint="CSV, e.g. 30,31">
            <input className="input" placeholder="30,31" value={cfg.gsm_ports || ""}
              onChange={e => setField("gsm_ports", e.target.value)}/>
          </Field>
          <Field label="Prefix template" hint="'70' means port 30 → '7030'">
            <input className="input" placeholder="70" value={cfg.gsm_prefix_template || ""}
              onChange={e => setField("gsm_prefix_template", e.target.value)}/>
          </Field>
        </div>
      </Card>

      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Btn kind="primary" onClick={save} disabled={saving}>{saving ? "Saving…" : "Save platform defaults"}</Btn>
          <Btn kind="ghost" onClick={runTest} disabled={testing || saving}>
            {testing ? "Testing…" : "Test platform AMI"}
          </Btn>
          {testResult && (
            <Badge tone={testResult.ok ? "green" : "red"}>
              {testResult.ok ? `OK (${testResult.ms || 0}ms)` : testResult.msg}
            </Badge>
          )}
        </div>
      </Card>
    </div>
  );
}

// Expose all admin screens globally
window.AdminOverviewScreen   = AdminOverviewScreen;
window.AdminClientsScreen    = AdminClientsScreen;
window.AdminSipScreen        = AdminSipScreen;
window.AdminAgentLibScreen   = AdminAgentLibScreen;
window.AdminBillingScreen    = AdminBillingScreen;
window.AdminComplianceScreen = AdminComplianceScreen;
window.AdminHealthScreen     = AdminHealthScreen;
window.AdminAuditScreen      = AdminAuditScreen;
window.AdminTelephonyScreen  = AdminTelephonyScreen;
