import './index.css';
import { DRAMA_DATABASE, TEAM_MEMBERS, FAQ_RESPONSES, DramaItem } from './data';

// ==========================================
// STATE MANAGEMENT & ROUTING
// ==========================================
let currentGenre = 'all';
let currentRegion = 'all';
let currentYear = 'all';
let currentRating = 'all';
let currentSort = 'latest';
let searchQuery = '';
let currentProductPage = 1;
const itemsPerPage = 8;

// Video Player State
let playerIsPlaying = false;
let playerTimelineInterval: any = null;
let playerPlaybackSpeed = 1.0;
let playerCurrentSeconds = 0;
const playerTotalSeconds = 2700; // 45 minutes
let danmakuIsEnabled = true;
let activeDrama: DramaItem = DRAMA_DATABASE[0];
let activeEpisode = 1;

// ==========================================
// INITIALIZATION
// ==========================================
window.addEventListener('DOMContentLoaded', () => {
  setupRouting();
  setupFilters();
  setupSearch();
  setupNewsInteraction();
  setupVideoPlayer();
  setupContactForm();
  setupCDNMap();
  setupChatbot();
  
  // Render initial feeds
  renderHomePopularGrid();
  renderHomeLatestGrid();
  renderProductGrid();
  renderTeamGrid();
  
  // Start autonomous bullet comment spawner for player
  startAutonomousDanmaku();
});

// ==========================================
// ROUTING & MENU CONTROLS
// ==========================================
function setupRouting() {
  const navLinks = document.querySelectorAll('.nav-link');
  const mobileNavLinks = document.querySelectorAll('.mobile-nav-link');
  const footerNavBtns = document.querySelectorAll('.footer-nav-btn');
  const viewSections = document.querySelectorAll('.view-section');
  const logo = document.getElementById('header-logo');
  const exploreBtns = document.querySelectorAll('.view-all-products-btn');

  const switchView = (targetViewId: string) => {
    // Hide all views, show targeted
    viewSections.forEach(section => {
      if (section.id === `view-${targetViewId}`) {
        section.classList.remove('hidden');
        section.classList.add('block');
      } else {
        section.classList.add('hidden');
        section.classList.remove('block');
      }
    });

    // Update Desktop Nav Active States
    navLinks.forEach(link => {
      const btn = link as HTMLButtonElement;
      if (btn.dataset.view === targetViewId) {
        btn.classList.add('text-cinema-accent', 'border-cinema-accent');
        btn.classList.remove('text-gray-300', 'hover:text-white');
      } else {
        btn.classList.remove('text-cinema-accent', 'border-cinema-accent');
        btn.classList.add('text-gray-300', 'hover:text-white');
      }
    });

    // Update Mobile Nav Active States
    mobileNavLinks.forEach(link => {
      const btn = link as HTMLButtonElement;
      if (btn.dataset.view === targetViewId) {
        btn.classList.add('text-cinema-accent', 'bg-white/5');
        btn.classList.remove('text-gray-300', 'hover:text-white', 'hover:bg-white/5');
      } else {
        btn.classList.remove('text-cinema-accent', 'bg-white/5');
        btn.classList.add('text-gray-300', 'hover:text-white', 'hover:bg-white/5');
      }
    });

    // Close mobile menu
    const mobileMenu = document.getElementById('mobile-menu');
    const closedIcon = document.getElementById('menu-icon-closed');
    const openedIcon = document.getElementById('menu-icon-opened');
    if (mobileMenu && !mobileMenu.classList.contains('hidden')) {
      mobileMenu.classList.add('hidden');
      closedIcon?.classList.remove('hidden');
      openedIcon?.classList.add('hidden');
    }

    // Scroll to top smoothly
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Bind desktop nav links
  navLinks.forEach(link => {
    link.addEventListener('click', () => {
      const view = (link as HTMLButtonElement).dataset.view || 'home';
      switchView(view);
    });
  });

  // Bind mobile nav links
  mobileNavLinks.forEach(link => {
    link.addEventListener('click', () => {
      const view = (link as HTMLButtonElement).dataset.view || 'home';
      switchView(view);
    });
  });

  // Bind footer links
  footerNavBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      const view = (btn as HTMLButtonElement).dataset.view || 'home';
      switchView(view);
    });
  });

  // Logo returns to home
  logo?.addEventListener('click', () => {
    switchView('home');
  });

  // Promo explore button transitions to product tab
  exploreBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      switchView('products');
    });
  });

  // Mobile hamburger menu trigger
  const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
  const mobileMenu = document.getElementById('mobile-menu');
  const closedIcon = document.getElementById('menu-icon-closed');
  const openedIcon = document.getElementById('menu-icon-opened');

  mobileMenuToggle?.addEventListener('click', () => {
    const isHidden = mobileMenu?.classList.contains('hidden');
    if (isHidden) {
      mobileMenu?.classList.remove('hidden');
      closedIcon?.classList.add('hidden');
      openedIcon?.classList.remove('hidden');
    } else {
      mobileMenu?.classList.add('hidden');
      closedIcon?.classList.remove('hidden');
      openedIcon?.classList.add('hidden');
    }
  });

  // Mobile search toggle bar
  const mobileSearchToggle = document.getElementById('mobile-search-toggle');
  const mobileSearchBar = document.getElementById('mobile-search-bar');
  mobileSearchToggle?.addEventListener('click', () => {
    mobileSearchBar?.classList.toggle('hidden');
  });
}

// ==========================================
// RENDER COMPONENT FUNCTIONS
// ==========================================

// Build standard video detail modal card triggers
function registerCardPlayTriggers() {
  const cards = document.querySelectorAll('.drama-card-trigger');
  cards.forEach(card => {
    card.addEventListener('click', () => {
      const dramaId = parseInt((card as HTMLDivElement).dataset.dramaId || '1', 10);
      const drama = DRAMA_DATABASE.find(item => item.id === dramaId);
      if (drama) {
        launchVideoPlayer(drama);
      }
    });
  });
}

