/**
 * Typography Section Component
 * Week 21 V2 - Visual Element Editor
 * 
 * Manages global typography settings with Elementor-style compact design.
 * Includes live chat preview on the left side.
 */

import React, { useState } from 'react';
import { TypographySettings, TypographyEntry, PresetGlobalValues, DEFAULT_GLOBAL_VALUES, CustomTypographyScale } from '../../../types/appearance';
import { Type, ChevronDown, ChevronUp, MessageCircle, Bot, Send, Plus, Download, Trash2 } from 'lucide-react';
import { apiClient } from '../../../api/client';
import { t } from '@/lib/i18n';

interface TypographySectionProps {
    typography: TypographySettings;
    globalValues?: PresetGlobalValues;
    onChange: (typography: TypographySettings) => void;
    onImportElementor?: () => void;
    disabled?: boolean;
}

interface ScaleConfig {
    key: keyof Pick<TypographySettings, 'heading' | 'body' | 'small' | 'button'>;
    label: string;
    elementorName: string;
    example: string;
}

function getScaleConfigs(): ScaleConfig[] {
    return [
        { key: 'heading', label: t('Primary'), elementorName: 'primary', example: t('Hello! How can I help?') },
        { key: 'body', label: t('Secondary'), elementorName: 'secondary', example: t('This is a regular chat message') },
        { key: 'small', label: t('Text'), elementorName: 'text', example: t('Sent 2 minutes ago') },
        { key: 'button', label: t('Accent'), elementorName: 'accent', example: t('Send Message') },
    ];
}

function getDefaultFontFamilyOptions() {
    return [
        { value: 'inherit', label: t('Default') },
        { value: '"Open Sans", sans-serif', label: 'Open Sans' },
        { value: 'system-ui, -apple-system, sans-serif', label: 'System UI' },
        { value: '"Heebo", sans-serif', label: 'Heebo' },
        { value: '"Assistant", sans-serif', label: 'Assistant' },
        { value: '"Rubik", sans-serif', label: 'Rubik' },
        { value: '"Inter", sans-serif', label: 'Inter' },
        { value: '"Roboto", sans-serif', label: 'Roboto' },
        { value: '"Arial", sans-serif', label: 'Arial' },
    ];
}

/**
 * Inject custom font CSS into the document head.
 * This is used for Elementor custom fonts that need @font-face definitions.
 */
const injectCustomFontCss = (css: string) => {
    // Remove existing custom font style if any
    const existingStyle = document.getElementById('boostbot-custom-fonts-admin');
    if (existingStyle) {
        existingStyle.remove();
    }
    
    // Create and inject new style element
    const style = document.createElement('style');
    style.id = 'boostbot-custom-fonts-admin';
    style.textContent = css;
    document.head.appendChild(style);
};

function getFontWeightOptions() {
    return [
        { value: '100', label: t('Thin (100)') },
        { value: '200', label: t('Extra Light (200)') },
        { value: '300', label: t('Light (300)') },
        { value: '400', label: t('Regular (400)') },
        { value: '500', label: t('Medium (500)') },
        { value: '600', label: t('Semi-Bold (600)') },
        { value: '700', label: t('Bold (700)') },
        { value: '800', label: t('Extra Bold (800)') },
        { value: '900', label: t('Black (900)') },
    ];
}

function getTextTransformOptions() {
    return [
        { value: 'none', label: t('Default') },
        { value: 'uppercase', label: t('Uppercase') },
        { value: 'lowercase', label: t('Lowercase') },
        { value: 'capitalize', label: t('Capitalize') },
    ];
}

function getFontStyleOptions() {
    return [
        { value: 'normal', label: t('Normal') },
        { value: 'italic', label: t('Italic') },
    ];
}

function getTextDecorationOptions() {
    return [
        { value: 'none', label: t('None') },
        { value: 'underline', label: t('Underline') },
        { value: 'line-through', label: t('Strikethrough') },
        { value: 'overline', label: t('Overline') },
    ];
}

