// Admin panel — wired to real API
const { useState: aSt, useEffect: aEf, useRef: aRf } = React;

// ───────── Admin Overview ─────────
function AdminOverview() {
  const [overview, setOverview] = aSt(null);
  const [pulse, setPulse]       = aSt({ summary: {}, recent: [] });

  aEf(() => {
    let stop = false;
    (async () => { setOverview(await window.HDR_API.adminOverview().catch(() => null)); })();
    const tick = async () => {
      if (stop) return;
      try { setPulse(await window.HDR_API.adminPulse()); } catch {}
    };
    tick();
    const id = setInterval(tick, 5000);
    return () => { stop = true; clearInterval(id); };
  }, []);

  const u = overview?.users  || {};
  const us = overview?.usage  || {};
  const byEp = overview?.byEndpoint || [];

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Admin Overview</h1>
          <p className="page-sub">Platform-wide KPIs and live request pulse. Auto-refreshes every 5s.</p>
        </div>
        <div className="actions">
          <button className="btn" onClick={() => location.reload()}><I.refresh/> Refresh</button>
        </div>
      </div>

      <div className="kpi-grid">
        <KPI label={<><I.users/> Total users</>} value={U.num(u.total || 0)} spark={[12,14,16,18,22,26,30]}/>
        <KPI label={<><I.zap/> Requests (30d)</>} value={U.num(us.reqs_30d || 0)} spark={[40,55,52,68,72,80,95]}/>
        <KPI label={<><I.wallet/> Revenue (30d)</>} value={U.rupees(us.revenue_30d || 0, { short: true })} spark={[20,28,32,38,42,48,55]} sparkColor="var(--pos)"/>
        <KPI label={<><I.shield/> Failed (30d)</>} value={U.num(us.failed_30d || 0)} spark={[12,11,9,8,7,6,5]} sparkColor="var(--neg)"/>
      </div>

      <div className="grid-32">
        <div className="card">
          <div className="card-head">
            <div className="card-title">Live activity</div>
            <div className="spacer"/>
            <span className="live-pill" style={{padding:'4px 10px'}}>
              <span className="live-dot"/>
              <span style={{fontSize: 11.5}}>{pulse.summary?.reqs_60min || 0} req · {U.rupees(pulse.summary?.revenue_60min || 0)} · {pulse.summary?.active_users_60min || 0} active (last hour)</span>
            </span>
          </div>
          <div style={{maxHeight: 360, overflow:'auto'}}>
            {(pulse.recent || []).length === 0 ? (
              <div className="muted" style={{padding:'20px 0', textAlign:'center', fontSize: 13}}>No recent activity</div>
            ) : (pulse.recent || []).map(p => (
              <div key={p.id} className="row" style={{padding:'8px 0', borderBottom:'1px solid var(--border)', fontSize: 12.5}}>
                <span className={'badge ' + (p.status === 'success' ? 'pos' : 'neg')}>{p.status === 'success' ? 'OK' : 'FAIL'}</span>
                <span className="mono" style={{minWidth: 80}}>{p.model_alias || '—'}</span>
                <span className="muted" style={{textTransform:'capitalize'}}>{p.endpoint}</span>
                <span className="muted" style={{flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{p.email || '—'}</span>
                <span className="mono muted">{U.rupees(p.cost_paise || 0)}</span>
                <span className="muted mono" style={{minWidth: 60, textAlign:'right'}}>{p.latency_ms || 0}ms</span>
              </div>
            ))}
          </div>
        </div>

        <div className="col" style={{gap: 16}}>
          <div className="card">
            <div className="card-head"><div className="card-title">Providers</div></div>
            {Object.entries(overview?.providers || {}).map(([name, ok]) => (
              <div key={name} className="row" style={{padding: '6px 0', fontSize: 13}}>
                <span className="tag-dot" style={{ background: C.providers[name]?.color }}/>
                <span style={{textTransform:'capitalize'}}>{name}</span>
                <div className="spacer"/>
                <span className={'badge ' + (ok ? 'pos' : 'neg')}>{ok ? 'configured' : 'missing'}</span>
              </div>
            ))}
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">Razorpay</div></div>
            <div className="row" style={{fontSize: 13}}>
              <span>Status</span>
              <div className="spacer"/>
              <span className={'badge ' + (overview?.razorpay?.configured ? (overview.razorpay.mode === 'live' ? 'pos' : 'warn') : 'neg')}>
                {overview?.razorpay?.configured ? (overview.razorpay.mode || 'test').toUpperCase() : 'Not configured'}
              </span>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">Endpoints (30d)</div></div>
            {byEp.length === 0 ? (
              <div className="muted" style={{fontSize: 13}}>No data yet</div>
            ) : byEp.map(e => (
              <div key={e.endpoint} className="row" style={{fontSize: 12.5, padding: '4px 0'}}>
                <span style={{textTransform:'capitalize'}}>{e.endpoint}</span>
                <div className="spacer"/>
                <span className="muted mono">{e.c}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ───────── Analytics ─────────
function AdminAnalytics() {
  const [days, setDays] = aSt(30);
  const { data, loading, reload } = useLoad(() => window.HDR_API.adminAnalytics(days), [days]);

  const series = (data?.series || []).map(s => ({ label: s.d?.slice(5) || '', v: Number(s.revenue) }));
  const totalRev = (data?.series || []).reduce((s, x) => s + Number(x.revenue), 0);
  const totalReq = (data?.series || []).reduce((s, x) => s + Number(x.reqs), 0);
  const totalFail = (data?.series || []).reduce((s, x) => s + Number(x.failed), 0);
  const successRate = totalReq ? (((totalReq - totalFail) / totalReq) * 100).toFixed(1) : '—';

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Analytics</h1>
          <p className="page-sub">Trends, top users, top models, provider performance.</p>
        </div>
        <div className="actions">
          <div className="seg">
            {[7, 30, 90].map(d => (
              <button key={d} className={days === d ? 'active' : ''} onClick={() => setDays(d)}>{d}d</button>
            ))}
          </div>
        </div>
      </div>

      <div className="kpi-grid">
        <KPI label="Requests" value={U.num(totalReq)} spark={[20,30,40,35,45,55,65]}/>
        <KPI label="Revenue" value={U.rupees(totalRev, { short: true })} spark={[10,20,30,25,40,45,55]} sparkColor="var(--accent)"/>
        <KPI label="Failed" value={U.num(totalFail)} spark={[5,3,4,2,3,1,2]} sparkColor="var(--neg)"/>
        <KPI label="Success rate" value={successRate} unit="%" spark={[95,96,97,98,99,99,99]} sparkColor="var(--pos)"/>
      </div>

      <div className="card">
        <div className="card-head"><div className="card-title">Daily revenue</div></div>
        {loading ? <div className="muted" style={{padding: 20}}>Loading…</div> : <LineChart series={series}/>}
      </div>

      <div className="grid-23" style={{gap: 16, marginTop: 20}}>
        <div className="card" style={{padding: 0}}>
          <div className="card-head" style={{padding:'14px 18px'}}><div className="card-title">Top users by spend</div></div>
          <table className="table">
            <thead><tr><th>User</th><th style={{textAlign:'right'}}>Requests</th><th style={{textAlign:'right'}}>Spent</th></tr></thead>
            <tbody>
              {(data?.topUsers || []).map(u => (
                <tr key={u.id}>
                  <td>{u.email || '—'}</td>
                  <td className="mono muted" style={{textAlign:'right'}}>{u.reqs}</td>
                  <td className="mono" style={{textAlign:'right'}}>{U.rupees(u.spent)}</td>
                </tr>
              ))}
              {(data?.topUsers || []).length === 0 && <tr><td colSpan="3" className="muted" style={{textAlign:'center', padding: 20}}>No data</td></tr>}
            </tbody>
          </table>
        </div>

        <div className="card" style={{padding: 0}}>
          <div className="card-head" style={{padding:'14px 18px'}}><div className="card-title">Top model aliases</div></div>
          <table className="table">
            <thead><tr><th>Alias</th><th style={{textAlign:'right'}}>Requests</th><th style={{textAlign:'right'}}>Revenue</th></tr></thead>
            <tbody>
              {(data?.topModels || []).map(m => (
                <tr key={m.model_alias}>
                  <td className="mono">{m.model_alias}</td>
                  <td className="mono muted" style={{textAlign:'right'}}>{m.c}</td>
                  <td className="mono" style={{textAlign:'right'}}>{U.rupees(m.revenue)}</td>
                </tr>
              ))}
              {(data?.topModels || []).length === 0 && <tr><td colSpan="3" className="muted" style={{textAlign:'center', padding: 20}}>No data</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card" style={{marginTop: 16, padding: 0}}>
        <div className="card-head" style={{padding:'14px 18px'}}><div className="card-title">Provider performance</div></div>
        <table className="table">
          <thead><tr><th>Provider</th><th style={{textAlign:'right'}}>Total</th><th style={{textAlign:'right'}}>Success</th><th style={{textAlign:'right'}}>Failed</th><th style={{textAlign:'right'}}>Success rate</th><th style={{textAlign:'right'}}>Avg latency</th></tr></thead>
          <tbody>
            {(data?.providerHealth || []).map(p => {
              const rate = p.total ? ((p.ok / p.total) * 100).toFixed(1) : '—';
              return (
                <tr key={p.provider}>
                  <td><span className="tag-dot" style={{ background: C.providers[p.provider]?.color }}/> <span style={{textTransform:'capitalize'}}>{p.provider}</span></td>
                  <td className="mono muted" style={{textAlign:'right'}}>{p.total}</td>
                  <td className="mono" style={{textAlign:'right', color:'var(--pos)'}}>{p.ok}</td>
                  <td className="mono" style={{textAlign:'right', color:'var(--neg)'}}>{p.fail}</td>
                  <td style={{textAlign:'right'}}><span className={'badge ' + (parseFloat(rate) >= 95 ? 'pos' : 'warn')}>{rate}%</span></td>
                  <td className="mono muted" style={{textAlign:'right'}}>{Math.round(p.avg_latency || 0)}ms</td>
                </tr>
              );
            })}
            {(data?.providerHealth || []).length === 0 && <tr><td colSpan="6" className="muted" style={{textAlign:'center', padding: 20}}>No data</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ───────── Users ─────────
function AdminUsers() {
  const [q, setQ] = aSt('');
  const [users, setUsers] = aSt([]);
  const [loading, setLoading] = aSt(true);
  const toast = useToast();
  const timer = aRf(null);

  const load = async (qv) => {
    setLoading(true);
    try { setUsers(await window.HDR_API.adminUsers(qv || '')); }
    finally { setLoading(false); }
  };

  aEf(() => { load(''); }, []);
  const onSearch = (v) => {
    setQ(v);
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => load(v), 300);
  };

  const credit = async (u) => {
    const inr = parseFloat(prompt(`Credit how much to ${u.email}? (₹)`));
    if (!inr || inr <= 0) return;
    const note = prompt('Note:', 'Manual top-up') || 'Admin credit';
    try {
      const r = await window.HDR_API.creditUser(u.id, { amount_inr: inr, note });
      if (r.ok) { toast('Credited', 'pos'); load(q); }
      else throw new Error(r.error);
    } catch (e) { toast('Failed: ' + e.message, 'neg'); }
  };

  const toggle = async (u) => {
    if (!confirm(u.is_active ? 'Suspend this user?' : 'Activate this user?')) return;
    await window.HDR_API.toggleUser(u.id);
    toast('Updated', 'pos');
    load(q);
  };

  const toggleAdmin = async (u) => {
    if (!confirm(u.is_admin ? 'Remove admin role?' : 'Make admin?')) return;
    const r = await window.HDR_API.toggleAdmin(u.id);
    if (r.error) toast('Failed: ' + r.error, 'neg');
    else { toast('Updated', 'pos'); load(q); }
  };

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Users</h1>
          <p className="page-sub">Manage user accounts, wallet credits, status, and admin roles.</p>
        </div>
        <div className="actions">
          <input className="input" placeholder="Search email or name…" value={q} onChange={e => onSearch(e.target.value)} style={{maxWidth: 240}}/>
        </div>
      </div>

      <div className="card" style={{padding: 0}}>
        <table className="table">
          <thead>
            <tr><th>Email</th><th>Name</th><th style={{textAlign:'right'}}>Wallet</th><th style={{textAlign:'right'}}>Spent</th><th>Joined</th><th>Status</th><th style={{textAlign:'right'}}>Actions</th></tr>
          </thead>
          <tbody>
            {loading && <tr><td colSpan="7" className="muted" style={{textAlign:'center', padding: 20}}>Loading…</td></tr>}
            {!loading && users.length === 0 && <tr><td colSpan="7" className="muted" style={{textAlign:'center', padding: 20}}>No users</td></tr>}
            {users.map(u => (
              <tr key={u.id}>
                <td>{u.email} {!!u.is_admin && <span className="badge warn" style={{marginLeft: 6}}>Admin</span>}</td>
                <td className="muted">{u.name || '—'}</td>
                <td className="mono" style={{textAlign:'right'}}>{U.rupees(u.wallet_paise || 0)}</td>
                <td className="mono muted" style={{textAlign:'right'}}>{U.rupees(u.total_spent_paise || 0)}</td>
                <td className="muted" style={{fontSize: 12}}>{new Date(u.created_at).toLocaleDateString('en-IN', { day:'2-digit', month:'short', year:'numeric' })}</td>
                <td><span className={'badge ' + (u.is_active ? 'pos' : 'neg')}>{u.is_active ? 'Active' : 'Suspended'}</span></td>
                <td style={{textAlign:'right'}}>
                  <button className="icon-btn" title="Credit wallet" onClick={() => credit(u)}><I.plus/></button>
                  <button className="icon-btn" title="Toggle active" onClick={() => toggle(u)}><I.refresh/></button>
                  <button className="icon-btn" title="Toggle admin" onClick={() => toggleAdmin(u)}><I.shield/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ───────── Models (routing chains) ─────────
function AdminModels() {
  const { data: settings, reload } = useLoad(() => window.HDR_API.adminSettings(), []);
  const toast = useToast();

  if (!settings) return <div className="muted" style={{padding: 24}}>Loading…</div>;

  const types = [
    { key: 'chat_routes',  label: 'Chat',  type: 'chat',  data: settings.chat_routes },
    { key: 'image_routes', label: 'Image', type: 'image', data: settings.image_routes },
    { key: 'tts_routes',   label: 'TTS',   type: 'tts',   data: settings.tts_routes },
    { key: 'stt_routes',   label: 'STT',   type: 'stt',   data: settings.stt_routes },
  ];

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Models</h1>
          <p className="page-sub">Edit provider chains per alias. Saves instantly, no redeploy.</p>
        </div>
      </div>
      <div className="col" style={{gap: 16}}>
        {types.map(t => <ModelRoutesCard key={t.type} {...t} onSaved={reload}/>)}
      </div>
    </div>
  );
}

function ModelRoutesCard({ label, type, data, onSaved }) {
  const [json, setJson] = aSt(JSON.stringify(data || {}, null, 2));
  const toast = useToast();

  const save = async () => {
    try {
      const parsed = JSON.parse(json);
      const r = await window.HDR_API.saveRoutes(type, parsed);
      if (r.ok) { toast(`${label} routes saved`, 'pos'); onSaved && onSaved(); }
      else throw new Error(r.error);
    } catch (e) { toast('Invalid JSON: ' + e.message, 'neg'); }
  };

  return (
    <div className="card">
      <div className="card-head">
        <div>
          <div className="card-title">{label} routing</div>
          <div className="card-sub">{Object.keys(data || {}).length} aliases — edit JSON below</div>
        </div>
        <div className="spacer"/>
        <button className="btn primary sm" onClick={save}><I.check/> Save</button>
      </div>
      <textarea className="textarea mono" rows={8} value={json} onChange={e => setJson(e.target.value)} style={{fontSize: 12}}/>
    </div>
  );
}

// ───────── Skills ─────────
function AdminSkills() {
  const [open, setOpen] = aSt(false);
  const [editing, setEditing] = aSt(null);
  const { data: skills, reload } = useLoad(() => window.HDR_API.adminSkills(), []);
  const toast = useToast();

  const startCreate = () => { setEditing({ slug:'', name:'', description:'', system_prompt:'', category:'', is_active: true, is_global: true }); setOpen(true); };
  const startEdit = (s) => { setEditing({ ...s }); setOpen(true); };

  const save = async () => {
    if (!editing.name || !editing.description || !editing.system_prompt) {
      toast('Name, description and system prompt required', 'neg'); return;
    }
    try {
      if (editing.id) await window.HDR_API.updateSkill(editing.id, editing);
      else {
        const r = await window.HDR_API.createSkill(editing);
        if (r.error) throw new Error(r.error);
      }
      toast('Saved', 'pos'); setOpen(false); reload();
    } catch (e) { toast('Failed: ' + e.message, 'neg'); }
  };

  const removeSkill = async () => {
    if (!confirm('Delete this skill?')) return;
    await window.HDR_API.deleteSkill(editing.id);
    toast('Deleted', 'pos'); setOpen(false); reload();
  };

  // group by category
  const byCat = {};
  (skills || []).forEach(s => { (byCat[s.category || 'uncategorized'] ||= []).push(s); });

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Skills</h1>
          <p className="page-sub">Global skills library. Users attach to agents.</p>
        </div>
        <div className="actions">
          <button className="btn primary" onClick={startCreate}><I.plus/> New skill</button>
        </div>
      </div>

      {(!skills || skills.length === 0) ? (
        <div className="card" style={{padding: 60, textAlign:'center'}}>
          <I.star size={32}/>
          <div style={{fontWeight: 600, marginTop: 12}}>No skills yet</div>
          <div className="muted" style={{fontSize: 13, marginTop: 4}}>Create your first skill — focused expertise areas users can attach.</div>
          <button className="btn primary" style={{marginTop: 16}} onClick={startCreate}><I.plus/> Create your first skill</button>
        </div>
      ) : Object.entries(byCat).map(([cat, list]) => (
        <div key={cat} style={{marginBottom: 28}}>
          <div className="muted" style={{fontSize: 11, textTransform:'uppercase', letterSpacing:'.05em', fontWeight: 600, marginBottom: 10}}>{cat}</div>
          <div className="grid-3" style={{gap: 12}}>
            {list.map(s => (
              <div key={s.id} className="card" style={{cursor:'pointer'}} onClick={() => startEdit(s)}>
                <div className="row" style={{marginBottom: 6}}>
                  <div style={{fontWeight: 600}}>{s.name}</div>
                  <div className="spacer"/>
                  <span className={'badge ' + (s.is_active ? 'pos' : 'neg')}>{s.is_active ? 'Active' : 'Off'}</span>
                </div>
                <code className="mono muted" style={{fontSize: 11}}>{s.slug}</code>
                <p className="muted" style={{fontSize: 12, lineHeight: 1.4, marginTop: 8, marginBottom: 0}}>{s.description}</p>
              </div>
            ))}
          </div>
        </div>
      ))}

      <Modal open={open} onClose={() => setOpen(false)}
             title={editing?.id ? `Edit "${editing?.name}"` : 'Create skill'}
             size="wide"
             foot={<>
               {editing?.id && <button className="btn ghost" onClick={removeSkill}><I.trash/> Delete</button>}
               <div className="spacer"/>
               <button className="btn ghost" onClick={() => setOpen(false)}>Cancel</button>
               <button className="btn primary" onClick={save}><I.check/> Save skill</button>
             </>}>
        {editing && <SkillEditor value={editing} onChange={setEditing}/>}
      </Modal>
    </div>
  );
}

function SkillEditor({ value, onChange }) {
  const upd = (k, v) => onChange({ ...value, [k]: v });
  const [busyAi, setBusyAi] = aSt(false);
  const toast = useToast();

  const aiSuggest = async () => {
    if (!value.name) { toast('Enter skill name first', 'neg'); return; }
    setBusyAi(true);
    try {
      const r = await window.HDR_API.aiSuggestSkill(value.name);
      if (r.description) onChange({ ...value, description: value.description || r.description, system_prompt: value.system_prompt || r.system_prompt });
      toast('AI suggested', 'pos');
    } catch (e) { toast('AI suggest failed', 'neg'); }
    finally { setBusyAi(false); }
  };

  return (
    <div className="col" style={{gap: 14}}>
      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Slug</div>
          <input className="input mono" value={value.slug || ''} onChange={e => upd('slug', e.target.value.toLowerCase().replace(/[^a-z0-9-]/g,'-'))} placeholder="gst-advisor" disabled={!!value.id}/>
        </div>
        <div className="field" style={{flex:1}}>
          <div className="label row" style={{justifyContent: 'space-between'}}>
            <span>Name</span>
            <button className="btn ghost" style={{padding: '2px 8px', fontSize: 11}} onClick={aiSuggest} disabled={busyAi}>
              {busyAi ? '...' : <><I.spark/> AI suggest</>}
            </button>
          </div>
          <input className="input" value={value.name || ''} onChange={e => upd('name', e.target.value)} placeholder="GST Advisor"/>
        </div>
      </div>

      <div className="field">
        <div className="label">Description <span className="dim">(AI uses this for relevance routing)</span></div>
        <textarea className="textarea" rows={2} value={value.description || ''} onChange={e => upd('description', e.target.value)} placeholder="Indian GST law expertise. Use when user asks about GST, returns, or compliance."/>
      </div>

      <div className="field">
        <div className="label">System prompt</div>
        <textarea className="textarea" rows={6} value={value.system_prompt || ''} onChange={e => upd('system_prompt', e.target.value)} placeholder="You are a GST expert specializing in Indian tax law…"/>
      </div>

      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Category</div>
          <input className="input" value={value.category || ''} onChange={e => upd('category', e.target.value)} placeholder="finance"/>
        </div>
        <div className="field">
          <div className="label">Active</div>
          <Switch on={!!value.is_active} onChange={v => upd('is_active', v)}/>
        </div>
        <div className="field">
          <div className="label">Available to users</div>
          <Switch on={!!value.is_global} onChange={v => upd('is_global', v)}/>
        </div>
      </div>
    </div>
  );
}

// ───────── Tools ─────────
function AdminTools() {
  const [open, setOpen] = aSt(false);
  const [editing, setEditing] = aSt(null);
  const { data: tools, reload } = useLoad(() => window.HDR_API.adminTools(), []);
  const toast = useToast();

  const startCreate = () => {
    setEditing({
      slug: '', name: '', description: '', category: '',
      method: 'GET', url_template: '',
      headers_json: null, body_template: '', timeout_ms: 15000,
      params_schema: [{ name: 'query', type: 'string', description: 'Search query', required: true }],
      response_path: '',
      is_active: true, is_global: true,
    });
    setOpen(true);
  };
  const startEdit = (t) => setEditing({ ...t }) || setOpen(true);

  const save = async () => {
    if (!editing.slug || !editing.name || !editing.description || !editing.url_template) {
      toast('Slug, name, description, URL required', 'neg'); return;
    }
    try {
      if (editing.id) await window.HDR_API.updateTool(editing.id, editing);
      else { const r = await window.HDR_API.createTool(editing); if (r.error) throw new Error(r.error); }
      toast('Saved', 'pos'); setOpen(false); reload();
    } catch (e) { toast('Failed: ' + e.message, 'neg'); }
  };

  const removeTool = async () => {
    if (!confirm('Delete this tool?')) return;
    await window.HDR_API.deleteTool(editing.id);
    toast('Deleted', 'pos'); setOpen(false); reload();
  };

  const testTool = async () => {
    const params = {};
    for (const p of editing.params_schema || []) {
      const v = prompt(`${p.name} (${p.description})${p.required ? ' *' : ''}:`);
      if (v !== null) params[p.name] = v;
    }
    const r = await window.HDR_API.testTool(editing.id, params);
    if (r.ok) alert('✓ Success\n\n' + JSON.stringify(r.data, null, 2).slice(0, 800));
    else alert('✗ Failed: ' + (r.error || 'unknown'));
  };

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Tools</h1>
          <p className="page-sub">HTTP endpoints AI can call as functions. Define URL templates + auth headers.</p>
        </div>
        <div className="actions">
          <button className="btn primary" onClick={startCreate}><I.plus/> New tool</button>
        </div>
      </div>

      {(!tools || tools.length === 0) ? (
        <div className="card" style={{padding: 60, textAlign:'center'}}>
          <I.wrench size={32}/>
          <div style={{fontWeight: 600, marginTop: 12}}>No tools yet</div>
          <div className="muted" style={{fontSize: 13, marginTop: 4}}>Define HTTP endpoints AI can call to fetch live data.</div>
          <button className="btn primary" style={{marginTop: 16}} onClick={startCreate}><I.plus/> Create your first tool</button>
        </div>
      ) : (
        <div className="grid-3" style={{gap: 12}}>
          {tools.map(t => (
            <div key={t.id} className="card" style={{cursor:'pointer'}} onClick={() => startEdit(t)}>
              <div className="row" style={{marginBottom: 6}}>
                <div style={{fontWeight: 600}}>{t.name}</div>
                <div className="spacer"/>
                <span className={'badge ' + (t.is_active ? 'pos' : 'neg')}>{t.is_active ? 'Active' : 'Off'}</span>
              </div>
              <code className="mono muted" style={{fontSize: 11}}>{t.slug}</code>
              <div className="row" style={{marginTop: 8, gap: 8}}>
                <span className="badge">{t.method}</span>
                {t.category && <span className="muted" style={{fontSize: 11}}>{t.category}</span>}
              </div>
              <p className="muted" style={{fontSize: 12, lineHeight: 1.4, marginTop: 10, marginBottom: 0}}>{t.description}</p>
            </div>
          ))}
        </div>
      )}

      <Modal open={open} onClose={() => setOpen(false)}
             title={editing?.id ? `Edit "${editing?.name}"` : 'Create tool'}
             size="wide"
             foot={<>
               {editing?.id && <button className="btn ghost" onClick={removeTool}><I.trash/> Delete</button>}
               {editing?.id && <button className="btn ghost" onClick={testTool}><I.refresh/> Test</button>}
               <div className="spacer"/>
               <button className="btn ghost" onClick={() => setOpen(false)}>Cancel</button>
               <button className="btn primary" onClick={save}><I.check/> Save</button>
             </>}>
        {editing && <ToolEditor value={editing} onChange={setEditing}/>}
      </Modal>
    </div>
  );
}

function ToolEditor({ value, onChange }) {
  const upd = (k, v) => onChange({ ...value, [k]: v });
  const updJsonField = (k, str) => {
    try { onChange({ ...value, [k]: JSON.parse(str) }); }
    catch { onChange({ ...value, [k]: str }); }
  };

  return (
    <div className="col" style={{gap: 14}}>
      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Slug</div>
          <input className="input mono" value={value.slug || ''} onChange={e => upd('slug', e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g,'_'))} disabled={!!value.id}/>
        </div>
        <div className="field" style={{flex:1}}>
          <div className="label">Name</div>
          <input className="input" value={value.name || ''} onChange={e => upd('name', e.target.value)}/>
        </div>
      </div>

      <div className="field">
        <div className="label">Description <span className="dim">(AI uses this to decide WHEN to call)</span></div>
        <textarea className="textarea" rows={2} value={value.description || ''} onChange={e => upd('description', e.target.value)}/>
      </div>

      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Category</div>
          <input className="input" value={value.category || ''} onChange={e => upd('category', e.target.value)}/>
        </div>
        <div className="field">
          <div className="label">Method</div>
          <select className="select" value={value.method || 'GET'} onChange={e => upd('method', e.target.value)}>
            {['GET','POST','PUT','DELETE'].map(m => <option key={m}>{m}</option>)}
          </select>
        </div>
        <div className="field">
          <div className="label">Timeout (ms)</div>
          <input className="input" type="number" value={value.timeout_ms || 15000} onChange={e => upd('timeout_ms', parseInt(e.target.value, 10))}/>
        </div>
      </div>

      <div className="field">
        <div className="label">URL template <span className="dim">{`(use {{param}} placeholders)`}</span></div>
        <input className="input mono" value={value.url_template || ''} onChange={e => upd('url_template', e.target.value)} placeholder="https://api.example.com/lookup/{{query}}"/>
      </div>

      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Headers (JSON, optional)</div>
          <textarea className="textarea mono" rows={3} value={typeof value.headers_json === 'string' ? value.headers_json : JSON.stringify(value.headers_json || {}, null, 2)} onChange={e => updJsonField('headers_json', e.target.value)} style={{fontSize: 11.5}}/>
        </div>
        <div className="field" style={{flex:1}}>
          <div className="label">Body template (for POST/PUT)</div>
          <textarea className="textarea mono" rows={3} value={value.body_template || ''} onChange={e => upd('body_template', e.target.value)} style={{fontSize: 11.5}} placeholder='{"query": "{{query}}"}'/>
        </div>
      </div>

      <div className="field">
        <div className="label">Params schema (JSON array)</div>
        <textarea className="textarea mono" rows={5} value={typeof value.params_schema === 'string' ? value.params_schema : JSON.stringify(value.params_schema || [], null, 2)} onChange={e => updJsonField('params_schema', e.target.value)} style={{fontSize: 11.5}}/>
      </div>

      <div className="row" style={{gap: 12}}>
        <div className="field" style={{flex:1}}>
          <div className="label">Response path (optional)</div>
          <input className="input mono" value={value.response_path || ''} onChange={e => upd('response_path', e.target.value)} placeholder="data.result"/>
        </div>
        <div className="field">
          <div className="label">Active</div>
          <Switch on={!!value.is_active} onChange={v => upd('is_active', v)}/>
        </div>
        <div className="field">
          <div className="label">Global</div>
          <Switch on={!!value.is_global} onChange={v => upd('is_global', v)}/>
        </div>
      </div>
    </div>
  );
}

// ───────── Settings ─────────
function AdminSettings() {
  const { data: settings, reload } = useLoad(() => window.HDR_API.adminSettings(), []);
  const { data: rzp, reload: reloadRzp } = useLoad(() => window.HDR_API.adminRazorpay(), []);

  if (!settings || !rzp) return <div className="muted" style={{padding: 20}}>Loading…</div>;

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Settings</h1>
          <p className="page-sub">Pricing, payments, and platform configuration.</p>
        </div>
      </div>
      <div className="grid-23" style={{gap: 16}}>
        <PricingCard settings={settings} onSaved={reload}/>
        <div className="col" style={{gap: 16}}>
          <RazorpayCard rzp={rzp} onSaved={reloadRzp}/>
          <ProvidersCard settings={settings}/>
        </div>
      </div>
    </div>
  );
}

function PricingCard({ settings, onSaved }) {
  const [v, setV] = aSt({
    pricing_markup: settings.pricing_markup,
    usd_to_paise: settings.usd_to_paise,
    signup_bonus_paise: settings.signup_bonus_paise,
    min_balance_paise: settings.min_balance_paise,
    live_model: settings.live_model || 'gemini-2.5-flash-native-audio-latest',
    live_token_multiplier: settings.live_token_multiplier ?? 2.0,
  });
  const toast = useToast();

  const save = async () => {
    try {
      const r = await window.HDR_API.saveSettings(v);
      if (r.ok) { toast('Pricing saved', 'pos'); onSaved && onSaved(); }
      else throw new Error(r.error);
    } catch (e) { toast('Failed: ' + e.message, 'neg'); }
  };

  return (
    <div className="card">
      <div className="card-head"><div className="card-title">Pricing</div></div>
      <div className="col" style={{gap: 14}}>
        <div className="field">
          <div className="label">Pricing markup <span className="dim">(e.g. 1.30 = 30% margin)</span></div>
          <input className="input" type="number" step="0.01" value={v.pricing_markup} onChange={e => setV({...v, pricing_markup: parseFloat(e.target.value)})}/>
        </div>
        <div className="field">
          <div className="label">USD to paise <span className="dim">(8400 = ₹84/USD)</span></div>
          <input className="input" type="number" value={v.usd_to_paise} onChange={e => setV({...v, usd_to_paise: parseInt(e.target.value, 10)})}/>
        </div>
        <div className="field">
          <div className="label">Signup bonus (paise) <span className="dim">(5000 = ₹50)</span></div>
          <input className="input" type="number" value={v.signup_bonus_paise} onChange={e => setV({...v, signup_bonus_paise: parseInt(e.target.value, 10)})}/>
        </div>
        <div className="field">
          <div className="label">Min balance (paise)</div>
          <input className="input" type="number" value={v.min_balance_paise} onChange={e => setV({...v, min_balance_paise: parseInt(e.target.value, 10)})}/>
        </div>
        <div className="divider" style={{margin: '4px 0'}}/>
        <div className="field">
          <div className="label">Live Call model <span className="dim">(Gemini Live model ID — /v1/live only)</span></div>
          <input className="input mono" type="text" value={v.live_model || ''} onChange={e => setV({...v, live_model: e.target.value})} placeholder="gemini-2.5-flash-native-audio-latest"/>
        </div>
        <div className="field">
          <div className="label">Live token multiplier <span className="dim">(2.0 = bill 2× Gemini's reported tokens)</span></div>
          <input className="input" type="number" step="0.1" min="1" value={v.live_token_multiplier} onChange={e => setV({...v, live_token_multiplier: parseFloat(e.target.value)})}/>
        </div>
        <button className="btn primary" style={{marginTop: 4}} onClick={save}><I.check/> Save pricing</button>
      </div>
    </div>
  );
}

function RazorpayCard({ rzp, onSaved }) {
  const [keyId, setKeyId]     = aSt(rzp.key_id || '');
  const [secret, setSecret]   = aSt('');
  const [webhook, setWebhook] = aSt('');
  const toast = useToast();

  const save = async () => {
    const body = { key_id: keyId };
    if (secret) body.key_secret = secret;
    if (webhook) body.webhook_secret = webhook;
    try {
      const r = await window.HDR_API.saveRazorpay(body);
      if (r.ok) { toast('Razorpay saved', 'pos'); onSaved && onSaved(); setSecret(''); setWebhook(''); }
      else throw new Error(r.error);
    } catch (e) { toast('Failed: ' + e.message, 'neg'); }
  };

  const test = async () => {
    const r = await window.HDR_API.testRazorpay();
    if (r.ok) toast(r.message || 'Razorpay valid', 'pos');
    else toast('Test failed: ' + (r.error || ''), 'neg');
  };

  return (
    <div className="card">
      <div className="card-head">
        <div className="card-title">Razorpay Payments</div>
        <div className="spacer"/>
        <span className={'badge ' + (rzp.configured ? (rzp.mode === 'live' ? 'pos' : 'warn') : 'neg')}>
          {rzp.configured ? rzp.mode?.toUpperCase() : 'Not configured'}
        </span>
      </div>
      <div className="col" style={{gap: 14}}>
        <div className="field">
          <div className="label">Key ID</div>
          <input className="input mono" value={keyId} onChange={e => setKeyId(e.target.value)} placeholder="rzp_test_xxx or rzp_live_xxx"/>
        </div>
        <div className="field">
          <div className="label">Key Secret {rzp.has_secret && <span className="badge pos">set</span>}</div>
          <input className="input mono" type="password" value={secret} onChange={e => setSecret(e.target.value)} placeholder={rzp.has_secret ? '•••••••• (leave empty to keep)' : 'Enter secret'}/>
        </div>
        <div className="field">
          <div className="label">Webhook Secret {rzp.has_webhook_secret && <span className="badge pos">set</span>}</div>
          <input className="input mono" type="password" value={webhook} onChange={e => setWebhook(e.target.value)} placeholder="For payment events (optional)"/>
          <div className="dim" style={{fontSize: 11, marginTop: 6}}>Configure in Razorpay dashboard:</div>
          <code className="mono" style={{fontSize: 11, display: 'block', marginTop: 4, padding: 6, background:'var(--surface-2)', borderRadius:'var(--r-xs)', wordBreak:'break-all'}}>{rzp.webhook_url}</code>
        </div>
        <div className="row" style={{gap: 8}}>
          <button className="btn primary" onClick={save}><I.check/> Save</button>
          <button className="btn ghost" onClick={test}><I.refresh/> Test</button>
        </div>
      </div>
    </div>
  );
}

function ProvidersCard({ settings }) {
  return (
    <div className="card">
      <div className="card-head"><div className="card-title">Provider keys</div></div>
      <div className="col" style={{gap: 8}}>
        {Object.entries(settings.providers || {}).map(([name, ok]) => (
          <div key={name} className="row" style={{padding: '6px 0', fontSize: 13}}>
            <span className="tag-dot" style={{ background: C.providers[name]?.color }}/>
            <span style={{textTransform:'capitalize'}}>{name}</span>
            <div className="spacer"/>
            <span className={'badge ' + (ok ? 'pos' : 'neg')}>{ok ? 'configured' : 'missing'}</span>
          </div>
        ))}
      </div>
      <div className="dim" style={{fontSize: 11.5, marginTop: 10, lineHeight: 1.5}}>
        Provider API keys are loaded from .env file. Update them in Hostinger Environment Variables and restart.
      </div>
    </div>
  );
}
