/**
 * Typography Control Component
 * 
 * Elementor-style typography control with:
 * - Font family dropdown
 * - Font size SLIDER with limits (8-72px)
 * - Font weight dropdown
 * - Text transform toggle buttons
 * - Font style toggle buttons
 * - Text decoration toggle buttons
 * - Line height SLIDER (0.8-3)
 * - Letter spacing SLIDER (-5 to 10px)
 * - Text shadow with PENCIL POPOVER
 * 
 * @since 1.5.0
 */

import React, { useState } from 'react';
import { t } from '@/lib/i18n';
import { ChevronDown, ChevronUp, Type, Save, X, AlignLeft, AlignCenter, AlignRight, AlignJustify } from 'lucide-react';
import { PresetGlobalValues, FieldValue, createCustomValue, createGlobalRef, isGlobalRef, resolveFieldValue } from '../../../types/appearance';
import { TextShadowControl } from '../controls/TextShadowControl';

export interface TypographySettings {
    fontFamily?: FieldValue;
    fontSize?: FieldValue;
    fontWeight?: FieldValue;
    textTransform?: FieldValue;
    textAlign?: FieldValue;
    fontStyle?: FieldValue;
    textDecoration?: FieldValue;
    lineHeight?: FieldValue;
    letterSpacing?: FieldValue;
    textShadow?: FieldValue;
}

interface TypographyControlProps {
    label: string;
    value: TypographySettings;
    globalValues: PresetGlobalValues;
    onChange: (value: TypographySettings) => void;
    /** Callback to save current typography as a new global custom scale */
    onSaveAsGlobalScale?: (scale: { id: string; name: string; fontSize: string; fontWeight: string; lineHeight: string; textTransform: string; textAlign: string; fontStyle: string; textDecoration: string; letterSpacing: string; textShadow: string }) => void;
    disabled?: boolean;
    /** Context for font size limits - header has lower max than body */
    context?: 'header' | 'body' | 'small' | 'button';
    /** When true, hide the text-align segmented control (use a separate controller instead). */
    hideTextAlign?: boolean;
}

// Font size limits by context - increased max to 36px for more flexibility
const FONT_SIZE_LIMITS = {
    header: { min: 8, max: 36, default: 16 },
    body: { min: 8, max: 36, default: 14 },
    small: { min: 8, max: 36, default: 12 },
    button: { min: 8, max: 36, default: 14 },
};

function getBaseTypographyPresets() {
    return [
        { value: '', label: t('Custom'), category: 'custom' },
        { value: 'headings-divider', label: `── ${t('Headings')} ──`, category: 'divider' },
        { value: 'headingLarge', label: t('Large Heading (22px, 600)'), category: 'headings' },
        { value: 'headingMedium', label: t('Medium Heading (18px, 600)'), category: 'headings' },
        { value: 'headingSmall', label: t('Small Heading (16px, 600)'), category: 'headings' },
        { value: 'productPrice', label: t('Product Price (24px, 600)'), category: 'headings' },
        { value: 'body-divider', label: `── ${t('Body Text')} ──`, category: 'divider' },
        { value: 'bodyLarge', label: t('Large Text (16px, 400)'), category: 'body' },
        { value: 'body', label: t('Regular Text (14px, 400)'), category: 'body' },
        { value: 'bodySmall', label: t('Small Text (12px, 400)'), category: 'body' },
        { value: 'buttons-divider', label: `── ${t('Buttons')} ──`, category: 'divider' },
        { value: 'buttonLarge', label: t('Large Button (16px, 600)'), category: 'buttons' },
        { value: 'button', label: t('Regular Button (14px, 600)'), category: 'buttons' },
        { value: 'buttonSmall', label: t('Small Button (12px, 600)'), category: 'buttons' },
        { value: 'labels-divider', label: `── ${t('Labels')} ──`, category: 'divider' },
        { value: 'labelLarge', label: t('Large Label (14px, 500)'), category: 'labels' },
        { value: 'label', label: t('Regular Label (12px, 500)'), category: 'labels' },
        { value: 'labelSmall', label: t('Small Label (10px, 500)'), category: 'labels' },
        { value: 'confirmationText', label: t('Confirmation Text (11px, 600)'), category: 'labels' },
        { value: 'micro', label: t('Micro (9px, 600)'), category: 'labels' },
        { value: 'inputs-divider', label: `── ${t('Input Fields')} ──`, category: 'divider' },
        { value: 'inputLarge', label: t('Large Input (16px, 400)'), category: 'inputs' },
        { value: 'input', label: t('Regular Input (14px, 400)'), category: 'inputs' },
        { value: 'inputSmall', label: t('Small Input (12px, 400)'), category: 'inputs' },
        { value: 'legacy-divider', label: `── ${t('Legacy')} ──`, category: 'divider' },
        { value: 'heading', label: t('Heading Scale (Legacy)'), category: 'legacy' },
        { value: 'small', label: t('Small Scale (Legacy)'), category: 'legacy' },
    ];
}

