// Main Application SPA Logic
import { Store } from './store.js';
import { VideoPlayer } from './player.js';

class App {
  constructor() {
    this.categories = [];
    this.channels = [];
    this.events = [];
    this.highlights = [];
    this.playlists = [];
    this.selectedCategoryId = null;
    this.selectedPlaylistId = null;
    this.activeTab = 'categories';
    
    // Instantiate player
    this.player = new VideoPlayer('custom-video-player');
    
    this.initElements();
    this.initEvents();
    
    // Apply initial saved theme and layout
    this.applyInitialThemeAndLayout();
    
    // Route popstate listener for browser back/forward buttons
    window.addEventListener('popstate', () => {
      this.handleRoute(window.location.pathname + window.location.search);
    });

    this.loadData().then(() => {
      this.handleRoute(window.location.pathname + window.location.search);
    });
  }

  initElements() {
    // Tab Sections
    this.sections = {
      categories: document.getElementById('section-categories'),
      channels: document.getElementById('section-channels'),
      sports: document.getElementById('section-sports'),
      highlights: document.getElementById('section-highlights'),
      favorites: document.getElementById('section-favorites'),
      settings: document.getElementById('section-settings')
    };

    // Nav Bar Items
    this.navItems = document.querySelectorAll('.navbar-item');

    // Grids
    this.categoriesGrid = document.getElementById('categories-grid');
    this.channelsGrid = document.getElementById('channels-grid');
    this.sportsGrid = document.getElementById('sports-grid');
    this.highlightsGrid = document.getElementById('highlights-grid');
    this.favoritesGrid = document.getElementById('favorites-grid');

    // Searches
    this.searchChannelsInput = document.getElementById('search-channels');
    this.searchFavsInput = document.getElementById('search-favorites');

    // Headers & Banners
    this.categoriesHeaderTitle = document.getElementById('categories-header-title');
    this.btnBackPlaylists = document.getElementById('btn-back-playlists');
    this.channelsHeaderTitle = document.getElementById('channels-header-title');
    this.btnBackToCategories = document.getElementById('btn-back-categories');
    
    // Grid/List Layout Toggle
    this.btnToggleLayout = document.getElementById('btn-toggle-layout');
    this.iconLayoutGrid = document.getElementById('icon-layout-grid');
    this.iconLayoutList = document.getElementById('icon-layout-list');
    
    // Theme Selectors
    this.themeSelectBtns = document.querySelectorAll('.theme-select-btn');
    
    // Theater Modal for Highlights
    this.theaterModal = document.getElementById('theater-modal');
    this.theaterClose = this.theaterModal ? this.theaterModal.querySelector('.theater-close') : null;
    this.theaterVideo = this.theaterModal ? this.theaterModal.querySelector('#theater-video') : null;

    // Settings and top header selectors
    this.btnTopSettings = document.getElementById('btn-top-settings');
    this.selectSeekInterval = document.getElementById('select-seek-interval');
    this.inputSeekIntervalCustom = document.getElementById('input-seek-interval-custom');
  }

