import React, {useEffect, useState} from "react";
import {useWidget, WidgetProvider} from "./context/WidgetContext";
import {
    BIG_BLACK_CURSOR_PREF,
    BIG_WHITE_CURSOR_PREF,
    FOCUS_TUNNEL_PREF,
    HIDE_IMAGES_PREF,
    HIDE_WIDGET_PREF,
    HIGH_CONTRAST_PREF,
    HIGH_SATURATION_PREF,
    HIGHLIGHT_LINKS_PREF,
    LOW_SATURATION_PREF,
    MONOCHROME_PREF,
    TEXT_ALIGNMENT_PREF,
} from "./constants";
import SPAObserver from "./modules/SPAObserver";
import {getIconUrl} from "./utils/icon-url";
import {getIconPosition, getDeviceType} from "./utils/position";
import {
    restoreFocusTunnel,
    restoreFontSize,
    restoreHideMedia,
    restoreLineHeight,
    restoreLineSpacing, restoreReadableFont
} from "./user-preferences";
import {
    toggleHighContrastTheme,
    toggleHighSaturationTheme,
    toggleLowSaturationTheme,
    toggleMonochromeTheme
} from "./effects/color-filters";
import {toggleHighlightLinks} from "./effects/highlighted-links";
import {restoreBigBlackCursorState} from "./effects/big-black-cursor";
import {restoreBigWhiteCursorState} from "./effects/big-white-cursor";
import {applyTextAlignment} from "./effects/text-alignment";
import {showConfirmHideModal} from "./components/confirm-hide-modal";
import WideAccessWidgetPanel from "./WideAccessWidgetPanel";
import {getStorageValue, setStorageValue} from "./storage";