function getBaseFontFamilies() {
    return [
        { value: 'inherit', label: t('Inherit (from site)') },
        { value: 'global', label: `🔗 ${t('From Global Settings')}` },
        { value: 'system-ui', label: 'System UI' },
        { value: "'Heebo', sans-serif", label: 'Heebo' },
        { value: "'Assistant', sans-serif", label: 'Assistant' },
        { value: "'Rubik', sans-serif", label: 'Rubik' },
        { value: "'Open Sans', sans-serif", label: 'Open Sans' },
        { value: "'Inter', sans-serif", label: 'Inter' },
        { value: "'Roboto', sans-serif", label: 'Roboto' },
    ];
}

function getFontWeights() {
    return [
        { value: '300', label: `300 ${t('Light')}` },
        { value: '400', label: `400 ${t('Regular')}` },
        { value: '500', label: `500 ${t('Medium')}` },
        { value: '600', label: `600 ${t('Semi Bold')}` },
        { value: '700', label: `700 ${t('Bold')}` },
        { value: '800', label: `800 ${t('Extra Bold')}` },
    ];
}

function getTextTransforms() {
    return [
        { value: 'none', label: 'Aa', title: t('None') },
        { value: 'uppercase', label: 'AA', title: t('Uppercase') },
        { value: 'lowercase', label: 'aa', title: t('Lowercase') },
        { value: 'capitalize', label: 'Aa', title: t('Capitalize') },
    ];
}

function getFontStyles() {
    return [
        { value: 'normal', label: 'R', title: t('Normal') },
        { value: 'italic', label: 'I', title: t('Italic'), italic: true },
    ];
}

function getTextDecorations() {
    return [
        { value: 'none', label: 'T', title: t('None') },
        { value: 'underline', label: 'T̲', title: t('Underline'), style: 'underline' },
        { value: 'line-through', label: 'T̶', title: t('Strikethrough'), style: 'line-through' },
        { value: 'overline', label: 'T̅', title: t('Overline'), style: 'overline' },
    ];
}

function getTextAligns() {
    return [
        { value: 'start', title: t('Align Start (RTL/LTR safe)') },
        { value: 'center', title: t('Center') },
        { value: 'end', title: t('Align End (RTL/LTR safe)') },
        { value: 'justify', title: t('Justify') },
    ];
}

function getDocumentDirection(): 'rtl' | 'ltr' {
    if (typeof document !== 'undefined') {
        const dir = document.documentElement?.dir;
        if (dir === 'rtl' || dir === 'ltr') return dir;
    }
    return 'ltr';
}

// Parse value like "16px" to number
function parseSize(value: string | undefined, defaultValue: number): number {
    if (!value) return defaultValue;
    const num = parseFloat(value);
    return isNaN(num) ? defaultValue : num;
}

