"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useEditContext, } from "../editor/client/editContext";
import { ParheliaAgentIcon } from "../editor/ui/Icons";
import { RecentPages } from "./RecentPages";
import { LatestFeedback } from "../editor/reviews/LatestFeedback";
import { getLatestFeedbackCreatedTime, isLatestFeedbackRefreshMessage, loadLatestFeedbackItems, } from "../editor/reviews/latestFeedbackData";
import { AlertTriangle, ArrowRight, Bell, Layers, Search, } from "lucide-react";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, } from "../components/ui/accordion";
import { CountBadge } from "../components/ui/badge";
import { CloseButton } from "../components/ui/close-button";
import { ItemSearch } from "../editor/ui/ItemSearch";
import { OpenInNewTabButton } from "../editor/menubar/OpenInNewTabButton";
import { Favorites } from "../editor/sidebar/Favorites";
import { SimpleTabs } from "../editor/ui/SimpleTabs";
import { HomeListBadge, HomeListIcon, homeListContainerClass, homeListRowClass, } from "../editor/ui/HomeListRow";
import { cn } from "../lib/utils";
import { executeCustomCommand, isCustomCommandDisabled, renderCustomCommandIcon, } from "../editor/commands/customCommandConverter";
import { dedupeInflight } from "../editor/utils/dedupeInflight";
import { getHomeQuickActions, getSystemStatus, } from "../editor/services/systemService";
import { getAgentsGrouped, } from "../editor/services/agentService";
import { getMyTasks } from "../task-board/services/taskService";
import { getTaskBoardNavSnapshot, setTaskBoardNavState, } from "../task-board/taskBoardNavStore";
import { normalizeTaskStatus } from "../task-board/taskStatus";
import { getMyReviews } from "../editor/services/reviewsService";
import { ClipboardCheck, ClipboardList } from "lucide-react";
import { useNotifications } from "../editor/notifications/useNotifications";
import { resolveNotificationAction } from "../editor/notifications/notificationRoutes";
import { tourScrollIntoViewMarginClass } from "../tour/Tour";
import { LicenseFeatures, useFeature } from "../licensing";
const LATEST_FEEDBACK_TAB_ID = "latest-feedback";
const LATEST_FEEDBACK_TAB_INDEX = 2;
const MY_AGENTS_QUICK_ACTION_ID = "066fe46d-7609-4387-8886-b5457812de0d";
function isTyping(event) {
    const target = event.target;
    if (!target)
        return false;
    const maybeNode = target;
    const el = typeof maybeNode.nodeType === "number" && maybeNode.nodeType === 3
        ? maybeNode.parentElement
        : target;
    if (!el)
        return false;
    const htmlEl = el;
    const tag = htmlEl.tagName?.toLowerCase?.() || "";
    if (tag === "input" || tag === "textarea" || tag === "select")
        return true;
    if (htmlEl.isContentEditable)
        return true;
    const closestEditable = htmlEl.closest?.('input,textarea,select,[contenteditable=""],[contenteditable="true"],[role="textbox"]');
    return !!closestEditable;
}
function agentStatusBadgeClass(status) {
    switch (status) {
        case "completed":
        case "running":
            return "bg-feedback-green-light text-feedback-green";
        case "error":
            return "bg-feedback-red-light text-feedback-red";
        case "waitingForApproval":
        case "waitingForInput":
        case "costLimitReached":
            return "bg-feedback-orange-light text-feedback-orange";
        default:
            return "bg-neutral-grey-5 text-neutral-grey-100";
    }
}
function agentStatusDotClass(status) {
    switch (status) {
        case "running":
            return "animate-pulse bg-feedback-green";
        case "error":
            return "bg-feedback-red";
        case "waitingForApproval":
        case "waitingForInput":
        case "costLimitReached":
            return "bg-feedback-orange";
        default:
            return "bg-neutral-grey-50";
    }
}
function getLatestFeedbackSeenTimestamp(items) {
    const latestItemTime = Math.max(0, ...items
        .map(getLatestFeedbackCreatedTime)
        .filter((time) => Number.isFinite(time) && time > 0));
    return new Date(Math.max(Date.now(), latestItemTime)).toISOString();
}
function isMyAgentsQuickAction(command) {
    const workspaceId = command.settings.workspaceId;
    return (command.id.toLowerCase() === MY_AGENTS_QUICK_ACTION_ID ||
        (command.commandType === "switchWorkspace" &&
            typeof workspaceId === "string" &&
            workspaceId.toLowerCase() === "agents" &&
            command.label.trim().toLowerCase() === "my agents"));
}
export function openAgentWorkspaceFromSplash(editContext, agentId) {
    editContext?.switchWorkspace("agents", {
        urlParams: { agentId },
    });
    window.dispatchEvent(new CustomEvent("editor:openAgent", { detail: { agentId } }));
}
/**
 * Modern splash screen with clean design featuring:
 * - Parhelia logo and branding
 * - Functional AI assistant chat interface
 * - Quick action buttons
 * - Recent pages overview
 */