export const TypographySection: React.FC<TypographySectionProps> = ({
    typography,
    globalValues = DEFAULT_GLOBAL_VALUES,
    onChange,
    onImportElementor,
    disabled = false,
}) => {
    const [expandedScale, setExpandedScale] = useState<string | null>(null);
    const [isImporting, setIsImporting] = useState(false);
    const [importMessage, setImportMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
    const [newScaleName, setNewScaleName] = useState('');
    const [customFonts, setCustomFonts] = useState<string[]>([]);
    
    // Initialize customFonts from the current typography value
    // This ensures imported fonts persist across page refreshes
    React.useEffect(() => {
        const fontsToAdd: string[] = [];
        
        // Check main font family
        if (typography.fontFamily && typography.fontFamily !== 'inherit') {
            const isDefault = getDefaultFontFamilyOptions().some(o => o.value === typography.fontFamily);
            if (!isDefault && !fontsToAdd.includes(typography.fontFamily)) {
                fontsToAdd.push(typography.fontFamily);
            }
        }
        
        // Check scale font families
        const scales = ['heading', 'body', 'small', 'button'] as const;
        scales.forEach(scale => {
            const scaleFont = typography[scale]?.fontFamily;
            if (scaleFont && scaleFont !== 'inherit') {
                const isDefault = getDefaultFontFamilyOptions().some(o => o.value === scaleFont);
                if (!isDefault && !fontsToAdd.includes(scaleFont)) {
                    fontsToAdd.push(scaleFont);
                }
            }
        });
        
        if (fontsToAdd.length > 0) {
            setCustomFonts(prev => [...new Set([...prev, ...fontsToAdd])]);
        }
    }, [typography.fontFamily]); // Run when typography fontFamily changes
    
    // Build font family options including custom fonts and current value
    const fontFamilyOptions = React.useMemo(() => {
        const options = [...getDefaultFontFamilyOptions()];
        
        // Add custom fonts from Elementor import
        customFonts.forEach(font => {
            if (!options.find(o => o.value === font)) {
                options.splice(1, 0, { value: font, label: font });
            }
        });
        
        // Add current font if not in list (e.g., custom imported font)
        const currentFont = typography.fontFamily;
        if (currentFont && currentFont !== 'inherit' && !options.find(o => o.value === currentFont)) {
            // Clean font name for display
            const displayName = currentFont.replace(/['"]/g, '').split(',')[0].trim();
            options.splice(1, 0, { value: currentFont, label: `${displayName} ★` });
        }
        
        return options;
    }, [customFonts, typography.fontFamily]);
    
    // Handle font family change
    const handleFontFamilyChange = (fontFamily: string) => {
        onChange({ ...typography, fontFamily });
    };
    
    // Handle scale entry change
    const handleScaleChange = (
        scale: keyof Pick<TypographySettings, 'heading' | 'body' | 'small' | 'button'>,
        field: keyof TypographyEntry,
        value: string
    ) => {
        onChange({
            ...typography,
            [scale]: {
                ...typography[scale],
                [field]: value,
            },
        });
    };
    
    // Handle custom scale change
    const handleCustomScaleChange = (index: number, field: keyof CustomTypographyScale, value: string) => {
        const customScales = [...(typography.custom || [])];
        customScales[index] = { ...customScales[index], [field]: value };
        onChange({ ...typography, custom: customScales });
    };
    
    // Add new custom scale
    const handleAddCustomScale = () => {
        if (!newScaleName.trim()) return;
        
        const newScale: CustomTypographyScale = {
            id: `custom_${Date.now()}`,
            name: newScaleName.trim(),
            fontSize: '14px',
            fontWeight: '400',
            lineHeight: '1.5',
        };
        
        onChange({
            ...typography,
            custom: [...(typography.custom || []), newScale],
        });
        setNewScaleName('');
    };
    
    // Remove custom scale
    const handleRemoveCustomScale = (index: number) => {
        const customScales = [...(typography.custom || [])];
        customScales.splice(index, 1);
        onChange({ ...typography, custom: customScales });
    };
    
    // Import from Elementor
    const handleImportElementor = async () => {
        setIsImporting(true);
        setImportMessage(null);
        
        try {
            const response = await apiClient.get<{ data: { message: string; imported: any } }>('appearance-presets/import-elementor');
            const imported = response?.data?.imported;
            
            if (imported?.typography) {
                const newTypography = { ...typography };
                const newCustomFonts: string[] = [];
                
                // Update font family
                if (imported.typography.fontFamily) {
                    newTypography.fontFamily = imported.typography.fontFamily;
                    // Add to custom fonts list
                    if (imported.typography.fontFamily !== 'inherit') {
                        newCustomFonts.push(imported.typography.fontFamily);
                    }
                }
                
                // Collect all unique fonts from scales
                const collectFont = (fontFamily: string | undefined) => {
                    if (fontFamily && fontFamily !== 'inherit' && !newCustomFonts.includes(fontFamily)) {
                        newCustomFonts.push(fontFamily);
                    }
                };
                
                if (imported.typography.headingScale?.fontFamily) collectFont(imported.typography.headingScale.fontFamily);
                if (imported.typography.bodyScale?.fontFamily) collectFont(imported.typography.bodyScale.fontFamily);
                if (imported.typography.smallScale?.fontFamily) collectFont(imported.typography.smallScale.fontFamily);
                if (imported.typography.buttonScale?.fontFamily) collectFont(imported.typography.buttonScale.fontFamily);
                
                // Update custom fonts state
                setCustomFonts(prev => [...new Set([...prev, ...newCustomFonts])]);
                
                // Helper to merge scale with all Elementor fields
                const mergeScale = (current: TypographyEntry, imported: any): TypographyEntry => ({
                    fontFamily: imported.fontFamily || current.fontFamily,
                    fontSize: imported.fontSize || current.fontSize,
                    fontWeight: imported.fontWeight || current.fontWeight,
                    textTransform: imported.textTransform || current.textTransform,
                    fontStyle: imported.fontStyle || current.fontStyle,
                    textDecoration: imported.textDecoration || current.textDecoration,
                    lineHeight: imported.lineHeight || current.lineHeight,
                    letterSpacing: imported.letterSpacing || current.letterSpacing,
                    wordSpacing: imported.wordSpacing || current.wordSpacing,
                });

                // Update scales with all typography properties
                if (imported.typography.headingScale) {
                    newTypography.heading = mergeScale(newTypography.heading, imported.typography.headingScale);
                }
                if (imported.typography.bodyScale) {
                    newTypography.body = mergeScale(newTypography.body, imported.typography.bodyScale);
                }
                if (imported.typography.smallScale) {
                    newTypography.small = mergeScale(newTypography.small, imported.typography.smallScale);
                }
                if (imported.typography.buttonScale) {
                    newTypography.button = mergeScale(newTypography.button, imported.typography.buttonScale);
                }
                
                // Add custom scales from Elementor with all properties
                if (imported.typography.customScales && imported.typography.customScales.length > 0) {
                    const newCustomScales = imported.typography.customScales.map((scale: any, index: number) => ({
                        id: `elementor_${Date.now()}_${index}`,
                        name: scale.name || `Elementor ${index + 1}`,
                        fontFamily: scale.fontFamily || newTypography.fontFamily,
                        fontSize: scale.fontSize || '14px',
                        fontWeight: scale.fontWeight || '400',
                        textTransform: scale.textTransform || 'none',
                        fontStyle: scale.fontStyle || 'normal',
                        textDecoration: scale.textDecoration || 'none',
                        lineHeight: scale.lineHeight || '1.5',
                        letterSpacing: scale.letterSpacing || '0px',
                        wordSpacing: scale.wordSpacing || '0px',
                    }));
                    newTypography.custom = [...(typography.custom || []), ...newCustomScales];
                }
                
                onChange(newTypography);
                onImportElementor?.();
                
                // Inject custom font CSS if available
                if (imported.customFontCss) {
                    injectCustomFontCss(imported.customFontCss);
                }
            }
            
            setImportMessage({ type: 'success', text: t('Elementor settings imported successfully!') });
        } catch (error: any) {
            setImportMessage({ 
                type: 'error', 
                text: error?.message || t('Error importing Elementor settings') 
            });
        } finally {
            setIsImporting(false);
            setTimeout(() => setImportMessage(null), 5000);
        }
    };

    const toggleScale = (key: string) => {
        setExpandedScale(expandedScale === key ? null : key);
    };
    
    return (
        <div className="typography-section">
            <div style={{ display: 'flex', gap: '24px', direction: 'rtl' }}>
                {/* Settings Column */}
                <div style={{ flex: '1', minWidth: 0 }}>
                    {/* Import from Elementor Button */}
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        marginBottom: '16px',
                        padding: '10px 12px',
                        background: 'linear-gradient(135deg, #92003B 0%, #FF6F61 100%)',
                        borderRadius: '8px',
                    }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <Download size={16} color="#FFFFFF" />
                            <span style={{ fontSize: '13px', fontWeight: 600, color: '#FFFFFF' }}>
                                {t('Import from Elementor')}
                            </span>
                        </div>
                        <button
                            onClick={handleImportElementor}
                            disabled={disabled || isImporting}
                            style={{
                                padding: '6px 14px',
                                background: '#FFFFFF',
                                border: 'none',
                                borderRadius: '6px',
                                fontSize: '12px',
                                fontWeight: 600,
                                color: '#92003B',
                                cursor: disabled || isImporting ? 'not-allowed' : 'pointer',
                                opacity: disabled || isImporting ? 0.7 : 1,
                            }}
                        >
                            {isImporting ? t('Importing...') : t('Import Settings')}
                        </button>
                    </div>
                    
                    {/* Import Message */}
                    {importMessage && (
                        <div style={{
                            padding: '10px 12px',
                            marginBottom: '16px',
                            borderRadius: '8px',
                            background: importMessage.type === 'success' ? '#D1FAE5' : '#FEE2E2',
                            color: importMessage.type === 'success' ? '#065F46' : '#991B1B',
                            fontSize: '12px',
                            fontWeight: 500,
                        }}>
                            {importMessage.text}
                        </div>
                    )}
                    
                    {/* Font Family - Compact Row */}
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '12px',
                        padding: '12px',
                        background: '#F9FAFB',
                        borderRadius: '8px',
                        marginBottom: '16px',
                    }}>
                        <Type size={18} style={{ color: globalValues.colors?.primary ?? '#3BC2D0', flexShrink: 0 }} />
                        <div style={{ flex: 1 }}>
                            <div style={{ fontSize: '13px', fontWeight: 600, color: '#374151', marginBottom: '4px' }}>
                                {t('Main Font')}
                            </div>
                            <select
                                value={typography.fontFamily}
                                onChange={(e) => handleFontFamilyChange(e.target.value)}
                                disabled={disabled}
                                style={{
                                    width: '100%',
                                    padding: '6px 10px',
                                    border: '1px solid #E5E7EB',
                                    borderRadius: '6px',
                                    fontSize: '12px',
                                    background: '#FFFFFF',
                                }}
                            >
                                {fontFamilyOptions.map((option) => (
                                    <option key={option.value} value={option.value}>
                                        {option.label}
                                    </option>
                                ))}
                            </select>
                        </div>
                        {/* Font Preview */}
                        <div
                            style={{
                                fontFamily: typography.fontFamily,
                                fontSize: '14px',
                                color: '#374151',
                                background: '#FFFFFF',
                                padding: '8px 16px',
                                borderRadius: '6px',
                                border: '1px solid #E5E7EB',
                                whiteSpace: 'nowrap',
                            }}
                        >
                            אבג ABC 123
                        </div>
                    </div>
                    
                    {/* Typography Scales - Compact Accordion */}
                    <div style={{ 
                        border: '1px solid #E5E7EB',
                        borderRadius: '8px',
                        overflow: 'hidden',
                    }}>
                        {getScaleConfigs().map((config, index) => (
                            <div key={config.key}>
                                {/* Scale Header - Always Visible */}
                                <div
                                    onClick={() => toggleScale(config.key)}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        padding: '10px 12px',
                                        background: expandedScale === config.key ? '#F3F4F6' : '#FFFFFF',
                                        cursor: 'pointer',
                                        borderTop: index > 0 ? '1px solid #E5E7EB' : 'none',
                                        transition: 'background 0.2s ease',
                                    }}
                                >
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                        <span style={{ 
                                            fontSize: '12px', 
                                            fontWeight: 600, 
                                            color: '#374151',
                                            minWidth: '70px',
                                        }}>
                                            {config.label}
                                        </span>
                                        {/* Live Example - Inline */}
                                        <span
                                            style={{
                                                fontFamily: typography.fontFamily,
                                                fontSize: typography[config.key].fontSize,
                                                fontWeight: typography[config.key].fontWeight as any,
                                                lineHeight: typography[config.key].lineHeight,
                                                color: '#6B7280',
                                            }}
                                        >
                                            {config.example}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                        <span style={{ fontSize: '10px', color: '#9CA3AF' }}>
                                            {typography[config.key].fontSize} / {typography[config.key].fontWeight}
                                        </span>
                                        {expandedScale === config.key ? (
                                            <ChevronUp size={14} color="#9CA3AF" />
                                        ) : (
                                            <ChevronDown size={14} color="#9CA3AF" />
                                        )}
                                    </div>
                                </div>
                                
                                {/* Scale Settings - Expandable (Elementor-style) */}
                                {expandedScale === config.key && (
                                    <div style={{
                                        padding: '12px',
                                        background: '#F9FAFB',
                                        borderTop: '1px solid #E5E7EB',
                                    }}>
                                        {/* Row 1: Font Family & Size */}
                                        <div style={{ 
                                            display: 'grid', 
                                            gridTemplateColumns: '1fr 1fr', 
                                            gap: '12px',
                                            marginBottom: '12px',
                                        }}>
                                            {/* Font Family */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Family')}
                                                </label>
                                                <select
                                                    value={typography[config.key].fontFamily || typography.fontFamily}
                                                    onChange={(e) => handleScaleChange(config.key, 'fontFamily', e.target.value)}
                                                    disabled={disabled}
                                                    style={{ width: '100%', padding: '6px 8px', border: '1px solid #E5E7EB', borderRadius: '4px', fontSize: '11px', background: '#FFFFFF' }}
                                                >
                                                    {fontFamilyOptions.map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                            
                                            {/* Font Size */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Size')}
                                                </label>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                                    <input
                                                        type="range"
                                                        min="8"
                                                        max="72"
                                                        value={parseInt(typography[config.key].fontSize) || 14}
                                                        onChange={(e) => handleScaleChange(config.key, 'fontSize', `${e.target.value}px`)}
                                                        disabled={disabled}
                                                        style={{ flex: 1, height: '4px' }}
                                                    />
                                                    <input
                                                        type="text"
                                                        value={typography[config.key].fontSize}
                                                        onChange={(e) => handleScaleChange(config.key, 'fontSize', e.target.value)}
                                                        disabled={disabled}
                                                        style={{ width: '50px', textAlign: 'center', fontSize: '10px', border: '1px solid #E5E7EB', borderRadius: '4px', padding: '4px' }}
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Row 2: Weight & Transform */}
                                        <div style={{ 
                                            display: 'grid', 
                                            gridTemplateColumns: '1fr 1fr', 
                                            gap: '12px',
                                            marginBottom: '12px',
                                        }}>
                                            {/* Font Weight */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Weight')}
                                                </label>
                                                <select
                                                    value={typography[config.key].fontWeight}
                                                    onChange={(e) => handleScaleChange(config.key, 'fontWeight', e.target.value)}
                                                    disabled={disabled}
                                                    style={{ width: '100%', padding: '6px 8px', border: '1px solid #E5E7EB', borderRadius: '4px', fontSize: '11px', background: '#FFFFFF' }}
                                                >
                                                    {getFontWeightOptions().map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                            
                                            {/* Text Transform */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Transform')}
                                                </label>
                                                <select
                                                    value={typography[config.key].textTransform || 'none'}
                                                    onChange={(e) => handleScaleChange(config.key, 'textTransform', e.target.value)}
                                                    disabled={disabled}
                                                    style={{ width: '100%', padding: '6px 8px', border: '1px solid #E5E7EB', borderRadius: '4px', fontSize: '11px', background: '#FFFFFF' }}
                                                >
                                                    {getTextTransformOptions().map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                        </div>

                                        {/* Row 3: Style & Decoration */}
                                        <div style={{ 
                                            display: 'grid', 
                                            gridTemplateColumns: '1fr 1fr', 
                                            gap: '12px',
                                            marginBottom: '12px',
                                        }}>
                                            {/* Font Style */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Style')}
                                                </label>
                                                <select
                                                    value={typography[config.key].fontStyle || 'normal'}
                                                    onChange={(e) => handleScaleChange(config.key, 'fontStyle', e.target.value)}
                                                    disabled={disabled}
                                                    style={{ width: '100%', padding: '6px 8px', border: '1px solid #E5E7EB', borderRadius: '4px', fontSize: '11px', background: '#FFFFFF' }}
                                                >
                                                    {getFontStyleOptions().map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                            
                                            {/* Text Decoration */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Decoration')}
                                                </label>
                                                <select
                                                    value={typography[config.key].textDecoration || 'none'}
                                                    onChange={(e) => handleScaleChange(config.key, 'textDecoration', e.target.value)}
                                                    disabled={disabled}
                                                    style={{ width: '100%', padding: '6px 8px', border: '1px solid #E5E7EB', borderRadius: '4px', fontSize: '11px', background: '#FFFFFF' }}
                                                >
                                                    {getTextDecorationOptions().map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </select>
                                            </div>
                                        </div>

                                        {/* Row 4: Line Height, Letter Spacing, Word Spacing */}
                                        <div style={{ 
                                            display: 'grid', 
                                            gridTemplateColumns: '1fr 1fr 1fr', 
                                            gap: '12px',
                                        }}>
                                            {/* Line Height */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Line Height')}
                                                </label>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                    <input
                                                        type="range"
                                                        min="0.8"
                                                        max="3"
                                                        step="0.1"
                                                        value={parseFloat(typography[config.key].lineHeight) || 1.5}
                                                        onChange={(e) => handleScaleChange(config.key, 'lineHeight', e.target.value)}
                                                        disabled={disabled}
                                                        style={{ flex: 1, height: '4px' }}
                                                    />
                                                    <input
                                                        type="text"
                                                        value={typography[config.key].lineHeight}
                                                        onChange={(e) => handleScaleChange(config.key, 'lineHeight', e.target.value)}
                                                        disabled={disabled}
                                                        style={{ width: '40px', textAlign: 'center', fontSize: '10px', border: '1px solid #E5E7EB', borderRadius: '4px', padding: '4px' }}
                                                    />
                                                </div>
                                            </div>
                                            
                                            {/* Letter Spacing */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Letter Spacing')}
                                                </label>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                    <input
                                                        type="range"
                                                        min="-2"
                                                        max="10"
                                                        step="0.1"
                                                        value={parseFloat(typography[config.key].letterSpacing || '0') || 0}
                                                        onChange={(e) => handleScaleChange(config.key, 'letterSpacing', `${e.target.value}px`)}
                                                        disabled={disabled}
                                                        style={{ flex: 1, height: '4px' }}
                                                    />
                                                    <input
                                                        type="text"
                                                        value={typography[config.key].letterSpacing || '0px'}
                                                        onChange={(e) => handleScaleChange(config.key, 'letterSpacing', e.target.value)}
                                                        disabled={disabled}
                                                        style={{ width: '45px', textAlign: 'center', fontSize: '10px', border: '1px solid #E5E7EB', borderRadius: '4px', padding: '4px' }}
                                                    />
                                                </div>
                                            </div>
                                            
                                            {/* Word Spacing */}
                                            <div>
                                                <label style={{ fontSize: '10px', fontWeight: 500, color: '#6B7280', marginBottom: '4px', display: 'block' }}>
                                                    {t('Word Spacing')}
                                                </label>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                    <input
                                                        type="range"
                                                        min="-5"
                                                        max="20"
                                                        step="0.5"
                                                        value={parseFloat(typography[config.key].wordSpacing || '0') || 0}
                                                        onChange={(e) => handleScaleChange(config.key, 'wordSpacing', `${e.target.value}px`)}
                                                        disabled={disabled}
                                                        style={{ flex: 1, height: '4px' }}
                                                    />
                                                    <input
                                                        type="text"
                                                        value={typography[config.key].wordSpacing || '0px'}
                                                        onChange={(e) => handleScaleChange(config.key, 'wordSpacing', e.target.value)}
                                                        disabled={disabled}
                                                        style={{ width: '45px', textAlign: 'center', fontSize: '10px', border: '1px solid #E5E7EB', borderRadius: '4px', padding: '4px' }}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                    
                    {/* Custom Typography Scales */}
                    <div style={{ marginTop: '16px' }}>
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            marginBottom: '12px',
                        }}>
                            <h4 style={{ fontSize: '13px', fontWeight: 600, color: '#374151', margin: 0 }}>
                                {t('Custom Typography Scales')}
                            </h4>
                        </div>
                        
                        {/* Add New Custom Scale */}
                        <div style={{
                            display: 'flex',
                            gap: '8px',
                            marginBottom: '12px',
                        }}>
                            <input
                                type="text"
                                placeholder={t('New scale name...')}
                                value={newScaleName}
                                onChange={(e) => setNewScaleName(e.target.value)}
                                onKeyPress={(e) => e.key === 'Enter' && handleAddCustomScale()}
                                disabled={disabled}
                                style={{
                                    flex: 1,
                                    padding: '8px 12px',
                                    border: '1px solid #E5E7EB',
                                    borderRadius: '6px',
                                    fontSize: '12px',
                                }}
                            />
                            <button
                                onClick={handleAddCustomScale}
                                disabled={disabled || !newScaleName.trim()}
                                style={{
                                    padding: '8px 16px',
                                    background: globalValues.colors?.primary ?? '#3BC2D0',
                                    color: '#FFFFFF',
                                    border: 'none',
                                    borderRadius: '6px',
                                    fontSize: '12px',
                                    fontWeight: 600,
                                    cursor: disabled || !newScaleName.trim() ? 'not-allowed' : 'pointer',
                                    opacity: disabled || !newScaleName.trim() ? 0.5 : 1,
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px',
                                }}
                            >
                                <Plus size={14} />
                                {t('Add')}
                            </button>
                        </div>
                        
                        {/* Custom Scales List */}
                        {(typography.custom || []).length > 0 && (
                            <div style={{
                                border: '1px solid #E5E7EB',
                                borderRadius: '8px',
                                overflow: 'hidden',
                            }}>
                                {(typography.custom || []).map((scale, index) => (
                                    <div key={scale.id}>
                                        {/* Scale Header */}
                                        <div
                                            onClick={() => toggleScale(`custom_${index}`)}
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'space-between',
                                                padding: '10px 12px',
                                                background: expandedScale === `custom_${index}` ? '#FEF3C7' : '#FFFBEB',
                                                cursor: 'pointer',
                                                borderTop: index > 0 ? '1px solid #E5E7EB' : 'none',
                                            }}
                                        >
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                <span style={{
                                                    fontSize: '12px',
                                                    fontWeight: 600,
                                                    color: '#92400E',
                                                    minWidth: '70px',
                                                }}>
                                                    {scale.name}
                                                </span>
                                                <span
                                                    style={{
                                                        fontFamily: scale.fontFamily || typography.fontFamily,
                                                        fontSize: scale.fontSize,
                                                        fontWeight: scale.fontWeight as any,
                                                        lineHeight: scale.lineHeight,
                                                        color: '#6B7280',
                                                    }}
                                                >
                                                    {t('Sample text')}
                                                </span>
                                            </div>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                <span style={{ fontSize: '10px', color: '#9CA3AF' }}>
                                                    {scale.fontSize} / {scale.fontWeight}
                                                </span>
                                                <button
                                                    type="button"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleRemoveCustomScale(index);
                                                    }}
                                                    disabled={disabled}
                                                    style={{
                                                        background: 'none',
                                                        border: 'none',
                                                        cursor: disabled ? 'not-allowed' : 'pointer',
                                                        padding: '4px',
                                                        color: '#EF4444',
                                                        opacity: disabled ? 0.5 : 1,
                                                    }}
                                                >
                                                    <Trash2 size={14} />
                                                </button>
                                                {expandedScale === `custom_${index}` ? (
                                                    <ChevronUp size={14} color="#9CA3AF" />
                                                ) : (
                                                    <ChevronDown size={14} color="#9CA3AF" />
                                                )}
                                            </div>
                                        </div>
                                        
                                        {/* Scale Settings */}
                                        {expandedScale === `custom_${index}` && (
                                            <div style={{
                                                padding: '12px',
                                                background: '#FFFBEB',
                                                borderTop: '1px solid #E5E7EB',
                                            }}>
                                                <div style={{
                                                    display: 'grid',
                                                    gridTemplateColumns: 'repeat(3, 1fr)',
                                                    gap: '12px',
                                                }}>
                                                    {/* Font Size */}
                                                    <div>
                                                        <label style={{
                                                            fontSize: '10px',
                                                            fontWeight: 500,
                                                            color: '#6B7280',
                                                            marginBottom: '4px',
                                                            display: 'block',
                                                        }}>
                                                            {t('Size')}
                                                        </label>
                                                        <input
                                                            type="text"
                                                            value={scale.fontSize}
                                                            onChange={(e) => handleCustomScaleChange(index, 'fontSize', e.target.value)}
                                                            disabled={disabled}
                                                            style={{
                                                                width: '100%',
                                                                padding: '6px 10px',
                                                                border: '1px solid #E5E7EB',
                                                                borderRadius: '4px',
                                                                fontSize: '11px',
                                                            }}
                                                        />
                                                    </div>
                                                    
                                                    {/* Font Weight */}
                                                    <div>
                                                        <label style={{
                                                            fontSize: '10px',
                                                            fontWeight: 500,
                                                            color: '#6B7280',
                                                            marginBottom: '4px',
                                                            display: 'block',
                                                        }}>
                                                            {t('Weight')}
                                                        </label>
                                                        <select
                                                            value={scale.fontWeight}
                                                            onChange={(e) => handleCustomScaleChange(index, 'fontWeight', e.target.value)}
                                                            disabled={disabled}
                                                            style={{
                                                                width: '100%',
                                                                padding: '6px 10px',
                                                                border: '1px solid #E5E7EB',
                                                                borderRadius: '4px',
                                                                fontSize: '11px',
                                                            }}
                                                        >
                                                            {getFontWeightOptions().map((option) => (
                                                                <option key={option.value} value={option.value}>
                                                                    {option.label}
                                                                </option>
                                                            ))}
                                                        </select>
                                                    </div>
                                                    
                                                    {/* Line Height */}
                                                    <div>
                                                        <label style={{
                                                            fontSize: '10px',
                                                            fontWeight: 500,
                                                            color: '#6B7280',
                                                            marginBottom: '4px',
                                                            display: 'block',
                                                        }}>
                                                            {t('Line Height')}
                                                        </label>
                                                        <input
                                                            type="text"
                                                            value={scale.lineHeight}
                                                            onChange={(e) => handleCustomScaleChange(index, 'lineHeight', e.target.value)}
                                                            disabled={disabled}
                                                            style={{
                                                                width: '100%',
                                                                padding: '6px 10px',
                                                                border: '1px solid #E5E7EB',
                                                                borderRadius: '4px',
                                                                fontSize: '11px',
                                                            }}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
                
                {/* Chat Preview Column */}
                <div style={{ 
                    width: '280px',
                    flexShrink: 0,
                }}>
                    <div style={{
                        fontSize: '11px',
                        fontWeight: 600,
                        color: '#6B7280',
                        marginBottom: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                    }}>
                        <MessageCircle size={12} />
                        {t('Preview')}
                    </div>
                    
                    {/* Mini Chat Window */}
                    <div
                        style={{
                            background: globalValues.colors?.background ?? '#FFFFFF',
                            borderRadius: '12px',
                            boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
                            overflow: 'hidden',
                            fontFamily: typography.fontFamily,
                            direction: 'rtl',
                        }}
                    >
                        {/* Chat Header */}
                        <div
                            style={{
                                background: globalValues.colors?.primary ?? '#3BC2D0',
                                padding: '10px 12px',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px',
                            }}
                        >
                            <div style={{
                                width: '28px',
                                height: '28px',
                                borderRadius: '50%',
                                background: 'rgba(255,255,255,0.2)',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                            }}>
                                <Bot size={14} color="#FFFFFF" />
                            </div>
                            <span
                                style={{
                                    color: '#FFFFFF',
                                    fontSize: typography.heading.fontSize,
                                    fontWeight: typography.heading.fontWeight as any,
                                    lineHeight: typography.heading.lineHeight,
                                }}
                            >
                                {t('Our Chatbot')}
                            </span>
                        </div>
                        
                        {/* Chat Messages */}
                        <div style={{ padding: '12px', background: globalValues.colors?.background ?? '#FFFFFF' }}>
                            {/* Bot Message */}
                            <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
                                <div style={{
                                    width: '24px',
                                    height: '24px',
                                    borderRadius: '50%',
                                    background: globalValues.colors?.surface ?? '#F9FAFB',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    flexShrink: 0,
                                }}>
                                    <Bot size={12} color={globalValues.colors?.primary ?? '#3BC2D0'} />
                                </div>
                                <div>
                                    <div
                                        style={{
                                            background: globalValues.colors?.surface ?? '#F9FAFB',
                                            padding: '8px 12px',
                                            borderRadius: '12px 12px 12px 4px',
                                            fontSize: typography.body.fontSize,
                                            fontWeight: typography.body.fontWeight as any,
                                            lineHeight: typography.body.lineHeight,
                                            color: globalValues.colors?.text ?? '#1F2937',
                                        }}
                                    >
                                        {t('Hello! How can I help you today?')}
                                    </div>
                                    <div
                                        style={{
                                            fontSize: typography.small.fontSize,
                                            fontWeight: typography.small.fontWeight as any,
                                            lineHeight: typography.small.lineHeight,
                                            color: globalValues.colors?.textMuted ?? '#6B7280',
                                            marginTop: '4px',
                                            marginRight: '4px',
                                        }}
                                    >
                                        {t('2 minutes ago')}
                                    </div>
                                </div>
                            </div>
                            
                            {/* User Message */}
                            <div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: '12px' }}>
                                <div>
                                    <div
                                        style={{
                                            background: globalValues.colors?.primary ?? '#3BC2D0',
                                            padding: '8px 12px',
                                            borderRadius: '12px 12px 4px 12px',
                                            fontSize: typography.body.fontSize,
                                            fontWeight: typography.body.fontWeight as any,
                                            lineHeight: typography.body.lineHeight,
                                            color: '#FFFFFF',
                                        }}
                                    >
                                        {t('I want to know about your products')}
                                    </div>
                                    <div
                                        style={{
                                            fontSize: typography.small.fontSize,
                                            fontWeight: typography.small.fontWeight as any,
                                            lineHeight: typography.small.lineHeight,
                                            color: globalValues.colors?.textMuted ?? '#6B7280',
                                            marginTop: '4px',
                                            marginRight: '4px',
                                            textAlign: 'left',
                                        }}
                                    >
                                        {t('Now')}
                                    </div>
                                </div>
                            </div>
                            
                            {/* Quick Buttons */}
                            <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '12px' }}>
                                {[t('Products'), t('Prices'), t('Contact Us')].map((btn) => (
                                    <button
                                        key={btn}
                                        style={{
                                            padding: '6px 12px',
                                            background: globalValues.colors?.surface ?? '#F9FAFB',
                                            border: `1px solid ${globalValues.colors?.border ?? '#E5E7EB'}`,
                                            borderRadius: '20px',
                                            fontSize: typography.button.fontSize,
                                            fontWeight: typography.button.fontWeight as any,
                                            lineHeight: typography.button.lineHeight,
                                            color: globalValues.colors?.text ?? '#1F2937',
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {btn}
                                    </button>
                                ))}
                            </div>
                        </div>
                        
                        {/* Input Area */}
                        <div
                            style={{
                                padding: '8px 12px',
                                borderTop: `1px solid ${globalValues.colors?.border ?? '#E5E7EB'}`,
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px',
                            }}
                        >
                            <input
                                type="text"
                                placeholder={t('Type a message...')}
                                style={{
                                    flex: 1,
                                    padding: '8px 12px',
                                    border: `1px solid ${globalValues.colors?.border ?? '#E5E7EB'}`,
                                    borderRadius: '12px',
                                    fontSize: typography.body.fontSize,
                                    fontFamily: typography.fontFamily,
                                    outline: 'none',
                                }}
                            />
                            <button
                                style={{
                                    width: '32px',
                                    height: '32px',
                                    borderRadius: '50%',
                                    background: globalValues.colors?.primary ?? '#3BC2D0',
                                    border: 'none',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    cursor: 'pointer',
                                }}
                            >
                                <Send size={14} color="#FFFFFF" style={{ transform: 'rotate(180deg)' }} />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default TypographySection;