// Render Top 4 popular on homepage
function renderHomePopularGrid() {
  const container = document.getElementById('home-popular-grid');
  if (!container) return;

  const populars = DRAMA_DATABASE.slice(0, 4);
  let html = '';

  populars.forEach(drama => {
    html += `
      <div class="drama-card-trigger bg-cinema-card rounded-xl overflow-hidden border border-white/5 shadow-md flex flex-col justify-between group cursor-pointer hover:border-cinema-accent/35 hover:scale-[1.02] transition-all duration-300" data-drama-id="${drama.id}">
        <div class="relative aspect-[3/4] overflow-hidden">
          <img src="https://tse-mm.bing.com/th?q=${encodeURIComponent(drama.keyword)}" alt="${drama.title}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" referrerPolicy="no-referrer" />
          <span class="absolute top-2 left-2 px-1.5 py-0.5 rounded text-[10px] font-bold bg-cinema-accent text-white">今日推荐</span>
          <span class="absolute bottom-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-black/75 text-cinema-gold">★ ${drama.rating.toFixed(1)}</span>
        </div>
        <div class="p-4">
          <span class="text-[10px] text-gray-500 uppercase font-mono">${drama.genre} | ${drama.region}</span>
          <h4 class="text-sm font-bold text-white mt-0.5 truncate group-hover:text-cinema-accent transition-colors">${drama.title}</h4>
          <p class="text-[11px] text-gray-400 mt-1 line-clamp-2">${drama.description}</p>
        </div>
      </div>
    `;
  });

  container.innerHTML = html;
  registerCardPlayTriggers();
}

// Render 6 recent uploads on homepage
function renderHomeLatestGrid() {
  const container = document.getElementById('home-latest-grid');
  if (!container) return;

  const latest = DRAMA_DATABASE.slice(4, 10);
  let html = '';

  const mockTimes = ["12分钟前", "35分钟前", "1小时前", "2小时前", "5小时前", "昨天"];

  latest.forEach((drama, i) => {
    html += `
      <div class="drama-card-trigger bg-cinema-card/50 rounded-xl overflow-hidden border border-white/5 group cursor-pointer hover:border-cinema-accent/30 hover:scale-[1.02] transition-all" data-drama-id="${drama.id}">
        <div class="relative aspect-[3/4] overflow-hidden">
          <img src="https://tse-mm.bing.com/th?q=${encodeURIComponent(drama.keyword)}" alt="${drama.title}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" referrerPolicy="no-referrer" />
          <span class="absolute top-2 left-2 px-1.5 py-0.2 rounded text-[8px] font-bold bg-emerald-600 text-white">${mockTimes[i]}更新</span>
        </div>
        <div class="p-3">
          <h4 class="text-xs font-bold text-white truncate group-hover:text-cinema-accent transition-colors">${drama.title}</h4>
          <div class="flex items-center justify-between mt-1">
            <span class="text-[9px] text-gray-500">${drama.genre} · ${drama.year}</span>
            <span class="text-[10px] font-bold text-cinema-accent">${drama.rating.toFixed(1)}分</span>
          </div>
        </div>
      </div>
    `;
  });

  container.innerHTML = html;
  registerCardPlayTriggers();
}

// Filter, Sort, Paginate, and Render Product Grid
function renderProductGrid() {
  const container = document.getElementById('product-drama-grid');
  if (!container) return;

  // 1. Filtering
  let results = DRAMA_DATABASE.filter(item => {
    // Genre filter
    if (currentGenre !== 'all' && item.genre !== currentGenre) return false;
    // Region filter
    if (currentRegion !== 'all' && item.region !== currentRegion) return false;
    // Year filter
    if (currentYear !== 'all' && item.year !== parseInt(currentYear, 10)) return false;
    // Rating filter
    if (currentRating !== 'all') {
      if (currentRating === '9' && item.rating < 9.0) return false;
      if (currentRating === '8-9' && (item.rating < 8.0 || item.rating >= 9.0)) return false;
      if (currentRating === '7-8' && (item.rating < 7.0 || item.rating >= 8.0)) return false;
    }
    // Search query matching
    if (searchQuery.trim() !== '') {
      const titleMatch = item.title.toLowerCase().includes(searchQuery.toLowerCase());
      const descMatch = item.description.toLowerCase().includes(searchQuery.toLowerCase());
      if (!titleMatch && !descMatch) return false;
    }
    return true;
  });

  // 2. Sorting
  if (currentSort === 'latest') {
    // Sort by Year desc, then id desc
    results.sort((a, b) => b.year - a.year || b.id - a.id);
  } else if (currentSort === 'popular') {
    // Simulated popularity via standard hashing
    results.sort((a, b) => (b.id * 31 % 100) - (a.id * 31 % 100));
  } else if (currentSort === 'rating') {
    results.sort((a, b) => b.rating - a.rating);
  }

  // Set totals in headers
  const countSpan = document.getElementById('filtered-count');
  const totalCountSpan = document.getElementById('db-total-count');
  if (countSpan) countSpan.textContent = results.length.toString();
  if (totalCountSpan) totalCountSpan.textContent = DRAMA_DATABASE.length.toString();

  // If no results found
  if (results.length === 0) {
    container.innerHTML = `
      <div class="col-span-full py-16 flex flex-col items-center justify-center text-center">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-12 h-12 text-gray-600 mb-4">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <h4 class="text-base font-bold text-white">暂未找到符合条件的电视剧</h4>
        <p class="text-xs text-gray-500 mt-1 max-w-sm">请尝试放宽筛选类目，或者清除搜索框输入，追剧大全正在为您全力调度拉取新资源。</p>
        <button id="reset-filters-btn" class="mt-4 px-4 py-2 bg-cinema-accent hover:bg-cinema-accent-hover text-white text-xs font-semibold rounded-lg transition-colors cursor-pointer">
          重置全部筛选条件
        </button>
      </div>
    `;

    document.getElementById('reset-filters-btn')?.addEventListener('click', () => {
      resetAllFilters();
    });

    const paginationControls = document.getElementById('pagination-controls');
    if (paginationControls) paginationControls.innerHTML = '';
    
    // Hide Load More
    const loadMoreBtn = document.getElementById('load-more-btn');
    if (loadMoreBtn) loadMoreBtn.classList.add('hidden');
    return;
  }

  // 3. Pagination calculation
  const totalPages = Math.ceil(results.length / itemsPerPage);
  if (currentProductPage > totalPages) currentProductPage = totalPages;
  if (currentProductPage < 1) currentProductPage = 1;

  const startIndex = (currentProductPage - 1) * itemsPerPage;
  const paginatedResults = results.slice(startIndex, startIndex + itemsPerPage);

  // Render cards
  let html = '';
  paginatedResults.forEach(drama => {
    // Generate styled tag badges
    let tagHtml = '';
    drama.tags.slice(0, 2).forEach(tag => {
      let colorClass = 'bg-cinema-accent';
      if (tag === '免广告') colorClass = 'bg-blue-600';
      if (tag === '完结') colorClass = 'bg-emerald-600';
      tagHtml += `<span class="px-1.5 py-0.5 rounded text-[9px] font-bold ${colorClass} text-white">${tag}</span>`;
    });

    html += `
      <div class="drama-card-trigger bg-cinema-card rounded-xl overflow-hidden border border-white/5 shadow-md flex flex-col justify-between group cursor-pointer hover:border-cinema-accent/35 hover:scale-[1.02] transition-all duration-300" data-drama-id="${drama.id}">
        <div class="relative aspect-[3/4] overflow-hidden">
          <img src="https://tse-mm.bing.com/th?q=${encodeURIComponent(drama.keyword)}" alt="${drama.title}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" referrerPolicy="no-referrer" />
          <div class="absolute top-2 left-2 flex gap-1">
            ${tagHtml}
          </div>
          <span class="absolute bottom-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-black/75 text-cinema-gold">★ ${drama.rating.toFixed(1)}</span>
        </div>
        <div class="p-4">
          <span class="text-[10px] text-gray-500 uppercase font-mono">${drama.genre} | ${drama.region} | ${drama.year}年</span>
          <h4 class="text-sm font-bold text-white mt-0.5 truncate group-hover:text-cinema-accent transition-colors">${drama.title}</h4>
          <p class="text-[11px] text-gray-400 mt-1 line-clamp-2 leading-relaxed">${drama.description}</p>
        </div>
      </div>
    `;
  });

  container.innerHTML = html;
  registerCardPlayTriggers();

  // Render pagination buttons
  renderPaginationControls(totalPages);

  // Control visibility of "Load More" button
  const loadMoreBtn = document.getElementById('load-more-btn');
  if (loadMoreBtn) {
    if (currentProductPage < totalPages) {
      loadMoreBtn.classList.remove('hidden');
    } else {
      loadMoreBtn.classList.add('hidden');
    }
  }
}

