/**
 * Text Shadow Control Component
 * 
 * Elementor-style text shadow control with:
 * - Pencil icon to open popover
 * - Color picker
 * - Horizontal offset (X)
 * - Vertical offset (Y)
 * - Blur radius
 * 
 * @since 1.5.0
 */

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Pencil, X, Eye, EyeOff } from 'lucide-react';
import { ColorPicker } from '../../common/ColorPicker';
import { t } from '@/lib/i18n';

interface TextShadowValue {
    enabled: boolean;
    color: string;
    horizontal: number;
    vertical: number;
    blur: number;
}

interface TextShadowControlProps {
    label: string;
    value: string;
    onChange: (value: string) => void;
    disabled?: boolean;
}

// Parse CSS text-shadow value
function parseTextShadow(value: string): TextShadowValue {
    if (!value || value === 'none' || value === '') {
        return {
            enabled: false,
            color: 'rgba(0,0,0,0.3)',
            horizontal: 1,
            vertical: 1,
            blur: 2,
        };
    }
    
    // Parse: "1px 2px 3px rgba(0,0,0,0.5)" or "1px 2px 3px #000"
    const match = value.match(/^([-\d.]+)px\s+([-\d.]+)px\s+([-\d.]+)px\s+(.+)$/);
    if (match) {
        return {
            enabled: true,
            horizontal: parseFloat(match[1]) || 0,
            vertical: parseFloat(match[2]) || 0,
            blur: parseFloat(match[3]) || 0,
            color: match[4] || 'rgba(0,0,0,0.3)',
        };
    }
    
    return {
        enabled: true,
        color: 'rgba(0,0,0,0.3)',
        horizontal: 1,
        vertical: 1,
        blur: 2,
    };
}

// Build CSS text-shadow value
function buildTextShadow(shadow: TextShadowValue): string {
    if (!shadow.enabled) return 'none';
    return `${shadow.horizontal}px ${shadow.vertical}px ${shadow.blur}px ${shadow.color}`;
}

