'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { 
  Shield, Key, PlusCircle, RefreshCw, Trash2, List, 
  Tv, Server, FileText, CheckCircle2, AlertTriangle, 
  Lock, LogOut, ExternalLink, Play, Eye, Download, Upload, Check,
  Palette, Sparkles, Image as ImageIcon, ArrowLeftRight, Users, Activity,
  Edit3, X, CheckSquare, Square, FolderEdit, RotateCcw
} from 'lucide-react';
import { savePlaylistToDevice } from '@/lib/playlistStorage';

const STANDARD_CATEGORIES = [
  'Bangla Entertainment',
  'Bangla News',
  'Indian Bangla',
  'Hindi Entertainment',
  'Hindi Movies',
  'Sports Live',
  'Kids & Cartoons',
  'Documentary & Science',
  'Music & Lifestyle',
  'Islamic & Spiritual',
  'English News',
  'General'
];

export default function AdminPage() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [checkingAuth, setCheckingAuth] = useState(true);
  const [loginPassword, setLoginPassword] = useState('');
  const [authError, setAuthError] = useState('');

  const [activeTab, setActiveTab] = useState('channels'); // 'channels', 'add-playlist', 'playlists', 'settings'
  const [playlists, setPlaylists] = useState([]);
  const [channels, setChannels] = useState([]);
  const [categories, setCategories] = useState([]);
  const [liveVisitors, setLiveVisitors] = useState(1);
  const [totalVisitors, setTotalVisitors] = useState(1);
  const [customTotalVisitors, setCustomTotalVisitors] = useState('1');
  const [updatingVisitors, setUpdatingVisitors] = useState(false);
  const [loading, setLoading] = useState(false);
  const [notification, setNotification] = useState(null);

  // Form State: Add Playlist
  const [playlistType, setPlaylistType] = useState('url'); // 'url', 'xtream', 'file'
  const [playlistName, setPlaylistName] = useState('');
  const [playlistUrl, setPlaylistUrl] = useState('');
  const [xtreamServer, setXtreamServer] = useState('');
  const [xtreamUser, setXtreamUser] = useState('');
  const [xtreamPass, setXtreamPass] = useState('');
  const [fileContent, setFileContent] = useState('');

  // Form State: Add Single Channel
  const [singleName, setSingleName] = useState('');
  const [singleCategory, setSingleCategory] = useState('');
  const [singleUrl, setSingleUrl] = useState('');
  const [singleLogo, setSingleLogo] = useState('');
  const [singleLogoUploading, setSingleLogoUploading] = useState(false);

  // Form State: Edit Channel Modal
  const [editingChannel, setEditingChannel] = useState(null);
  const [editName, setEditName] = useState('');
  const [editCategory, setEditCategory] = useState('');
  const [editCustomCategory, setEditCustomCategory] = useState('');
  const [editLogo, setEditLogo] = useState('');
  const [editStreamUrl, setEditStreamUrl] = useState('');
  const [isUploadingEditLogo, setIsUploadingEditLogo] = useState(false);
  const [savingChannel, setSavingChannel] = useState(false);

  // Form State: Batch Selection & Category Update
  const [selectedChannelIds, setSelectedChannelIds] = useState([]);
  const [batchCategory, setBatchCategory] = useState('');
  const [batchApplying, setBatchApplying] = useState(false);

  // Form State: Change Password
  const [newPassword, setNewPassword] = useState('');

  // Filter channels in admin view
  const [channelSearch, setChannelSearch] = useState('');

  // Form State: FTP Server & App Upload
  const [ftpServerUrl, setFtpServerUrl] = useState('');
  const [appInfo, setAppInfo] = useState(null);
  const [appFile, setAppFile] = useState(null);
  const [appVersion, setAppVersion] = useState('1.0.0');
  const [savingFtp, setSavingFtp] = useState(false);
  const [uploadingApp, setUploadingApp] = useState(false);

  // Form State: Logo, Branding & Dynamic Site Theme
  const [siteName, setSiteName] = useState('TN TV');
  const [logoUrl, setLogoUrl] = useState('/images/logo.png');
  const [logoPreview, setLogoPreview] = useState('/images/logo.png');
  const [primaryColor, setPrimaryColor] = useState('#ff5500');
  const [secondaryColor, setSecondaryColor] = useState('#ff9900');
  const [logoFile, setLogoFile] = useState(null);
  const [savingTheme, setSavingTheme] = useState(false);
  const [extractedColors, setExtractedColors] = useState([]);

  // Form State: Video Screen Logo / Watermark
  const [screenLogoEnabled, setScreenLogoEnabled] = useState(true);
  const [screenLogoUrl, setScreenLogoUrl] = useState('/watermark.png');
  const [screenLogoPreview, setScreenLogoPreview] = useState('/watermark.png');
  const [screenLogoOpacity, setScreenLogoOpacity] = useState(0.85);
  const [screenLogoPosition, setScreenLogoPosition] = useState('top-right');
  const [screenLogoSize, setScreenLogoSize] = useState(130);
  const [screenLogoFile, setScreenLogoFile] = useState(null);
  const [savingScreenLogo, setSavingScreenLogo] = useState(false);

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

  const notify = (msg, type = 'success') => {
    setNotification({ msg, type });
    setTimeout(() => setNotification(null), 4500);
  };

  const checkAuthStatus = async () => {
    try {
      setCheckingAuth(true);
      const res = await fetch('/api/auth');
      const data = await res.json();
      setIsAuthenticated(Boolean(data.authenticated));
      if (data.authenticated) {
        loadAdminData();
      }
    } catch {
      setIsAuthenticated(false);
    } finally {
      setCheckingAuth(false);
    }
  };

  const loadAdminData = async () => {
    setLoading(true);
    try {
      const [plRes, chRes, setRes, visRes] = await Promise.all([
        fetch('/api/playlists'),
        fetch('/api/channels'),
        fetch('/api/settings'),
        fetch('/api/visitors')
      ]);
      const plData = await plRes.json();
      const chData = await chRes.json();
      const setData = await setRes.json();
      const visData = visRes.ok ? await visRes.json() : null;

      setPlaylists(plData.playlists || []);
      const chList = chData.channels || [];
      setChannels(chList);
      const catList = chData.categories || [];
      setCategories(catList);
      if (chList.length > 0) {
        savePlaylistToDevice(chList, catList);
      }
      setFtpServerUrl(setData.ftpUrl || '');
      setAppInfo(setData.appInfo || null);
      if (visData) {
        if (typeof visData.liveVisitors === 'number') setLiveVisitors(visData.liveVisitors);
        if (typeof visData.totalVisitors === 'number') {
          setTotalVisitors(visData.totalVisitors);
          setCustomTotalVisitors(String(visData.totalVisitors));
        }
      }
      if (setData.siteName) setSiteName(setData.siteName);
      if (setData.logoUrl) {
        setLogoUrl(setData.logoUrl);
        setLogoPreview(setData.logoUrl);
        extractColorsFromImage(setData.logoUrl, false);
      } else {
        setLogoUrl('');
        setLogoPreview('');
      }
      if (setData.primaryColor) setPrimaryColor(setData.primaryColor);
      if (setData.secondaryColor) setSecondaryColor(setData.secondaryColor);
      if (setData.screenLogoEnabled !== undefined) setScreenLogoEnabled(Boolean(setData.screenLogoEnabled));
      if (setData.screenLogoUrl) {
        setScreenLogoUrl(setData.screenLogoUrl);
        setScreenLogoPreview(setData.screenLogoUrl);
      } else {
        setScreenLogoUrl('/watermark.png');
        setScreenLogoPreview('/watermark.png');
      }
      if (typeof setData.screenLogoOpacity === 'number') setScreenLogoOpacity(setData.screenLogoOpacity);
      if (setData.screenLogoPosition) setScreenLogoPosition(setData.screenLogoPosition);
      if (typeof setData.screenLogoSize === 'number') setScreenLogoSize(setData.screenLogoSize);
    } catch (err) {
      notify('Failed to load data: ' + err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  // Real-time live visitor polling every 5 seconds when authenticated
  useEffect(() => {
    if (!isAuthenticated) return;
    const interval = setInterval(async () => {
      try {
        const res = await fetch('/api/visitors');
        if (res.ok) {
          const data = await res.json();
          if (typeof data.liveVisitors === 'number') setLiveVisitors(data.liveVisitors);
          if (typeof data.totalVisitors === 'number') setTotalVisitors(data.totalVisitors);
        }
      } catch (err) {}
    }, 5000);
    return () => clearInterval(interval);
  }, [isAuthenticated]);

  const handleLogin = async (e) => {
    e.preventDefault();
    setAuthError('');
    try {
      const res = await fetch('/api/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: loginPassword })
      });
      const data = await res.json();
      if (res.ok) {
        setIsAuthenticated(true);
        loadAdminData();
      } else {
        setAuthError(data.error || 'Login failed');
      }
    } catch (err) {
      setAuthError('Connection error: ' + err.message);
    }
  };

  const handleLogout = async () => {
    await fetch('/api/auth', { method: 'DELETE' });
    setIsAuthenticated(false);
    setLoginPassword('');
  };

  const handleAddPlaylist = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const payload = {
        name: playlistName,
        type: playlistType,
        url: playlistUrl,
        xtreamServer,
        xtreamUser,
        xtreamPass,
        content: fileContent
      };

      const res = await fetch('/api/playlists', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();

      if (res.ok) {
        notify(data.message || 'Playlist added successfully!');
        if (data.warning) notify(data.warning, 'error');
        // Reset form
        setPlaylistName('');
        setPlaylistUrl('');
        setXtreamServer('');
        setXtreamUser('');
        setXtreamPass('');
        setFileContent('');
        loadAdminData();
        setActiveTab('playlists');
      } else {
        notify(data.error || 'Failed to add playlist', 'error');
      }
    } catch (err) {
      notify('Error adding playlist: ' + err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleFileUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (event) => {
      setFileContent(event.target.result);
      if (!playlistName) {
        setPlaylistName(file.name.replace(/\.[^/.]+$/, ''));
      }
    };
    reader.readAsText(file);
  };

  const handleSyncPlaylist = async (id) => {
    setLoading(true);
    try {
      const res = await fetch('/api/playlists/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id })
      });
      const data = await res.json();
      if (res.ok) {
        notify(data.message);
        loadAdminData();
      } else {
        notify(data.error || 'Sync failed', 'error');
      }
    } catch (err) {
      notify('Sync error: ' + err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleDeletePlaylist = async (id, name) => {
    if (!confirm(`Are you sure you want to delete playlist "${name}" and all its channels?`)) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/playlists?id=${id}`, { method: 'DELETE' });
      if (res.ok) {
        notify('Playlist deleted');
        loadAdminData();
      } else {
        const data = await res.json();
        notify(data.error || 'Delete failed', 'error');
      }
    } catch (err) {
      notify('Delete error: ' + err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleAddSingleChannel = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/channels', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: singleName,
          category: singleCategory || 'General',
          streamUrl: singleUrl,
          logo: singleLogo
        })
      });
      const data = await res.json();
      if (res.ok) {
        notify('Channel added successfully!');
        setSingleName('');
        setSingleCategory('');
        setSingleUrl('');
        setSingleLogo('');
        loadAdminData();
      } else {
        notify(data.error || 'Failed to add channel', 'error');
      }
    } catch (err) {
      notify('Error: ' + err.message, 'error');
    }
  };

  const handleDeleteChannel = async (id, name) => {
    if (!confirm(`Delete channel "${name}"?`)) return;
    try {
      const res = await fetch(`/api/channels/${id}`, { method: 'DELETE' });
      if (res.ok) {
        notify('Channel deleted');
        loadAdminData();
      }
    } catch (err) {
      notify('Failed to delete channel', 'error');
    }
  };

  const handleAutoCategorize = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/channels/auto-categorize', { method: 'POST' });
      const data = await res.json();
      if (res.ok) {
        notify(data.message || 'Channels categorized successfully!');
        loadAdminData();
      } else {
        notify(data.error || 'Auto-categorization failed', 'error');
      }
    } catch (err) {
      notify('Categorization error: ' + err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  // Channel filtering & distinct categories
  const filteredChannels = channels.filter(c =>
    c.name.toLowerCase().includes(channelSearch.toLowerCase()) ||
    (c.category && c.category.toLowerCase().includes(channelSearch.toLowerCase()))
  );

  const distinctCategories = Array.from(new Set([
    ...STANDARD_CATEGORIES,
    ...categories.filter(c => c && c !== 'All'),
    ...channels.map(c => c.category).filter(Boolean)
  ]));

  const openEditModal = (ch) => {
    setEditingChannel(ch);
    setEditName(ch.name || '');
    if (ch.category && distinctCategories.includes(ch.category)) {
      setEditCategory(ch.category);
      setEditCustomCategory('');
    } else if (ch.category) {
      setEditCategory('__custom__');
      setEditCustomCategory(ch.category);
    } else {
      setEditCategory('General');
      setEditCustomCategory('');
    }
    setEditLogo(ch.logo || '');
    setEditStreamUrl(ch.streamUrl || '');
  };

  const closeEditModal = () => {
    setEditingChannel(null);
    setEditName('');
    setEditCategory('');
    setEditCustomCategory('');
    setEditLogo('');
    setEditStreamUrl('');
  };

  const handleSaveEditedChannel = async (e) => {
    if (e) e.preventDefault();
    if (!editingChannel) return;
    setSavingChannel(true);

    const finalCategory = (editCategory === '__custom__' ? editCustomCategory : editCategory) || 'General';

    try {
      const res = await fetch(`/api/channels/${editingChannel.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...editingChannel,
          name: editName.trim() || editingChannel.name,
          category: finalCategory.trim(),
          logo: editLogo.trim(),
          streamUrl: editStreamUrl.trim() || editingChannel.streamUrl
        })
      });

      if (res.ok) {
        notify(`Channel "${editName || editingChannel.name}" updated successfully!`);
        closeEditModal();
        loadAdminData();
      } else {
        const data = await res.json();
        notify(data.error || 'Failed to update channel', 'error');
      }
    } catch (err) {
      notify('Update error: ' + err.message, 'error');
    } finally {
      setSavingChannel(false);
    }
  };

  const handleUploadChannelLogo = async (file, isSingleForm = false) => {
    if (!file) return;
    if (isSingleForm) {
      setSingleLogoUploading(true);
    } else {
      setIsUploadingEditLogo(true);
    }

    try {
      const formData = new FormData();
      formData.append('file', file);
      if (!isSingleForm && editingChannel?.id) {
        formData.append('channelId', editingChannel.id);
      }

      const res = await fetch('/api/channels/upload-logo', {
        method: 'POST',
        body: formData
      });
      const data = await res.json();

      if (res.ok && data.logoUrl) {
        if (isSingleForm) {
          setSingleLogo(data.logoUrl);
        } else {
          setEditLogo(data.logoUrl);
        }
        notify('Channel logo uploaded successfully!');
      } else {
        notify(data.error || 'Failed to upload logo', 'error');
      }
    } catch (err) {
      notify('Upload error: ' + err.message, 'error');
    } finally {
      if (isSingleForm) {
        setSingleLogoUploading(false);
      } else {
        setIsUploadingEditLogo(false);
      }
    }
  };

  const handleInlineCategoryChange = async (channelId, newCategory) => {
    if (!newCategory) return;
    try {
      const ch = channels.find(c => c.id === channelId);
      if (!ch) return;
      const res = await fetch(`/api/channels/${channelId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...ch,
          category: newCategory
        })
      });
      if (res.ok) {
        notify(`Updated "${ch.name}" category to "${newCategory}"`);
        setChannels(prev => prev.map(c => c.id === channelId ? { ...c, category: newCategory } : c));
      } else {
        notify('Failed to update category', 'error');
      }
    } catch (err) {
      notify('Error updating category: ' + err.message, 'error');
    }
  };

  const handleBatchCategoryChange = async () => {
    if (selectedChannelIds.length === 0) {
      notify('No channels selected', 'error');
      return;
    }
    if (!batchCategory) {
      notify('Please select a category to apply', 'error');
      return;
    }

    setBatchApplying(true);
    try {
      const res = await fetch('/api/channels', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          channelIds: selectedChannelIds,
          category: batchCategory
        })
      });
      const data = await res.json();
      if (res.ok) {
        notify(data.message || `Updated ${selectedChannelIds.length} channels`);
        setSelectedChannelIds([]);
        setBatchCategory('');
        loadAdminData();
      } else {
        notify(data.error || 'Failed to update channels', 'error');
      }
    } catch (err) {
      notify('Batch update error: ' + err.message, 'error');
    } finally {
      setBatchApplying(false);
    }
  };

  const toggleSelectAllChannels = () => {
    if (selectedChannelIds.length === filteredChannels.length) {
      setSelectedChannelIds([]);
    } else {
      setSelectedChannelIds(filteredChannels.map(c => c.id));
    }
  };

  const toggleSelectChannel = (id) => {
    setSelectedChannelIds(prev => 
      prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]
    );
  };

  const handleSaveFtp = async (e) => {
    e.preventDefault();
    setSavingFtp(true);
    try {
      const res = await fetch('/api/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ftpUrl: ftpServerUrl })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update FTP URL');
      setFtpServerUrl(data.ftpUrl || '');
      notify('FTP Server URL updated successfully!');
    } catch (err) {
      notify(err.message, 'error');
    } finally {
      setSavingFtp(false);
    }
  };

  const handleUploadApp = async (e) => {
    e.preventDefault();
    if (!appFile) {
      notify('Please select an application file (.apk, .zip, etc.) to upload', 'error');
      return;
    }
    setUploadingApp(true);
    try {
      const formData = new FormData();
      formData.append('file', appFile);
      formData.append('version', appVersion);

      const res = await fetch('/api/upload-app', {
        method: 'POST',
        body: formData
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to upload app');
      setAppInfo(data.appInfo);
      setAppFile(null);
      const inputEl = document.getElementById('app-file-input');
      if (inputEl) inputEl.value = '';
      notify('Application uploaded and activated successfully!');
    } catch (err) {
      notify(err.message, 'error');
    } finally {
      setUploadingApp(false);
    }
  };

  const handleDeleteApp = async () => {
    if (!confirm('Are you sure you want to delete the uploaded app? Users will no longer be able to download it.')) {
      return;
    }
    try {
      const res = await fetch('/api/upload-app', { method: 'DELETE' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to delete app');
      setAppInfo(null);
      notify('Application removed successfully');
    } catch (err) {
      notify(err.message, 'error');
    }
  };

  const handleSwapColors = () => {
    const temp = primaryColor;
    setPrimaryColor(secondaryColor);
    setSecondaryColor(temp);
    notify(`Swapped colors! Primary is now ${secondaryColor}`);
  };

  const extractColorsFromImage = (imageSrc, autoApply = true) => {
    if (!imageSrc) return;
    const img = new Image();
    // Only set crossOrigin if it is an external URL on another origin
    if (typeof window !== 'undefined' && imageSrc.startsWith('http') && !imageSrc.startsWith(window.location.origin)) {
      img.crossOrigin = 'Anonymous';
    }
    img.onload = () => {
      try {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const maxDim = 150;
        let w = img.width || maxDim;
        let h = img.height || maxDim;
        if (w > maxDim || h > maxDim) {
          if (w > h) {
            h = Math.round((h * maxDim) / w);
            w = maxDim;
          } else {
            w = Math.round((w * maxDim) / h);
            h = maxDim;
          }
        }
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(img, 0, 0, w, h);
        const imgData = ctx.getImageData(0, 0, w, h).data;

        const toHex = (n) => Math.min(255, Math.max(0, Math.round(n))).toString(16).padStart(2, '0');
        const rgbToHex = (r, g, b) => `#${toHex(r)}${toHex(g)}${toHex(b)}`;

        const rgbToHsl = (r, g, b) => {
          const rN = r / 255, gN = g / 255, bN = b / 255;
          const max = Math.max(rN, gN, bN), min = Math.min(rN, gN, bN);
          let h = 0, s = 0, l = (max + min) / 2;
          if (max !== min) {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
              case rN: h = ((gN - bN) / d + (gN < bN ? 6 : 0)) / 6; break;
              case gN: h = ((bN - rN) / d + 2) / 6; break;
              case bN: h = ((rN - gN) / d + 4) / 6; break;
            }
          }
          return { h: Math.round(h * 360), s, l };
        };

        const hueFamilies = {};
        const rawClusters = {};

        for (let i = 0; i < imgData.length; i += 4) {
          const r = imgData[i];
          const g = imgData[i + 1];
          const b = imgData[i + 2];
          const a = imgData[i + 3];

          if (a < 120) continue; // transparent background

          const { h, s, l } = rgbToHsl(r, g, b);
          if (l < 0.12 || l > 0.92) continue; // ignore near-black outlines and near-white backgrounds
          if (s < 0.18) continue; // ignore neutral grays

          // Group into 18 hue sectors (20° each)
          const sector = Math.floor(h / 20);
          if (!hueFamilies[sector]) {
            hueFamilies[sector] = { count: 0, sumR: 0, sumG: 0, sumB: 0, sumS: 0 };
          }
          hueFamilies[sector].count++;
          hueFamilies[sector].sumR += r;
          hueFamilies[sector].sumG += g;
          hueFamilies[sector].sumB += b;
          hueFamilies[sector].sumS += s;

          // Fine clustering for authentic color swatches
          const fKey = `${r >> 4}_${g >> 4}_${b >> 4}`;
          if (!rawClusters[fKey]) {
            rawClusters[fKey] = { count: 0, sumR: 0, sumG: 0, sumB: 0, sat: s };
          }
          rawClusters[fKey].count++;
          rawClusters[fKey].sumR += r;
          rawClusters[fKey].sumG += g;
          rawClusters[fKey].sumB += b;
        }

        const families = Object.entries(hueFamilies).map(([sec, data]) => {
          const avgR = Math.round(data.sumR / data.count);
          const avgG = Math.round(data.sumG / data.count);
          const avgB = Math.round(data.sumB / data.count);
          const avgS = data.sumS / data.count;
          const hsl = rgbToHsl(avgR, avgG, avgB);
          // Boost energetic fiery brand tones (red, orange, flame)
          const isVividWarm = hsl.h <= 30 || hsl.h >= 340;
          const brandBoost = isVividWarm ? 1.5 : 1.0;
          return {
            hue: hsl.h,
            r: avgR, g: avgG, b: avgB,
            hex: rgbToHex(avgR, avgG, avgB),
            score: data.count * (1 + avgS * 2) * brandBoost,
            count: data.count
          };
        }).sort((a, b) => b.score - a.score);

        // Build top unique swatches
        const swatchList = Object.values(rawClusters).map(c => {
          const avgR = Math.round(c.sumR / c.count);
          const avgG = Math.round(c.sumG / c.count);
          const avgB = Math.round(c.sumB / c.count);
          return {
            hex: rgbToHex(avgR, avgG, avgB),
            score: c.count * (1 + c.sat * 2)
          };
        }).sort((a, b) => b.score - a.score);

        const swatches = [];
        const seen = new Set();
        // Add top hue family hexes first
        for (const fam of families) {
          if (!seen.has(fam.hex) && swatches.length < 8) {
            seen.add(fam.hex);
            swatches.push(fam.hex);
          }
        }
        // Then add top individual swatches
        for (const item of swatchList) {
          if (!seen.has(item.hex) && swatches.length < 8) {
            seen.add(item.hex);
            swatches.push(item.hex);
          }
        }

        if (families.length > 0) {
          const primary = families[0];
          // Find secondary from a distinct hue family (at least 20 degrees difference)
          let secondary = families.find(f => {
            const hueDiff = Math.abs(f.hue - primary.hue);
            const minDiff = Math.min(hueDiff, 360 - hueDiff);
            return minDiff >= 20;
          });

          if (!secondary) {
            secondary = families[1] || primary;
          }

          if (autoApply) {
            setPrimaryColor(primary.hex);
            setSecondaryColor(secondary.hex);
            notify(`Real logo colors extracted! Primary: ${primary.hex} (Tornado Cone), Accent: ${secondary.hex} (Glow)`);
          }
          setExtractedColors(swatches);
        } else if (swatches.length > 0) {
          if (autoApply) {
            setPrimaryColor(swatches[0]);
            setSecondaryColor(swatches[1] || swatches[0]);
          }
          setExtractedColors(swatches);
        }
      } catch (err) {
        console.error('Error extracting logo colors:', err);
      }
    };
    img.src = imageSrc;
  };

  const handleLogoFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setLogoFile(file);
    const objectUrl = URL.createObjectURL(file);
    setLogoPreview(objectUrl);
    extractColorsFromImage(objectUrl);
  };

  const handleSaveTheme = async (e) => {
    e.preventDefault();
    setSavingTheme(true);
    try {
      const formData = new FormData();
      if (logoFile) {
        formData.append('logo', logoFile);
      } else {
        formData.append('logoUrl', logoUrl || '');
      }
      formData.append('siteName', siteName);
      formData.append('primaryColor', primaryColor);
      formData.append('secondaryColor', secondaryColor);

      const res = await fetch('/api/upload-logo', {
        method: 'POST',
        body: formData
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update settings');

      setLogoUrl(data.settings.logoUrl || '');
      setLogoPreview(data.settings.logoUrl || '');
      setLogoFile(null);
      const inputEl = document.getElementById('logo-file-input');
      if (inputEl) inputEl.value = '';

      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('theme-updated', { detail: data.settings }));
      }

      notify('Site branding and theme saved successfully!');
    } catch (err) {
      notify(err.message, 'error');
    } finally {
      setSavingTheme(false);
    }
  };

  const handleRemoveLogo = async () => {
    try {
      const res = await fetch('/api/upload-logo', { method: 'DELETE' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to remove logo');
      setLogoUrl('');
      setLogoPreview('');
      setLogoFile(null);
      const inputEl = document.getElementById('logo-file-input');
      if (inputEl) inputEl.value = '';

      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('theme-updated', { detail: data.settings }));
      }
      notify('Site logo removed successfully! Text branding is now active.');
    } catch (err) {
      notify(err.message, 'error');
    }
  };

  const handleScreenLogoFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setScreenLogoFile(file);
    const objectUrl = URL.createObjectURL(file);
    setScreenLogoPreview(objectUrl);
  };

  const handleResetToDefaultWatermark = () => {
    setScreenLogoFile(null);
    setScreenLogoUrl('/watermark.png');
    setScreenLogoPreview('/watermark.png');
    const inputEl = document.getElementById('screen-logo-file-input');
    if (inputEl) inputEl.value = '';
    notify('Reset to default Tornado Network screen logo.');
  };

  const handleSaveScreenLogo = async (e) => {
    if (e && e.preventDefault) e.preventDefault();
    setSavingScreenLogo(true);
    try {
      if (screenLogoFile) {
        const formData = new FormData();
        formData.append('file', screenLogoFile);
        formData.append('opacity', String(screenLogoOpacity));
        formData.append('position', screenLogoPosition);
        formData.append('size', String(screenLogoSize));
        formData.append('enabled', String(screenLogoEnabled));

        const res = await fetch('/api/upload-watermark', {
          method: 'POST',
          body: formData
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to upload screen logo');
        setScreenLogoUrl(data.url);
        setScreenLogoPreview(data.url);
        setScreenLogoFile(null);
        const inputEl = document.getElementById('screen-logo-file-input');
        if (inputEl) inputEl.value = '';

        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('settings-updated', { detail: data.settings }));
        }
        notify('Video screen logo uploaded and applied successfully!');
      } else {
        const res = await fetch('/api/settings', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            screenLogoEnabled,
            screenLogoUrl,
            screenLogoOpacity,
            screenLogoPosition,
            screenLogoSize
          })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to save screen logo settings');

        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('settings-updated', { detail: data.settings }));
        }
        notify('Video screen logo settings saved successfully!');
      }
    } catch (err) {
      notify(err.message, 'error');
    } finally {
      setSavingScreenLogo(false);
    }
  };

  const handleChangePassword = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'change-password', newPassword })
      });
      const data = await res.json();
      if (res.ok) {
        notify('Password updated successfully!');
        setNewPassword('');
      } else {
        notify(data.error || 'Password update failed', 'error');
      }
    } catch (err) {
      notify('Error updating password', 'error');
    }
  };

  if (checkingAuth) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: '10rem 0' }}>
        <div className="spinner"></div>
      </div>
    );
  }

  // Login Screen
  if (!isAuthenticated) {
    return (
      <div style={{ maxWidth: '440px', margin: '6rem auto', padding: '0 1.5rem' }}>
        <div className="admin-card" style={{ textAlign: 'center' }} id="admin-login-box">
          <div style={{
            width: '60px',
            height: '60px',
            borderRadius: '50%',
            background: 'rgba(99, 102, 241, 0.15)',
            color: 'var(--accent-primary)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 1.5rem'
          }}>
            <Shield size={32} />
          </div>

          <h2 style={{ fontSize: '1.7rem', marginBottom: '0.5rem' }}>Admin Control Center</h2>
          <p style={{ color: 'var(--text-muted)', fontSize: '0.9rem', marginBottom: '2rem' }}>
            Please authenticate to manage live streams, M3U playlists, and Xtream accounts.
          </p>

          {authError && (
            <div style={{
              background: 'rgba(239, 68, 68, 0.15)',
              border: '1px solid rgba(239, 68, 68, 0.3)',
              color: '#fca5a5',
              padding: '0.75rem',
              borderRadius: 'var(--radius-sm)',
              fontSize: '0.85rem',
              marginBottom: '1.5rem'
            }}>
              {authError}
            </div>
          )}

          <form onSubmit={handleLogin} style={{ textAlign: 'left' }}>
            <div className="form-group">
              <label className="form-label">Admin Master Password</label>
              <div style={{ position: 'relative' }}>
                <input
                  type="password"
                  className="form-input"
                  id="admin-password-input"
                  placeholder="Enter admin password (default: admin123)"
                  value={loginPassword}
                  onChange={e => setLoginPassword(e.target.value)}
                  required
                />
              </div>
            </div>

            <button
              type="submit"
              className="btn-primary"
              id="admin-login-submit"
              style={{ width: '100%', justifyContent: 'center', marginTop: '1rem' }}
            >
              <Lock size={16} />
              <span>Unlock Admin Panel</span>
            </button>
          </form>

          <p style={{ fontSize: '0.75rem', color: 'var(--text-faint)', marginTop: '1.5rem' }}>
            Default setup credentials: Password <code>admin123</code>
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="admin-container" id="admin-dashboard">
      {/* Toast Notification */}
      {notification && (
        <div style={{
          position: 'fixed',
          top: '20px',
          right: '20px',
          zIndex: 100,
          background: notification.type === 'error' ? '#ef4444' : '#10b981',
          color: 'white',
          padding: '0.85rem 1.5rem',
          borderRadius: 'var(--radius-md)',
          boxShadow: '0 10px 25px rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          gap: '0.6rem',
          fontWeight: '600',
          fontSize: '0.9rem'
        }}>
          {notification.type === 'error' ? <AlertTriangle size={18} /> : <CheckCircle2 size={18} />}
          <span>{notification.msg}</span>
        </div>
      )}

      {/* Admin Header */}
      <div className="admin-header">
        <div>
          <h1 style={{ fontSize: '2.2rem', marginBottom: '0.35rem' }}>Broadcast Manager</h1>
          <p style={{ color: 'var(--text-muted)' }}>
            Seamlessly orchestrate M3U playlists, Xtream IPTV connections, and live stream channels.
          </p>
        </div>

        <div style={{ display: 'flex', gap: '0.75rem' }}>
          <button onClick={loadAdminData} className="btn-secondary" title="Refresh data">
            <RefreshCw size={16} className={loading ? 'spinner' : ''} />
            <span>Reload</span>
          </button>
          <button onClick={handleLogout} className="btn-secondary" style={{ color: '#ef4444' }} id="admin-logout-btn">
            <LogOut size={16} />
            <span>Logout</span>
          </button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="admin-stat-grid">
        <div className="stat-card channels-stat-card" id="card-total-channels" style={{
          background: 'linear-gradient(135deg, rgba(255, 85, 0, 0.12) 0%, rgba(20, 16, 12, 0.88) 100%)',
          borderColor: 'rgba(255, 85, 0, 0.4)',
          boxShadow: '0 4px 20px rgba(255, 85, 0, 0.15)'
        }}>
          <div className="stat-icon" style={{ color: 'var(--accent-primary)', background: 'rgba(255, 85, 0, 0.2)' }}>
            <Tv size={24} />
          </div>
          <div>
            <div className="stat-val" style={{ color: '#fff' }}>{channels.length}</div>
            <div className="stat-label">Total Live Channels</div>
          </div>
        </div>

        <div className="stat-card live-visitor-card" id="card-live-visitors">
          <div className="stat-icon" style={{ color: '#10b981', background: 'rgba(16, 185, 129, 0.15)' }}>
            <Activity size={24} />
          </div>
          <div>
            <div className="stat-val" style={{ display: 'flex', alignItems: 'center' }}>
              <span className="live-pulse-dot" title="Active real-time viewer stream"></span>
              <span>{liveVisitors}</span>
              <span className="live-badge-tag">Live</span>
            </div>
            <div className="stat-label">Live Visitors</div>
          </div>
        </div>

        <div className="stat-card total-visitor-card" id="card-total-visitors">
          <div className="stat-icon" style={{ color: '#3b82f6', background: 'rgba(59, 130, 246, 0.15)' }}>
            <Users size={24} />
          </div>
          <div>
            <div className="stat-val">{(totalVisitors || 0).toLocaleString()}</div>
            <div className="stat-label">Total Visitors</div>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon" style={{ color: '#a855f7', background: 'rgba(168, 85, 247, 0.15)' }}>
            <List size={24} />
          </div>
          <div>
            <div className="stat-val">{playlists.length}</div>
            <div className="stat-label">Active Playlists</div>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon" style={{ color: '#06b6d4', background: 'rgba(6, 182, 212, 0.15)' }}>
            <Server size={24} />
          </div>
          <div>
            <div className="stat-val">{categories.length}</div>
            <div className="stat-label">Categories</div>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon" style={{ color: '#ec4899', background: 'rgba(236, 72, 153, 0.15)' }}>
            <Download size={24} />
          </div>
          <div>
            <div className="stat-val">{appInfo ? '1 Active' : 'None'}</div>
            <div className="stat-label">App Client</div>
          </div>
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="admin-tabs" id="admin-nav-tabs">
        <button
          className={`tab-btn ${activeTab === 'channels' ? 'active' : ''}`}
          onClick={() => setActiveTab('channels')}
          id="tab-manage-channels"
        >
          <Tv size={18} />
          <span>Channels</span>
          <span className="tab-badge">{channels.length}</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'add-playlist' ? 'active' : ''}`}
          onClick={() => setActiveTab('add-playlist')}
          id="tab-add-playlist"
        >
          <PlusCircle size={18} />
          <span>Add M3U / Xtream</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'playlists' ? 'active' : ''}`}
          onClick={() => setActiveTab('playlists')}
          id="tab-manage-playlists"
        >
          <List size={18} />
          <span>Playlists</span>
          <span className="tab-badge">{playlists.length}</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'ftp-app' ? 'active' : ''}`}
          onClick={() => setActiveTab('ftp-app')}
          id="tab-ftp-app"
        >
          <Server size={18} />
          <span>FTP & App</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'branding' ? 'active' : ''}`}
          onClick={() => setActiveTab('branding')}
          id="tab-branding"
        >
          <Palette size={18} />
          <span>Logo & Theme</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'screen-logo' ? 'active' : ''}`}
          onClick={() => setActiveTab('screen-logo')}
          id="tab-screen-logo"
        >
          <Eye size={18} />
          <span>Screen Watermark</span>
        </button>

        <button
          className={`tab-btn ${activeTab === 'settings' ? 'active' : ''}`}
          onClick={() => setActiveTab('settings')}
          id="tab-settings"
        >
          <Lock size={18} />
          <span>Security</span>
        </button>
      </div>

      {/* TAB 1: ADD PLAYLIST (M3U URL / Xtream / File) */}
      {activeTab === 'add-playlist' && (
        <div className="admin-card">
          <h3 style={{ fontSize: '1.3rem', marginBottom: '1.5rem' }}>Import Live TV Channels</h3>

          <div style={{ display: 'flex', gap: '1rem', marginBottom: '2rem' }}>
            <button
              type="button"
              className={`btn-secondary ${playlistType === 'url' ? 'btn-primary' : ''}`}
              onClick={() => setPlaylistType('url')}
            >
              M3U URL
            </button>
            <button
              type="button"
              className={`btn-secondary ${playlistType === 'xtream' ? 'btn-primary' : ''}`}
              onClick={() => setPlaylistType('xtream')}
            >
              Xtream Codes (Server, User, Pass)
            </button>
            <button
              type="button"
              className={`btn-secondary ${playlistType === 'file' ? 'btn-primary' : ''}`}
              onClick={() => setPlaylistType('file')}
            >
              Upload M3U File / Paste
            </button>
          </div>

          <form onSubmit={handleAddPlaylist}>
            <div className="form-group">
              <label className="form-label">Playlist Display Name</label>
              <input
                type="text"
                className="form-input"
                placeholder="e.g. Sports & News HD, International IPTV"
                value={playlistName}
                onChange={e => setPlaylistName(e.target.value)}
                required
              />
            </div>

            {/* URL Mode */}
            {playlistType === 'url' && (
              <div className="form-group">
                <label className="form-label">M3U or M3U8 Playlist URL</label>
                <input
                  type="url"
                  className="form-input"
                  id="playlist-url-input"
                  placeholder="https://example.com/playlist.m3u"
                  value={playlistUrl}
                  onChange={e => setPlaylistUrl(e.target.value)}
                  required
                />
                <p style={{ fontSize: '0.8rem', color: 'var(--text-faint)', marginTop: '0.4rem' }}>
                  The server will automatically fetch, parse channels, and synchronize them.
                </p>
              </div>
            )}

            {/* Xtream Mode */}
            {playlistType === 'xtream' && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '1rem' }}>
                <div className="form-group">
                  <label className="form-label">Xtream Server URL & Port</label>
                  <input
                    type="text"
                    className="form-input"
                    id="xtream-server-input"
                    placeholder="http://iptv.server.com:8080"
                    value={xtreamServer}
                    onChange={e => setXtreamServer(e.target.value)}
                    required
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">Username</label>
                  <input
                    type="text"
                    className="form-input"
                    id="xtream-user-input"
                    placeholder="Username"
                    value={xtreamUser}
                    onChange={e => setXtreamUser(e.target.value)}
                    required
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">Password</label>
                  <input
                    type="password"
                    className="form-input"
                    id="xtream-pass-input"
                    placeholder="Password"
                    value={xtreamPass}
                    onChange={e => setXtreamPass(e.target.value)}
                    required
                  />
                </div>
              </div>
            )}

            {/* File Mode */}
            {playlistType === 'file' && (
              <div>
                <div className="form-group">
                  <label className="form-label">Choose .m3u / .m3u8 file from computer</label>
                  <input
                    type="file"
                    accept=".m3u,.m3u8,text/plain"
                    className="form-input"
                    onChange={handleFileUpload}
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">Or paste raw M3U text here</label>
                  <textarea
                    rows={6}
                    className="form-textarea"
                    placeholder="#EXTM3U&#10;#EXTINF:-1 tvg-name=&quot;Channel 1&quot;,Channel 1&#10;http://example.com/stream.m3u8"
                    value={fileContent}
                    onChange={e => setFileContent(e.target.value)}
                  />
                </div>
              </div>
            )}

            <button
              type="submit"
              className="btn-primary"
              id="import-playlist-submit"
              disabled={loading}
              style={{ marginTop: '1rem' }}
            >
              <PlusCircle size={18} />
              <span>{loading ? 'Processing & Syncing...' : 'Save and Sync Channels'}</span>
            </button>
          </form>
        </div>
      )}

      {/* TAB 2: PLAYLISTS LIST */}
      {activeTab === 'playlists' && (
        <div className="admin-card">
          <h3 style={{ fontSize: '1.3rem', marginBottom: '1.5rem' }}>Active Playlists</h3>

          {playlists.length === 0 ? (
            <p style={{ color: 'var(--text-muted)' }}>No playlists added yet.</p>
          ) : (
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Channels</th>
                    <th>Last Synced</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {playlists.map(pl => (
                    <tr key={pl.id}>
                      <td style={{ fontWeight: '600' }}>{pl.name}</td>
                      <td>
                        <span className="channel-category">{pl.type.toUpperCase()}</span>
                      </td>
                      <td>{pl.channelCount || 0}</td>
                      <td style={{ color: 'var(--text-faint)', fontSize: '0.8rem' }}>
                        {pl.lastSync ? new Date(pl.lastSync).toLocaleString() : 'Never'}
                      </td>
                      <td>
                        <div style={{ display: 'flex', gap: '0.5rem' }}>
                          {pl.url && (
                            <button
                              className="btn-secondary"
                              style={{ padding: '0.4rem 0.75rem', fontSize: '0.8rem' }}
                              onClick={() => handleSyncPlaylist(pl.id)}
                              title="Fetch latest channels from URL"
                            >
                              <RefreshCw size={14} />
                              <span>Re-sync</span>
                            </button>
                          )}
                          <button
                            className="btn-danger"
                            onClick={() => handleDeletePlaylist(pl.id, pl.name)}
                            title="Delete playlist"
                          >
                            <Trash2 size={14} />
                            <span>Delete</span>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* TAB 3: CHANNELS MANAGEMENT */}
      {activeTab === 'channels' && (
        <div>
          {/* Add Single Custom Channel */}
          <div className="admin-card" style={{ marginBottom: '2rem', padding: '1.75rem 2rem' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.85rem' }}>
                <div style={{
                  width: '42px',
                  height: '42px',
                  borderRadius: '12px',
                  background: 'linear-gradient(135deg, rgba(255, 85, 0, 0.2) 0%, rgba(255, 153, 0, 0.08) 100%)',
                  border: '1px solid rgba(255, 85, 0, 0.3)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: 'var(--accent-primary)',
                  boxShadow: '0 4px 14px rgba(255, 85, 0, 0.15)'
                }}>
                  <Tv size={22} />
                </div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <h3 style={{ fontSize: '1.25rem', margin: 0, fontWeight: '700' }}>Add Live Channel</h3>
                    <span style={{ 
                      fontSize: '0.72rem', 
                      fontWeight: '700', 
                      padding: '0.18rem 0.55rem', 
                      borderRadius: '999px', 
                      background: 'rgba(255, 85, 0, 0.15)', 
                      color: 'var(--accent-primary)',
                      border: '1px solid rgba(255, 85, 0, 0.3)'
                    }}>
                      Custom Stream
                    </span>
                  </div>
                  <p style={{ color: 'var(--text-muted)', fontSize: '0.82rem', margin: '0.2rem 0 0 0' }}>
                    Register individual HLS, M3U8, or TS streams with custom broadcast branding and categorization.
                  </p>
                </div>
              </div>
            </div>

            {/* Form */}
            <form onSubmit={handleAddSingleChannel}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '1.5rem' }}>
                
                {/* Column 1: Channel Info & Category */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                  <div>
                    <label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                      <span>Channel Name</span>
                      <span style={{ color: 'var(--accent-primary)' }}>*</span>
                    </label>
                    <input
                      type="text"
                      className="form-input"
                      placeholder="e.g. ESPN HD, T Sports, Discovery"
                      value={singleName}
                      onChange={e => setSingleName(e.target.value)}
                      required
                    />
                  </div>

                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.35rem' }}>
                      <label className="form-label" style={{ margin: 0 }}>Category</label>
                      <span style={{ fontSize: '0.75rem', color: 'var(--text-faint)' }}>Choose or type custom</span>
                    </div>
                    <input
                      type="text"
                      list="category-suggestions"
                      className="form-input"
                      placeholder="e.g. Sports Live, Bangla Entertainment..."
                      value={singleCategory}
                      onChange={e => setSingleCategory(e.target.value)}
                    />
                    <datalist id="category-suggestions">
                      {distinctCategories.map(cat => (
                        <option key={cat} value={cat} />
                      ))}
                    </datalist>

                    {/* Quick Category Chips */}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.4rem', marginTop: '0.6rem' }}>
                      {['Bangla Entertainment', 'Bangla News', 'Sports Live', 'Indian Bangla', 'Hindi Entertainment', 'Kids & Cartoons'].map(chip => (
                        <button
                          key={chip}
                          type="button"
                          onClick={() => setSingleCategory(chip)}
                          style={{
                            background: singleCategory === chip ? 'rgba(255, 85, 0, 0.2)' : 'rgba(255, 255, 255, 0.04)',
                            color: singleCategory === chip ? 'var(--accent-primary)' : 'var(--text-muted)',
                            border: singleCategory === chip ? '1px solid rgba(255, 85, 0, 0.4)' : '1px solid var(--border-subtle)',
                            borderRadius: '999px',
                            padding: '0.2rem 0.6rem',
                            fontSize: '0.74rem',
                            cursor: 'pointer',
                            transition: 'all 0.2s'
                          }}
                        >
                          {chip}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Column 2: Stream URL & Logo */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                  <div>
                    <label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                      <span>Stream Source URL (HLS / M3U8 / TS)</span>
                      <span style={{ color: 'var(--accent-primary)' }}>*</span>
                    </label>
                    <input
                      type="url"
                      className="form-input"
                      placeholder="http://... or https://.../master.m3u8"
                      value={singleUrl}
                      onChange={e => setSingleUrl(e.target.value)}
                      required
                    />
                  </div>

                  <div>
                    <label className="form-label" style={{ marginBottom: '0.35rem' }}>Channel Logo Branding</label>
                    <div style={{
                      display: 'flex',
                      gap: '1rem',
                      alignItems: 'center',
                      background: 'rgba(255, 255, 255, 0.025)',
                      border: '1px solid var(--border-subtle)',
                      borderRadius: 'var(--radius-sm)',
                      padding: '0.75rem 0.9rem'
                    }}>
                      {/* Logo Preview Box */}
                      <div style={{
                        width: '56px',
                        height: '56px',
                        background: 'rgba(0, 0, 0, 0.55)',
                        border: singleLogo ? '1px solid rgba(255, 85, 0, 0.4)' : '1px dashed rgba(255, 255, 255, 0.15)',
                        borderRadius: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0,
                        overflow: 'hidden',
                        position: 'relative'
                      }}>
                        {singleLogo ? (
                          <img 
                            src={singleLogo} 
                            alt="Preview" 
                            style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', padding: '3px' }} 
                            onError={e => { e.currentTarget.style.opacity = '0.3'; }}
                          />
                        ) : (
                          <Tv size={22} style={{ color: 'var(--text-faint)' }} />
                        )}
                      </div>

                      {/* URL input and upload action */}
                      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: '0.45rem' }}>
                        <input
                          type="text"
                          className="form-input"
                          placeholder="https://.../logo.png or /channel-logos/..."
                          value={singleLogo}
                          onChange={e => setSingleLogo(e.target.value)}
                          style={{ fontSize: '0.85rem', padding: '0.5rem 0.75rem' }}
                        />
                        <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                          <label 
                            className="btn-secondary" 
                            style={{ 
                              padding: '0.35rem 0.75rem', 
                              fontSize: '0.78rem', 
                              cursor: 'pointer',
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '0.35rem'
                            }}
                          >
                            <Upload size={12} />
                            <span>{singleLogoUploading ? 'Uploading...' : 'Upload Image File'}</span>
                            <input
                              type="file"
                              accept="image/*"
                              hidden
                              disabled={singleLogoUploading}
                              onChange={e => {
                                if (e.target.files?.[0]) handleUploadChannelLogo(e.target.files[0], true);
                              }}
                            />
                          </label>
                          {singleLogo && (
                            <button
                              type="button"
                              onClick={() => setSingleLogo('')}
                              style={{
                                background: 'transparent',
                                border: 'none',
                                color: 'var(--text-muted)',
                                fontSize: '0.75rem',
                                cursor: 'pointer',
                                padding: '0.2rem 0.4rem',
                                textDecoration: 'underline'
                              }}
                            >
                              Clear Logo
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

              </div>

              {/* Action Footer */}
              <div style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: '1rem',
                marginTop: '1.5rem',
                paddingTop: '1.25rem',
                borderTop: '1px solid var(--border-subtle)'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', color: 'var(--text-faint)', fontSize: '0.8rem' }}>
                  <Sparkles size={14} style={{ color: 'var(--accent-primary)' }} />
                  <span>Channels become immediately live and streamable in player & sidebar.</span>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
                  {(singleName || singleCategory || singleUrl || singleLogo) && (
                    <button
                      type="button"
                      className="btn-secondary"
                      onClick={() => {
                        setSingleName('');
                        setSingleCategory('');
                        setSingleUrl('');
                        setSingleLogo('');
                      }}
                      style={{ padding: '0.65rem 1rem', fontSize: '0.85rem' }}
                    >
                      Reset Form
                    </button>
                  )}
                  <button 
                    type="submit" 
                    className="btn-primary" 
                    style={{ 
                      padding: '0.65rem 1.6rem', 
                      fontSize: '0.9rem',
                      boxShadow: '0 4px 18px var(--accent-glow)'
                    }}
                  >
                    <PlusCircle size={16} />
                    <span>Add Channel to Broadcast</span>
                  </button>
                </div>
              </div>
            </form>
          </div>

          {/* Channels Table */}
          <div className="admin-card">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div>
                <h3 style={{ fontSize: '1.3rem' }}>All Available Channels ({filteredChannels.length})</h3>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
                  Click <strong>Edit</strong> or change categories directly inline below.
                </p>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap' }}>
                <button
                  type="button"
                  className="btn-secondary"
                  onClick={handleAutoCategorize}
                  disabled={loading}
                  style={{ padding: '0.5rem 0.95rem', fontSize: '0.85rem' }}
                  title="Run automatic categorization across all channels"
                >
                  <Sparkles size={15} style={{ color: 'var(--accent-primary)' }} />
                  <span>Auto-Categorize All</span>
                </button>
                <div className="search-box" style={{ maxWidth: '300px' }}>
                  <input
                    type="text"
                    className="search-input"
                    placeholder="Filter channels..."
                    value={channelSearch}
                    onChange={e => setChannelSearch(e.target.value)}
                  />
                </div>
              </div>
            </div>

            {/* Batch Action Bar */}
            {selectedChannelIds.length > 0 && (
              <div className="batch-action-bar">
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                  <CheckSquare size={17} style={{ color: 'var(--accent-primary)' }} />
                  <span style={{ fontWeight: '600', fontSize: '0.9rem' }}>
                    {selectedChannelIds.length} channel{selectedChannelIds.length > 1 ? 's' : ''} selected
                  </span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', flexWrap: 'wrap' }}>
                  <span style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>Change Category to:</span>
                  <select
                    className="channel-category-select"
                    value={batchCategory}
                    onChange={e => setBatchCategory(e.target.value)}
                    style={{ minWidth: '180px' }}
                  >
                    <option value="">-- Choose Category --</option>
                    {distinctCategories.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                  <button
                    type="button"
                    className="btn-primary"
                    style={{ padding: '0.4rem 0.85rem', fontSize: '0.85rem' }}
                    onClick={handleBatchCategoryChange}
                    disabled={batchApplying || !batchCategory}
                  >
                    {batchApplying ? 'Updating...' : 'Apply Category'}
                  </button>
                  <button
                    type="button"
                    className="btn-secondary"
                    style={{ padding: '0.4rem 0.75rem', fontSize: '0.85rem' }}
                    onClick={() => setSelectedChannelIds([])}
                  >
                    Clear Selection
                  </button>
                </div>
              </div>
            )}

            <div style={{ overflowX: 'auto', maxHeight: '600px' }}>
              <table className="data-table">
                <thead>
                  <tr>
                    <th style={{ width: '40px', textAlign: 'center' }}>
                      <input
                        type="checkbox"
                        checked={filteredChannels.length > 0 && selectedChannelIds.length === filteredChannels.length}
                        onChange={toggleSelectAllChannels}
                        title="Select/Deselect all filtered channels"
                        style={{ cursor: 'pointer', accentColor: 'var(--accent-primary)', width: '16px', height: '16px' }}
                      />
                    </th>
                    <th>Channel</th>
                    <th>Category</th>
                    <th>Stream Source</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredChannels.slice(0, 100).map(ch => (
                    <tr key={ch.id} style={{ background: selectedChannelIds.includes(ch.id) ? 'rgba(255, 85, 0, 0.06)' : undefined }}>
                      <td style={{ textAlign: 'center' }}>
                        <input
                          type="checkbox"
                          checked={selectedChannelIds.includes(ch.id)}
                          onChange={() => toggleSelectChannel(ch.id)}
                          style={{ cursor: 'pointer', accentColor: 'var(--accent-primary)', width: '16px', height: '16px' }}
                        />
                      </td>
                      <td>
                        <div 
                          style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', cursor: 'pointer' }}
                          onClick={() => openEditModal(ch)}
                          title="Click to edit channel logo and details"
                        >
                          <div style={{ 
                            width: '32px', 
                            height: '32px', 
                            background: 'rgba(255,255,255,0.05)', 
                            borderRadius: '6px', 
                            display: 'flex', 
                            alignItems: 'center', 
                            justifyContent: 'center',
                            overflow: 'hidden',
                            flexShrink: 0
                          }}>
                            {ch.logo ? (
                              <img 
                                src={ch.logo} 
                                alt="" 
                                style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} 
                                onError={e => { e.currentTarget.style.display = 'none'; }} 
                              />
                            ) : (
                              <Tv size={18} style={{ color: 'var(--text-faint)' }} />
                            )}
                          </div>
                          <span style={{ fontWeight: '600' }}>{ch.name}</span>
                        </div>
                      </td>
                      <td style={{ minWidth: '180px' }}>
                        <select
                          className="channel-category-select"
                          value={ch.category || 'General'}
                          onChange={(e) => handleInlineCategoryChange(ch.id, e.target.value)}
                          title="Quick category change"
                        >
                          {distinctCategories.map(cat => (
                            <option key={cat} value={cat}>{cat}</option>
                          ))}
                        </select>
                      </td>
                      <td style={{ maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--text-faint)', fontSize: '0.8rem' }}>
                        {ch.streamUrl}
                      </td>
                      <td>
                        <div style={{ display: 'flex', gap: '0.45rem' }}>
                          <button
                            type="button"
                            className="btn-secondary"
                            style={{ padding: '0.35rem 0.65rem' }}
                            onClick={() => openEditModal(ch)}
                            title="Edit Channel Logo, Category & Details"
                          >
                            <Edit3 size={14} style={{ color: 'var(--accent-primary)' }} />
                            <span>Edit</span>
                          </button>
                          <Link href={`/watch/${ch.id}`} className="btn-secondary" style={{ padding: '0.35rem 0.65rem' }} target="_blank">
                            <Eye size={14} />
                            <span>Preview</span>
                          </Link>
                          <button
                            className="btn-danger"
                            onClick={() => handleDeleteChannel(ch.id, ch.name)}
                            title="Delete Channel"
                          >
                            <Trash2 size={14} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {filteredChannels.length > 100 && (
                <div style={{ textAlign: 'center', padding: '1rem', color: 'var(--text-muted)' }}>
                  Showing first 100 of {filteredChannels.length} channels. Use search to filter specific channels.
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* TAB 4: FTP SERVER & APP UPLOAD */}
      {activeTab === 'ftp-app' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(420px, 1fr))', gap: '1.75rem' }}>
          {/* Card 1: FTP Server Configuration */}
          <div className="admin-card">
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.25rem' }}>
              <div style={{
                width: '38px',
                height: '38px',
                borderRadius: 'var(--radius-sm)',
                background: 'rgba(99, 102, 241, 0.15)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'var(--accent-primary)'
              }}>
                <Server size={20} />
              </div>
              <div>
                <h3 style={{ fontSize: '1.25rem', margin: 0 }}>FTP Server Configuration</h3>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', margin: 0 }}>
                  Set the local BDIX / ISP FTP address for your viewers
                </p>
              </div>
            </div>

            <form onSubmit={handleSaveFtp}>
              <div className="form-group">
                <label className="form-label">FTP Server URL or IP Address</label>
                <input
                  type="text"
                  className="form-input"
                  id="admin-ftp-url-input"
                  placeholder="e.g. ftp://10.16.100.1 or http://ftp.yourdomain.com"
                  value={ftpServerUrl}
                  onChange={e => setFtpServerUrl(e.target.value)}
                  required
                />
                <span style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '0.35rem', display: 'block' }}>
                  This URL is linked directly to the &quot;FTP Server&quot; button in the top navigation bar.
                </span>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginTop: '1.5rem' }}>
                <button type="submit" className="btn-primary" disabled={savingFtp} id="save-ftp-btn">
                  {savingFtp ? <RefreshCw size={16} className="spinner" /> : <Check size={16} />}
                  <span>{savingFtp ? 'Saving...' : 'Save FTP Settings'}</span>
                </button>

                {ftpServerUrl && (
                  <a
                    href={ftpServerUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="btn-secondary"
                    style={{ textDecoration: 'none' }}
                  >
                    <ExternalLink size={15} />
                    <span>Test Open</span>
                  </a>
                )}
              </div>
            </form>
          </div>

          {/* Card 2: App Upload (Single App) */}
          <div className="admin-card">
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.25rem' }}>
              <div style={{
                width: '38px',
                height: '38px',
                borderRadius: 'var(--radius-sm)',
                background: 'rgba(168, 85, 247, 0.15)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#c084fc'
              }}>
                <Download size={20} />
              </div>
              <div>
                <h3 style={{ fontSize: '1.25rem', margin: 0 }}>Application Upload (Single App)</h3>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', margin: 0 }}>
                  Upload your Android TV, FireStick or Mobile APK
                </p>
              </div>
            </div>

            {/* Current App Status Display */}
            {appInfo ? (
              <div style={{
                background: 'rgba(16, 185, 129, 0.08)',
                border: '1px solid rgba(16, 185, 129, 0.3)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem',
                marginBottom: '1.5rem',
                display: 'flex',
                flexDirection: 'column',
                gap: '0.75rem'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.5rem' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <CheckCircle2 size={18} style={{ color: '#10b981' }} />
                    <span style={{ fontWeight: '700', color: '#fff', fontSize: '0.95rem' }}>{appInfo.fileName}</span>
                    <span style={{
                      background: 'rgba(99, 102, 241, 0.2)',
                      color: 'var(--accent-primary)',
                      padding: '0.15rem 0.5rem',
                      borderRadius: 'var(--radius-sm)',
                      fontSize: '0.75rem',
                      fontWeight: '700'
                    }}>
                      v{appInfo.version || '1.0.0'}
                    </span>
                  </div>

                  <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)', fontWeight: '500' }}>
                    {appInfo.fileSize}
                  </span>
                </div>

                <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                  Uploaded: {new Date(appInfo.uploadedAt).toLocaleString()}
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginTop: '0.25rem' }}>
                  <a
                    href={appInfo.downloadUrl}
                    download={appInfo.fileName}
                    className="btn-secondary"
                    style={{ padding: '0.4rem 0.85rem', fontSize: '0.8rem', textDecoration: 'none' }}
                  >
                    <Download size={14} />
                    <span>Test Download</span>
                  </a>

                  <button
                    type="button"
                    onClick={handleDeleteApp}
                    className="btn-danger"
                    style={{ padding: '0.4rem 0.85rem', fontSize: '0.8rem' }}
                    id="delete-app-btn"
                  >
                    <Trash2 size={14} />
                    <span>Delete App</span>
                  </button>
                </div>
              </div>
            ) : (
              <div style={{
                background: 'rgba(255, 255, 255, 0.03)',
                border: '1px dashed var(--border-subtle)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem',
                marginBottom: '1.5rem',
                textAlign: 'center',
                color: 'var(--text-muted)',
                fontSize: '0.85rem'
              }}>
                No application uploaded yet. Upload an APK or installer file below.
              </div>
            )}

            {/* Upload Form */}
            <form onSubmit={handleUploadApp}>
              <div className="form-group">
                <label className="form-label">
                  {appInfo ? 'Upload Replacement / Updated App File' : 'Select Application File'}
                </label>
                <input
                  type="file"
                  id="app-file-input"
                  className="form-input"
                  accept=".apk,.zip,.exe,.dmg,.pkg"
                  onChange={e => setAppFile(e.target.files[0] || null)}
                  style={{ padding: '0.6rem', background: 'rgba(0, 0, 0, 0.3)' }}
                />
                <span style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '0.35rem', display: 'block' }}>
                  Supported formats: APK (Android TV / Box / Mobile), ZIP, EXE. Only one active app is maintained.
                </span>
              </div>

              <div className="form-group" style={{ marginTop: '1rem' }}>
                <label className="form-label">App Release Version</label>
                <input
                  type="text"
                  className="form-input"
                  id="app-version-input"
                  placeholder="e.g. 1.0.0 or 2.4.0"
                  value={appVersion}
                  onChange={e => setAppVersion(e.target.value)}
                />
              </div>

              <div style={{ marginTop: '1.5rem' }}>
                <button
                  type="submit"
                  className="btn-primary"
                  disabled={uploadingApp || !appFile}
                  id="upload-app-submit-btn"
                  style={{ opacity: !appFile ? 0.6 : 1 }}
                >
                  {uploadingApp ? <RefreshCw size={16} className="spinner" /> : <Upload size={16} />}
                  <span>{uploadingApp ? 'Uploading App...' : (appInfo ? 'Replace Active App' : 'Upload & Activate App')}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* TAB: LOGO & THEME BRANDING */}
      {activeTab === 'branding' && (
        <div className="admin-card" id="branding-theme-card">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
            <div>
              <h3 style={{ fontSize: '1.3rem', display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                <Palette size={22} style={{ color: 'var(--accent-primary)' }} />
                <span>Site Logo & Dynamic Theme Colors</span>
              </h3>
              <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginTop: '0.25rem' }}>
                Change the site logo and customize branding colors. When you upload a new logo, dominant colors are automatically extracted so the entire site adopts the logo's color palette!
              </p>
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'minmax(280px, 360px) 1fr',
            gap: '2rem',
            alignItems: 'start'
          }}>
            {/* Left: Live Visual Preview Card */}
            <div style={{
              background: 'rgba(0, 0, 0, 0.4)',
              border: '1px solid var(--border-subtle)',
              borderRadius: 'var(--radius-md)',
              padding: '1.5rem',
              display: 'flex',
              flexDirection: 'column',
              gap: '1.25rem',
              textAlign: 'center'
            }}>
              <div style={{ fontSize: '0.85rem', fontWeight: '700', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                Active Site Logo Preview
              </div>

              <div style={{
                width: '100%',
                height: '140px',
                background: 'radial-gradient(circle, rgba(255, 255, 255, 0.05) 0%, rgba(0, 0, 0, 0.6) 100%)',
                borderRadius: 'var(--radius-sm)',
                border: logoPreview ? '1px solid var(--border-subtle)' : '1px dashed var(--border-subtle)',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '1rem',
                overflow: 'hidden'
              }}>
                {logoPreview ? (
                  <img
                    src={logoPreview}
                    alt="Logo Preview"
                    style={{ maxHeight: '110px', maxWidth: '100%', objectFit: 'contain' }}
                  />
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.4rem', color: 'var(--text-muted)' }}>
                    <ImageIcon size={36} style={{ color: primaryColor, opacity: 0.6 }} />
                    <span style={{ fontSize: '0.8rem' }}>No logo active (Text branding only)</span>
                  </div>
                )}
              </div>

              {logoPreview && (
                <div style={{ display: 'flex', gap: '0.6rem', justifyContent: 'center', flexWrap: 'wrap' }}>
                  <button
                    type="button"
                    onClick={() => extractColorsFromImage(logoPreview)}
                    className="btn-secondary"
                    style={{ padding: '0.35rem 0.8rem', fontSize: '0.8rem' }}
                    id="detect-logo-colors-btn"
                    title="Scan logo and auto-detect its real colors"
                  >
                    <Sparkles size={14} style={{ color: primaryColor }} />
                    <span>Auto-Detect Colors</span>
                  </button>

                  <button
                    type="button"
                    onClick={handleRemoveLogo}
                    className="btn-danger"
                    style={{ padding: '0.35rem 0.8rem', fontSize: '0.8rem' }}
                    id="remove-logo-btn"
                  >
                    <Trash2 size={14} />
                    <span>Remove Logo</span>
                  </button>
                </div>
              )}

              {/* Sample Header Simulation */}
              <div style={{
                background: 'rgba(15, 12, 10, 0.85)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-sm)',
                padding: '0.75rem 1rem',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                  {logoPreview && (
                    <img src={logoPreview} alt="brand" style={{ height: '24px', width: 'auto', objectFit: 'contain' }} />
                  )}
                  <span style={{
                    fontWeight: '800',
                    fontSize: '1rem',
                    background: `linear-gradient(135deg, ${primaryColor} 0%, ${secondaryColor} 100%)`,
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent'
                  }}>
                    {siteName || 'TN TV'}
                  </span>
                </div>
                <span style={{
                  background: `linear-gradient(135deg, ${primaryColor} 0%, ${secondaryColor} 100%)`,
                  color: '#fff',
                  fontSize: '0.65rem',
                  fontWeight: '800',
                  padding: '0.2rem 0.5rem',
                  borderRadius: '9999px'
                }}>
                  LIVE
                </span>
              </div>

              {/* Sample Buttons with Dynamic Colors */}
              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'center' }}>
                <button
                  type="button"
                  style={{
                    background: `linear-gradient(135deg, ${primaryColor} 0%, ${secondaryColor} 100%)`,
                    color: '#fff',
                    border: 'none',
                    padding: '0.5rem 1rem',
                    borderRadius: '8px',
                    fontSize: '0.8rem',
                    fontWeight: '700',
                    boxShadow: `0 4px 14px ${primaryColor}40`
                  }}
                >
                  Primary Button
                </button>
                <button
                  type="button"
                  style={{
                    background: 'rgba(255, 255, 255, 0.08)',
                    border: `1px solid ${primaryColor}`,
                    color: '#fff',
                    padding: '0.5rem 1rem',
                    borderRadius: '8px',
                    fontSize: '0.8rem',
                    fontWeight: '600'
                  }}
                >
                  Glow Outline
                </button>
              </div>
            </div>

            {/* Right: Upload & Color Configuration Form */}
            <form onSubmit={handleSaveTheme}>
              <div className="form-group">
                <label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                  <span>Site Name / Brand Title</span>
                </label>
                <input
                  type="text"
                  className="form-input"
                  id="site-name-input"
                  value={siteName}
                  onChange={e => setSiteName(e.target.value)}
                  placeholder="e.g. TN TV"
                  required
                />
              </div>

              <div className="form-group" style={{ marginTop: '1.25rem' }}>
                <label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                  <span>Upload New Logo Image (PNG / SVG / JPG)</span>
                </label>
                <input
                  type="file"
                  id="logo-file-input"
                  className="form-input"
                  accept="image/*"
                  onChange={handleLogoFileChange}
                  style={{ padding: '0.6rem', background: 'rgba(0, 0, 0, 0.3)' }}
                />
                <div style={{
                  fontSize: '0.75rem',
                  color: 'var(--text-muted)',
                  marginTop: '0.4rem',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.4rem'
                }}>
                  <Sparkles size={14} style={{ color: primaryColor }} />
                  <span>Selecting an image will automatically extract its dominant & accent colors!</span>
                </div>
              </div>

              {/* Extracted Swatches if any */}
              {extractedColors.length > 0 && (
                <div style={{ marginTop: '1rem', padding: '0.85rem 1rem', background: 'rgba(255, 255, 255, 0.03)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border-subtle)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '0.65rem', flexWrap: 'wrap', gap: '0.5rem' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <span style={{ fontSize: '0.78rem', fontWeight: '700', color: 'var(--text-main)' }}>
                        Authentic Logo Palette:
                      </span>
                      <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>
                        (Left-click = Primary, Right-click = Accent)
                      </span>
                    </div>

                    <button
                      type="button"
                      onClick={handleSwapColors}
                      className="btn-secondary"
                      style={{ padding: '0.25rem 0.6rem', fontSize: '0.72rem', display: 'flex', alignItems: 'center', gap: '0.35rem' }}
                      id="swap-theme-colors-btn"
                      title="Swap Primary and Accent colors"
                    >
                      <ArrowLeftRight size={12} />
                      <span>Swap Colors</span>
                    </button>
                  </div>

                  <div style={{ display: 'flex', gap: '0.6rem', flexWrap: 'wrap', alignItems: 'center' }}>
                    {extractedColors.map((hex, idx) => {
                      const isPrimary = primaryColor.toLowerCase() === hex.toLowerCase();
                      const isSecondary = secondaryColor.toLowerCase() === hex.toLowerCase();
                      return (
                        <div key={idx} style={{ position: 'relative', display: 'inline-flex' }}>
                          <button
                            type="button"
                            onClick={() => setPrimaryColor(hex)}
                            onContextMenu={(e) => { e.preventDefault(); setSecondaryColor(hex); }}
                            title={`Left-Click = Primary, Right-Click = Accent: ${hex}`}
                            style={{
                              width: '38px',
                              height: '38px',
                              borderRadius: '8px',
                              background: hex,
                              border: isPrimary ? '3px solid #ffffff' : (isSecondary ? '3px dashed #ffffff' : '1px solid rgba(255, 255, 255, 0.25)'),
                              cursor: 'pointer',
                              boxShadow: isPrimary ? `0 0 14px ${hex}` : '0 2px 5px rgba(0,0,0,0.4)',
                              transition: 'all 0.18s ease',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center'
                            }}
                          >
                            {isPrimary && <span style={{ fontSize: '10px', fontWeight: '900', color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,0.9)' }}>P</span>}
                            {isSecondary && !isPrimary && <span style={{ fontSize: '10px', fontWeight: '900', color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,0.9)' }}>A</span>}
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Theme Color Pickers */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                gap: '1.25rem',
                marginTop: '1.25rem'
              }}>
                <div className="form-group">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.4rem' }}>
                    <label className="form-label" style={{ margin: 0 }}>Primary Brand Color</label>
                    <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>Main UI & Glow</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                    <input
                      type="color"
                      value={primaryColor}
                      onChange={e => setPrimaryColor(e.target.value)}
                      style={{
                        width: '44px',
                        height: '40px',
                        borderRadius: '6px',
                        border: 'none',
                        cursor: 'pointer',
                        background: 'transparent'
                      }}
                      id="primary-color-picker"
                    />
                    <input
                      type="text"
                      className="form-input"
                      value={primaryColor}
                      onChange={e => setPrimaryColor(e.target.value)}
                      placeholder="#fe480a"
                      style={{ fontFamily: 'monospace', textTransform: 'uppercase' }}
                    />
                  </div>
                </div>

                <div className="form-group">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.4rem' }}>
                    <label className="form-label" style={{ margin: 0 }}>Secondary Accent Color</label>
                    <span style={{ fontSize: '0.7rem', color: 'var(--text-muted)' }}>Gradients & Swirls</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                    <input
                      type="color"
                      value={secondaryColor}
                      onChange={e => setSecondaryColor(e.target.value)}
                      style={{
                        width: '44px',
                        height: '40px',
                        borderRadius: '6px',
                        border: 'none',
                        cursor: 'pointer',
                        background: 'transparent'
                      }}
                      id="secondary-color-picker"
                    />
                    <input
                      type="text"
                      className="form-input"
                      value={secondaryColor}
                      onChange={e => setSecondaryColor(e.target.value)}
                      placeholder="#fdc51b"
                      style={{ fontFamily: 'monospace', textTransform: 'uppercase' }}
                    />
                  </div>
                </div>
              </div>

              {/* Action Button */}
              <div style={{ marginTop: '2rem', display: 'flex', alignItems: 'center', gap: '1rem' }}>
                <button
                  type="submit"
                  className="btn-primary"
                  id="save-branding-submit-btn"
                  disabled={savingTheme}
                  style={{
                    padding: '0.85rem 1.8rem',
                    background: `linear-gradient(135deg, ${primaryColor} 0%, ${secondaryColor} 100%)`
                  }}
                >
                  {savingTheme ? <RefreshCw size={16} className="spinner" /> : <CheckCircle2 size={16} />}
                  <span>{savingTheme ? 'Applying Theme Across Site...' : 'Save & Adopt Logo Colors Everywhere'}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* TAB: VIDEO SCREEN LOGO / WATERMARK */}
      {activeTab === 'screen-logo' && (
        <div className="admin-card" id="screen-logo-card">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
            <div>
              <h3 style={{ fontSize: '1.3rem', display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                <Eye size={22} style={{ color: 'var(--accent-primary)' }} />
                <span>Video Screen Logo & Watermark Overlay</span>
              </h3>
              <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginTop: '0.25rem' }}>
                Display your brand logo directly on top of the live video stream (like broadcast channel bugs). Customize the logo, transparency/opacity, position (Top-Right, Top-Left, Bottom-Right, Bottom-Left), and scale in real-time.
              </p>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', fontSize: '0.88rem', fontWeight: '600' }}>
                <input 
                  type="checkbox"
                  id="screen-logo-toggle"
                  checked={screenLogoEnabled}
                  onChange={e => setScreenLogoEnabled(e.target.checked)}
                  style={{ width: '18px', height: '18px', accentColor: 'var(--accent-primary)', cursor: 'pointer' }}
                />
                <span>Enable Screen Logo</span>
              </label>
            </div>
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: 'minmax(320px, 440px) 1fr',
            gap: '2rem',
            alignItems: 'start'
          }}>
            {/* Left: Interactive Live 16:9 Video Canvas Simulation */}
            <div style={{
              background: 'rgba(0, 0, 0, 0.5)',
              border: '1px solid var(--border-subtle)',
              borderRadius: 'var(--radius-md)',
              padding: '1.25rem',
              display: 'flex',
              flexDirection: 'column',
              gap: '1rem'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '0.8rem', fontWeight: '700', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  Live Screen Preview (16:9)
                </span>
                <span style={{
                  fontSize: '0.72rem',
                  padding: '0.2rem 0.55rem',
                  borderRadius: 'var(--radius-full)',
                  background: screenLogoEnabled ? 'rgba(16, 185, 129, 0.15)' : 'rgba(239, 68, 68, 0.15)',
                  color: screenLogoEnabled ? '#10b981' : '#ef4444',
                  fontWeight: '600'
                }}>
                  {screenLogoEnabled ? 'Visible' : 'Hidden'}
                </span>
              </div>

              {/* Simulated 16:9 Video Screen */}
              <div style={{
                position: 'relative',
                width: '100%',
                aspectRatio: '16 / 9',
                background: 'linear-gradient(135deg, #090d16 0%, #151c2e 50%, #060911 100%)',
                borderRadius: 'var(--radius-sm)',
                overflow: 'hidden',
                border: '1px solid rgba(255, 255, 255, 0.1)',
                boxShadow: 'inset 0 0 40px rgba(0, 0, 0, 0.8)'
              }}>
                {/* Simulated live video graphics */}
                <div style={{
                  position: 'absolute',
                  inset: 0,
                  opacity: 0.25,
                  backgroundImage: 'radial-gradient(circle at 30% 30%, rgba(251, 66, 9, 0.4) 0%, transparent 60%), radial-gradient(circle at 70% 70%, rgba(244, 184, 25, 0.3) 0%, transparent 60%)'
                }} />

                {/* Simulated center live stream text */}
                <div style={{
                  position: 'absolute',
                  inset: 0,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '0.3rem',
                  pointerEvents: 'none',
                  opacity: 0.4
                }}>
                  <Play size={28} style={{ color: '#fff' }} />
                  <span style={{ fontSize: '0.75rem', fontWeight: '600', color: '#fff' }}>LIVE STREAM SIMULATION</span>
                </div>

                {/* Simulated Bottom Controls Bar */}
                <div style={{
                  position: 'absolute',
                  bottom: 0,
                  left: 0,
                  right: 0,
                  height: '24px',
                  background: 'linear-gradient(to top, rgba(0,0,0,0.85), transparent)',
                  display: 'flex',
                  alignItems: 'center',
                  padding: '0 0.5rem',
                  gap: '0.4rem',
                  opacity: 0.6
                }}>
                  <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: 'var(--accent-primary)' }} />
                  <div style={{ flex: 1, height: '3px', borderRadius: '2px', background: 'rgba(255,255,255,0.2)' }}>
                    <div style={{ width: '40%', height: '100%', background: 'var(--accent-primary)', borderRadius: '2px' }} />
                  </div>
                </div>

                {/* Simulated Watermark Logo Overlay */}
                {screenLogoEnabled && screenLogoPreview && (
                  <div
                    style={{
                      position: 'absolute',
                      zIndex: 10,
                      top: screenLogoPosition.startsWith('top') ? '0.75rem' : 'auto',
                      bottom: screenLogoPosition.startsWith('bottom') ? '1.75rem' : 'auto',
                      left: screenLogoPosition.endsWith('left') ? '0.75rem' : 'auto',
                      right: screenLogoPosition.endsWith('right') ? '0.75rem' : 'auto',
                      opacity: screenLogoOpacity,
                      maxWidth: `${Math.round(screenLogoSize * 0.75)}px`,
                      transition: 'all 0.2s ease',
                      pointerEvents: 'none'
                    }}
                  >
                    <img
                      src={screenLogoPreview}
                      alt="Watermark Simulation"
                      style={{
                        width: '100%',
                        height: 'auto',
                        maxHeight: '45px',
                        objectFit: 'contain',
                        filter: 'drop-shadow(0 2px 6px rgba(0,0,0,0.85))'
                      }}
                    />
                  </div>
                )}
              </div>

              {/* Status summary */}
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr 1fr',
                gap: '0.5rem',
                fontSize: '0.75rem',
                color: 'var(--text-muted)',
                background: 'rgba(255, 255, 255, 0.02)',
                padding: '0.6rem 0.75rem',
                borderRadius: 'var(--radius-sm)'
              }}>
                <div>
                  <span style={{ opacity: 0.6, display: 'block' }}>Position</span>
                  <strong style={{ color: '#fff', textTransform: 'capitalize' }}>{screenLogoPosition.replace('-', ' ')}</strong>
                </div>
                <div>
                  <span style={{ opacity: 0.6, display: 'block' }}>Opacity</span>
                  <strong style={{ color: '#fff' }}>{Math.round(screenLogoOpacity * 100)}%</strong>
                </div>
                <div>
                  <span style={{ opacity: 0.6, display: 'block' }}>Width</span>
                  <strong style={{ color: '#fff' }}>{screenLogoSize}px</strong>
                </div>
              </div>
            </div>

            {/* Right: Controls & Options */}
            <form onSubmit={handleSaveScreenLogo} style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
              {/* Option 1: Change Logo Image */}
              <div style={{
                background: 'rgba(255, 255, 255, 0.02)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem'
              }}>
                <label className="form-label" style={{ fontSize: '0.95rem', fontWeight: '700', marginBottom: '0.4rem' }}>
                  1. Screen Logo Image
                </label>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.9rem' }}>
                  Select or upload an image file to display on screen (transparent PNG or WebP recommended for clean overlay).
                </p>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                  <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                    <input
                      type="file"
                      id="screen-logo-file-input"
                      className="form-input"
                      accept="image/png,image/webp,image/svg+xml,image/jpeg"
                      onChange={handleScreenLogoFileChange}
                      style={{ padding: '0.5rem', flex: 1, minWidth: '220px' }}
                    />
                    <button
                      type="button"
                      onClick={handleResetToDefaultWatermark}
                      className="btn-secondary"
                      style={{ padding: '0.55rem 0.9rem', fontSize: '0.82rem', whiteSpace: 'nowrap' }}
                      id="reset-watermark-btn"
                    >
                      <Sparkles size={14} style={{ color: 'var(--accent-primary)' }} />
                      <span>Use Default Tornado Logo</span>
                    </button>
                  </div>

                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <span style={{ fontSize: '0.75rem', color: 'var(--text-faint)' }}>Or image URL:</span>
                    <input
                      type="text"
                      className="form-input"
                      value={screenLogoUrl}
                      onChange={e => {
                        setScreenLogoUrl(e.target.value);
                        setScreenLogoPreview(e.target.value);
                      }}
                      placeholder="/watermark.png or https://example.com/logo.png"
                      style={{ padding: '0.4rem 0.75rem', fontSize: '0.8rem', flex: 1 }}
                    />
                  </div>
                </div>
              </div>

              {/* Option 2: Position Selector */}
              <div style={{
                background: 'rgba(255, 255, 255, 0.02)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem'
              }}>
                <label className="form-label" style={{ fontSize: '0.95rem', fontWeight: '700', marginBottom: '0.4rem' }}>
                  2. Screen Position
                </label>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.9rem' }}>
                  Choose which corner of the video screen the logo floats on.
                </p>

                <div style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr 1fr',
                  gap: '0.75rem',
                  maxWidth: '420px'
                }}>
                  {[
                    { id: 'top-left', label: '↖ Top Left', desc: 'Header corner' },
                    { id: 'top-right', label: '↗ Top Right', desc: 'TV broadcast standard' },
                    { id: 'bottom-left', label: '↙ Bottom Left', desc: 'Above timeline' },
                    { id: 'bottom-right', label: '↘ Bottom Right', desc: 'Above controls' }
                  ].map(pos => (
                    <button
                      key={pos.id}
                      type="button"
                      onClick={() => setScreenLogoPosition(pos.id)}
                      id={`pos-btn-${pos.id}`}
                      style={{
                        background: screenLogoPosition === pos.id 
                          ? 'rgba(251, 66, 9, 0.15)' 
                          : 'rgba(255, 255, 255, 0.04)',
                        border: screenLogoPosition === pos.id 
                          ? '2px solid var(--accent-primary)' 
                          : '1px solid var(--border-subtle)',
                        borderRadius: 'var(--radius-sm)',
                        padding: '0.75rem 1rem',
                        cursor: 'pointer',
                        textAlign: 'left',
                        transition: 'all 0.18s ease',
                        boxShadow: screenLogoPosition === pos.id ? '0 0 15px var(--accent-glow)' : 'none'
                      }}
                    >
                      <div style={{
                        fontWeight: '700',
                        fontSize: '0.88rem',
                        color: screenLogoPosition === pos.id ? '#fff' : 'var(--text-primary)'
                      }}>
                        {pos.label}
                      </div>
                      <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '0.2rem' }}>
                        {pos.desc}
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Option 3: Opacity Controller */}
              <div style={{
                background: 'rgba(255, 255, 255, 0.02)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem'
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.4rem' }}>
                  <label className="form-label" style={{ fontSize: '0.95rem', fontWeight: '700', margin: 0 }}>
                    3. Logo Opacity / Transparency
                  </label>
                  <span style={{
                    fontWeight: '800',
                    fontSize: '0.95rem',
                    color: 'var(--accent-primary)',
                    background: 'rgba(251, 66, 9, 0.12)',
                    padding: '0.2rem 0.6rem',
                    borderRadius: 'var(--radius-sm)'
                  }}>
                    {Math.round(screenLogoOpacity * 100)}%
                  </span>
                </div>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.9rem' }}>
                  Adjust how transparent the watermark appears over the video stream.
                </p>

                <input
                  type="range"
                  min="0.10"
                  max="1.00"
                  step="0.05"
                  value={screenLogoOpacity}
                  onChange={e => setScreenLogoOpacity(parseFloat(e.target.value))}
                  id="screen-logo-opacity-slider"
                  style={{
                    width: '100%',
                    accentColor: 'var(--accent-primary)',
                    cursor: 'pointer',
                    height: '6px'
                  }}
                />

                <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem', flexWrap: 'wrap' }}>
                  {[
                    { label: '25% Subtle', val: 0.25 },
                    { label: '50% Semi', val: 0.50 },
                    { label: '75% Standard', val: 0.75 },
                    { label: '85% Default', val: 0.85 },
                    { label: '100% Solid', val: 1.00 }
                  ].map(preset => (
                    <button
                      key={preset.val}
                      type="button"
                      className="btn-secondary"
                      onClick={() => setScreenLogoOpacity(preset.val)}
                      style={{
                        padding: '0.25rem 0.6rem',
                        fontSize: '0.75rem',
                        background: Math.abs(screenLogoOpacity - preset.val) < 0.03 ? 'var(--accent-primary)' : undefined,
                        color: Math.abs(screenLogoOpacity - preset.val) < 0.03 ? '#fff' : undefined
                      }}
                    >
                      {preset.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Option 4: Size / Width Controller */}
              <div style={{
                background: 'rgba(255, 255, 255, 0.02)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-md)',
                padding: '1.25rem'
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.4rem' }}>
                  <label className="form-label" style={{ fontSize: '0.95rem', fontWeight: '700', margin: 0 }}>
                    4. Logo Size / Scale
                  </label>
                  <span style={{
                    fontWeight: '800',
                    fontSize: '0.95rem',
                    color: 'var(--accent-primary)',
                    background: 'rgba(251, 66, 9, 0.12)',
                    padding: '0.2rem 0.6rem',
                    borderRadius: 'var(--radius-sm)'
                  }}>
                    {screenLogoSize}px
                  </span>
                </div>
                <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginBottom: '0.9rem' }}>
                  Scale the logo width to fit your broadcast preference.
                </p>

                <input
                  type="range"
                  min="60"
                  max="260"
                  step="5"
                  value={screenLogoSize}
                  onChange={e => setScreenLogoSize(parseInt(e.target.value, 10))}
                  id="screen-logo-size-slider"
                  style={{
                    width: '100%',
                    accentColor: 'var(--accent-primary)',
                    cursor: 'pointer',
                    height: '6px'
                  }}
                />

                <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem', flexWrap: 'wrap' }}>
                  {[
                    { label: 'Small (90px)', val: 90 },
                    { label: 'Medium (130px)', val: 130 },
                    { label: 'Large (170px)', val: 170 },
                    { label: 'Extra Large (220px)', val: 220 }
                  ].map(preset => (
                    <button
                      key={preset.val}
                      type="button"
                      className="btn-secondary"
                      onClick={() => setScreenLogoSize(preset.val)}
                      style={{
                        padding: '0.25rem 0.6rem',
                        fontSize: '0.75rem',
                        background: screenLogoSize === preset.val ? 'var(--accent-primary)' : undefined,
                        color: screenLogoSize === preset.val ? '#fff' : undefined
                      }}
                    >
                      {preset.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Submit Button */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginTop: '0.5rem' }}>
                <button
                  type="submit"
                  className="btn-primary"
                  id="save-screen-logo-btn"
                  disabled={savingScreenLogo}
                  style={{
                    padding: '0.85rem 1.8rem',
                    fontSize: '0.92rem'
                  }}
                >
                  {savingScreenLogo ? <RefreshCw size={16} className="spinner" /> : <CheckCircle2 size={16} />}
                  <span>{savingScreenLogo ? 'Saving & Applying...' : 'Save & Apply Screen Logo'}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* TAB 5: SETTINGS */}
      {activeTab === 'settings' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: '2rem' }}>
          <div className="admin-card">
            <h3 style={{ fontSize: '1.3rem', marginBottom: '1.5rem' }}>Admin Security Settings</h3>
            <form onSubmit={handleChangePassword}>
              <div className="form-group">
                <label className="form-label">New Admin Password</label>
                <input
                  type="password"
                  className="form-input"
                  id="new-admin-password-input"
                  placeholder="Enter at least 5 characters"
                  value={newPassword}
                  onChange={e => setNewPassword(e.target.value)}
                  required
                />
              </div>
              <button type="submit" className="btn-primary">
                <Key size={16} />
                <span>Update Password</span>
              </button>
            </form>
          </div>

          <div className="admin-card">
            <h3 style={{ fontSize: '1.3rem', marginBottom: '0.5rem' }}>Visitor Traffic Counter</h3>
            <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '1.5rem' }}>
              Real-time live traffic is monitored automatically. You can manually adjust or seed the all-time total visitor counter here.
            </p>
            <form onSubmit={async (e) => {
              e.preventDefault();
              setUpdatingVisitors(true);
              try {
                const res = await fetch('/api/visitors', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ totalVisitors: parseInt(customTotalVisitors, 10) })
                });
                const data = await res.json();
                if (res.ok) {
                  setTotalVisitors(data.totalVisitors);
                  notify('Total visitors counter updated successfully!');
                } else {
                  notify(data.error || 'Failed to update total visitors', 'error');
                }
              } catch (err) {
                notify('Error updating visitors: ' + err.message, 'error');
              } finally {
                setUpdatingVisitors(false);
              }
            }}>
              <div className="form-group">
                <label className="form-label">Total All-Time Visitors</label>
                <input
                  type="number"
                  min="0"
                  className="form-input"
                  id="total-visitors-input"
                  value={customTotalVisitors}
                  onChange={e => setCustomTotalVisitors(e.target.value)}
                  required
                />
              </div>
              <button type="submit" className="btn-secondary" disabled={updatingVisitors}>
                <RefreshCw size={16} className={updatingVisitors ? 'spinner' : ''} />
                <span>{updatingVisitors ? 'Updating...' : 'Set Total Counter'}</span>
              </button>
            </form>
          </div>
        </div>
      )}

      {/* EDIT CHANNEL MODAL */}
      {editingChannel && (
        <div className="admin-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) closeEditModal(); }}>
          <div className="admin-modal-card">
            <div className="admin-modal-header">
              <h3>
                <Edit3 size={18} style={{ color: 'var(--accent-primary)' }} />
                <span>Edit Channel</span>
              </h3>
              <button className="admin-modal-close" onClick={closeEditModal} title="Close">
                <X size={18} />
              </button>
            </div>

            <form onSubmit={handleSaveEditedChannel}>
              <div className="admin-modal-body">
                {/* Channel Name */}
                <div className="form-group" style={{ margin: 0 }}>
                  <label className="form-label">Channel Name</label>
                  <input
                    type="text"
                    className="form-input"
                    value={editName}
                    onChange={e => setEditName(e.target.value)}
                    required
                  />
                </div>

                {/* Category Selection */}
                <div className="form-group" style={{ margin: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.4rem' }}>
                    <label className="form-label" style={{ margin: 0 }}>Category</label>
                    <span style={{ fontSize: '0.75rem', color: 'var(--accent-primary)' }}>
                      Current: {editingChannel.category || 'General'}
                    </span>
                  </div>
                  <select
                    className="form-input"
                    value={editCategory}
                    onChange={e => setEditCategory(e.target.value)}
                  >
                    {distinctCategories.map(cat => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                    <option value="__custom__">+ Add Custom Category...</option>
                  </select>

                  {editCategory === '__custom__' && (
                    <input
                      type="text"
                      className="form-input"
                      placeholder="Type custom category name..."
                      value={editCustomCategory}
                      onChange={e => setEditCustomCategory(e.target.value)}
                      style={{ marginTop: '0.5rem' }}
                      autoFocus
                      required
                    />
                  )}
                </div>

                {/* Logo Section */}
                <div className="form-group" style={{ margin: 0 }}>
                  <label className="form-label">Channel Logo</label>
                  <div className="channel-logo-edit-section">
                    <div className="channel-logo-preview-box">
                      {editLogo ? (
                        <img 
                          src={editLogo} 
                          alt="Logo Preview" 
                          onError={e => { e.currentTarget.style.opacity = '0.3'; }} 
                        />
                      ) : (
                        <Tv size={28} style={{ color: 'var(--text-faint)' }} />
                      )}
                    </div>
                    <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                      <input
                        type="text"
                        className="form-input"
                        placeholder="Logo image URL or /channel-logos/... path"
                        value={editLogo}
                        onChange={e => setEditLogo(e.target.value)}
                        style={{ fontSize: '0.85rem' }}
                      />
                      <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                        <label className="btn-secondary" style={{ padding: '0.4rem 0.75rem', fontSize: '0.8rem', cursor: 'pointer' }}>
                          <Upload size={13} />
                          <span>{isUploadingEditLogo ? 'Uploading...' : 'Upload Image File'}</span>
                          <input
                            type="file"
                            accept="image/*"
                            hidden
                            disabled={isUploadingEditLogo}
                            onChange={e => {
                              if (e.target.files?.[0]) handleUploadChannelLogo(e.target.files[0], false);
                            }}
                          />
                        </label>
                        <button
                          type="button"
                          className="btn-secondary"
                          style={{ padding: '0.4rem 0.75rem', fontSize: '0.8rem' }}
                          onClick={() => {
                            const autoLogo = `/channel-logos/${editingChannel.id}.png`;
                            setEditLogo(autoLogo);
                            notify('Reset to default channel asset logo');
                          }}
                          title="Reset to local channel logo"
                        >
                          <RotateCcw size={13} />
                          <span>Reset Logo</span>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Stream Source URL */}
                <div className="form-group" style={{ margin: 0 }}>
                  <label className="form-label">Stream Source URL (HLS / M3U8 / TS)</label>
                  <input
                    type="url"
                    className="form-input"
                    value={editStreamUrl}
                    onChange={e => setEditStreamUrl(e.target.value)}
                    required
                  />
                </div>
              </div>

              <div className="admin-modal-footer">
                <button type="button" className="btn-secondary" onClick={closeEditModal} disabled={savingChannel}>
                  Cancel
                </button>
                <button type="submit" className="btn-primary" disabled={savingChannel}>
                  {savingChannel ? (
                    <>
                      <RefreshCw size={15} className="spinner" />
                      <span>Saving Changes...</span>
                    </>
                  ) : (
                    <>
                      <Check size={15} />
                      <span>Save Channel</span>
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