// Render Paginator buttons
function renderPaginationControls(totalPages: number) {
  const container = document.getElementById('pagination-controls');
  if (!container) return;

  if (totalPages <= 1) {
    container.innerHTML = '';
    return;
  }

  let html = '';
  
  // Previous button
  html += `
    <button id="pag-prev" class="px-3 py-1.5 rounded bg-cinema-dark hover:bg-cinema-card border border-white/5 hover:border-cinema-accent/30 text-gray-300 transition-colors cursor-pointer ${currentProductPage === 1 ? 'opacity-40 pointer-events-none' : ''}">
      上一页
    </button>
  `;

  // Page Numbers
  for (let i = 1; i <= totalPages; i++) {
    const isActive = i === currentProductPage;
    html += `
      <button class="pag-num px-3 py-1.5 rounded border transition-all cursor-pointer ${isActive ? 'bg-cinema-accent text-white border-cinema-accent font-bold' : 'bg-cinema-dark hover:bg-cinema-card border-white/5 hover:border-white/10 text-gray-300'}" data-page="${i}">
        ${i}
      </button>
    `;
  }

  // Next button
  html += `
    <button id="pag-next" class="px-3 py-1.5 rounded bg-cinema-dark hover:bg-cinema-card border border-white/5 hover:border-cinema-accent/30 text-gray-300 transition-colors cursor-pointer ${currentProductPage === totalPages ? 'opacity-40 pointer-events-none' : ''}">
      下一页
    </button>
  `;

  container.innerHTML = html;

  // Bind pagination clicks
  document.getElementById('pag-prev')?.addEventListener('click', () => {
    if (currentProductPage > 1) {
      currentProductPage--;
      renderProductGrid();
      scrollToProductHeader();
    }
  });

  document.getElementById('pag-next')?.addEventListener('click', () => {
    if (currentProductPage < totalPages) {
      currentProductPage++;
      renderProductGrid();
      scrollToProductHeader();
    }
  });

  const numButtons = document.querySelectorAll('.pag-num');
  numButtons.forEach(btn => {
    btn.addEventListener('click', () => {
      currentProductPage = parseInt((btn as HTMLButtonElement).dataset.page || '1', 10);
      renderProductGrid();
      scrollToProductHeader();
    });
  });
}

function scrollToProductHeader() {
  const panel = document.getElementById('filter-panel');
  if (panel) {
    const headerOffset = 100;
    const elementPosition = panel.getBoundingClientRect().top;
    const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });
  }
}

// Render Team section on about us page
function renderTeamGrid() {
  const container = document.getElementById('team-grid');
  if (!container) return;

  let html = '';
  TEAM_MEMBERS.forEach(member => {
    html += `
      <div class="bg-cinema-dark rounded-xl p-5 border border-white/5 text-center flex flex-col justify-between items-center hover:border-cinema-accent/20 cursor-pointer group">
        <div class="w-24 h-24 rounded-full overflow-hidden mb-4 border-2 border-cinema-accent/30 group-hover:border-cinema-accent transition-colors">
          <img src="https://tse-mm.bing.com/th?q=${encodeURIComponent(member.keyword)}" alt="${member.name}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" referrerPolicy="no-referrer" />
        </div>
        <div>
          <h4 class="text-sm font-bold text-white">${member.name}</h4>
          <p class="text-[10px] text-cinema-accent font-semibold tracking-wider uppercase mt-0.5">${member.role}</p>
          <p class="text-[11px] text-gray-400 leading-relaxed mt-3">${member.bio}</p>
        </div>
      </div>
    `;
  });

  container.innerHTML = html;
}