// Contrast helper for outline ring
function getComplementaryColor(hex) {
    hex = hex.replace(/^#/, '');
    if (hex.length === 3) {
      hex = hex.split('').map(x => x + x).join('');
    }
  
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
  
    // Compute complement
    const compR = (255 - r).toString(16).padStart(2, '0');
    const compG = (255 - g).toString(16).padStart(2, '0');
    const compB = (255 - b).toString(16).padStart(2, '0');
  
    return `#${compR}${compG}${compB}`;
  }


function WideAccessWidget({config}) {
    // Stop any ongoing speech immediately when component loads
    if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
        speechSynthesis.cancel();
    }

    const {isMediaHidden, setMediaHidden} = useWidget();
    const {isLinksHighlighted, setLinksHighlighted} = useWidget();
    const {originalMediaStyles, setOriginalMediaStyles} = useWidget();
    const {currentFontSizeMultiplier, setCurrentFontSizeMultiplier} = useWidget();
    const {currentSpacing, setCurrentSpacing} = useWidget();
    const {currentLineHeight, setCurrentLineHeight} = useWidget();
    const {readableFont, setReadableFont} = useWidget();
    const {isBigWhiteCursorEnabled, setBigWhiteCursorEnabled} = useWidget();
    const {cursorStyleEl, setCursorStyleEl} = useWidget();
    const {isFocusTunnelActive, setFocusTunnelActive} = useWidget();
    const {focusTunnelContainer, setFocusTunnelContainer} = useWidget();
    const {isHighContrastMode, setHighContrastMode} = useWidget();
    const {svgFilterElement, setSvgFilterElement} = useWidget();
    const {isMonochromeMode, setMonochromeMode} = useWidget();
    const {isLowSaturationMode, setLowSaturationMode} = useWidget();
    const {isHighSaturationMode, setHighSaturationMode} = useWidget();
    const {isBigBlackCursorEnabled, setBigBlackCursorEnabled} = useWidget();
    const {textAlignment} = useWidget();
    const {widgetPosition} = useWidget();


    const [isOpen, setIsOpen] = useState(false);
    const [isHidden, setIsHidden] = useState(getStorageValue(HIDE_WIDGET_PREF, false));
    const [deviceType, setDeviceType] = useState(getDeviceType());

    const restoreAccessibilitySettings = (forceReset = false) => {
        restoreFontSize(setCurrentFontSizeMultiplier, forceReset);
        restoreLineSpacing(setCurrentSpacing);
        restoreLineHeight(setCurrentLineHeight);
        restoreReadableFont(setReadableFont);
        restoreFocusTunnel(window.innerHeight / 2, isFocusTunnelActive, setFocusTunnelActive, focusTunnelContainer, setFocusTunnelContainer);
        restoreHideMedia(isMediaHidden, setMediaHidden, originalMediaStyles, setOriginalMediaStyles);

        // restore high contrast
        if (getStorageValue(HIGH_CONTRAST_PREF, false)) {
            toggleHighContrastTheme(isHighContrastMode, svgFilterElement, setSvgFilterElement, setMonochromeMode, setLowSaturationMode, setHighSaturationMode, setHighContrastMode);
        }

        // restore monochrome
        if (getStorageValue(MONOCHROME_PREF, false)) {
            toggleMonochromeTheme(isMonochromeMode, svgFilterElement, setSvgFilterElement, setMonochromeMode, setLowSaturationMode, setHighSaturationMode, setHighContrastMode);
        }

        // restore low saturation
        if (getStorageValue(LOW_SATURATION_PREF, false)) {
            toggleLowSaturationTheme(isLowSaturationMode, svgFilterElement, setSvgFilterElement, setMonochromeMode, setLowSaturationMode, setHighSaturationMode, setHighContrastMode);
        }

        // restore high saturation
        if (getStorageValue(HIGH_SATURATION_PREF, false)) {
            toggleHighSaturationTheme(isHighSaturationMode, svgFilterElement, setSvgFilterElement, setMonochromeMode, setLowSaturationMode, setHighSaturationMode, setHighContrastMode);
        }

        if (getStorageValue(HIGHLIGHT_LINKS_PREF, false)) {
            toggleHighlightLinks(isLinksHighlighted, setLinksHighlighted);
        }

        if (getStorageValue(BIG_BLACK_CURSOR_PREF, false)) {
            restoreBigBlackCursorState(setBigBlackCursorEnabled, cursorStyleEl, setCursorStyleEl);
        }

        if (getStorageValue(BIG_WHITE_CURSOR_PREF, false)) {
            restoreBigWhiteCursorState(cursorStyleEl, setCursorStyleEl, setBigWhiteCursorEnabled);
        }



        // restore text alignment
        const savedAlignment = getStorageValue(TEXT_ALIGNMENT_PREF, 'none');
        if (savedAlignment && savedAlignment !== 'none') {
            applyTextAlignment(savedAlignment);
        }


    }

    const preloadCursors = () => {
        const urls = [
            "big-black-cursor",
            "big-black-link-cursor",
            "big-white-cursor",
            "big-white-link-cursor",
        ];

        if (!window.WPWidgetConfig?.iconsUrl) return;

        urls.forEach((url) => {

            const icon = getIconUrl(url);

            const link = document.createElement("link");
            link.rel = "preload";
            link.as = "image";
            link.href = icon;
            document.head.appendChild(link);
        });
    }

    useEffect(() => {

        const shouldHide = getStorageValue(HIDE_WIDGET_PREF, false);
        if (shouldHide) {
            setIsHidden(true);
        }
    }, []);

    useEffect(() => {
        // Stop any ongoing speech immediately on page load
        if ('speechSynthesis' in window) {
            speechSynthesis.cancel();
        }

        // Use setTimeout to ensure DOM is ready
        setTimeout(() => {
            restoreAccessibilitySettings(true); // Pass true to force reset on initial load
        }, 100);
    }, []); // Run only once on mount

    useEffect(() => {
        // Auto-open on wideaccess.ca landing page only
        try {
            const hostname = (window.location?.hostname || '').replace(/^www\./, '');
            const pathname = window.location?.pathname || '/';
            const isLanding = pathname === '/' || pathname === '' || pathname === '/index.html';
            const isTargetDomain = hostname === 'wideaccess.ca';
            const isWideViewport = (window.innerWidth || 0) >= 768;
            if (isTargetDomain && isLanding && isWideViewport && !getStorageValue(HIDE_WIDGET_PREF, false)) {
                setIsOpen(true);
            }
        } catch (e) {
            // no-op
        }
    }, []);

    useEffect(() => {
        // Add keyboard event listener for Ctrl+W
        const handleKeyDown = (event) => {
            // Check for Ctrl+W (works on both Windows and Mac)
            if ((event.ctrlKey || event.metaKey) && event.key === 'w') {
                event.preventDefault(); // Prevent browser close behavior
                setIsOpen(!isOpen);
            }
        };

        // Add event listener
        document.addEventListener('keydown', handleKeyDown);

        // Cleanup function to remove event listener
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isOpen]); // Include isOpen in dependency array

    useEffect(() => {
        preloadCursors();
    }, []);

    useEffect(() => {
        // restore hidden state from storage
        if (getStorageValue(HIDE_WIDGET_PREF, false)) {
            setIsHidden(true);
        }
    }, []);

    useEffect(() => {
        // Handle window resize to update position based on device type
        const handleResize = () => {
            const newDeviceType = getDeviceType();
            if (newDeviceType !== deviceType) {
                setDeviceType(newDeviceType);
            }
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, [deviceType]);

    const handleHide = () => {
        showConfirmHideModal({
            onConfirm: () => {
                setStorageValue(HIDE_WIDGET_PREF, true);
                setIsHidden(true);
            },
            onCancel: () => {
            },
        });
    };

    if (isHidden) {
        return null; // nothing to render
    }

    // Determine if any module is currently active
    const hasTypographyAdjustments = (
        (Number(currentFontSizeMultiplier) || 1) > 1 ||
        (Number(currentSpacing) || 0) > 0 ||
        (Number(currentLineHeight) || 1) > 1 ||
        (textAlignment && textAlignment !== 'none')
    );
    const anyModuleActive = (
        isHighContrastMode ||
        isMonochromeMode ||
        isLowSaturationMode ||
        isHighSaturationMode ||
        isLinksHighlighted ||
        isBigBlackCursorEnabled ||
        isBigWhiteCursorEnabled ||
        isFocusTunnelActive ||
        readableFont ||
        isMediaHidden ||
        hasTypographyAdjustments
    );

    return (
        <>
            {(() => {
                const iconConfig = window.WPWidgetConfig?.icon;
                const iconSize = window.WPWidgetConfig?.iconSize;
                const iconColor = window.WPWidgetConfig?.iconColor;

                // Determine the icon source
                let iconSrc;
                if (iconConfig?.type === 'custom' && iconConfig?.url) {
                    iconSrc = iconConfig.url;
                } else if (iconConfig?.type === 'default' && iconConfig?.name) {
                    iconSrc = getIconUrl(iconConfig.name);
                }

                // Get dynamic position based on widget position
                const positionStyles = getIconPosition(widgetPosition);

                const ringColor = getComplementaryColor((iconColor || '').replace(/^rgba?\(.+\)$/,'').trim() || iconColor);
                const baseShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';

                return (
                    <div
                        className="wideaccess-widget-toggle"
                        aria-label="Accessibility Settings"
                        onClick={() => setIsOpen(!isOpen)}
                        style={{
                            ...positionStyles,
                            cursor: "pointer",
                            width: `${iconSize}px`,
                            height: `${iconSize}px`,
                            boxShadow: anyModuleActive ? `${baseShadow}, 0 0 0 2px ${ringColor}` : baseShadow,
                        }}
                    >
                        <div 
                            style={{
                                width: '100%',
                                height: '100%',
                                borderRadius: '50%',
                                backgroundColor: iconColor,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                boxShadow: anyModuleActive ? `inset 0 0 0 2px ${ringColor}` : 'none',
                                transition: 'all 0.3s ease'
                            }}
                        >
                            <img
                                src={iconSrc}
                                alt="Accessibility Icon"
                                style={{
                                    width: '60%',
                                    height: '60%',
                                    filter: 'brightness(0) invert(1)' // Make icon white
                                }}
                            />
                        </div>
                    </div>
                );
            })()}
            <div className="wideaccess-widget-container">
                <WideAccessWidgetPanel
                    config={config}
                    onClose={() => setIsOpen(false)}
                    onHide={handleHide}
                    isOpen={isOpen}
                />
            </div>

            <SPAObserver/>
        </>
    );
}

export default WideAccessWidget;
