"use client";

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

const PROFILE_ROUTES = ["/profiles", "/settings", "/account", "/setup/ui"];

function isProfileRoute(pathname: string | null): boolean {
  if (!pathname) return false;
  return PROFILE_ROUTES.some(
    (r) => pathname === r || pathname.startsWith(`${r}/`),
  );
}

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

/**
 * Owns profile-skin-mode on the browse shell (not <html>).
 * Skin id always starts as "classic" on SSR + first client render, then
 * upgrades in useLayoutEffect — avoids hydration mismatches when the
 * profile provider already has account data on the client.
 */
export function ProfileSkinHost({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const { account, profile } = useProfile();
  const active = isProfileRoute(pathname);

  // Constant initial state — must match server HTML
  const [skinId, setSkinId] = useState<UiSkinId>("classic");

  useLayoutEffect(() => {
    // Clear leftover attrs from older builds that mutated <html>
    const root = document.documentElement;
    delete root.dataset.uiSkin;
    root.classList.remove("profile-skin-mode");
  }, []);

  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);

  return (
    <div
      className={`browse-shell flex min-h-full flex-col${active ? " profile-skin-mode" : ""}`}
      data-ui-skin={active ? skinId : undefined}
      style={
        active
          ? ({
              "--skin-accent": skin.preview.accent,
              "--skin-bg": skin.preview.bg,
            } as CSSProperties)
          : undefined
      }
    >
      {children}
    </div>
  );
}