// Reset all filter options
function resetAllFilters() {
  currentGenre = 'all';
  currentRegion = 'all';
  currentYear = 'all';
  currentRating = 'all';
  currentSort = 'latest';
  searchQuery = '';
  currentProductPage = 1;

  // Clear inputs
  const filterInput = document.getElementById('filter-search-input') as HTMLInputElement;
  const headerInput = document.getElementById('header-search-input') as HTMLInputElement;
  const mobileInput = document.getElementById('mobile-search-input') as HTMLInputElement;
  if (filterInput) filterInput.value = '';
  if (headerInput) headerInput.value = '';
  if (mobileInput) mobileInput.value = '';

  // Synchronize button active states
  const filterButtons = document.querySelectorAll('.filter-btn');
  filterButtons.forEach(btn => {
    const filterType = (btn as HTMLButtonElement).dataset.filter;
    const filterVal = (btn as HTMLButtonElement).dataset.value;
    if (filterVal === 'all') {
      btn.classList.add('bg-cinema-accent', 'text-white', 'font-medium');
      btn.classList.remove('hover:bg-white/5', 'text-gray-300');
    } else {
      btn.classList.remove('bg-cinema-accent', 'text-white', 'font-medium');
      btn.classList.add('hover:bg-white/5', 'text-gray-300');
    }
  });

  // Reset sort button states
  const sortButtons = document.querySelectorAll('.sort-btn');
  sortButtons.forEach(btn => {
    const sortVal = (btn as HTMLButtonElement).dataset.sort;
    if (sortVal === 'latest') {
      btn.classList.add('bg-cinema-accent', 'text-white');
      btn.classList.remove('text-gray-400', 'hover:text-white');
    } else {
      btn.classList.remove('bg-cinema-accent', 'text-white');
      btn.classList.add('text-gray-400', 'hover:text-white');
    }
  });

  renderProductGrid();
}

// ==========================================
// FILTERS & SEARCH SETUP
// ==========================================
function setupFilters() {
  const filterButtons = document.querySelectorAll('.filter-btn');
  filterButtons.forEach(btn => {
    btn.addEventListener('click', () => {
      const type = (btn as HTMLButtonElement).dataset.filter;
      const value = (btn as HTMLButtonElement).dataset.value;

      if (!type || !value) return;

      // Update state
      if (type === 'genre') currentGenre = value;
      if (type === 'region') currentRegion = value;
      if (type === 'year') currentYear = value;
      if (type === 'rating') currentRating = value;

      currentProductPage = 1;

      // Toggle active classes on siblings
      const rowButtons = btn.parentElement?.querySelectorAll('.filter-btn');
      rowButtons?.forEach(sib => {
        sib.classList.remove('bg-cinema-accent', 'text-white', 'font-medium');
        sib.classList.add('hover:bg-white/5', 'text-gray-300');
      });

      btn.classList.add('bg-cinema-accent', 'text-white', 'font-medium');
      btn.classList.remove('hover:bg-white/5', 'text-gray-300');

      renderProductGrid();
    });
  });

  // Sort buttons binding
  const sortButtons = document.querySelectorAll('.sort-btn');
  sortButtons.forEach(btn => {
    btn.addEventListener('click', () => {
      const sortVal = (btn as HTMLButtonElement).dataset.sort;
      if (!sortVal) return;

      currentSort = sortVal;
      currentProductPage = 1;

      sortButtons.forEach(sib => {
        sib.classList.remove('bg-cinema-accent', 'text-white');
        sib.classList.add('text-gray-400', 'hover:text-white');
      });

      btn.classList.add('bg-cinema-accent', 'text-white');
      btn.classList.remove('text-gray-400', 'hover:text-white');

      renderProductGrid();
    });
  });

  // Load more appending binding
  document.getElementById('load-more-btn')?.addEventListener('click', () => {
    currentProductPage++;
    renderProductGrid();
  });
}

function setupSearch() {
  const headerSearchInput = document.getElementById('header-search-input') as HTMLInputElement;
  const headerSearchBtn = document.getElementById('header-search-btn');
  const filterSearchInput = document.getElementById('filter-search-input') as HTMLInputElement;
  const filterSearchBtn = document.getElementById('filter-search-btn');
  const mobileSearchInput = document.getElementById('mobile-search-input') as HTMLInputElement;
  const mobileSearchBtn = document.getElementById('mobile-search-btn');
  const clearBtn = document.getElementById('filter-search-clear');

  const triggerSearch = (query: string) => {
    searchQuery = query;
    currentProductPage = 1;
    
    // Sync all inputs
    if (headerSearchInput) headerSearchInput.value = query;
    if (filterSearchInput) filterSearchInput.value = query;
    if (mobileSearchInput) mobileSearchInput.value = query;

    // Show/hide clear button on filters search
    if (clearBtn) {
      if (query.trim() !== '') {
        clearBtn.classList.remove('hidden');
      } else {
        clearBtn.classList.add('hidden');
      }
    }

    // Move to Products view to display search results
    const navProducts = document.getElementById('nav-products');
    if (navProducts) {
      navProducts.click();
    }

    renderProductGrid();
  };

  // Bind Header Search
  headerSearchBtn?.addEventListener('click', () => {
    triggerSearch(headerSearchInput.value);
  });
  headerSearchInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      triggerSearch(headerSearchInput.value);
    }
  });

  // Bind Filter Search
  filterSearchBtn?.addEventListener('click', () => {
    triggerSearch(filterSearchInput.value);
  });
  filterSearchInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      triggerSearch(filterSearchInput.value);
    }
  });

  // Bind Mobile Search
  mobileSearchBtn?.addEventListener('click', () => {
    triggerSearch(mobileSearchInput.value);
  });
  mobileSearchInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      triggerSearch(mobileSearchInput.value);
    }
  });

  // Clear Search button
  clearBtn?.addEventListener('click', () => {
    triggerSearch('');
  });
}

// Expandable accordion for enterprise news
function setupNewsInteraction() {
  const newsFeatured = document.querySelector('[alt="战略签约新闻"]')?.closest('div');
  newsFeatured?.addEventListener('click', () => {
    showCustomToast("企业新闻动态", "战略签约仪式专案：追剧大全完成北京市朝阳区影音数字版权洽谈会，获得广泛认可。");
  });
}

