const { useState, useEffect, useRef } = React;

// --- Configuración ---
const API_URL = 'https://tryon.likemedia.ai/api_proxy.php'; // Apunta al backend principal
const STORAGE_KEY = 'lm_tryon_history_v3';
const MOCK_MODE = false; // Set true para probar sin backend

// --- Componentes UI ---

const Header = () => (
    <div className="text-center mb-8 fade-in">
        <h1 className="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600 mb-2">
            Probador Virtual IA
        </h1>
        <p className="text-slate-500">Sube tus fotos y visualiza el resultado en segundos</p>
    </div>
);

const Dropzone = ({ label, icon, onFile, preview }) => {
    const inputRef = useRef(null);

    const handleFile = (e) => {
        const file = e.target.files[0];
        if (file) onFile(file);
    };

    return (
        <div className="flex flex-col gap-2">
            <span className="font-semibold text-slate-700 text-sm">{label}</span>
            <div
                onClick={() => inputRef.current.click()}
                className={`
                    border-2 border-dashed rounded-xl h-48 flex flex-col items-center justify-center cursor-pointer transition-all duration-200 relative overflow-hidden group
                    ${preview ? 'border-indigo-500 bg-indigo-50' : 'border-slate-300 hover:border-indigo-400 hover:bg-slate-50 bg-white'}
                `}
            >
                <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />

                {preview ? (
                    <img src={URL.createObjectURL(preview)} className="w-full h-full object-contain p-2" alt="Preview" />
                ) : (
                    <div className="text-center p-4">
                        <div className="text-4xl mb-3 text-slate-400 group-hover:text-indigo-500 transition-colors">
                            {icon}
                        </div>
                        <p className="text-sm text-slate-500 font-medium">Click para subir</p>
                    </div>
                )}
            </div>
        </div>
    );
};

const RatioSelect = ({ value, onChange }) => (
    <div className="w-full">
        <label className="block text-sm font-semibold text-slate-700 mb-2">Formato de Salida</label>
        <select
            value={value}
            onChange={(e) => onChange(e.target.value)}
            className="w-full p-3 bg-white border border-slate-200 rounded-lg text-slate-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-shadow"
        >
            <option value="1:1">1:1 (Cuadrado)</option>
            <option value="9:16">9:16 (Stories/Reels)</option>
            <option value="16:9">16:9 (Horizontal)</option>
            <option value="4:5">4:5 (Instagram Portrait)</option>
            <option value="3:4">3:4 (Vertical Estándar)</option>
        </select>
    </div>
);

