import { useState, useEffect, useCallback } from 'react';
import { getMyServices, getServiceDetails, getHostingServiceDetails, resetHostingPassword } from '../../services/api';
import { useVPC } from '../../services/useVPC';
import { Server, Database, Cloud, Globe, Folder, Trash2, ExternalLink, Loader, Plus, Play, Lock, Maximize2 } from 'lucide-react';

// ============================================================================
// COMPOSANT 0 : MODAL DE NOTIFICATION (Remplace les alert() natifs)
// ============================================================================
const NotificationModal = ({ notification, onClose }) => {
    if (!notification) return null;
    const isError = notification.type === 'error';
    return (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
            <div className={`bg-gray-900 border ${isError ? 'border-red-500/50 shadow-red-500/10' : 'border-cyan-500/50 shadow-cyan-500/10'} rounded-lg shadow-2xl max-w-sm w-full p-6 text-gray-200`}>
                <h4 className={`text-lg font-mono font-bold tracking-wider mb-2 ${isError ? 'text-red-400' : 'text-cyan-400'}`}>
                    {notification.title.toUpperCase()}
                </h4>
                <p className="text-sm text-gray-400 mb-6">{notification.message}</p>
                <button onClick={onClose} className={`w-full font-mono py-2 rounded text-xs font-bold transition ${isError ? 'bg-red-600 hover:bg-red-500 text-white' : 'bg-cyan-500 hover:bg-cyan-400 text-gray-950'}`}>
                    COMPRIS
                </button>
            </div>
        </div>
    );
};

// ============================================================================
// COMPOSANT 1 : INSTANCE CARD (Mode PaaS Pur - IP Masquée)
// ============================================================================
const InstanceCard = ({ service, vpcs, onAssignVpc, onRemoveVpc, onOpenConsole, isConnecting }) => {
    const titleLower = (service.title || '').toLowerCase();
    const isVPS = titleLower.includes('vps') || titleLower.includes('compute');
    const isCloud = titleLower.includes('cloud') || titleLower.includes('nextcloud');
    const isDB = titleLower.includes('db') || titleLower.includes('base') || titleLower.includes('sql');
    const isWeb = !isVPS && !isCloud && !isDB;

    const hasIP = service.hostingDetails?.ip && service.hostingDetails.ip !== '127.0.0.1' && service.hostingDetails.ip !== '';

    let buttonText = "CONSOLE D'ADMINISTRATION";
    let ButtonIcon = ExternalLink;
    let buttonStyle = "bg-cyan-400/10 hover:bg-cyan-400 text-cyan-400 hover:text-gray-900 border-cyan-400";

    if (isVPS) {
        if (hasIP) {
            buttonText = "GÉRER L'INSTANCE";
            ButtonIcon = ExternalLink;
        } else {
            buttonText = "INITIALISATION";
            ButtonIcon = Play;
            buttonStyle = "bg-yellow-500/10 text-yellow-500 hover:bg-yellow-500 hover:text-gray-900 border-yellow-500/50";
        }
    } else if (isWeb) {
        buttonText = "GÉRER L'HÉBERGEMENT";
        ButtonIcon = Globe;
        buttonStyle = "bg-emerald-400/10 hover:bg-emerald-400 text-emerald-400 hover:text-gray-900 border-emerald-400";
    } else if (isCloud) {
        buttonText = "ACCÉDER AU CLOUD";
        buttonStyle = "bg-blue-400/10 hover:bg-blue-400 text-blue-400 hover:text-gray-900 border-blue-400";
    } else if (isDB) {
        buttonText = "PHPMYADMIN / CLUSTER";
        ButtonIcon = Database;
        buttonStyle = "bg-purple-400/10 hover:bg-purple-400 text-purple-400 hover:text-gray-900 border-purple-400";
    }

    const getServiceIcon = () => {
        if (isVPS) return <Server className="w-8 h-8 text-cyan-400" />;
        if (isCloud) return <Cloud className="w-8 h-8 text-blue-400" />;
        if (isDB) return <Database className="w-8 h-8 text-purple-400" />;
        return <Globe className="w-8 h-8 text-emerald-400" />;
    };

    const baseTitle = (service.title || '').split(/(?: for | pour )/i)[0].trim();
    const shortTitle = baseTitle.split(' ').slice(0, 2).join(' ');

    const titleMatch = (service.title || '').match(/(?: for | pour )(.+)$/i);
    const domainFromTitle = titleMatch ? titleMatch[1].trim() : null;

    let displayDomain = service.hostingDetails?.domain && service.hostingDetails.domain !== '127.0.0.1'
        ? service.hostingDetails.domain
        : domainFromTitle || service.domain;

    if (!displayDomain || displayDomain === '127.0.0.1') displayDomain = null;

    return (
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-5 flex flex-col justify-between hover:border-gray-700 transition-all shadow-lg">
            <div>
                <div className="flex justify-between items-start mb-4">
                    <div className="p-2 bg-black/40 rounded-lg">
                        {getServiceIcon()}
                    </div>
                    {service.status === 'active' ? (
                        <span className="bg-emerald-500/10 text-emerald-400 px-2 py-1 rounded text-xs border border-emerald-500/20 font-bold tracking-widest">
                            {isVPS && !hasIP ? 'AWAITING INIT' : 'ONLINE'}
                        </span>
                    ) : (
                        <span className="bg-orange-500/10 text-orange-400 px-2 py-1 rounded text-xs border border-orange-500/20 animate-pulse">DEPLOYING</span>
                    )}
                </div>

                <h3 className="font-bold text-white text-lg truncate" title={baseTitle}>
                    {shortTitle}
                </h3>

                <div className="flex flex-col gap-1 mt-2 mb-4 h-8 justify-center">
                    {displayDomain ? (
                        <p className={`${isVPS ? 'text-cyan-400' : 'text-emerald-400'} text-xs font-mono truncate`} title={displayDomain}>
                            {displayDomain}
                        </p>
                    ) : (
                        <p className="text-gray-600 text-xs font-mono italic">En attente de déploiement</p>
                    )}
                </div>
            </div>

            <div className="mt-auto space-y-3">
                <div className="flex items-center justify-between text-sm border-t border-gray-800 pt-3">
                    <span className="text-gray-500 text-xs">Projet VPC:</span>
                    <select
                        onChange={(e) => {
                            const val = e.target.value;
                            if (val === "free") onRemoveVpc(service.id);
                            else if (val) onAssignVpc(service.id, val);
                        }}
                        className="bg-black border border-gray-700 text-gray-300 rounded px-2 py-1 outline-none focus:border-cyan-400 text-xs w-[130px]"
                        defaultValue={vpcs.find(v => v.services.includes(service.id))?.id || "free"}
                    >
                        <option value="free">-- Libre --</option>
                        {vpcs.map(vpc => (
                            <option key={vpc.id} value={vpc.id}>{vpc.name}</option>
                        ))}
                    </select>
                </div>

                <button
                    onClick={() => onOpenConsole(service)}
                    disabled={isConnecting === service.id || service.status !== 'active'}
                    className={`w-full flex items-center justify-center space-x-2 py-2.5 rounded-lg font-bold text-sm tracking-wide transition-all disabled:opacity-50 border ${buttonStyle}`}
                >
                    {isConnecting === service.id ? (
                        <><Loader className="w-4 h-4 animate-spin" /><span>CONNEXION...</span></>
                    ) : (
                        <><ButtonIcon className="w-4 h-4" /><span>{buttonText}</span></>
                    )}
                </button>
            </div>
        </div>
    );
};

