/**
 * Colors Section Component
 * Week 21 V2 - Visual Element Editor
 * 
 * Manages global color palette including built-in and custom colors.
 */

import React, { useState } from 'react';
import { BuiltInColors, ColorEntry, generateColorId } from '../../../types/appearance';
import { ColorPicker } from '../../common/ColorPicker';
import { Download, Loader2 } from 'lucide-react';
import { apiClient } from '../../../api/client';
import { t, sprintf } from '@/lib/i18n';

interface ColorsSectionProps {
    colors: BuiltInColors & { custom: ColorEntry[] };
    onChange: (colors: BuiltInColors & { custom: ColorEntry[] }) => void;
    disabled?: boolean;
    claudeApiKey?: string;
}

interface BuiltInColorConfig {
    key: keyof BuiltInColors;
    label: string;
    description: string;
}

function getBuiltInColorConfigs(): BuiltInColorConfig[] {
    return [
        { key: 'primary', label: t('Primary Color'), description: t('Main brand color') },
        { key: 'secondary', label: t('Secondary Color'), description: t('Complementary design color') },
        { key: 'accent', label: t('Accent Color'), description: t('Color for prominent elements') },
        { key: 'text', label: t('Text Color'), description: t('Main text color') },
        { key: 'textLight', label: t('Light Text'), description: t('Text color on dark backgrounds') },
        { key: 'textMuted', label: t('Muted Text'), description: t('Dimmed text color') },
        { key: 'background', label: t('Background'), description: t('Main background color') },
        { key: 'backgroundDark', label: t('Dark Background'), description: t('Dark background color') },
        { key: 'surface', label: t('Surface'), description: t('Surface/card color') },
        { key: 'border', label: t('Borders'), description: t('Border line color') },
        { key: 'success', label: t('Success'), description: t('Success message color') },
        { key: 'warning', label: t('Warning'), description: t('Warning message color') },
        { key: 'error', label: t('Error'), description: t('Error message color') },
    ];
}

// Helper function to calculate color luminance (for smart matching)
function getLuminance(hex: string): number {
    const rgb = hexToRgb(hex);
    if (!rgb) return 0;
    const [r, g, b] = [rgb.r / 255, rgb.g / 255, rgb.b / 255].map(v =>
        v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)
    );
    return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

// Check if color is saturated (vibrant)
function getSaturation(hex: string): number {
    const rgb = hexToRgb(hex);
    if (!rgb) return 0;
    const max = Math.max(rgb.r, rgb.g, rgb.b);
    const min = Math.min(rgb.r, rgb.g, rgb.b);
    if (max === 0) return 0;
    return (max - min) / max;
}

// Get hue from hex color
function getHue(hex: string): number {
    const rgb = hexToRgb(hex);
    if (!rgb) return 0;
    const r = rgb.r / 255, g = rgb.g / 255, b = rgb.b / 255;
    const max = Math.max(r, g, b), min = Math.min(r, g, b);
    if (max === min) return 0;
    const d = max - min;
    let h = 0;
    if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
    else if (max === g) h = ((b - r) / d + 2) / 6;
    else h = ((r - g) / d + 4) / 6;
    return h * 360;
}

