// React is available globally from UMD build
const useState = React.useState;
const useEffect = React.useEffect;
const useCallback = React.useCallback;

// API client (API, KEY, DEBUG, get, post) loaded from /dashboard-api.js

function StatusBadge({ ok, label }) {
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${ok ? "bg-emerald-100 text-emerald-800" : "bg-red-100 text-red-800"}`}>
      {label}
    </span>
  );
}

function CostBar({ used, limit, label }) {
  const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
  const color = pct > 90 ? "bg-red-500" : pct > 70 ? "bg-amber-500" : "bg-emerald-500";
  return (
    <div className="mb-2">
      <div className="flex justify-between text-xs mb-1">
        <span className="text-gray-600">{label}</span>
        <span className="font-mono">${used.toFixed(2)} / ${limit.toFixed(2)}</span>
      </div>
      <div className="w-full bg-gray-200 rounded-full h-2">
        <div className={`${color} h-2 rounded-full transition-all`} style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

function Card({ title, children, className = "" }) {
  return (
    <div className={`bg-white rounded-xl shadow-sm border border-gray-200 p-5 ${className}`}>
      {title && <h3 className="text-sm font-semibold text-gray-900 mb-3">{title}</h3>}
      {children}
    </div>
  );
}

function ModelsTable({ models }) {
  if (!models?.length) return <p className="text-gray-500 text-sm">No models available</p>;
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-xs">
        <thead>
          <tr className="border-b border-gray-200 text-left text-gray-500">
            <th className="pb-2 font-medium">Model</th>
            <th className="pb-2 font-medium">Provider</th>
            <th className="pb-2 font-medium text-right">Input $/1M</th>
            <th className="pb-2 font-medium text-right">Output $/1M</th>
            <th className="pb-2 font-medium">Tier Range</th>
            <th className="pb-2 font-medium">Capabilities</th>
          </tr>
        </thead>
        <tbody>
          {models.map(m => (
            <tr key={m.id} className="border-b border-gray-100 hover:bg-gray-50">
              <td className="py-2 font-mono text-gray-900">{m.id}</td>
              <td className="py-2"><span className="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs">{m.owned_by}</span></td>
              <td className="py-2 text-right font-mono">{m.input_cost_per_1m === 0 ? <span className="text-emerald-600">FREE</span> : `$${m.input_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-right font-mono">{m.output_cost_per_1m === 0 ? <span className="text-emerald-600">FREE</span> : `$${m.output_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-gray-600">{m.tier_range}</td>
              <td className="py-2">
                <div className="flex flex-wrap gap-1">
                  {m.capabilities?.map(c => (
                    <span key={c} className="px-1 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">{c}</span>
                  ))}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ── Account sub-components ───────────────────────────────────

const PROVIDERS = ["anthropic","openai","openrouter","google","deepseek","groq","mistral","windsurf","cursor","github_copilot"];
const EMPTY_FORM = { name: "", provider: "anthropic", api_key: "", email: "", daily_budget_usd: 5, monthly_budget_usd: 60 };

function AccountRow({ account }) {
  const a = account;
  return (
    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
      <div>
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm">{a.name}</span>
          <span className="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs">{a.provider}</span>
          <span className="px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded text-xs">{a.plan || "free"}</span>
          <StatusBadge ok={a.active} label={a.active ? "active" : "inactive"} />
          {a.over_budget && <StatusBadge ok={false} label="over budget" />}
        </div>
        <div className="text-xs text-gray-500 mt-1">
          Today: ${a.usage?.daily_cost?.toFixed(4)} · Total: ${a.usage?.total_cost?.toFixed(4)} · {a.usage?.total_requests} reqs
        </div>
      </div>
      <div className="text-xs text-gray-400">{a.tools?.length || 0} tools</div>
    </div>
  );
}

function NewAccountForm({ onSubmit, onCancel }) {
  const [form, setForm] = useState({ ...EMPTY_FORM });

  const handleSubmit = async () => {
    await onSubmit(form);
    setForm({ ...EMPTY_FORM });
  };

  return (
    <div className="mt-4 p-4 bg-blue-50 rounded-lg space-y-2">
      <div className="grid grid-cols-2 gap-2">
        <input className="px-2 py-1.5 border rounded text-sm" placeholder="Account name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
        <select className="px-2 py-1.5 border rounded text-sm" value={form.provider} onChange={e => setForm({...form, provider: e.target.value})}>
          {PROVIDERS.map(p => <option key={p} value={p}>{p}</option>)}
        </select>
        <input className="px-2 py-1.5 border rounded text-sm col-span-2" placeholder="API Key" type="password" value={form.api_key} onChange={e => setForm({...form, api_key: e.target.value})} />
        <input className="px-2 py-1.5 border rounded text-sm" placeholder="Daily budget $" type="number" value={form.daily_budget_usd} onChange={e => setForm({...form, daily_budget_usd: +e.target.value})} />
        <input className="px-2 py-1.5 border rounded text-sm" placeholder="Monthly budget $" type="number" value={form.monthly_budget_usd} onChange={e => setForm({...form, monthly_budget_usd: +e.target.value})} />
      </div>
      <div className="flex gap-2">
        <button onClick={handleSubmit} className="px-3 py-1.5 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">Create</button>
        <button onClick={onCancel} className="px-3 py-1.5 bg-gray-200 text-gray-700 rounded text-sm">Cancel</button>
      </div>
    </div>
  );
}

function AccountsPanel({ accounts, onRefresh }) {
  const [showForm, setShowForm] = useState(false);

  const handleCreate = async (formData) => {
    await post("/dashboard/accounts", formData);
    setShowForm(false);
    onRefresh();
  };

  return (
    <Card title="Accounts">
      <div className="space-y-3">
        {accounts?.map(a => <AccountRow key={a.id} account={a} />)}
        {(!accounts || accounts.length === 0) && <p className="text-gray-400 text-sm">No accounts configured</p>}
      </div>
      {showForm
        ? <NewAccountForm onSubmit={handleCreate} onCancel={() => setShowForm(false)} />
        : <button onClick={() => setShowForm(true)} className="mt-3 px-3 py-1.5 border border-dashed border-gray-300 rounded text-sm text-gray-500 hover:border-blue-400 hover:text-blue-600 w-full">+ Add Account</button>
      }
    </Card>
  );
}

// ── VM sub-components ────────────────────────────────────────

const VM_ACTIONS = {
  stopped: [{ action: "start", label: "Start", cls: "bg-emerald-100 text-emerald-700 hover:bg-emerald-200" }],
  running: [
    { action: "stop", label: "Stop", cls: "bg-red-100 text-red-700 hover:bg-red-200" },
    { action: "pause", label: "Pause", cls: "bg-amber-100 text-amber-700 hover:bg-amber-200" },
  ],
  paused: [{ action: "resume", label: "Resume", cls: "bg-blue-100 text-blue-700 hover:bg-blue-200" }],
};

function VMCard({ vm, onAction }) {
  const actions = VM_ACTIONS[vm.state] || [];
  return (
    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
      <div>
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm">{vm.name}</span>
          <StatusBadge ok={vm.state === "running"} label={vm.state} />
          {vm.tool && <span className="px-1.5 py-0.5 bg-purple-50 text-purple-700 rounded text-xs">{vm.tool}</span>}
        </div>
        <div className="text-xs text-gray-500 mt-1">
          {vm.ip || "no IP"} · {vm.code_mount || "no mount"}
          {vm.uptime > 0 && ` · up ${Math.round(vm.uptime / 60)}m`}
        </div>
      </div>
      <div className="flex gap-1">
        {actions.map(a => (
          <button key={a.action} onClick={() => onAction(vm.id, a.action)} className={`px-2 py-1 rounded text-xs ${a.cls}`}>{a.label}</button>
        ))}
      </div>
    </div>
  );
}

function VMsPanel({ vms, onRefresh }) {
  const handleAction = async (vmId, action) => {
    await post(`/dashboard/vms/${vmId}/${action}`, {});
    onRefresh();
  };

  return (
    <Card title="Virtual Machines">
      <div className="space-y-2">
        {vms?.map(vm => <VMCard key={vm.id} vm={vm} onAction={handleAction} />)}
        {(!vms || vms.length === 0) && <p className="text-gray-400 text-sm">No VMs configured. Use CLI or API to create.</p>}
      </div>
    </Card>
  );
}

// ── Layout components ────────────────────────────────────────

const TABS = [
  { id: "overview", label: "Overview" },
  { id: "accounts", label: "Accounts" },
  { id: "models", label: "Models" },
  { id: "vms", label: "VMs" },
];

function DashboardHeader({ connected, lastRefresh, health, onRefresh }) {
  return (
    <header className="bg-white border-b border-gray-200 px-6 py-3">
      <div className="flex items-center justify-between max-w-7xl mx-auto">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-gradient-to-br from-blue-600 to-indigo-700 rounded-lg flex items-center justify-center">
            <span className="text-white text-xs font-bold">AI</span>
          </div>
          <div>
            <h1 className="text-lg font-semibold text-gray-900">AI Proxy Dashboard</h1>
            <p className="text-xs text-gray-500">Multi-provider LLM Gateway</p>
          </div>
        </div>
        <div className="flex items-center gap-4">
          <StatusBadge ok={connected} label={connected ? "Connected" : "Disconnected"} />
          <span className="text-xs text-gray-400">{lastRefresh?.toLocaleTimeString()}</span>
          <button onClick={onRefresh} className="px-2 py-1 bg-gray-100 rounded text-xs hover:bg-gray-200">Refresh</button>
        </div>
      </div>
    </header>
  );
}

function TabNav({ tab, onTabChange }) {
  return (
    <nav className="bg-white border-b border-gray-200 px-6">
      <div className="flex gap-1 max-w-7xl mx-auto">
        {TABS.map(t => (
          <button key={t.id} onClick={() => onTabChange(t.id)}
            className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
              tab === t.id
                ? "border-blue-600 text-blue-600"
                : "border-transparent text-gray-500 hover:text-gray-700"
            }`}>{t.label}</button>
        ))}
      </div>
    </nav>
  );
}

function CostSummary({ costs }) {
  if (!costs) return null;
  return (
    <Card title="Cost Summary">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
        <div>
          <div className="text-2xl font-mono font-bold text-gray-900">${costs.daily_total_usd?.toFixed(2)}</div>
          <div className="text-xs text-gray-500">Today</div>
        </div>
        <div>
          <div className="text-2xl font-mono font-bold text-gray-900">${costs.monthly_total_usd?.toFixed(2)}</div>
          <div className="text-xs text-gray-500">This month</div>
        </div>
        <div>
          <div className="text-2xl font-mono font-bold text-gray-900">{costs.total_requests}</div>
          <div className="text-xs text-gray-500">Total requests</div>
        </div>
        <div>
          <div className="text-2xl font-mono font-bold text-gray-900">{costs.accounts_active}/{costs.accounts_count}</div>
          <div className="text-xs text-gray-500">Active accounts</div>
        </div>
      </div>
      {costs.by_provider && Object.keys(costs.by_provider).length > 0 && (
        <div className="mt-4 pt-4 border-t border-gray-100">
          <h4 className="text-xs font-medium text-gray-500 mb-2">Cost by Provider</h4>
          <div className="flex flex-wrap gap-2">
            {Object.entries(costs.by_provider).map(([p, c]) => (
              <span key={p} className="px-2 py-1 bg-gray-100 rounded text-xs">
                <span className="font-medium">{p}</span>: ${c.toFixed(4)}
              </span>
            ))}
          </div>
        </div>
      )}
    </Card>
  );
}

function OverviewTab({ budget, connected, health, models, accounts, context, costs, refresh }) {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card title="Today's Budget">
          <CostBar
            used={budget ? budget.daily_limit_usd - budget.daily_remaining_usd : 0}
            limit={budget?.daily_limit_usd || 5}
            label="Daily spend"
          />
        </Card>
        <Card title="Monthly Budget">
          <CostBar
            used={budget ? budget.monthly_limit_usd - budget.monthly_remaining_usd : 0}
            limit={budget?.monthly_limit_usd || 60}
            label="Monthly spend"
          />
        </Card>
        <Card title="System">
          <div className="space-y-1 text-xs">
            <div className="flex justify-between"><span className="text-gray-500">Proxy</span><StatusBadge ok={connected} label={health?.version || "?"} /></div>
            <div className="flex justify-between"><span className="text-gray-500">Models</span><span className="font-mono">{models.length}</span></div>
            <div className="flex justify-between"><span className="text-gray-500">Accounts</span><span className="font-mono">{accounts.length}</span></div>
            <div className="flex justify-between"><span className="text-gray-500">Context buffer</span><span className="font-mono">{context?.files_tracked || 0} files, v{context?.version || 0}</span></div>
          </div>
        </Card>
      </div>
      <CostSummary costs={costs} />
      <AccountsPanel accounts={accounts} onRefresh={refresh} />
    </div>
  );
}

// ── Main Dashboard ───────────────────────────────────────────

function Dashboard() {
  const data = useDashboardData();

  return (
    <div className="min-h-screen bg-gray-50">
      <DashboardHeader connected={data.connected} lastRefresh={data.lastRefresh} health={data.health} onRefresh={data.refresh} />
      <TabNav tab={data.tab} onTabChange={data.setTab} />
      <main className="max-w-7xl mx-auto px-6 py-6">
        {data.tab === "overview" && <OverviewTab {...data} />}
        {data.tab === "accounts" && <AccountsPanel accounts={data.accounts} onRefresh={data.refresh} />}
        {data.tab === "models" && <Card title={`Available Models (${data.models.length})`}><ModelsTable models={data.models} /></Card>}
        {data.tab === "vms" && <VMsPanel vms={data.vms} onRefresh={data.refresh} />}
      </main>
    </div>
  );
}

// Render the app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Dashboard />);
