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

export interface ShellOptions {
  readonly active: "home" | "factory-runs" | "reviews" | "queues" | "accounts";
  readonly breadcrumbs: readonly string[];
  readonly content: string;
  readonly project?: { readonly id: string; readonly name: string };
  readonly latestFactoryRunId?: string;
  readonly latestChangeSetId?: string;
}

const breadcrumbMarkup = (items: readonly string[]): string =>
  items
    .map((item, index) =>
      index === 0
        ? `<span>${escapeHtml(item)}</span>`
        : `<span class="sep">/</span><span>${escapeHtml(item)}</span>`,
    )
    .join("");

const sideLink = (href: string, label: string, active: boolean, icon: string, extra = ""): string =>
  `<a class="side-link${active ? " active" : ""}" href="${href}"${active ? ' aria-current="page"' : ""}><span class="nav-ico" aria-hidden="true">${icon}</span><span>${label}</span>${extra}</a>`;

export function renderLifecycleShell(options: ShellOptions): string {
  const project = options.project ?? { id: "fixture-project", name: "Fixture Project" };
  const projectPath = `/projects/${encodeURIComponent(project.id)}`;
  const factoryPath = options.latestFactoryRunId
    ? `/factory-runs/${encodeURIComponent(options.latestFactoryRunId)}?project=${encodeURIComponent(project.id)}`
    : `${projectPath}?tab=factory-runs`;
  const reviewPath = options.latestChangeSetId
    ? `/changesets/${encodeURIComponent(options.latestChangeSetId)}?project=${encodeURIComponent(project.id)}`
    : `${projectPath}?tab=reviews`;
  return `<div class="screen lifecycle-shell">
    <a class="skip-link" href="#main-content">Skip to main content</a>
    <aside class="sidebar" aria-label="Primary navigation">
      <div class="brand"><span class="brand-mark" aria-hidden="true"></span><span>AWP</span></div>
      <nav class="side-scroll">
        ${sideLink(projectPath, "Home", options.active === "home", "⌂")}
        <div class="side-label">Workflow</div>
        ${sideLink(`${projectPath}?tab=plans`, "Plans", false, "⌘")}
        ${sideLink(factoryPath, "FactoryRuns", options.active === "factory-runs", "◷")}
        ${sideLink(`${projectPath}?tab=factory-runs`, "AgentRuns", false, "◉")}
        ${sideLink(reviewPath, "ChangeSets", false, "⌘")}
        ${sideLink(`${projectPath}?tab=reviews`, "Reviews", options.active === "reviews", "▣")}
        <div class="side-label">Foundation</div>
        ${sideLink(`/accounts?project=${encodeURIComponent(project.id)}`, "Accounts", options.active === "accounts", "◎")}
        ${sideLink("#planned-agents", "Agents", false, "⌘", '<span class="planned-chip">Planned I4</span>')}
        ${sideLink("#planned-factories", "Factories", false, "⌂", '<span class="planned-chip">Planned I4</span>')}
        ${sideLink("#planned-templates", "Templates", false, "▤", '<span class="planned-chip">Planned I4</span>')}
        <div class="side-label">Operations</div>
        ${sideLink("/projects", "Projects", false, "▣")}
        ${sideLink(`${projectPath}/queue`, "Queues", options.active === "queues", "≋")}
        ${sideLink(`${projectPath}?tab=settings`, "Settings", false, "⚙")}
      </nav>
      <div class="project-switch" aria-label="Current project"><span class="project-dot">A</span><div><small>Project</small><b>${escapeHtml(project.name)}</b></div><span class="right" aria-hidden="true">⌄</span></div>
    </aside>
    <main class="main" id="main-content">
      <header class="topbar">
        <div class="brand-spacer" aria-hidden="true">.</div>
        <label class="search-box planned-search" title="Search activates in I3"><span aria-hidden="true">⌕</span><input aria-label="Search — planned for I3" aria-disabled="true" disabled placeholder="Search plans, runs, tasks, agents, change sets…"><span class="kbd">⌘ K</span></label>
        <div class="top-user"><button class="icon-button" aria-label="Notifications" type="button">♧</button><span class="avatar" aria-hidden="true">O</span><span>Owner</span><span aria-hidden="true">⌄</span></div>
      </header>
      <div class="content">
        <div class="breadcrumbs" aria-label="Breadcrumb">${breadcrumbMarkup(options.breadcrumbs)}</div>
        ${options.content}
      </div>
    </main>
  </div>`;
}

export function renderStateBanner(state: string, kind: "project" | "factory" | "review"): string {
  if (state === "stale")
    return `<div class="state-banner warning" role="status"><strong>Stale / disconnected</strong><span>Last-known authoritative ${kind} data remains readable. Protected mutations are disabled until freshness is restored.</span><button class="btn" type="button" data-command="refresh">Refresh</button></div>`;
  if (state === "permission")
    return `<div class="state-banner warning" role="status"><strong>Permission limited</strong><span>You can inspect this ${kind}, but your current Principal cannot perform protected actions.</span></div>`;
  if (state === "error")
    return `<div class="state-banner error" role="alert"><strong>Some current data could not be refreshed</strong><span>Last-known content is preserved. Retry the read without discarding page context.</span><button class="btn" type="button" data-command="refresh">Retry</button></div>`;
  return "";
}

export const protectedActionDisabled = (state: string): boolean =>
  state === "stale" || state === "permission" || state === "error";