export const TextShadowControl: React.FC<TextShadowControlProps> = ({
    label,
    value,
    onChange,
    disabled = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [shadow, setShadow] = useState<TextShadowValue>(parseTextShadow(value));
    const popoverRef = useRef<HTMLDivElement>(null);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const [popoverPosition, setPopoverPosition] = useState({ top: 0, left: 0 });
    
    // Calculate popover position when opening
    const updatePopoverPosition = useCallback(() => {
        if (triggerRef.current) {
            const rect = triggerRef.current.getBoundingClientRect();
            const popoverHeight = 480; // Approximate height of popover
            const popoverWidth = 288; // w-72
            const viewportHeight = window.innerHeight;
            const viewportWidth = window.innerWidth;
            
            // Check if there's enough space below
            const spaceBelow = viewportHeight - rect.bottom;
            const shouldOpenAbove = spaceBelow < popoverHeight && rect.top > popoverHeight;
            
            let top = shouldOpenAbove ? rect.top - popoverHeight - 8 : rect.bottom + 8;
            const maxTop = Math.max(16, viewportHeight - popoverHeight - 16);
            top = Math.min(Math.max(16, top), maxTop);

            // RTL-friendly: align to trigger right edge
            let left = rect.right - popoverWidth;
            const maxLeft = Math.max(16, viewportWidth - popoverWidth - 16);
            left = Math.min(Math.max(16, left), maxLeft);

            setPopoverPosition({ top, left });
        }
    }, []);
    
    // Sync with external value changes
    useEffect(() => {
        setShadow(parseTextShadow(value));
    }, [value]);
    
    // Close popover when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (popoverRef.current && !popoverRef.current.contains(event.target as Node) &&
                triggerRef.current && !triggerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        
        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside);
            updatePopoverPosition();
            // Update position on scroll/resize
            window.addEventListener('scroll', updatePopoverPosition, true);
            window.addEventListener('resize', updatePopoverPosition);
        }
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
            window.removeEventListener('scroll', updatePopoverPosition, true);
            window.removeEventListener('resize', updatePopoverPosition);
        };
    }, [isOpen, updatePopoverPosition]);
    
    // Update shadow and emit change
    const updateShadow = (updates: Partial<TextShadowValue>) => {
        const newShadow = { ...shadow, ...updates };
        setShadow(newShadow);
        onChange(buildTextShadow(newShadow));
    };

    // IMPORTANT: admin Tailwind utilities are scoped with `important: '.boostbot-admin'`,
    // so portals must render inside the `.boostbot-admin` subtree.
    const portalContainer =
        (document.querySelector('.boostbot-admin') as HTMLElement | null) ||
        (document.getElementById('boostbot-admin-root') as HTMLElement | null) ||
        document.body;
    
    return (
        <div className="text-shadow-control relative">
            <div className="flex items-center justify-between mb-1">
                <label className="text-xs text-gray-600 font-medium">{label}</label>
            </div>
            
            {/* Control Row */}
            <div className="flex items-center gap-2">
                {/* Toggle Button */}
                <button
                    type="button"
                    onClick={() => updateShadow({ enabled: !shadow.enabled })}
                    disabled={disabled}
                    className={`p-2 rounded-lg border transition-colors ${
                        shadow.enabled 
                            ? 'bg-primary-50 border-primary-300 text-primary-600' 
                            : 'bg-gray-50 border-gray-200 text-gray-400'
                    }`}
                    title={shadow.enabled ? t('Remove shadow') : t('Add shadow')}
                >
                    {shadow.enabled ? <Eye size={14} /> : <EyeOff size={14} />}
                </button>
                
                {/* Preview & Edit Button - Always clickable to open settings */}
                <button
                    ref={triggerRef}
                    type="button"
                    onClick={() => {
                        // If shadow is disabled, enable it first
                        if (!shadow.enabled) {
                            updateShadow({ enabled: true });
                        }
                        setIsOpen(!isOpen);
                    }}
                    disabled={disabled}
                    className={`flex-1 flex items-center justify-between px-3 py-2 rounded-lg border transition-colors ${
                        shadow.enabled 
                            ? 'bg-white border-gray-200 hover:border-primary-300' 
                            : 'bg-gray-50 border-gray-200 hover:border-gray-300'
                    }`}
                >
                    <span 
                        className="text-sm font-medium"
                        style={{ 
                            textShadow: shadow.enabled ? buildTextShadow(shadow) : 'none',
                        }}
                    >
                        {t('Sample text')}
                    </span>
                    <Pencil size={14} className="text-gray-400" />
                </button>
            </div>
            
            {/* Popover - Using Portal to avoid overflow clipping */}
            {isOpen && createPortal(
                <div 
                    ref={popoverRef}
                    className="fixed w-72 bg-white rounded-lg shadow-xl border border-gray-200 p-4 animate-fade-in"
                    style={{
                        top: popoverPosition.top,
                        left: popoverPosition.left,
                        zIndex: 999999, // High z-index to be above WordPress admin modals
                        backgroundColor: '#FFFFFF',
                        opacity: 1,
                    }}
                >
                    {/* Header */}
                    <div className="flex items-center justify-between mb-4">
                        <h4 className="text-sm font-semibold text-gray-900">{t('Text shadow settings')}</h4>
                        <button
                            type="button"
                            onClick={() => setIsOpen(false)}
                            className="p-1 text-gray-400 hover:text-gray-600 rounded"
                        >
                            <X size={16} />
                        </button>
                    </div>
                    
                    {/* Preview */}
                    <div className="mb-4 p-4 bg-gray-100 rounded-lg text-center">
                        <span 
                            className="text-2xl font-bold text-gray-800"
                            style={{ textShadow: buildTextShadow(shadow) }}
                        >
                            {t('Sample text')}
                        </span>
                    </div>
                    
                    {/* Color */}
                    <div className="mb-4">
                        <label className="text-xs text-gray-500 mb-1.5 block">{t('Shadow color')}</label>
                        <ColorPicker
                            value={shadow.color}
                            onChange={(color) => updateShadow({ color })}
                            disabled={disabled}
                        />
                    </div>
                    
                    {/* Horizontal Offset */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Horizontal offset (X)')}</label>
                            <span className="text-xs text-gray-400">{shadow.horizontal}px</span>
                        </div>
                        <input
                            type="range"
                            min={-20}
                            max={20}
                            step={1}
                            value={shadow.horizontal}
                            onChange={(e) => updateShadow({ horizontal: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Vertical Offset */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Vertical offset (Y)')}</label>
                            <span className="text-xs text-gray-400">{shadow.vertical}px</span>
                        </div>
                        <input
                            type="range"
                            min={-20}
                            max={20}
                            step={1}
                            value={shadow.vertical}
                            onChange={(e) => updateShadow({ vertical: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Blur */}
                    <div className="mb-3">
                        <div className="flex items-center justify-between mb-1">
                            <label className="text-xs text-gray-500">{t('Blur')}</label>
                            <span className="text-xs text-gray-400">{shadow.blur}px</span>
                        </div>
                        <input
                            type="range"
                            min={0}
                            max={30}
                            step={1}
                            value={shadow.blur}
                            onChange={(e) => updateShadow({ blur: parseInt(e.target.value) })}
                            disabled={disabled}
                            className="w-full h-1.5 bg-gray-200 rounded-full appearance-none cursor-pointer"
                        />
                    </div>
                    
                    {/* Quick Presets */}
                    <div className="border-t border-gray-200 pt-3 mt-3">
                        <label className="text-xs text-gray-500 mb-2 block">{t('Quick presets')}</label>
                        <div className="flex gap-2">
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 1, vertical: 1, blur: 2, color: 'rgba(0,0,0,0.2)' })}
                                className="flex-1 py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Subtle')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 2, vertical: 2, blur: 4, color: 'rgba(0,0,0,0.3)' })}
                                className="flex-1 py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Medium')}
                            </button>
                            <button
                                type="button"
                                onClick={() => updateShadow({ horizontal: 3, vertical: 3, blur: 6, color: 'rgba(0,0,0,0.4)' })}
                                className="flex-1 py-1.5 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                            >
                                {t('Strong')}
                            </button>
                        </div>
                    </div>
                </div>,
                portalContainer
            )}
        </div>
    );
};

export default TextShadowControl;