// ==========================================
// CUSTOM VIDEO PLAYER MODAL LOGIC
// ==========================================
function setupVideoPlayer() {
  const modal = document.getElementById('video-player-modal');
  const closeBtnOuter = document.getElementById('modal-close-outer-btn');
  const screenPlayCenterBtn = document.getElementById('screen-play-center-btn');
  const ctrlPlayBtn = document.getElementById('ctrl-play-btn');
  
  const centerPlayIcon = document.getElementById('center-play-icon');
  const centerPauseIcon = document.getElementById('center-pause-icon');
  const ctrlPlayIcon = document.getElementById('ctrl-play-icon');
  const ctrlPauseIcon = document.getElementById('ctrl-pause-icon');

  const volumeSlider = document.getElementById('volume-slider') as HTMLInputElement;
  const volumeUpIcon = document.getElementById('volume-up-icon');
  const volumeMuteIcon = document.getElementById('volume-mute-icon');

  // Hero Section "立即免费播放" binding
  const heroPlayBtn = document.getElementById('hero-play-btn');
  heroPlayBtn?.addEventListener('click', () => {
    const firstDrama = DRAMA_DATABASE[0];
    launchVideoPlayer(firstDrama);
  });

  // Close Modal
  const closeModal = () => {
    modal?.classList.add('hidden');
    pauseSimulatedPlayback();
  };

  closeBtnOuter?.addEventListener('click', closeModal);
  modal?.addEventListener('click', (e) => {
    if (e.target === modal) closeModal();
  });

  // Play/Pause toggles
  const togglePlay = () => {
    if (playerIsPlaying) {
      pauseSimulatedPlayback();
    } else {
      startSimulatedPlayback();
    }
  };

  screenPlayCenterBtn?.addEventListener('click', togglePlay);
  ctrlPlayBtn?.addEventListener('click', togglePlay);

  // Next Episode binding
  document.getElementById('ctrl-next-episode-btn')?.addEventListener('click', () => {
    if (activeEpisode < activeDrama.episodesCount) {
      playEpisode(activeEpisode + 1);
    } else {
      showCustomToast("播放提示", "当前已是本剧最后一集。每日同步最新更新中，敬请期待！");
    }
  });

  // Quality & Speed Dropdowns toggles
  const qualityBtn = document.getElementById('ctrl-quality-btn');
  const qualityDropdown = document.getElementById('quality-dropdown');
  qualityBtn?.addEventListener('click', (e) => {
    e.stopPropagation();
    qualityDropdown?.classList.toggle('hidden');
    speedDropdown?.classList.add('hidden');
  });

  const speedBtn = document.getElementById('ctrl-speed-btn');
  const speedDropdown = document.getElementById('speed-dropdown');
  speedBtn?.addEventListener('click', (e) => {
    e.stopPropagation();
    speedDropdown?.classList.toggle('hidden');
    qualityDropdown?.classList.add('hidden');
  });

  // Close dropdowns on document click
  document.addEventListener('click', () => {
    qualityDropdown?.classList.add('hidden');
    speedDropdown?.classList.add('hidden');
  });

  // Handle Quality Selection
  const qualityOptions = document.querySelectorAll('.quality-select-option');
  qualityOptions.forEach(opt => {
    opt.addEventListener('click', () => {
      const qText = (opt as HTMLButtonElement).textContent;
      if (qualityBtn && qText) {
        qualityBtn.textContent = qText;
        showCustomToast("清晰度切换成功", `极速分布式 CDN 已为您智能切换为【${qText}】专线。`);
      }
    });
  });

  // Handle Speed Selection
  const speedOptions = document.querySelectorAll('.speed-select-option');
  speedOptions.forEach(opt => {
    opt.addEventListener('click', () => {
      const sVal = (opt as HTMLButtonElement).dataset.speed;
      if (speedBtn && sVal) {
        speedBtn.textContent = sVal + 'x 倍速';
        playerPlaybackSpeed = parseFloat(sVal);
        showCustomToast("播放倍速已切换", `倍速已变更为 ${sVal}x，极速流媒体自适应就绪。`);
      }
    });
  });

  // Volume Slider Changes
  volumeSlider?.addEventListener('input', () => {
    const val = parseInt(volumeSlider.value, 10);
    if (val === 0) {
      volumeUpIcon?.classList.add('hidden');
      volumeMuteIcon?.classList.remove('hidden');
    } else {
      volumeUpIcon?.classList.remove('hidden');
      volumeMuteIcon?.classList.add('hidden');
    }
  });

  // Danmaku Toggle inside player controls
  const danmakuToggle = document.getElementById('ctrl-danmaku-toggle');
  danmakuToggle?.addEventListener('click', () => {
    danmakuIsEnabled = !danmakuIsEnabled;
    const container = document.getElementById('danmaku-container');
    if (danmakuIsEnabled) {
      container?.classList.remove('hidden');
      danmakuToggle.classList.add('text-cinema-accent');
      danmakuToggle.classList.remove('text-gray-400');
    } else {
      container?.classList.add('hidden');
      danmakuToggle.classList.remove('text-cinema-accent');
      danmakuToggle.classList.add('text-gray-400');
    }
  });

  // Danmaku Input text sending
  const danmakuInput = document.getElementById('danmaku-input') as HTMLInputElement;
  const danmakuSendBtn = document.getElementById('danmaku-send-btn');
  
  const sendNewDanmaku = () => {
    const text = danmakuInput.value.trim();
    if (text === '') return;
    
    danmakuInput.value = '';
    // Append to live floating stream
    spawnCustomDanmaku(text, true);

    // Append to scrollable Comments feed inside sidebar
    const commentsFeed = document.getElementById('player-comments-feed');
    if (commentsFeed) {
      const div = document.createElement('div');
      div.className = 'space-y-0.5 border-l-2 border-cinema-accent pl-2';
      div.innerHTML = `
        <div class="flex items-center gap-1.5 text-cinema-accent font-semibold">
          <span>我 (发送的弹幕)</span>
          <span class="text-[9px] text-gray-600 font-normal">刚刚</span>
        </div>
        <p class="text-white leading-relaxed font-medium">${text}</p>
      `;
      commentsFeed.prepend(div);
      commentsFeed.scrollTop = 0;
    }
  };

  danmakuSendBtn?.addEventListener('click', sendNewDanmaku);
  danmakuInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      sendNewDanmaku();
    }
  });

  // Timeline Click interaction
  const timelineBar = document.getElementById('player-timeline-bar');
  timelineBar?.addEventListener('click', (e) => {
    const rect = timelineBar.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const width = rect.width;
    const ratio = clickX / width;
    
    playerCurrentSeconds = Math.floor(playerTotalSeconds * ratio);
    updateTimelineUI();
  });
}

