import { useState, useEffect, useCallback, useRef } from "@wordpress/element";
import { useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { Button, TabPanel, Modal, Icon, Notice } from "@wordpress/components";
import { __, sprintf } from "@wordpress/i18n";
import { check, cancelCircleFilled as error } from "@wordpress/icons";
import apiFetch from "@wordpress/api-fetch";
import ecwLogo from "../../../images/ecw-logo.svg";
import { getProductBranding } from "@cache-autopilot/warmup-branding";

import Notices from "./components/Notices";
import WarmupTab from "./tabs/WarmupTab";
import LoggingTab from "./tabs/LoggingTab";
import PrioritiesTab from "./tabs/PrioritiesTab";
import DiagnosticsTab from "./tabs/DiagnosticsTab";
import AdvancedTab from "./tabs/AdvancedTab";
import { initTableScrollShadows } from "./utils/responsiveTables";
import {
    DIAGNOSTICS_PATH,
    PRIORITY_PAGES_PATH,
    RECENT_LOGS_PATH,
    REST_PATH,
    RUN_FULL_PATH,
    SERVER_TIME_PATH,
    SITEMAP_STATUS_PATH,
    SITEMAP_STATUS_REFRESH_PATH,
} from "./utils/rest-paths";
import { isRefreshInProgressError } from "./utils/rest-errors";
import { parseNonNegativeInt } from "./utils/number";
import {
    hasInvalidSitemapUrl,
    parseSitemapUrls,
    SITEMAP_PRESENCE_EVENT,
} from "./utils/sitemap";
import { buildCleanPayload, tabKeysMap } from "./utils/payload";
import { hasDirtyOptions } from "./utils/dirty-state";
import { createModeRequestCoordinator } from "./utils/mode-request-coordinator";

const OPTION_KEY = "ekesto_cache_warmup";

const timingsEnabled = () =>
    typeof window !== "undefined"
    && window.location.search.includes("ekesto_ecw_timing=1");

const nowMs = () => (
    typeof window !== "undefined"
    && window.performance
    && typeof window.performance.now === "function"
)
    ? window.performance.now()
    : Date.now();

const logTiming = (label, startedAt, meta = {}) => {
    if (!timingsEnabled()) {
        return;
    }

    const durationMs = Math.round((nowMs() - startedAt) * 10) / 10;
    console.info(`[ECW timing] ${label}: ${durationMs}ms`, meta);
};

const isDocumentVisible = () => (
    typeof document === "undefined" || document.visibilityState === "visible"
);

export default function App() {
    const pluginVersion = typeof window.EkestoCacheWarmup?.pluginVersion === "string"
        ? window.EkestoCacheWarmup.pluginVersion
        : "";
    const isPremium = window.EkestoCacheWarmup?.isPremium === true;
    const defaults = window.EkestoCacheWarmup?.defaults || {};
    const initial = window.EkestoCacheWarmup?.initial || defaults;
    const [options, setOptions] = useState(initial);
    const [originalOptions, setOriginalOptions] = useState(initial);
    const [isSaving, setIsSaving] = useState(false);
    const [runFullBusy, setRunFullBusy] = useState(false);
    const [showResetModal, setShowResetModal] = useState(false);
    const [sitemapApiWarning, setSitemapApiWarning] = useState(null);
    const [sitemapApiHasSitemap, setSitemapApiHasSitemap] = useState(null);
    const [sitemapStatus, setSitemapStatus] = useState(null);
    const sitemapStatusRequestRef = useRef(null);
    const initialSitemapBootstrapRequestRef = useRef(null);
    const [sitemapRefreshTrigger, setSitemapRefreshTrigger] = useState(0);
    const [priorityPages, setPriorityPages] = useState([]);
    const [priorityPagesLoading, setPriorityPagesLoading] = useState(false);
    const [priorityPagesError, setPriorityPagesError] = useState(null);
    const [priorityPagesLoaded, setPriorityPagesLoaded] = useState(false);
    const priorityPagesRequestRef = useRef(null);
    const [recentLogs, setRecentLogs] = useState([]);
    const [recentLogsLoading, setRecentLogsLoading] = useState(false);
    const [recentLogsError, setRecentLogsError] = useState(null);
    const [recentLogsLoaded, setRecentLogsLoaded] = useState(false);
    const [recentLogsMode, setRecentLogsMode] = useState("default");
    const [recentLogsMeta, setRecentLogsMeta] = useState({
        logsTotal: 0,
        logsShown: 0,
        logsOverflow: 0,
        logsTruncated: false,
    });
    const recentLogsRequestCoordinatorRef = useRef(null);
    if (recentLogsRequestCoordinatorRef.current === null) {
        recentLogsRequestCoordinatorRef.current = createModeRequestCoordinator("default");
    }
    const [logsTimezone, setLogsTimezone] = useState("UTC");
    const [logsTimezoneLoaded, setLogsTimezoneLoaded] = useState(false);
    const logsTimezoneRequestRef = useRef(null);
    const [queueRuntime, setQueueRuntime] = useState({
        queue_active: false,
        run_now_actionable: false,
        last_activity_ts: 0,
    });
    const [queueRuntimeLoaded, setQueueRuntimeLoaded] = useState(false);
    const [isPageVisible, setIsPageVisible] = useState(isDocumentVisible);
    const queueRuntimeRequestRef = useRef(null);
    const previousPageVisibleRef = useRef(isPageVisible);
    const previousQueueActiveRef = useRef(false);
    const previousQueueActivityRef = useRef(null);

    // Tab state with URL + local storage sync.
    const tabNames = ["warmup", "priorities", "logging", "diagnostics", "advanced"];
    const tabStorageKey = "ekesto_cache_warmup_last_tab";
    const normalizeTab = (value) => (
        typeof value === "string" && tabNames.includes(value) ? value : null
    );
    const getTabFromUrl = () => {
        try {
            const fromQuery = normalizeTab(
                new URLSearchParams(window.location.search).get("tab"),
            );
            if (fromQuery) {
                return fromQuery;
            }
        } catch {
            // Ignore URL parsing errors and continue to hash fallback.
        }

        return normalizeTab((window.location.hash || "").replace("#", ""));
    };
    const getTabFromStorage = () => {
        try {
            return normalizeTab(window.localStorage.getItem(tabStorageKey));
        } catch {
            return null;
        }
    };
    const getInitialTab = () => (
        getTabFromUrl() || getTabFromStorage() || tabNames[0]
    );
    const [selectedTab, setSelectedTab] = useState(getInitialTab);

    useEffect(() => {
        try {
            const url = new URL(window.location.href);
            url.searchParams.set("tab", selectedTab);
            url.hash = selectedTab;
            window.history.replaceState({}, "", url.toString());
        } catch {
            window.location.hash = selectedTab;
        }

        try {
            window.localStorage.setItem(tabStorageKey, selectedTab);
        } catch {
            // Ignore storage errors so navigation keeps working.
        }
    }, [selectedTab]);

    const { createNotice, createSuccessNotice, createErrorNotice } = useDispatch(noticesStore);

    // Load settings on mount
    useEffect(() => {
        apiFetch({ path: REST_PATH })
            .then((response) => {
                const data = response[OPTION_KEY];
                if (data && typeof data === "object") {
                    setOptions(data);
                    setOriginalOptions(data);
                }
            })
            .catch(console.error);
    }, []);

    useEffect(() => {
        if (typeof document === "undefined") {
            return undefined;
        }

        const handleVisibilityChange = () => {
            setIsPageVisible(document.visibilityState === "visible");
        };

        document.addEventListener("visibilitychange", handleVisibilityChange);

        return () => {
            document.removeEventListener("visibilitychange", handleVisibilityChange);
        };
    }, []);

    const dispatchSitemapPresence = (hasSitemap) => {
        if (typeof window === "undefined") {
            return;
        }

        window.dispatchEvent(
            new CustomEvent(SITEMAP_PRESENCE_EVENT, {
                detail: { hasSitemap: hasSitemap === true },
            }),
        );
    };

    const applySitemapStatus = useCallback((response) => {
        if (!response || typeof response !== "object") {
            setSitemapApiWarning(null);
            setSitemapApiHasSitemap(null);
            setSitemapStatus(null);
            return;
        }

        const normalized = {
            ...response,
            post_types: Array.isArray(response.post_types) ? response.post_types : [],
            sitemap_urls: Array.isArray(response.sitemap_urls) ? response.sitemap_urls : [],
        };

        setSitemapStatus(normalized);
        setSitemapApiWarning(normalized.warning || null);
        setSitemapApiHasSitemap(
            typeof normalized.has_sitemap === "boolean"
                ? normalized.has_sitemap
                : null,
        );
    }, []);

    const fetchSitemapStatus = useCallback(async () => {
        if (sitemapStatusRequestRef.current) {
            return sitemapStatusRequestRef.current;
        }

        const startedAt = nowMs();
        const request = apiFetch({ path: SITEMAP_STATUS_PATH })
            .then((response) => {
                applySitemapStatus(response);
                logTiming("GET /post-types-from-sitemap", startedAt, {
                    postTypes: Array.isArray(response?.post_types)
                        ? response.post_types.length
                        : 0,
                });
                return response;
            })
            .finally(() => {
                sitemapStatusRequestRef.current = null;
            });

        sitemapStatusRequestRef.current = request;
        return request;
    }, [applySitemapStatus]);

    const refreshSitemapStatus = useCallback(async () => {
        const startedAt = nowMs();
        const response = await apiFetch({
            path: SITEMAP_STATUS_REFRESH_PATH,
            method: "POST",
        });
        applySitemapStatus(response);
        logTiming("POST /post-types-from-sitemap/refresh", startedAt, {
            postTypes: Array.isArray(response?.post_types)
                ? response.post_types.length
                : 0,
        });
        return response;
    }, [applySitemapStatus]);

    const bootstrapInitialSitemapIndex = useCallback(async ({ showNotice = true } = {}) => {
        if (initialSitemapBootstrapRequestRef.current) {
            return initialSitemapBootstrapRequestRef.current;
        }

        if (showNotice) {
            createNotice(
                "info",
                __("Settings saved. Building sitemap index.", "cache-autopilot"),
                { type: "snackbar" },
            );
        }

        const request = refreshSitemapStatus()
            .then((response) => {
                if (showNotice) {
                    const warning = typeof response?.warning === "string" && response.warning !== ""
                        ? response.warning
                        : null;
                    const lastError = typeof response?.last_error === "string" && response.last_error !== ""
                        ? response.last_error
                        : null;

                    if (warning || lastError) {
                        createNotice(
                            "warning",
                            __("Settings saved. Cache Autopilot will keep trying in the background.", "cache-autopilot"),
                            { type: "snackbar" },
                        );
                    } else {
                        createSuccessNotice(__("Sitemap data refreshed.", "cache-autopilot"), {
                            type: "snackbar",
                            icon: <Icon icon={check} />,
                        });
                    }
                }

                return response;
            })
            .catch((err) => {
                if (isRefreshInProgressError(err)) {
                    return null;
                }

                if (showNotice) {
                    createNotice(
                        "warning",
                        __("Settings saved. Cache Autopilot will keep trying in the background.", "cache-autopilot"),
                        { type: "snackbar" },
                    );
                }

                return null;
            })
            .finally(() => {
                initialSitemapBootstrapRequestRef.current = null;
            });

        initialSitemapBootstrapRequestRef.current = request;
        return request;
    }, [createNotice, createSuccessNotice, refreshSitemapStatus]);

    const fetchPriorityPages = useCallback(async ({ force = false } = {}) => {
        if (!force && priorityPagesLoaded) {
            return [];
        }

        if (priorityPagesRequestRef.current) {
            return priorityPagesRequestRef.current;
        }

        setPriorityPagesLoading(true);
        setPriorityPagesError(null);

        const startedAt = nowMs();
        const path = force ? `${PRIORITY_PAGES_PATH}?refresh=1` : PRIORITY_PAGES_PATH;
        const request = apiFetch({ path, parse: false })
            .then(async (rawResponse) => {
                const payload = await rawResponse.json();
                const pages = Array.isArray(payload?.pages) ? payload.pages : [];
                const source = rawResponse.headers.get("x-ecw-pages-source") || "unknown";
                const serverDurationMs = rawResponse.headers.get("x-ecw-pages-duration-ms");

                setPriorityPages(pages);
                setPriorityPagesLoaded(true);

                logTiming("GET /pages", startedAt, {
                    count: pages.length,
                    source,
                    serverDurationMs,
                });

                return pages;
            })
            .catch((error) => {
                setPriorityPagesError(error?.message || __("Failed to load pages.", "cache-autopilot"));
                throw error;
            })
            .finally(() => {
                setPriorityPagesLoading(false);
                priorityPagesRequestRef.current = null;
            });

        priorityPagesRequestRef.current = request;
        return request;
    }, [priorityPagesLoaded]);

    const fetchRecentLogs = useCallback(async ({
        force = false,
        mode = recentLogsRequestCoordinatorRef.current.getSelectedMode(),
        surfaceError = true,
        ensureFresh = false,
        showLoading = true,
    } = {}) => {
        const normalizedMode = mode === "all" ? "all" : "default";

        if (!force && recentLogsLoaded && normalizedMode === recentLogsMode) {
            return [];
        }

        return recentLogsRequestCoordinatorRef.current.run(
            normalizedMode,
            () => {
                if (showLoading) {
                    setRecentLogsLoading(true);
                    setRecentLogsError(null);
                }

                const startedAt = nowMs();
                const path = normalizedMode === "all"
                    ? `${RECENT_LOGS_PATH}?all=1`
                    : RECENT_LOGS_PATH;

                return apiFetch({ path })
                    .then((response) => {
                        const logs = Array.isArray(response?.logs) ? response.logs : [];
                        const logsTotal = parseNonNegativeInt(response?.logs_total, logs.length);
                        const logsShown = parseNonNegativeInt(response?.logs_shown, logs.length);
                        const logsOverflow = parseNonNegativeInt(
                            response?.logs_overflow,
                            Math.max(0, logsTotal - logsShown),
                        );
                        const logsTruncated = response?.logs_truncated === true;

                        setRecentLogs(logs);
                        setRecentLogsLoaded(true);
                        setRecentLogsMode(normalizedMode);
                        setRecentLogsMeta({
                            logsTotal,
                            logsShown,
                            logsOverflow,
                            logsTruncated,
                        });

                        logTiming("GET /logs", startedAt, {
                            count: logs.length,
                            mode: normalizedMode,
                            total: logsTotal,
                            overflow: logsOverflow,
                            truncated: logsTruncated,
                        });

                        return logs;
                    })
                    .catch((error) => {
                        if (surfaceError) {
                            setRecentLogsError(error?.message || __("Failed to load recent runs.", "cache-autopilot"));
                        }
                        throw error;
                    })
                    .finally(() => {
                        if (showLoading) {
                            setRecentLogsLoading(false);
                        }
                    });
            },
            { ensureFresh: force && ensureFresh },
        );
    }, [recentLogsLoaded, recentLogsMode]);

    const fetchLogsTimezone = useCallback(async ({ force = false } = {}) => {
        if (!force && logsTimezoneLoaded) {
            return logsTimezone;
        }

        if (logsTimezoneRequestRef.current) {
            return logsTimezoneRequestRef.current;
        }

        const startedAt = nowMs();
        const request = apiFetch({ path: SERVER_TIME_PATH })
            .then((response) => {
                const tz = typeof response?.tz === "string" && response.tz
                    ? response.tz
                    : "UTC";
                setLogsTimezone(tz);
                setLogsTimezoneLoaded(true);

                logTiming("GET /server-time", startedAt, { tz });
                return tz;
            })
            .catch((error) => {
                throw error;
            })
            .finally(() => {
                logsTimezoneRequestRef.current = null;
            });

        logsTimezoneRequestRef.current = request;
        return request;
    }, [logsTimezoneLoaded, logsTimezone]);

    const fetchQueueRuntime = useCallback(async () => {
        if (queueRuntimeRequestRef.current) {
            return queueRuntimeRequestRef.current;
        }

        const request = apiFetch({ path: DIAGNOSTICS_PATH })
            .then((diagnostics) => {
                const normalized = {
                    queue_active: diagnostics?.queue_active === true,
                    run_now_actionable: diagnostics?.run_now_actionable === true,
                    queue_status: typeof diagnostics?.queue_status === "string"
                        ? diagnostics.queue_status
                        : (diagnostics?.queue_active === true ? "running" : "idle"),
                    run_id: typeof diagnostics?.run_id === "string"
                        ? diagnostics.run_id
                        : "",
                    last_activity_ts: parseNonNegativeInt(
                        diagnostics?.last_activity_ts,
                        0,
                    ),
                };

                setQueueRuntime(normalized);
                setQueueRuntimeLoaded(true);

                return normalized;
            })
            .finally(() => {
                queueRuntimeRequestRef.current = null;
            });

        queueRuntimeRequestRef.current = request;
        return request;
    }, []);

    // Load sitemap warning on mount
    useEffect(() => {
        fetchSitemapStatus()
            .catch(console.error);
    }, [fetchSitemapStatus]);

    // Refresh sitemap warning after a save.
    useEffect(() => {
        if (sitemapRefreshTrigger > 0) {
            fetchSitemapStatus()
                .catch(console.error);
        }
    }, [sitemapRefreshTrigger, fetchSitemapStatus]);

    // Load priority pages once per settings-session when the Priorities tab is opened.
    useEffect(() => {
        if (selectedTab === "priorities") {
            fetchPriorityPages()
                .catch(console.error);
        }
    }, [selectedTab, fetchPriorityPages]);

    // Load recent logs and timezone once per settings-session when the Log tab is opened.
    useEffect(() => {
        if (selectedTab === "logging") {
            fetchRecentLogs()
                .catch(console.error);
            fetchLogsTimezone()
                .catch(console.error);
            setQueueRuntimeLoaded(false);
            fetchQueueRuntime()
                .catch(console.error);
        }
    }, [selectedTab, fetchRecentLogs, fetchLogsTimezone, fetchQueueRuntime]);

    useEffect(() => {
        const wasPageVisible = previousPageVisibleRef.current;
        previousPageVisibleRef.current = isPageVisible;

        if (wasPageVisible || !isPageVisible || selectedTab !== "logging") {
            return;
        }

        fetchRecentLogs({
            force: true,
            ensureFresh: true,
            surfaceError: false,
            showLoading: false,
        })
            .catch(console.error);
    }, [selectedTab, isPageVisible, fetchRecentLogs]);

    useEffect(() => {
        if (selectedTab !== "logging" || !isPageVisible) {
            return undefined;
        }

        const intervalId = window.setInterval(() => {
            fetchQueueRuntime()
                .then((diagnostics) => {
                    const wasActive = previousQueueActiveRef.current;
                    const isActive = diagnostics.queue_active === true;
                    const previousActivityTs = previousQueueActivityRef.current;
                    const activityTs = diagnostics.last_activity_ts;
                    const activityChanged = previousActivityTs === null
                        ? activityTs > 0
                        : activityTs !== previousActivityTs;

                    previousQueueActiveRef.current = isActive;
                    previousQueueActivityRef.current = activityTs;

                    if (isActive || wasActive || activityChanged) {
                        return fetchRecentLogs({
                            force: true,
                            ensureFresh: true,
                            surfaceError: false,
                            showLoading: false,
                        });
                    }

                    return undefined;
                })
                .catch(console.error);
        }, 2000);

        return () => {
            window.clearInterval(intervalId);
        };
    }, [selectedTab, isPageVisible, fetchQueueRuntime, fetchRecentLogs]);

    const syncAdminBarWarmupState = useCallback((enabled) => {
        if (typeof enabled !== "boolean") {
            return;
        }

        const rootLink = document.querySelector(
            "#wp-admin-bar-ekesto-cache-warmup > .ab-item",
        );
        const stateLink = document.querySelector(
            "#wp-admin-bar-ekesto-cache-warmup-state > .ab-item",
        );
        const toggleLink = document.querySelector(
            "#wp-admin-bar-ekesto-cache-warmup-toggle > .ab-item",
        );
        const runFullNode = document.querySelector(
            "#wp-admin-bar-ekesto-cache-warmup-run-full",
        );

        if (stateLink) {
            stateLink.textContent = enabled
                ? __("Warmup: Active", "cache-autopilot")
                : __("Warmup: Paused", "cache-autopilot");
        }

        if (toggleLink) {
            toggleLink.textContent = enabled
                ? __("Pause warmup", "cache-autopilot")
                : __("Enable warmup", "cache-autopilot");

            const href = toggleLink.getAttribute("href");
            if (href) {
                try {
                    const url = new URL(href, window.location.origin);
                    url.searchParams.set("enabled", enabled ? "0" : "1");
                    toggleLink.setAttribute("href", url.toString());
                } catch {
                    // Keep current URL when browser URL parsing is unavailable.
                }
            }
        }

        if (runFullNode) {
            runFullNode.classList.toggle("ecw-adminbar-hidden", !enabled);
        }

        if (rootLink) {
            const iconWrap = rootLink.querySelector(".ecw-adminbar-icon-wrap");
            if (iconWrap) {
                const existingBadge = iconWrap.querySelector(
                    ".ecw-adminbar-pause-indicator",
                );

                if (enabled) {
                    if (existingBadge) {
                        existingBadge.remove();
                    }
                } else if (!existingBadge) {
                    const badge = document.createElement("span");
                    badge.className = "ecw-adminbar-pause-indicator";
                    badge.setAttribute("aria-hidden", "true");
                    iconWrap.appendChild(badge);
                }
            }
        }
    }, []);

    useEffect(() => {
        let cleanupTableShadows = () => {};
        const frameId = requestAnimationFrame(() => {
            cleanupTableShadows = initTableScrollShadows(document) || (() => {});
        });

        return () => {
            cancelAnimationFrame(frameId);
            cleanupTableShadows();
        };
    }, [selectedTab]);

    // Save all settings
    const saveAll = async (payloadOptions = options, showNotice = true) => {
        if (hasInvalidSitemapUrl(payloadOptions?.general?.sitemaps || "")) {
            if (showNotice) {
                createErrorNotice(__("One or more sitemap URLs are invalid.", "cache-autopilot"), {
                    type: "snackbar",
                    icon: <Icon icon={error} />,
                });
            }
            return;
        }

        setIsSaving(true);
        const toSend = buildCleanPayload(defaults, payloadOptions);
        const previousSitemapUrls = parseSitemapUrls(originalOptions?.general?.sitemaps || "");

        try {
            const response = await apiFetch({
                path: REST_PATH,
                method: "POST",
                data: { [OPTION_KEY]: toSend },
            });
            const result = response[OPTION_KEY];
            if (result && typeof result === "object") {
                setOptions(result);
                setOriginalOptions(result);

                if (typeof result?.general?.enabled === "boolean") {
                    syncAdminBarWarmupState(result.general.enabled);
                }
            }

            const savedSitemapsRaw = result?.general?.sitemaps ?? payloadOptions?.general?.sitemaps ?? "";
            const savedSitemapUrls = parseSitemapUrls(savedSitemapsRaw);
            const shouldBootstrapInitialSitemap = previousSitemapUrls.length === 0 && savedSitemapUrls.length > 0;

            dispatchSitemapPresence(savedSitemapUrls.length > 0);

            // Clear stale API-derived warning state; persisted settings drive the immediate notice.
            setSitemapApiWarning(null);
            setSitemapApiHasSitemap(null);

            // Trigger sitemap validation refresh unless the initial POST bootstrap owns it.
            if (!shouldBootstrapInitialSitemap) {
                setSitemapRefreshTrigger((prev) => prev + 1);
            }
            setPriorityPagesLoaded(false);
            setPriorityPagesError(null);

            if (selectedTab === "priorities") {
                fetchPriorityPages({ force: true })
                    .catch(console.error);
            }

            if (shouldBootstrapInitialSitemap) {
                bootstrapInitialSitemapIndex({ showNotice });
            } else if (showNotice) {
                createSuccessNotice(__("Settings saved.", "cache-autopilot"), {
                    type: "snackbar",
                    icon: <Icon icon={check} />,
                });
            }
        } catch (err) {
            console.error(err);
            createErrorNotice(__("Failed to save settings.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={error} />,
            });
        } finally {
            setIsSaving(false);
        }
    };

    // Reset active tab — tabKeysMap values are { phpGroup: [fields] } objects
    const handleResetTab = async () => {
        const resetOptions = { ...options };
        const groupMap = tabKeysMap[selectedTab] || {};

        Object.entries(groupMap).forEach(([phpGroup, fields]) => {
            fields.forEach((fieldKey) => {
                const groupDefaults = defaults[phpGroup] || {};
                if (fieldKey in groupDefaults) {
                    resetOptions[phpGroup] = {
                        ...(resetOptions[phpGroup] || {}),
                        [fieldKey]: groupDefaults[fieldKey],
                    };
                }
            });
        });

        setOptions(resetOptions);
        setShowResetModal(false);
        await saveAll(resetOptions, false);

        createSuccessNotice(__("Tab reset to defaults.", "cache-autopilot"), {
            type: "snackbar",
            icon: <Icon icon={check} />,
        });
    };

    // Reset all settings
    const handleResetAll = async () => {
        setOptions(defaults);
        setShowResetModal(false);
        await saveAll(defaults, false);

        createSuccessNotice(__("All settings reset to defaults.", "cache-autopilot"), {
            type: "snackbar",
            icon: <Icon icon={check} />,
        });
    };

    // Dirty state detection
    const isDirty = hasDirtyOptions(options, originalOptions);

    // Warn when leaving the page with unsaved settings changes.
    useEffect(() => {
        if (!isDirty) {
            return undefined;
        }

        const handleBeforeUnload = (event) => {
            event.preventDefault();
            event.returnValue = "";
            return "";
        };

        window.addEventListener("beforeunload", handleBeforeUnload);

        return () => {
            window.removeEventListener("beforeunload", handleBeforeUnload);
        };
    }, [isDirty]);

    const savedSitemapUrls =
        parseSitemapUrls(originalOptions?.general?.sitemaps || "");
    const effectiveSitemapWarning = sitemapApiHasSitemap === false
          ? null
          : sitemapApiWarning;
    const warmupEnabled = options?.general?.enabled === true;
    const runFullDisabled = runFullBusy || isSaving || !warmupEnabled || isDirty;
    const runFullHelperText = runFullBusy
        ? __("Scheduling full cache refresh...", "cache-autopilot")
        : !warmupEnabled
        ? __("Enable warmup to run a full cache refresh.", "cache-autopilot")
        : isDirty
        ? __("Save settings first to run a full cache refresh.", "cache-autopilot")
        : isSaving
        ? __("Please wait until settings are saved.", "cache-autopilot")
        : __(
              "Invalidates cache, then warms all sitemap URLs in the background.",
              "cache-autopilot",
          );

    // Tab configuration
    const handleRunWarmupSuccess = async (result) => {
        createSuccessNotice(
            result?.message || __("Warmup batch completed.", "cache-autopilot"),
            {
                type: "snackbar",
                icon: <Icon icon={check} />,
            },
        );

        setRecentLogsLoaded(false);
        try {
            await fetchRecentLogs({ force: true, ensureFresh: true });
        } catch (err) {
            console.error(err);
        }

        try {
            await fetchQueueRuntime();
        } catch (err) {
            console.error(err);
        }
    };

    const handleRunFullWarmup = async () => {
        if (runFullDisabled) {
            return;
        }

        setRunFullBusy(true);
        try {
            await apiFetch({
                path: RUN_FULL_PATH,
                method: "POST",
            });

            createSuccessNotice(__("Full warmup scheduled successfully.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });

            setRecentLogsLoaded(false);
            fetchRecentLogs({ force: true })
                .catch(console.error);
        } catch (err) {
            console.error(err);
            const isPaused = err?.data?.code === "warmup_paused" || err?.status === 409;

            createErrorNotice(
                isPaused
                    ? __("Warmup is paused. Enable warmup and save settings first.", "cache-autopilot")
                    : __("Failed to schedule full warmup.", "cache-autopilot"),
                {
                    type: "snackbar",
                    icon: <Icon icon={error} />,
                },
            );
        } finally {
            setRunFullBusy(false);
        }
    };

    const handleResetTuningSuccess = () => {
        createSuccessNotice(__("Tuning data reset.", "cache-autopilot"), {
            type: "snackbar",
            icon: <Icon icon={check} />,
        });
    };

    const handleResetTuningError = () => {
        createErrorNotice(__("Failed to reset tuning data.", "cache-autopilot"), {
            type: "snackbar",
            icon: <Icon icon={error} />,
        });
    };

    const tabs = [
        {
            name: "warmup",
            title: __("Warmup", "cache-autopilot"),
            children: (
                <WarmupTab
                    options={options}
                    setOptions={setOptions}
                    savedSitemapUrls={savedSitemapUrls}
                    onRunFullWarmup={handleRunFullWarmup}
                    runFullBusy={runFullBusy}
                    runFullDisabled={runFullDisabled}
                    runFullHelperText={runFullHelperText}
                />
            ),
        },
        {
            name: "priorities",
            title: __("Priorities", "cache-autopilot"),
            children: (
                <PrioritiesTab
                    options={options}
                    setOptions={setOptions}
                    sitemapStatus={sitemapStatus}
                    priorityPages={priorityPages}
                    priorityPagesLoading={priorityPagesLoading}
                    priorityPagesError={priorityPagesError}
                    onRefreshSitemapStatus={refreshSitemapStatus}
                    onRefreshPriorityPages={() => fetchPriorityPages({ force: true })}
                />
            ),
        },
        {
            name: "logging",
            title: __("Log", "cache-autopilot"),
            children: (
                <LoggingTab
                    options={options}
                    setOptions={setOptions}
                    onRunSuccess={handleRunWarmupSuccess}
                    recentLogs={recentLogs}
                    recentLogsMeta={recentLogsMeta}
                    recentLogsLoading={recentLogsLoading}
                    recentLogsError={recentLogsError}
                    logsTimezone={logsTimezone}
                    onRefreshRecentLogs={() => fetchRecentLogs({ force: true })}
                    onLoadAllRecentLogs={() => fetchRecentLogs({
                        force: true,
                        mode: "all",
                        surfaceError: false,
                    })}
                    canLoadAllRecentLogs={recentLogsMode !== "all"}
                    queueRuntime={queueRuntime}
                    queueRuntimeLoaded={queueRuntimeLoaded}
                />
            ),
        },
        {
            name: "diagnostics",
            title: __("Diagnostics", "cache-autopilot"),
            children: <DiagnosticsTab options={options} setOptions={setOptions} />,
        },
        {
            name: "advanced",
            title: __("Advanced", "cache-autopilot"),
            children: <AdvancedTab options={options} setOptions={setOptions} onResetTuningSuccess={handleResetTuningSuccess} onResetTuningError={handleResetTuningError} />,
        },
    ];

    const { logoSrc, logoAlt } = getProductBranding({ isPremium });

    return (
        <div className='ekesto-settings-app'>
            <div className='ekesto-settings-header'>
                <div className='ekesto-settings-header__container'>
                    <div className='ekesto-settings-header__brand'>
                        <h1 className='ekesto-settings-header__heading'>
                            <span className='screen-reader-text'>
                                {__("Cache Warmup", "cache-autopilot")}
                            </span>
                            <img
                                src={ecwLogo}
                                alt=''
                                aria-hidden='true'
                                className='ekesto-settings-header__logo'
                            />
                        </h1>
                    </div>
                    <div className='ekesto-settings-header-buttons'>
                        <Button
                            variant='tertiary'
                            onClick={() => setShowResetModal(true)}
                            className='ekesto-settings-header-buttons__reset'
                        >
                            {__("Reset Settings", "cache-autopilot")}
                        </Button>
                        <Button
                            variant='primary'
                            onClick={() => saveAll()}
                            disabled={!isDirty || isSaving}
                            isBusy={isSaving}
                            className='ekesto-settings-header-buttons__save'
                        >
                            {__("Save All", "cache-autopilot")}
                        </Button>
                    </div>
                </div>
            </div>

            <div className='ekesto-plugin-meta'>
                <div className='ekesto-plugin-meta__inner'>
                    <span className='ekesto-plugin-meta__link'>
                        <a
                            href='https://wpcacheautopilot.com/'
                            target='_blank'
                            title={__("Visit Cache Autopilot website", "cache-autopilot")}
                            rel='noopener noreferrer'
                        >
                            <span className='screen-reader-text'>
                                {logoAlt}
                            </span>

                            <img
                                src={logoSrc}
                                alt={logoAlt}
                                className='ekesto-plugin-meta__img'
                            />
                        </a>
                    </span>
                    <span
                        className='ekesto-plugin-meta__separator'
                        aria-hidden='true'
                    >
                        {"|"}
                    </span>
                    <span className='ekesto-plugin-meta__link'>
                        <a
                            href='https://ekesto.github.io/cache-autopilot-site/docs/changelog/cache-autopilot/'
                            target='_blank'
                            title={__("View changelog", "cache-autopilot")}
                            rel='noopener noreferrer'
                        >
                            {sprintf(
                                /* translators: %s: Plugin version. */
                                __("v%s", "cache-autopilot"),
                                pluginVersion,
                            )}
                        </a>
                    </span>
                    <span
                        className='ekesto-plugin-meta__separator'
                        aria-hidden='true'
                    >
                        {"|"}
                    </span>
                    <span className='ekesto-plugin-meta__link'>
                        <a
                            href='https://wpcacheautopilot.com/docs/'
                            target='_blank'
                            title={__("View documentation", "cache-autopilot")}
                            rel='noopener noreferrer'
                        >
                            {__("Docs", "cache-autopilot")}
                        </a>
                    </span>
                </div>
            </div>

            <Notices />

            {effectiveSitemapWarning && (
                <div className='ekesto-global-notice-container'>
                    <Notice status='warning' isDismissible={false}>
                        {effectiveSitemapWarning}
                    </Notice>
                </div>
            )}

            <TabPanel
                tabs={tabs}
                initialTabName={selectedTab}
                onSelect={(tabName) => setSelectedTab(tabName)}
                className='ekesto-settings-tabs'
            >
                {({ children }) => (
                    <div className='ekesto-settings-panel-container'>
                        {children}
                    </div>
                )}
            </TabPanel>

            {showResetModal && (
                <Modal
                    className='ekesto-settings-modal ekesto-settings-modal--narrow'
                    title={__("Reset Settings", "cache-autopilot")}
                    onRequestClose={() => setShowResetModal(false)}
                >
                    <div className='ekesto-settings-modal__content'>
                        <div className='ekesto-settings-modal__body'>
                            <p>
                                {__(
                                    "Resetting will restore all configured settings on the current tab to their default values. To restore all plugin settings, choose Reset All.",
                                    "cache-autopilot",
                                )}
                            </p>
                        </div>
                        <div className='ekesto-settings-modal__actions ekesto-settings-modal__actions--split'>
                            <div className='ekesto-settings-modal__actions-group'>
                                <Button
                                    variant='primary'
                                    onClick={handleResetTab}
                                >
                                    {__("Reset Active Tab", "cache-autopilot")}
                                </Button>
                                <Button
                                    variant='secondary'
                                    onClick={handleResetAll}
                                >
                                    {__("Reset All", "cache-autopilot")}
                                </Button>
                            </div>
                            <Button
                                variant='tertiary'
                                onClick={() => setShowResetModal(false)}
                            >
                                {__("Cancel", "cache-autopilot")}
                            </Button>
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
}
