"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { EditorShell } from "./client/EditorShell";
import { useEffect, useState, useRef, useCallback } from "react";
import { getUserInfo } from "./services/editService";
import { getSystemStatus, getEditorSettings, saveUserPreferences, } from "./services/systemService";
import uuid from "react-uuid";
import { configureForLicense, getConfiguration } from "../config/config";
import { useMediaQuery } from "./client/hooks/useMediaQuery";
import { MigrationsView } from "./MigrationsView";
import { SetupWizard } from "./SetupWizard";
import { AdminRequiredView } from "./AdminRequiredView";
import { getLicenseStatus } from "../licensing/licenseService";
import { LicenseProvider } from "../licensing/LicenseContext";
import { LicenseOverlay } from "../licensing/LicenseOverlay";
import { EditorLoadingOverlay } from "./EditorLoadingOverlay";
export function Editor({ configure, className, page, children, }) {
    const [config, setConfig] = useState();
    const [userInfo, setUserInfo] = useState();
    const [systemStatus, setSystemStatus] = useState();
    const [parheliaSettings, setParheliaSettings] = useState();
    const [parheliaSettingsLoaded, setParheliaSettingsLoaded] = useState(false);
    const [hasLicenseError, setHasLicenseError] = useState(false);
    const [licenseStatus, setLicenseStatus] = useState(undefined);
    // Same breakpoint as EditorShell — EditContext is not available here (provider is inside Shell)
    const isMobile = useMediaQuery("(max-width: 767px)");
    const hasInitializedRef = useRef(false);
    const [sessionId] = useState(() => {
        if (typeof window === "undefined") {
            return uuid();
        }
        const existingSessionId = sessionStorage.getItem("sessionId");
        if (existingSessionId) {
            return existingSessionId;
        }
        const nextSessionId = uuid();
        sessionStorage.setItem("sessionId", nextSessionId);
        return nextSessionId;
    });
    useEffect(() => {
        // Ensure this only runs once, even in Strict Mode
        if (hasInitializedRef.current) {
            return;
        }
        hasInitializedRef.current = true;
        // Get user info, system status, and editor settings
        getUserInfo().then((result) => {
            if (result.type === "success" && result.data) {
                setUserInfo(result.data);
            }
            else if (result.type === "unauthorized") {
                // Authentication failure - redirect to login
                window.location.href = "/sitecore/login";
            }
            else if (result.type === "error") {
                // License error or other error - don't redirect
                // Check if it's a license error by checking the summary
                const isLicenseError = result.summary?.toLowerCase().includes("license") ||
                    result.details?.toLowerCase().includes("license");
                if (isLicenseError) {
                    // Set flag to render LicenseProvider even without userInfo
                    setHasLicenseError(true);
                }
                // The license:validation-failed event will be handled by LicenseProvider
                // Don't set userInfo so component doesn't render the full editor
                // The LicenseProvider will show the activation dialog
            }
        });
        getSystemStatus().then((status) => {
            if (status.data) {
                setSystemStatus(status.data);
            }
        });
        getEditorSettings()
            .then((settings) => {
            if (settings.data) {
                setParheliaSettings(settings.data);
            }
        })
            .catch((error) => {
            console.error("Failed to load editor settings:", error);
        })
            .finally(() => {
            setParheliaSettingsLoaded(true);
        });
        getLicenseStatus()
            .then((status) => {
            setLicenseStatus(status);
        })
            .catch((error) => {
            console.error("Failed to preload license status:", error);
            setLicenseStatus(null);
        });
    }, []);
    // Check if there are database/migration issues that need to be resolved
    const hasMigrationIssue = systemStatus?.messages.some((m) => m.severity === "error" &&
        (m.message.includes("Pending DB migrations") ||
            m.message.includes("Table missing") ||
            m.message.includes("Table missing columns")));
    // Check if settings item exists (only if no migration issues)
    const settingsMissing = !hasMigrationIssue && systemStatus?.setupComplete === false;
    // Handle migrations/setup complete - refresh the bootstrap state a reload would fetch.
    const handleRefreshStatus = useCallback(() => {
        getSystemStatus({ force: true }).then((status) => {
            if (status.data) {
                setSystemStatus(status.data);
            }
        });
        setParheliaSettingsLoaded(false);
        getEditorSettings()
            .then((settings) => {
            if (settings.data) {
                setParheliaSettings(settings.data);
            }
        })
            .catch((error) => {
            console.error("Failed to refresh editor settings:", error);
        })
            .finally(() => {
            setParheliaSettingsLoaded(true);
        });
        getLicenseStatus()
            .then((status) => {
            setLicenseStatus(status);
            if (status.isValid || status.licensingDisabled) {
                setHasLicenseError(false);
            }
        })
            .catch((error) => {
            console.error("Failed to refresh license status:", error);
            setLicenseStatus(null);
        });
        getUserInfo().then((result) => {
            if (result.type === "success" && result.data) {
                setUserInfo(result.data);
                setHasLicenseError(false);
            }
            else if (result.type === "unauthorized") {
                window.location.href = "/sitecore/login";
            }
            else if (result.type === "error") {
                const isLicenseError = result.summary?.toLowerCase().includes("license") ||
                    result.details?.toLowerCase().includes("license") ||
                    false;
                setHasLicenseError(isLicenseError);
            }
        });
    }, []);
    useEffect(() => {
        if (!userInfo || !systemStatus || licenseStatus === undefined)
            return;
        // Don't configure if there are migration or setup issues
        if (hasMigrationIssue || settingsMissing)
            return;
        const baseConfig = configure({
            configuration: getConfiguration(isMobile),
            userInfo: userInfo,
        });
        const config = configureForLicense(baseConfig, licenseStatus);
        setConfig(config);
    }, [
        userInfo,
        systemStatus,
        licenseStatus,
        configure,
        hasMigrationIssue,
        settingsMissing,
        isMobile,
    ]);
    // Show setup wizard if settings are missing (includes integrated license activation)
    // This takes priority over license overlay because setup includes license steps
    if (settingsMissing) {
        if (userInfo?.user.isAdministrator) {
            return (_jsx(SetupWizard, { onComplete: handleRefreshStatus, settingsExist: systemStatus.settingsExist }));
        }
        else if (userInfo) {
            return _jsx(AdminRequiredView, {});
        }
        // Safety fallback: if user info failed due license checks during setup,
        // still show setup wizard (license steps are integrated there).
        if (hasLicenseError) {
            return (_jsx(SetupWizard, { onComplete: handleRefreshStatus, settingsExist: systemStatus.settingsExist }));
        }
        // If setup is needed but user info is still loading, wait.
        return _jsx(EditorLoadingOverlay, {});
    }
    // When setup is complete, /parhelia/userinfo can fail with a license-only error (no
    // UserInfo payload). `hasLicenseError` is set but `userInfo` stays unset — still show
    // the activation overlay so we never render a blank shell forever.
    if ((!userInfo && !hasLicenseError) || !systemStatus) {
        return _jsx(EditorLoadingOverlay, {});
    }
    // License-only userinfo failure: no UserInfo to render shell; show activation UI first.
    // (Must run before MigrationsView, which requires `userInfo`.)
    if (hasLicenseError) {
        return (_jsx(LicenseProvider, { initialLicenseStatus: licenseStatus, initialStatusLoaded: licenseStatus != null, children: _jsx(LicenseOverlay, {}) }));
    }
    // Narrowing: after `hasLicenseError` is false, line 181 implies `userInfo` is set.
    if (!userInfo)
        return _jsx(EditorLoadingOverlay, {});
    if (hasMigrationIssue) {
        return (_jsx(MigrationsView, { isAdmin: userInfo.user.isAdministrator ?? false, onMigrationsComplete: handleRefreshStatus }));
    }
    if (!config)
        return _jsx(EditorLoadingOverlay, {});
    return (_jsx(EditorShell, { configuration: config, className: className, item: page, sessionId: sessionId, userInfo: userInfo, userPreferences: userInfo.preferences, initialLicenseStatus: licenseStatus, initialLicenseStatusLoaded: licenseStatus != null, parheliaSettings: parheliaSettings, parheliaSettingsLoaded: parheliaSettingsLoaded, setUserPreferences: (preferences) => {
            const newPreferences = { ...userInfo.preferences, ...preferences };
            saveUserPreferences(newPreferences);
            setUserInfo({ ...userInfo, preferences: newPreferences });
        }, children: children }));
}
//# sourceMappingURL=Editor.js.map