/**
 * Widget Section Base Component
 * 
 * A two-column layout component for widget customization.
 * Left side: Settings tabs
 * Right side: Live preview in ChatSimulator
 * 
 * @since 1.5.0
 */

import React, { useEffect, useMemo, useRef, useState, ReactNode } from 'react';
import { ChevronDown, ChevronUp, Settings, Eye } from 'lucide-react';
import { t } from '@/lib/i18n';

export interface WidgetSectionTab {
    id: string;
    label: string;
    icon?: ReactNode;
    content: ReactNode;
}

export interface WidgetSectionBaseProps {
    /** Section title */
    title: string;
    /** Section description */
    description: string;
    /** Icon to display */
    icon: ReactNode;
    /** Settings tabs */
    tabs: WidgetSectionTab[];
    /** Preview component */
    preview: ReactNode;
    /** Initial collapsed state */
    defaultCollapsed?: boolean;
    /** Custom class name */
    className?: string;
    /**
     * When true, the entire settings column becomes non-interactive (pointer-events: none).
     * Used to enforce "linked preset = read-only" UX.
     */
    disableSettingsPointerEvents?: boolean;
    /**
     * Optional: when settings are locked (linked preset), show a hover-only overlay
     * with an action button (e.g., "Unlink for independent editing").
     */
    lockedHoverActionLabel?: string;
    lockedHoverActionDescription?: string;
    onLockedHoverActionClick?: () => void;
}