function launchVideoPlayer(drama: DramaItem) {
  activeDrama = drama;
  activeEpisode = 1;

  const modal = document.getElementById('video-player-modal');
  const titleText = document.getElementById('player-drama-title');
  const imagePoster = document.getElementById('player-screen-poster') as HTMLImageElement;
  const indicator = document.getElementById('player-episode-indicator');

  if (titleText) titleText.textContent = `正在播映：${drama.title}`;
  if (imagePoster) imagePoster.src = `https://tse-mm.bing.com/th?q=${encodeURIComponent(drama.keyword)}`;
  if (indicator) indicator.textContent = `第01集`;

  // Render episodes buttons grid
  const episodesContainer = document.getElementById('player-episodes-grid');
  if (episodesContainer) {
    let epHtml = '';
    for (let i = 1; i <= drama.episodesCount; i++) {
      epHtml += `
        <button class="player-ep-btn h-9 rounded bg-white/5 border border-white/10 text-xs font-semibold hover:border-cinema-accent text-gray-300 hover:text-white transition-all cursor-pointer ${i === 1 ? 'border-cinema-accent bg-cinema-accent/10 text-cinema-accent font-extrabold' : ''}" data-episode="${i}">
          ${i < 10 ? '0' + i : i}
        </button>
      `;
    }
    episodesContainer.innerHTML = epHtml;

    // Bind episode select click
    const epButtons = document.querySelectorAll('.player-ep-btn');
    epButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const ep = parseInt((btn as HTMLButtonElement).dataset.episode || '1', 10);
        playEpisode(ep);
      });
    });
  }

  // Open modal
  modal?.classList.remove('hidden');

  // Reset timeline
  playerCurrentSeconds = 0;
  updateTimelineUI();

  // Start playing automatically
  startSimulatedPlayback();
}

function playEpisode(epNumber: number) {
  activeEpisode = epNumber;

  const spinner = document.getElementById('player-spinner');
  const indicator = document.getElementById('player-episode-indicator');
  
  if (spinner) spinner.classList.remove('hidden');
  pauseSimulatedPlayback();

  // Highlight active episode button
  const epButtons = document.querySelectorAll('.player-ep-btn');
  epButtons.forEach(btn => {
    const bNum = parseInt((btn as HTMLButtonElement).dataset.episode || '1', 10);
    if (bNum === epNumber) {
      btn.classList.add('border-cinema-accent', 'bg-cinema-accent/10', 'text-cinema-accent', 'font-extrabold');
    } else {
      btn.classList.remove('border-cinema-accent', 'bg-cinema-accent/10', 'text-cinema-accent', 'font-extrabold');
    }
  });

  // Delay simulation to emulate cloud CDN caching
  setTimeout(() => {
    if (spinner) spinner.classList.add('hidden');
    if (indicator) indicator.textContent = `第${epNumber < 10 ? '0' + epNumber : epNumber}集`;

    playerCurrentSeconds = 0;
    updateTimelineUI();
    startSimulatedPlayback();

    showCustomToast("极速CDN节点加载成功", `已成功接入线路。您正在免广告观看：${activeDrama.title} - 第${epNumber}集。`);
  }, 900);
}

// Simulated video player ticking interval
function startSimulatedPlayback() {
  playerIsPlaying = true;

  const centerPlayIcon = document.getElementById('center-play-icon');
  const centerPauseIcon = document.getElementById('center-pause-icon');
  const ctrlPlayIcon = document.getElementById('ctrl-play-icon');
  const ctrlPauseIcon = document.getElementById('ctrl-pause-icon');

  centerPlayIcon?.classList.add('hidden');
  centerPauseIcon?.classList.remove('hidden');
  ctrlPlayIcon?.classList.add('hidden');
  ctrlPauseIcon?.classList.remove('hidden');

  if (playerTimelineInterval) clearInterval(playerTimelineInterval);

  playerTimelineInterval = setInterval(() => {
    playerCurrentSeconds += Math.round(1 * playerPlaybackSpeed);
    if (playerCurrentSeconds >= playerTotalSeconds) {
      playerCurrentSeconds = playerTotalSeconds;
      pauseSimulatedPlayback();
      showCustomToast("播放完毕", "当前集数已播放完毕。正在智能加载下一集...");
      
      // Auto transition next episode
      setTimeout(() => {
        if (activeEpisode < activeDrama.episodesCount) {
          playEpisode(activeEpisode + 1);
        }
      }, 2000);
    }
    updateTimelineUI();
  }, 1000);
}

function pauseSimulatedPlayback() {
  playerIsPlaying = false;

  const centerPlayIcon = document.getElementById('center-play-icon');
  const centerPauseIcon = document.getElementById('center-pause-icon');
  const ctrlPlayIcon = document.getElementById('ctrl-play-icon');
  const ctrlPauseIcon = document.getElementById('ctrl-pause-icon');

  centerPlayIcon?.classList.remove('hidden');
  centerPauseIcon?.classList.add('hidden');
  ctrlPlayIcon?.classList.remove('hidden');
  ctrlPauseIcon?.classList.add('hidden');

  if (playerTimelineInterval) {
    clearInterval(playerTimelineInterval);
    playerTimelineInterval = null;
  }
}

function updateTimelineUI() {
  const currentSpan = document.getElementById('player-time-current');
  const totalSpan = document.getElementById('player-time-total');
  const progressBar = document.getElementById('player-timeline-progress');
  const progressKnob = document.getElementById('player-timeline-knob');

  const formatTime = (secs: number) => {
    const mins = Math.floor(secs / 60);
    const remainingSecs = secs % 60;
    return `${mins < 10 ? '0' + mins : mins}:${remainingSecs < 10 ? '0' + remainingSecs : remainingSecs}`;
  };

  if (currentSpan) currentSpan.textContent = formatTime(playerCurrentSeconds);
  if (totalSpan) totalSpan.textContent = formatTime(playerTotalSeconds);

  const percentage = (playerCurrentSeconds / playerTotalSeconds) * 100;
  if (progressBar) progressBar.style.width = `${percentage}%`;
  if (progressKnob) progressKnob.style.left = `${percentage}%`;
}

// Spawns a floating bullet text across player screen
function spawnCustomDanmaku(text: string, isUser = false) {
  const container = document.getElementById('danmaku-container');
  if (!container || !danmakuIsEnabled) return;

  const bullet = document.createElement('div');
  bullet.className = `absolute whitespace-nowrap text-xs px-3 py-1 rounded-full animate-danmaku select-none font-medium text-white shadow-md transition-transform ${isUser ? 'border border-cinema-accent/60 bg-cinema-accent text-white font-extrabold z-15 scale-105' : 'bg-black/60 text-gray-200'}`;
  bullet.textContent = text;

  // Determine randomized floating vertical rows (5 main levels)
  const rowsCount = 6;
  const randomRow = Math.floor(Math.random() * rowsCount);
  const rowHeightPercentage = (85 / rowsCount) * randomRow + 5; // offset top and bottom margins

  bullet.style.top = `${rowHeightPercentage}%`;
  
  // Custom velocity speed to make overlapping comments rhythmic
  const randomDuration = Math.random() * 6 + 10; // between 10s and 16s
  bullet.style.animationDuration = `${randomDuration}s`;

  container.appendChild(bullet);

  // Auto clean up element
  bullet.addEventListener('animationend', () => {
    bullet.remove();
  });
}

