import Link from "next/link";
import { HeaderControls } from "@/components/header-controls";
import { MainNav } from "@/components/main-nav";
import { getViewerSession } from "@/lib/popiart-api";
import { getLiveCopy } from "@/lib/live-copy";
import type { AppDictionary, Locale } from "@/lib/site-content";

function localize(locale: Locale, path: string) {
  if (!path || path === "/") {
    return `/${locale}`;
  }
  return `/${locale}${path}`;
}

export async function SiteChrome({
  children,
  dictionary,
  locale,
}: {
  children: React.ReactNode;
  dictionary: AppDictionary;
  locale: Locale;
}) {
  const liveCopy = getLiveCopy(locale);
  const session = await getViewerSession();

  return (
    <div className="site-shell">
      <header className="site-header">
        <div className="brand-lockup">
          <Link className="brand-mark" href={localize(locale, "/")}>
            PA
          </Link>
          <div>
            <strong>{dictionary.brand.name}</strong>
            <span>{dictionary.brand.subtitle}</span>
          </div>
        </div>

        <MainNav
          labels={{
            home: dictionary.nav.home,
            docs: dictionary.nav.docs,
            skills: liveCopy.nav.skills,
            console: dictionary.nav.console,
            pricing: dictionary.nav.pricing,
            billing: locale === "zh" ? "账单" : "Billing",
          }}
          locale={locale}
        />

        <HeaderControls
          labels={{
            zh: liveCopy.header.zh,
            en: liveCopy.header.en,
            logout: liveCopy.header.logout,
            loggingOut: liveCopy.header.loggingOut,
            loginHint: liveCopy.header.loginHint,
            login: dictionary.nav.login,
          }}
          locale={locale}
          loginHref={localize(locale, "/login")}
          user={session?.user ?? null}
        />
      </header>

      <main className="main-content">{children}</main>

      <footer className="site-footer">
        <div>
          <strong>{dictionary.brand.name}</strong>
          <p>{dictionary.footer.copy}</p>
        </div>
        <div className="footer-links">
          <Link href={localize(locale, "/docs")}>{dictionary.nav.docs}</Link>
          <Link href={localize(locale, "/skills")}>{liveCopy.nav.skills}</Link>
          <Link href={localize(locale, "/pricing")}>{dictionary.nav.pricing}</Link>
          <Link href={localize(locale, "/billing")}>{locale === "zh" ? "账单" : "Billing"}</Link>
          <Link href={localize(locale, "/console")}>{dictionary.nav.console}</Link>
        </div>
      </footer>
    </div>
  );
}