// Convert RGB to Hex
function rgbToHex(r: number, g: number, b: number): string {
    const toHex = (n: number) => {
        const hex = Math.round(Math.max(0, Math.min(255, n))).toString(16);
        return hex.length === 1 ? '0' + hex : hex;
    };
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

// Lighten a color by a percentage
function lighten(hex: string, percent: number): string {
    const rgb = hexToRgb(hex);
    if (!rgb) return hex;
    const factor = percent / 100;
    return rgbToHex(
        rgb.r + (255 - rgb.r) * factor,
        rgb.g + (255 - rgb.g) * factor,
        rgb.b + (255 - rgb.b) * factor
    );
}

// Darken a color by a percentage
function darken(hex: string, percent: number): string {
    const rgb = hexToRgb(hex);
    if (!rgb) return hex;
    const factor = 1 - percent / 100;
    return rgbToHex(rgb.r * factor, rgb.g * factor, rgb.b * factor);
}

// Desaturate a color
function desaturate(hex: string, percent: number): string {
    const rgb = hexToRgb(hex);
    if (!rgb) return hex;
    const gray = 0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b;
    const factor = percent / 100;
    return rgbToHex(
        rgb.r + (gray - rgb.r) * factor,
        rgb.g + (gray - rgb.g) * factor,
        rgb.b + (gray - rgb.b) * factor
    );
}

// Create a color with specific hue (keeping saturation high)
function createColorWithHue(hue: number, saturation = 0.7, lightness = 0.5): string {
    // HSL to RGB conversion
    const c = (1 - Math.abs(2 * lightness - 1)) * saturation;
    const x = c * (1 - Math.abs((hue / 60) % 2 - 1));
    const m = lightness - c / 2;
    
    let r = 0, g = 0, b = 0;
    if (hue < 60) { r = c; g = x; b = 0; }
    else if (hue < 120) { r = x; g = c; b = 0; }
    else if (hue < 180) { r = 0; g = c; b = x; }
    else if (hue < 240) { r = 0; g = x; b = c; }
    else if (hue < 300) { r = x; g = 0; b = c; }
    else { r = c; g = 0; b = x; }
    
    return rgbToHex((r + m) * 255, (g + m) * 255, (b + m) * 255);
}

// Smart color matching without AI
function matchColorsHeuristically(
    elementorColors: Array<{ name: string; value: string }>,
    _builtInConfigs: BuiltInColorConfig[]
): Partial<BuiltInColors> & { unmatchedColors: ColorEntry[] } {
    const result: Partial<BuiltInColors> = {};
    const usedColors = new Set<string>();
    const unmatchedColors: ColorEntry[] = [];

    // Analyze all colors
    const analyzedColors = elementorColors.map(c => ({
        ...c,
        luminance: getLuminance(c.value),
        saturation: getSaturation(c.value),
        hue: getHue(c.value),
    }));

    // Sort by saturation (most vibrant first for primary/secondary/accent)
    const sortedByVibrance = [...analyzedColors].sort((a, b) => b.saturation - a.saturation);
    
    // Sort by luminance
    const sortedByLuminance = [...analyzedColors].sort((a, b) => a.luminance - b.luminance);

    // 1. Try to match by name first
    const nameMatches: Record<string, string[]> = {
        primary: ['ראשי', 'primary', 'main', 'brand'],
        secondary: ['משני', 'secondary', 'sub'],
        accent: ['הדגשה', 'accent', 'highlight'],
        text: ['טקסט', 'text', 'font'],
        textMuted: ['משני', 'muted', 'secondary text', 'gray'],
        textLight: ['בהיר', 'light', 'white'],
        background: ['רקע', 'background', 'bg', 'white'],
        backgroundDark: ['כהה', 'dark', 'black'],
        surface: ['משטח', 'surface', 'card'],
        border: ['גבול', 'border', 'line'],
        success: ['הצלחה', 'success', 'green', 'ירוק'],
        warning: ['אזהרה', 'warning', 'yellow', 'orange', 'צהוב', 'כתום'],
        error: ['שגיאה', 'error', 'red', 'אדום', 'danger'],
    };

    // Try name-based matching
    for (const [key, patterns] of Object.entries(nameMatches)) {
        for (const color of analyzedColors) {
            if (usedColors.has(color.value)) continue;
            const lowerName = color.name.toLowerCase();
            if (patterns.some(p => lowerName.includes(p))) {
                result[key as keyof BuiltInColors] = color.value;
                usedColors.add(color.value);
                break;
            }
        }
    }

    // 2. Heuristic matching for unmapped colors
    // Primary - most vibrant unused color
    if (!result.primary) {
        const vibrant = sortedByVibrance.find(c => !usedColors.has(c.value) && c.saturation > 0.3);
        if (vibrant) {
            result.primary = vibrant.value;
            usedColors.add(vibrant.value);
        }
    }

    // Secondary - second most vibrant
    if (!result.secondary) {
        const vibrant = sortedByVibrance.find(c => !usedColors.has(c.value) && c.saturation > 0.2);
        if (vibrant) {
            result.secondary = vibrant.value;
            usedColors.add(vibrant.value);
        }
    }

    // Accent - third most vibrant
    if (!result.accent) {
        const vibrant = sortedByVibrance.find(c => !usedColors.has(c.value) && c.saturation > 0.2);
        if (vibrant) {
            result.accent = vibrant.value;
            usedColors.add(vibrant.value);
        }
    }

    // Text - darkest unused color with low saturation
    if (!result.text) {
        const dark = sortedByLuminance.find(c => !usedColors.has(c.value) && c.luminance < 0.2);
        if (dark) {
            result.text = dark.value;
            usedColors.add(dark.value);
        }
    }

    // Background Dark - very dark color
    if (!result.backgroundDark) {
        const dark = sortedByLuminance.find(c => !usedColors.has(c.value) && c.luminance < 0.1);
        if (dark) {
            result.backgroundDark = dark.value;
            usedColors.add(dark.value);
        }
    }

    // Text Light - brightest color
    if (!result.textLight) {
        const light = [...sortedByLuminance].reverse().find(c => !usedColors.has(c.value) && c.luminance > 0.9);
        if (light) {
            result.textLight = light.value;
            usedColors.add(light.value);
        }
    }

    // Background - very light color
    if (!result.background) {
        const light = [...sortedByLuminance].reverse().find(c => !usedColors.has(c.value) && c.luminance > 0.8);
        if (light) {
            result.background = light.value;
            usedColors.add(light.value);
        }
    }

    // Success - greenish hue (90-150)
    if (!result.success) {
        const green = analyzedColors.find(c => !usedColors.has(c.value) && c.hue >= 90 && c.hue <= 150 && c.saturation > 0.3);
        if (green) {
            result.success = green.value;
            usedColors.add(green.value);
        }
    }

    // Warning - yellow/orange hue (30-60)
    if (!result.warning) {
        const yellow = analyzedColors.find(c => !usedColors.has(c.value) && c.hue >= 30 && c.hue <= 60 && c.saturation > 0.3);
        if (yellow) {
            result.warning = yellow.value;
            usedColors.add(yellow.value);
        }
    }

    // Error - red hue (0-20 or 340-360)
    if (!result.error) {
        const red = analyzedColors.find(c => !usedColors.has(c.value) && ((c.hue >= 0 && c.hue <= 20) || c.hue >= 340) && c.saturation > 0.3);
        if (red) {
            result.error = red.value;
            usedColors.add(red.value);
        }
    }

    for (const color of analyzedColors) {
        if (!usedColors.has(color.value)) {
            unmatchedColors.push({ id: generateColorId(), name: color.name, value: color.value });
        }
    }

    return { ...result, unmatchedColors };
}

// Generate missing colors mathematically from existing colors
function generateMissingColors(matched: Partial<BuiltInColors>): BuiltInColors {
    const result = { ...matched } as BuiltInColors;
    
    // Find a base vibrant color to derive others from
    const baseColor = result.primary || result.secondary || result.accent || '#3BC2D0';
    const baseHue = getHue(baseColor);
    
    // Primary - use base or create a teal
    if (!result.primary) {
        result.primary = baseColor !== '#3BC2D0' ? baseColor : '#3BC2D0';
    }
    
    // Secondary - complementary or analogous color
    if (!result.secondary) {
        const secondaryHue = (baseHue + 150) % 360; // Split-complementary
        result.secondary = createColorWithHue(secondaryHue, 0.75, 0.45);
    }
    
    // Accent - triadic color
    if (!result.accent) {
        const accentHue = (baseHue + 240) % 360;
        result.accent = createColorWithHue(accentHue, 0.6, 0.55);
    }
    
    // Text - very dark, slightly desaturated version of primary
    if (!result.text) {
        result.text = darken(desaturate(result.primary, 80), 75);
    }
    
    // Text Muted - lighter than text
    if (!result.textMuted) {
        result.textMuted = lighten(result.text, 40);
    }
    
    // Text Light - almost white, or white
    if (!result.textLight) {
        result.textLight = '#FFFFFF';
    }
    
    // Background - very light, almost white
    if (!result.background) {
        result.background = '#FFFFFF';
    }
    
    // Background Dark - very dark version of primary
    if (!result.backgroundDark) {
        result.backgroundDark = darken(desaturate(result.primary, 70), 80);
    }
    
    // Surface - slightly off-white, tinted with primary
    if (!result.surface) {
        result.surface = lighten(desaturate(result.primary, 90), 95);
    }
    
    // Border - light gray, slightly tinted
    if (!result.border) {
        result.border = lighten(desaturate(result.primary, 85), 75);
    }
    
    // Success - green
    if (!result.success) {
        result.success = createColorWithHue(145, 0.65, 0.45); // Green
    }
    
    // Warning - orange/yellow
    if (!result.warning) {
        result.warning = createColorWithHue(38, 0.9, 0.55); // Orange
    }
    
    // Error - red
    if (!result.error) {
        result.error = createColorWithHue(0, 0.75, 0.55); // Red
    }
    
    return result;
}

export const ColorsSection: React.FC<ColorsSectionProps> = ({
    colors,
    onChange,
    disabled = false,
}) => {
    const [newColorName, setNewColorName] = useState('');
    const [newColorValue, setNewColorValue] = useState('#6366F1');
    const [isImporting, setIsImporting] = useState(false);
    const [importMessage, setImportMessage] = useState<{ type: 'success' | 'error' | 'info'; text: string } | null>(null);
    
    // Ensure custom colors array exists
    const customColors = colors?.custom ?? [];
    
    // Handle built-in color change
    const handleBuiltInColorChange = (key: keyof BuiltInColors, value: string) => {
        onChange({
            ...colors,
            custom: customColors,
            [key]: value,
        });
    };
    
    // Handle custom color change
    const handleCustomColorChange = (colorId: string, field: 'name' | 'value', value: string) => {
        const newCustom = customColors.map(c => c.id === colorId ? { ...c, [field]: value } : c);
        onChange({
            ...colors,
            custom: newCustom,
        });
    };
    
    // Add new custom color
    const handleAddCustomColor = () => {
        if (!newColorName.trim()) return;
        
        onChange({
            ...colors,
            custom: [...customColors, { id: generateColorId(), name: newColorName.trim(), value: newColorValue }],
        });
        setNewColorName('');
        setNewColorValue('#6366F1');
    };
    
    // Remove custom color
    const handleRemoveCustomColor = (colorId: string) => {
        const newCustom = customColors.filter(c => c.id !== colorId);
        onChange({
            ...colors,
            custom: newCustom,
        });
    };
    
    // Import colors from Elementor
    const handleImportElementor = async () => {
        setIsImporting(true);
        setImportMessage(null);
        
        try {
            const response = await apiClient.get<{ data: { message: string; imported: { colors?: any } } }>('appearance-presets/import-elementor');
            const imported = response?.data?.imported;
            
            if (imported?.colors) {
                // Collect all colors from Elementor
                const elementorColors: Array<{ name: string; value: string }> = [];
                
                // Add mapped colors
                if (imported.colors.primary) {
                    elementorColors.push({ name: 'Primary', value: imported.colors.primary });
                }
                if (imported.colors.secondary) {
                    elementorColors.push({ name: 'Secondary', value: imported.colors.secondary });
                }
                if (imported.colors.text) {
                    elementorColors.push({ name: 'Text', value: imported.colors.text });
                }
                if (imported.colors.accent) {
                    elementorColors.push({ name: 'Accent', value: imported.colors.accent });
                }
                
                // Add custom colors
                if (imported.colors.customColors && Array.isArray(imported.colors.customColors)) {
                    imported.colors.customColors.forEach((c: { name: string; value: string }) => {
                        elementorColors.push(c);
                    });
                }
                
                if (elementorColors.length === 0) {
                    setImportMessage({ type: 'info', text: t('No colors found in Elementor to import') });
                    setIsImporting(false);
                    return;
                }
                
                // Use heuristic matching to map Elementor colors to slots
                const matched = matchColorsHeuristically(elementorColors, getBuiltInColorConfigs());
                
                // Generate any missing colors mathematically
                const completeColors = generateMissingColors(matched);
                
                // Create the final colors object
                const newColors: BuiltInColors & { custom: ColorEntry[] } = {
                    ...completeColors,
                    custom: [...customColors],
                };
                
                // Add unmatched colors as custom colors
                if (matched.unmatchedColors && matched.unmatchedColors.length > 0) {
                    newColors.custom = [...customColors, ...matched.unmatchedColors];
                }
                
                onChange(newColors);
                
                // Count how many colors were imported vs generated
                const importedCount = Object.keys(matched).filter(k => k !== 'unmatchedColors' && matched[k as keyof typeof matched]).length;
                const generatedCount = 13 - importedCount;
                
                setImportMessage({ 
                    type: 'success', 
                    text: generatedCount > 0 
                        ? sprintf(t('Imported %s colors and generated %s additional colors!'), String(importedCount), String(generatedCount))
                        : sprintf(t('Successfully imported all %s colors!'), String(importedCount))
                });
            } else {
                setImportMessage({ type: 'info', text: t('No colors found in Elementor') });
            }
        } catch (error: any) {
            setImportMessage({ 
                type: 'error', 
                text: error?.message || t('Error importing colors from Elementor') 
            });
        }
        
        setIsImporting(false);
    };
    
    return (
        <div className="colors-section space-y-8">
            {/* Import from Elementor Button */}
            <div
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '12px 16px',
                    background: 'linear-gradient(135deg, #92003B 0%, #FF6F61 100%)',
                    borderRadius: '10px',
                    marginBottom: '16px',
                }}
            >
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <Download size={18} color="#FFFFFF" />
                    <div>
                        <span style={{ fontSize: '14px', fontWeight: 600, color: '#FFFFFF', display: 'block' }}>
                            {t('Import Colors from Elementor')}
                        </span>
                        <span style={{ fontSize: '11px', color: 'rgba(255,255,255,0.8)' }}>
                            {t('Auto-matching and filling missing colors')}
                        </span>
                    </div>
                </div>
                <button
                    onClick={handleImportElementor}
                    disabled={disabled || isImporting}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '6px',
                        padding: '8px 16px',
                        background: '#FFFFFF',
                        border: 'none',
                        borderRadius: '6px',
                        fontSize: '13px',
                        fontWeight: 600,
                        color: '#92003B',
                        cursor: disabled || isImporting ? 'not-allowed' : 'pointer',
                        opacity: disabled || isImporting ? 0.7 : 1,
                    }}
                >
                    {isImporting ? (
                        <>
                            <Loader2 size={14} className="animate-spin" />
                            <span>{t('Importing...')}</span>
                        </>
                    ) : (
                        <span>{t('Import')}</span>
                    )}
                </button>
            </div>
            
            {/* Import Message */}
            {importMessage && (
                <div
                    style={{
                        padding: '10px 14px',
                        borderRadius: '8px',
                        fontSize: '13px',
                        background: importMessage.type === 'success' ? '#ECFDF5' 
                            : importMessage.type === 'error' ? '#FEF2F2' 
                            : '#EFF6FF',
                        color: importMessage.type === 'success' ? '#065F46' 
                            : importMessage.type === 'error' ? '#991B1B' 
                            : '#1E40AF',
                        border: `1px solid ${
                            importMessage.type === 'success' ? '#A7F3D0' 
                            : importMessage.type === 'error' ? '#FECACA' 
                            : '#BFDBFE'
                        }`,
                    }}
                >
                    {importMessage.text}
                </div>
            )}
            
            {/* Built-in Colors */}
            <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                    {t('System Colors')}
                </h3>
                <p className="text-sm text-gray-500 mb-4">
                    {t('These colors are used as defaults across all chat components. You can link to them from any element.')}
                </p>
                
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
                    gap: '16px',
                }}>
                    {getBuiltInColorConfigs().map((config) => (
                        <div
                            key={config.key}
                            className="bg-white border border-gray-200 rounded-lg p-3 hover:border-gray-300 hover:shadow-sm transition-all overflow-hidden"
                        >
                            <label className="block text-sm font-semibold text-gray-800 mb-0.5">
                                {config.label}
                            </label>
                            <p className="text-xs text-gray-400 mb-1">
                                {config.description}
                            </p>
                            <code className="text-[10px] bg-gray-100 px-1.5 py-0.5 rounded font-mono text-gray-500 mb-2 inline-block">
                                colors.{config.key}
                            </code>
                            <ColorPicker
                                value={colors[config.key]}
                                onChange={(color: string) => handleBuiltInColorChange(config.key, color)}
                                disabled={disabled}
                                showOpacity
                            />
                        </div>
                    ))}
                </div>
            </div>
            
            {/* Custom Colors */}
            <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                    {t('Custom Colors')}
                </h3>
                <p className="text-sm text-gray-500 mb-4">
                    {t('Add custom colors that you can link to from various components.')}
                </p>
                
                {/* Custom Colors List */}
                {customColors.length > 0 && (
                    <div className="space-y-3 mb-4">
                        {customColors.map((color) => (
                            <div
                                key={color.id}
                                className="flex items-center gap-3 bg-white border border-gray-200 rounded-lg p-3"
                            >
                                <ColorPicker
                                    value={color.value}
                                    onChange={(value: string) => handleCustomColorChange(color.id, 'value', value)}
                                    disabled={disabled}
                                />
                                <input
                                    type="text"
                                    value={color.name}
                                    onChange={(e) => handleCustomColorChange(color.id, 'name', e.target.value)}
                                    className="flex-1 text-sm border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary focus:border-primary"
                                    placeholder={t('Color name')}
                                    disabled={disabled}
                                />
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono text-gray-600">
                                    colors.custom.{color.id}
                                </code>
                                <button
                                    onClick={() => handleRemoveCustomColor(color.id)}
                                    className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                    disabled={disabled}
                                    title={t('Remove color')}
                                >
                                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        ))}
                    </div>
                )}
                
                {/* Add New Custom Color */}
                <div className="flex items-center gap-3 bg-gradient-to-r from-gray-50 to-primary-50 border-2 border-dashed border-primary-200 rounded-lg p-4">
                    <ColorPicker
                        value={newColorValue}
                        onChange={(value: string) => setNewColorValue(value)}
                        disabled={disabled}
                    />
                    <input
                        type="text"
                        value={newColorName}
                        onChange={(e) => setNewColorName(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && handleAddCustomColor()}
                        className="flex-1 text-sm border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-primary focus:border-primary bg-white"
                        placeholder={t('New color name...')}
                        disabled={disabled}
                    />
                    <button
                        type="button"
                        onClick={() => handleAddCustomColor()}
                        disabled={disabled || !newColorName.trim()}
                        className="inline-flex items-center gap-2 px-5 py-2.5 bg-primary-600 text-white text-sm font-semibold rounded-lg hover:bg-primary-700 transition-all shadow-sm hover:shadow disabled:opacity-50 disabled:cursor-not-allowed"
                        style={{
                            backgroundColor: newColorName.trim() ? '#3BC2D0' : '#9CA3AF',
                            minWidth: '100px',
                        }}
                    >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 4v16m8-8H4" />
                        </svg>
                        {t('Add Color')}
                    </button>
                </div>
            </div>
            
            {/* Color Preview Grid */}
            <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                    {t('Preview')}
                </h3>
                <div className="flex flex-wrap gap-3">
                    {getBuiltInColorConfigs().map((config) => (
                        <div
                            key={config.key}
                            className="flex flex-col items-center gap-1"
                            title={`${config.label}: ${colors[config.key]}`}
                        >
                            <div
                                className="w-10 h-10 rounded-lg border border-gray-200 shadow-sm cursor-help"
                                style={{ backgroundColor: colors[config.key] }}
                            />
                            <span className="text-[10px] text-gray-500 max-w-[60px] text-center leading-tight">{config.label}</span>
                        </div>
                    ))}
                    {colors.custom.map((color) => (
                        <div
                            key={color.id}
                            className="flex flex-col items-center gap-1"
                            title={`${color.name}: ${color.value}`}
                        >
                            <div
                                className="w-10 h-10 rounded-lg border border-gray-200 shadow-sm cursor-help"
                                style={{ backgroundColor: color.value }}
                            />
                            <span className="text-[10px] text-gray-500 max-w-[60px] text-center leading-tight">{color.name}</span>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default ColorsSection;

