"use client";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ArrowRight, Bot, ChartColumn, CornerDownLeft, Film, ListChecks, ListOrdered, LogOut, Play, Plus, Search, Settings, Share2, Shield, Sparkles, Target,
} from "lucide-react";
import { toast } from "sonner";
import { signOut, useSession } from "@/lib/auth-client";
import { resetAnalytics } from "@/lib/posthog";
import { useBillingSummary } from "@/hooks/use-billing-summary";
import { useSocialAccess } from "@/hooks/use-social-access";
import { billingPlanMessageKey } from "@/lib/billing-plans";
import { getUpgradeState } from "@/components/billing/upgrade-prompt";
import { fetchGenerations, timeAgo, type GenerationSummary } from "@/lib/generations";
import { StatusBadge } from "@/components/app/status-badge";
import { Announcements } from "@/components/announcements";
import { ThemeToggle } from "@/components/theme-toggle";
import { useAppTheme } from "@/components/theme-provider";
import { availableWorkflows, useWorkflowsInfo } from "@/components/workflow-picker";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Kbd } from "@/components/ui/kbd";
import { cn } from "@/lib/utils";
// `mobile: false` keeps an item out of the five-slot mobile tab bar.
// `social: true` items only show when social publishing is enabled for the user.
type NavItem = { href: string; labelKey: "create" | "library" | "social" | "analytics" | "agents" | "settings"; icon: typeof Film; match: (path: string) => boolean; mobile?: boolean; social?: boolean };
const NAV: NavItem[] = [
{ href: "/", labelKey: "create", icon: Sparkles, match: (p) => p === "/" },
{ href: "/list", labelKey: "library", icon: Film, match: (p) => p.startsWith("/list") || p.startsWith("/tasks") },
{ href: "/settings/social", labelKey: "social", icon: Share2, match: (p) => p.startsWith("/settings/social"), social: true },
{ href: "/analytics", labelKey: "analytics", icon: ChartColumn, match: (p) => p.startsWith("/analytics"), social: true },
{ href: "/settings/api-keys", labelKey: "agents", icon: Bot, match: (p) => p.startsWith("/settings/api-keys"), mobile: false },
{ href: "/settings", labelKey: "settings", icon: Settings, match: (p) => p === "/settings" },
];
function initials(name?: string | null, email?: string | null) {
const source = name?.trim() || email || "?";
return source.split(/[\s@.]+/).filter(Boolean).slice(0, 2).map((part) => part[0]?.toUpperCase()).join("");
}
/** Signed-in application chrome: sidebar on desktop, tab bar on mobile, ⌘K palette everywhere. */
export function AppShell({ children }: { children: React.ReactNode }) {
const t = useTranslations("shell");
const { data: session } = useSession();
const pathname = usePathname();
const router = useRouter();
const [paletteOpen, setPaletteOpen] = useState(false);
const [billing] = useBillingSummary(Boolean(session?.user));
// The editor is a full-screen workspace with its own back button: no app
// chrome there. Elements stay in place (hidden) so children keep their position.
const immersive = /^\/tasks\/[^/]+\/edit/.test(pathname);
const compact = immersive;
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
setPaletteOpen((open) => !open);
return;
}
const target = event.target as HTMLElement | null;
const typing = target?.closest("input, textarea, select, [contenteditable=true], [role=dialog]");
if (!typing && !event.metaKey && !event.ctrlKey && !event.altKey && event.key.toLowerCase() === "n") {
event.preventDefault();
router.push("/");
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [router]);
// Children must keep the same tree position whether or not the session has
// loaded — otherwise the page remounts and re-runs its initial fetches.
const user = session?.user;
useAppTheme(Boolean(user));
const admin = Boolean((user as { is_admin?: boolean } | undefined)?.is_admin);
const socialAccess = useSocialAccess(Boolean(user));
const labeled = NAV.map((item) => ({ ...item, label: t(`nav.${item.labelKey}`) }));
const nav = labeled.filter((item) => !item.social || socialAccess === true);
const mobileNav = nav.filter((item) => item.mobile !== false);
const items = admin ? [...nav, { href: "/admin", label: t("nav.admin"), icon: Shield, match: (p: string) => p.startsWith("/admin") }] : nav;
return (
{user ?
: null}
{user && !immersive ?
SupoClip
: null}
{children}
{user && !immersive ?
: null}
{user ?
: null}
);
}
function SidebarLink({ href, label, active, compact, shortcut, className, children }: {
href: string; label: string; active?: boolean; compact: boolean; shortcut?: string; className?: string; children: React.ReactNode;
}) {
const link = (
{children}
{!compact && {label}}
{!compact && shortcut && {shortcut}}
);
if (!compact) return link;
return {link}{label};
}
function UsageCard({ billing }: { billing: NonNullable[0]> }) {
const t = useTranslations("shell");
const tCommon = useTranslations("common");
const limit = billing.minute_limit ?? null;
const used = billing.usage_minutes ?? 0;
const pct = limit ? Math.min(100, (used / limit) * 100) : 0;
const upgrade = getUpgradeState(billing);
const nudge = !upgrade?.isPaid
? t("usage.pickPlan")
: upgrade.nextPlan && (upgrade.atLimit || upgrade.nearLimit)
? t("usage.moreWith", { name: tCommon(`plans.${billingPlanMessageKey(upgrade.nextPlan.id)}`) })
: null;
return (
{tCommon(`plans.${billingPlanMessageKey(billing.plan)}`)}
{limit ? t("usage.minutesOf", { used, limit }) : t("usage.minutes", { used })}
{limit ? (
) : null}
{nudge ? (
{nudge}
) : (
{limit && upgrade?.remaining !== null ? t("usage.minutesLeft", { count: upgrade?.remaining ?? 0 }) : t("usage.minutesThisMonth")}
)}
);
}
function UserRow({ compact, name, email }: { compact: boolean; name?: string | null; email?: string | null }) {
const t = useTranslations("shell");
const [signingOut, setSigningOut] = useState(false);
const handleSignOut = async () => {
setSigningOut(true);
try { await signOut(); resetAnalytics(); window.location.assign("/sign-in"); }
catch { toast.error(t("user.signOutError")); setSigningOut(false); }
};
return (
{initials(name, email)}
{!compact && (
{name || t("user.creator")}
{email}
)}
{signingOut ? t("user.signingOut") : t("user.signOut")}
);
}
type PaletteEntry = { id: string; label: string; hint?: string; href: string; icon: typeof Film; generation?: GenerationSummary };
// "New series" and friends open the create screen with that workflow picked.
const WORKFLOW_SHORTCUTS = [
{ id: "series", icon: ListOrdered },
{ id: "topic", icon: Target },
{ id: "recap", icon: ListChecks },
{ id: "trailer", icon: Play },
] as const;
function CommandPalette({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
const t = useTranslations("shell");
const tHome = useTranslations("home");
const locale = useLocale();
const router = useRouter();
const [query, setQuery] = useState("");
const [generations, setGenerations] = useState([]);
const [active, setActive] = useState(0);
const listRef = useRef(null);
useEffect(() => {
if (!open) return;
setQuery("");
setActive(0);
void fetchGenerations().then(setGenerations).catch(() => {});
}, [open]);
const socialAccess = useSocialAccess(open);
const workflowsInfo = useWorkflowsInfo(open);
const entries = useMemo(() => {
const q = query.trim().toLowerCase();
const offered = availableWorkflows(workflowsInfo);
const actions: PaletteEntry[] = [
{ id: "new", label: t("nav.newGeneration"), hint: t("palette.newHint"), href: "/", icon: Plus },
...WORKFLOW_SHORTCUTS.filter((shortcut) => offered.has(shortcut.id)).map((shortcut) => ({
id: `new-${shortcut.id}`, label: tHome(`palette.${shortcut.id}`), href: `/?workflow=${shortcut.id}`, icon: shortcut.icon,
})),
{ id: "library", label: t("palette.library"), href: "/list", icon: Film },
...(socialAccess === true ? [{ id: "social", label: t("palette.social"), hint: t("palette.socialHint"), href: "/settings/social", icon: Share2 },
{ id: "analytics", label: t("nav.analytics"), hint: t("palette.analyticsHint"), href: "/analytics", icon: ChartColumn }] : []),
{ id: "keys", label: t("nav.agents"), hint: t("palette.agentsHint"), href: "/settings/api-keys", icon: Bot },
{ id: "settings", label: t("nav.settings"), href: "/settings", icon: Settings },
].filter((entry) => !q || entry.label.toLowerCase().includes(q));
const matches = generations
.filter((generation) => !q || generation.source_title.toLowerCase().includes(q))
.slice(0, 8)
.map((generation) => ({
id: generation.id, label: generation.source_title, hint: timeAgo(generation.created_at, locale),
href: `/tasks/${generation.id}`, icon: Film, generation,
}));
return [...actions, ...matches];
}, [generations, query, socialAccess, workflowsInfo, t, tHome, locale]);
const go = useCallback((entry: PaletteEntry | undefined) => {
if (!entry) return;
onOpenChange(false);
router.push(entry.href);
}, [onOpenChange, router]);
useEffect(() => {
listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" });
}, [active]);
return (
);
}