/**
 * scaffold-layout/generate.ts — Build PageTemplate.tsx + AppShell.tsx + Sidebar.tsx.
 *
 * Pure function — no I/O.
 */
import type { GeneratedFile, ScaffoldLayoutInput } from './types.js';

const HEADER = `/* AUTO-GENERATED — re-run scaffold-layout to refresh. Add @customised at the top to opt out. */`;

function pageTemplate(): string {
  return `${HEADER}
import { useEffect, type ReactNode, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { ChevronRight } from 'lucide-react';

export interface BreadcrumbItem {
  readonly label: string;
  readonly href?: string;
}

export interface PageTemplateProps {
  title: string;
  subtitle?: string | null;
  icon?: ReactNode;
  actions?: ReactNode;
  breadcrumbs?: BreadcrumbItem[];
  children: ReactNode;
  className?: string;
  contentClassName?: string;
}

export function PageTemplate({
  title,
  subtitle,
  icon,
  actions,
  breadcrumbs,
  children,
  className,
  contentClassName,
}: PageTemplateProps) {
  useEffect(() => {
    const prev = document.title;
    document.title = title;
    return () => {
      document.title = prev;
    };
  }, [title]);

  return (
    <div className={\`flex flex-col gap-6 p-6 \${className ?? ''}\`}>
      {breadcrumbs && breadcrumbs.length > 0 && (
        <nav aria-label="Breadcrumb" className="flex items-center gap-1.5 text-sm">
          {breadcrumbs.map((item, i) => (
            <Fragment key={i}>
              {i > 0 && <ChevronRight className="w-3.5 h-3.5 text-[var(--text-muted)]" />}
              {item.href && i < breadcrumbs.length - 1 ? (
                <Link to={item.href} className="text-[var(--text-muted)] hover:text-[var(--color-accent-600)] transition-colors">
                  {item.label}
                </Link>
              ) : (
                <span className={i === breadcrumbs.length - 1 ? 'font-medium text-[var(--text-primary)]' : 'text-[var(--text-muted)]'}>
                  {item.label}
                </span>
              )}
            </Fragment>
          ))}
        </nav>
      )}
      <header className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          {icon && <span className="text-[var(--color-accent-500)]">{icon}</span>}
          <div>
            <h1 className="text-2xl font-bold text-[var(--text-primary)]">{title}</h1>
            {subtitle && <p className="text-sm text-[var(--text-muted)]">{subtitle}</p>}
          </div>
        </div>
        {actions && <div className="flex items-center gap-2">{actions}</div>}
      </header>
      <main className={contentClassName ?? ''}>{children}</main>
    </div>
  );
}
`;
}

function appShell(spec: ScaffoldLayoutInput): string {
  const brand = spec.appCode.charAt(0).toUpperCase() + spec.appCode.slice(1);
  return `${HEADER}
import type { ReactNode } from 'react';
import { Sidebar } from './Sidebar';

export interface AppShellProps {
  children: ReactNode;
}

export function AppShell({ children }: AppShellProps) {
  return (
    <div className="flex flex-col h-screen bg-[var(--bg-app)]">
      <header className="flex items-center justify-between h-14 px-4 border-b border-[var(--border-color)] bg-[var(--bg-card)]">
        <div className="text-lg font-semibold text-[var(--text-primary)]">${brand}</div>
        <div className="flex items-center gap-2">{/* user menu, theme toggle, etc. */}</div>
      </header>
      <div className="flex flex-1 overflow-hidden">
        <aside className="w-64 border-r border-[var(--border-color)] bg-[var(--bg-card)] overflow-y-auto">
          <Sidebar />
        </aside>
        <main className="flex-1 overflow-y-auto">{children}</main>
      </div>
    </div>
  );
}
`;
}

function sidebar(): string {
  return `${HEADER}
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '@atlashub/smartstack';

interface NavEntry {
  componentKey: string;
  label: string;
  href: string;
  children?: NavEntry[];
}

export function Sidebar() {
  const [entries, setEntries] = useState<NavEntry[]>([]);

  useEffect(() => {
    api.get<NavEntry[]>('/api/navigation/menu')
      .then((r) => setEntries(Array.isArray(r) ? r : []))
      .catch(() => setEntries([]));
  }, []);

  return (
    <nav className="flex flex-col gap-1 p-3">
      {entries.map((e) => (
        <NavItem key={e.componentKey} entry={e} />
      ))}
    </nav>
  );
}

function NavItem({ entry }: { entry: NavEntry }) {
  return (
    <div className="flex flex-col">
      <Link
        to={entry.href}
        className="px-3 py-2 rounded-[var(--radius-button)] text-sm text-[var(--text-primary)] hover:bg-[var(--bg-hover)] transition-colors"
      >
        {entry.label}
      </Link>
      {entry.children && entry.children.length > 0 && (
        <div className="ml-4 flex flex-col gap-0.5">
          {entry.children.map((c) => (
            <NavItem key={c.componentKey} entry={c} />
          ))}
        </div>
      )}
    </div>
  );
}
`;
}

export function generate(spec: ScaffoldLayoutInput): GeneratedFile[] {
  return [
    { path: 'src/components/ui/PageTemplate.tsx', content: pageTemplate() },
    { path: 'src/components/AppShell.tsx', content: appShell(spec) },
    { path: 'src/components/Sidebar.tsx', content: sidebar() },
  ];
}
