// 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 || !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 ? <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 ? <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>
  );
}

function formatDate(timestamp) {
  if (!timestamp || timestamp === 0) return "never";
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);
  
  if (diffMins < 1) return "just now";
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  if (diffDays < 7) return `${diffDays}d ago`;
  return date.toLocaleDateString();
}

function formatDuration(seconds) {
  if (!seconds || seconds <= 0) return "";
  const mins = Math.floor(seconds / 60);
  const hours = Math.floor(mins / 60);
  const days = Math.floor(hours / 24);
  if (days > 0) return `${days}d ${hours % 24}h`;
  if (hours > 0) return `${hours}h ${mins % 60}m`;
  return `${mins}m`;
}

function formatSize(mb) {
  if (!mb || mb === 0) return "-";
  if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;
  return `${mb} MB`;
}

const VM_ACTIONS = {
  stopped: [
    { action: "start", label: "Start", cls: "bg-emerald-100 text-emerald-700 hover:bg-emerald-200" },
    { action: "delete", label: "Delete", cls: "bg-gray-100 text-gray-700 hover:bg-gray-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" },
    { action: "delete", label: "Delete", cls: "bg-gray-100 text-gray-700 hover:bg-gray-200" },
  ],
  paused: [
    { action: "resume", label: "Resume", cls: "bg-blue-100 text-blue-700 hover:bg-blue-200" },
    { action: "delete", label: "Delete", cls: "bg-gray-100 text-gray-700 hover:bg-gray-200" },
  ],
};

const STATE_COLORS = {
  running: { bg: "bg-emerald-100", text: "text-emerald-700", dot: "bg-emerald-500" },
  stopped: { bg: "bg-gray-100", text: "text-gray-600", dot: "bg-gray-400" },
  paused: { bg: "bg-amber-100", text: "text-amber-700", dot: "bg-amber-500" },
  error: { bg: "bg-red-100", text: "text-red-700", dot: "bg-red-500" },
};

