import {SettingsProvider} from "../contexts/SettingsContext";
import Colors from "./Settings/Colors";
import Switch from "./Settings/Switch";
import General from "./Settings/General";

import {saveSettings, useMounted} from "../includes/functions";

const {Button} = wp.components;
const {useState, useEffect, useRef} = React;

export default function Setup() {

    const [data, setData] = useState(dracula.settings);

    const menuItems = [
        {
            key: 'general',
            title: wp.i18n.__('General Settings', 'dracula-dark-mode'),
        },
        {
            key: 'colors',
            title: wp.i18n.__('Colors Settings', 'dracula-dark-mode'),
        },
        {
            key: 'toggle',
            title: wp.i18n.__('Toggle Switch', 'dracula-dark-mode'),
        },
    ];

    const urlParams = new URLSearchParams(window.location.search);
    const [menu, setMenu] = useState(urlParams.get('tab') || 'general');

    const [saving, setSaving] = useState(false);

    const isMounted = useMounted();

    const iframeRef = useRef(null);
    const prevPayloadRef = useRef(null);

    // Cache the iframe once (no repeated DOM queries)
    useEffect(() => {
        if (!isMounted) return;

        iframeRef.current = document.querySelector(".dracula-setup-iframe");
    }, [isMounted]);

    // Post only when the payload actually changes
    useEffect(() => {
        if (!isMounted || !iframeRef.current || !iframeRef.current.contentWindow) return;

        const nextPayload = {...data, isLiveEdit: true, isSetup: true};
        const prev = prevPayloadRef.current;

        // inline shallow compare (no separate function)
        const keys = Object.keys(nextPayload);
        const changed =
            !prev ||
            keys.length !== Object.keys(prev).length ||
            keys.some((k) => nextPayload[k] !== prev[k]);

        if (!changed) return;

        prevPayloadRef.current = nextPayload;

        const rafId = requestAnimationFrame(() => {
            iframeRef.current.contentWindow.postMessage(
                {type: "dracula-setup-data", data: nextPayload},
                window.location.origin // safer than '*'
            );
        });

        return () => cancelAnimationFrame(rafId);
    }, [isMounted, data]);

    const steps = [
        {key: 'general', title: wp.i18n.__('General', 'dracula-dark-mode')},
        {key: 'colors', title: wp.i18n.__('Colors', 'dracula-dark-mode')},
        {key: 'toggle', title: wp.i18n.__('Switch', ' dracula-dark-mode')}
    ]

    return (
        <div className={`dracula-ignore dracula-live-edit dracula-setup-sidebar`}>

            <ol
                className="steps"
                role="list"
                aria-label="Progress"
                style={{"--progress": `${(steps.findIndex(step => step.key === menu) + 1) / steps.length * 100}%`}}
            >
                <span className="steps__track" aria-hidden="true"/>
                <span className="steps__progress" aria-hidden="true"/>

                {steps.map(({key, title}, n) => {

                    let status = 'upcoming';

                    if (key === menu) {
                        status = 'active';
                    } else {
                        const currentIndex = steps.findIndex(step => step.key === menu);
                        const stepIndex = steps.findIndex(step => step.key === key);

                        if (stepIndex < currentIndex) {
                            status = 'completed';
                        }
                    }

                    return (
                        <li
                            key={key}
                            className={`step ${status}`}
                            aria-current={status === "active" ? "step" : undefined}
                            onClick={() => setMenu(key)}
                        >
                            <span className="step__marker" aria-hidden="true">{n + 1}</span>

                            <span className="step__label">{title}</span>
                        </li>
                    );
                })}
            </ol>

            <SettingsProvider value={{menu, data, setData, isLiveEdit: true, isSetup: true}}>

                <div className="dracula-live-edit-menu">
                    {
                        menuItems.map(item => {
                            const {key, title} = item;
                            const isActive = menu === key;
                            return (
                                !!menu && !isActive ? null :
                                    <div className={`dracula-live-edit-menu-item ${isActive ? 'active' : ''}`} key={key}
                                         onClick={() => {
                                             setMenu(isActive ? '' : key)
                                         }}>
                                        <img src={dracula.pluginUrl + '/assets/images/settings/' + key + '.svg'}/>
                                        <span>{title}</span>
                                        <i className={`dashicons dashicons-arrow-${isActive ? 'up' : 'down'}`}></i>
                                    </div>
                            );
                        })
                    }
                </div>

                {'general' === menu && <General/>}
                {'colors' === menu && <Colors/>}
                {'adjustments' === menu && <Colors/>}
                {'toggle' === menu && <Switch/>}

            </SettingsProvider>

            <div className="dracula-setup-footer">

                <Button
                    className="dracula-btn btn-skip"
                    text={wp.i18n.__('Skip', 'dracula-dark-mode')}
                    label={wp.i18n.__('Skip Setup', 'dracula-dark-mode')}
                    title={wp.i18n.__('Skip Setup', 'dracula-dark-mode')}
                    onClick={() => {
                        const url = new URL(window.location.href);
                        url.searchParams.set('setup_complete', '1');
                        window.location.href = url.toString();
                    }}
                />

                {menu && 'general' !== menu &&
                    <Button
                        className="dracula-btn btn-back"
                        text={wp.i18n.__('Back', 'dracula-dark-mode')}
                        label={wp.i18n.__('Back', 'dracula-dark-mode')}
                        title={wp.i18n.__('Back', 'dracula-dark-mode')}
                        icon={'arrow-left-alt2'}
                        onClick={() => {
                            if ('toggle' === menu) {
                                setMenu('colors');
                            } else if ('colors' === menu) {
                                setMenu('general');
                            } else {
                                setMenu('general');
                            }
                        }}
                    />
                }

                <Button
                    className="dracula-btn"
                    text={'toggle' === menu ? wp.i18n.__('Done', 'dracula-dark-mode') : wp.i18n.__('Continue', 'dracula-dark-mode')}
                    label={wp.i18n.__('Save', 'dracula-dark-mode')}
                    icon={'toggle' === menu ? 'saved' : 'arrow-right-alt2'}
                    iconPosition={'toggle' === menu ? 'left' : 'right'}
                    isBusy={saving}
                    onClick={() => {
                        if ('toggle' === menu) {
                            setSaving(true);

                            saveSettings(data).then(() => {
                                setSaving(false);

                                const url = new URL(window.location.href);
                                url.searchParams.set('setup_complete', '1');
                                window.location.href = url.toString();

                            });

                        } else if ('colors' === menu) {
                            setMenu('toggle');
                        } else if ('general' === menu) {
                            setMenu('colors');
                        } else {
                            setMenu('general');
                        }
                    }}
                />

            </div>

        </div>
    )
}