export function ModernSplashScreen() {
    const editContext = useEditContext();
    const canUseAi = useFeature(LicenseFeatures.AI);
    const isDark = false;
    const [systemStatus, setSystemStatus] = useState(null);
    const [statusWarningDismissed, setStatusWarningDismissed] = useState(false);
    const [homeQuickActions, setHomeQuickActions] = useState([]);
    const [activeAgents, setActiveAgents] = useState([]);
    const [myTasks, setMyTasks] = useState([]);
    const [myReviews, setMyReviews] = useState([]);
    const { notifications, unreadCount, markRead } = useNotifications(editContext, { showAll: false });
    const [activeListTab, setActiveListTab] = useState(0);
    const [latestFeedbackItems, setLatestFeedbackItems] = useState([]);
    const [latestFeedbackLastSeenAt, setLatestFeedbackLastSeenAt] = useState(editContext?.userInfo?.preferences?.latestFeedbackLastSeenAt);
    const greeting = useMemo(() => {
        const hour = new Date().getHours();
        const lateNight = {
            label: "Still up",
            slogans: [
                "Burning the midnight oil?",
                "The world is asleep — your story isn't.",
                "Quiet hours, bold headlines.",
                "Coffee or copy?",
                "Owl mode engaged.",
                "Stars are out — so is your draft.",
                "Night shift, no apologies.",
                "The page never sleeps.",
                "Late, but legendary.",
                "Shh — creativity loading.",
            ],
        };
        const morning = {
            label: "Good morning",
            slogans: [
                "Let's make today's stories shine.",
                "Fresh start, fresh content.",
                "The homepage is yours before noon.",
                "First coffee, first headline.",
                "Mornings are made for storytellers.",
                "Today's a blank page.",
                "Sunrise, sign-in, publish.",
                "Be the early editor.",
                "New day, new narratives.",
                "Caffeine and inspiration on tap.",
            ],
        };
        const lunch = {
            label: "Good afternoon",
            slogans: [
                "Hope lunch was great.",
                "Refuel and rewrite.",
                "Midday momentum.",
                "Half the day, twice the words.",
                "Lunch break or breakthrough draft?",
                "Bon appétit, then publish.",
                "Sandwich in one hand, headline in the other.",
                "The afternoon is yours to write.",
                "Recharge, then publish.",
                "Halftime — back to the page.",
            ],
        };
        const afternoon = {
            label: "Good afternoon",
            slogans: [
                "Plenty of daylight left to publish.",
                "The afternoon is your runway.",
                "Second wind activated.",
                "Golden hours, golden copy.",
                "Focus mode: on.",
                "Make every paragraph count.",
                "Sunshine and storytelling.",
                "Onwards, upwards.",
                "The day's still got room for one more page.",
                "Productive vibes only.",
            ],
        };
        const evening = {
            label: "Good evening",
            slogans: [
                "Wrapping up the last revisions.",
                "Golden hour for proofreading.",
                "Evening focus, evening flow.",
                "The world dims, your words shine.",
                "Last lap of the day.",
                "Slow down, polish sharp.",
                "Cozy hours, careful edits.",
                "Sunset clarity.",
                "One more headline?",
                "Twilight tinkering with copy.",
            ],
        };
        const night = {
            label: "Good night",
            slogans: [
                "Don't forget to rest.",
                "The day's almost done — and so is your draft?",
                "Bed > backlog.",
                "Save your draft, save yourself.",
                "Tomorrow's a fresh page.",
                "Wind down mode.",
                "Stars are calling.",
                "Last paragraph, then lights out.",
                "Quality sleep, quality content.",
                "Goodnight is a feature, not a typo.",
            ],
        };
        const slot = hour < 5
            ? lateNight
            : hour < 12
                ? morning
                : hour < 14
                    ? lunch
                    : hour < 18
                        ? afternoon
                        : hour < 22
                            ? evening
                            : night;
        const subtitle = slot.slogans[Math.floor(Math.random() * slot.slogans.length)] ?? "";
        return { label: slot.label, subtitle };
    }, []);
    const userFirstName = useMemo(() => {
        const user = editContext?.user;
        if (!user)
            return "";
        if (user.fullName) {
            return user.fullName.trim().split(/\s+/)[0] ?? "";
        }
        const namePart = user.name?.split("\\").pop() ?? user.name ?? "";
        return namePart;
    }, [editContext?.user]);
    const persistedLatestFeedbackLastSeenAt = editContext?.userInfo?.preferences?.latestFeedbackLastSeenAt;
    const setUserPreferences = editContext?.setUserPreferences;
    useEffect(() => {
        setLatestFeedbackLastSeenAt(persistedLatestFeedbackLastSeenAt);
    }, [persistedLatestFeedbackLastSeenAt]);
    const loadLatestFeedbackSummary = useCallback(async () => {
        const items = await loadLatestFeedbackItems();
        setLatestFeedbackItems(items);
        return items;
    }, []);
    const markLatestFeedbackSeen = useCallback((items = latestFeedbackItems) => {
        const seenAt = getLatestFeedbackSeenTimestamp(items);
        setLatestFeedbackLastSeenAt(seenAt);
        setUserPreferences?.({ latestFeedbackLastSeenAt: seenAt });
    }, [latestFeedbackItems, setUserPreferences]);
    const latestFeedbackUnreadCount = useMemo(() => {
        if (!latestFeedbackLastSeenAt)
            return latestFeedbackItems.length;
        const lastSeenTime = new Date(latestFeedbackLastSeenAt).getTime();
        if (!Number.isFinite(lastSeenTime))
            return latestFeedbackItems.length;
        return latestFeedbackItems.filter((item) => getLatestFeedbackCreatedTime(item) > lastSeenTime).length;
    }, [latestFeedbackItems, latestFeedbackLastSeenAt]);
    const handleSetActiveListTab = useCallback((index) => {
        setActiveListTab(index);
        if (index === LATEST_FEEDBACK_TAB_INDEX) {
            markLatestFeedbackSeen();
            void loadLatestFeedbackSummary()
                .then((items) => markLatestFeedbackSeen(items))
                .catch(() => { });
        }
    }, [loadLatestFeedbackSummary, markLatestFeedbackSeen]);
    useEffect(() => {
        let cancelled = false;
        loadLatestFeedbackItems()
            .then((items) => {
            if (!cancelled)
                setLatestFeedbackItems(items);
        })
            .catch(() => {
            if (!cancelled)
                setLatestFeedbackItems([]);
        });
        return () => {
            cancelled = true;
        };
    }, []);
    useEffect(() => {
        const dispose = editContext?.addSocketMessageListener?.((message) => {
            try {
                if (!isLatestFeedbackRefreshMessage(message?.type))
                    return;
                void loadLatestFeedbackSummary()
                    .then((items) => {
                    if (activeListTab === LATEST_FEEDBACK_TAB_INDEX) {
                        markLatestFeedbackSeen(items);
                    }
                })
                    .catch(() => { });
            }
            catch { }
        });
        return () => {
            try {
                dispose?.();
            }
            catch { }
        };
    }, [
        activeListTab,
        editContext?.addSocketMessageListener,
        loadLatestFeedbackSummary,
        markLatestFeedbackSeen,
    ]);
    useEffect(() => {
        getSystemStatus().then((res) => {
            if (res.data)
                setSystemStatus(res.data);
        });
    }, []);
    useEffect(() => {
        let mounted = true;
        dedupeInflight("home-quick-actions", () => getHomeQuickActions()).then((res) => {
            if (!mounted || !res.data)
                return;
            setHomeQuickActions([...res.data].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)));
        });
        return () => {
            mounted = false;
        };
    }, []);
    useEffect(() => {
        if (!canUseAi)
            return;
        let mounted = true;
        getAgentsGrouped().then((res) => {
            if (!mounted)
                return;
            setActiveAgents(res?.activeAgents ?? []);
        });
        return () => {
            mounted = false;
        };
    }, [canUseAi]);
    useEffect(() => {
        if (!editContext?.user?.name) {
            setMyTasks([]);
            return;
        }
        let cancelled = false;
        dedupeInflight("home-my-tasks", () => getMyTasks({ excludeDone: true }))
            .then(async (res) => {
            if (cancelled)
                return;
            if (res.type !== "success") {
                setMyTasks([]);
                return;
            }
            const list = (res.data ?? [])
                .map((item) => ({
                taskId: item.task.taskId,
                projectId: item.task.projectId,
                title: item.task.title,
                projectTitle: item.projectTitle ?? "",
                status: normalizeTaskStatus(item.task.status, item.task.executionState),
                updatedAt: item.task.updatedAt,
            }))
                .sort((a, b) => {
                const aTime = a.updatedAt ? new Date(a.updatedAt).getTime() : 0;
                const bTime = b.updatedAt ? new Date(b.updatedAt).getTime() : 0;
                return bTime - aTime;
            });
            setMyTasks(list);
        })
            .catch(() => {
            if (!cancelled)
                setMyTasks([]);
        });
        return () => {
            cancelled = true;
        };
    }, [editContext?.user?.name]);
    useEffect(() => {
        if (!editContext?.user?.name && !editContext?.user?.email) {
            setMyReviews([]);
            return;
        }
        let cancelled = false;
        dedupeInflight("home-my-reviews", () => getMyReviews({ excludeFinished: true }))
            .then(async (res) => {
            if (cancelled)
                return;
            if (res.type !== "success") {
                setMyReviews([]);
                return;
            }
            const list = [...(res.data ?? [])].sort((a, b) => {
                const aTime = a.createdAt ? new Date(a.createdAt).getTime() : 0;
                const bTime = b.createdAt ? new Date(b.createdAt).getTime() : 0;
                return bTime - aTime;
            });
            setMyReviews(list);
        })
            .catch(() => {
            if (!cancelled)
                setMyReviews([]);
        });
        return () => {
            cancelled = true;
        };
    }, [editContext?.user?.name, editContext?.user?.email]);
    const handleOpenReview = useCallback((review) => {
        editContext?.updateUrl({ reviewId: review.reviewId });
        editContext?.openSidebar?.("reviews");
        editContext?.switchWorkspace("editor");
    }, [editContext]);
    const handleOpenTask = useCallback((task) => {
        editContext?.switchWorkspace("taskboard");
        const snap = getTaskBoardNavSnapshot();
        if (snap.onSelectMyTask) {
            snap.onSelectMyTask({
                projectId: task.projectId,
                taskId: task.taskId,
            });
        }
        else {
            setTaskBoardNavState({
                selectedProjectId: task.projectId,
                selectedTaskId: task.taskId,
            });
        }
    }, [editContext]);
    const handleOpenAgent = useCallback((agentId) => {
        openAgentWorkspaceFromSplash(editContext, agentId);
    }, [editContext]);
    const handleOpenNotification = useCallback(async (notification) => {
        const action = resolveNotificationAction(editContext, notification);
        if (!notification.isRead) {
            void markRead(notification.id);
        }
        if (action) {
            await action.open();
        }
    }, [editContext, markRead, notifications]);
    const handleLoadSearchItem = useCallback((item) => {
        if (!editContext)
            return;
        editContext
            .loadItem({
            id: item.id,
            language: item.language ?? "en",
            version: item.version ?? 0,
        })
            .then(() => editContext.switchWorkspace("editor"));
    }, [editContext]);
    const statusIssues = systemStatus?.messages?.filter((message) => message.severity === "warning" || message.severity === "error") ?? [];
    const errorCount = statusIssues.filter((message) => message.severity === "error").length;
    const warningCount = statusIssues.filter((message) => message.severity === "warning").length;
    const openStatusPanel = useCallback(() => {
        editContext?.updateUrl({ view: "settings", ccpanel: "status" });
        editContext?.switchWorkspace("settings", {
            skipConfirmation: false,
        });
    }, [editContext]);
    const quickActionCommands = useMemo(() => {
        const actions = homeQuickActions.length > 0
            ? homeQuickActions
            : [
                {
                    id: "default-new-page",
                    title: "Create New Page",
                    description: "Start a new page in the editor",
                    svgIcon: undefined,
                    commandType: "openDialog",
                    sortOrder: 0,
                    settings: { dialogId: "newPage" },
                },
            ];
        return actions
            .map((action) => ({
            id: action.id,
            label: action.title,
            description: action.description,
            svgIcon: action.svgIcon,
            commandType: action.commandType,
            sortOrder: action.sortOrder,
            settings: action.settings ?? {},
        }))
            .filter((command) => canUseAi || command.commandType !== "agent");
    }, [canUseAi, homeQuickActions]);
    // Get workspace switching functionality
    const { visibleWorkspaces, workspaceId, switchWorkspace, previousWorkspaceId, } = editContext ?? {};
    // Prepare workspaces list for Alt+number switching (same logic as WorkspaceRail)
    const workspaces = useMemo(() => {
        if (!visibleWorkspaces)
            return [];
        const base = (visibleWorkspaces ?? [])
            .filter((w) => !w.hidden)
            // Home is accessible via the logo; keep the rail focused on other workspaces.
            .filter((w) => w.id !== "home")
            .slice()
            .sort((a, b) => (a.sortOrder ?? 100) - (b.sortOrder ?? 100));
        // Pin Settings to the absolute bottom (last), regardless of sortOrder.
        const settingsIndex = base.findIndex((w) => w.id === "settings");
        if (settingsIndex >= 0) {
            const [settings] = base.splice(settingsIndex, 1);
            if (settings)
                base.push(settings);
        }
        return base;
    }, [visibleWorkspaces]);
    const handleWorkspaceClick = useCallback((targetWorkspaceId) => {
        if (targetWorkspaceId !== workspaceId && switchWorkspace) {
            switchWorkspace(targetWorkspaceId);
        }
    }, [workspaceId, switchWorkspace]);
    // Preserve Alt+1-9 direct workspace switching (same as WorkspaceRail)
    useEffect(() => {
        if (!editContext || workspaces.length === 0)
            return;
        const handleKeyDown = (event) => {
            const isCleanAlt = event.altKey && !event.ctrlKey && !event.metaKey;
            if (!isCleanAlt)
                return;
            if (isTyping(event))
                return;
            const key = event.key;
            const numMatch = key.match(/^[1-9]$/);
            if (!numMatch)
                return;
            const index = parseInt(key, 10) - 1;
            if (index < 0 || index >= workspaces.length)
                return;
            const target = workspaces[index];
            if (!target)
                return;
            event.preventDefault();
            event.stopPropagation();
            handleWorkspaceClick(target.id);
        };
        window.addEventListener("keydown", handleKeyDown);
        return () => window.removeEventListener("keydown", handleKeyDown);
    }, [workspaces, handleWorkspaceClick, editContext]);
    const returnWorkspace = useMemo(() => {
        if (!previousWorkspaceId || previousWorkspaceId === "home")
            return undefined;
        return (visibleWorkspaces ?? []).find((workspace) => workspace.id === previousWorkspaceId && !workspace.hidden);
    }, [previousWorkspaceId, visibleWorkspaces]);
    const returnWorkspaceLabel = returnWorkspace?.title?.trim() || "workspace";
    const buildQuickActionContext = useCallback(() => {
        if (!editContext)
            return null;
        return {
            editContext,
            components: undefined,
        };
    }, [editContext]);
    const getFallbackQuickActionIcon = useCallback(() => _jsx(Layers, { strokeWidth: 1 }), []);
    const getQuickActionIcon = useCallback((command) => {
        if (isMyAgentsQuickAction(command)) {
            return _jsx(ParheliaAgentIcon, { size: 28, className: "text-current" });
        }
        if (!editContext)
            return getFallbackQuickActionIcon();
        return (renderCustomCommandIcon(command, editContext.configuration, {
            svgClassName: "h-9 w-9 [&_svg]:h-full [&_svg]:w-full",
            fallback: getFallbackQuickActionIcon(),
        }) ?? getFallbackQuickActionIcon());
    }, [editContext, getFallbackQuickActionIcon]);
    const handleQuickActionClick = useCallback(async (command) => {
        const context = buildQuickActionContext();
        if (!context || !editContext)
            return;
        await executeCustomCommand(command, editContext.configuration, context);
    }, [buildQuickActionContext, editContext]);
    const isQuickActionDisabled = useCallback((command) => {
        const context = buildQuickActionContext();
        if (!context || !editContext)
            return true;
        return isCustomCommandDisabled(command, editContext.configuration, context);
    }, [buildQuickActionContext, editContext]);
    const getQuickActionTestId = useCallback((command) => {
        const settings = command.settings;
        if (command.commandType === "openDialog" &&
            settings.dialogId === "newPage") {
            return "create-new-page-button";
        }
        return undefined;
    }, []);
    return (_jsxs("div", { className: cn(
        // Keep a scroll container, but make the background move with content (not fixed to viewport).
        "relative flex h-full min-h-0 w-full flex-col overflow-y-auto bg-local transition-colors duration-1000", isDark
            ? "bg-neutral-grey-100 text-neutral-grey-15"
            : "text-neutral-grey-100"), style: isDark
            ? undefined
            : {
                backgroundColor: "var(--color-neutral-grey-5)",
            }, children: [_jsx("style", { dangerouslySetInnerHTML: {
                    __html: `
          @keyframes logo-entrance {
            0% { 
              transform: scale(0.95) translateY(10px);
              opacity: 0;
              filter: blur(5px);
            }
            100% { 
              transform: scale(1) translateY(0);
              opacity: 1;
              filter: blur(0);
            }
          }
          @keyframes content-fade-in {
            0% { opacity: 0; transform: translateY(20px); filter: blur(5px); }
            100% { opacity: 1; transform: translateY(0); filter: blur(0); }
          }
          .animate-logo-entrance {
            animation: logo-entrance 1s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
          }
          .animate-content-entrance {
            opacity: 0;
            animation: content-fade-in 0.8s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
          }
        `,
                } }), _jsx(OpenInNewTabButton, { floating: true }), _jsxs("div", { className: "relative z-10 flex flex-1 flex-col items-center px-4 py-8 md:py-10", "data-testid": "modern-splash-screen-main-content", children: [_jsxs("div", { className: "animate-content-entrance mt-6 mb-16 w-full max-w-7xl", style: { animationDelay: "0.6s" }, children: [_jsxs("p", { className: "text-neutral-grey-50 text-base font-normal", children: [greeting.label, userFirstName ? `, ${userFirstName}` : "", _jsx("span", { className: "text-neutral-grey-50", children: "." })] }), _jsx("h1", { className: "text-neutral-grey-100 mt-3 text-[40px] leading-tight font-medium tracking-tight", children: greeting.subtitle })] }), _jsx("div", { className: "animate-content-entrance mb-12 w-full max-w-7xl", style: {
                            animationDelay: "0.9s",
                            viewTransitionName: "splash-search",
                        }, children: _jsxs("div", { className: "border-border-default relative flex flex-col rounded-xl border bg-white p-3 [&_.lucide-search:not([data-splash-search])]:!hidden [&_[data-slot=item-search-empty]]:!pl-9 [&_input]:!h-10 [&_input]:!border-transparent [&_input]:!bg-transparent [&_input]:!pl-9 [&_input]:!ring-0 [&_input]:focus:!border-transparent [&_input]:focus:!ring-0", children: [_jsx(Search, { "data-splash-search": true, className: "text-neutral-grey-100 pointer-events-none absolute top-8 left-6 z-10 h-4 w-4 -translate-y-1/2", strokeWidth: 2 }), _jsx(ItemSearch, { itemSelected: (item) => handleLoadSearchItem(item), resultClassName: "max-h-80", placeholder: "Search content" })] }) }), statusIssues.length > 0 && !statusWarningDismissed && (_jsx("div", { className: "animate-content-entrance mb-6 w-full max-w-7xl md:mb-8", style: {
                            animationDelay: "1.25s",
                            viewTransitionName: "splash-system-warning",
                        }, children: _jsxs("div", { className: "border-feedback-orange/30 bg-feedback-orange-light/90 flex items-start gap-3 rounded-xl border p-4 backdrop-blur-sm", children: [_jsx("div", { className: "mt-0.5 shrink-0", children: _jsx(AlertTriangle, { className: "text-feedback-orange h-5 w-5" }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("p", { className: "text-feedback-orange/90 text-sm font-medium", children: [errorCount > 0
                                                    ? `${errorCount} system error${errorCount !== 1 ? "s" : ""}`
                                                    : `${warningCount} system warning${warningCount !== 1 ? "s" : ""}`, warningCount > 0 && errorCount > 0
                                                    ? ` and ${warningCount} warning${warningCount !== 1 ? "s" : ""}`
                                                    : "", " ", "need attention. Review the full details in Settings."] }), _jsxs("button", { onClick: openStatusPanel, className: "text-feedback-orange/90 hover:text-feedback-orange mt-3 flex items-center gap-1.5 text-xs font-medium underline underline-offset-2 transition-colors", children: ["Open Settings Status Page", _jsx(ArrowRight, { className: "h-3 w-3" })] })] }), _jsx(CloseButton, { onClick: () => setStatusWarningDismissed(true), label: "Dismiss system warning", className: "text-feedback-orange/70 hover:bg-feedback-orange/10 hover:text-feedback-orange -mt-1 -mr-1" })] }) })), (() => {
                        const listCardClass = "mt-6 overflow-hidden rounded-xl border border-border-default bg-white shadow-sm";
                        const recentContent = (_jsx("div", { className: listCardClass, children: _jsx(RecentPages, { bare: true, compact: true }) }));
                        const latestFeedbackContent = (_jsx("div", { className: listCardClass, children: _jsx(LatestFeedback, {}) }));
                        const favoritesContent = (_jsx("div", { className: listCardClass, children: _jsx("div", { className: "min-h-[360px]", children: _jsx(Favorites, { variant: "home" }) }) }));
                        const agentsContent = (_jsx("div", { className: listCardClass, children: activeAgents.length === 0 ? (_jsxs("div", { className: "text-neutral-grey-50 flex flex-col items-center gap-2 p-12 text-center text-sm", children: [_jsx(ParheliaAgentIcon, { className: "text-neutral-grey-50 h-5 w-5", strokeWidth: 1.5 }), "No active agents"] })) : (_jsx("div", { className: homeListContainerClass, children: activeAgents.slice(0, 12).map((agent) => (_jsxs("button", { onClick: () => handleOpenAgent(agent.id), className: homeListRowClass, children: [_jsxs(HomeListIcon, { children: [_jsx(ParheliaAgentIcon, { className: "h-4 w-4", strokeWidth: 1.5 }), _jsx("span", { className: cn("ring-neutral-grey-50 absolute right-1 bottom-1 h-2 w-2 rounded-full ring-2", agentStatusDotClass(agent.status)) })] }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: agent.name || "Untitled agent" }), agent.profileName && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: agent.profileName }))] }), _jsx(HomeListBadge, { className: cn(agentStatusBadgeClass(agent.status)), children: agent.status })] }, agent.id))) })) }));
                        const notificationsContent = (_jsx("div", { className: listCardClass, children: notifications.length === 0 ? (_jsxs("div", { className: "text-neutral-grey-50 flex flex-col items-center gap-2 p-12 text-center text-sm", children: [_jsx(Bell, { className: "text-neutral-grey-50 h-5 w-5", strokeWidth: 1.5 }), "You're all caught up"] })) : (_jsx("div", { className: homeListContainerClass, children: notifications.slice(0, 12).map((n) => {
                                    const created = n.createdAt
                                        ? new Date(n.createdAt)
                                        : undefined;
                                    const dateText = created
                                        ? `${created.toLocaleDateString()} ${created.toLocaleTimeString()}`
                                        : "";
                                    return (_jsxs("button", { onClick: () => void handleOpenNotification(n), className: homeListRowClass, children: [_jsxs(HomeListIcon, { children: [_jsx(Bell, { className: "h-4 w-4", strokeWidth: 1.5 }), !n.isRead && (_jsx("span", { className: cn("ring-neutral-grey-5 group-hover:ring-highlight-10 absolute right-1 bottom-1 h-2 w-2 rounded-full ring-2", n.priority === "high"
                                                            ? "bg-feedback-red"
                                                            : "bg-highlight-100") }))] }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: n.title }), n.message && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: n.message }))] }), _jsx("div", { className: "text-neutral-grey-50 hidden shrink-0 text-xs md:block", children: dateText })] }, n.id));
                                }) })) }));
                        const myTasksContent = (_jsx("div", { className: listCardClass, children: myTasks.length === 0 ? (_jsxs("div", { className: "text-neutral-grey-50 flex flex-col items-center gap-2 p-12 text-center text-sm", children: [_jsx(ClipboardCheck, { className: "text-neutral-grey-50 h-5 w-5", strokeWidth: 1.5 }), "No tasks assigned to you"] })) : (_jsx("div", { className: homeListContainerClass, children: myTasks.slice(0, 12).map((task) => (_jsxs("button", { onClick: () => handleOpenTask(task), className: homeListRowClass, children: [_jsx(HomeListIcon, { children: _jsx(ClipboardCheck, { className: "h-4 w-4", strokeWidth: 1.5 }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: task.title }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: task.projectTitle })] }), _jsx(HomeListBadge, { className: cn(task.status === "Done"
                                                ? "bg-feedback-green-light text-feedback-green"
                                                : task.status === "InProgress"
                                                    ? "bg-feedback-green-light text-feedback-green"
                                                    : task.status === "Review"
                                                        ? "bg-feedback-orange-light text-feedback-orange"
                                                        : task.status === "Waiting"
                                                            ? "bg-feedback-orange-light text-feedback-orange"
                                                            : "bg-neutral-grey-5 text-neutral-grey-100"), children: task.status })] }, `${task.projectId}:${task.taskId}`))) })) }));
                        const myReviewsContent = (_jsx("div", { className: listCardClass, children: myReviews.length === 0 ? (_jsxs("div", { className: "text-neutral-grey-50 flex flex-col items-center gap-2 p-12 text-center text-sm", children: [_jsx(ClipboardList, { className: "text-neutral-grey-50 h-5 w-5", strokeWidth: 1.5 }), "No reviews waiting for you"] })) : (_jsx("div", { className: homeListContainerClass, children: myReviews.slice(0, 12).map((review) => {
                                    const status = review.finalDecision ??
                                        review.status ??
                                        (review.isExpired ? "Expired" : "Pending");
                                    return (_jsxs("button", { onClick: () => handleOpenReview(review), className: homeListRowClass, children: [_jsx(HomeListIcon, { children: _jsx(ClipboardList, { className: "h-4 w-4", strokeWidth: 1.5 }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: review.title || "Untitled review" }), _jsxs("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: [review.pagesCount, " page", review.pagesCount !== 1 ? "s" : "", review.reviewersCount > 0
                                                                ? ` · ${review.reviewersCount} reviewer${review.reviewersCount !== 1 ? "s" : ""}`
                                                                : ""] })] }), _jsx(HomeListBadge, { className: cn(status === "Approved"
                                                    ? "bg-feedback-green-light text-feedback-green"
                                                    : status === "Rejected"
                                                        ? "bg-feedback-red-light text-feedback-red"
                                                        : status === "Expired"
                                                            ? "bg-neutral-grey-5 text-neutral-grey-100"
                                                            : "bg-feedback-orange-light text-feedback-orange"), children: status })] }, review.reviewId));
                                }) })) }));
                        const renderCountBadge = (count) => (_jsx(CountBadge, { children: count }));
                        const tabs = [
                            { id: "recent", label: "Recent Items", content: recentContent },
                            {
                                id: "my-favorites",
                                label: "My Favorites",
                                content: favoritesContent,
                                testId: "my-favorites-tab",
                                badge: editContext?.favorites?.length
                                    ? renderCountBadge(editContext.favorites.length)
                                    : undefined,
                            },
                            {
                                id: LATEST_FEEDBACK_TAB_ID,
                                label: "Latest Feedback",
                                content: latestFeedbackContent,
                                testId: "latest-feedback-tab",
                                badge: activeListTab !== LATEST_FEEDBACK_TAB_INDEX &&
                                    latestFeedbackUnreadCount > 0
                                    ? renderCountBadge(latestFeedbackUnreadCount)
                                    : undefined,
                            },
                            {
                                id: "my-tasks",
                                label: "My Tasks",
                                content: myTasksContent,
                                badge: myTasks.length > 0
                                    ? renderCountBadge(myTasks.length)
                                    : undefined,
                            },
                            {
                                id: "my-reviews",
                                label: "My Reviews",
                                content: myReviewsContent,
                                badge: myReviews.length > 0
                                    ? renderCountBadge(myReviews.length)
                                    : undefined,
                            },
                        ];
                        if (canUseAi) {
                            tabs.push({
                                id: "agents",
                                label: "Agents",
                                content: agentsContent,
                            });
                        }
                        tabs.push({
                            id: "notifications",
                            label: "Notifications",
                            content: notificationsContent,
                            badge: unreadCount > 0 ? renderCountBadge(unreadCount) : undefined,
                        });
                        return (_jsxs("div", { className: "animate-content-entrance grid w-full max-w-7xl min-w-0 gap-x-8 md:grid-cols-[1fr_3fr]", style: {
                                animationDelay: "1.3s",
                                viewTransitionName: "splash-quick-actions",
                            }, children: [quickActionCommands.length > 0 ? (_jsxs("section", { "data-testid": "modern-splash-screen-quick-actions", className: "min-w-0", children: [_jsx("h2", { className: "border-border-default text-neutral-grey-100 mb-6 border-b px-4 pt-3 pb-3 text-[14px] font-medium tracking-tight", children: "Quick Actions" }), _jsx("div", { className: "flex flex-col gap-3", children: quickActionCommands.map((command) => {
                                                const quickActionTestId = getQuickActionTestId(command);
                                                return (_jsx(BentoTile, { icon: getQuickActionIcon(command), title: command.label, description: command.description, onClick: () => handleQuickActionClick(command), dataTestId: quickActionTestId, className: quickActionTestId === "create-new-page-button"
                                                        ? tourScrollIntoViewMarginClass
                                                        : undefined, disabled: isQuickActionDisabled(command) }, command.id));
                                            }) })] })) : (_jsx("div", { className: "hidden md:block" })), _jsxs("section", { style: { viewTransitionName: "splash-recent-pages" }, className: "mt-8 min-w-0 md:mt-0", children: [_jsx("div", { className: "md:hidden", children: _jsx(SplashSectionAccordion, { tabs: tabs, activeTab: activeListTab, setActiveTab: handleSetActiveListTab }) }), _jsx("div", { className: "hidden md:block", children: _jsx(SimpleTabs, { tabs: tabs, activeTab: activeListTab, setActiveTab: handleSetActiveListTab, variant: "large", className: "border-border-default border-b" }) })] })] }));
                    })()] })] }));
}
const renderActionIcon = (icon, size = 24, strokeWidth = 1.75) => React.isValidElement(icon) && typeof icon.type !== "string"
    ? React.cloneElement(icon, { width: size, height: size, strokeWidth })
    : icon;