const ResultCard = ({ item, onDelete }) => {
    const [isHovered, setIsHovered] = useState(false);

    // Fallback híbrido de descarga (Logic Copied from V1.9)
    const handleDownload = async () => {
        const url = item.url || item.urlimagen;
        const filename = `tryon_${item.id}.png`;
        try {
            const response = await fetch(url);
            const blob = await response.blob();
            const blobUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = blobUrl;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(blobUrl);
        } catch (e) {
            console.warn("Direct download failed, using proxy", e);
            const downloadBase = API_URL.substring(0, API_URL.lastIndexOf('/'));
            window.location.href = `${downloadBase}/download_image.php?url=${encodeURIComponent(url)}`;
        }
    };

    return (
        <div
            className="group relative rounded-xl overflow-hidden bg-slate-100 shadow-sm hover:shadow-xl transition-all duration-300 aspect-[3/4]"
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
        >
            <img
                src={item.url || item.urlimagen}
                alt="Resultado"
                className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
            />

            {/* Overlay */}
            <div className={`absolute inset-0 bg-black/40 backdrop-blur-[2px] flex flex-col items-center justify-center gap-2 transition-opacity duration-200 ${isHovered ? 'opacity-100' : 'opacity-0'}`}>

                <button
                    onClick={() => window.open(item.url || item.urlimagen, '_blank')}
                    className="flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-full text-xs font-semibold backdrop-blur-md transition-all transform hover:scale-105"
                >
                    <i className="fas fa-eye"></i> Ver
                </button>

                <button
                    onClick={handleDownload}
                    className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-full text-xs font-semibold shadow-lg transition-all transform hover:scale-105"
                >
                    <i className="fas fa-download"></i> Descargar
                </button>

                <button
                    onClick={() => onDelete(item.id)}
                    className="flex items-center gap-2 px-4 py-2 bg-red-500/90 hover:bg-red-500 text-white rounded-full text-xs font-semibold shadow-lg transition-all transform hover:scale-105 mt-2"
                >
                    <i className="fas fa-trash"></i> Borrar
                </button>
            </div>

            <div className="absolute top-2 right-2">
                <span className="px-2 py-1 bg-black/50 text-white text-[10px] rounded backdrop-blur">
                    {new Date(item.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                </span>
            </div>
        </div>
    );
};

// --- Main App ---

const App = () => {
    // State
    const [personFile, setPersonFile] = useState(null);
    const [clothFile, setClothFile] = useState(null);
    const [ratio, setRatio] = useState('1:1');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [history, setHistory] = useState([]);

    // Load History on Mount
    useEffect(() => {
        const saved = localStorage.getItem(STORAGE_KEY);
        if (saved) {
            try {
                const parsed = JSON.parse(saved);
                if (Array.isArray(parsed)) setHistory(parsed);
            } catch (e) { console.error("History load error", e); }
        }
    }, []);

    // Save History on Change
    useEffect(() => {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
    }, [history]);

    // --- B2B Contextual Loader ---
    const [isContextMode, setIsContextMode] = useState(false);

    useEffect(() => {
        const container = document.getElementById('tryon-widget-container-react');
        const contextUrl = container?.getAttribute('data-product-image');

        if (contextUrl) {
            setIsContextMode(true);
            setLoading(true); // Show loading while fetching context image

            // Fetch the image and convert to File to mimic user upload
            fetch(contextUrl)
                .then(res => res.blob())
                .then(blob => {
                    const file = new File([blob], "product_context.jpg", { type: blob.type });
                    setClothFile(file);
                    // Also define a preview property on the file for the Dropzone to show it (if we were showing it)
                    // But usually Dropzone takes the file and creates objectURL. 
                    // We can just rely on normal Dropzone behavior or custom UI.
                })
                .catch(err => console.error("Error loading context product:", err))
                .finally(() => setLoading(false));
        }
    }, []);

    const handleClearHistory = () => {
        if (confirm('¿Seguro que quieres borrar todo el historial?')) {
            setHistory([]);
        }
    };

    const handleDeleteItem = (id) => {
        if (confirm('¿Eliminar esta imagen?')) {
            setHistory(prev => prev.filter(item => item.id !== id));
        }
    };

    const handleGenerate = async () => {
        if (!personFile || !clothFile) {
            setError("Por favor sube ambas imágenes");
            return;
        }

        setError(null);
        setLoading(true);

        const formData = new FormData();
        formData.append('action', 'tryon');
        formData.append('api_key', 'TEST-KEY-123'); // Debería venir de config
        formData.append('user_email', 'react_tester@example.com');
        formData.append('prefijo_tabla', 'react_beta');
        formData.append('image_ratio', ratio);
        formData.append('num_images', '1');
        formData.append('imagen_modelo', personFile);
        formData.append('imagen_accesorio', clothFile);

        try {
            if (MOCK_MODE) {
                // Simulation
                await new Promise(r => setTimeout(r, 2000));
                const mockItem = {
                    id: Date.now().toString(),
                    url: 'https://via.placeholder.com/600x800',
                    timestamp: Date.now()
                };
                setHistory(prev => [mockItem, ...prev]);
            } else {
                // Real API
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: { 'X-Api-Key': 'TEST-KEY-123' },
                    body: formData
                });

                if (!response.ok) throw new Error("Error en el servidor");
                const result = await response.json();
                const imageUrl = result.url || result.urlimagen || (Array.isArray(result) ? result[0].urlimagen : null);

                if (imageUrl) {
                    const newItem = {
                        id: Date.now().toString(),
                        url: imageUrl,
                        timestamp: Date.now()
                    };
                    setHistory(prev => [newItem, ...prev]);
                } else {
                    throw new Error("No se recibió imagen válida");
                }
            }
        } catch (err) {
            setError(err.message || "Error desconocido");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="bg-white rounded-3xl shadow-2xl p-6 md:p-10 border border-slate-100/50 fade-in">
            <Header />

            <div className="grid md:grid-cols-2 gap-6 mb-8">
                {/* Context Mode: Show Product Card instead of Dropzone */}
                {isContextMode ? (
                    <div className="border-2 border-indigo-100 bg-indigo-50/50 rounded-xl h-48 flex flex-col items-center justify-center relative overflow-hidden p-4">
                        <div className="absolute top-0 left-0 bg-indigo-500 text-white text-[10px] font-bold px-3 py-1 rounded-br-lg z-10">
                            PRODUCTO DE TIENDA
                        </div>
                        {clothFile ? (
                            <img
                                src={URL.createObjectURL(clothFile)}
                                className="h-32 object-contain mb-2 drop-shadow-md"
                                alt="Producto"
                            />
                        ) : (
                            <div className="animate-pulse flex flex-col items-center">
                                <i className="fas fa-spinner fa-spin text-2xl text-indigo-400 mb-2"></i>
                                <span className="text-xs text-indigo-400">Cargando producto...</span>
                            </div>
                        )}
                        <p className="text-xs text-indigo-600 font-semibold mt-1">
                            <i className="fas fa-check-circle"></i> Prenda lista
                        </p>
                    </div>
                ) : (
                    <Dropzone
                        label="1. Prenda"
                        icon="👕"
                        preview={clothFile}
                        onFile={setClothFile}
                    />
                )}

                <Dropzone
                    label={isContextMode ? "1. Tu Foto" : "2. Tu Foto"}
                    icon="📸"
                    preview={personFile}
                    onFile={setPersonFile}
                />
            </div>

            <div className="bg-slate-50 p-6 rounded-2xl mb-8 border border-slate-100">
                <div className="grid md:grid-cols-[1fr,auto] gap-4 items-end">
                    <RatioSelect value={ratio} onChange={setRatio} />

                    <button
                        onClick={handleGenerate}
                        disabled={loading}
                        className={`
                            h-[50px] px-8 rounded-lg font-bold text-white shadow-lg transition-all transform
                            ${loading
                                ? 'bg-slate-400 cursor-not-allowed'
                                : 'bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 hover:scale-[1.02] hover:shadow-indigo-500/30'
                            }
                        `}
                    >
                        {loading ? (
                            <span className="flex items-center gap-2">
                                <i className="fas fa-spinner fa-spin"></i> Procesando...
                            </span>
                        ) : (
                            <span className="flex items-center gap-2">
                                <i className="fas fa-wand-magic-sparkles"></i> Generar
                            </span>
                        )}
                    </button>
                </div>
                {error && (
                    <div className="mt-4 p-3 bg-red-50 text-red-600 text-sm font-medium rounded-lg flex items-center gap-2 animate-bounce">
                        <i className="fas fa-exclamation-circle"></i> {error}
                    </div>
                )}
            </div>

            {/* Results Section */}
            {history.length > 0 && (
                <div className="fade-in">
                    <div className="flex items-center justify-between mb-6 border-b border-slate-100 pb-4">
                        <h3 className="text-xl font-bold text-slate-800">
                            Resultados <span className="text-sm font-normal text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full ml-2">{history.length}</span>
                        </h3>
                        {history.length > 0 && (
                            <button
                                onClick={handleClearHistory}
                                className="text-xs font-semibold text-red-500 hover:text-red-700 hover:bg-red-50 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1"
                            >
                                <i className="fas fa-trash-alt"></i> Borrar Todo
                            </button>
                        )}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                        {history.map(item => (
                            <ResultCard key={item.id} item={item} onDelete={handleDeleteItem} />
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

// Render
// Render
const initWidget = () => {
    const container = document.getElementById('tryon-widget-container-react') || document.getElementById('root');
    if (container) {
        const root = ReactDOM.createRoot(container);
        root.render(<App />);
    } else {
        console.error("TryOn Widget: Target container not found!");
    }
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initWidget);
} else {
    initWidget();
}
