import"./animations-CS0Gouue.js";let u=localStorage.getItem("sportzx_admin_token"),T=[],_=[],P=[],N=[],q=[],k=null,y="";document.addEventListener("DOMContentLoaded",()=>{O(),R(),W(),V(),ee(),J(),Q(),ae()});async function O(){if(!u){I();return}try{(await fetch("/api/admin/verify",{headers:{Authorization:`Bearer ${u}`}})).ok?(D(),b()):(localStorage.removeItem("sportzx_admin_token"),u=null,I())}catch{I()}}function h(){return u?!0:(I(),!1)}function I(){document.getElementById("login-overlay").classList.remove("hidden"),document.getElementById("admin-main-container").classList.add("hidden")}function D(){document.getElementById("login-overlay").classList.add("hidden"),document.getElementById("admin-main-container").classList.remove("hidden")}function R(){const t=document.getElementById("login-form"),e=document.getElementById("login-alert-placeholder");t.addEventListener("submit",async()=>{const n=document.getElementById("login-username").value,l=document.getElementById("login-password").value;try{const a=await fetch("/api/admin/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:l})}),r=await a.json();a.ok?(u=r.token,localStorage.setItem("sportzx_admin_token",u),e.innerHTML="",D(),b()):e.innerHTML=`<div class="alert alert-error">${r.error||"Login failed"}</div>`}catch(a){e.innerHTML=`<div class="alert alert-error">Network error: ${a.message}</div>`}}),document.getElementById("btn-logout").addEventListener("click",()=>{localStorage.removeItem("sportzx_admin_token"),u=null,I()})}function W(){const t=document.querySelectorAll(".admin-menu-item"),e=document.querySelectorAll(".admin-panel");t.forEach(n=>{n.addEventListener("click",()=>{const l=n.getAttribute("data-panel");l&&(t.forEach(a=>a.classList.remove("active")),n.classList.add("active"),e.forEach(a=>{a.getAttribute("id")===`panel-${l}`?a.classList.add("active"):a.classList.remove("active")}))})})}function V(){const t=document.getElementById("btn-admin-hamburger"),e=document.querySelector(".admin-sidebar"),n=document.getElementById("admin-sidebar-overlay");t&&e&&n&&(t.addEventListener("click",()=>{e.classList.add("open"),n.classList.add("active")}),n.addEventListener("click",()=>{e.classList.remove("open"),n.classList.remove("active")}),e.querySelectorAll(".admin-menu-item").forEach(a=>{a.addEventListener("click",()=>{e.classList.remove("open"),n.classList.remove("active")})}))}function J(){const t=document.getElementById("btn-clear-db"),e=document.getElementById("clear-db-alert-placeholder");t&&t.addEventListener("click",async()=>{if(confirm("Are you absolutely sure you want to delete ALL channels and categories? This cannot be undone.")&&h()){t.textContent="Clearing...",t.disabled=!0,e&&(e.innerHTML="");try{const n=await fetch("/api/channels/clear",{method:"POST",headers:{Authorization:`Bearer ${u}`}}),l=await n.json();n.ok?(e&&(e.innerHTML='<div class="alert alert-success">Database cleared successfully!</div>'),b()):e&&(e.innerHTML=`<div class="alert alert-error">Clear failed: ${l.error||"Server error"}</div>`)}catch(n){e&&(e.innerHTML=`<div class="alert alert-error">Network error: ${n.message}</div>`)}finally{t.textContent="Clear All Channels & Categories",t.disabled=!1}}})}async function b(){if(h())try{const[t,e,n,l,a]=await Promise.all([fetch("/api/categories").then(o=>o.json()),fetch("/api/channels").then(o=>o.json()),fetch("/api/events").then(o=>o.json()),fetch("/api/highlights").then(o=>o.json()),fetch("/api/playlists").then(o=>o.json()).catch(()=>[])]);T=t,_=e,P=n,N=l,q=a;const r=document.getElementById("stat-channels"),s=document.getElementById("stat-categories"),c=document.getElementById("stat-events"),d=document.getElementById("stat-highlights");r&&(r.textContent=_.length),s&&(s.textContent=T.length),c&&(c.textContent=P.filter(o=>o.status.toLowerCase()==="live").length),d&&(d.textContent=N.length),G(),K(),X(),Z(),te(),le()}catch(t){console.error("Error loading data:",t.message)}}function G(){const t=document.querySelector("#categories-table tbody");t.innerHTML="",T.forEach(e=>{const n=document.createElement("tr");n.innerHTML=`
      <td style="font-weight:600;">${e.name}</td>
      <td>${e.display_order}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-category" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-category" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `,n.querySelector(".btn-edit-category").addEventListener("click",()=>C("categories",e)),n.querySelector(".btn-delete-category").addEventListener("click",()=>w("categories",e.id)),t.appendChild(n)})}function K(){const t=document.querySelector("#channels-table tbody");t.innerHTML="",_.forEach(e=>{const n=document.createElement("tr"),l=e.name.substring(0,2).toUpperCase(),a=e.logo_url?`<img src="${e.logo_url}" onerror="this.outerHTML='<div class=\\'category-icon-fallback\\' style=\\'width:32px; height:32px; font-size:0.75rem; border-radius:6px;\\'>${l}</div>'">`:`<div class="category-icon-fallback" style="width:32px; height:32px; font-size:0.75rem; border-radius:6px;">${l}</div>`;n.innerHTML=`
      <td>${a}</td>
      <td style="font-weight:600;">${e.name}</td>
      <td>${e.category_name||"Uncategorized"}</td>
      <td style="font-family:monospace; font-size:0.75rem; max-width: 250px; text-overflow:ellipsis; overflow:hidden; white-space:nowrap;">${e.stream_url}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-channel" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-channel" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `,n.querySelector(".btn-edit-channel").addEventListener("click",()=>C("channels",e)),n.querySelector(".btn-delete-channel").addEventListener("click",()=>w("channels",e.id)),t.appendChild(n)})}function X(){const t=document.querySelector("#events-table tbody");t.innerHTML="",P.forEach(e=>{const n=document.createElement("tr");n.innerHTML=`
      <td style="color:var(--accent-cyan); font-weight:600;">${e.league||"Event"}</td>
      <td style="font-weight:600;">${e.title}</td>
      <td><span class="badge ${e.status.toLowerCase()==="live"?"badge-live":""}">${e.status}</span></td>
      <td>${e.category}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-event" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-event" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `,n.querySelector(".btn-edit-event").addEventListener("click",()=>C("events",e)),n.querySelector(".btn-delete-event").addEventListener("click",()=>w("events",e.id)),t.appendChild(n)})}function Z(){const t=document.querySelector("#highlights-table tbody");t.innerHTML="",N.forEach(e=>{const n=document.createElement("tr");n.innerHTML=`
      <td style="color:var(--text-secondary);">${e.league||"Highlight"}</td>
      <td style="font-weight:600;">${e.title}</td>
      <td style="font-family:monospace; font-weight:700;">${e.score1} : ${e.score2}</td>
      <td>${e.date||""}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-hl" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-hl" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `,n.querySelector(".btn-edit-hl").addEventListener("click",()=>C("highlights",e)),n.querySelector(".btn-delete-hl").addEventListener("click",()=>w("highlights",e.id)),t.appendChild(n)})}async function w(t,e){if(confirm("Are you sure you want to delete this item?")&&h())try{const n=await fetch(`/api/${t}/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`}});if(n.ok)b();else{const l=await n.json();alert("Delete failed: "+(l.error||"Unknown error"))}}catch(n){alert("Network error: "+n.message)}}function Q(){document.getElementById("btn-add-category-modal").addEventListener("click",()=>$("categories")),document.getElementById("btn-add-channel-modal").addEventListener("click",()=>$("channels")),document.getElementById("btn-add-event-modal").addEventListener("click",()=>$("events")),document.getElementById("btn-add-highlight-modal").addEventListener("click",()=>$("highlights")),document.getElementById("btn-modal-close").addEventListener("click",j),document.getElementById("btn-modal-save").addEventListener("click",Y)}function $(t){k=null,y=t,document.getElementById("crud-modal-title").textContent=`Add New ${t.slice(0,-1).toUpperCase()}`,F(t),document.getElementById("crud-modal").classList.add("active")}function C(t,e){k=e,y=t,document.getElementById("crud-modal-title").textContent=`Edit ${t.slice(0,-1).toUpperCase()}`,F(t,e),document.getElementById("crud-modal").classList.add("active")}function j(){document.getElementById("crud-modal").classList.remove("active")}function F(t,e=null){const n=document.getElementById("crud-modal-body");if(n.innerHTML="",t==="categories")n.innerHTML=`
      <div class="form-group">
        <label>Category Name</label>
        <input type="text" class="form-control" id="f-cat-name" value="${e?e.name:""}" required>
      </div>
      <div class="form-group">
        <label>Display Order</label>
        <input type="number" class="form-control" id="f-cat-order" value="${e?e.display_order:0}">
      </div>
      <div class="form-group">
        <label>Category Logo URL (Optional)</label>
        <input type="url" class="form-control" id="f-cat-logo" value="${e&&e.logo_url||""}">
      </div>
    `;else if(t==="channels"){const l=T.map(r=>`<option value="${r.id}" ${e&&e.category_id===r.id?"selected":""}>${r.name}</option>`).join("");n.innerHTML=`
      <div class="form-group">
        <label>Channel Name</label>
        <input type="text" class="form-control" id="f-chan-name" value="${e?e.name:""}" required>
      </div>
      <div class="form-group">
        <label>Category</label>
        <select class="form-control" id="f-chan-category">
          <option value="">Select Category</option>
          ${l}
        </select>
      </div>
      <div class="form-group">
        <label>Logo URL (Optional)</label>
        <input type="url" class="form-control" id="f-chan-logo" value="${e&&e.logo_url||""}">
      </div>
      <div class="form-group">
        <label>Default Stream URL</label>
        <input type="text" class="form-control" id="f-chan-url" value="${e?e.stream_url:""}" placeholder="http://...m3u8" required>
      </div>
      
      ${e?"":`
      <div class="form-group" style="display:flex; align-items:center; gap:12px; margin-bottom: 24px;">
        <label class="switch" style="margin-bottom:0; flex-shrink:0;">
          <input type="checkbox" id="f-chan-merge">
          <span class="slider"></span>
        </label>
        <span style="font-size:0.9rem; font-weight:600; color:var(--text-secondary);">Merge if Channel exists (Same Name & Category)</span>
      </div>
      `}
      
      <!-- Multi-server stream settings -->
      <div class="form-group">
        <label style="display:flex; justify-content:space-between; align-items:center;">
          <span>Streaming Servers List</span>
          <button class="btn btn-secondary" id="btn-add-server-input" style="padding: 2px 8px; font-size: 0.75rem;">+ Add Server</button>
        </label>
        <div id="servers-input-list" style="margin-top: 10px;">
          <!-- Dynamically populated server rows -->
        </div>
      </div>
    `,(e&&e.servers?e.servers:[{name:"Primary Server",url:e?e.stream_url:""}]).forEach(r=>S(r.name,r.url)),document.getElementById("btn-add-server-input").addEventListener("click",r=>{r.preventDefault(),S("","")})}else t==="events"?(n.innerHTML=`
      <div class="form-group">
        <label>Event Match Title</label>
        <input type="text" class="form-control" id="f-event-title" value="${e?e.title:""}" placeholder="Argentina VS Honduras" required>
      </div>
      <div class="form-group">
        <label>League Name</label>
        <input type="text" class="form-control" id="f-event-league" value="${e&&e.league||""}" placeholder="National Friendly Games">
      </div>
      <div class="form-group">
        <label>Sports Category</label>
        <select class="form-control" id="f-event-category">
          <option value="Football" ${e&&e.category==="Football"?"selected":""}>Football</option>
          <option value="Cricket" ${e&&e.category==="Cricket"?"selected":""}>Cricket</option>
          <option value="WWE" ${e&&e.category==="WWE"?"selected":""}>WWE</option>
          <option value="IPL" ${e&&e.category==="IPL"?"selected":""}>IPL</option>
        </select>
      </div>
      <div class="form-group">
        <label>Status</label>
        <select class="form-control" id="f-event-status">
          <option value="Upcoming" ${e&&e.status==="Upcoming"?"selected":""}>Upcoming</option>
          <option value="Live" ${e&&e.status==="Live"?"selected":""}>Live</option>
          <option value="Ended" ${e&&e.status==="Ended"?"selected":""}>Ended</option>
        </select>
      </div>
      <div class="form-group">
        <label>Start Date/Time String</label>
        <input type="text" class="form-control" id="f-event-time" value="${e&&e.start_time||""}" placeholder="e.g. 06:00 AM 07/06/2026">
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Name</label>
          <input type="text" class="form-control" id="f-event-t1name" value="${e&&e.team1_name||""}">
        </div>
        <div class="form-group">
          <label>Team 2 Name</label>
          <input type="text" class="form-control" id="f-event-t2name" value="${e&&e.team2_name||""}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Logo URL</label>
          <input type="url" class="form-control" id="f-event-t1logo" value="${e&&e.team1_logo||""}">
        </div>
        <div class="form-group">
          <label>Team 2 Logo URL</label>
          <input type="url" class="form-control" id="f-event-t2logo" value="${e&&e.team2_logo||""}">
        </div>
      </div>
      
      <!-- Live event multiple streaming servers setup -->
      <div class="form-group">
        <label style="display:flex; justify-content:space-between; align-items:center;">
          <span>Event Streaming Servers</span>
          <button class="btn btn-secondary" id="btn-add-event-srv" style="padding: 2px 8px; font-size: 0.75rem;">+ Add Server</button>
        </label>
        <div id="servers-input-list" style="margin-top: 10px;">
          <!-- Dynamically populated server rows -->
        </div>
      </div>
    `,(e&&e.servers?e.servers:[]).forEach(a=>S(a.name,a.url)),document.getElementById("btn-add-event-srv").addEventListener("click",a=>{a.preventDefault(),S("","")})):t==="highlights"&&(n.innerHTML=`
      <div class="form-group">
        <label>Highlights Video Title</label>
        <input type="text" class="form-control" id="f-hl-title" value="${e?e.title:""}" placeholder="Argentina vs Honduras Highlights" required>
      </div>
      <div class="form-group">
        <label>League Name</label>
        <input type="text" class="form-control" id="f-hl-league" value="${e&&e.league||""}">
      </div>
      <div class="form-group">
        <label>Sports Category</label>
        <select class="form-control" id="f-hl-category">
          <option value="Football" ${e&&e.category==="Football"?"selected":""}>Football</option>
          <option value="Cricket" ${e&&e.category==="Cricket"?"selected":""}>Cricket</option>
          <option value="IPL" ${e&&e.category==="IPL"?"selected":""}>IPL</option>
        </select>
      </div>
      <div class="form-group">
        <label>Date String</label>
        <input type="text" class="form-control" id="f-hl-date" value="${e&&e.date||""}" placeholder="e.g. 06/06/2026">
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Name</label>
          <input type="text" class="form-control" id="f-hl-t1name" value="${e&&e.team1_name||""}">
        </div>
        <div class="form-group">
          <label>Team 2 Name</label>
          <input type="text" class="form-control" id="f-hl-t2name" value="${e&&e.team2_name||""}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Logo URL</label>
          <input type="url" class="form-control" id="f-hl-t1logo" value="${e&&e.team1_logo||""}">
        </div>
        <div class="form-group">
          <label>Team 2 Logo URL</label>
          <input type="url" class="form-control" id="f-hl-t2logo" value="${e&&e.team2_logo||""}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Score</label>
          <input type="text" class="form-control" id="f-hl-score1" value="${e&&e.score1||"0"}">
        </div>
        <div class="form-group">
          <label>Team 2 Score</label>
          <input type="text" class="form-control" id="f-hl-score2" value="${e&&e.score2||"0"}">
        </div>
      </div>
      <div class="form-group">
        <label>Highlight Video URL (HLS .m3u8)</label>
        <input type="text" class="form-control" id="f-hl-video" value="${e?e.video_url:""}" placeholder="http://...m3u8" required>
      </div>
    `)}function S(t="",e=""){const n=document.getElementById("servers-input-list"),l=document.createElement("div");l.className="server-input-row",l.innerHTML=`
    <input type="text" class="form-control srv-name" value="${t}" placeholder="Server Name (e.g. SportzX MLB)" style="flex:1;">
    <input type="text" class="form-control srv-url" value="${e}" placeholder="HLS Stream URL (.m3u8)" style="flex:2;">
    <button class="btn btn-danger btn-remove-srv" style="padding: 10px;">✕</button>
  `,l.querySelector(".btn-remove-srv").addEventListener("click",a=>{a.preventDefault(),l.remove()}),n.appendChild(l)}function A(){const t=document.getElementById("servers-input-list");if(!t)return[];const e=t.querySelectorAll(".server-input-row"),n=[];return e.forEach(l=>{const a=l.querySelector(".srv-name").value.trim(),r=l.querySelector(".srv-url").value.trim();a&&r&&n.push({name:a,url:r})}),n}async function Y(){if(!h())return;let t=`/api/${y}`,e="POST",n={};if(k&&(t=`/api/${y}/${k.id}`,e="PUT"),y==="categories"){const l=document.getElementById("f-cat-name").value.trim(),a=Number(document.getElementById("f-cat-order").value),r=document.getElementById("f-cat-logo").value.trim();if(!l)return alert("Name is required");n={name:l,display_order:a,logo_url:r}}else if(y==="channels"){const l=document.getElementById("f-chan-name").value.trim(),a=document.getElementById("f-chan-category").value,r=document.getElementById("f-chan-logo").value.trim(),s=document.getElementById("f-chan-url").value.trim(),c=A(),d=document.getElementById("f-chan-merge"),o=d?d.checked:!1;if(!l||!s)return alert("Name and Stream URL are required");n={name:l,stream_url:s,logo_url:r,category_id:a?Number(a):null,servers:c.length>0?c:[{name:"Primary Server",url:s}],merge:o}}else if(y==="events"){const l=document.getElementById("f-event-title").value.trim(),a=document.getElementById("f-event-league").value.trim(),r=document.getElementById("f-event-category").value,s=document.getElementById("f-event-status").value,c=document.getElementById("f-event-time").value.trim(),d=document.getElementById("f-event-t1name").value.trim(),o=document.getElementById("f-event-t2name").value.trim(),f=document.getElementById("f-event-t1logo").value.trim(),p=document.getElementById("f-event-t2logo").value.trim(),v=A();if(!l)return alert("Title is required");n={title:l,league:a,category:r,status:s,start_time:c,team1_name:d,team2_name:o,team1_logo:f,team2_logo:p,servers:v}}else if(y==="highlights"){const l=document.getElementById("f-hl-title").value.trim(),a=document.getElementById("f-hl-league").value.trim(),r=document.getElementById("f-hl-category").value,s=document.getElementById("f-hl-date").value.trim(),c=document.getElementById("f-hl-t1name").value.trim(),d=document.getElementById("f-hl-t2name").value.trim(),o=document.getElementById("f-hl-t1logo").value.trim(),f=document.getElementById("f-hl-t2logo").value.trim(),p=document.getElementById("f-hl-score1").value.trim(),v=document.getElementById("f-hl-score2").value.trim(),L=document.getElementById("f-hl-video").value.trim();if(!l||!L)return alert("Title and Video URL are required");n={title:l,league:a,category:r,date:s,team1_name:c,team2_name:d,team1_logo:o,team2_logo:f,score1:p,score2:v,video_url:L}}try{const l=await fetch(t,{method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(n)});if(l.ok)j(),b();else{const a=await l.json();alert("Save failed: "+(a.error||"Server error"))}}catch(l){alert("Network error: "+l.message)}}function ee(){const t=document.getElementById("tab-import-paste"),e=document.getElementById("tab-import-file"),n=document.getElementById("tab-import-url"),l=document.getElementById("content-import-paste"),a=document.getElementById("content-import-file"),r=document.getElementById("content-import-url"),s=document.getElementById("m3u-drag-drop"),c=document.getElementById("m3u-file-input"),d=document.getElementById("m3u-file-name"),o=document.getElementById("playlist-name-input"),f=document.getElementById("playlist-url-input"),p=document.getElementById("btn-import-m3u"),v=document.getElementById("m3u-alert-placeholder"),L=document.getElementById("m3u-textarea");let E="paste",x="",M="";t&&e&&n&&(t.addEventListener("click",()=>{E="paste",t.classList.add("active"),e.classList.remove("active"),n.classList.remove("active"),l.classList.remove("hidden"),a.classList.add("hidden"),r.classList.add("hidden")}),e.addEventListener("click",()=>{E="file",e.classList.add("active"),t.classList.remove("active"),n.classList.remove("active"),a.classList.remove("hidden"),l.classList.add("hidden"),r.classList.add("hidden")}),n.addEventListener("click",()=>{E="url",n.classList.add("active"),t.classList.remove("active"),e.classList.remove("active"),r.classList.remove("hidden"),l.classList.add("hidden"),a.classList.add("hidden")})),s&&c&&(s.addEventListener("click",()=>c.click()),c.addEventListener("change",i=>{const m=i.target.files[0];m&&z(m)}),s.addEventListener("dragover",i=>{i.preventDefault(),s.style.borderColor="var(--accent-secondary)",s.style.background="rgba(255, 255, 255, 0.06)"}),s.addEventListener("dragleave",()=>{s.style.borderColor="rgba(255, 255, 255, 0.15)",s.style.background="rgba(255, 255, 255, 0.02)"}),s.addEventListener("drop",i=>{i.preventDefault(),s.style.borderColor="rgba(255, 255, 255, 0.15)",s.style.background="rgba(255, 255, 255, 0.02)";const m=i.dataTransfer.files[0];m&&z(m)}));function z(i){M=i.name,d&&(d.textContent=`Selected: ${i.name} (${(i.size/1024).toFixed(1)} KB)`),o&&!o.value.trim()&&(o.value=i.name.replace(/\.[^/.]+$/,""));const m=new FileReader;m.onload=B=>{x=B.target.result},m.readAsText(i)}p.addEventListener("click",async()=>{let i={};const m=o?o.value.trim():"",B=document.getElementById("m3u-merge-toggle"),H=B?B.checked:!1;if(E==="paste"){const g=L.value.trim();if(!g){v.innerHTML='<div class="alert alert-error">Please paste M3U playlist content first.</div>';return}i={m3u:g,playlist_name:m,merge:H}}else if(E==="file"){if(!x){v.innerHTML='<div class="alert alert-error">Please select or upload an M3U file first.</div>';return}i={m3u:x,playlist_name:m||M,merge:H}}else if(E==="url"){const g=f?f.value.trim():"";if(!g){v.innerHTML='<div class="alert alert-error">Please enter a valid remote playlist URL.</div>';return}i={playlist_url:g,playlist_name:m,merge:H}}if(h()){p.textContent="Importing... Please wait",p.disabled=!0,v.innerHTML="";try{const g=await fetch("/api/channels/import",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(i)}),U=await g.json();g.ok?(v.innerHTML=`<div class="alert alert-success">Playlist "${U.playlistName||"IPTV"}" imported successfully! Channels and Categories synced.</div>`,L.value="",f&&(f.value=""),o&&(o.value=""),d&&(d.textContent=""),x="",M="",b()):v.innerHTML=`<div class="alert alert-error">Import failed: ${U.error||"Server error"}</div>`}catch(g){v.innerHTML=`<div class="alert alert-error">Network error: ${g.message}</div>`}finally{p.textContent="Start Bulk Import",p.disabled=!1}}})}function te(){const t=document.querySelector("#playlists-table tbody");if(t){if(t.innerHTML="",q.length===0){t.innerHTML='<tr><td colspan="3" style="text-align:center; color:var(--text-muted); padding:20px 0; font-size:0.85rem;">No playlists uploaded yet.</td></tr>';return}q.forEach(e=>{const n=document.createElement("tr");n.innerHTML=`
      <td style="font-weight:600;">${e.name}</td>
      <td style="font-family:monospace; font-size:0.75rem; color:var(--text-secondary); max-width: 250px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${e.url||"Direct File / Paste"}</td>
      <td class="actions">
        <button class="btn btn-danger btn-delete-playlist" style="padding: 6px 12px; font-size: 0.75rem;" data-id="${e.id}">Delete</button>
      </td>
    `,n.querySelector(".btn-delete-playlist").addEventListener("click",()=>ne(e.id,e.name)),t.appendChild(n)})}}async function ne(t,e){if(!confirm(`Are you absolutely sure you want to delete playlist "${e}"? This will permanently delete all channels associated with it.`)||!h())return;const n=document.getElementById("playlist-mgr-alert-placeholder");n&&(n.innerHTML="");try{const l=await fetch(`/api/playlists/${t}`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`}});if(l.ok)n&&(n.innerHTML=`<div class="alert alert-success">Playlist "${e}" deleted successfully!</div>`),b();else{const a=await l.json();alert("Delete failed: "+(a.error||"Unknown error"))}}catch(l){alert("Network error: "+l.message)}}async function le(){try{const t=await fetch("/api/settings/announcement");if(t.ok){const e=await t.json();document.getElementById("announcement-input").value=e.value||""}}catch(t){console.error("Error fetching announcement setting:",t.message)}}function ae(){const t=document.getElementById("btn-save-announcement"),e=document.getElementById("settings-alert-placeholder"),n=document.getElementById("announcement-input");t.addEventListener("click",async()=>{const l=n.value.trim();if(h()){t.textContent="Saving...",t.disabled=!0,e.innerHTML="";try{const a=await fetch("/api/settings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify({key:"announcement",value:l})}),r=await a.json();a.ok?e.innerHTML='<div class="alert alert-success">Announcement saved successfully!</div>':e.innerHTML=`<div class="alert alert-error">Save failed: ${r.error||"Server error"}</div>`}catch(a){e.innerHTML=`<div class="alert alert-error">Network error: ${a.message}</div>`}finally{t.textContent="Save Announcement",t.disabled=!1}}})}