// Generate recurring mock bullets to simulate an active visual auditorium
function startAutonomousDanmaku() {
  const pool = [
    "第一集太震撼了！真4K画质！",
    "追剧大全这网站太良心了，支持！",
    "卧槽，高燃科幻大片，配音绝了！",
    "等了很久了，今日更新非常同步！",
    "古装戏探案神都洛阳好看",
    "无弹窗无广告，真的是终身免费！已加标签收藏",
    "细节拉满，这片子值得推荐给朋友",
    "在线观看极速秒开啊，牛逼！",
    "女主古装造型真好看，我爱了！",
    "有没有老哥推荐一下第三集剧情怎么样",
    "向阳而生这部职场剧很治愈，给追剧大全点赞",
    "速度与激情极速赛车那个片段燃炸了！"
  ];

  setInterval(() => {
    if (playerIsPlaying && danmakuIsEnabled) {
      const text = pool[Math.floor(Math.random() * pool.length)];
      spawnCustomDanmaku(text, false);
    }
  }, 2200);
}

// ==========================================
// CONTACT FORM SUBMISSION
// ==========================================
function setupContactForm() {
  const form = document.getElementById('contact-feedback-form');
  const submitBtn = document.getElementById('form-submit-btn');

  form?.addEventListener('submit', (e) => {
    e.preventDefault();

    const name = (document.getElementById('form-name') as HTMLInputElement).value;
    const contact = (document.getElementById('form-contact') as HTMLInputElement).value;
    const category = (document.getElementById('form-category') as HTMLSelectElement).value;
    const message = (document.getElementById('form-message') as HTMLInputElement).value;

    let categoryText = "意见建议反馈";
    if (category === 'bd') categoryText = "版权采购与商务合作";
    if (category === 'tech') categoryText = "播放卡顿技术纠错";
    if (category === 'complaint') categoryText = "不良侵权极速投诉";

    if (submitBtn) {
      submitBtn.setAttribute('disabled', 'true');
      submitBtn.innerHTML = `
        <div class="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin mr-2"></div>
        <span>中枢安全加密上传中...</span>
      `;
    }

    // Simulate database secure post back
    setTimeout(() => {
      if (submitBtn) {
        submitBtn.removeAttribute('disabled');
        submitBtn.innerHTML = `
          <span>提交反馈至客服中枢</span>
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M14 5l7 7m0 0l-7 7m7-7H3" />
          </svg>
        `;
      }

      // Show customized popup
      showDetailedSuccessToast(
        "您的申诉已接收完成",
        `尊敬的 ${name}。我们已将您的【${categoryText}】安全送达北京无限视界数字合规审查系统。处理流水号: A${Date.now().toString().slice(-6)}。我们承诺在最高2小时内（侵权纠纷）予以处理答复。联系人邮箱已登记为: ${contact}。`
      );

      // Reset form
      (form as HTMLFormElement).reset();
    }, 1200);
  });
}

// ==========================================
// INTERACTIVE CDN MAP LOGIC
// ==========================================
function setupCDNMap() {
  const nodeMarkers = document.querySelectorAll('.cdn-node-marker');
  const tooltip = document.getElementById('cdn-tooltip');

  const nodesData: Record<string, { title: string, stat: string, ping: string, load: string, location: string }> = {
    bj: {
      title: "北京总部 CDN 总调度中心",
      stat: "● 状态优良",
      ping: "8ms",
      load: "14%",
      location: "39.9° N, 116.4° E | 当前主干吞吐: 2.4Tbps"
    },
    sh: {
      title: "华东上海分布式 CDN 镜像矩阵",
      stat: "● 极速播映",
      ping: "12ms",
      load: "28%",
      location: "31.2° N, 121.4° E | 当前边缘带宽: 1.8Tbps"
    },
    sz: {
      title: "华南深圳万兆接入核心骨干节点",
      stat: "● 高速缓存",
      ping: "14ms",
      load: "19%",
      location: "22.5° N, 114.0° E | 当前并发峰值: 35万流"
    },
    cd: {
      title: "西南成都负载均衡节点服务器机房",
      stat: "● 稳健运行",
      ping: "18ms",
      load: "8%",
      location: "30.5° N, 104.0° E | 当前路由健康率: 99.9%"
    }
  };

  nodeMarkers.forEach(marker => {
    marker.addEventListener('mouseenter', () => {
      const code = (marker as SVGElement).dataset.node || 'bj';
      const info = nodesData[code];
      
      if (tooltip && info) {
        tooltip.innerHTML = `
          <p class="font-bold text-white flex justify-between items-center">
            <span>${info.title}</span>
            <span class="text-green-400 font-semibold">${info.stat}</span>
          </p>
          <p class="text-[9px] text-gray-500">${info.location}</p>
          <p class="text-[10px] text-gray-300">骨干分发延时: <strong class="text-cinema-accent">${info.ping}</strong> | 核心节点负载: ${info.load}</p>
        `;
        tooltip.classList.remove('opacity-0');
      }
    });

    marker.addEventListener('click', () => {
      const code = (marker as SVGElement).dataset.node || 'bj';
      const info = nodesData[code];
      if (info) {
        showCustomToast("CDN调度成功", `播放线路已重定向至【${info.title}】加速主干节点。实时延时：${info.ping}。`);
      }
    });
  });
}

