import React, { useEffect, useRef } from "react";
import TextSpacingModule from "./modules/TextSpacingModule";
import VisualAdjustmentsModule from "./modules/VisualAdjustmentsModule";
import NavigationFocusModule from "./modules/NavigationFocusModule";
import ResetModule from "./modules/ResetModule";
import { useWidget } from "./context/WidgetContext";
import { t } from "./translations";
import LanguageDropdown from "@/components/LanguageDropdown";
import MoveWidgetDropdown from "./components/MoveWidgetDropdown";
import XLModeToggle from "./components/XLModeToggle";
import { getWidgetConfig, getOptionsByGroup } from "./config/widget-config";
import {getIconUrl} from "./utils/icon-url";
import { setupOptionIcons, addOptionIcon } from "./utils/option-icons.jsx";
import { initializeSmoothScrolling } from "./utils/smooth-scroll";
import { showAccessibilityStatementModal } from "./components/accessibility-statement-modal";

function WideAccessWidgetPanel({config, onClose, onHide, isOpen}) {
    const { currentLanguage, widgetPosition, isXLMode } = useWidget();
    const groupsContainerRef = useRef(null);

    useEffect(() => {
        setupOptionIcons();

        // Debug header background color
        setTimeout(() => {
            const header = document.querySelector('.wideaccess-widget-header');
            if (header) {
                const computedStyle = getComputedStyle(header);
            }
        }, 100);
    }, []);
    
    // Ensure icons are set up immediately when panel opens, before slide animation
    useEffect(() => {
        if (isOpen) {
            // Set up icons synchronously before animation starts
            setupOptionIcons();
            // Also set up after a microtask to catch any async rendering
            Promise.resolve().then(() => {
                setupOptionIcons();
            });
        }
    }, [isOpen]);

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

    // Initialize smooth scrolling when component mounts
    useEffect(() => {
        if (groupsContainerRef.current) {
            initializeSmoothScrolling(groupsContainerRef.current);
        }
    }, []);

    // Get widget configuration
    const widgetConfig = getWidgetConfig();
    const enabledOptions = getOptionsByGroup(widgetConfig.enabledOptions);

    // Handle accessibility statement click
    const handleAccessibilityStatementClick = () => {
        const statementConfig = widgetConfig.accessibilityStatement;

        if (!statementConfig || !statementConfig.enabled) {
            return;
        }

        // Check mode: 'link' or 'generated'
        if (statementConfig.mode === 'link' && statementConfig.link) {
            // Mode 1: Redirect to external link
            window.open(statementConfig.link, '_blank', 'noopener,noreferrer');
        } else if (statementConfig.mode === 'generated' || statementConfig.text) {
            // Mode 2: Show modal with generated/custom text
            let statementText = statementConfig.text;

            // If no custom text, generate default statement
            if (!statementText && statementConfig.companyName) {
                const companyName = statementConfig.companyName || 'Example Company';
                const companyWebsite = statementConfig.companyWebsite || 'www.example.com';
                const businessEmail = statementConfig.businessEmail || 'contact@example.com';
                const today = new Date().toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });

                statementText = `<h2>Accessibility Statement for https://${companyWebsite}</h2>

<p>${companyName} is committed to ensuring digital accessibility for people with disabilities. We are continually improving the user experience for everyone and applying the relevant accessibility standards.</p>

<h3>Conformance status</h3>

<p>The Web Content Accessibility Guidelines (WCAG) defines requirements for designers and developers to improve accessibility for people with disabilities. It defines three levels of conformance: Level A, Level AA, and Level AAA.</p>

<p>${companyName} is making constant efforts to improve the accessibility of its site and services in the belief that it is our collective moral obligation to allow seamless, accessible, and unhindered use for those of us with disabilities.</p>

<p>We aim to make all pages and content on https://${companyWebsite} accessible, but some content may not yet fully meet the highest accessibility standards. This could be due to challenges in identifying the most suitable technological solution.</p>

<p>We may revise this Statement periodically to reflect improvements or changes to our accessibility practices.</p>

<h3>Feedback</h3>

<p>We welcome your feedback on the accessibility of ${companyName} website. Please let us know if you encounter accessibility barriers on our website:</p>

<p>E-mail: ${businessEmail}</p>

<p>We try to respond to feedback within 3-5 business days.</p>

<p>This statement was created on ${today}.</p>`;
            }

            showAccessibilityStatementModal({
                statementText: statementText,
                onClose: () => {
                    // Modal cleanup is handled by the modal component
                }
            });
        }
    };

    return (
        <div className={`wideaccess-widget-panel ${isOpen ? 'open' : ''} ${widgetPosition === 'left' ? 'left' : ''} ${isXLMode ? 'xl-mode' : ''}`} data-position={widgetPosition}>
            <div className="wideaccess-widget-header">
                <div className="wideaccess-widget-header-top">
                    <button
                        className="wideaccess-widget-close"
                        onClick={onClose}
                        aria-label="Close widget"
                    >
                        <img
                            src={getIconUrl('close')}
                            alt="Close"
                            className="wideaccess-close-icon"
                        />
                    </button>
                    <button
                        className="wideaccess-widget-hide"
                        onClick={onHide}
                        aria-label="Hide widget"
                    >
                        <img
                            src={getIconUrl('hide')}
                            alt="Hide"
                            className="wideaccess-hide-icon"
                        />
                    </button>
                </div>
                <div className="wideaccess-header-center">
                    {(() => {
                        const titleText = t('accessibilitySettings', currentLanguage) || '';
                        const isLongTitle = titleText.length > 28;
                        const extraEsClass = isLongTitle && currentLanguage === 'es' ? 'wideaccess-title-compact-es' : '';
                        const compactClass = isLongTitle ? 'wideaccess-title-compact' : '';
                        const langSizeClass =
                            currentLanguage === 'pt' ? 'wideaccess-title-lang-pt' :
                                (currentLanguage === 'nl' || currentLanguage === 'da' || currentLanguage === 'el') ? 'wideaccess-title-lang-2' : '';
                        return (
                            <span className={`wideaccess-widget-title ${compactClass} ${extraEsClass} ${langSizeClass}`}>{titleText}</span>
                        );
                    })()}
                </div>
            </div>

            <div className="wideaccess-widget-content">
                {/* Content wrapper - now empty, just provides background */}
            </div>

            <div className="wideaccess-widget-content-wrapper">
                <div className="wideaccess-widget-groups-container" ref={groupsContainerRef}>
                    <div className="wideaccess-widget-group wideaccess-widget-controls-wrapper">
                    <div className="wideaccess-widget-controls">
                        <LanguageDropdown/>
                        <MoveWidgetDropdown/>
                        <XLModeToggle/>
                    </div>
                </div>

                {enabledOptions.textSpacing.length > 0 && (
                        <TextSpacingModule config={config} enabledOptions={enabledOptions.textSpacing}/>
                    )}
                    {enabledOptions.visualAdjustments.length > 0 && (
                        <VisualAdjustmentsModule config={config} enabledOptions={enabledOptions.visualAdjustments}/>
                    )}
                    {enabledOptions.navigationFocus.length > 0 && (
                        <NavigationFocusModule config={config} enabledOptions={enabledOptions.navigationFocus}/>
                    )}
                    {enabledOptions.reset.length > 0 && (
                        <ResetModule enabledOptions={enabledOptions.reset}/>
                    )}
                </div>
            </div>

            {/* Only show footer if there's content to display */}
            {(!widgetConfig.hidePoweredBy || widgetConfig.accessibilityStatement?.enabled) && (
                <div className="wideaccess-widget-footer">
                    {(widgetConfig.accessibilityStatement?.enabled === true) && (
                        (() => {
                            const stmt = widgetConfig.accessibilityStatement;
                            if (stmt?.mode === 'link' && stmt?.link) {
                                return (
                                    <a
                                        href={stmt.link}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="wideaccess-widget-accessibility-statement"
                                        aria-label={t('accessibilityStatement', currentLanguage)}
                                    >
                                        {t('accessibilityStatement', currentLanguage)}
                                    </a>
                                );
                            }
                            return (
                                <button
                                    onClick={handleAccessibilityStatementClick}
                                    className="wideaccess-widget-accessibility-statement"
                                    aria-label={t('accessibilityStatement', currentLanguage)}
                                >
                                    {t('accessibilityStatement', currentLanguage)}
                                </button>
                            );
                        })()
                    )}
                    {!widgetConfig.hidePoweredBy && (
                        <a
                            href="https://wideaccess.ca"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="wideaccess-widget-branding-link"
                        >
                            <span className="wideaccess-widget-branding-text">{t('webAccessibilityBy', currentLanguage)}</span>
                            <img
                                src={getIconUrl('w_logo_light', 'svg')}
                                alt="WideAccess Logo"
                                className="wideaccess-widget-footer-logo"
                            />
                            <span className="wideaccess-widget-branding-name">WideAccess</span>
                        </a>
                    )}
                </div>
            )}
        </div>
    );
}

export default WideAccessWidgetPanel;
