import Settings from "./components/Settings";
import ToggleBuilder from "./components/ToggleBuilder";
import Analytics from "./components/Analytics";
import LiveEdit from "./components/LiveEdit";
import Setup from "./components/Setup";
import Toggles from "./components/Settings/Toggles";
import {showProModal} from "./components/ProModal";

;(function ($) {

    const {
        blockEditorDarkMode = true,
        keyboardShortcuts,
    } = dracula.settings;

    const app = {

        init: () => {

            if (blockEditorDarkMode) {
                app.renderBlockEditorToggle();
            }

            app.initSettings();
            app.initSetup();
            app.initEditorSettings();
            app.initToggleBuilder();
            app.initAnalytics();
            app.initMenuToggle();
            app.renderMenuToggle();

            app.handleAdminColorSchemeChange();

        },

        ready: () => {

            // Handle getting-started menu
            $('.dracula-getting-started-menu-item').on('click', function () {
                $('.dracula-getting-started-menu-item').removeClass('active');
                $(this).addClass('active');

                $('.dracula-getting-started-content').removeClass('active');
                $('#' + $(this).data('target')).addClass('active');
            });

            // Handle keyboard shortcuts
            if (keyboardShortcuts) {
                $(document).on('keydown', app.handleKeydown);
            }

            // Handle show all button
            $(document).on('click', '.show-all-btn-wrap .show-all-btn', function () {
                $('.valuable-features .feature').removeClass('dracula-hidden');
                $('.show-all-btn-wrap').remove();
            });

            // Toggle change text on hover
            $(document).on({
                mouseenter: function () {
                    $(this).find('.toggle-prefix-text').text(wp.i18n.__('Dark Mode', 'dracula'));
                },
                mouseleave: function () {
                    $(this).find('.toggle-prefix-text').text(wp.i18n.__('Light Mode', 'dracula'));
                }
            }, '.toggle-wrap');

            // Add class to toggle button based on dark mode
            if ($('.dracula-toggle-wrap button.dracula-toggle').length) {
                $('.dracula-toggle-wrap button.dracula-toggle').addClass(`mode-${draculaDarkMode.isEnabled() ? 'dark' : 'light'}`);
            }

            // Handle PRO feature clicks
            $(document).on('click', '.dracula-pro-icon', () => {
                showProModal(wp.i18n.__('Upgrade to PRO to access this feature', 'radio-player'));
            });

            // on click .menu-top#toplevel_page_dracula a:has(.dracula-icon.icon-pro) open link in new tab
            $(document).on('click', '.menu-top#toplevel_page_dracula a:has(.dracula-icon.icon-pro)', function (e) {
                e.preventDefault();
                const proUrl = $(this).attr('href');
                window.open(proUrl, '_blank');
            });

        },

        handleKeydown: function (e) {
            //Ctrl + Alt + D (windows) or Cmd + Alt + D (mac)
            if (e.ctrlKey && e.altKey && e.keyCode === 68 || e.metaKey && e.altKey && e.keyCode === 68) {
                e.preventDefault();

                if (draculaDarkMode.isEnabled()) {
                    draculaDarkMode.disable();
                } else {
                    draculaDarkMode.enable();
                }
            }
        },

        renderBlockEditorToggle: () => {
            if (typeof wp.data === 'undefined') return;

            wp.data.subscribe(() => {
                setTimeout(() => {

                    const hasPrimaryToolbar = $(".edit-post-header-toolbar").length > 0;

                    const $toolbar = hasPrimaryToolbar
                        ? $(".edit-post-header-toolbar")
                        : $(".edit-post-header__toolbar");

                    const $toolbarChild = hasPrimaryToolbar
                        ? $toolbar
                        : $(".editor-document-tools__left");

                    const $editorToggle = $(".dracula-block-editor-toggle");

                    if (!$toolbar.length || $editorToggle.length) return;

                    const editorToggleDiv = $('<div>', {
                        class: "dracula-ignore dracula-toggle dracula-block-editor-toggle",
                        click: function () {
                            if (typeof draculaDarkMode !== 'undefined') {
                                draculaDarkMode.isEnabled() ? draculaDarkMode.disable() : draculaDarkMode.enable();
                            }
                        }
                    });

                    editorToggleDiv.insertBefore($toolbarChild);
                }, 1);
            });
        },

        initSettings: () => {
            const settingsElement = document.getElementById('dracula-settings-app');
            if (settingsElement) {
                ReactDOM.render(<Settings/>, settingsElement);
            }
        },

        initSetup: () => {
            const setupElement = document.getElementById('dracula-setup-sidebar');

            if (setupElement) {
                ReactDOM.render(<Setup/>, setupElement);
            }
        },

        initEditorSettings: () => {
            const settingsElement = document.getElementById('dracula-settings-metabox');
            if (settingsElement) {
                ReactDOM.render(<LiveEdit isEditor={'classic'}/>, settingsElement);
            }
        },

        initMenuToggle: () => {

            // Expand the meta box if the URL hash matches
            if (window.location.hash === '#dracula-dark-mode') {
                const $box = $('#dracula_dark_mode_nav_link'); // Meta box ID
                if ($box.length) {
                    $('.accordion-section').removeClass('open'); // Close other sections

                    // Remove the 'closed' class to expand it
                    $box.addClass('open');
                    // Make sure the inside is visible
                    $box.find('#dracula_dark_mode_nav_link-content').show();
                }
            }

            // Initialize the toggles menu settings on first add
            $('#menu-to-edit').on('click', '.menu-item-dracula-dark-mode-switch.pending .item-edit', app.renderMenuToggle);

        },

        renderMenuToggle: () => {
            const menuToggleElement = document.getElementById('dracula-dark-mode-switches');

            const toggleStyle = menuToggleElement?.getAttribute('data-style') || '1';

            if (menuToggleElement) {
                ReactDOM.render(
                    <Toggles
                        value={toggleStyle}
                        onChange={(value, data) => {
                            document.querySelector('.dracula-dark-mode-switches-panel input[type="hidden"]').value = value;
                        }}
                    />,
                    menuToggleElement
                );
            }
        },

        initToggleBuilder: () => {
            const toggleBuilderElement = document.getElementById('dracula-toggle-builder');
            if (toggleBuilderElement) {
                ReactDOM.render(<ToggleBuilder/>, toggleBuilderElement);
            }
        },

        initAnalytics: () => {
            const analyticsElement = document.getElementById('dracula-analytics');

            if (analyticsElement) {
                ReactDOM.render(<Analytics/>, analyticsElement);
            }
        },

        handleAdminColorSchemeChange: () => {
            const draculaDarkMode = window.draculaDarkMode;

            const colorOptions = document.querySelectorAll('.color-option');

            if (colorOptions) {
                colorOptions.forEach(option => {
                        option.addEventListener('click', () => {
                                const color = option.querySelector('[name="admin_color"]').value;
                                color === 'z_dracula' ? draculaDarkMode.enable() : draculaDarkMode.disable();
                            }
                        )
                    }
                )
            }

        }

    }

    app.init();
    $(document).ready(app.ready);

})(jQuery);