"use client";

import {
  useLayoutEffect,
  useState,
  type CSSProperties,
  type ReactNode,
} from "react";
import Link from "next/link";
import { useProfile } from "@/lib/profile/context";
import {
  AVATARS,
  getCachedPreferredUi,
  getUiSkin,
  setCachedPreferredUi,
  type UiSkinId,
} from "@/lib/uiSkins";

export type ProfileNavId = "profiles" | "settings" | "account" | "ui";

function pickSkinId(
  accountUi?: string | null,
  profileUi?: string | null,
): UiSkinId {
  const live = accountUi || profileUi;
  if (live) return getUiSkin(live).id;
  return getCachedPreferredUi() ?? "classic";
}

export function ThemedProfileShell({
  title,
  subtitle,
  active,
  children,
  narrow,
}: {
  title: string;
  subtitle?: string;
  active: ProfileNavId;
  children: ReactNode;
  /** tighter max width for forms */
  narrow?: boolean;
}) {
  const { ready, account, profile } = useProfile();
  // Always "classic" for SSR + first client render so markup matches.
  // Real skin applied in useLayoutEffect (before paint).
  const [skinId, setSkinId] = useState<UiSkinId>("classic");

  useLayoutEffect(() => {
    const next = pickSkinId(
      account?.preferredUi,
      profile?.settings.preferredUi,
    );
    setSkinId(next);
    if (account?.preferredUi || profile?.settings.preferredUi) {
      setCachedPreferredUi(next);
    }
  }, [account?.preferredUi, profile?.settings.preferredUi]);

  const skin = getUiSkin(skinId);
  const avatar = AVATARS.find(
    (a) => a.id === (account?.avatarId ?? profile?.avatarId ?? "default"),
  );

  const frameStyle = {
    "--skin-accent": skin.preview.accent,
    "--skin-bg": skin.preview.bg,
  } as CSSProperties;

  if (!ready) {
    return (
      <div
        className={`profile-skin profile-skin--${skin.id} profile-skin--loading`}
        data-ui-skin={skin.id}
        style={frameStyle}
      >
        <div className="profile-skin-atmosphere" aria-hidden />
        <p className="profile-skin-loading-text">Loading…</p>
      </div>
    );
  }

  return (
    <div
      className={`profile-skin profile-skin--${skin.id}`}
      data-ui-skin={skin.id}
      style={frameStyle}
    >
      <div className="profile-skin-atmosphere" aria-hidden />
      <div className="profile-skin-scan" aria-hidden />

      <div
        className={`profile-skin-frame${narrow ? " profile-skin-frame--narrow" : ""}`}
      >
        <header className="profile-skin-top">
          <Link href="/" className="profile-skin-back">
            ← Cabinet
          </Link>

          <div className="profile-skin-brand">
            <span className="profile-skin-mark">{skin.preview.label}</span>
            <div>
              <p className="profile-skin-kicker">{skin.name}</p>
              <h1 className="profile-skin-title">{title}</h1>
            </div>
          </div>

          <div className="profile-skin-user">
            {account || profile ? (
              <>
                <span
                  className="profile-skin-avatar"
                  style={{ background: avatar?.color ?? skin.preview.accent }}
                  aria-hidden
                />
                <span className="profile-skin-user-name">
                  {account?.displayName ?? profile?.displayName ?? "Player"}
                </span>
              </>
            ) : (
              <span className="profile-skin-user-name text-muted">Guest</span>
            )}
          </div>
        </header>

        <nav className="profile-skin-nav" aria-label="Account sections">
          <NavLink href="/profiles" active={active === "profiles"}>
            Profiles
          </NavLink>
          <NavLink href="/settings" active={active === "settings"}>
            Settings
          </NavLink>
          <NavLink href="/account" active={active === "account"}>
            Account
          </NavLink>
          <NavLink href="/setup/ui" active={active === "ui"}>
            Cabinet UI
          </NavLink>
        </nav>

        {subtitle && <p className="profile-skin-subtitle">{subtitle}</p>}

        <div className="profile-skin-body">{children}</div>
      </div>
    </div>
  );
}

function NavLink({
  href,
  active,
  children,
}: {
  href: string;
  active: boolean;
  children: ReactNode;
}) {
  return (
    <Link
      href={href}
      className={`profile-skin-nav-link${active ? " is-active" : ""}`}
      aria-current={active ? "page" : undefined}
      prefetch
    >
      {children}
    </Link>
  );
}
