// parent 布局：认证守卫 + AppShell + MultiChildTabBar
// 依据：02-architecture-design.md §3.1 路由结构、§6 应用外壳
// - 未认证重定向到 /login
// - MF 启用时由 Shell 提供外壳（本布局的 AppShell 仅独立模式使用）

"use client";

import { type ReactNode, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { isAuthenticated } from "@/lib/auth";
import { AppShell } from "@/components/AppShell";
import { MultiChildTabBar } from "@/components/MultiChildTabBar";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { useCrossTabSync } from "@/hooks/useCrossTabSync";
import { EmptyChildState } from "@/components/EmptyChildState";

export default function ParentLayout({ children }: { children: ReactNode }) {
  const router = useRouter();
  const [checked, setChecked] = useState(false);
  const { children: childList, loading } = useChildSwitcher();
  useCrossTabSync();

  useEffect(() => {
    if (!isAuthenticated()) {
      router.replace("/login");
      return;
    }
    setChecked(true);
  }, [router]);

  if (!checked) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <span className="skeleton h-8 w-48 rounded" />
      </div>
    );
  }

  return (
    <AppShell>
      {childList.length === 0 && !loading ? (
        <EmptyChildState />
      ) : (
        <>
          <MultiChildTabBar />
          {children}
        </>
      )}
    </AppShell>
  );
}
