import { useState, useEffect, useMemo, useCallback } from "@wordpress/element";
import apiFetch from "@wordpress/api-fetch";
import { TabPanel, Button, Modal, Icon, Notice } from "@wordpress/components";
import { useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { __, sprintf } from "@wordpress/i18n";
import { check, error, settings, unseen } from "@wordpress/icons";
import eciLogo from "../../../images/eci-logo.svg";
import {
    buildFeatureSettingsPayload,
    buildFeatureSettingsResetPayload,
    getProductBranding,
    useFeatureSettingsLifecycle,
} from "@cache-autopilot/invalidator-settings-feature-panels";

import PostTypeTab from "./tabs/PostTypeTab";
import SettingsTab from "./tabs/SettingsTab";
import Notices from "./components/Notices";
import ValidationErrors from "./components/ValidationErrors";
import { initTableScrollShadows } from "./utils/responsiveTables";
import {
    catalogToLabelMap,
    defaultPostTypeConfig,
    filterPostTypeCatalog,
    isDisplayablePostType,
    normalizeInvalidationBehavior,
    normalizePostTypeCatalog,
    normalizePostTypeConfig,
    normalizePostTypes,
    stripNonPublicSuffix,
} from "./utils/normalizers";
import { hasDirtySettings } from "./utils/dirty-state";
import {
    applyNonPublicPostTypeRestrictions,
    buildPostTypesPayload,
} from "./utils/post-type-payload";
import { normalizeTab } from "./utils/tabs";

import {
    REST_PATH,
    SETTINGS_CONFIG,
    SETTINGS_BOOT,
    ROOT_ELEMENT_ID,
} from "./config";

const SETTINGS_TAB_NAME = "__settings__";
const FALLBACK_ASYNC_DELAY_SECONDS = 10;
const MANY_TABS_THRESHOLD = 6;
const TAB_STORAGE_KEY = "ekesto_ci_last_tab";
const INVALIDATION_STATE_EVENT = "ekesto-cache-invalidator:invalidation-state";

/**
 * Main settings app - manages state, REST API, dynamic tabs.
 */
export default function App() {
    const initial = SETTINGS_BOOT.initial || null;
    const pluginVersion =
        typeof SETTINGS_CONFIG.pluginVersion === "string"
            ? SETTINGS_CONFIG.pluginVersion
            : "";
    const isPremium = SETTINGS_CONFIG.isPremium === true;
    const featureSettings = useFeatureSettingsLifecycle({ initial });
    const {
        handleFeatureSettingsLoaded,
        handleFeatureSettingsLoadError,
        isDirty: isFeatureSettingsDirty,
        loadFeatureSettings,
        saveFeatureSettings,
        settingsTabProps,
    } = featureSettings;

    const initialDelay =
        initial?.async_delay_default_seconds || FALLBACK_ASYNC_DELAY_SECONDS;
    const initialIncludeNonPublicPostTypes = !!(
        initial?.include_non_public_post_types ?? false
    );
    const initialPostTypeCatalog = normalizePostTypeCatalog(
        initial?.post_type_catalog ||
            initial?.available_post_types ||
            initial?.public_post_types ||
            {},
    );
    const initialConfiguredPostTypeKeys = Object.keys(
        initial?.post_types || {},
    ).filter((postType) =>
        isDisplayablePostType(postType, initialPostTypeCatalog),
    );
    const initialInvalidationBehavior = normalizeInvalidationBehavior(
        initial?.invalidation_behavior || {},
    );

    const [data, setData] = useState(initial);
    const [postTypeSettings, setPostTypeSettings] = useState(
        normalizePostTypes(initial?.post_types || {}),
    );
    const [originalPostTypeSettings, setOriginalPostTypeSettings] = useState(
        normalizePostTypes(initial?.post_types || {}),
    );
    const [isSaving, setIsSaving] = useState(false);
    const [showResetModal, setShowResetModal] = useState(false);
    const [validationErrors, setValidationErrors] = useState([]);
    const [globalInvalidation, setGlobalInvalidation] = useState(
        initial?.global_invalidation || {},
    );
    const [originalGlobalInvalidation, setOriginalGlobalInvalidation] =
        useState(initial?.global_invalidation || {});
    const [timedInvalidation, setTimedInvalidation] = useState(
        initial?.timed_invalidation || {},
    );
    const [originalTimedInvalidation, setOriginalTimedInvalidation] = useState(
        initial?.timed_invalidation || {},
    );
    const [includeNonPublicPostTypes, setIncludeNonPublicPostTypes] = useState(
        initialIncludeNonPublicPostTypes,
    );
    const [
        originalIncludeNonPublicPostTypes,
        setOriginalIncludeNonPublicPostTypes,
    ] = useState(initialIncludeNonPublicPostTypes);

    const [asyncDelayDefaultSeconds, setAsyncDelayDefaultSeconds] =
        useState(initialDelay);
    const [invalidationBehavior, setInvalidationBehavior] = useState(
        initialInvalidationBehavior,
    );
    const [originalInvalidationBehavior, setOriginalInvalidationBehavior] =
        useState(initialInvalidationBehavior);

    const configuredPostTypeKeys = useMemo(
        () => Object.keys(postTypeSettings || {}),
        [postTypeSettings],
    );
    const originalConfiguredPostTypeKeys = useMemo(
        () => Object.keys(originalPostTypeSettings || {}),
        [originalPostTypeSettings],
    );

    const getTabFromUrl = useCallback(
        (postTypeKeys = []) => {
            try {
                const fromQuery = normalizeTab(
                    new URLSearchParams(window.location.search).get("tab"),
                    postTypeKeys,
                );
                if (fromQuery) {
                    return fromQuery;
                }
            } catch {
                // Continue with hash fallback.
            }

            try {
                return normalizeTab(
                    decodeURIComponent(window.location.hash.slice(1)),
                    postTypeKeys,
                );
            } catch {
                return null;
            }
        },
        [],
    );

    const getTabFromStorage = useCallback(
        (postTypeKeys = []) => {
            try {
                return normalizeTab(
                    window.localStorage.getItem(TAB_STORAGE_KEY),
                    postTypeKeys,
                );
            } catch {
                return null;
            }
        },
        [],
    );

    // Compute initial tab synchronously from URL/storage (before first render).
    const getInitialTab = useCallback(() => {
        return (
            getTabFromUrl(initialConfiguredPostTypeKeys) ||
            getTabFromStorage(initialConfiguredPostTypeKeys) ||
            SETTINGS_TAB_NAME
        );
    }, [getTabFromStorage, getTabFromUrl, initialConfiguredPostTypeKeys]);

    const [selectedTab, setSelectedTab] = useState(getInitialTab);

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

    const dispatchInvalidationState = (enabled) => {
        if (typeof window === "undefined") {
            return;
        }

        window.dispatchEvent(
            new CustomEvent(INVALIDATION_STATE_EVENT, {
                detail: { enabled: enabled === true },
            }),
        );
    };

    // Keep settings state in sync with server response after load/save/reset.
    const syncSettingsFromResponse = (response) => {
        const fallbackDelay =
            response?.async_delay_default_seconds ||
            FALLBACK_ASYNC_DELAY_SECONDS;
        const normalizedPostTypes = normalizePostTypes(
            response?.post_types || {},
        );
        const normalizedInvalidationBehavior = normalizeInvalidationBehavior(
            response?.invalidation_behavior || {},
        );

        setData(response);
        dispatchInvalidationState(
            response?.global_invalidation?.plugin_enabled ?? true,
        );
        setPostTypeSettings(normalizedPostTypes);
        setOriginalPostTypeSettings(normalizedPostTypes);
        setGlobalInvalidation(response?.global_invalidation || {});
        setOriginalGlobalInvalidation(response?.global_invalidation || {});
        setTimedInvalidation(response?.timed_invalidation || {});
        setOriginalTimedInvalidation(response?.timed_invalidation || {});
        setIncludeNonPublicPostTypes(
            !!(response?.include_non_public_post_types ?? false),
        );
        setOriginalIncludeNonPublicPostTypes(
            !!(response?.include_non_public_post_types ?? false),
        );
        setAsyncDelayDefaultSeconds(fallbackDelay);
        setInvalidationBehavior(normalizedInvalidationBehavior);
        setOriginalInvalidationBehavior(normalizedInvalidationBehavior);
    };

    // Fetch settings + edition-specific settings on mount for freshness.
    useEffect(() => {
        let cancelled = false;

        const load = async () => {
            const [settingsResult, featureSettingsResult] =
                await Promise.allSettled([
                    apiFetch({ path: REST_PATH }),
                    loadFeatureSettings(),
                ]);

            if (cancelled) {
                return;
            }

            if (settingsResult.status === "fulfilled") {
                syncSettingsFromResponse(settingsResult.value);
            } else {
                console.error(settingsResult.reason);
                createErrorNotice(__("Failed to load settings.", "cache-autopilot"));
            }

            if (featureSettingsResult.status === "fulfilled") {
                handleFeatureSettingsLoaded(featureSettingsResult.value);
            } else {
                handleFeatureSettingsLoadError(featureSettingsResult.reason);
            }
        };

        load();

        return () => {
            cancelled = true;
        };
    }, [
        createErrorNotice,
        handleFeatureSettingsLoaded,
        handleFeatureSettingsLoadError,
        loadFeatureSettings,
    ]);

    const isDirty = useMemo(
        () =>
            hasDirtySettings({
                postTypeSettings,
                originalPostTypeSettings,
                globalInvalidation,
                originalGlobalInvalidation,
                timedInvalidation,
                originalTimedInvalidation,
                invalidationBehavior,
                originalInvalidationBehavior,
                isFeatureSettingsDirty,
                includeNonPublicPostTypes,
                originalIncludeNonPublicPostTypes,
            }),
        [
            postTypeSettings,
            originalPostTypeSettings,
            globalInvalidation,
            originalGlobalInvalidation,
            timedInvalidation,
            originalTimedInvalidation,
            invalidationBehavior,
            originalInvalidationBehavior,
            isFeatureSettingsDirty,
            includeNonPublicPostTypes,
            originalIncludeNonPublicPostTypes,
        ],
    );

    // 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 handlePostTypeTabToggle = (postType, enabled) => {
        const slug = `${postType || ""}`.trim();
        if (slug === "") {
            return;
        }

        setPostTypeSettings((prev) => {
            const next = { ...(prev || {}) };

            if (enabled) {
                next[slug] = normalizePostTypeConfig(
                    next[slug] || defaultPostTypeConfig(),
                );
            } else {
                delete next[slug];
            }

            return next;
        });
    };

    // Persist settings and access control in one save flow.
    const saveAll = async () => {
        setIsSaving(true);
        setValidationErrors([]);
        let settingsSaved = false;

        try {
            const settingsResponse = await apiFetch({
                path: REST_PATH,
                method: "POST",
                data: {
                    post_types: buildPostTypesPayload(
                        postTypeSettings,
                        postTypeCatalogBySlug,
                    ),
                    include_non_public_post_types: includeNonPublicPostTypes,
                    global_invalidation: globalInvalidation,
                    invalidation_behavior: invalidationBehavior,
                    ...buildFeatureSettingsPayload({ timedInvalidation }),
                },
            });
            settingsSaved = true;
            syncSettingsFromResponse(settingsResponse);

            const featureSaveResult = await saveFeatureSettings();
            if (!featureSaveResult.ok) {
                createErrorNotice(
                    featureSaveResult.message ||
                        __(
                            "Settings were saved, but edition-specific settings were not updated.",
                            "cache-autopilot",
                        ),
                    {
                        type: "snackbar",
                        icon: <Icon icon={error} />,
                    },
                );
                return;
            }

            createSuccessNotice(__("Settings saved.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });
        } catch (err) {
            console.error(err);
            if (!settingsSaved && err.errors) {
                setValidationErrors(err.errors);
            } else if (settingsSaved) {
                createErrorNotice(
                    err.message ||
                        __(
                            "Settings were saved, but edition-specific settings failed to save.",
                            "cache-autopilot",
                        ),
                    {
                        type: "snackbar",
                        icon: <Icon icon={error} />,
                    },
                );
            } else {
                createErrorNotice(
                    err.message || __("Failed to save settings.", "cache-autopilot"),
                    {
                        type: "snackbar",
                        icon: <Icon icon={error} />,
                    },
                );
            }
        } finally {
            setIsSaving(false);
        }
    };

    // Reset only the currently selected tab while preserving unrelated settings.
    const handleResetTab = async () => {
        const isSettingsTab = activeTab === SETTINGS_TAB_NAME;

        let resetData;
        if (isSettingsTab) {
            resetData = {
                post_types: buildPostTypesPayload(
                    postTypeSettings,
                    postTypeCatalogBySlug,
                ),
                include_non_public_post_types: false,
                global_invalidation: {},
                invalidation_behavior: {},
                ...buildFeatureSettingsResetPayload({
                    resetScope: "settings",
                    timedInvalidation,
                }),
            };
        } else {
            const resetSettings = buildPostTypesPayload(
                postTypeSettings,
                postTypeCatalogBySlug,
            );
            resetSettings[activeTab] = defaultPostTypeConfig();

            resetData = {
                post_types: resetSettings,
                include_non_public_post_types: includeNonPublicPostTypes,
                global_invalidation: globalInvalidation,
                invalidation_behavior: invalidationBehavior,
                ...buildFeatureSettingsResetPayload({
                    resetScope: "postType",
                    timedInvalidation,
                }),
            };
        }

        setIsSaving(true);
        setValidationErrors([]);
        try {
            const response = await apiFetch({
                path: REST_PATH,
                method: "POST",
                data: resetData,
            });
            syncSettingsFromResponse(response);
            setShowResetModal(false);
            createSuccessNotice(__("Tab reset to defaults.", "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 all post-type and global settings back to defaults.
    const handleResetAll = async () => {
        setIsSaving(true);
        setValidationErrors([]);
        try {
            const response = await apiFetch({
                path: REST_PATH,
                method: "POST",
                data: {
                    post_types: {},
                    include_non_public_post_types: false,
                    global_invalidation: {},
                    invalidation_behavior: {},
                    ...buildFeatureSettingsResetPayload({
                        resetScope: "all",
                        timedInvalidation,
                    }),
                },
            });
            syncSettingsFromResponse(response);
            setShowResetModal(false);
            createSuccessNotice(__("All settings reset to defaults.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={check} />,
            });
        } catch (err) {
            console.error(err);
            createErrorNotice(__("Failed to reset settings.", "cache-autopilot"), {
                type: "snackbar",
                icon: <Icon icon={error} />,
            });
        } finally {
            setIsSaving(false);
        }
    };

    if (!data) {
        return <div className='wrap'>{__("Loading\u2026", "cache-autopilot")}</div>;
    }

    const {
        available_pages,
        available_pages_meta,
        all_post_types,
        public_post_types,
        cron_disabled,
        theme_context,
        site_timezone,
    } = data;

    const postTypeCatalogBySlug = useMemo(
        () =>
            normalizePostTypeCatalog(
                data?.post_type_catalog ||
                    data?.available_post_types ||
                    data?.public_post_types ||
                    {},
            ),
        [
            data?.post_type_catalog,
            data?.available_post_types,
            data?.public_post_types,
        ],
    );
    const eligiblePostTypeLabels = useMemo(
        () => catalogToLabelMap(postTypeCatalogBySlug),
        [postTypeCatalogBySlug],
    );
    const publicPostTypeLabels = useMemo(
        () =>
            catalogToLabelMap(
                filterPostTypeCatalog(postTypeCatalogBySlug, false),
            ),
        [postTypeCatalogBySlug],
    );
    const visibleConfiguredPostTypeKeys = useMemo(
        () =>
            configuredPostTypeKeys.filter((postType) =>
                isDisplayablePostType(postType, postTypeCatalogBySlug),
            ),
        [configuredPostTypeKeys, postTypeCatalogBySlug],
    );
    const visibleOriginalConfiguredPostTypeKeys = useMemo(
        () =>
            originalConfiguredPostTypeKeys.filter((postType) =>
                isDisplayablePostType(postType, postTypeCatalogBySlug),
            ),
        [originalConfiguredPostTypeKeys, postTypeCatalogBySlug],
    );
    const configuredPostTypeLabels = useMemo(() => {
        const out = {};
        visibleConfiguredPostTypeKeys.forEach((postType) => {
            out[postType] =
                all_post_types?.[postType] ||
                postTypeCatalogBySlug[postType]?.label ||
                postType;
        });
        return out;
    }, [
        all_post_types,
        visibleConfiguredPostTypeKeys,
        postTypeCatalogBySlug,
    ]);
    const activeTab = useMemo(() => {
        const validTab = normalizeTab(
            selectedTab,
            visibleConfiguredPostTypeKeys,
        );
        return validTab || SETTINGS_TAB_NAME;
    }, [selectedTab, visibleConfiguredPostTypeKeys]);

    const hasSavedPostTypeTabs =
        visibleOriginalConfiguredPostTypeKeys.length > 0;
    const hasCurrentPostTypeTabs = visibleConfiguredPostTypeKeys.length > 0;
    const shouldShowNoPostTypesInfo =
        !hasSavedPostTypeTabs && !hasCurrentPostTypeTabs;
    const shouldShowPostTypesPendingSaveSuccess =
        !hasSavedPostTypeTabs && hasCurrentPostTypeTabs && isDirty;

    useEffect(() => {
        if (selectedTab === activeTab) {
            return;
        }
        setSelectedTab(activeTab);
    }, [activeTab, selectedTab]);

    useEffect(() => {
        if (!ROOT_ELEMENT_ID) {
            return undefined;
        }

        const rootElement = document.getElementById(ROOT_ELEMENT_ID);
        if (!rootElement) {
            return undefined;
        }

        const hasManyTabs =
            visibleConfiguredPostTypeKeys.length > MANY_TABS_THRESHOLD;
        rootElement.classList.toggle("has-many-tabs", hasManyTabs);

        return () => {
            rootElement.classList.remove("has-many-tabs");
        };
    }, [visibleConfiguredPostTypeKeys]);

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

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

    // Helper to get propagation for a post type key.
    const getPropagation = (key) =>
        postTypeSettings[key]?.propagation ||
        defaultPostTypeConfig().propagation;

    // Helper to update propagation for a post type key.
    const handlePropagationChange = (key, newPropagation) => {
        setPostTypeSettings((prev) => ({
            ...prev,
            [key]: {
                ...normalizePostTypeConfig(prev[key]),
                propagation: {
                    ...normalizePostTypeConfig(prev[key]).propagation,
                    ...(newPropagation || {}),
                },
            },
        }));
    };

    const handleInvalidationBehaviorChange = (nextBehavior) => {
        setInvalidationBehavior(normalizeInvalidationBehavior(nextBehavior));
    };

    const settingsTabLabel = __("Settings", "cache-autopilot");
    const getDisplayPostTypeSettings = (key) =>
        applyNonPublicPostTypeRestrictions(
            postTypeSettings[key] || defaultPostTypeConfig(),
            postTypeCatalogBySlug[key],
        );
    const getPostTypeTabTitle = (key) => {
        const rawLabel =
            configuredPostTypeLabels?.[key] ||
            eligiblePostTypeLabels?.[key] ||
            key;
        const displayLabel = stripNonPublicSuffix(rawLabel);
        const postType = postTypeCatalogBySlug[key];

        if (postType?.public === false) {
            return (
                <>
                    {displayLabel} <Icon icon={unseen} />
                </>
            );
        }

        return displayLabel;
    };

    const postTypeTabs = visibleConfiguredPostTypeKeys.map((key) => ({
        name: key,
        title: getPostTypeTabTitle(key),
        className: "eci-tab--group",
        children: (
            <PostTypeTab
                postTypeKey={key}
                postType={postTypeCatalogBySlug[key] || null}
                postTypeLabel={stripNonPublicSuffix(
                    configuredPostTypeLabels?.[key] ||
                        eligiblePostTypeLabels?.[key] ||
                        key,
                )}
                settings={getDisplayPostTypeSettings(key)}
                availablePages={available_pages}
                pageSelectionMeta={available_pages_meta}
                postTypeCatalog={postTypeCatalogBySlug}
                publicPostTypes={publicPostTypeLabels}
                includeNonPublicPostTypes={includeNonPublicPostTypes}
                onIncludeNonPublicPostTypesChange={setIncludeNonPublicPostTypes}
                onUpdate={(newSettings) => {
                    setPostTypeSettings((prev) => ({
                        ...prev,
                        [key]: normalizePostTypeConfig(newSettings),
                    }));
                }}
                propagation={getPropagation(key)}
                onPropagationChange={(newProp) =>
                    handlePropagationChange(key, newProp)
                }
            />
        ),
    }));

    const tabs = [
        {
            name: SETTINGS_TAB_NAME,
            title: (
                <>
                    <Icon icon={settings} />
                    {settingsTabLabel}
                </>
            ),
            className: "eci-tab--settings",
            children: (
                <SettingsTab
                    publicPostTypes={publicPostTypeLabels}
                    postTypeCatalog={postTypeCatalogBySlug}
                    configuredPostTypes={visibleConfiguredPostTypeKeys}
                    onPostTypeTabToggle={handlePostTypeTabToggle}
                    includeNonPublicPostTypes={includeNonPublicPostTypes}
                    onIncludeNonPublicPostTypesChange={
                        setIncludeNonPublicPostTypes
                    }
                    globalInvalidation={globalInvalidation}
                    onGlobalInvalidationChange={setGlobalInvalidation}
                    timedInvalidation={timedInvalidation}
                    onTimedInvalidationChange={setTimedInvalidation}
                    themeContext={theme_context || {}}
                    invalidationBehavior={invalidationBehavior}
                    onInvalidationBehaviorChange={
                        handleInvalidationBehaviorChange
                    }
                    asyncDelayDefaultSeconds={asyncDelayDefaultSeconds}
                    cronDisabled={cron_disabled}
                    availablePages={available_pages}
                    pageSelectionMeta={available_pages_meta}
                    siteTimezone={site_timezone || "UTC"}
                    featureSettings={settingsTabProps}
                />
            ),
        },
        ...postTypeTabs,
    ];

    // Persist current tab in URL hash for direct linking/reload continuity.
    const handleTabSelect = useCallback(
        (tabName) => {
            const normalizedTab = normalizeTab(
                tabName,
                visibleConfiguredPostTypeKeys,
            );
            const nextTab = normalizedTab || SETTINGS_TAB_NAME;

            setSelectedTab(nextTab);

            const hashTab =
                nextTab === SETTINGS_TAB_NAME ? "settings" : nextTab;

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

            try {
                window.localStorage.setItem(TAB_STORAGE_KEY, nextTab);
            } catch {
                // Ignore storage errors and keep navigation functional.
            }
        },
        [visibleConfiguredPostTypeKeys],
    );

    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 Invalidator", "cache-autopilot")}
                            </span>
                            <img
                                src={eciLogo}
                                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 />

            {validationErrors.length > 0 && (
                <div className='ekesto-settings-validation-wrap'>
                    <ValidationErrors
                        errors={validationErrors}
                        onDismiss={() => setValidationErrors([])}
                    />
                </div>
            )}

            {shouldShowNoPostTypesInfo && (
                <div className='ekesto-global-notice-container'>
                    <Notice status='info' isDismissible={false}>
                        {__(
                            "No post type tabs are enabled yet. Use the Post Type Tabs panel in Settings to start configuring host invalidation rules.",
                            "cache-autopilot",
                        )}
                    </Notice>
                </div>
            )}

            {shouldShowPostTypesPendingSaveSuccess && (
                <div className='ekesto-global-notice-container'>
                    <Notice status='success' isDismissible={false}>
                        {__(
                            "Post Type Tabs have been enabled successfully. Save settings for this message to disappear.",
                            "cache-autopilot",
                        )}
                    </Notice>
                </div>
            )}

            <TabPanel
                key={`eci-tabpanel-${activeTab}`}
                tabs={tabs}
                initialTabName={activeTab}
                onSelect={handleTabSelect}
                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>
    );
}