export const WidgetSectionBase: React.FC<WidgetSectionBaseProps> = ({
    title,
    description,
    icon,
    tabs,
    preview,
    defaultCollapsed = true,
    className = '',
    disableSettingsPointerEvents = false,
    lockedHoverActionLabel = t('Edit preset'),
    lockedHoverActionDescription = t('To edit here, go to the preset editor'),
    onLockedHoverActionClick,
}) => {
    const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
    const [activeTab, setActiveTab] = useState(tabs[0]?.id || '');
    const [isSettingsHovered, setIsSettingsHovered] = useState(false);
    const previewContentRef = useRef<HTMLDivElement | null>(null);
    const [measuredHeight, setMeasuredHeight] = useState<number>(760);
    const [viewportHeight, setViewportHeight] = useState<number>(() => window.innerHeight);

    // Measure preview desired height based on ChatSimulator wrapper + paddings.
    useEffect(() => {
        if (isCollapsed) return;

        const el = previewContentRef.current;
        if (!el) return;

        const measure = () => {
            setViewportHeight(window.innerHeight);
            const wrapper = el.querySelector('.chat-simulator-wrapper') as HTMLElement | null;
            if (!wrapper) return;

            // IMPORTANT: ChatSimulator is often rendered with a CSS transform scale()
            // (e.g. GeneralChatViewSection uses scale(0.9)). getBoundingClientRect()
            // returns the *scaled* height which underestimates space needed.
            // scrollHeight/offsetHeight reflect layout height (pre-transform).
            const wrapperHeight = Math.max(wrapper.scrollHeight || 0, wrapper.offsetHeight || 0, wrapper.getBoundingClientRect().height || 0);
            const styles = window.getComputedStyle(el);
            const padTop = parseFloat(styles.paddingTop || '0') || 0;
            const padBottom = parseFloat(styles.paddingBottom || '0') || 0;

            // Include preview header height (we know it exists above this container).
            const previewHeader = el.parentElement?.querySelector('.bb-preset-editor-preview-header') as HTMLElement | null;
            const headerHeight = previewHeader ? previewHeader.getBoundingClientRect().height : 0;

            const desired = Math.ceil(headerHeight + padTop + padBottom + wrapperHeight);
            if (desired > 0) setMeasuredHeight(desired);
        };

        // Initial measure (after paint)
        const raf = window.requestAnimationFrame(measure);

        // ResizeObserver for when user changes chat window height etc.
        const ro = new ResizeObserver(() => measure());
        const wrapper = el.querySelector('.chat-simulator-wrapper') as HTMLElement | null;
        if (wrapper) ro.observe(wrapper);
        window.addEventListener('resize', measure);

        return () => {
            window.cancelAnimationFrame(raf);
            ro.disconnect();
            window.removeEventListener('resize', measure);
        };
    }, [isCollapsed, activeTab]);

    const containerHeightPx = useMemo(() => {
        const viewportBased = Math.max(0, viewportHeight - 280);
        return Math.max(760, viewportBased, measuredHeight);
    }, [measuredHeight, viewportHeight]);

    return (
        <div 
            className={`widget-section ${className}`}
            style={{
                background: '#FFFFFF',
                borderRadius: '16px',
                border: '1px solid #E5E7EB',
                marginBottom: '16px',
            }}
        >
            {/* Header */}
            <button
                onClick={() => setIsCollapsed(!isCollapsed)}
                style={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '16px',
                    padding: '20px 24px',
                    background: isCollapsed ? '#FFFFFF' : '#F9FAFB',
                    border: 'none',
                    cursor: 'pointer',
                    transition: 'background 0.2s ease',
                    textAlign: 'start',
                }}
            >
                {/* Icon */}
                <div
                    style={{
                        width: '48px',
                        height: '48px',
                        borderRadius: '12px',
                        background: 'linear-gradient(135deg, #3BC2D0 0%, #2BA8B5 100%)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#FFFFFF',
                        flexShrink: 0,
                    }}
                >
                    {icon}
                </div>

                {/* Title & Description */}
                <div style={{ flex: 1, minWidth: 0 }}>
                    <h3 
                        style={{ 
                            margin: 0, 
                            fontSize: '18px', 
                            fontWeight: 600, 
                            color: '#1F2937',
                        }}
                    >
                        {title}
                    </h3>
                    <p 
                        style={{ 
                            margin: '4px 0 0', 
                            fontSize: '14px', 
                            color: '#6B7280',
                        }}
                    >
                        {description}
                    </p>
                </div>

                {/* Collapse Arrow */}
                <div style={{ color: '#9CA3AF' }}>
                    {isCollapsed ? <ChevronDown size={24} /> : <ChevronUp size={24} />}
                </div>
            </button>

            {/* Content */}
            {!isCollapsed && (
                <div
                    style={{
                        borderTop: '1px solid #E5E7EB',
                        padding: '0',
                    }}
                >
                    <div
                        className="bb-preset-editor-columns"
                        style={{
                            display: 'grid',
                            gridTemplateColumns: '1fr 1fr',
                            minWidth: 0, // Prevent grid blowout
                            // Keep preview visible: internal scrolling instead of growing the whole page
                            height: `${containerHeightPx}px`,
                            overflow: 'hidden',
                        }}
                    >
                        {/* Settings Column */}
                        <div
                            className="bb-preset-editor-settings"
                            onMouseEnter={() => setIsSettingsHovered(true)}
                            onMouseLeave={() => setIsSettingsHovered(false)}
                            style={{
                                borderInlineStart: '1px solid #E5E7EB',
                                padding: '0',
                                display: 'flex',
                                flexDirection: 'column',
                                minWidth: 0, // Prevent flex blowout
                                overflow: 'hidden', // Contain children
                                position: 'relative',
                            }}
                        >
                            {/* Hover-only locked overlay */}
                            {disableSettingsPointerEvents && !!onLockedHoverActionClick && (
                                <div
                                    className="bb-preset-editor-settings-locked-overlay"
                                    style={{
                                        position: 'absolute',
                                        inset: 0,
                                        zIndex: 20,
                                        opacity: isSettingsHovered ? 1 : 0,
                                        pointerEvents: isSettingsHovered ? 'auto' : 'none',
                                        transition: 'opacity 150ms ease',
                                        background: 'rgba(255,255,255,0.55)',
                                        backdropFilter: 'blur(1px)',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        padding: '24px',
                                    }}
                                >
                                    <div
                                        style={{
                                            textAlign: 'center',
                                            maxWidth: 360,
                                        }}
                                    >
                                        <div style={{ fontSize: 13, color: '#374151', marginBottom: 12 }}>
                                            {lockedHoverActionDescription}
                                        </div>
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                onLockedHoverActionClick();
                                            }}
                                            style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                gap: 8,
                                                padding: '10px 14px',
                                                borderRadius: 10,
                                                border: 'none',
                                                background: '#0EA5E9', // sky-500
                                                color: '#FFFFFF',
                                                fontSize: 14,
                                                fontWeight: 600,
                                                cursor: 'pointer',
                                                boxShadow: '0 6px 18px rgba(0,0,0,0.12)',
                                            }}
                                        >
                                            {lockedHoverActionLabel}
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Tabs Header */}
                            <div
                                className="bb-preset-editor-settings-content"
                                style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    flex: 1,
                                    minHeight: 0,
                                    opacity: disableSettingsPointerEvents ? 0.65 : 1,
                                    pointerEvents: disableSettingsPointerEvents ? 'none' : 'auto',
                                }}
                            >
                                <div
                                    className="bb-preset-editor-settings-header"
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        padding: '12px 20px',
                                        borderBottom: '1px solid #E5E7EB',
                                        background: '#F9FAFB',
                                    }}
                                >
                                    <Settings size={16} color="#6B7280" />
                                    <span style={{ fontSize: '13px', fontWeight: 500, color: '#374151' }}>
                                        {t('Design Settings')}
                                    </span>
                                </div>

                                <div
                                    className="bb-preset-editor-settings-body"
                                    style={{
                                        flex: 1,
                                        display: 'flex',
                                        flexDirection: 'column',
                                        overflow: 'hidden',
                                        minHeight: 0,
                                    }}
                                >
                                    {/* Tab Navigation */}
                                    <div
                                        className="bb-preset-editor-tabs"
                                        style={{
                                            display: 'flex',
                                            flexWrap: 'wrap',
                                            gap: '4px',
                                            padding: '12px 16px',
                                            borderBottom: '1px solid #E5E7EB',
                                            background: '#FFFFFF',
                                            position: 'sticky',
                                            top: 0,
                                            zIndex: 1,
                                        }}
                                    >
                                        {tabs.map((tab) => (
                                            <button
                                                key={tab.id}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    setActiveTab(tab.id);
                                                }}
                                                style={{
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    gap: '6px',
                                                    padding: '8px 14px',
                                                    borderRadius: '8px',
                                                    border: 'none',
                                                    background: activeTab === tab.id ? '#3BC2D0' : '#F3F4F6',
                                                    color: activeTab === tab.id ? '#FFFFFF' : '#4B5563',
                                                    fontSize: '13px',
                                                    fontWeight: 500,
                                                    cursor: 'pointer',
                                                    transition: 'all 0.2s ease',
                                                    whiteSpace: 'nowrap',
                                                }}
                                            >
                                                {tab.icon}
                                                {tab.label}
                                            </button>
                                        ))}
                                    </div>

                                    {/* Tab Content */}
                                    <div
                                        className="bb-preset-editor-tab-content"
                                        style={{
                                            padding: '20px',
                                            flex: 1,
                                            overflowY: 'auto',
                                            minHeight: 0,
                                        }}
                                    >
                                        {tabs.find(t => t.id === activeTab)?.content}
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Preview Column */}
                        <div
                            className="bb-preset-editor-preview"
                            style={{
                                background: 'linear-gradient(135deg, #F3F4F6 0%, #E5E7EB 100%)',
                                display: 'flex',
                                flexDirection: 'column',
                                height: '100%',
                                overflow: 'hidden',
                            }}
                        >
                            {/* Preview Header */}
                            <div
                                className="bb-preset-editor-preview-header"
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '8px',
                                    padding: '12px 20px',
                                    borderBottom: '1px solid #E5E7EB',
                                    background: 'rgba(255,255,255,0.8)',
                                    flexShrink: 0,
                                }}
                            >
                                <Eye size={16} color="#6B7280" />
                                <span style={{ fontSize: '13px', fontWeight: 500, color: '#374151' }}>
                                    {t('Preview')}
                                </span>
                            </div>

                            {/* Preview Content */}
                            <div
                                className="bb-preset-editor-preview-content"
                                ref={previewContentRef}
                                style={{
                                    flex: 1,
                                    display: 'flex',
                                    alignItems: 'flex-start',
                                    justifyContent: 'center',
                                    padding: '24px',
                                    overflowY: 'auto',
                                    minHeight: 0,
                                }}
                            >
                                {preview}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default WidgetSectionBase;