// ==========================================
// FLOATING AI CHAT BOT HELPDESK SYSTEM
// ==========================================
function setupChatbot() {
  const launcher = document.getElementById('chat-widget-launcher-btn');
  const chatPanel = document.getElementById('chat-panel');
  const closeBtn = document.getElementById('chat-panel-close-btn');
  const msgInput = document.getElementById('chat-message-input') as HTMLInputElement;
  const sendBtn = document.getElementById('chat-message-send-btn');
  const history = document.getElementById('chat-history-container');

  // Toggle Panel open/close
  launcher?.addEventListener('click', () => {
    const isClosed = chatPanel?.classList.contains('pointer-events-none');
    if (isClosed) {
      chatPanel?.classList.remove('pointer-events-none', 'opacity-0', 'scale-95');
      chatPanel?.classList.add('opacity-100', 'scale-100');
    } else {
      chatPanel?.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
      chatPanel?.classList.remove('opacity-100', 'scale-100');
    }
  });

  closeBtn?.addEventListener('click', () => {
    chatPanel?.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
    chatPanel?.classList.remove('opacity-100', 'scale-100');
  });

  const appendMessage = (sender: 'user' | 'ai', text: string) => {
    if (!history) return;

    const msgBlock = document.createElement('div');
    msgBlock.className = `flex items-start gap-2.5 ${sender === 'user' ? 'justify-end' : ''}`;

    if (sender === 'ai') {
      msgBlock.innerHTML = `
        <div class="w-6 h-6 rounded-full bg-cinema-accent flex items-center justify-center text-white shrink-0 text-[10px]">AI</div>
        <div class="bg-white/5 border border-white/5 p-3 rounded-2xl rounded-tl-none text-gray-300 leading-relaxed max-w-[85%] whitespace-pre-line">
          ${text}
        </div>
      `;
    } else {
      msgBlock.innerHTML = `
        <div class="bg-cinema-accent p-3 rounded-2xl rounded-tr-none text-white leading-relaxed max-w-[85%] whitespace-pre-line font-medium">
          ${text}
        </div>
        <div class="w-6 h-6 rounded-full bg-cinema-card border border-white/15 flex items-center justify-center text-white shrink-0 text-[10px]">我</div>
      `;
    }

    history.appendChild(msgBlock);
    history.scrollTop = history.scrollHeight;
  };

  const getSmartReply = (userText: string) => {
    const query = userText.trim();
    
    // Check key phrases matches
    if (query.includes("为什么") || query.includes("免费") || query.includes("广告")) {
      return FAQ_RESPONSES["为什么免费且免广告？"];
    }
    if (query.includes("卡") || query.includes("加载") || query.includes("慢") || query.includes("缓冲")) {
      return FAQ_RESPONSES["视频卡顿/黑屏怎么办？"];
    }
    if (query.includes("合作") || query.includes("版权") || query.includes("加盟") || query.includes("合作邮箱")) {
      return FAQ_RESPONSES["如何加入剧集资源合作？"];
    }
    if (query.includes("古装") || query.includes("推荐") || query.includes("好看") || query.includes("科幻") || query.includes("悬疑")) {
      let genreQuery = '古装';
      if (query.includes("科幻")) genreQuery = '科幻';
      if (query.includes("悬疑")) genreQuery = '悬疑';
      if (query.includes("都市")) genreQuery = '都市';

      const rec = DRAMA_DATABASE.find(d => d.genre === genreQuery) || DRAMA_DATABASE[0];
      return `【小追专属剧集推荐】🎬\n既然您提到相关兴趣，为您极力推荐热播好剧：\n《${rec.title}》\n题材分类：${rec.genre} | 评分：★ ${rec.rating.toFixed(1)}\n简介：${rec.description}\n\n您可直接在顶部检索框搜索该片，享受全网唯一终身免费1080P免片头广告播放！`;
    }

    return `您咨询的关于：“${query}”的信息，小追已为您登记记录。如果您在使用播放器过程中遇到了视频卡顿报错，请在视频下方点击切换其他的“CDN极速镜像专线”；如果是侵权纠纷，请发送书面侵权主张函至：ts@zhuijudaquan.com，我们将由首席合规内容采购官为您极速办结。`;
  };

  const handleUserMessage = (text: string) => {
    if (text.trim() === '') return;

    appendMessage('user', text);

    // Typing simulated indicator dot
    const typingDot = document.createElement('div');
    typingDot.id = 'ai-typing-indicator';
    typingDot.className = 'flex items-center gap-1 bg-white/5 p-3 rounded-2xl max-w-[80px] justify-center ml-8';
    typingDot.innerHTML = `
      <span class="w-1.5 h-1.5 rounded-full bg-cinema-accent animate-bounce" style="animation-delay: 0.1s"></span>
      <span class="w-1.5 h-1.5 rounded-full bg-cinema-accent animate-bounce" style="animation-delay: 0.2s"></span>
      <span class="w-1.5 h-1.5 rounded-full bg-cinema-accent animate-bounce" style="animation-delay: 0.3s"></span>
    `;
    history?.appendChild(typingDot);
    if (history) history.scrollTop = history.scrollHeight;

    setTimeout(() => {
      typingDot.remove();
      const answer = getSmartReply(text);
      appendMessage('ai', answer);
    }, 1100);
  };

  // Bind Quick chip buttons
  const chips = document.querySelectorAll('.chat-chip');
  chips.forEach(chip => {
    chip.addEventListener('click', () => {
      const q = (chip as HTMLButtonElement).dataset.question || '';
      handleUserMessage(q);
    });
  });

  // Bind Custom Input message send
  const triggerCustomMsgSend = () => {
    const val = msgInput.value;
    if (val.trim() === '') return;
    msgInput.value = '';
    handleUserMessage(val);
  };

  sendBtn?.addEventListener('click', triggerCustomMsgSend);
  msgInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      triggerCustomMsgSend();
    }
  });
}

// ==========================================
// TOAST POPUPS NOTIFICATION SYSTEMS
// ==========================================
function showCustomToast(title: string, message: string) {
  const toast = document.getElementById('success-toast');
  const tTitle = document.getElementById('success-toast-title');
  const tMsg = document.getElementById('success-toast-message');

  if (tTitle) tTitle.textContent = title;
  if (tMsg) tMsg.textContent = message;

  if (toast) {
    toast.classList.remove('hidden');
    // Force transition fade in
    setTimeout(() => {
      toast.classList.add('opacity-100');
    }, 50);

    // Auto close
    setTimeout(() => {
      toast.classList.remove('opacity-100');
      setTimeout(() => {
        toast.classList.add('hidden');
      }, 300);
    }, 4000);
  }
}

function showDetailedSuccessToast(title: string, message: string) {
  const toast = document.getElementById('success-toast');
  const tTitle = document.getElementById('success-toast-title');
  const tMsg = document.getElementById('success-toast-message');

  if (tTitle) tTitle.textContent = title;
  if (tMsg) tMsg.textContent = message;

  if (toast) {
    toast.classList.remove('hidden');
    toast.classList.add('opacity-100');
    // Remains active slightly longer for detailed feedback letters
    setTimeout(() => {
      toast.classList.remove('opacity-100');
      setTimeout(() => {
        toast.classList.add('hidden');
      }, 300);
    }, 9000);
  }
}