export const TypographyControl: React.FC<TypographyControlProps> = ({
    label,
    value,
    globalValues,
    onChange,
    onSaveAsGlobalScale,
    disabled = false,
    context = 'body',
    hideTextAlign = false,
}) => {
    const [isExpanded, setIsExpanded] = useState(false);
    const [selectedPreset, setSelectedPreset] = useState<string>('');
    const [showSaveDialog, setShowSaveDialog] = useState(false);
    const [newScaleName, setNewScaleName] = useState('');
    
    const fontSizeLimits = FONT_SIZE_LIMITS[context];
    
    // Build font families list including global custom font
    const FONT_FAMILIES = React.useMemo(() => {
        const families = [...getBaseFontFamilies()];
        
        // Add global font if it's a custom font not in the list
        const globalFont = globalValues.typography?.fontFamily;
        if (globalFont && globalFont !== 'inherit') {
            const isInList = families.some(f => f.value === globalFont);
            if (!isInList) {
                const displayName = globalFont.replace(/['"]/g, '').split(',')[0].trim();
                // Insert after "global" option
                families.splice(2, 0, { value: globalFont, label: `${displayName} ★` });
            }
        }
        
        return families;
    }, [globalValues.typography?.fontFamily]);
    
    // Build presets list including custom scales
    const typographyPresets = React.useMemo(() => {
        const presets = [...getBaseTypographyPresets()];
        
        // Add custom scales from globalValues - filter out invalid entries (empty strings, nulls, etc.)
        const customScales = (globalValues.typography?.custom || [])
            .filter((scale: unknown): scale is { id: string; name: string } => 
                typeof scale === 'object' && 
                scale !== null && 
                'id' in scale && 
                'name' in scale &&
                typeof (scale as { id: string }).id === 'string' &&
                typeof (scale as { name: string }).name === 'string' &&
                (scale as { name: string }).name.trim() !== ''
            );
        
        if (customScales.length > 0) {
            presets.push({ value: 'custom-divider', label: `── ${t('Custom Scales')} ──`, category: 'divider' });
            customScales.forEach((scale) => {
                presets.push({
                    value: `custom.${scale.id}`,
                    label: `✨ ${scale.name}`,
                    category: 'custom',
                });
            });
        }
        
        return presets;
    }, [globalValues.typography?.custom]);

    // Infer the currently selected global typography preset from stored FieldValue refs.
    // This ensures presets like "headingMedium" display as linked in the UI when the preset
    // is stored as global refs (instead of always showing "custom" on load).
    // We check the core scale fields: fontSize, fontWeight, lineHeight (these are ALWAYS linked to scale).
    // Note: textAlign and textShadow use custom defaults, so we don't check them.
    React.useEffect(() => {
        const getRef = (fv: FieldValue | undefined): string | null => {
            if (!fv || !isGlobalRef(fv)) return null;
            return (fv as unknown as { ref?: string }).ref || null;
        };

        const fontSizeRef = getRef(value.fontSize);
        const fontWeightRef = getRef(value.fontWeight);
        const lineHeightRef = getRef(value.lineHeight);

        // We consider a preset "selected" only when these core fields are all global and share a prefix.
        const refs = [fontSizeRef, fontWeightRef, lineHeightRef];
        if (refs.some(r => !r)) {
            setSelectedPreset('');
            return;
        }

        const parsePrefix = (ref: string): string | null => {
            // Expected shapes:
            // - typography.headingMedium.fontSize
            // - typography.custom.31.fontSize
            const parts = ref.split('.').filter(Boolean);
            if (parts[0] !== 'typography') return null;
            if (parts[1] === 'custom') {
                const idx = parts[2];
                if (!idx) return null;
                return `custom.${idx}`;
            }
            const presetName = parts[1];
            return presetName ? presetName : null;
        };

        const prefixes = refs.map(r => parsePrefix(r as string));
        if (prefixes.some(p => !p)) {
            setSelectedPreset('');
            return;
        }

        const first = prefixes[0] as string;
        if (!prefixes.every(p => p === first)) {
            setSelectedPreset('');
            return;
        }

        // Map custom.<index> back to custom.<id> (UI uses ids)
        if (first.startsWith('custom.')) {
            const idxRaw = first.replace('custom.', '');
            const idx = Number.parseInt(idxRaw, 10);
            const scale = Array.isArray(globalValues.typography?.custom) ? globalValues.typography?.custom[idx] : undefined;
            const scaleId = (scale && typeof scale === 'object' && scale !== null && 'id' in scale) ? (scale as { id: string }).id : null;
            setSelectedPreset(scaleId ? `custom.${scaleId}` : '');
            return;
        }

        setSelectedPreset(first);
    }, [
        value.fontSize,
        value.fontWeight,
        value.lineHeight,
        globalValues.typography?.custom,
    ]);
    
    // Helper to update a single field
    const updateField = (field: keyof TypographySettings, newValue: string) => {
        onChange({
            ...value,
            [field]: createCustomValue(newValue),
        });
    };

    /**
     * Build a fully-linked TypographySettings object for a given scale prefix.
     * Links ALL TypographySettings fields to global refs.
     * For fields not in the scale (textAlign, textShadow), uses sensible custom defaults.
     */
    const buildFullyLinkedTypography = (scalePrefix: string): TypographySettings => ({
        fontFamily: createGlobalRef('typography', 'fontFamily'),
        fontSize: createGlobalRef('typography', `${scalePrefix}.fontSize`),
        fontWeight: createGlobalRef('typography', `${scalePrefix}.fontWeight`),
        lineHeight: createGlobalRef('typography', `${scalePrefix}.lineHeight`),
        textTransform: createGlobalRef('typography', `${scalePrefix}.textTransform`),
        fontStyle: createGlobalRef('typography', `${scalePrefix}.fontStyle`),
        textDecoration: createGlobalRef('typography', `${scalePrefix}.textDecoration`),
        letterSpacing: createGlobalRef('typography', `${scalePrefix}.letterSpacing`),
        // textAlign is not part of standard typography scales - use custom default
        textAlign: createCustomValue('start'),
        // textShadow is not part of standard typography scales - use custom default
        textShadow: createCustomValue('none'),
    });

    // Apply a global typography preset
    const applyPreset = (presetName: string) => {
        // Ignore dividers
        if (presetName === 'divider' || presetName.endsWith('-divider')) return;
        
        setSelectedPreset(presetName);
        
        // If "Custom" (empty preset) is selected, convert global refs to custom values
        if (!presetName) {
            // Get current resolved values and convert them ALL to custom values
            const resolvedFontFamily = getResolvedValue(value.fontFamily, 'inherit');
            const resolvedFontSize = getResolvedValue(value.fontSize, `${fontSizeLimits.default}px`);
            const resolvedFontWeight = getResolvedValue(value.fontWeight, '400');
            const resolvedLineHeight = getResolvedValue(value.lineHeight, '1.5');
            const resolvedTextTransform = getResolvedValue(value.textTransform, 'none');
            const resolvedFontStyle = getResolvedValue(value.fontStyle, 'normal');
            const resolvedTextDecoration = getResolvedValue(value.textDecoration, 'none');
            const resolvedLetterSpacing = getResolvedValue(value.letterSpacing, '0px');
            const resolvedTextAlign = getResolvedValue(value.textAlign, 'start');
            const resolvedTextShadow = getResolvedValue(value.textShadow, 'none');
            
            onChange({
                fontFamily: createCustomValue(resolvedFontFamily),
                fontSize: createCustomValue(resolvedFontSize),
                fontWeight: createCustomValue(resolvedFontWeight),
                lineHeight: createCustomValue(resolvedLineHeight),
                textTransform: createCustomValue(resolvedTextTransform),
                fontStyle: createCustomValue(resolvedFontStyle),
                textDecoration: createCustomValue(resolvedTextDecoration),
                letterSpacing: createCustomValue(resolvedLetterSpacing),
                textAlign: createCustomValue(resolvedTextAlign),
                textShadow: createCustomValue(resolvedTextShadow),
            });
            return;
        }
        
        if (presetName.startsWith('custom.')) {
            const scaleId = presetName.replace('custom.', '');
            const customScales = globalValues.typography?.custom || [];
            const scaleIndex = customScales.findIndex((s: { id: string }) => s.id === scaleId);
            
            if (scaleIndex !== -1) {
                // Custom scales: link all available fields
                onChange({
                    fontFamily: createGlobalRef('typography', 'fontFamily'),
                    fontSize: createGlobalRef('typography', `custom.${scaleIndex}.fontSize`),
                    fontWeight: createGlobalRef('typography', `custom.${scaleIndex}.fontWeight`),
                    lineHeight: createGlobalRef('typography', `custom.${scaleIndex}.lineHeight`),
                    textTransform: createGlobalRef('typography', `custom.${scaleIndex}.textTransform`),
                    fontStyle: createGlobalRef('typography', `custom.${scaleIndex}.fontStyle`),
                    textDecoration: createGlobalRef('typography', `custom.${scaleIndex}.textDecoration`),
                    letterSpacing: createGlobalRef('typography', `custom.${scaleIndex}.letterSpacing`),
                    textAlign: createGlobalRef('typography', `custom.${scaleIndex}.textAlign`),
                    textShadow: createGlobalRef('typography', `custom.${scaleIndex}.textShadow`),
                });
            }
        } else {
            // Built-in scales: use the helper function
            onChange(buildFullyLinkedTypography(presetName));
        }
    };

    // Get resolved value for display
    const getResolvedValue = (fieldValue: FieldValue | undefined, defaultValue: string): string => {
        if (!fieldValue) return defaultValue;
        return resolveFieldValue(fieldValue, globalValues) || defaultValue;
    };

    // Handle font family change
    const handleFontFamilyChange = (fontValue: string) => {
        if (fontValue === 'global') {
            onChange({
                ...value,
                fontFamily: createGlobalRef('typography', 'fontFamily'),
            });
        } else {
            updateField('fontFamily', fontValue);
        }
    };

    // Check if using global reference
    const isUsingGlobal = (fieldValue: FieldValue | undefined): boolean => {
        return fieldValue ? isGlobalRef(fieldValue) : false;
    };
    
    // Check if font family is using global (undefined = using global as default)
    const isFontFamilyGlobal = (): boolean => {
        return !value.fontFamily || isGlobalRef(value.fontFamily);
    };

    // Save current typography settings as a new global custom scale
    const handleSaveAsGlobalScale = () => {
        if (!newScaleName.trim() || !onSaveAsGlobalScale) return;
        
        const scaleId = `custom_${Date.now()}`;
        const newScale = {
            id: scaleId,
            name: newScaleName.trim(),
            fontSize: getResolvedValue(value.fontSize, `${fontSizeLimits.default}px`),
            fontWeight: getResolvedValue(value.fontWeight, '400'),
            lineHeight: getResolvedValue(value.lineHeight, '1.5'),
            textTransform: getResolvedValue(value.textTransform, 'none'),
            textAlign: getResolvedValue(value.textAlign, 'start'),
            fontStyle: getResolvedValue(value.fontStyle, 'normal'),
            textDecoration: getResolvedValue(value.textDecoration, 'none'),
            letterSpacing: getResolvedValue(value.letterSpacing, '0px'),
            textShadow: getResolvedValue(value.textShadow, 'none'),
        };
        
        onSaveAsGlobalScale(newScale);
        setShowSaveDialog(false);
        setNewScaleName('');
        
        // Auto-select the new scale
        setSelectedPreset(`custom.${scaleId}`);
    };

    // Check if currently using custom values (not linked to global)
    const isUsingCustomValues = (): boolean => {
        return selectedPreset === '' || !selectedPreset;
    };

    // Get summary of current settings
    const getSummary = (): string => {
        const fontSize = getResolvedValue(value.fontSize, `${fontSizeLimits.default}px`);
        const fontWeight = getResolvedValue(value.fontWeight, '400');
        
        const weightLabel = getFontWeights().find(w => w.value === fontWeight);
        return `${fontSize} / ${weightLabel?.label || fontWeight}`;
    };

    // Handle font size slider
    const handleFontSizeChange = (sizeNum: number) => {
        updateField('fontSize', `${sizeNum}px`);
    };

    // Handle line height slider
    const handleLineHeightChange = (lineHeight: number) => {
        updateField('lineHeight', lineHeight.toFixed(2));
    };

    // Handle letter spacing slider
    const handleLetterSpacingChange = (spacing: number) => {
        updateField('letterSpacing', `${spacing}px`);
    };

    // Current values for sliders
    const currentFontSize = parseSize(getResolvedValue(value.fontSize, `${fontSizeLimits.default}px`), fontSizeLimits.default);
    const currentLineHeight = parseFloat(getResolvedValue(value.lineHeight, '1.5')) || 1.5;
    const currentLetterSpacing = parseSize(getResolvedValue(value.letterSpacing, '0px'), 0);

    return (
        <div className="border border-gray-200 rounded-lg overflow-hidden">
            {/* Header - Always visible */}
            <button
                type="button"
                onClick={() => setIsExpanded(!isExpanded)}
                disabled={disabled}
                className="w-full flex items-center justify-between px-3 py-2.5 bg-gray-50 hover:bg-gray-100 transition-colors disabled:opacity-50"
            >
                <div className="flex items-center gap-2">
                    <Type size={14} className="text-gray-500" />
                    <span className="text-sm font-medium text-gray-700">{label}</span>
                </div>
                <div className="flex items-center gap-2">
                    <span className="text-xs text-gray-500">{getSummary()}</span>
                    {isExpanded ? (
                        <ChevronUp size={14} className="text-gray-400" />
                    ) : (
                        <ChevronDown size={14} className="text-gray-400" />
                    )}
                </div>
            </button>

            {/* Expanded Content */}
            {isExpanded && (
                <div className="p-3 space-y-4 bg-white">
                    {/* Global Preset Selector */}
                    <div className="pb-3 border-b border-gray-200">
                        <label className="text-xs text-gray-500 mb-1 block">{t('Use Global Scale')}</label>
                        <select
                            value={selectedPreset}
                            onChange={(e) => applyPreset(e.target.value)}
                            disabled={disabled}
                            className="w-full px-2 py-1.5 text-sm border border-primary-300 bg-primary-50 rounded focus:outline-none focus:ring-1 focus:ring-primary-500 disabled:bg-gray-100"
                        >
                            {typographyPresets.map(preset => {
                                const isDivider = preset.value.endsWith('-divider') || preset.category === 'divider';
                                return (
                                    <option 
                                        key={preset.value} 
                                        value={preset.value}
                                        disabled={isDivider}
                                        style={isDivider ? { fontWeight: 600, color: '#9CA3AF', backgroundColor: '#F3F4F6' } : {}}
                                    >
                                        {preset.label}
                                    </option>
                                );
                            })}
                        </select>
                        
                        {/* Save as Global Scale Button - only show when using custom values */}
                        {isUsingCustomValues() && onSaveAsGlobalScale && (
                            <div className="mt-2">
                                {!showSaveDialog ? (
                                    <button
                                        type="button"
                                        onClick={() => setShowSaveDialog(true)}
                                        className="flex items-center gap-1.5 text-xs text-primary-600 hover:text-primary-700 transition-colors"
                                    >
                                        <Save size={12} />
                                        {t('Save as New Global Scale')}
                                    </button>
                                ) : (
                                    <div className="p-2 bg-primary-50 border border-primary-200 rounded-md space-y-2">
                                        <div className="flex items-center gap-2">
                                            <input
                                                type="text"
                                                value={newScaleName}
                                                onChange={(e) => setNewScaleName(e.target.value)}
                                                placeholder={t('New scale name')}
                                                className="flex-1 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-primary-500"
                                                autoFocus
                                            />
                                            <button
                                                type="button"
                                                onClick={handleSaveAsGlobalScale}
                                                disabled={!newScaleName.trim()}
                                                className="p-1 text-white bg-primary-500 hover:bg-primary-600 disabled:bg-gray-300 rounded transition-colors"
                                                title={t('Save')}
                                            >
                                                <Save size={14} />
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => { setShowSaveDialog(false); setNewScaleName(''); }}
                                                className="p-1 text-gray-500 hover:text-gray-700 bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                                                title={t('Cancel')}
                                            >
                                                <X size={14} />
                                            </button>
                                        </div>
                                        <p className="text-xs text-gray-500">
                                            {t('Current settings will be saved as a new global scale')}
                                        </p>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Font Family */}
                    <div>
                        <label className="text-xs text-gray-500 mb-1 block">{t('Font Family')}</label>
                        <select
                            value={isFontFamilyGlobal() ? 'global' : getResolvedValue(value.fontFamily, 'global')}
                            onChange={(e) => handleFontFamilyChange(e.target.value)}
                            disabled={disabled}
                            className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-primary-500 disabled:bg-gray-100"
                        >
                            {FONT_FAMILIES.map(font => (
                                <option key={font.value} value={font.value}>{font.label}</option>
                            ))}
                        </select>
                        {isFontFamilyGlobal() && (
                            <p className="text-xs text-primary-600 mt-1">
                                🔗 {t('Linked')}: {globalValues.typography?.fontFamily || 'inherit'}
                            </p>
                        )}
                    </div>

                    {/* Font Size - SLIDER */}
                    <div>
                        <div className="flex items-center justify-between mb-1.5">
                            <label className="text-xs text-gray-500">{t('Font Size')}</label>
                            <span className="text-xs text-gray-400">{fontSizeLimits.min}-{fontSizeLimits.max}px</span>
                        </div>
                        <div className="flex items-center gap-3">
                            <input
                                type="range"
                                min={fontSizeLimits.min}
                                max={fontSizeLimits.max}
                                step={1}
                                value={Math.min(Math.max(currentFontSize, fontSizeLimits.min), fontSizeLimits.max)}
                                onChange={(e) => handleFontSizeChange(parseInt(e.target.value))}
                                disabled={disabled || isUsingGlobal(value.fontSize)}
                                className="flex-1 h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer accent-primary-500"
                            />
                            <div className="flex items-center bg-gray-50 border border-gray-200 rounded-md overflow-hidden">
                                <input
                                    type="number"
                                    value={Math.round(currentFontSize)}
                                    onChange={(e) => handleFontSizeChange(parseInt(e.target.value) || fontSizeLimits.default)}
                                    onFocus={(e) => e.currentTarget.select()}
                                    disabled={disabled || isUsingGlobal(value.fontSize)}
                                    className="w-14 px-2 py-1 text-sm text-center bg-transparent border-none focus:outline-none"
                                />
                                <span className="px-2 py-1 text-xs text-gray-500 bg-gray-100 border-r border-gray-200">px</span>
                            </div>
                        </div>
                        {isUsingGlobal(value.fontSize) && (
                            <p className="text-xs text-primary-600 mt-1">🔗 {t('Linked to global scale')}</p>
                        )}
                    </div>

                    {/* Font Weight */}
                    <div>
                        <label className="text-xs text-gray-500 mb-1 block">{t('Font Weight')}</label>
                        <select
                            value={getResolvedValue(value.fontWeight, '400')}
                            onChange={(e) => updateField('fontWeight', e.target.value)}
                            disabled={disabled}
                            className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-primary-500 disabled:bg-gray-100"
                        >
                            {getFontWeights().map(weight => (
                                <option key={weight.value} value={weight.value}>{weight.label}</option>
                            ))}
                        </select>
                    </div>

                    {/* Text Transform, Style, Decoration - Toggle Buttons Row */}
                    <div className="grid grid-cols-3 gap-3">
                        {/* Text Transform */}
                        <div>
                            <label className="text-xs text-gray-500 mb-1.5 block">{t('Transform')}</label>
                            <div className="flex border border-gray-200 rounded-md overflow-hidden">
                                {getTextTransforms().map(t => (
                                    <button
                                        key={t.value}
                                        type="button"
                                        onClick={() => updateField('textTransform', t.value)}
                                        disabled={disabled}
                                        title={t.title}
                                        className={`flex-1 py-1.5 text-xs font-medium transition-colors ${
                                            getResolvedValue(value.textTransform, 'none') === t.value
                                                ? 'bg-primary-500 text-white'
                                                : 'bg-white text-gray-600 hover:bg-gray-50'
                                        }`}
                                    >
                                        {t.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Font Style */}
                        <div>
                            <label className="text-xs text-gray-500 mb-1.5 block">{t('Style')}</label>
                            <div className="flex border border-gray-200 rounded-md overflow-hidden">
                                {getFontStyles().map(s => (
                                    <button
                                        key={s.value}
                                        type="button"
                                        onClick={() => updateField('fontStyle', s.value)}
                                        disabled={disabled}
                                        title={s.title}
                                        className={`flex-1 py-1.5 text-xs font-medium transition-colors ${
                                            getResolvedValue(value.fontStyle, 'normal') === s.value
                                                ? 'bg-primary-500 text-white'
                                                : 'bg-white text-gray-600 hover:bg-gray-50'
                                        } ${s.italic ? 'italic' : ''}`}
                                    >
                                        {s.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Text Decoration */}
                        <div>
                            <label className="text-xs text-gray-500 mb-1.5 block">{t('Text Decoration')}</label>
                            <div className="flex border border-gray-200 rounded-md overflow-hidden">
                                {getTextDecorations().map(d => (
                                    <button
                                        key={d.value}
                                        type="button"
                                        onClick={() => updateField('textDecoration', d.value)}
                                        disabled={disabled}
                                        title={d.title}
                                        className={`flex-1 py-1.5 text-xs font-medium transition-colors ${
                                            getResolvedValue(value.textDecoration, 'none') === d.value
                                                ? 'bg-primary-500 text-white'
                                                : 'bg-white text-gray-600 hover:bg-gray-50'
                                        }`}
                                        style={{ textDecoration: d.style }}
                                    >
                                        {d.label}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Text Align (icon segmented control, RTL-aware) */}
                    {!hideTextAlign && (
                        <div>
                            <label className="text-xs text-gray-500 mb-1.5 block">{t('Text Align')}</label>
                            <div className="flex border border-gray-200 rounded-md overflow-hidden bg-white">
                                {(() => {
                                    const dir = getDocumentDirection();
                                    const current = getResolvedValue(value.textAlign, 'start');
                                    const StartIcon = dir === 'rtl' ? AlignRight : AlignLeft;
                                    const EndIcon = dir === 'rtl' ? AlignLeft : AlignRight;
                                    const iconFor = (v: string) => {
                                        if (v === 'start') return <StartIcon className="w-4 h-4" />;
                                        if (v === 'center') return <AlignCenter className="w-4 h-4" />;
                                        if (v === 'end') return <EndIcon className="w-4 h-4" />;
                                        return <AlignJustify className="w-4 h-4" />;
                                    };

                                    return getTextAligns().map(a => (
                                        <button
                                            key={a.value}
                                            type="button"
                                            onClick={() => updateField('textAlign', a.value)}
                                            disabled={disabled}
                                            title={a.title}
                                            className={`flex-1 py-1.5 flex items-center justify-center text-xs font-medium transition-colors ${
                                                current === a.value
                                                    ? 'bg-primary-500 text-white'
                                                    : 'text-gray-600 hover:bg-gray-50'
                                            }`}
                                        >
                                            {iconFor(a.value)}
                                        </button>
                                    ));
                                })()}
                            </div>
                            <p className="text-[11px] text-gray-400 mt-1">
                                {t('Recommended default:')} <span className="font-medium">start/end</span> {t('(RTL/LTR compatible). left/right not recommended.')}
                            </p>
                        </div>
                    )}

                    {/* Line Height - SLIDER */}
                    <div>
                        <div className="flex items-center justify-between mb-1.5">
                            <label className="text-xs text-gray-500">{t('Line Height')}</label>
                            <span className="text-xs text-gray-400">0.8-3</span>
                        </div>
                        <div className="flex items-center gap-3">
                            <input
                                type="range"
                                min={0.8}
                                max={3}
                                step={0.1}
                                value={currentLineHeight}
                                onChange={(e) => handleLineHeightChange(parseFloat(e.target.value))}
                                disabled={disabled}
                                className="flex-1 h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer accent-primary-500"
                            />
                            <div className="flex items-center bg-gray-50 border border-gray-200 rounded-md overflow-hidden">
                                <input
                                    type="number"
                                    min={0.8}
                                    max={3}
                                    step={0.1}
                                    value={currentLineHeight.toFixed(1)}
                                    onChange={(e) => handleLineHeightChange(parseFloat(e.target.value) || 1.5)}
                                    disabled={disabled}
                                    className="w-14 px-2 py-1 text-sm text-center bg-transparent border-none focus:outline-none"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Letter Spacing - SLIDER */}
                    <div>
                        <div className="flex items-center justify-between mb-1.5">
                            <label className="text-xs text-gray-500">{t('Letter Spacing')}</label>
                            <span className="text-xs text-gray-400">{t('-5 to 10px')}</span>
                        </div>
                        <div className="flex items-center gap-3">
                            <input
                                type="range"
                                min={-5}
                                max={10}
                                step={0.5}
                                value={currentLetterSpacing}
                                onChange={(e) => handleLetterSpacingChange(parseFloat(e.target.value))}
                                disabled={disabled}
                                className="flex-1 h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer accent-primary-500"
                            />
                            <div className="flex items-center bg-gray-50 border border-gray-200 rounded-md overflow-hidden">
                                <input
                                    type="number"
                                    min={-5}
                                    max={10}
                                    step={0.5}
                                    value={currentLetterSpacing}
                                    onChange={(e) => handleLetterSpacingChange(parseFloat(e.target.value) || 0)}
                                    disabled={disabled}
                                    className="w-14 px-2 py-1 text-sm text-center bg-transparent border-none focus:outline-none"
                                />
                                <span className="px-2 py-1 text-xs text-gray-500 bg-gray-100 border-r border-gray-200">px</span>
                            </div>
                        </div>
                    </div>

                    {/* Text Shadow - PENCIL POPOVER */}
                    <TextShadowControl
                        label={t('Text Shadow')}
                        value={getResolvedValue(value.textShadow, 'none')}
                        onChange={(shadowValue) => updateField('textShadow', shadowValue)}
                        disabled={disabled}
                    />
                </div>
            )}
        </div>
    );
};

export default TypographyControl;
