import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react' import { channelService } from '../services/channelService' import { Channel, ChannelCategory } from '../types/channel' interface ChannelContextType { channels: Channel[] categories: ChannelCategory[] currentChannel: Channel | null isLoading: boolean error: string | null favorites: string[] searchTerm: string selectedCategory: string viewerCount: number setCurrentChannel: (channel: Channel | null) => void setSearchTerm: (term: string) => void setSelectedCategory: (category: string) => void toggleFavorite: (channelId: string) => void refreshChannels: () => Promise } const ChannelContext = createContext(undefined) export function ChannelProvider({ children }: { children: ReactNode }) { const [channels, setChannels] = useState([]) const [categories, setCategories] = useState([]) const [currentChannel, setCurrentChannel] = useState(null) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) const [favorites, setFavorites] = useState([]) const [searchTerm, setSearchTerm] = useState('') const [selectedCategory, setSelectedCategory] = useState('all') const [viewerCount, setViewerCount] = useState(0) useEffect(() => { const savedFavorites = localStorage.getItem('daddytv_favorites') if (savedFavorites) { setFavorites(JSON.parse(savedFavorites)) } }, []) useEffect(() => { localStorage.setItem('daddytv_favorites', JSON.stringify(favorites)) }, [favorites]) const refreshChannels = async () => { setIsLoading(true) setError(null) try { const data = await channelService.getChannels() setChannels(data.channels) setCategories(data.categories) } catch (err) { setError('Error al cargar los canales. Inténtalo de nuevo.') console.error('Error loading channels:', err) } finally { setIsLoading(false) } } const toggleFavorite = (channelId: string) => { setFavorites(prev => prev.includes(channelId) ? prev.filter(id => id !== channelId) : [...prev, channelId] ) } const handleSetCurrentChannel = async (channel: Channel | null) => { if (channel) { try { const result = await channelService.setViewing(channel.url) if (result.switched) { // Mostrar mensaje de cambio automático console.log('Canal cambiado automáticamente') } setViewerCount(result.viewers || 1) } catch (err) { console.error('Error setting current channel:', err) } } setCurrentChannel(channel) } return ( {children} ) } export function useChannels() { const context = useContext(ChannelContext) if (context === undefined) { throw new Error('useChannels must be used within a ChannelProvider') } return context }