// ============================================================================
// ADVERTISINGS VIEW - VERSION AVEC CONFIGURATIONS
// ============================================================================

const AdvertisingsView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [configurations, setConfigurations] = useState([]);
    const [selectedConfig, setSelectedConfig] = useState(null);
    const [advertisings, setAdvertisings] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingAd, setEditingAd] = useState(null);
    const [uploading, setUploading] = useState(false);

    // Form state
    const [formTitle, setFormTitle] = useState('');
    const [formImageUrl, setFormImageUrl] = useState('');
    const [formDuration, setFormDuration] = useState(10000);
    const [formActive, setFormActive] = useState(true);
    const [preselectedScreenId, setPreselectedScreenId] = useState(null);
    const [formIsUnlimited, setFormIsUnlimited] = useState(true);
    const [formStartDate, setFormStartDate] = useState('');
    const [formEndDate, setFormEndDate] = useState('');

    useEffect(() => {
        loadConfigurations();
        
        // Vérifier si on doit ouvrir la modal d'ajout automatiquement
        const shouldOpenModal = localStorage.getItem('open_add_modal');
        const preselectedScreenId = localStorage.getItem('preselected_screen_id');
        
        if (shouldOpenModal === 'advertisings' && preselectedScreenId) {
            // Nettoyer le localStorage
            localStorage.removeItem('open_add_modal');
            localStorage.removeItem('preselected_screen_id');
            
            // Ouvrir la modal après un court délai
            setTimeout(() => {
                setPreselectedScreenId(parseInt(preselectedScreenId));
                openModal(null, parseInt(preselectedScreenId));
            }, 500);
        }
    }, []);

    useEffect(() => {
        if (selectedConfig) {
            loadAdvertisings();
        }
    }, [selectedConfig]);

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations && result.configurations.length > 0) {
                setConfigurations(result.configurations);
                setSelectedConfig(result.configurations[0].id);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const loadAdvertisings = async () => {
        try {
            // Charger les publicités de la configuration
            const result = await api.getAdvertisingsByConfig(selectedConfig);
            if (result.advertisings) {
                setAdvertisings(result.advertisings);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement des publicités');
        }
    };

    const handleFileUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (!file.type.startsWith('image/')) {
            toast.error('Seules les images sont acceptées');
            return;
        }

        setUploading(true);
        try {
            const result = await api.uploadFile(file);
            if (result.url) {
                setFormImageUrl(result.url);
                toast.success('Image uploadée avec succès');
            }
        } catch (error) {
            toast.error('Erreur lors de l\'upload');
        }
        setUploading(false);
    };

    const openModal = (ad = null, screenId = null) => {
        if (ad) {
            setEditingAd(ad);
            setFormTitle(ad.title || '');
            setFormImageUrl(ad.image_url);
            setFormDuration(ad.display_duration);
            setFormActive(ad.is_active == 1);
            
            // Gérer les dates
            const hasNoDates = !ad.start_date && !ad.end_date;
            setFormIsUnlimited(hasNoDates);
            setFormStartDate(ad.start_date || '');
            setFormEndDate(ad.end_date || '');
        } else {
            setEditingAd(null);
            setFormTitle('');
            setFormImageUrl('');
            setFormDuration(10000);
            setFormActive(true);
            setFormIsUnlimited(true);
            setFormStartDate('');
            setFormEndDate('');
        }
        if (screenId) {
            setPreselectedScreenId(screenId);
        }
        setIsModalOpen(true);
    };

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

        // Validation côté client
        if (!formImageUrl || formImageUrl.trim() === '') {
            toast.error('Veuillez uploader une image avant de créer la publicité');
            return;
        }

        const data = {
            customer_id: customer.id,
            title: formTitle,
            image_url: formImageUrl,
            display_duration: formDuration,
            is_active: formActive ? 1 : 0,
            start_date: formIsUnlimited ? null : formStartDate,
            end_date: formIsUnlimited ? null : formEndDate
        };
        
        // Utiliser screen_id OU configuration_id selon le cas
        if (preselectedScreenId) {
            data.screen_id = preselectedScreenId;
        } else {
            data.configuration_id = selectedConfig;
        }

        console.log('📤 Envoi des données:', data);

        try {
            if (editingAd) {
                data.id = editingAd.id;
                const result = await api.updateAdvertising(data);
                if (result.success) {
                    toast.success('Publicité modifiée');
                    loadAdvertisings();
                    setIsModalOpen(false);
                } else {
                    toast.error(result.error || 'Erreur lors de la modification');
                }
            } else {
                const result = await api.createAdvertising(data);
                if (result.success) {
                    toast.success('Publicité créée');
                    loadAdvertisings();
                    setIsModalOpen(false);
                } else {
                    toast.error(result.error || 'Erreur lors de la création');
                }
            }
        } catch (error) {
            console.error('❌ Erreur:', error);
            const errorMessage = error.message || error.error || 'Erreur lors de l\'enregistrement';
            toast.error(errorMessage);
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('Supprimer cette publicité ?')) return;

        try {
            const result = await api.deleteAdvertising(id);
            if (result.success) {
                toast.success('Publicité supprimée');
                loadAdvertisings();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    if (loading) return <Loader />;

    if (configurations.length === 0) {
        return (
            <Card>
                <EmptyState
                    icon="fa-cog"
                    title="Aucune configuration"
                    message="Créez d'abord une configuration dans le menu Configurations"
                    action={
                        <Button onClick={() => window.location.reload()} icon="fa-cog">
                            Aller aux Configurations
                        </Button>
                    }
                />
            </Card>
        );
    }

    const currentConfig = configurations.find(c => c.id === selectedConfig);

    return (
        <div className="fade-in">
            <div className="flex items-center justify-between mb-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800">Publicités</h1>
                    <p className="text-gray-600 mt-2">Gérez les publicités de vos configurations</p>
                </div>
                <Button onClick={() => openModal()} icon="fa-plus">
                    Nouvelle publicité
                </Button>
            </div>

            {/* Sélecteur de configuration */}
            <Card className="mb-6">
                <div className="flex items-center gap-4">
                    <label className="font-semibold text-gray-700">Configuration :</label>
                    <select
                        value={selectedConfig || ''}
                        onChange={(e) => setSelectedConfig(parseInt(e.target.value))}
                        className="px-4 py-2 border border-gray-300 rounded-lg flex-1"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </select>
                    {currentConfig && (
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                            <i className="fas fa-tv"></i>
                            <span>{currentConfig.screens_count} écran(s) utilisent cette configuration</span>
                        </div>
                    )}
                </div>
            </Card>

            {/* Liste des publicités */}
            {advertisings.length === 0 ? (
                <Card>
                    <EmptyState
                        icon="fa-image"
                        title="Aucune publicité"
                        message="Ajoutez votre première publicité à cette configuration"
                        action={
                            <Button onClick={() => openModal()} icon="fa-plus">
                                Ajouter une publicité
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div id="sm-ad-list" className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                    {/* Header */}
                    <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-2">Image</div>
                        <div className="col-span-2">Titre</div>
                        <div className="col-span-2">Durée</div>
                        <div className="col-span-2">Période</div>
                        <div className="col-span-2">Statut</div>
                        <div className="col-span-2 text-right">Actions</div>
                    </div>

                    {/* Lignes */}
                    {advertisings.map(ad => (
                        <div 
                            key={ad.id}
                            id={`sm-ad-row-${ad.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"
                        >
                            {/* Image */}
                            <div className="col-span-2">
                                <div className="w-24 h-16 rounded-lg overflow-hidden shadow-sm">
                                    <img 
                                        src={ad.image_url} 
                                        alt={ad.title || 'Publicité'}
                                        className="w-full h-full object-cover"
                                    />
                                </div>
                            </div>

                            {/* Titre */}
                            <div className="col-span-2">
                                <div className="text-sm text-gray-900 font-medium truncate">
                                    {ad.title || <span className="text-gray-400 italic">Sans titre</span>}
                                </div>
                            </div>

                            {/* Durée */}
                            <div className="col-span-2">
                                <div className="flex items-center gap-2 text-sm text-gray-600">
                                    <i className="fas fa-clock text-blue-500"></i>
                                    <span className="font-medium">{ad.display_duration / 1000}s</span>
                                </div>
                            </div>

                            {/* Période */}
                            <div className="col-span-2">
                                {ad.start_date && ad.end_date ? (
                                    <div className="text-xs text-gray-600">
                                        <div className="flex items-center gap-1 mb-1">
                                            <i className="fas fa-calendar-check text-green-500"></i>
                                            <span>{new Date(ad.start_date).toLocaleDateString('fr-FR')}</span>
                                        </div>
                                        <div className="flex items-center gap-1">
                                            <i className="fas fa-calendar-times text-red-500"></i>
                                            <span>{new Date(ad.end_date).toLocaleDateString('fr-FR')}</span>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="flex items-center gap-2 text-sm">
                                        <i className="fas fa-infinity text-purple-500"></i>
                                        <span className="text-purple-600 font-medium">Permanent</span>
                                    </div>
                                )}
                            </div>

                            {/* Statut */}
                            <div className="col-span-2">
                                <span className={ad.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                    {ad.is_active == 1 ? 'Active' : 'Inactive'}
                                </span>
                            </div>

                            {/* Actions */}
                            <div className="col-span-2 flex items-center justify-end gap-2">
                                <button
                                    onClick={() => openModal(ad)}
                                    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(ad.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-ad-modal"
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingAd ? 'Modifier la publicité' : 'Nouvelle publicité'}
            >
                <form id="sm-ad-form" className="sm-form" onSubmit={handleSubmit}>
                    <Input
                        id="sm-ad-input-title"
                        label="Titre (optionnel)"
                        value={formTitle}
                        onChange={setFormTitle}
                        placeholder="Titre de la publicité"
                        icon="fa-heading"
                    />

                    {/* Upload zone */}
                    <div id="sm-ad-upload-group" className="sm-form-group mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            Image <span className="text-red-500">*</span>
                        </label>
                        <div 
                            id="sm-ad-upload-zone"
                            className="sm-upload-zone upload-zone p-6 text-center cursor-pointer" 
                            onClick={() => document.getElementById('sm-ad-file-input').click()}
                        >
                            {formImageUrl ? (
                                <div id="sm-ad-preview-container" className="sm-upload-preview">
                                    <img 
                                        id="sm-ad-preview-image"
                                        src={formImageUrl} 
                                        alt="Preview" 
                                        className="max-h-48 mx-auto mb-2 rounded-lg" 
                                    />
                                    <p className="text-sm text-green-600">
                                        <i className="fas fa-check-circle mr-1"></i>
                                        Image uploadée
                                    </p>
                                </div>
                            ) : (
                                <div id="sm-ad-upload-placeholder">
                                    <i className="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                                    <p className="text-gray-600">Cliquez pour uploader une image</p>
                                    <p className="text-xs text-gray-400 mt-1">JPG, PNG (max 5MB)</p>
                                </div>
                            )}
                            {uploading && (
                                <p id="sm-ad-upload-progress" className="text-sm text-orange-500 mt-2">
                                    Upload en cours...
                                </p>
                            )}
                        </div>
                        <input
                            id="sm-ad-file-input"
                            type="file"
                            accept="image/*"
                            onChange={handleFileUpload}
                            className="hidden"
                        />
                    </div>

                    <Input
                        id="sm-ad-input-duration"
                        label="Durée d'affichage (ms)"
                        type="number"
                        value={formDuration}
                        onChange={(val) => setFormDuration(parseInt(val))}
                        placeholder="10000"
                        required
                        icon="fa-clock"
                    />

                    {/* Période d'affichage */}
                    <div className="mb-4">
                        <label className="block text-gray-700 font-medium mb-3">
                            <i className="fas fa-calendar-alt mr-2"></i>
                            Période d'affichage
                        </label>
                        
                        <div className="space-y-3">
                            <label className="flex items-center gap-2 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
                                <input
                                    type="radio"
                                    name="displayPeriod"
                                    checked={formIsUnlimited}
                                    onChange={() => setFormIsUnlimited(true)}
                                    className="w-4 h-4"
                                />
                                <div>
                                    <div className="font-medium text-gray-800">Affichage permanent</div>
                                    <div className="text-sm text-gray-600">La publicité sera affichée en continu</div>
                                </div>
                            </label>
                            
                            <label className="flex items-center gap-2 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
                                <input
                                    type="radio"
                                    name="displayPeriod"
                                    checked={!formIsUnlimited}
                                    onChange={() => setFormIsUnlimited(false)}
                                    className="w-4 h-4"
                                />
                                <div className="flex-1">
                                    <div className="font-medium text-gray-800">Période personnalisée</div>
                                    <div className="text-sm text-gray-600 mb-3">Définir des dates de début et de fin</div>
                                    
                                    {!formIsUnlimited && (
                                        <div className="space-y-3 mt-3 ml-6">
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    Date de début
                                                </label>
                                                <input
                                                    id="sm-ad-input-start-date"
                                                    type="datetime-local"
                                                    value={formStartDate}
                                                    onChange={(e) => setFormStartDate(e.target.value)}
                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                                                    required={!formIsUnlimited}
                                                />
                                            </div>
                                            
                                            <div>
                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                    Date de fin
                                                </label>
                                                <input
                                                    id="sm-ad-input-end-date"
                                                    type="datetime-local"
                                                    value={formEndDate}
                                                    onChange={(e) => setFormEndDate(e.target.value)}
                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                                                    required={!formIsUnlimited}
                                                />
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </label>
                        </div>
                    </div>

                    <div id="sm-ad-checkbox-group" className="sm-form-group mb-4">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                id="sm-ad-checkbox-active"
                                type="checkbox"
                                checked={formActive}
                                onChange={(e) => setFormActive(e.target.checked)}
                                className="w-5 h-5"
                            />
                            <span className="text-gray-700 font-medium">Publicité active</span>
                        </label>
                    </div>

                    <div id="sm-ad-actions" className="sm-modal-actions flex gap-3">
                        <Button 
                            id="sm-ad-btn-cancel"
                            type="button" 
                            variant="secondary" 
                            onClick={() => setIsModalOpen(false)} 
                            className="flex-1"
                        >
                            Annuler
                        </Button>
                        <Button 
                            id="sm-ad-btn-save"
                            variant="primary" 
                            className="flex-1" 
                            disabled={!formImageUrl || uploading}
                        >
                            {editingAd ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

// ============================================================================
// NEWS VIEW - VERSION AVEC CONFIGURATIONS
// ============================================================================

const NewsView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [configurations, setConfigurations] = useState([]);
    const [selectedConfig, setSelectedConfig] = useState(null);
    const [news, setNews] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingNews, setEditingNews] = useState(null);

    // Form state
    const [formTitle, setFormTitle] = useState('');
    const [formSubtitle, setFormSubtitle] = useState('');
    const [formTime, setFormTime] = useState('');
    const [formTags, setFormTags] = useState('');
    const [formColor, setFormColor] = useState('red');
    const [formPriority, setFormPriority] = useState('medium');
    const [formActive, setFormActive] = useState(true);

    const colorSchemes = [
        { value: 'red', label: 'Rouge', from: '#f43f5e', to: '#dc2626' },
        { value: 'purple', label: 'Violet', from: '#a855f7', to: '#7c3aed' },
        { value: 'blue', label: 'Bleu', from: '#3b82f6', to: '#1d4ed8' },
        { value: 'green', label: 'Vert', from: '#10b981', to: '#059669' },
        { value: 'orange', label: 'Orange', from: '#f97316', to: '#ea580c' },
        { value: 'yellow', label: 'Jaune', from: '#eab308', to: '#ca8a04' },
        { value: 'pink-pastel', label: 'Rose pastel', from: '#fbcfe8', to: '#f9a8d4' },
        { value: 'lavender-pastel', label: 'Lavande pastel', from: '#e9d5ff', to: '#d8b4fe' },
        { value: 'sky-pastel', label: 'Ciel pastel', from: '#bae6fd', to: '#7dd3fc' },
        { value: 'mint-pastel', label: 'Menthe pastel', from: '#a7f3d0', to: '#6ee7b7' },
        { value: 'peach-pastel', label: 'Pêche pastel', from: '#fed7aa', to: '#fdba74' },
        { value: 'lemon-pastel', label: 'Citron pastel', from: '#fef08a', to: '#fde047' }
    ];

    useEffect(() => {
        loadConfigurations();
        
        // Vérifier si on doit ouvrir la modal d'ajout automatiquement
        const shouldOpenModal = localStorage.getItem('open_add_modal');
        const preselectedScreenId = localStorage.getItem('preselected_screen_id');
        
        if (shouldOpenModal === 'news' && preselectedScreenId) {
            // Nettoyer le localStorage
            localStorage.removeItem('open_add_modal');
            localStorage.removeItem('preselected_screen_id');
            
            // Ouvrir la modal après un court délai
            setTimeout(() => {
                openModal(null, parseInt(preselectedScreenId));
            }, 500);
        }
    }, []);

    useEffect(() => {
        if (selectedConfig) {
            loadNews();
        }
    }, [selectedConfig]);

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations && result.configurations.length > 0) {
                setConfigurations(result.configurations);
                setSelectedConfig(result.configurations[0].id);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const loadNews = async () => {
        try {
            const result = await api.getNewsByConfig(selectedConfig);
            if (result.news) {
                setNews(result.news);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement des alertes');
        }
    };

    const openModal = (newsItem = null) => {
        if (newsItem) {
            setEditingNews(newsItem);
            setFormTitle(newsItem.title);
            setFormSubtitle(newsItem.subtitle || '');
            setFormTime(newsItem.time_info || '');
            setFormTags(newsItem.tags ? newsItem.tags.join(', ') : '');
            setFormColor(newsItem.color_scheme);
            setFormPriority(newsItem.priority);
            setFormActive(newsItem.is_active == 1);
        } else {
            setEditingNews(null);
            setFormTitle('');
            setFormSubtitle('');
            setFormTime('');
            setFormTags('');
            setFormColor('red');
            setFormPriority('medium');
            setFormActive(true);
        }
        setIsModalOpen(true);
    };

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

        const tags = formTags.split(',').map(t => t.trim()).filter(t => t);

        const data = {
            configuration_id: selectedConfig,
            customer_id: customer.id,
            title: formTitle,
            subtitle: formSubtitle,
            time_info: formTime,
            tags: tags,
            color_scheme: formColor,
            priority: formPriority,
            is_active: formActive ? 1 : 0
        };

        try {
            if (editingNews) {
                data.id = editingNews.id;
                const result = await api.updateNews(data);
                if (result.success) {
                    toast.success('Alerte modifiée');
                    loadNews();
                    setIsModalOpen(false);
                }
            } else {
                const result = await api.createNews(data);
                if (result.success) {
                    toast.success('Alerte créée');
                    loadNews();
                    setIsModalOpen(false);
                }
            }
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('Supprimer cette alerte ?')) return;

        try {
            const result = await api.deleteNews(id);
            if (result.success) {
                toast.success('Alerte supprimée');
                loadNews();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    if (loading) return <Loader />;

    if (configurations.length === 0) {
        return (
            <Card>
                <EmptyState
                    icon="fa-cog"
                    title="Aucune configuration"
                    message="Créez d'abord une configuration dans le menu Configurations"
                />
            </Card>
        );
    }

    const currentConfig = configurations.find(c => c.id === selectedConfig);

    return (
        <div className="fade-in">
            <div className="flex items-center justify-between mb-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800">Alertes & News</h1>
                    <p className="text-gray-600 mt-2">Gérez les alertes importantes de vos configurations</p>
                </div>
                <Button onClick={() => openModal()} icon="fa-plus">
                    Nouvelle alerte
                </Button>
            </div>

            {/* Sélecteur de configuration */}
            <Card className="mb-6">
                <div className="flex items-center gap-4">
                    <label className="font-semibold text-gray-700">Configuration :</label>
                    <select
                        value={selectedConfig || ''}
                        onChange={(e) => setSelectedConfig(parseInt(e.target.value))}
                        className="px-4 py-2 border border-gray-300 rounded-lg flex-1"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </select>
                    {currentConfig && (
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                            <i className="fas fa-tv"></i>
                            <span>{currentConfig.screens_count} écran(s) utilisent cette configuration</span>
                        </div>
                    )}
                </div>
            </Card>

            {/* Liste des alertes */}
            {news.length === 0 ? (
                <Card>
                    <EmptyState
                        icon="fa-exclamation-triangle"
                        title="Aucune alerte"
                        message="Ajoutez votre première alerte à cette configuration"
                        action={
                            <Button onClick={() => openModal()} icon="fa-plus">
                                Ajouter une alerte
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div className="space-y-4">
                    {news.map(item => {
                        const colorScheme = colorSchemes.find(c => c.value === item.color_scheme) || colorSchemes[0];
                        return (
                            <Card key={item.id} className="overflow-hidden">
                                <div
                                    className="p-6 text-white rounded-lg mb-4"
                                    style={{
                                        background: `linear-gradient(135deg, ${colorScheme.from}, ${colorScheme.to})`
                                    }}
                                >
                                    <h3 className="text-2xl font-bold mb-2">{item.title}</h3>
                                    {item.subtitle && <p className="text-lg mb-1">{item.subtitle}</p>}
                                    {item.time_info && <p className="text-lg">{item.time_info}</p>}
                                    {item.tags && item.tags.length > 0 && (
                                        <div className="flex gap-2 mt-4">
                                            {item.tags.map((tag, i) => (
                                                <span key={i} className="px-3 py-1 bg-white/20 rounded-full text-sm">
                                                    {tag}
                                                </span>
                                            ))}
                                        </div>
                                    )}
                                </div>

                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <span className={item.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                            {item.is_active == 1 ? 'Active' : 'Inactive'}
                                        </span>
                                        <span className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm">
                                            Priorité: {item.priority}
                                        </span>
                                    </div>

                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => openModal(item)}
                                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all"
                                        >
                                            <i className="fas fa-edit mr-2"></i>Modifier
                                        </button>
                                        <button
                                            onClick={() => handleDelete(item.id)}
                                            className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-all"
                                        >
                                            <i className="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </Card>
                        );
                    })}
                </div>
            )}

            {/* Modal Créer/Modifier */}
            <Modal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingNews ? 'Modifier l\'alerte' : 'Nouvelle alerte'}
                size="lg"
            >
                <form onSubmit={handleSubmit}>
                    <Input
                        label="Titre"
                        value={formTitle}
                        onChange={setFormTitle}
                        placeholder="COUPURE DE GAZ"
                        required
                        icon="fa-heading"
                    />

                    <Input
                        label="Sous-titre"
                        value={formSubtitle}
                        onChange={setFormSubtitle}
                        placeholder="1er novembre 2025"
                        icon="fa-align-left"
                    />

                    <Input
                        label="Horaire"
                        value={formTime}
                        onChange={setFormTime}
                        placeholder="09h–13h"
                        icon="fa-clock"
                    />

                    <Input
                        label="Tags (séparés par des virgules)"
                        value={formTags}
                        onChange={setFormTags}
                        placeholder="Travaux, Sécurité, Avis"
                        icon="fa-tags"
                    />

                    <div className="mb-4">
                        <label className="block text-gray-700 font-medium mb-2">
                            <i className="fas fa-palette mr-2"></i>
                            Couleur
                            <span className="text-red-500 ml-1">*</span>
                        </label>
                        <div className="flex items-center gap-3">
                            <select
                                value={formColor}
                                onChange={(e) => setFormColor(e.target.value)}
                                required
                                className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                            >
                                {colorSchemes.map(color => (
                                    <option key={color.value} value={color.value}>
                                        {color.label}
                                    </option>
                                ))}
                            </select>
                            {/* Aperçu de la couleur */}
                            <div 
                                className="w-12 h-12 rounded-lg border-2 border-gray-300 shadow-sm"
                                style={{ 
                                    background: `linear-gradient(135deg, ${colorSchemes.find(c => c.value === formColor)?.from}, ${colorSchemes.find(c => c.value === formColor)?.to})`
                                }}
                                title="Aperçu de la couleur"
                            ></div>
                        </div>
                    </div>

                    <Select
                        label="Configuration"
                        value={selectedConfig || ''}
                        onChange={(val) => setSelectedConfig(parseInt(val))}
                        required
                        icon="fa-cog"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </Select>

                    <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"
                            />
                            <span className="text-gray-700 font-medium">Alerte active</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">
                            {editingNews ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

// ============================================================================
// SLIDERS VIEW - VERSION AVEC CONFIGURATIONS
// ============================================================================

const SlidersView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [configurations, setConfigurations] = useState([]);
    const [selectedConfig, setSelectedConfig] = useState(null);
    const [sliders, setSliders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingSlider, setEditingSlider] = useState(null);

    // Form state
    const [formMessage, setFormMessage] = useState('');
    const [formIcon, setFormIcon] = useState('');
    const [formDuration, setFormDuration] = useState(10000);
    const [formActive, setFormActive] = useState(true);

    useEffect(() => {
        loadConfigurations();
        
        // Vérifier si on doit ouvrir la modal d'ajout automatiquement
        const shouldOpenModal = localStorage.getItem('open_add_modal');
        const preselectedScreenId = localStorage.getItem('preselected_screen_id');
        
        if (shouldOpenModal === 'sliders' && preselectedScreenId) {
            // Nettoyer le localStorage
            localStorage.removeItem('open_add_modal');
            localStorage.removeItem('preselected_screen_id');
            
            // Ouvrir la modal après un court délai
            setTimeout(() => {
                openModal(null, parseInt(preselectedScreenId));
            }, 500);
        }
    }, []);

    useEffect(() => {
        if (selectedConfig) {
            loadSliders();
        }
    }, [selectedConfig]);

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations && result.configurations.length > 0) {
                setConfigurations(result.configurations);
                setSelectedConfig(result.configurations[0].id);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const loadSliders = async () => {
        try {
            const result = await api.getSlidersByConfig(selectedConfig);
            if (result.sliders) {
                setSliders(result.sliders);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement des messages');
        }
    };

    const openModal = (slider = null) => {
        if (slider) {
            setEditingSlider(slider);
            setFormMessage(slider.message);
            setFormIcon(slider.icon || '');
            setFormDuration(slider.display_duration);
            setFormActive(slider.is_active == 1);
        } else {
            setEditingSlider(null);
            setFormMessage('');
            setFormIcon('');
            setFormDuration(10000);
            setFormActive(true);
        }
        setIsModalOpen(true);
    };

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

        const data = {
            configuration_id: selectedConfig,
            customer_id: customer.id,
            message: formMessage,
            icon: formIcon,
            display_duration: formDuration,
            is_active: formActive ? 1 : 0
        };

        try {
            if (editingSlider) {
                data.id = editingSlider.id;
                const result = await api.updateSlider(data);
                if (result.success) {
                    toast.success('Message modifié');
                    loadSliders();
                    setIsModalOpen(false);
                }
            } else {
                const result = await api.createSlider(data);
                if (result.success) {
                    toast.success('Message créé');
                    loadSliders();
                    setIsModalOpen(false);
                }
            }
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('Supprimer ce message ?')) return;

        try {
            const result = await api.deleteSlider(id);
            if (result.success) {
                toast.success('Message supprimé');
                loadSliders();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    if (loading) return <Loader />;

    if (configurations.length === 0) {
        return (
            <Card>
                <EmptyState
                    icon="fa-cog"
                    title="Aucune configuration"
                    message="Créez d'abord une configuration dans le menu Configurations"
                />
            </Card>
        );
    }

    const currentConfig = configurations.find(c => c.id === selectedConfig);

    return (
        <div className="fade-in">
            <div className="flex items-center justify-between mb-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800">Messages défilants</h1>
                    <p className="text-gray-600 mt-2">Gérez les messages du bandeau défilant</p>
                </div>
                <Button onClick={() => openModal()} icon="fa-plus">
                    Nouveau message
                </Button>
            </div>

            {/* Sélecteur de configuration */}
            <Card className="mb-6">
                <div className="flex items-center gap-4">
                    <label className="font-semibold text-gray-700">Configuration :</label>
                    <select
                        value={selectedConfig || ''}
                        onChange={(e) => setSelectedConfig(parseInt(e.target.value))}
                        className="px-4 py-2 border border-gray-300 rounded-lg flex-1"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </select>
                    {currentConfig && (
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                            <i className="fas fa-tv"></i>
                            <span>{currentConfig.screens_count} écran(s) utilisent cette configuration</span>
                        </div>
                    )}
                </div>
            </Card>

            {/* Liste des sliders */}
            {sliders.length === 0 ? (
                <Card>
                    <EmptyState
                        icon="fa-stream"
                        title="Aucun message"
                        message="Ajoutez votre premier message défilant"
                        action={
                            <Button onClick={() => openModal()} icon="fa-plus">
                                Ajouter un message
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div className="space-y-4">
                    {sliders.map(slider => (
                        <Card key={slider.id}>
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4 flex-1">
                                    {slider.icon && (
                                        <div className="text-3xl">{slider.icon}</div>
                                    )}
                                    <div className="flex-1">
                                        <p className="text-lg text-gray-800">{slider.message}</p>
                                        <div className="flex items-center gap-4 mt-2 text-sm text-gray-600">
                                            <span><i className="fas fa-clock mr-1"></i>{slider.display_duration / 1000}s</span>
                                            <span className={slider.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                                {slider.is_active == 1 ? 'Actif' : 'Inactif'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex gap-2">
                                    <button
                                        onClick={() => openModal(slider)}
                                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                                    >
                                        <i className="fas fa-edit"></i>
                                    </button>
                                    <button
                                        onClick={() => handleDelete(slider.id)}
                                        className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
                                    >
                                        <i className="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </Card>
                    ))}
                </div>
            )}

            {/* Modal Créer/Modifier */}
            <Modal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingSlider ? 'Modifier le message' : 'Nouveau message'}
            >
                <form onSubmit={handleSubmit}>
                    <Input
                        label="Message"
                        value={formMessage}
                        onChange={setFormMessage}
                        placeholder="Nettoyage des parties communes : mardi 10h-12h"
                        required
                        icon="fa-comment"
                    />

                    <Input
                        label="Durée d'affichage (ms)"
                        type="number"
                        value={formDuration}
                        onChange={(val) => setFormDuration(parseInt(val))}
                        required
                        icon="fa-clock"
                    />

                    <Select
                        label="Configuration"
                        value={selectedConfig || ''}
                        onChange={(val) => setSelectedConfig(parseInt(val))}
                        required
                        icon="fa-cog"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </Select>

                    <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"
                            />
                            <span className="text-gray-700 font-medium">Message 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">
                            {editingSlider ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

// ============================================================================
// NUMBERS VIEW - VERSION AVEC CONFIGURATIONS
// ============================================================================

const NumbersView = () => {
    const { customer } = useAuth();
    const toast = useToast();
    const [configurations, setConfigurations] = useState([]);
    const [selectedConfig, setSelectedConfig] = useState(null);
    const [numbers, setNumbers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingNumber, setEditingNumber] = useState(null);

    // Form state
    const [formLabel, setFormLabel] = useState('');
    const [formNumber, setFormNumber] = useState('');
    const [formSubtitle, setFormSubtitle] = useState('');
    const [formCategory, setFormCategory] = useState('custom');
    const [formIcon, setFormIcon] = useState('');
    const [formActive, setFormActive] = useState(true);

    useEffect(() => {
        loadConfigurations();
        
        // Vérifier si on doit ouvrir la modal d'ajout automatiquement
        const shouldOpenModal = localStorage.getItem('open_add_modal');
        const preselectedScreenId = localStorage.getItem('preselected_screen_id');
        
        if (shouldOpenModal === 'numbers' && preselectedScreenId) {
            // Nettoyer le localStorage
            localStorage.removeItem('open_add_modal');
            localStorage.removeItem('preselected_screen_id');
            
            // Ouvrir la modal après un court délai
            setTimeout(() => {
                openModal(null, parseInt(preselectedScreenId));
            }, 500);
        }
    }, []);

    useEffect(() => {
        if (selectedConfig) {
            loadNumbers();
        }
    }, [selectedConfig]);

    const loadConfigurations = async () => {
        try {
            const result = await api.getConfigurations(customer.id);
            if (result.configurations && result.configurations.length > 0) {
                setConfigurations(result.configurations);
                setSelectedConfig(result.configurations[0].id);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement');
        }
        setLoading(false);
    };

    const loadNumbers = async () => {
        try {
            const result = await api.getNumbersByConfig(selectedConfig);
            if (result.numbers) {
                setNumbers(result.numbers);
            }
        } catch (error) {
            toast.error('Erreur lors du chargement des contacts');
        }
    };

    const openModal = (number = null) => {
        if (number) {
            setEditingNumber(number);
            setFormLabel(number.label);
            setFormNumber(number.number);
            setFormSubtitle(number.subtitle || '');
            setFormCategory(number.category);
            setFormIcon(number.icon || '');
            setFormActive(number.is_active == 1);
        } else {
            setEditingNumber(null);
            setFormLabel('');
            setFormNumber('');
            setFormSubtitle('');
            setFormCategory('custom');
            setFormIcon('');
            setFormActive(true);
        }
        setIsModalOpen(true);
    };

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

        const data = {
            configuration_id: selectedConfig,
            customer_id: customer.id,
            label: formLabel,
            number: formNumber,
            subtitle: formSubtitle,
            category: formCategory,
            icon: formIcon,
            is_active: formActive ? 1 : 0
        };

        try {
            if (editingNumber) {
                data.id = editingNumber.id;
                const result = await api.updateNumber(data);
                if (result.success) {
                    toast.success('Contact modifié');
                    loadNumbers();
                    setIsModalOpen(false);
                }
            } else {
                const result = await api.createNumber(data);
                if (result.success) {
                    toast.success('Contact créé');
                    loadNumbers();
                    setIsModalOpen(false);
                }
            }
        } catch (error) {
            toast.error('Erreur lors de l\'enregistrement');
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('Supprimer ce contact ?')) return;

        try {
            const result = await api.deleteNumber(id);
            if (result.success) {
                toast.success('Contact supprimé');
                loadNumbers();
            }
        } catch (error) {
            toast.error('Erreur lors de la suppression');
        }
    };

    if (loading) return <Loader />;

    if (configurations.length === 0) {
        return (
            <Card>
                <EmptyState
                    icon="fa-cog"
                    title="Aucune configuration"
                    message="Créez d'abord une configuration dans le menu Configurations"
                />
            </Card>
        );
    }

    const currentConfig = configurations.find(c => c.id === selectedConfig);

    const categories = {
        emergency: 'Urgence',
        concierge: 'Conciergerie',
        service: 'Services',
        custom: 'Autres'
    };

    return (
        <div className="fade-in">
            <div className="flex items-center justify-between mb-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800">Contacts rapides</h1>
                    <p className="text-gray-600 mt-2">Gérez les numéros de téléphone importants</p>
                </div>
                <Button onClick={() => openModal()} icon="fa-plus">
                    Nouveau contact
                </Button>
            </div>

            {/* Sélecteur de configuration */}
            <Card className="mb-6">
                <div className="flex items-center gap-4">
                    <label className="font-semibold text-gray-700">Configuration :</label>
                    <select
                        value={selectedConfig || ''}
                        onChange={(e) => setSelectedConfig(parseInt(e.target.value))}
                        className="px-4 py-2 border border-gray-300 rounded-lg flex-1"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </select>
                    {currentConfig && (
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                            <i className="fas fa-tv"></i>
                            <span>{currentConfig.screens_count} écran(s) utilisent cette configuration</span>
                        </div>
                    )}
                </div>
            </Card>

            {/* Liste des contacts */}
            {numbers.length === 0 ? (
                <Card>
                    <EmptyState
                        icon="fa-phone"
                        title="Aucun contact"
                        message="Ajoutez votre premier contact rapide"
                        action={
                            <Button onClick={() => openModal()} icon="fa-plus">
                                Ajouter un contact
                            </Button>
                        }
                    />
                </Card>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {numbers.map(num => (
                        <Card key={num.id}>
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3 flex-1">
                                    {num.icon && <div className="text-2xl">{num.icon}</div>}
                                    <div className="flex-1">
                                        <div className="flex items-center gap-2">
                                            <h3 className="font-semibold text-gray-800">{num.label}</h3>
                                            <span className="text-xs px-2 py-1 bg-gray-100 rounded-full text-gray-600">
                                                {categories[num.category]}
                                            </span>
                                        </div>
                                        <p className="text-lg font-bold text-orange-600 mt-1">{num.number}</p>
                                        {num.subtitle && (
                                            <p className="text-sm text-gray-600 mt-1">{num.subtitle}</p>
                                        )}
                                        <div className="mt-2">
                                            <span className={num.is_active == 1 ? 'badge-online' : 'badge-offline'}>
                                                {num.is_active == 1 ? 'Actif' : 'Inactif'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex gap-2">
                                    <button
                                        onClick={() => openModal(num)}
                                        className="px-3 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                                    >
                                        <i className="fas fa-edit"></i>
                                    </button>
                                    <button
                                        onClick={() => handleDelete(num.id)}
                                        className="px-3 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
                                    >
                                        <i className="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </Card>
                    ))}
                </div>
            )}

            {/* Modal Créer/Modifier */}
            <Modal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                title={editingNumber ? 'Modifier le contact' : 'Nouveau contact'}
            >
                <form onSubmit={handleSubmit}>
                    <Input
                        label="Nom"
                        value={formLabel}
                        onChange={setFormLabel}
                        placeholder="Pompiers"
                        required
                        icon="fa-tag"
                    />

                    <Input
                        label="Numéro"
                        value={formNumber}
                        onChange={setFormNumber}
                        placeholder="118 ou +41 22 xxx xx xx"
                        required
                        icon="fa-phone"
                    />

                    <Input
                        label="Sous-titre (optionnel)"
                        value={formSubtitle}
                        onChange={setFormSubtitle}
                        placeholder="Service d'urgence"
                        icon="fa-align-left"
                    />

                    <Select
                        label="Configuration"
                        value={selectedConfig || ''}
                        onChange={(val) => setSelectedConfig(parseInt(val))}
                        required
                        icon="fa-cog"
                    >
                        {(configurations || []).map(config => (
                            <option key={config.id} value={config.id}>
                                {config.name} ({config.screens_count} écran(s))
                            </option>
                        ))}
                    </Select>

                    <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"
                            />
                            <span className="text-gray-700 font-medium">Contact 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">
                            {editingNumber ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </div>
                </form>
            </Modal>
        </div>
    );
};