export function SplashSectionAccordion({ tabs, activeTab, setActiveTab, mode = "multiple", }) {
    const [expandedTabValues, setExpandedTabValues] = useState(() => {
        const activeTabId = tabs[activeTab]?.id;
        return activeTabId ? [activeTabId] : [];
    });
    const tabIdsKey = tabs.map((tab) => tab.id).join("\u001f");
    const tabIdSet = useMemo(() => new Set(tabIdsKey ? tabIdsKey.split("\u001f") : []), [tabIdsKey]);
    const activeTabId = tabs[activeTab]?.id;
    useEffect(() => {
        setExpandedTabValues((current) => {
            const validCurrent = current.filter((value) => tabIdSet.has(value));
            const areValuesUnchanged = validCurrent.length === current.length &&
                validCurrent.every((value, index) => value === current[index]);
            if (!activeTabId) {
                if (mode === "single")
                    return current.length === 0 ? current : [];
                return areValuesUnchanged ? current : validCurrent;
            }
            if (mode === "single") {
                return current.length === 1 && current[0] === activeTabId
                    ? current
                    : [activeTabId];
            }
            const nextValues = validCurrent.length > 0 ? validCurrent : [activeTabId];
            return areValuesUnchanged && nextValues.length === current.length
                ? current
                : nextValues;
        });
    }, [activeTabId, mode, tabIdSet]);
    if (tabs.length === 0)
        return null;
    const items = tabs.map((tab, index) => {
        const isExpanded = expandedTabValues.includes(tab.id);
        return (_jsxs(AccordionItem, { value: tab.id, className: cn("overflow-hidden rounded-xl border border-b-0 bg-white/80 shadow-sm backdrop-blur-2xl transition-colors", isExpanded ? "border-border-default/60" : "border-border-default"), children: [_jsx(AccordionTrigger, { "data-testid": tab.testId, className: cn("w-full px-4 py-3 hover:no-underline", "focus-visible:ring-neutral-grey-50/70 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-white", isExpanded
                        ? "text-neutral-grey-100 bg-white"
                        : "text-neutral-grey-100 hover:bg-neutral-grey-5/80"), onClick: () => {
                        setActiveTab(index);
                    }, children: _jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [_jsx("span", { className: cn("truncate text-[14px] tracking-tight", isExpanded
                                    ? "text-neutral-grey-100 font-medium"
                                    : "text-neutral-grey-50"), children: tab.label }), tab.badge] }) }), _jsx(AccordionContent, { children: _jsx("div", { className: cn("min-h-0 overflow-hidden border-t bg-white", isExpanded ? "border-border-default" : "border-transparent"), children: tab.content }) })] }, tab.id));
    });
    if (mode === "single") {
        return (_jsx(Accordion, { type: "single", collapsible: true, value: expandedTabValues[0], onValueChange: (value) => setExpandedTabValues(value ? [value] : []), className: "space-y-3", children: items }));
    }
    return (_jsx(Accordion, { type: "multiple", value: expandedTabValues, onValueChange: setExpandedTabValues, className: "space-y-3", children: items }));
}
const BentoTile = ({ icon, title, description, onClick, dataTestId, className, disabled = false, }) => (_jsxs("button", { onClick: onClick, "data-testid": dataTestId, disabled: disabled, className: cn("group border-border-default/60 hover:border-border-default relative flex w-full cursor-pointer items-center gap-4 rounded-xl border bg-white/80 px-4 py-3 text-left backdrop-blur-sm transition-all duration-300 hover:bg-white active:scale-[0.99]", disabled && "cursor-not-allowed opacity-50", className), children: [_jsx("div", { className: "bg-neutral-grey-5 text-neutral-grey-100 group-hover:bg-neutral-grey-15 group-hover:text-neutral-grey-100 relative flex h-14 w-14 shrink-0 items-center justify-center rounded-xl transition-all duration-300 [&_svg]:transition-colors [&_svg]:duration-300", children: renderActionIcon(icon, 28, 1.75) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: [_jsx("h3", { className: "group-hover:text-neutral-grey-100 truncate text-sm font-medium text-[var(--color-neutral-grey-50)] transition-colors duration-300", children: title }), _jsx("p", { className: "text-neutral-grey-50 group-hover:text-neutral-grey-50 line-clamp-2 text-[11px] transition-colors duration-300", children: description })] })] }));
//# sourceMappingURL=ModernSplashScreen.js.map