import { escapeHtml } from "./html.js";
import { renderLifecycleShell } from "./shell.js";

export interface AccountListItem {
  readonly accountKey: string;
  readonly label: string;
  readonly capabilities: readonly string[];
}

export function renderAccountsPage(
  project: { readonly id: string; readonly name: string },
  accounts: readonly AccountListItem[],
): string {
  const rows = accounts.length
    ? accounts
        .map(
          (account) =>
            `<tr><td><strong>${escapeHtml(account.label)}</strong><div class="subtle">${escapeHtml(account.accountKey)}</div></td><td>${account.capabilities.map((capability) => `<span class="pill purple">${escapeHtml(capability)}</span>`).join(" ")}</td><td><span class="pill green">Available</span></td></tr>`,
        )
        .join("")
    : '<tr><td colspan="3"><div class="empty-note"><strong>No K3s Subrouter accounts yet.</strong><br>Add a fresh server-owned Codex account below before starting a real FactoryRun.</div></td></tr>';

  const content = `<div class="run-head"><div><div class="run-title">Accounts</div><div class="context-strip"><span class="pill green">K3s Subrouter</span><span>${accounts.length} available account${accounts.length === 1 ? "" : "s"}</span><span class="divider"></span><span>Credentials are owned and refreshed by this Subrouter instance.</span></div></div></div>
  <section class="panel"><div class="panel-head"><h2>Available accounts</h2><p>These are the only accounts eligible for Slice 1 FactoryRun selection.</p></div><div class="panel-body table-pad"><div class="table-wrap"><table class="table"><thead><tr><th>Account</th><th>Capabilities</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table></div></div></section>
  <section class="panel"><div class="panel-head"><h2>Add account</h2><p>Starts a fresh Codex device-auth flow in an isolated temporary login home. No workstation auth files are read or copied.</p></div><div class="panel-body"><div class="callout purple"><div class="callout-title">Fresh server-owned login</div><div class="callout-sub">Complete the verification URL/code shown below. On success AWP imports the new OAuth chain into K3s Subrouter and deletes the temporary login directory.</div></div><div class="mini-actions"><button class="btn primary" type="button" data-account-login data-provider="codex">＋ Add Codex account</button><a class="btn" href="/projects/${encodeURIComponent(project.id)}?tab=plans">Back to Plan launch</a></div><pre class="login-output" data-login-output aria-live="polite" hidden></pre><div class="error" data-login-error role="alert"></div></div></section>`;

  return renderLifecycleShell({
    active: "accounts",
    breadcrumbs: ["AWP", project.name, "Accounts"],
    content,
    project,
  });
}
