"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 { ActionButton } from "../components/ActionButton";
import { RecentPages } from "./RecentPages";
import { ParheliaAssistantChat } from "./ParheliaAssistantChat";
import { AlertTriangle, ArrowRight, Layers } from "lucide-react";
import { ParheliaIconWhite } from "../editor/ui/ParheliaIconWhite";
import { ParheliaLogo } from "./ParheliaLogo";
import { cn } from "../lib/utils";
import { executeCustomCommand, isCustomCommandDisabled, renderCustomCommandIcon, } from "../editor/commands/customCommandConverter";
import { getHomeQuickActions, getSystemStatus, } from "../editor/services/systemService";
import { tourScrollIntoViewMarginClass } from "../tour/Tour";
import { LicenseFeatures, useFeature } from "../licensing";
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;
}
/**
 * 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 [homeQuickActions, setHomeQuickActions] = useState([]);
    useEffect(() => {
        getSystemStatus().then((res) => {
            if (res.data)
                setSystemStatus(res.data);
        });
    }, []);
    useEffect(() => {
        let mounted = true;
        getHomeQuickActions().then((res) => {
            if (!mounted || !res.data)
                return;
            setHomeQuickActions([...res.data].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)));
        });
        return () => {
            mounted = false;
        };
    }, []);
    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(() => homeQuickActions.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 (!editContext)
            return getFallbackQuickActionIcon();
        return (renderCustomCommandIcon(command, editContext.configuration, {
            svgClassName: "h-6 w-6 p-0.5",
            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-dvh w-full flex-col overflow-y-auto bg-local transition-colors duration-1000", isDark ? "bg-black text-slate-200" : "text-slate-900"), 
        // Fixed pixel stops avoid contrast shifting based on viewport height.
        style: isDark
            ? undefined
            : {
                // Keep the default (below-gradient) background slightly gray for better card contrast.
                backgroundColor: "#f1f5f9", // slate-100
                backgroundImage: "radial-gradient(circle at 80% 600px, rgba(236, 72, 153, 0.05), transparent 50%), " +
                    "radial-gradient(circle at 20% 500px, rgba(59, 130, 246, 0.08), transparent 50%), " +
                    "linear-gradient(to bottom, #000000 0px, #050b18 500px, #0f172a 1000px, #f1f5f9 1700px)",
            }, 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;
          }
        `,
                } }), _jsxs("div", { className: "relative z-10 flex flex-1 flex-col items-center px-4 py-8 md:py-10", children: [_jsx("div", { className: "mb-10 flex w-full max-w-6xl flex-col items-center justify-center pt-10 pb-8 md:mb-12 md:pt-16", children: _jsxs("div", { className: "animate-logo-entrance flex flex-col items-center gap-4 md:gap-6", children: [_jsxs("div", { className: "relative", children: [_jsx("div", { className: "absolute -inset-8 animate-pulse rounded-full bg-blue-500/10 blur-3xl" }), _jsx(ParheliaIconWhite, { size: 64, className: "relative z-10 drop-shadow-[0_0_15px_rgba(255,255,255,0.2)] md:size-[90px]" })] }), _jsxs("div", { className: "flex flex-col items-center", children: [_jsx(ParheliaLogo, { textClassName: "text-4xl md:text-6xl tracking-widest text-white" }), _jsx("p", { className: "mt-4 text-center text-[10px] font-light tracking-[0.4em] text-slate-500 uppercase md:mt-5 md:text-xs", children: "Experience your content in a new light" })] })] }) }), canUseAi && (_jsx("div", { className: "animate-content-entrance mb-12 w-full max-w-5xl md:mb-16", style: { animationDelay: "1.1s" }, children: _jsx(ParheliaAssistantChat, { className: "w-full" }) })), statusIssues.length > 0 && (_jsx("div", { className: "animate-content-entrance mb-6 w-full max-w-5xl md:mb-8", style: {
                            animationDelay: "1.25s",
                            viewTransitionName: "splash-system-warning",
                        }, children: _jsxs("div", { className: "flex items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-50/90 p-4 shadow-sm backdrop-blur-sm", children: [_jsx("div", { className: "mt-0.5 shrink-0", children: _jsx(AlertTriangle, { className: "h-5 w-5 text-amber-600" }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("p", { className: "text-sm font-medium text-amber-900/90", 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: "mt-3 flex items-center gap-1.5 text-xs font-semibold text-purple-600 transition-colors hover:text-purple-700", children: ["Open Settings Status Page", _jsx(ArrowRight, { className: "h-3 w-3" })] })] })] }) })), quickActionCommands.length > 0 && (_jsxs("div", { className: "animate-content-entrance mb-8 w-full max-w-5xl md:mb-12", style: {
                            animationDelay: "1.3s",
                            viewTransitionName: "splash-quick-actions",
                        }, children: [_jsx("h2", { className: cn("mb-4 text-center text-sm font-medium tracking-widest uppercase transition-colors duration-1000", isDark ? "text-slate-400" : "text-slate-400"), children: "Quick Actions" }), _jsx("div", { className: "flex flex-wrap justify-center gap-3 md:gap-4", children: quickActionCommands.map((command, index) => {
                                    const quickActionTestId = getQuickActionTestId(command);
                                    return (_jsx("div", { className: cn("w-[calc(50%-6px)] md:w-[calc(33.333%-10.66px)]", index === quickActionCommands.length - 1 &&
                                            quickActionCommands.length % 2 !== 0 &&
                                            "md:mx-auto", index === quickActionCommands.length - 1 &&
                                            quickActionCommands.length % 2 !== 0 &&
                                            "max-md:mx-auto"), children: _jsx(ActionCard, { icon: getQuickActionIcon(command), title: command.label, description: command.description, onClick: () => handleQuickActionClick(command), dataTestId: quickActionTestId, className: quickActionTestId === "create-new-page-button"
                                                ? tourScrollIntoViewMarginClass
                                                : undefined, isDark: isDark, disabled: isQuickActionDisabled(command) }) }, command.id));
                                }) })] })), _jsx("div", { className: "animate-content-entrance w-full max-w-5xl", style: {
                            animationDelay: "1.5s",
                            viewTransitionName: "splash-recent-pages",
                        }, children: _jsx(RecentPages, {}) }), returnWorkspace && (_jsx("div", { className: "animate-content-entrance mt-8 flex flex-col gap-3 md:mt-12", style: {
                            animationDelay: "1.7s",
                            viewTransitionName: "splash-footer",
                        }, children: _jsxs(ActionButton, { variant: "defaultInverted", onClick: () => {
                                switchWorkspace?.(returnWorkspace.id);
                            }, children: [_jsx(Layers, { strokeWidth: 2, className: "mr-0.5 h-4 w-4" }), "Return to ", returnWorkspaceLabel] }) }))] })] }));
}
const ActionCard = ({ icon, title, description, onClick, dataTestId, className, isDark, disabled = false, }) => {
    return (_jsxs("button", { onClick: onClick, "data-testid": dataTestId, disabled: disabled, className: cn("group relative flex h-full w-full cursor-pointer flex-col items-center gap-3 rounded-2xl border p-5 transition-all duration-500 active:scale-[0.98] md:p-6", disabled && "cursor-not-allowed opacity-50", isDark
            ? "border-white/10 bg-white/5 backdrop-blur-md hover:border-white/20 hover:bg-white/10"
            : "border-white/60 bg-white/70 shadow-sm backdrop-blur-sm hover:border-purple-200/50 hover:bg-white/90 hover:shadow-xl hover:shadow-purple-500/10", className), children: [_jsx("div", { className: "absolute inset-0 -z-10 rounded-2xl bg-linear-to-br from-purple-500/0 to-blue-500/0 opacity-0 blur-xl transition-all duration-500 group-hover:from-purple-500/5 group-hover:to-blue-500/5 group-hover:opacity-100" }), _jsx("div", { className: cn("relative flex h-12 w-12 items-center justify-center rounded-xl transition-all duration-500 group-hover:scale-110 md:h-14 md:w-14", isDark
                    ? "bg-slate-800/50 text-purple-400 shadow-inner group-hover:bg-purple-600 group-hover:text-white"
                    : "bg-slate-50/80 text-purple-600 shadow-sm group-hover:bg-purple-600 group-hover:text-white group-hover:shadow-lg group-hover:shadow-purple-500/30"), children: React.isValidElement(icon) && typeof icon.type !== "string"
                    ? React.cloneElement(icon, {
                        width: 24,
                        height: 24,
                        strokeWidth: 1.5,
                    })
                    : icon }), _jsxs("div", { className: "flex flex-col items-center gap-1 text-center", children: [_jsx("h3", { className: cn("text-sm font-semibold tracking-tight transition-colors duration-500 md:text-base", isDark ? "text-slate-200" : "text-slate-900"), children: title }), _jsx("p", { className: cn("max-w-[230px] text-[11px] leading-tight transition-colors duration-500 md:text-xs", isDark
                            ? "text-slate-400"
                            : "text-slate-500 group-hover:text-slate-600"), children: description })] })] }));
};
//# sourceMappingURL=ModernSplashScreen.js.map