// ============================================================================
// COMPOSANT 2 : VPS DEPLOYER (Instanciation)
// ============================================================================
const VpsDeployer = ({ serviceId, onDeploySuccess, onAlert }) => {
    const [domain, setDomain] = useState('');
    const [password, setPassword] = useState('');
    const [isDeploying, setIsDeploying] = useState(false);

    const handleDeploy = async () => {
        if (password.length < 8) { onAlert("Sécurité", "Le mot de passe doit faire au moins 8 caractères.", "error"); return; }

        setIsDeploying(true);
        try {
            const response = await fetch('https://web.gise.be/custom_api/proxmox_create_vps.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ service_id: serviceId, domain: domain, password: password })
            });
            const data = await response.json();

            if (data.status === 'success') {
                onDeploySuccess({ ip: data.ip, domain: data.domain, password: password });
            } else {
                onAlert("Échec", "Erreur de provisionnement : " + (data.message || 'Inconnue'), "error");
            }
        } catch (err) {
            onAlert("Erreur Réseau", "Erreur de communication avec l'API Proxmox Gateway.", "error");
        } finally {
            setIsDeploying(false);
        }
    };

    return (
        <div>
            <div className="bg-yellow-900/20 border border-yellow-600/30 p-4 rounded mb-6 text-yellow-500/80 text-sm">
                <span className="font-bold text-yellow-500">PHASE D'INITIALISATION REQUISE</span><br />
                La facturation est activée. Veuillez définir un mot de passe Root pour lancer la création de l'instance sur l'hyperviseur.
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label className="block text-xs uppercase tracking-widest text-cyan-500 mb-1">Hostname personnalisé (Optionnel)</label>
                    <input type="text" value={domain} onChange={(e) => setDomain(e.target.value.toLowerCase())} placeholder="Laissez vide pour le défaut" className="w-full bg-gray-950 border border-gray-800 text-white p-3 rounded font-mono outline-none focus:border-cyan-500 transition-colors" />
                </div>
                <div>
                    <label className="block text-xs uppercase tracking-widest text-cyan-500 mb-1">Mot de passe Root (Requis)</label>
                    <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••" className="w-full bg-gray-950 border border-gray-800 text-white p-3 rounded font-mono outline-none focus:border-cyan-500 transition-colors" />
                </div>
            </div>
            <button onClick={handleDeploy} disabled={isDeploying} className={`mt-6 w-full px-6 py-3 rounded font-bold font-mono tracking-widest uppercase transition ${isDeploying ? 'bg-gray-800 text-gray-500 cursor-not-allowed' : 'bg-cyan-600 hover:bg-cyan-500 text-white shadow-lg shadow-cyan-500/20'}`}>
                {isDeploying ? 'Fabrication sur le Métal en cours...' : 'Lancer l\'Instanciation'}
            </button>
        </div>
    );
};