function StateBadge({ state }) {
  const colors = STATE_COLORS[state] || STATE_COLORS.error;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium ${colors.bg} ${colors.text}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${colors.dot} ${state === "running" ? "animate-pulse" : ""}`} />
      {state}
    </span>
  );
}

function VMCard({ vm, selected, onSelect, onAction }) {
  const actions = VM_ACTIONS[vm.state] || [];
  return (
    <div className="flex items-start justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
      <div className="flex items-start gap-3">
        <input
          type="checkbox"
          checked={selected}
          onChange={() => onSelect(vm.id)}
          className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 mt-1"
        />
        <div>
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-medium text-sm">{vm.name}</span>
            <StateBadge state={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.5 space-y-0.5">
            <div className="flex items-center gap-3">
              <span className="font-mono">{vm.vcpus || 0} vCPU</span>
              <span>·</span>
              <span className="font-mono">{formatSize(vm.memory_mb)}</span>
              {vm.disk_gb > 0 && (
                <><span>·</span><span className="font-mono">{vm.disk_gb} GB disk</span></>
              )}
            </div>
            <div className="flex items-center gap-3">
              {vm.ip ? (
                <span className="font-mono text-blue-600">{vm.ip}</span>
              ) : (
                <span className="text-gray-400">no IP</span>
              )}
              <span>·</span>
              <span>{vm.code_mount || "no mount"}</span>
            </div>
            <div className="flex items-center gap-3">
              {vm.state === "running" && vm.uptime > 0 && (
                <><span className="text-emerald-600">⏱ up {formatDuration(vm.uptime)}</span><span>·</span></>
              )}
              <span>started: {formatDate(vm.last_started_at)}</span>
              <span>·</span>
              <span>created: {formatDate(vm.created_at)}</span>
            </div>
          </div>
        </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 [selected, setSelected] = useState(new Set());
  const [sortBy, setSortBy] = useState("state"); // state, name, created, last_started, size
  const [sortDesc, setSortDesc] = useState(false);

  // Sort VMs based on selected criteria
  const sortedVms = React.useMemo(() => {
    if (!vms) return [];
    const sorted = [...vms];
    sorted.sort((a, b) => {
      let comparison = 0;
      switch (sortBy) {
        case "state":
          // Order: running > paused > stopped > other
          const stateOrder = { running: 0, paused: 1, stopped: 2 };
          const aOrder = stateOrder[a.state] ?? 3;
          const bOrder = stateOrder[b.state] ?? 3;
          comparison = aOrder - bOrder;
          break;
        case "name":
          comparison = a.name.localeCompare(b.name);
          break;
        case "created":
          comparison = (a.created_at || 0) - (b.created_at || 0);
          break;
        case "last_started":
          comparison = (a.last_started_at || 0) - (b.last_started_at || 0);
          break;
        case "size":
          const aSize = (a.memory_mb || 0) * (a.vcpus || 1);
          const bSize = (b.memory_mb || 0) * (b.vcpus || 1);
          comparison = aSize - bSize;
          break;
        default:
          comparison = 0;
      }
      return sortDesc ? -comparison : comparison;
    });
    return sorted;
  }, [vms, sortBy, sortDesc]);

  const handleSelect = (vmId) => {
    const newSelected = new Set(selected);
    if (newSelected.has(vmId)) {
      newSelected.delete(vmId);
    } else {
      newSelected.add(vmId);
    }
    setSelected(newSelected);
  };

  const handleSelectAll = () => {
    if (selected.size === vms?.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(vms?.map(vm => vm.id) || []));
    }
  };

  const handleBulkAction = async (action) => {
    const vmIds = Array.from(selected);
    if (action === "delete") {
      if (!confirm(`Delete ${vmIds.length} selected VM${vmIds.length > 1 ? 's' : ''}?`)) return;
      await post("/dashboard/vms/bulk-delete", vmIds);
    } else if (action === "start") {
      for (const vmId of vmIds) {
        await post(`/dashboard/vms/${vmId}/start`, {});
      }
    } else if (action === "stop") {
      for (const vmId of vmIds) {
        await post(`/dashboard/vms/${vmId}/stop`, {});
      }
    }
    setSelected(new Set());
    onRefresh();
  };

  const handleAction = async (vmId, action) => {
    if (action === "delete") {
      if (!confirm("Delete VM?")) return;
      await post(`/dashboard/vms/${vmId}/delete`, {});
    } else {
      await post(`/dashboard/vms/${vmId}/${action}`, {});
    }
    onRefresh();
  };

  const hasSelected = selected.size > 0;
  const allSelected = vms?.length > 0 && selected.size === vms.length;

  // Count VMs by state
  const runningCount = vms?.filter(v => v.state === "running").length || 0;
  const stoppedCount = vms?.filter(v => v.state === "stopped").length || 0;
  const pausedCount = vms?.filter(v => v.state === "paused").length || 0;

  return (
    <Card title={`Virtual Machines (${vms?.length || 0})`}>
      <div className="space-y-3">
        {/* Stats bar */}
        <div className="flex items-center gap-4 text-xs">
          <span className="flex items-center gap-1">
            <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
            {runningCount} running
          </span>
          <span className="flex items-center gap-1">
            <span className="w-2 h-2 rounded-full bg-amber-500" />
            {pausedCount} paused
          </span>
          <span className="flex items-center gap-1">
            <span className="w-2 h-2 rounded-full bg-gray-400" />
            {stoppedCount} stopped
          </span>
        </div>

        {/* Controls row */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              checked={allSelected}
              onChange={handleSelectAll}
              className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <span className="text-sm text-gray-600">
              {selected.size > 0 ? `${selected.size} selected` : "Select all"}
            </span>
          </div>
          
          <div className="flex items-center gap-2">
            {/* Sort controls */}
            <span className="text-xs text-gray-500">Sort by:</span>
            <select 
              value={sortBy} 
              onChange={(e) => setSortBy(e.target.value)}
              className="text-xs border rounded px-2 py-1 bg-white"
            >
              <option value="state">State</option>
              <option value="name">Name</option>
              <option value="created">Created</option>
              <option value="last_started">Last Started</option>
              <option value="size">Size</option>
            </select>
            <button 
              onClick={() => setSortDesc(!sortDesc)}
              className="text-xs px-2 py-1 border rounded hover:bg-gray-50"
              title={sortDesc ? "Descending" : "Ascending"}
            >
              {sortDesc ? "↓" : "↑"}
            </button>

            {hasSelected && (
              <div className="flex gap-2 ml-4">
                <button
                  onClick={() => handleBulkAction("start")}
                  className="px-3 py-1.5 bg-emerald-100 text-emerald-700 rounded text-sm hover:bg-emerald-200"
                >
                  Start
                </button>
                <button
                  onClick={() => handleBulkAction("stop")}
                  className="px-3 py-1.5 bg-red-100 text-red-700 rounded text-sm hover:bg-red-200"
                >
                  Stop
                </button>
                <button
                  onClick={() => handleBulkAction("delete")}
                  className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded text-sm hover:bg-gray-200"
                >
                  Delete
                </button>
              </div>
            )}
          </div>
        </div>

        {/* VM list */}
        <div className="space-y-2">
          {sortedVms.map(vm => (
            <VMCard
              key={vm.id}
              vm={vm}
              selected={selected.has(vm.id)}
              onSelect={handleSelect}
              onAction={handleAction}
            />
          ))}
          {(!vms || vms.length === 0) && <p className="text-gray-400 text-sm">No VMs configured. Use CLI or API to create.</p>}
        </div>
      </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 BudgetCards({ budget }) {
  const dailyUsed = budget ? budget.daily_limit_usd - budget.daily_remaining_usd : 0;
  const monthlyUsed = budget ? budget.monthly_limit_usd - budget.monthly_remaining_usd : 0;
  return (
    <>
      <Card title="Today's Budget">
        <CostBar used={dailyUsed} limit={budget?.daily_limit_usd || 5} label="Daily spend" />
      </Card>
      <Card title="Monthly Budget">
        <CostBar used={monthlyUsed} limit={budget?.monthly_limit_usd || 60} label="Monthly spend" />
      </Card>
    </>
  );
}

function SystemCard({ connected, health, modelCount, accountCount, providerCount, context }) {
  return (
    <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">Providers</span><span className="font-mono">{providerCount} configured</span></div>
        <div className="flex justify-between"><span className="text-gray-500">Models</span><span className="font-mono">{modelCount}</span></div>
        <div className="flex justify-between"><span className="text-gray-500">Accounts</span><span className="font-mono">{accountCount}</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>
  );
}

function ProvidersCard({ providers }) {
  if (!providers?.length) return null;
  return (
    <Card title="Configured Providers">
      <div className="flex flex-wrap gap-2">
        {providers.map(p => (
          <div key={p.name} className="flex items-center gap-1.5 px-2.5 py-1.5 bg-gray-50 rounded-lg border border-gray-200">
            <span className={`w-2 h-2 rounded-full ${p.has_key ? 'bg-emerald-500' : 'bg-gray-400'}`} />
            <span className="text-sm font-medium text-gray-700">{p.name}</span>
            <span className="text-xs text-gray-400">{p.model_count} models</span>
          </div>
        ))}
      </div>
    </Card>
  );
}

function OverviewTab({ budget, connected, health, models, providers, accounts, context, costs, refresh }) {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <BudgetCards budget={budget} />
        <SystemCard connected={connected} health={health} modelCount={models.length} accountCount={accounts.length} providerCount={providers.length} context={context} />
      </div>
      <ProvidersCard providers={providers} />
      <CostSummary costs={costs} />
      <AccountsPanel accounts={accounts} onRefresh={refresh} />
    </div>
  );
}

// ── Log Panel ───────────────────────────────────────────────

const LOG_COLORS = {
  ERROR: "bg-red-100 text-red-700 border-red-200",
  WARN: "bg-amber-100 text-amber-700 border-amber-200",
  INFO: "bg-blue-100 text-blue-700 border-blue-200",
  DEBUG: "bg-gray-100 text-gray-600 border-gray-200",
};

function LogPanel({ logs, error, source }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [filter, setFilter] = useState("ALL");
  
  const filteredLogs = logs?.filter(log => 
    filter === "ALL" || log.level === filter
  ) || [];
  
  const errorCount = logs?.filter(l => l.level === "ERROR").length || 0;
  const warnCount = logs?.filter(l => l.level === "WARN").length || 0;

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-50">
      {/* Header bar */}
      <div className="flex items-center justify-between px-4 py-2 bg-gray-50 border-b border-gray-200">
        <div className="flex items-center gap-3">
          <button 
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900"
          >
            <span>{isExpanded ? "▼" : "▲"}</span>
            Logs {source && `(${source.split('/').pop()})`}
          </button>
          
          {/* Level filters */}
          <div className="flex items-center gap-1 text-xs">
            <button 
              onClick={() => setFilter("ALL")}
              className={`px-2 py-0.5 rounded ${filter === "ALL" ? "bg-gray-800 text-white" : "bg-gray-200 text-gray-600"}`}
            >
              ALL
            </button>
            <button 
              onClick={() => setFilter("ERROR")}
              className={`px-2 py-0.5 rounded ${filter === "ERROR" ? "bg-red-600 text-white" : errorCount > 0 ? "bg-red-100 text-red-600" : "bg-gray-200 text-gray-600"}`}
            >
              ERR {errorCount > 0 && `(${errorCount})`}
            </button>
            <button 
              onClick={() => setFilter("WARN")}
              className={`px-2 py-0.5 rounded ${filter === "WARN" ? "bg-amber-600 text-white" : warnCount > 0 ? "bg-amber-100 text-amber-600" : "bg-gray-200 text-gray-600"}`}
            >
              WARN {warnCount > 0 && `(${warnCount})`}
            </button>
            <button 
              onClick={() => setFilter("INFO")}
              className={`px-2 py-0.5 rounded ${filter === "INFO" ? "bg-blue-600 text-white" : "bg-gray-200 text-gray-600"}`}
            >
              INFO
            </button>
          </div>
        </div>
        
        {error && (
          <span className="text-xs text-red-600">{error}</span>
        )}
      </div>
      
      {/* Log content */}
      {isExpanded && (
        <div className="max-h-64 overflow-y-auto px-4 py-2 space-y-1">
          {filteredLogs.length === 0 ? (
            <p className="text-xs text-gray-400 italic">No logs to display</p>
          ) : (
            filteredLogs.map((log, i) => (
              <div 
                key={i} 
                className={`flex items-start gap-2 text-xs p-1.5 rounded border ${LOG_COLORS[log.level] || LOG_COLORS.INFO}`}
              >
                <span className="font-mono opacity-60 whitespace-nowrap">{log.timestamp}</span>
                <span className="font-bold whitespace-nowrap">{log.level}</span>
                <span className="break-all">{log.message}</span>
              </div>
            ))
          )}
        </div>
      )}
      
      {/* Mini preview when collapsed */}
      {!isExpanded && logs?.length > 0 && (
        <div className="px-4 py-1 flex items-center gap-2 text-xs">
          {errorCount > 0 && (
            <span className="text-red-600 font-medium">⚠ {errorCount} errors</span>
          )}
          {warnCount > 0 && (
            <span className="text-amber-600 font-medium">⚡ {warnCount} warnings</span>
          )}
          <span className="text-gray-400">{logs.length} total entries</span>
          <span className="text-gray-300">|</span>
          <span className="text-gray-500 italic">
            {logs[logs.length - 1]?.message?.substring(0, 80)}...
          </span>
        </div>
      )}
    </div>
  );
}

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

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

  return (
    <div className="min-h-screen bg-gray-50 pb-20">
      <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 || 0})`}><ModelsTable models={data.models} /></Card>}
        {data.tab === "vms" && <VMsPanel vms={data.vms} onRefresh={data.refresh} />}
      </main>
      <LogPanel logs={data.logs} error={data.logsError} source={data.logsSource} />
    </div>
  );
}

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