// ============================================================================
// DASHBOARD VIEW
// ============================================================================

const DashboardView = () => {
    const { customer } = useAuth();
    const [screens, setScreens] = useState([]);
    const [loading, setLoading] = useState(true);
    const [stats, setStats] = useState({
        total_screens: 0,
        active_screens: 0,
        total_ads: 0,
        total_news: 0
    });

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

    const loadScreens = async () => {
        setLoading(true);
        try {
            const result = await api.getScreens(customer.id);
            if (result.screens) {
                setScreens(result.screens);
                
                // Calculer les stats
                setStats({
                    total_screens: result.screens.length,
                    active_screens: result.screens.filter(s => s.is_active == 1).length,
                    total_ads: result.screens.reduce((sum, s) => sum + (parseInt(s.ads_count) || 0), 0),
                    total_news: result.screens.reduce((sum, s) => sum + (parseInt(s.news_count) || 0), 0)
                });
            }
        } catch (error) {
            console.error('Erreur chargement écrans:', error);
        }
        setLoading(false);
    };

    if (loading) return <Loader />;

    return (
        <div id="sm-dashboard" className="sm-dashboard fade-in">
            <h1 id="sm-dashboard-title" className="sm-page-title text-3xl font-bold text-gray-800 mb-8">Dashboard</h1>

            {/* Stats Cards */}
            <div id="sm-dashboard-stats" className="sm-stats-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <Card id="sm-stat-total-screens" className="sm-stat-card">
                    <div className="sm-stat-content flex items-center gap-4">
                        <div className="sm-stat-icon w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i className="fas fa-tv text-2xl text-blue-600"></i>
                        </div>
                        <div className="sm-stat-data">
                            <p className="sm-stat-label text-gray-600 text-sm">Écrans totaux</p>
                            <p className="sm-stat-value text-2xl font-bold text-gray-800">{stats.total_screens}</p>
                        </div>
                    </div>
                </Card>

                <Card id="sm-stat-active-screens" className="sm-stat-card">
                    <div className="sm-stat-content flex items-center gap-4">
                        <div className="sm-stat-icon w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i className="fas fa-check-circle text-2xl text-green-600"></i>
                        </div>
                        <div className="sm-stat-data">
                            <p className="sm-stat-label text-gray-600 text-sm">Écrans actifs</p>
                            <p className="sm-stat-value text-2xl font-bold text-gray-800">{stats.active_screens}</p>
                        </div>
                    </div>
                </Card>

                <Card id="sm-stat-ads" className="sm-stat-card">
                    <div className="sm-stat-content flex items-center gap-4">
                        <div className="sm-stat-icon w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i className="fas fa-image text-2xl text-purple-600"></i>
                        </div>
                        <div className="sm-stat-data">
                            <p className="sm-stat-label text-gray-600 text-sm">Publicités</p>
                            <p className="sm-stat-value text-2xl font-bold text-gray-800">{stats.total_ads}</p>
                        </div>
                    </div>
                </Card>

                <Card id="sm-stat-news" className="sm-stat-card">
                    <div className="sm-stat-content flex items-center gap-4">
                        <div className="sm-stat-icon w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <i className="fas fa-exclamation-triangle text-2xl text-red-600"></i>
                        </div>
                        <div className="sm-stat-data">
                            <p className="sm-stat-label text-gray-600 text-sm">Alertes actives</p>
                            <p className="sm-stat-value text-2xl font-bold text-gray-800">{stats.total_news}</p>
                        </div>
                    </div>
                </Card>
            </div>

            {/* Liste des écrans */}
            <Card id="sm-dashboard-screens-list" title="Mes écrans">
                {screens.length === 0 ? (
                    <EmptyState
                        id="sm-dashboard-empty"
                        icon="fa-tv"
                        title="Aucun écran"
                        message="Créez votre premier écran pour commencer"
                    />
                ) : (
                    <div className="sm-screens-list space-y-4">
                        {screens.map(screen => (
                            <div key={screen.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all">
                                <div className="flex items-center gap-4">
                                    <div className="w-12 h-12 bg-gradient-to-br from-orange-500 to-red-600 rounded-lg flex items-center justify-center text-white text-xl">
                                        <i className="fas fa-tv"></i>
                                    </div>
                                    <div>
                                        <h3 className="font-semibold text-gray-800">{screen.label}</h3>
                                        <p className="text-sm text-gray-600">
                                            {screen.location_city} • {screen.address}
                                        </p>
                                    </div>
                                </div>
                                <div className="flex items-center gap-3">
                                    <span className={screen.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                        {screen.is_active == 1 ? 'Actif' : 'Inactif'}
                                    </span>
                                    <div className="text-sm text-gray-600">
                                        <div><i className="fas fa-image mr-1"></i> {screen.ads_count || 0} pub(s)</div>
                                        <div><i className="fas fa-bell mr-1"></i> {screen.news_count || 0} alerte(s)</div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </Card>
        </div>
    );
};

// ============================================================================
// SCREENS VIEW
// ============================================================================

const ScreensView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [screens, setScreens] = useState([]);
    const [configurations, setConfigurations] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
    const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false);
    const [editingScreen, setEditingScreen] = useState(null);
    const [viewingScreen, setViewingScreen] = useState(null);
    const [previewUrl, setPreviewUrl] = useState('');

    // Fermer la modal de preview avec la touche Échap
    useEffect(() => {
        const handleEscape = (e) => {
            if (e.key === 'Escape' && isPreviewModalOpen) {
                setIsPreviewModalOpen(false);
            }
        };
        window.addEventListener('keydown', handleEscape);
        return () => window.removeEventListener('keydown', handleEscape);
    }, [isPreviewModalOpen]);
    

    // Form state
    const [formLabel, setFormLabel] = useState('');
    const [formCity, setFormCity] = useState('Genève');
    const [formAddress, setFormAddress] = useState('');
    const [formLatitude, setFormLatitude] = useState(null);
    const [formLongitude, setFormLongitude] = useState(null);
    const [formBusStop, setFormBusStop] = useState('');
    const [formBusCode, setFormBusCode] = useState('');
    const [formActive, setFormActive] = useState(true);
    const [formConfigurationId, setFormConfigurationId] = useState(null);
    const [formConciergeId, setFormConciergeId] = useState(null);
    
    // Liste des concierges
    const [concierges, setConcierges] = useState([]);

    useEffect(() => {
        loadScreens();
        loadConfigurations();
        loadConcierges();
    }, []);

    const loadScreens = async () => {
        setLoading(true);
        try {
            const result = await api.getScreens(customer.id);
            if (result.screens) {
                setScreens(result.screens);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations) {
                setConfigurations(result.configurations);
            }
        } catch (error) {
            console.error('Erreur lors du chargement des configurations');
        }
    };

    const loadConcierges = async () => {
        try {
            const result = await api.getConcierges(customer.id);
            if (result.concierges) {
                setConcierges(result.concierges);
            }
        } catch (error) {
            console.error('Erreur lors du chargement des concierges');
        }
    };

    const openModal = (screen = null) => {
        if (screen) {
            setEditingScreen(screen);
            setFormLabel(screen.label);
            setFormCity(screen.location_city);
            setFormAddress(screen.address);
            setFormLatitude(screen.latitude || null);
            setFormLongitude(screen.longitude || null);
            setFormBusStop(screen.bus_stop_name || '');
            setFormBusCode(screen.bus_stop_code || '');
            setFormActive(screen.is_active == 1);
            setFormConfigurationId(screen.configuration_id ? parseInt(screen.configuration_id) : null);
            setFormConciergeId(screen.concierge_id ? parseInt(screen.concierge_id) : null);
        } else {
            setEditingScreen(null);
            setFormLabel('');
            setFormCity('Genève');
            setFormAddress('');
            setFormLatitude(null);
            setFormLongitude(null);
            setFormBusStop('');
            setFormBusCode('');
            setFormActive(true);
            setFormConfigurationId(configurations.length > 0 ? configurations[0].id : null);
            setFormConciergeId(null);
        }
        setIsModalOpen(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        const data = {
            customer_id: customer.id,
            label: formLabel,
            location_city: formCity,
            address: formAddress,
            latitude: formLatitude,
            longitude: formLongitude,
            bus_stop_name: formBusStop,
            bus_stop_code: formBusCode,
            is_active: formActive ? 1 : 0,
            configuration_id: formConfigurationId,
            concierge_id: formConciergeId
        };

        try {
            if (editingScreen) {
                data.screen_id = editingScreen.id;
                const result = await api.updateScreen(data);
                if (result.success) {
                    toast.success('Écran modifié avec succès');
                }
            } else {
                const result = await api.createScreen(data);
                if (result.success) {
                    toast.success('Écran créé avec succès');
                    toast.info(`Code écran : ${result.screen_code}`);
                }
            }

            loadScreens();
            setIsModalOpen(false);
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const openDetailModal = (screen) => {
        setViewingScreen(screen);
        setIsDetailModalOpen(true);
    };

    const closeDetailModal = () => {
        setIsDetailModalOpen(false);
        setViewingScreen(null);
    };

    const handleDelete = async (screenId) => {
        if (!confirm('Êtes-vous sûr de vouloir supprimer cet écran ?')) return;

        try {
            const result = await api.deleteScreen(screenId);
            if (result.success) {
                toast.success('Écran supprimé');
                loadScreens();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    const handlePreview = (screen) => {
        // Détecter si on est en local ou en production
        const isLocal = window.location.hostname === 'localhost' || 
                       window.location.hostname === '127.0.0.1' ||
                       window.location.hostname.includes('local');
        
        // Construire l'URL de base (HTTPS partout car le serveur local utilise SSL)
        const baseUrl = isLocal 
            ? 'https://local.smarthall.screen:8890'
            : 'https://screen.smarthall.ch';
        
        // Utiliser md5_id ou screen_code en fallback
        const identifier = screen.md5_id || screen.screen_code;
        
        // Construire l'URL complète
        const url = `${baseUrl}/?md5=${identifier}`;
        
        // Ouvrir dans une modal avec iframe
        setPreviewUrl(url);
        setIsPreviewModalOpen(true);
        
        toast.info(`Chargement de la prévisualisation...`);
    };

    if (loading) return <Loader />;

    return (
        <div id="sm-screens-view" className="sm-screens-view fade-in">
            <div className="sm-view-header flex items-center justify-between mb-8">
                <h1 id="sm-screens-title" className="sm-page-title text-3xl font-bold text-gray-800">Mes Écrans</h1>
                <Button 
                    id="sm-btn-new-screen"
                    onClick={() => openModal()} 
                    icon="fa-plus"
                >
                    Nouvel écran
                </Button>
            </div>

            {screens.length === 0 ? (
                <Card id="sm-screens-empty-card">
                    <EmptyState
                        id="sm-screens-empty"
                        icon="fa-tv"
                        title="Aucun écran"
                        message="Créez votre premier écran pour commencer à gérer votre affichage dynamique"
                        action={
                            <Button 
                                id="sm-btn-create-first-screen"
                                onClick={() => openModal()} 
                                icon="fa-plus"
                            >
                                Créer un écran
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div id="sm-screens-list" className="sm-screens-list bg-white rounded-lg border border-gray-200 overflow-hidden">
                    {/* En-tête du tableau */}
                    <div className="bg-gray-50 border-b border-gray-200 px-6 py-3 grid grid-cols-12 gap-4 items-center font-semibold text-gray-700 text-sm">
                        <div className="col-span-3">Écran</div>
                        <div className="col-span-2">Localisation</div>
                        <div className="col-span-2">Configuration</div>
                        <div className="col-span-2">Statistiques</div>
                        <div className="col-span-1">Statut</div>
                        <div className="col-span-2 text-right">Actions</div>
                    </div>
                    
                    {/* Lignes du tableau */}
                    {screens.map(screen => (
                        <div 
                            key={screen.id}
                            id={`sm-screen-row-${screen.id}`}
                            className="border-b border-gray-100 px-6 py-4 grid grid-cols-12 gap-4 items-center hover:bg-gray-50 transition-all"
                        >
                            {/* Nom de l'écran */}
                            <div className="col-span-3 flex items-center gap-3">
                                <div className="w-10 h-10 bg-gradient-to-br from-orange-500 to-red-600 rounded-lg flex items-center justify-center text-white flex-shrink-0">
                                    <i className="fas fa-tv"></i>
                                </div>
                                <div className="min-w-0">
                                    <h3 className="font-semibold text-gray-800 truncate">{screen.label}</h3>
                                    <div className="flex items-center gap-2 text-xs">
                                        <span className="text-gray-500 font-mono truncate" title="Code écran">{screen.screen_code}</span>
                                        {screen.md5_id && (
                                            <>
                                                <span className="text-gray-400">•</span>
                                                <span className="text-orange-600 font-mono truncate" title="ID unique MD5">
                                                    <i className="fas fa-fingerprint mr-1"></i>
                                                    {screen.md5_id.substring(0, 8)}...
                                                </span>
                                            </>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Localisation */}
                            <div className="col-span-2 text-sm text-gray-600">
                                <div className="font-medium">{screen.location_city}</div>
                                <div className="text-xs text-gray-500 truncate">{screen.address}</div>
                            </div>

                            {/* Configuration */}
                            <div className="col-span-2 text-sm">
                                {screen.configuration_name ? (
                                    <div className="flex items-center gap-1 text-orange-600">
                                        <i className="fas fa-cog"></i>
                                        <span className="truncate">{screen.configuration_name}</span>
                                    </div>
                                ) : (
                                    <span className="text-gray-400 italic">Aucune</span>
                                )}
                            </div>

                            {/* Statistiques */}
                            <div className="col-span-2 flex items-center gap-2 text-xs">
                                <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded">
                                    <i className="fas fa-image mr-1"></i>{screen.ads_count || 0}
                                </span>
                                <span className="px-2 py-1 bg-red-100 text-red-700 rounded">
                                    <i className="fas fa-bell mr-1"></i>{screen.news_count || 0}
                                </span>
                            </div>

                            {/* Statut */}
                            <div className="col-span-1">
                                <span className={screen.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                    {screen.is_active == 1 ? 'Actif' : 'Inactif'}
                                </span>
                            </div>

                            {/* Actions */}
                            <div className="col-span-2 flex items-center justify-end gap-2">
                                <button
                                    onClick={() => openDetailModal(screen)}
                                    className="px-3 py-1.5 bg-purple-500 text-white text-sm rounded hover:bg-purple-600 transition-all"
                                    title="Voir détail et contenu"
                                >
                                    <i className="fas fa-list"></i>
                                </button>
                                <button
                                    onClick={() => handlePreview(screen)}
                                    className="px-3 py-1.5 bg-green-500 text-white text-sm rounded hover:bg-green-600 transition-all"
                                    title="Prévisualiser l'écran"
                                >
                                    <i className="fas fa-eye"></i>
                                </button>
                                <button
                                    onClick={() => openModal(screen)}
                                    className="px-3 py-1.5 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-all"
                                    title="Modifier"
                                >
                                    <i className="fas fa-edit"></i>
                                </button>
                                <button
                                    onClick={() => handleDelete(screen.id)}
                                    className="px-3 py-1.5 bg-red-500 text-white text-sm rounded hover:bg-red-600 transition-all"
                                    title="Supprimer"
                                >
                                    <i className="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Modal Créer/Modifier */}
            <Modal
                id="sm-screen-modal"
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingScreen ? 'Modifier l\'écran' : 'Nouvel écran'}
            >
                <form id="sm-screen-form" className="sm-screen-form" onSubmit={handleSubmit}>
                    <Input
                        label="Nom de l'écran"
                        value={formLabel}
                        onChange={setFormLabel}
                        placeholder="Hall Principal"
                        required
                        icon="fa-tv"
                    />

                    {/* Composant de recherche de ville pour la météo */}
                    <CityAutocomplete
                        id="sm-screen-weather-city"
                        label="Météo"
                        value={formCity}
                        onChange={setFormCity}
                        placeholder="Genève, Lausanne, Zurich..."
                        required
                    />

                    {/* Composant de recherche d'adresse avec Maps API */}
                    <AddressAutocomplete
                        label="Adresse complète"
                        value={formAddress}
                        placeholder="Pl. de Saint-Gervais 1, 1201 Genève"
                        required
                        onAddressSelected={(data) => {
                            console.log('🎯 [ScreensView] Adresse sélectionnée:', data);
                            setFormAddress(data.address);
                            setFormLatitude(data.latitude);
                            setFormLongitude(data.longitude);
                            console.log('🎯 [ScreensView] Coordonnées GPS:', {
                                latitude: data.latitude,
                                longitude: data.longitude
                            });
                        }}
                    />

                    {/* Composant de recherche TPG avec auto-complétion */}
                    <TPGStopSearch
                        label="Arrêt de bus le plus proche"
                        value={formBusStop}
                        placeholder="Rechercher un arrêt TPG (ex: Bel-Air, Cornavin)..."
                        onStopSelected={(stop) => {
                            console.log('🎯 [ScreensView] onStopSelected appelé avec:', stop);
                            console.log('🎯 [ScreensView] Avant - formBusStop:', formBusStop);
                            console.log('🎯 [ScreensView] Avant - formBusCode:', formBusCode);
                            setFormBusStop(stop.nom);
                            setFormBusCode(stop.code);
                            console.log('🎯 [ScreensView] Après - formBusStop:', stop.nom);
                            console.log('🎯 [ScreensView] Après - formBusCode:', stop.code);
                        }}
                    />

                    {/* Sélecteur de configuration */}
                    <div className="mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            <i className="fas fa-cog mr-2"></i>
                            Configuration
                        </label>
                        {configurations.length > 0 ? (
                            <>
                                <select
                                    value={formConfigurationId || ''}
                                    onChange={(e) => setFormConfigurationId(e.target.value ? parseInt(e.target.value) : null)}
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                                >
                                    <option value="">Aucune configuration (manuel)</option>
                                    {configurations.map(config => (
                                        <option key={config.id} value={config.id}>
                                            {config.name} ({config.screens_count || 0} écran(s))
                                        </option>
                                    ))}
                                </select>
                                <p className="text-sm text-gray-600 mt-1">
                                    <i className="fas fa-info-circle mr-1"></i>
                                    La configuration définit le contenu affiché sur cet écran
                                </p>
                            </>
                        ) : (
                            <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-800">
                                <i className="fas fa-exclamation-triangle mr-2"></i>
                                Aucune configuration disponible. Créez-en une dans le menu "Configurations".
                            </div>
                        )}
                    </div>

                    <div className="mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            <i className="fas fa-concierge-bell mr-2"></i>
                            Concierge
                        </label>
                        <select
                            value={formConciergeId || ''}
                            onChange={(e) => setFormConciergeId(e.target.value ? parseInt(e.target.value) : null)}
                            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                        >
                            <option value="">Aucun concierge</option>
                            {concierges.filter(c => c.is_active == 1).map(concierge => (
                                <option key={concierge.id} value={concierge.id}>
                                    {concierge.name} - {concierge.phone}
                                </option>
                            ))}
                        </select>
                        <p className="text-sm text-gray-600 mt-1">
                            <i className="fas fa-info-circle mr-1"></i>
                            Les informations du concierge seront affichées sur l'écran
                        </p>
                    </div>

                    <div className="mb-4">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={formActive}
                                onChange={(e) => setFormActive(e.target.checked)}
                                className="w-5 h-5 text-orange-500"
                            />
                            <span className="text-gray-700 font-medium">Écran actif</span>
                        </label>
                    </div>

                    <div className="flex gap-3">
                        <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)} className="flex-1">
                            Annuler
                        </Button>
                        <Button variant="primary" className="flex-1">
                            {editingScreen ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>

            {/* Modal de détail simplifiée */}
            <Modal
                isOpen={isDetailModalOpen}
                onClose={closeDetailModal}
                title={`Détail - ${viewingScreen?.label || ''}`}
                size="md"
            >
                {viewingScreen && (
                    <div className="space-y-4">
                        {/* Nom de l'écran */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-tv mr-2"></i>Nom de l'écran
                            </label>
                            <div className="text-lg font-semibold text-gray-900">
                                {viewingScreen.label}
                            </div>
                        </div>

                        {/* Météo */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-cloud-sun mr-2"></i>Météo
                            </label>
                            <div className="text-gray-900">
                                {viewingScreen.location_city || 'Non définie'}
                            </div>
                        </div>

                        {/* Adresse complète */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-map-marker-alt mr-2"></i>Adresse complète
                            </label>
                            <div className="text-gray-900">
                                {viewingScreen.address || 'Non définie'}
                            </div>
                            {(viewingScreen.latitude && viewingScreen.longitude) && (
                                <div className="text-xs text-gray-500 mt-1">
                                    Coordonnées GPS: {viewingScreen.latitude}, {viewingScreen.longitude}
                                </div>
                            )}
                        </div>

                        {/* Arrêt de bus */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-bus mr-2"></i>Arrêt de bus le plus proche
                            </label>
                            <div className="text-gray-900">
                                {viewingScreen.bus_stop_name || 'Non défini'}
                            </div>
                            {viewingScreen.bus_stop_code && (
                                <div className="text-xs text-gray-500 mt-1">
                                    Code: {viewingScreen.bus_stop_code}
                                </div>
                            )}
                        </div>

                        {/* Configuration */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-cog mr-2"></i>Configuration
                            </label>
                            <div className="text-gray-900">
                                {viewingScreen.configuration_id ? (
                                    configurations.find(c => c.id == viewingScreen.configuration_id)?.name || 'Configuration inconnue'
                                ) : (
                                    <span className="text-gray-500 italic">Aucune configuration (manuel)</span>
                                )}
                            </div>
                        </div>

                        {/* Concierge */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-concierge-bell mr-2"></i>Concierge
                            </label>
                            <div className="text-gray-900">
                                {viewingScreen.concierge_id ? (
                                    concierges.find(c => c.id == viewingScreen.concierge_id)?.name || 'Concierge inconnu'
                                ) : (
                                    <span className="text-gray-500 italic">Aucun concierge</span>
                                )}
                            </div>
                            {viewingScreen.concierge_id && concierges.find(c => c.id == viewingScreen.concierge_id)?.phone && (
                                <div className="text-xs text-gray-500 mt-1">
                                    Tél: {concierges.find(c => c.id == viewingScreen.concierge_id)?.phone}
                                </div>
                            )}
                        </div>

                        {/* Statut */}
                        <div className="bg-gray-50 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-gray-600 mb-1">
                                <i className="fas fa-power-off mr-2"></i>Statut
                            </label>
                            <div>
                                <span className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${
                                    viewingScreen.is_active == 1 
                                        ? 'bg-green-100 text-green-700' 
                                        : 'bg-red-100 text-red-700'
                                }`}>
                                    {viewingScreen.is_active == 1 ? 'Actif' : 'Inactif'}
                                </span>
                            </div>
                        </div>

                        {/* Informations techniques */}
                        <div className="bg-blue-50 border border-blue-200 p-4 rounded-lg">
                            <label className="block text-sm font-medium text-blue-700 mb-2">
                                <i className="fas fa-info-circle mr-2"></i>Informations techniques
                            </label>
                            <div className="grid grid-cols-2 gap-3 text-sm">
                                <div>
                                    <span className="text-gray-600">ID:</span>
                                    <span className="ml-2 font-mono text-gray-900">{viewingScreen.id}</span>
                                </div>
                                <div>
                                    <span className="text-gray-600">Code:</span>
                                    <span className="ml-2 font-mono text-gray-900">{viewingScreen.screen_code}</span>
                                </div>
                                <div className="col-span-2">
                                    <span className="text-gray-600">API Key:</span>
                                    <span className="ml-2 font-mono text-xs text-gray-900">{viewingScreen.api_key}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </Modal>

            {/* Modal de Prévisualisation Écran - Plein écran avec Screenshot */}
            {isPreviewModalOpen && (
                <ScreenPreviewModal 
                    previewUrl={previewUrl}
                    onClose={() => setIsPreviewModalOpen(false)}
                />
            )}
        </div>
    );
};

// Suite dans views.jsx pour les autres vues...