  initEvents() {
    // 1. Navigation Tab Switching
    this.navItems.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const tab = item.getAttribute('data-tab');
        this.navigate(`/${tab}`);
      });
    });

    // 2. Back to Categories from Channels
    this.btnBackToCategories.addEventListener('click', () => {
      if (this.selectedPlaylistId) {
        this.navigate(`/categories?playlist=${this.selectedPlaylistId}`);
      } else {
        this.navigate('/categories');
      }
    });

    // 2b. Back to Playlists from nested category view
    if (this.btnBackPlaylists) {
      this.btnBackPlaylists.addEventListener('click', () => {
        this.navigate('/categories');
      });
    }

    // 3. Search Key Event Bindings
    this.searchChannelsInput.addEventListener('input', () => {
      this.filterChannelsList(this.searchChannelsInput.value, this.selectedCategoryId);
    });

    this.searchFavsInput.addEventListener('input', () => {
      this.filterFavoritesList(this.searchFavsInput.value);
    });

    // 4. Settings Toggle Handlers
    const toggleLowQuality = document.getElementById('toggle-low-quality');
    if (toggleLowQuality) {
      toggleLowQuality.checked = Store.getSetting('forceLowQuality');
      toggleLowQuality.addEventListener('change', () => {
        Store.updateSetting('forceLowQuality', toggleLowQuality.checked);
      });
    }

    // Theme selector click events
    this.themeSelectBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        const theme = btn.getAttribute('data-theme');
        Store.updateSetting('themeAccent', theme);
        this.applyTheme(theme);
      });
    });

    // Layout Toggle Handler
    if (this.btnToggleLayout) {
      this.btnToggleLayout.addEventListener('click', () => {
        const currentLayout = Store.getSetting('channelsLayout');
        const nextLayout = currentLayout === 'list' ? 'grid' : 'list';
        Store.updateSetting('channelsLayout', nextLayout);
        this.updateLayoutToggleIcon(nextLayout);
        
        this.filterChannelsList(this.searchChannelsInput.value, this.selectedCategoryId);
        if (this.activeTab === 'favorites') {
          this.renderFavorites();
        }
      });
    }

    // Theater Modal Events
    if (this.theaterClose) {
      this.theaterClose.addEventListener('click', () => this.closeTheater());
    }
    if (this.theaterModal) {
      this.theaterModal.addEventListener('click', (e) => {
        if (e.target === this.theaterModal) {
          this.closeTheater();
        }
      });
    }
    window.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.theaterModal && this.theaterModal.classList.contains('active')) {
        this.closeTheater();
      }
    });

    // 5. Highlights Event Filter Chips
    const chips = document.querySelectorAll('#highlights-chips .chip');
    chips.forEach(chip => {
      chip.addEventListener('click', () => {
        chips.forEach(c => c.classList.remove('active'));
        chip.classList.add('active');
        const filter = chip.getAttribute('data-filter');
        this.renderHighlights(filter);
      });
    });

    // 6. Live Events Filter Chips
    const liveChips = document.querySelectorAll('#live-chips .chip');
    liveChips.forEach(chip => {
      chip.addEventListener('click', () => {
        liveChips.forEach(c => c.classList.remove('active'));
        chip.classList.add('active');
        const filter = chip.getAttribute('data-filter');
        this.renderEvents(filter);
      });
    });

    // 7. Mobile Top Header Settings Gear
    if (this.btnTopSettings) {
      this.btnTopSettings.addEventListener('click', (e) => {
        e.preventDefault();
        this.navigate('/settings');
      });
    }

    // 8. Double Tap Seek settings binding
    if (this.selectSeekInterval) {
      const savedSeek = Store.getSetting('seekInterval') || 10;
      if ([5, 10, 20].includes(Number(savedSeek))) {
        this.selectSeekInterval.value = savedSeek;
        if (this.inputSeekIntervalCustom) {
          this.inputSeekIntervalCustom.classList.add('hidden');
        }
      } else {
        this.selectSeekInterval.value = 'custom';
        if (this.inputSeekIntervalCustom) {
          this.inputSeekIntervalCustom.classList.remove('hidden');
          this.inputSeekIntervalCustom.value = savedSeek;
        }
      }

      this.selectSeekInterval.addEventListener('change', () => {
        const val = this.selectSeekInterval.value;
        if (val === 'custom') {
          if (this.inputSeekIntervalCustom) {
            this.inputSeekIntervalCustom.classList.remove('hidden');
            const customVal = Number(this.inputSeekIntervalCustom.value) || 10;
            Store.updateSetting('seekInterval', customVal);
          }
        } else {
          if (this.inputSeekIntervalCustom) {
            this.inputSeekIntervalCustom.classList.add('hidden');
          }
          Store.updateSetting('seekInterval', Number(val));
        }
      });
    }

    if (this.inputSeekIntervalCustom) {
      this.inputSeekIntervalCustom.addEventListener('input', () => {
        let customVal = Number(this.inputSeekIntervalCustom.value) || 10;
        if (customVal < 1) customVal = 1;
        Store.updateSetting('seekInterval', customVal);
      });
    }
  }

  async loadData() {
    try {
      // Fetch Categories, Channels, Events, Highlights, Playlists and Settings concurrently from API
      const [resCats, resChans, resEvs, resHls, resPlaylists, resAnnounce] = await Promise.all([
        fetch('/api/categories').then(r => r.json()),
        fetch('/api/channels').then(r => r.json()),
        fetch('/api/events').then(r => r.json()),
        fetch('/api/highlights').then(r => r.json()),
        fetch('/api/playlists').then(r => r.json()).catch(() => []),
        fetch('/api/settings/announcement').then(r => r.json()).catch(() => ({ value: '' }))
      ]);

      this.categories = resCats;
      this.channels = resChans;
      this.events = resEvs;
      this.highlights = resHls;
      this.playlists = resPlaylists;

      // Update scrolling announcement text
      if (resAnnounce && resAnnounce.value) {
        const announceTextEl = document.querySelector('.announcement-text');
        if (announceTextEl) announceTextEl.textContent = resAnnounce.value;
      }

      // Render items
      this.renderCategories();
      this.renderEvents('all');
      this.renderHighlights('all');
      this.renderFavorites();
      // Start real-time countdown updates
      this.startTicker();
    } catch (err) {
      console.error('Failed to load application data:', err);
    }
  }

  navigate(path, pushState = true) {
    if (pushState) {
      window.history.pushState(null, '', path);
    }
    this.handleRoute(path);
  }

  handleRoute(path) {
    // Parse URL path and query parameters
    const url = new URL(path, window.location.origin);
    const pathname = url.pathname;
    const searchParams = url.searchParams;

    // 1. Determine tab name
    let tabName = 'categories';
    if (pathname.startsWith('/channels')) {
      tabName = 'channels';
    } else if (pathname.startsWith('/sports')) {
      tabName = 'sports';
    } else if (pathname.startsWith('/highlights')) {
      tabName = 'highlights';
    } else if (pathname.startsWith('/favorites')) {
      tabName = 'favorites';
    } else if (pathname.startsWith('/settings')) {
      tabName = 'settings';
    }

    // 2. Extract specific query params
    const playlistId = searchParams.get('playlist');
    const categoryId = searchParams.get('category');

    // 3. Update application state
    this.selectedPlaylistId = playlistId ? Number(playlistId) : null;
    this.selectedCategoryId = categoryId ? Number(categoryId) : null;

    // 4. Update tab selection in UI
    this.activeTab = tabName;

    // Update active navbar styles
    this.navItems.forEach(item => {
      if (item.getAttribute('data-tab') === tabName) {
        item.classList.add('active');
      } else {
        item.classList.remove('active');
      }
    });

    // Toggle Sections visibility
    Object.keys(this.sections).forEach(key => {
      if (key === tabName) {
        this.sections[key].classList.add('active');
      } else {
        this.sections[key].classList.remove('active');
      }
    });

    // 5. Render appropriate content
    if (tabName === 'categories') {
      this.renderCategories();
    } else if (tabName === 'channels') {
      // Set correct title
      if (this.selectedCategoryId) {
        const cat = this.categories.find(c => c.id === this.selectedCategoryId);
        this.channelsHeaderTitle.textContent = cat ? cat.name : 'Channels';
      } else {
        this.channelsHeaderTitle.textContent = 'All Channels';
      }
      this.filterChannelsList(this.searchChannelsInput.value, this.selectedCategoryId);
    } else if (tabName === 'favorites') {
      this.renderFavorites();
    }
  }

  // --- 1. RENDER CATEGORIES ---
  renderCategories() {
    this.categoriesGrid.innerHTML = '';
    
    if (this.selectedPlaylistId === null) {
      if (this.btnBackPlaylists) this.btnBackPlaylists.classList.add('hidden');
      if (this.categoriesHeaderTitle) this.categoriesHeaderTitle.textContent = 'Categories';

      // 1. General Header & Card
      const allHeader = document.createElement('div');
      allHeader.style.gridColumn = '1 / -1';
      allHeader.style.margin = '10px 0 5px 0';
      allHeader.style.fontSize = '1.05rem';
      allHeader.style.fontWeight = '700';
      allHeader.style.color = 'var(--accent-secondary)';
      allHeader.textContent = 'General';
      this.categoriesGrid.appendChild(allHeader);

      const allCard = document.createElement('div');
      allCard.className = 'category-card';
      allCard.setAttribute('data-cat', 'ALL CHANNELS');
      allCard.innerHTML = `
        <div class="category-icon-wrap" style="--glow-color: rgba(0, 242, 254, 0.45);">
          <div class="category-icon-fallback" style="background: var(--grad-accent);">ALL</div>
        </div>
        <div class="category-name">All Channels</div>
      `;
      allCard.addEventListener('click', () => {
        this.navigate('/channels');
      });
      this.categoriesGrid.appendChild(allCard);
      
      // 2. Playlists Section
      if (this.playlists && this.playlists.length > 0) {
        const plHeader = document.createElement('div');
        plHeader.style.gridColumn = '1 / -1';
        plHeader.style.margin = '20px 0 5px 0';
        plHeader.style.fontSize = '1.05rem';
        plHeader.style.fontWeight = '700';
        plHeader.style.color = 'var(--accent-secondary)';
        plHeader.textContent = 'Playlists';
        this.categoriesGrid.appendChild(plHeader);

        this.playlists.forEach(pl => {
          const card = document.createElement('div');
          card.className = 'category-card';
          const firstLetter = pl.name.substring(0, 2).toUpperCase();
          card.innerHTML = `
            <div class="category-icon-wrap" style="--glow-color: rgba(0, 242, 254, 0.4);">
              <div class="category-icon-fallback" style="background: var(--grad-accent); font-size: 1.25rem;">${firstLetter}</div>
            </div>
            <div class="category-name">${pl.name}</div>
          `;
          card.addEventListener('click', () => {
            this.navigate(`/categories?playlist=${pl.id}`);
          });
          this.categoriesGrid.appendChild(card);
        });
      }

      // 3. Categories / Groups Section
      const catHeader = document.createElement('div');
      catHeader.style.gridColumn = '1 / -1';
      catHeader.style.margin = '24px 0 5px 0';
      catHeader.style.fontSize = '1.05rem';
      catHeader.style.fontWeight = '700';
      catHeader.style.color = 'var(--accent-secondary)';
      catHeader.textContent = 'Global Categories';
      this.categoriesGrid.appendChild(catHeader);

      this.renderCategoriesList(this.categories);
      
    } else {
      // Nested View: showing categories inside a selected playlist
      const playlist = this.playlists.find(p => p.id === this.selectedPlaylistId);
      const playlistName = playlist ? playlist.name : 'Playlist';

      if (this.btnBackPlaylists) this.btnBackPlaylists.classList.remove('hidden');
      if (this.categoriesHeaderTitle) this.categoriesHeaderTitle.textContent = playlistName;

      // Filter categories to show ONLY those containing channels from this playlist
      const categoryIdsInPlaylist = [
        ...new Set(
          this.channels
            .filter(c => c.playlist_id === this.selectedPlaylistId && c.category_id !== null)
            .map(c => c.category_id)
        )
      ];

      const filteredCategories = this.categories.filter(cat => categoryIdsInPlaylist.includes(cat.id));

      if (filteredCategories.length === 0) {
        const noCats = document.createElement('div');
        noCats.style.gridColumn = '1 / -1';
        noCats.style.textAlign = 'center';
        noCats.style.color = 'var(--text-muted)';
        noCats.style.padding = '40px 0';
        noCats.textContent = 'No categories found in this playlist.';
        this.categoriesGrid.appendChild(noCats);
      } else {
        this.renderCategoriesList(filteredCategories);
      }
    }
  }

  renderCategoriesList(categoriesToRender) {
    // Sort categories (place SPORTS, BANGLA at first)
    const sorted = [...categoriesToRender].sort((a, b) => {
      if (a.name === 'SPORTS' || a.name === 'BANGLA') return -1;
      if (b.name === 'SPORTS' || b.name === 'BANGLA') return 1;
      return a.display_order - b.display_order;
    });

    sorted.forEach(cat => {
      const card = document.createElement('div');
      card.className = 'category-card';
      card.setAttribute('data-cat', cat.name);
      
      // FALLBACK LETTER AVATAR
      const firstLetter = cat.name.substring(0, 2).toUpperCase();
      const logoHtml = cat.logo_url 
        ? `<img src="${cat.logo_url}" alt="${cat.name}" onerror="this.outerHTML='<div class=\\'category-icon-fallback\\'>${firstLetter}</div>'">`
        : `<div class="category-icon-fallback">${firstLetter}</div>`;
      
      card.innerHTML = `
        <div class="category-icon-wrap">
          ${logoHtml}
        </div>
        <div class="category-name">${cat.name}</div>
      `;

      card.addEventListener('click', () => {
        this.navigate(`/channels?category=${cat.id}`);
      });

      this.categoriesGrid.appendChild(card);
    });
  }

  // --- 2. RENDER CHANNELS IN SELECTED CATEGORY ---
  filterChannelsList(searchQuery = '', categoryId = null) {
    this.channelsGrid.innerHTML = '';
    const query = searchQuery.toLowerCase().trim();

    const filtered = this.channels.filter(chan => {
      const matchesCategory = categoryId === null || chan.category_id === Number(categoryId);
      const matchesPlaylist = this.selectedPlaylistId === null || chan.playlist_id === Number(this.selectedPlaylistId);
      const matchesSearch = chan.name.toLowerCase().includes(query);
      return matchesCategory && matchesPlaylist && matchesSearch;
    });

    if (filtered.length === 0) {
      this.channelsGrid.innerHTML = `<div style="grid-column: 1/-1; text-align:center; color: var(--text-muted); padding: 40px 0;">No Channels Found</div>`;
      return;
    }

    // Read active channels layout
    const layout = Store.getSetting('channelsLayout') || 'grid';
    if (layout === 'list') {
      this.channelsGrid.className = 'grid-cols-compact';
    } else {
      this.channelsGrid.className = 'grid-cols-auto';
    }

    filtered.forEach(chan => {
      const isFav = Store.isFavorite(chan.id);
      const card = document.createElement('div');
      
      if (layout === 'list') {
        card.className = 'channel-card compact-list-row';
      } else {
        card.className = 'channel-card';
      }
      
      const initials = chan.name.substring(0, 2).toUpperCase();
      const logoHtml = chan.logo_url 
        ? `<img src="${chan.logo_url}" alt="${chan.name}" onerror="this.outerHTML='<div class=\\'channel-logo-fallback\\'>${initials}</div>'">`
        : `<div class="channel-logo-fallback">${initials}</div>`;

      card.innerHTML = `
        <div class="channel-logo">
          ${logoHtml}
        </div>
        <div class="channel-name">${chan.name}</div>
        <div class="channel-fav-toggle" style="${layout === 'list' ? '' : 'margin-top: 10px;'} color: ${isFav ? 'var(--accent-secondary)' : 'var(--text-muted)'}; cursor: pointer; display: flex; align-items: center; justify-content: center;">
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="${isFav ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/></svg>
        </div>
      `;

      // Click logo/name to play
      card.addEventListener('click', (e) => {
        if (e.target.closest('.channel-fav-toggle')) return;
        this.player.loadChannel(chan);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      });

      // Click Favorite Heart to toggle favorite cache
      const btnFav = card.querySelector('.channel-fav-toggle');
      btnFav.addEventListener('click', (e) => {
        e.stopPropagation();
        Store.toggleFavorite(chan.id);
        this.filterChannelsList(searchQuery, categoryId);
      });

      this.channelsGrid.appendChild(card);
    });
  }

  // --- 3. RENDER FAVORITES TAB ---
  renderFavorites() {
    this.filterFavoritesList(this.searchFavsInput.value);
  }

  filterFavoritesList(searchQuery = '') {
    this.favoritesGrid.innerHTML = '';
    const query = searchQuery.toLowerCase().trim();
    const favIds = Store.getFavorites();

    const filtered = this.channels.filter(chan => {
      return favIds.includes(Number(chan.id)) && chan.name.toLowerCase().includes(query);
    });

    if (filtered.length === 0) {
      this.favoritesGrid.innerHTML = `<div style="grid-column:1/-1; text-align:center; color:var(--text-muted); padding:40px 0;">No Favorites Saved Yet. Add favorites by clicking the heart button on channel lists.</div>`;
      return;
    }

    // Apply active channels layout
    const layout = Store.getSetting('channelsLayout') || 'grid';
    if (layout === 'list') {
      this.favoritesGrid.className = 'grid-cols-compact';
    } else {
      this.favoritesGrid.className = 'grid-cols-auto';
    }

    filtered.forEach(chan => {
      const card = document.createElement('div');
      
      if (layout === 'list') {
        card.className = 'channel-card compact-list-row';
      } else {
        card.className = 'channel-card';
      }
      
      const initials = chan.name.substring(0, 2).toUpperCase();
      const logoHtml = chan.logo_url 
        ? `<img src="${chan.logo_url}" alt="${chan.name}" onerror="this.outerHTML='<div class=\\'channel-logo-fallback\\'>${initials}</div>'">`
        : `<div class="channel-logo-fallback">${initials}</div>`;

      card.innerHTML = `
        <div class="channel-logo">
          ${logoHtml}
        </div>
        <div class="channel-name">${chan.name}</div>
        <div class="channel-fav-toggle" style="${layout === 'list' ? '' : 'margin-top:10px;'} color:var(--accent-secondary); cursor:pointer; display: flex; align-items: center; justify-content: center;">
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/></svg>
        </div>
      `;

      card.addEventListener('click', (e) => {
        if (e.target.closest('.channel-fav-toggle')) return;
        this.player.loadChannel(chan);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      });

      card.querySelector('.channel-fav-toggle').addEventListener('click', () => {
        Store.toggleFavorite(chan.id);
        this.renderFavorites();
      });

      this.favoritesGrid.appendChild(card);
    });
  }

  // --- 4. RENDER LIVE EVENTS ---
  renderEvents(filter = 'all') {
    this.sportsGrid.innerHTML = '';
    
    const filtered = this.events.filter(ev => {
      if (filter === 'all') return true;
      if (filter === 'live') return ev.status.toLowerCase() === 'live';
      if (filter === 'today') return ev.status.toLowerCase() !== 'ended';
      return ev.category.toLowerCase() === filter.toLowerCase();
    });

    if (filtered.length === 0) {
      this.sportsGrid.innerHTML = `<div style="text-align:center; color: var(--text-muted); padding:40px 0; width:100%;">No Live Events Scheduled</div>`;
      return;
    }

    filtered.forEach(ev => {
      const card = document.createElement('div');
      card.className = 'event-card';

      const servers = ev.servers || [];
      const numServers = servers.length;
      
      const badgeClass = ev.status.toLowerCase() === 'live' ? 'badge-live' : '';
      const badgeLabel = ev.status.toUpperCase();
      
      const countdownText = this.getCountdownString(ev.start_time, ev.status);
      
      card.innerHTML = `
        <div class="event-header">
          <div class="event-league">${ev.league || 'Sports Event'}</div>
          <div class="badge ${badgeClass}">${badgeLabel}</div>
        </div>
        <div class="event-body">
          <div class="event-team">
            <img class="event-team-logo" src="${ev.team1_logo || 'https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'}" onerror="this.src='https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'">
            <div class="event-team-name">${ev.team1_name || 'Team 1'}</div>
          </div>
          <div class="event-vs">VS</div>
          <div class="event-team">
            <img class="event-team-logo" src="${ev.team2_logo || 'https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'}" onerror="this.src='https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'">
            <div class="event-team-name">${ev.team2_name || 'Team 2'}</div>
          </div>
        </div>
        <div class="event-footer">
          <div class="event-countdown-badge event-time" data-start-time="${ev.start_time}" data-event-status="${ev.status}">${countdownText}</div>
          <button class="btn-server" style="background: var(--grad-accent); border: none;">
            ${numServers} ${numServers === 1 ? 'Server' : 'Servers'}
          </button>
        </div>
      `;

      card.addEventListener('click', () => {
        // Open Multi Server Dialog
        if (numServers > 0) {
          this.openStreamChooser(ev.title, servers);
        } else {
          alert('No streams currently linked for this live event.');
        }
      });

      this.sportsGrid.appendChild(card);
    });
  }

  // --- 5. RENDER HIGHLIGHTS ---
  renderHighlights(filter = 'all') {
    this.highlightsGrid.innerHTML = '';
    
    const filtered = this.highlights.filter(hl => {
      if (filter === 'all') return true;
      return hl.category.toLowerCase() === filter.toLowerCase();
    });

    if (filtered.length === 0) {
      this.highlightsGrid.innerHTML = `<div style="text-align:center; color: var(--text-muted); padding:40px 0; width:100%;">No Highlights Found</div>`;
      return;
    }

    filtered.forEach(hl => {
      const card = document.createElement('div');
      card.className = 'event-card';

      card.innerHTML = `
        <div class="event-header">
          <div class="event-league">${hl.league || 'Highlights'}</div>
          <div class="badge" style="background:rgba(0, 242, 254, 0.1); color:var(--accent-primary); border:1px solid rgba(0, 242, 254, 0.2)">REPLAY</div>
        </div>
        <div class="event-body">
          <div class="event-team">
            <img class="event-team-logo" src="${hl.team1_logo || 'https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'}" onerror="this.src='https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'">
            <div class="event-team-name">${hl.team1_name || 'Team 1'}</div>
          </div>
          <div class="event-score" style="font-family: var(--font-display); font-size: 1.8rem; font-weight: 800; color:var(--text-primary); letter-spacing:8px; padding:0 20px;">
            ${hl.score1} : ${hl.score2}
          </div>
          <div class="event-team">
            <img class="event-team-logo" src="${hl.team2_logo || 'https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'}" onerror="this.src='https://i.ibb.co/Ns62bY2/2021-04-22-10-24-01.png'">
            <div class="event-team-name">${hl.team2_name || 'Team 2'}</div>
          </div>
        </div>
        <div class="event-footer">
          <div class="event-time">${hl.date || 'Ended'}</div>
          <button class="btn-server" style="background:var(--grad-accent); border:none; color:#fff">
            Watch Replay
          </button>
        </div>
      `;

      card.addEventListener('click', () => {
        this.openTheater(hl.title, hl.video_url);
      });

      this.highlightsGrid.appendChild(card);
    });
  }

  // --- 6. MULTIPLE SERVERS CHOOSER DIALOG ---
  openStreamChooser(title, servers) {
    const overlay = document.getElementById('chooser-modal');
    const titleEl = overlay.querySelector('.modal-title');
    const listEl = overlay.querySelector('.modal-option-list');
    const btnCancel = overlay.querySelector('.modal-cancel');

    titleEl.textContent = title;
    listEl.innerHTML = '';

    servers.forEach((srv) => {
      const opt = document.createElement('div');
      opt.className = 'modal-option';
      opt.innerHTML = `
        <div style="font-weight:600; color:#fff;">${srv.name}</div>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--accent-primary)"><path d="m9 18 6-6-6-6"/></svg>
      `;
      opt.addEventListener('click', () => {
        overlay.classList.remove('active');
        this.player.loadChannel({
          name: title,
          servers: servers
        });
        // Select active server
        const activeIdx = servers.findIndex(s => s.url === srv.url);
        if (activeIdx !== -1) {
          this.player.activeServerIndex = activeIdx;
          this.player.renderServerChips();
        }
        window.scrollTo({ top: 0, behavior: 'smooth' });
      });
      listEl.appendChild(opt);
    });

    overlay.classList.add('active');

    btnCancel.onclick = () => {
      overlay.classList.remove('active');
    };
  }

  // --- 7. UX THEME & LAYOUT HELPER MODULES ---
  applyInitialThemeAndLayout() {
    const theme = Store.getSetting('themeAccent') || 'purple';
    this.applyTheme(theme);

    const layout = Store.getSetting('channelsLayout') || 'grid';
    this.updateLayoutToggleIcon(layout);
  }

  applyTheme(theme) {
    // Remove existing themes
    document.body.classList.forEach(className => {
      if (className.startsWith('theme-')) {
        document.body.classList.remove(className);
      }
    });
    // Add active theme class
    document.body.classList.add(`theme-${theme}`);

    // Update active highlight style for theme selectors
    this.themeSelectBtns.forEach(btn => {
      if (btn.getAttribute('data-theme') === theme) {
        btn.classList.add('active');
        btn.style.borderColor = '#fff';
        btn.style.transform = 'scale(1.1)';
        btn.style.boxShadow = '0 0 14px var(--accent-primary)';
      } else {
        btn.classList.remove('active');
        btn.style.borderColor = 'transparent';
        btn.style.transform = 'none';
        btn.style.boxShadow = 'none';
      }
    });
  }

  updateLayoutToggleIcon(layout) {
    if (!this.iconLayoutGrid || !this.iconLayoutList) return;
    if (layout === 'list') {
      this.iconLayoutGrid.classList.remove('hidden');
      this.iconLayoutList.classList.add('hidden');
    } else {
      this.iconLayoutGrid.classList.add('hidden');
      this.iconLayoutList.classList.remove('hidden');
    }
  }

  // --- 8. HIGHLIGHTS THEATER OVERLAY ---
  openTheater(title, url) {
    if (!this.theaterModal || !this.theaterVideo) return;
    
    // Pause live player to prevent cross audio bleeding
    if (this.player) {
      this.player.pause();
    }

    this.theaterVideo.src = url;
    this.theaterModal.classList.add('active');
    this.theaterVideo.play().catch(err => {
      console.warn('Theater playback autoplay block:', err.message);
    });
  }

  closeTheater() {
    if (!this.theaterModal || !this.theaterVideo) return;
    this.theaterVideo.pause();
    this.theaterVideo.src = '';
    this.theaterModal.classList.remove('active');
  }

  // --- 9. DATE PARSING & COUNTDOWNS ---
  parseEventDate(dateStr) {
    if (!dateStr) return null;
    // Format: "hh:mm AM/PM DD/MM/YYYY" e.g. "06:00 AM 07/06/2026"
    try {
      const parts = dateStr.trim().split(/\s+/);
      if (parts.length >= 3) {
        const timePart = parts[0]; // "06:00"
        const ampmPart = parts[1]; // "AM"
        const datePart = parts[2]; // "07/06/2026"
        
        const [hourStr, minStr] = timePart.split(':');
        let hour = parseInt(hourStr, 10);
        const min = parseInt(minStr, 10);
        
        if (ampmPart.toUpperCase() === 'PM' && hour < 12) hour += 12;
        if (ampmPart.toUpperCase() === 'AM' && hour === 12) hour = 0;
        
        const [dayStr, monthStr, yearStr] = datePart.split('/');
        const day = parseInt(dayStr, 10);
        const month = parseInt(monthStr, 10) - 1; // 0-indexed in JS
        const year = parseInt(yearStr, 10);
        
        return new Date(year, month, day, hour, min, 0);
      }
    } catch (e) {
      console.error('Error parsing date string:', dateStr, e);
    }
    const d = new Date(dateStr);
    return isNaN(d.getTime()) ? null : d;
  }

  getCountdownString(startTime, status) {
    if (status.toLowerCase() === 'live') {
      return '🟢 Live Now';
    }
    if (status.toLowerCase() === 'ended') {
      return '🏁 Ended';
    }
    
    const parsed = this.parseEventDate(startTime);
    if (!parsed) return startTime || 'Schedule pending';
    
    const diffMs = parsed.getTime() - Date.now();
    if (diffMs <= 0) {
      return '🟢 Live Now';
    }
    
    const diffSecs = Math.floor(diffMs / 1000);
    const diffMins = Math.floor(diffSecs / 60);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);
    
    if (diffDays > 0) {
      return `⏳ In ${diffDays}d ${diffHours % 24}h`;
    } else if (diffHours > 0) {
      return `⏳ In ${diffHours}h ${diffMins % 60}m`;
    } else if (diffMins > 0) {
      return `⏳ In ${diffMins}m ${diffSecs % 60}s`;
    } else {
      return `⏳ Starting now`;
    }
  }

  startTicker() {
    if (this.tickerInterval) clearInterval(this.tickerInterval);
    this.tickerInterval = setInterval(() => this.updateTickers(), 1000);
  }

  updateTickers() {
    const tickerEls = document.querySelectorAll('.event-time[data-start-time]');
    tickerEls.forEach(el => {
      const startTime = el.getAttribute('data-start-time');
      const status = el.getAttribute('data-event-status');
      const text = this.getCountdownString(startTime, status);
      
      if (el.textContent !== text) {
        el.textContent = text;
      }

      // Upgrade upcoming to live automatically on screen
      if (text === '🟢 Live Now' && status.toLowerCase() === 'upcoming') {
        const card = el.closest('.event-card');
        if (card) {
          const badge = card.querySelector('.badge');
          if (badge && !badge.classList.contains('badge-live')) {
            badge.className = 'badge badge-live';
            badge.textContent = 'LIVE';
          }
        }
      }
    });
  }
}

// Instantiate App on window load
window.addEventListener('DOMContentLoaded', () => {
  window.app = new App();
});