// ============================================================================
// COMPOSANT 3 : VPS MANAGER (Day-2 Operations)
// ============================================================================
const VpsManager = ({ details, orderId, onRefresh, onAlert }) => {
    const [showTerminal, setShowTerminal] = useState(false);
    const [isEditingDomain, setIsEditingDomain] = useState(false);
    const [newDomain, setNewDomain] = useState(details.domain);
    const [isUpdating, setIsUpdating] = useState(false);
    const [sslStatus, setSslStatus] = useState(null);

    const isInternal = details.domain && details.domain.endsWith('.gise.be');
    const isCustomDomain = details.domain && !isInternal;

    const fileManagerUrl = isInternal ? `https://file-${details.domain}` : `http://${details.domain}:8080`;
    const terminalUrl = isInternal ? `https://terminal-${details.domain}` : `http://${details.domain}:8081`;

    const handleUpdateDomain = async () => {
        if (!newDomain || newDomain === details.domain) return;
        setIsUpdating(true);
        try {
            const response = await fetch('https://web.gise.be/custom_api/update_service_domain.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ order_id: orderId, new_domain: newDomain })
            });
            const data = await response.json();
            if (data.status === 'success') {
                setIsEditingDomain(false);
                if (onRefresh) onRefresh();
                onAlert("Succès", "Domaine VPS mis à jour avec succès sur l'infrastructure !", "success");
            } else onAlert("Erreur", data.error, "error");
        } catch (err) {
            onAlert("Erreur", "Erreur de connexion avec l'API.", "error");
        } finally { setIsUpdating(false); }
    };

    const handleGenerateSSL = async () => {
        setSslStatus('loading');
        try {
            const response = await fetch('https://web.gise.be/custom_api/generate_custom_ssl.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ domain: details.domain })
            });
            const data = await response.json();
            if (data.status === 'success') {
                setSslStatus('success');
                onAlert("SSL Activé", "Certificat SSL Let's Encrypt généré et activé avec succès !", "success");
            } else {
                setSslStatus('error');
                onAlert("Challenge DNS Échoué", "Vérifiez que votre domaine pointe bien vers notre IP publique.", "error");
            }
        } catch (e) { setSslStatus('error'); }
    };

    return (
        <div>
            {!showTerminal ? (
                <>
                    <div className="mb-6 bg-gray-950 border border-gray-800 rounded p-4">
                        <label className="block text-xs uppercase tracking-widest text-cyan-500 mb-2">Domaine de l'instance VPS</label>
                        {!isEditingDomain ? (
                            <div className="flex justify-between items-center">
                                <span className="font-mono text-xl text-green-400 font-bold flex items-center gap-2">
                                    <span className="h-3 w-3 rounded-full bg-green-500 shadow-[0_0_10px_#22c55e]"></span>
                                    {details.domain}
                                </span>
                                <button onClick={() => setIsEditingDomain(true)} className="text-xs border border-gray-700 hover:border-cyan-500 text-gray-400 hover:text-cyan-400 px-3 py-1.5 rounded transition">MODIFIER</button>
                            </div>
                        ) : (
                            <div className="flex gap-2">
                                <input type="text" value={newDomain} onChange={(e) => setNewDomain(e.target.value.toLowerCase())} className="flex-1 bg-black border border-gray-700 rounded px-3 py-1.5 text-white font-mono text-sm focus:border-cyan-500 outline-none" disabled={isUpdating} />
                                <button onClick={handleUpdateDomain} disabled={isUpdating} className="bg-cyan-500 text-gray-900 px-4 py-1.5 rounded text-xs font-bold hover:bg-cyan-400">
                                    {isUpdating ? 'SYNC...' : 'SAUVEGARDER'}
                                </button>
                                <button onClick={() => setIsEditingDomain(false)} className="bg-gray-800 text-white px-3 py-1.5 rounded text-xs hover:bg-gray-700">ANNULER</button>
                            </div>
                        )}
                        {isCustomDomain && (
                            <div className="mt-4 border-t border-gray-900 pt-3 flex justify-between items-center">
                                <p className="text-[11px] text-gray-500">Domaine externe détecté. Sécurisez après pointage DNS.</p>
                                <button onClick={handleGenerateSSL} disabled={sslStatus === 'loading'} className="text-xs bg-purple-600/20 hover:bg-purple-600 text-purple-400 hover:text-white border border-purple-500/30 px-3 py-1 rounded transition flex items-center gap-1">
                                    {sslStatus === 'loading' ? 'GÉNÉRATION...' : <><Lock className="w-3 h-3" /> GÉNÉRER SSL</>}
                                </button>
                            </div>
                        )}

                        {/* ACCÈS DE FAUT REMIS À JOUR */}
                        <div className="mt-4 bg-black/60 border border-gray-900 rounded p-3 text-[11px] space-y-1">
                            <span className="text-gray-500 font-bold uppercase tracking-wider block mb-1 text-[10px]">Identifiants d'usine :</span>
                            <p className="text-gray-400 font-mono">Console SSH : <span className="text-cyan-400 font-bold">root</span> / <span className="text-gray-500 italic">Clé choisie à l'initialisation</span></p>
                            <p className="text-gray-400 font-mono">Explorateur : <span className="text-cyan-400 font-bold">admin</span> / <span className="text-cyan-400 font-bold">admin</span></p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                        <div>
                            <label className="block text-xs uppercase tracking-widest text-cyan-500 mb-1">Explorateur de Fichiers</label>
                            <button onClick={() => window.open(fileManagerUrl, '_blank')} className="w-full bg-gray-950 hover:bg-gray-900 border border-gray-800 hover:border-cyan-500/50 rounded p-3 flex justify-between items-center transition group">
                                <span className="font-mono text-gray-300 text-sm flex items-center gap-2"><Folder className="w-4 h-4 text-cyan-500" /> Ouvrir l'explorateur</span>
                                <ExternalLink className="w-4 h-4 text-gray-600 group-hover:text-cyan-400" />
                            </button>
                        </div>
                        <div>
                            <label className="block text-xs uppercase tracking-widest text-cyan-500 mb-1">Console Système</label>
                            <button onClick={() => setShowTerminal(true)} className="w-full bg-cyan-900/20 hover:bg-cyan-900/40 border border-cyan-800/50 hover:border-cyan-500 rounded p-3 flex justify-between items-center transition group">
                                <span className="font-mono text-cyan-400 text-sm flex items-center gap-2"><span>{">_"}</span> Ouvrir le Terminal</span>
                                <Play className="w-4 h-4 text-cyan-600 group-hover:text-cyan-400" />
                            </button>
                        </div>
                    </div>
                </>
            ) : (
                <div>
                    <div className="flex justify-between items-center mb-4 border-b border-gray-800 pb-2">
                        <span className="text-cyan-400 font-mono text-sm tracking-widest">NEXUS TERMINAL ({details.domain})</span>
                        <div className="flex items-center space-x-2">
                            {/* OPTION AJOUTÉE : OUVRIR EN PLEIN ÉCRAN DANS UN NOUVEL ONGLET */}
                            <button onClick={() => { window.open(terminalUrl, '_blank'); setShowTerminal(false); }} className="text-xs bg-cyan-600/30 text-cyan-400 hover:bg-cyan-600 hover:text-white border border-cyan-500/30 px-3 py-1 rounded transition flex items-center gap-1">
                                <Maximize2 className="w-3 h-3" /> Plein Écran ↗
                            </button>
                            <button onClick={() => setShowTerminal(false)} className="text-xs bg-red-900/30 text-white px-3 py-1 rounded">Fermer</button>
                        </div>
                    </div>
                    <div className="bg-black border border-gray-800 rounded h-[400px]">
                        <iframe src={terminalUrl} className="w-full h-full border-none" title="Terminal" />
                    </div>
                </div>
            )}
        </div>
    );
};

// ============================================================================
// COMPOSANT 4 : WEB MANAGER (HestiaCP & Day-2 Operations)
// ============================================================================
const WebManager = ({ details, orderId, onRefresh, onOpenSso, onAlert }) => {
    const [isEditingDomain, setIsEditingDomain] = useState(false);
    const [newDomain, setNewDomain] = useState(details.domain);
    const [isUpdating, setIsUpdating] = useState(false);
    const [sslStatus, setSslStatus] = useState(null);
    const [isGeneratingSso, setIsGeneratingSso] = useState(false);

    const isCustomDomain = details.domain && !details.domain.endsWith('.gise.be');
    const siteUrl = (isCustomDomain && sslStatus !== 'success') ? `http://${details.domain}` : `https://${details.domain}`;

    const handleUpdateDomain = async () => {
        if (!newDomain || newDomain === details.domain) return;
        setIsUpdating(true);
        try {
            const response = await fetch('https://web.gise.be/custom_api/update_service_domain.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ order_id: orderId, new_domain: newDomain })
            });
            const data = await response.json();
            if (data.status === 'success') {
                setIsEditingDomain(false);
                if (onRefresh) onRefresh(); 
                onAlert("Succès", "Domaine web mis à jour avec succès sur le serveur HestiaCP !", "success");
            } else onAlert("Erreur", data.error, "error");
        } catch (err) {
            onAlert("Erreur", "Erreur de connexion avec l'API.", "error");
        } finally { setIsUpdating(false); }
    };

    const handleGenerateSSL = async () => {
        setSslStatus('loading');
        try {
            const response = await fetch('https://web.gise.be/custom_api/generate_custom_ssl.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ domain: details.domain })
            });
            const data = await response.json();
            if (data.status === 'success') {
                setSslStatus('success');
                onAlert("SSL Validé", "Certificat SSL Let's Encrypt généré !", "success");
            } else {
                setSslStatus('error');
                onAlert("Erreur DNS", "Échec Let's Encrypt. Vérifiez vos DNS.", "error");
            }
        } catch (e) { setSslStatus('error'); }
    };

    const handleOpenPanel = async () => {
        setIsGeneratingSso(true);
        try {
            const secureHash = Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-4).toUpperCase();
            const rollingPassword = `Nx${secureHash}`;
            await resetHostingPassword(orderId, rollingPassword);
            onOpenSso({ username: details.username, password: rollingPassword, url: 'https://panel.gise.be/login/' });
        } catch (err) {
            onAlert("Erreur Métal", "Erreur lors de la génération du SSO HestiaCP.", "error");
        } finally {
            setIsGeneratingSso(false);
        }
    };

    return (
        <div>
            <div className="mb-6 bg-gray-950 border border-gray-800 rounded p-4">
                <label className="block text-xs uppercase tracking-widest text-emerald-500 mb-2">Domaine du Site Web</label>
                {!isEditingDomain ? (
                    <div className="flex justify-between items-center">
                        <span className="font-mono text-xl text-emerald-400 font-bold flex items-center gap-2">
                            <span className="h-3 w-3 rounded-full bg-emerald-500 shadow-[0_0_10px_#10b981]"></span>
                            {details.domain}
                        </span>
                        <button onClick={() => setIsEditingDomain(true)} className="text-xs border border-gray-700 hover:border-emerald-500 text-gray-400 hover:text-emerald-400 px-3 py-1.5 rounded transition">MODIFIER</button>
                    </div>
                ) : (
                    <div className="flex gap-2">
                        <input type="text" value={newDomain} onChange={(e) => setNewDomain(e.target.value.toLowerCase())} className="flex-1 bg-black border border-gray-700 rounded px-3 py-1.5 text-white font-mono text-sm focus:border-emerald-500 outline-none" disabled={isUpdating} />
                        <button onClick={handleUpdateDomain} disabled={isUpdating} className="bg-emerald-500 text-gray-900 px-4 py-1.5 rounded text-xs font-bold hover:bg-emerald-400">
                            {isUpdating ? 'SYNC...' : 'SAUVEGARDER'}
                        </button>
                        <button onClick={() => setIsEditingDomain(false)} className="bg-gray-800 text-white px-3 py-1.5 rounded text-xs hover:bg-gray-700">ANNULER</button>
                    </div>
                )}

                {isCustomDomain && (
                    <div className="mt-4 border-t border-gray-900 pt-3 flex justify-between items-center">
                        <p className="text-[11px] text-gray-500">Domaine personnalisé détecté. Sécurisez après pointage DNS.</p>
                        <button onClick={handleGenerateSSL} disabled={sslStatus === 'loading'} className="text-xs bg-purple-600/20 hover:bg-purple-600 text-purple-400 hover:text-white border border-purple-500/30 px-3 py-1 rounded transition flex items-center gap-1">
                            {sslStatus === 'loading' ? 'GÉNÉRATION...' : <><Lock className="w-3 h-3" /> GÉNÉRER SSL</>}
                        </button>
                    </div>
                )}
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label className="block text-xs uppercase tracking-widest text-emerald-500 mb-1">Visiter le Site</label>
                    <button onClick={() => window.open(siteUrl, '_blank')} className="w-full bg-gray-950 hover:bg-gray-900 border border-gray-800 hover:border-emerald-500/50 rounded p-3 flex justify-between items-center transition group">
                        <span className="font-mono text-gray-300 text-sm flex items-center gap-2"><Globe className="w-4 h-4 text-emerald-500" /> Ouvrir dans le navigateur</span>
                        <ExternalLink className="w-4 h-4 text-gray-600 group-hover:text-emerald-400" />
                    </button>
                </div>
                <div>
                    <label className="block text-xs uppercase tracking-widest text-emerald-500 mb-1">Panel de Contrôle</label>
                    <button onClick={handleOpenPanel} disabled={isGeneratingSso} className="w-full bg-emerald-900/20 hover:bg-emerald-900/40 border border-emerald-800/50 hover:border-emerald-500 rounded p-3 flex justify-between items-center transition group disabled:opacity-50">
                        {isGeneratingSso ? (
                            <span className="font-mono text-emerald-400 text-sm flex items-center gap-2"><Loader className="w-4 h-4 animate-spin" /> GÉNÉRATION SSO...</span>
                        ) : (
                            <>
                                <span className="font-mono text-emerald-400 text-sm flex items-center gap-2"><Lock className="w-4 h-4" /> Gérer l'hébergement</span>
                                <ExternalLink className="w-4 h-4 text-emerald-600 group-hover:text-emerald-400" />
                            </>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
};

// ============================================================================
// COMPOSANT PRINCIPAL : SERVICES
// ============================================================================
export default function Services() {
    const [services, setServices] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [newVpcName, setNewVpcName] = useState("");
    const [isConnecting, setIsConnecting] = useState(null);
    const [ssoVault, setSsoVault] = useState(null);
    const [activeServiceModal, setActiveServiceModal] = useState(null); 
    const [customAlert, setCustomAlert] = useState(null); // Gère les pop-ups personnalisés

    const { vpcs, createVPC, deleteVPC, assignToVPC, removeFromVPC } = useVPC();

    const triggerAlert = (title, message, type = "info") => {
        setCustomAlert({ title, message, type });
    };

    const fetchServices = useCallback(async () => {
        try {
            const data = await getMyServices();
            if (data.list && data.list.length > 0) {
                const detailedServices = await Promise.all(
                    data.list.map(async (order) => {
                        let hDetails = null;
                        if (order.status === 'active' && (order.plugin === 'hosting' || (order.title || '').toLowerCase().includes('vps'))) {
                            try { hDetails = await getHostingServiceDetails(order.id); } 
                            catch (e) { console.warn(`Détails inaccessibles pour ${order.id}:`, e); }
                        }
                        return { ...order, hostingDetails: hDetails };
                    })
                );

                const filteredServices = detailedServices.filter(s => {
                    const type = (s.type || '').toLowerCase();
                    const title = (s.title || '').toLowerCase();
                    const isGhostProduct = type === 'domain' || title.includes('domain') || title.includes('domaine') || title.includes('enregistrement');
                    return (s.status === 'active' || s.status === 'pending_setup') && !isGhostProduct;
                });

                setServices(filteredServices);
            }
        } catch (err) {
            setError(err.message || "Impossible de charger la télémétrie des services.");
        } finally {
            setIsLoading(false);
        }
    }, []);

    useEffect(() => {
        fetchServices();
    }, [fetchServices]);

    const handleOpenConsole = async (service) => {
        const titleLower = (service.title || '').toLowerCase();
        const isVPS = titleLower.includes('vps') || titleLower.includes('compute');
        const isCloud = titleLower.includes('cloud') || titleLower.includes('nextcloud');
        const isDB = titleLower.includes('db') || titleLower.includes('base') || titleLower.includes('sql');
        const isWeb = !isVPS && !isCloud && !isDB;

        setIsConnecting(service.id);

        try {
            if (isCloud) {
                const titleMatch = (service.title || '').match(/(?: for | pour )(.+)$/i);
                const domainUrl = titleMatch ? titleMatch[1].trim() : service.domain;
                if (domainUrl) window.open(`https://${domainUrl}`, '_blank');
            } else if (isDB) {
                window.open('https://pma.gise.be/', '_blank');
            } else if (isVPS || isWeb) {
                const freshDetails = await getHostingServiceDetails(service.id);
                setActiveServiceModal({ type: isVPS ? 'vps' : 'web', data: service, details: freshDetails });
            }
        } catch (err) {
            triggerAlert("Erreur d'Orchestration", "Échec du protocole : " + err.message, "error");
        } finally {
            setIsConnecting(null);
        }
    };

    const assignedServiceIds = vpcs.flatMap(vpc => vpc.services);
    const freeServices = services.filter(s => !assignedServiceIds.includes(s.id));

    if (isLoading) return <div className="text-center mt-20 text-cyan-400 animate-pulse font-mono tracking-widest">ANALYSE DU RÉSEAU...</div>;

    return (
        <div className="max-w-7xl mx-auto mt-8 p-6">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-10 gap-4">
                <div>
                    <h1 className="text-3xl font-black text-white tracking-wider">INVENTAIRE RÉSEAU</h1>
                    <p className="text-gray-400 mt-1">Orchestration des environnements et des Virtual Private Clouds.</p>
                </div>

                <div className="flex space-x-2 bg-gray-900 p-2 rounded-xl border border-gray-800">
                    <input type="text" placeholder="Nom du nouveau VPC..." value={newVpcName} onChange={(e) => setNewVpcName(e.target.value)} className="bg-black border border-gray-800 rounded-lg px-4 py-2 text-sm text-white focus:outline-none focus:border-cyan-400 w-64" />
                    <button onClick={() => { createVPC(newVpcName); setNewVpcName(""); triggerAlert("VPC", "Nouveau groupe de routage VPC créé avec succès !", "success"); }} disabled={!newVpcName.trim()} className="bg-cyan-400 text-gray-900 px-4 py-2 rounded-lg font-bold text-sm disabled:opacity-50 hover:bg-cyan-300 flex items-center">
                        <Plus className="w-4 h-4 mr-1" /> CRÉER GROUPE
                    </button>
                </div>
            </div>

            {error && <div className="text-red-400 bg-red-400/10 p-4 rounded-xl border border-red-500/20 mb-6">{error}</div>}

            <div className="space-y-8 mb-12">
                {vpcs.map(vpc => {
                    const vpcServices = services.filter(s => vpc.services.includes(s.id));
                    return (
                        <div key={vpc.id} className="bg-gray-900/40 border border-gray-800 rounded-2xl p-6">
                            <div className="flex justify-between items-center mb-6 border-b border-gray-800 pb-4">
                                <div className="flex items-center space-x-3 text-white">
                                    <Folder className="w-6 h-6 text-cyan-400" />
                                    <h2 className="text-xl font-bold tracking-wider">{vpc.name.toUpperCase()}</h2>
                                    <span className="bg-gray-800 text-gray-400 px-2 py-0.5 rounded text-xs font-mono">{vpcServices.length} INSTANCES</span>
                                </div>
                                <button onClick={() => { deleteVPC(vpc.id); triggerAlert("VPC Démantelé", "Le groupe de routage a été dissous. Les instances ont été reversées dans le pool libre.", "info"); }} className="text-gray-500 hover:text-red-400 transition-colors flex items-center text-sm">
                                    <Trash2 className="w-4 h-4 mr-1" /> Démanteler VPC
                                </button>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                                {vpcServices.length === 0 ? (
                                    <div className="col-span-full text-gray-600 text-sm border border-dashed border-gray-800 rounded-xl p-6 text-center font-mono">
                                        Réseau virtuel vide. Assigner des instances depuis le pool libre.
                                    </div>
                                ) : (
                                    vpcServices.map(service => (
                                        <InstanceCard
                                            key={service.id} service={service} vpcs={vpcs}
                                            onAssignVpc={assignToVPC} onRemoveVpc={removeFromVPC}
                                            onOpenConsole={handleOpenConsole} isConnecting={isConnecting}
                                        />
                                    ))
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>

            <div>
                <h2 className="text-lg font-bold text-gray-500 tracking-wider mb-6 flex items-center">
                    <Server className="w-5 h-5 mr-2" /> POOL D'INSTANCES LIBRES
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {freeServices.length === 0 ? (
                        <div className="col-span-full text-gray-600 text-sm border border-gray-900 bg-gray-900/20 rounded-xl p-6 text-center font-mono">
                            Aucune instance libre. Toutes vos accréditations sont assignées à des VPC.
                        </div>
                    ) : (
                        freeServices.map(service => (
                            <InstanceCard
                                key={service.id} service={service} vpcs={vpcs}
                                onAssignVpc={assignToVPC} onRemoveVpc={removeFromVPC}
                                onOpenConsole={handleOpenConsole} isConnecting={isConnecting}
                            />
                        ))
                    )}
                </div>
            </div>

            {/* MODAL 1 : HESTIACP SSO VAULT */}
            {ssoVault && (
                <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-[60] flex items-center justify-center p-4">
                    <div className="bg-gray-900 border border-emerald-500/50 rounded-lg shadow-2xl shadow-emerald-500/20 max-w-md w-full p-6 text-gray-200">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="text-xl font-bold text-emerald-400 font-mono tracking-wider">ACCÈS AUTORISÉ</h3>
                            {/* La croix permet de fermer manuellement le modal après copie */}
                            <button onClick={() => setSsoVault(null)} className="text-gray-400 hover:text-white transition text-lg">✖</button>
                        </div>
                        <p className="text-sm text-gray-400 mb-6">Le pare-feu HestiaCP bloque les injections directes. Un mot de passe <strong>jetable</strong> a été généré. Copiez-le et connectez-vous.</p>
                        <div className="space-y-4 mb-8">
                            <div>
                                <label className="block text-xs uppercase tracking-widest text-emerald-500 mb-1">Utilisateur</label>
                                <div className="flex bg-gray-950 border border-gray-800 rounded p-3 justify-between items-center">
                                    <span className="font-mono text-white">{ssoVault.username}</span>
                                    <button onClick={() => navigator.clipboard.writeText(ssoVault.username)} className="text-xs bg-gray-800 hover:bg-gray-700 text-white px-3 py-1 rounded transition">Copier</button>
                                </div>
                            </div>
                            <div>
                                <label className="block text-xs uppercase tracking-widest text-emerald-500 mb-1">Clé Éphémère</label>
                                <div className="flex bg-gray-950 border border-gray-800 rounded p-3 justify-between items-center">
                                    <span className="font-mono text-emerald-400">{ssoVault.password}</span>
                                    <button onClick={() => navigator.clipboard.writeText(ssoVault.password)} className="text-xs bg-emerald-600 hover:bg-emerald-500 text-white px-3 py-1 rounded transition">Copier</button>
                                </div>
                            </div>
                        </div>
                        {/* REFIXÉ : Pas de setSsoVault(null) ici pour garder le modal ouvert au retour de l'onglet */}
                        <a href={ssoVault.url} target="_blank" rel="noopener noreferrer" className="block w-full bg-emerald-500 hover:bg-emerald-400 text-gray-950 font-bold py-3 text-center rounded transition font-mono tracking-widest uppercase">
                            Ouvrir le Panel Web ↗
                        </a>
                    </div>
                </div>
            )}

            {/* MODAL 2 : GESTIONNAIRE DE SERVICE GÉNÉRIQUE (VPS & WEB) */}
            {activeServiceModal && (
                <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className={`bg-gray-900 border rounded-lg shadow-2xl max-w-2xl w-full p-6 text-gray-200 ${activeServiceModal.type === 'vps' ? 'border-cyan-500/50 shadow-cyan-500/20' : 'border-emerald-500/50 shadow-emerald-500/20'}`}>
                        <div className="flex justify-between items-center mb-6 border-b border-gray-800 pb-4">
                            <h3 className="text-xl font-bold text-white tracking-wider flex items-center gap-3">
                                {activeServiceModal.type === 'vps' ? (
                                    <><Server className="w-6 h-6 text-cyan-400" /> {activeServiceModal.details?.ip && activeServiceModal.details.ip !== '127.0.0.1' ? "GESTION DE L'INSTANCE" : "PHASE D'INITIALISATION"}</>
                                ) : (
                                    <><Globe className="w-6 h-6 text-emerald-400" /> GESTION DE L'HÉBERGEMENT WEB</>
                                )}
                            </h3>
                            <button onClick={() => setActiveServiceModal(null)} className="text-gray-400 hover:text-white transition text-xl">✖</button>
                        </div>

                        {activeServiceModal.type === 'vps' ? (
                            activeServiceModal.details?.ip && activeServiceModal.details.ip !== '127.0.0.1' ? (
                                <VpsManager details={activeServiceModal.details} orderId={activeServiceModal.data.id} onRefresh={fetchServices} onAlert={triggerAlert} />
                            ) : (
                                <VpsDeployer serviceId={activeServiceModal.data.id} onDeploySuccess={() => { setActiveServiceModal(null); fetchServices(); }} onAlert={triggerAlert} />
                            )
                        ) : (
                            <WebManager details={activeServiceModal.details} orderId={activeServiceModal.data.id} onRefresh={fetchServices} onOpenSso={setSsoVault} onAlert={triggerAlert} />
                        )}
                    </div>
                </div>
            )}

            {/* VRAI MODAL DE NOTIFICATION REACT SURCHARGE */}
            <NotificationModal notification={customAlert} onClose={() => setCustomAlert(null)} />
        </div>
    );
}