dPaste

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#090909">
<title>NEXORA — Cinema sem sair do lugar</title>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>

<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700;800&family=Manrope:wght@400;500;600;700;800&display=swap');
:root{--bg:#090909;--panel:#141414;--panel2:#1d1d1d;--red:#e50914;--white:#f7f7f7;--muted:#999;--line:#ffffff18}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{margin:0;background:var(--bg);color:var(--white);font-family:"DM Sans",Arial,sans-serif;min-width:300px}
button,input,select,textarea{font:inherit}
button{cursor:pointer;color:inherit}
a{color:inherit;text-decoration:none}
.hidden{display:none!important}
.shell{width:min(100% - 36px,1440px);margin:auto}
header{position:sticky;top:0;z-index:30;background:#090909ed;backdrop-filter:blur(16px);border-bottom:1px solid var(--line)}
.topbar{min-height:68px;display:flex;align-items:center;gap:25px}
.brand{display:flex;align-items:center;gap:10px;font:800 21px Manrope,sans-serif;letter-spacing:3px;white-space:nowrap}
.brand-mark{width:34px;height:34px;display:grid;place-items:center;border:1px solid var(--red);border-radius:9px;color:#ff3039;font-size:23px}
.brand-name span{color:var(--red)}
nav.desktop{display:flex;align-items:center;gap:18px}
nav button{border:0;background:none;color:#aaa;font-size:12px;white-space:nowrap}
nav button.active,nav button:hover{color:white}
.actions{margin-left:auto;display:flex;align-items:center;gap:5px}
.top-quick-actions{
  display:flex;
  justify-content:center;
  align-items:center;
  gap:10px;
  padding:5px 12px 9px;
}

.top-quick-actions button{
  min-height:34px;
  padding:7px 13px;
  border-radius:7px;
  font-size:10px !important;
  font-weight:800;
  letter-spacing:.1px;
  white-space:nowrap;
}

.top-action-request{
  background:#e50914;
  color:white;
  border:1px solid #e50914;
}

.top-action-bug{
  background:#191919;
  color:white;
  border:1px solid #e50914;
}

@media(max-width:700px){
  .top-quick-actions{
    justify-content:center;
    gap:9px;
  }

  .top-quick-actions button{
    min-height:33px;
    padding:7px 12px;
  }
}
.icon-btn{width:38px;height:38px;border:0;border-radius:50%;background:transparent;font-size:20px}
.icon-btn:hover{background:#ffffff15}
#searchInput{width:0;opacity:0;border:0;border-bottom:1px solid #777;outline:0;background:transparent;color:white;transition:.25s}
#searchInput.open{width:180px;opacity:1;padding:9px}
.hero{
  min-height:570px;
  display:flex;
  align-items:flex-end;
  position:relative;
  overflow:hidden;
  background:
    linear-gradient(90deg,#090909 0%,#090909dd 30%,#09090933 100%),
    linear-gradient(0deg,#090909 0%,transparent 70%),
    var(--hero-image,linear-gradient(135deg,#45151a,#090909)) center/cover;
}

.hero-content{
  padding:0 0 65px;
  max-width:620px;
  position:relative;
  z-index:2;
  transition:transform .45s ease,opacity .45s ease;
}

.hero-content.slide-out{
  opacity:0;
  transform:translateX(-45px);
}

.hero-content.slide-in{
  opacity:1;
  transform:translateX(0);
}

.hero-dots{
  display:flex;
  gap:7px;
  margin-top:22px;
}

.hero-dot{
  width:20px;
  height:4px;
  border:0;
  border-radius:5px;
  background:#ffffff55;
  padding:0;
}

.hero-dot.active{
  background:#e50914;
  width:32px;
}
.eyebrow{color:#eee;font-size:10px;letter-spacing:3px;text-transform:uppercase}
.hero h1{margin:15px 0;font:800 clamp(42px,7vw,75px)/.98 Manrope,sans-serif;text-transform:uppercase;letter-spacing:-4px}
.hero p{color:#ccc;line-height:1.7;font-size:13px;max-width:500px}
.hero-meta{color:#ccc;font-size:12px;margin:15px 0}
.btn{border:0;border-radius:5px;padding:13px 19px;font-weight:700;font-size:12px;margin:5px 5px 0 0;display:inline-flex;align-items:center;justify-content:center}
.primary{background:var(--red);color:white}
.secondary{background:#ffffff20;color:white}
.btn:hover{filter:brightness(1.2)}
.btn:disabled{opacity:.5;cursor:not-allowed}
main{padding-top:30px;min-height:50vh}
.section{margin-bottom:35px;scroll-margin-top:90px}
.section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:15px}
.section-heading h2{font:700 19px Manrope,sans-serif;margin:0}
.section-heading small{display:block;color:#777;font:400 11px "DM Sans";margin-top:5px}
.section-heading button{border:0;background:none;color:#aaa;font-size:11px;white-space:nowrap}
.rail{display:grid;grid-auto-flow:column;grid-auto-columns:155px;gap:13px;overflow-x:auto;padding:3px 2px 14px;scrollbar-width:thin;scrollbar-color:#444 transparent}
.card{min-width:0;cursor:pointer}
.poster{aspect-ratio:2/3;position:relative;overflow:hidden;border-radius:8px;background:var(--art);isolation:isolate;transition:.2s;background-size:cover;background-position:center}
.poster::before{content:"";position:absolute;inset:0;z-index:0;background:var(--art);pointer-events:none;transition:.3s}.poster[style*="background-image"]::before{background:transparent}
.poster::after{content:"";position:absolute;inset:35% 0 0;background:linear-gradient(0deg,#000e,transparent)}
.card:hover .poster{transform:translateY(-4px)}
.card:hover .poster::before{transform:scale(1.07)}
.art-title{position:absolute;bottom:17px;left:11px;right:9px;z-index:2;font:800 18px Manrope;text-transform:uppercase;text-shadow:0 2px 10px black}
.poster-label{position:absolute;top:8px;left:8px;z-index:3;background:var(--red);padding:4px 6px;border-radius:3px;font-size:8px;font-weight:800}
.save{position:absolute;top:7px;right:7px;z-index:4;width:30px;height:30px;border:1px solid #ffffff44;border-radius:50%;background:#0009;font-size:17px}
.save.saved{color:#ff343d}
.card h3{font-size:12px;margin:9px 0 4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.card-meta{font-size:10px;color:#888}
.empty{color:#888;font-size:13px;padding:20px 0}
.page-title{font:800 29px Manrope;margin:20px 0 7px}
.page-description{color:#888;font-size:12px;margin-bottom:20px}
.catalog-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:22px 0}
.catalog-tabs{display:flex;gap:8px;flex-wrap:wrap}
.catalog-tabs button{background:#171717;border:1px solid #333;color:#aaa;border-radius:20px;padding:9px 15px;font-size:11px}
.catalog-tabs button.active{background:var(--red);border-color:var(--red);color:white}
.filter-row{display:flex;gap:9px;flex-wrap:wrap}
.filter-row select,.field{background:#171717;border:1px solid #333;color:white;padding:11px;border-radius:6px;outline:none}
.catalog-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(155px,1fr));gap:24px 15px;padding-bottom:35px}
/* CORREÇÃO DAS CATEGORIAS AO VIVO */
#liveChannels {
  display: block !important;
  width: 100%;
}

#liveChannels > section {
  display: block;
  width: 100%;
  min-width: 0;
}
  .catalog-grid .card{max-width:230px;width:100%}
.overlay{position:fixed;inset:0;z-index:80;display:none;align-items:center;justify-content:center;background:#000e;padding:15px;overflow-y:auto}
.overlay.show{display:flex}
.modal{width:min(850px,100%);max-height:94vh;overflow:auto;background:#121212;border:1px solid var(--line);border-radius:12px;padding:22px}
.close{float:right;border:0;background:#292929;border-radius:50%;width:34px;height:34px}
.detail-banner{min-height:220px;border-radius:9px;position:relative;background:var(--banner,linear-gradient(120deg,#50151b,#111));background-size:cover;background-position:center;overflow:hidden;margin:12px 0 20px}
.detail-banner::after{content:"";position:absolute;inset:0;background:linear-gradient(0deg,#121212 0%,transparent 90%)}
.detail-body{display:grid;grid-template-columns:155px 1fr;gap:22px;align-items:start;margin-top:-75px;position:relative;z-index:2}
.detail-poster{aspect-ratio:2/3;border-radius:8px;background:var(--art);background-size:cover;background-position:center;border:2px solid #222}
.detail-title{font:800 29px Manrope;margin:10px 0}
.detail-info{color:#aaa;font-size:12px;line-height:1.8}
.detail-rating{display:inline-flex;align-items:center;gap:7px;background:#242424;border:1px solid #ffffff15;padding:8px 11px;border-radius:7px;margin:10px 0}
.detail-rating strong{font-size:16px;color:#f4c542}
.detail-rating span{font-size:10px;color:#aaa}
.detail-synopsis{color:#ccc;font-size:13px;line-height:1.7;margin-top:12px}
.detail-actions{margin-top:18px}
.detail-section{margin-top:25px}
.detail-section h3{font:700 16px Manrope}
/* RECOMENDAÇÕES */
.recommendations{
display:grid;
grid-template-columns:repeat(2,minmax(0,1fr));
gap:15px;
padding:12px 0 25px;
}

.recommendations .card{
width:100%;
max-width:none;
min-width:0;
}

.recommendations .poster{
width:100%;
aspect-ratio:2/3;
}

/* DETALHES EXCLUSIVOS */
.detail-crumb{
font-size:11px;
color:#888;
margin:5px 0 15px;
}

.detail-crumb span{
color:#e50914;
}

.detail-layout{
background:#11131b;
border:1px solid #ffffff12;
border-radius:12px;
padding:18px;
}

.detail-cover{
width:145px;
margin:0 auto 12px;
}

.detail-cover .detail-poster{
width:100%;
}

.detail-buttons{
display:grid;
grid-template-columns:1fr;
gap:7px;
max-width:260px;
margin:12px auto 20px;
}

.detail-buttons button{
width:100%;
margin:0;
}

.detail-main-title{
text-align:center;
font:800 23px Manrope;
margin:12px 0;
}

.detail-tags{
display:flex;
justify-content:center;
flex-wrap:wrap;
gap:7px;
margin:12px 0;
}

.detail-tag{
background:#202638;
color:#d7e3ff;
padding:6px 10px;
border-radius:20px;
font-size:10px;
font-weight:700;
}

.detail-status{
display:flex;
justify-content:center;
flex-wrap:wrap;
gap:7px;
margin:14px 0;
}

.detail-status button{
background:#171d2b;
border:1px solid #30394e;
border-radius:7px;
padding:9px 12px;
font-size:10px;
}

.detail-description-box{
background:#171923;
border:1px solid #ffffff10;
border-radius:10px;
padding:15px;
margin-top:16px;
}

.detail-description-box p{
font-size:12px;
line-height:1.8;
color:#ccc;
margin:0;
}

.detail-section{
background:#11131b;
border:1px solid #ffffff12;
border-radius:10px;
padding:13px;
margin-top:17px;
}

.detail-section h3{
font-size:14px;
margin:0 0 13px;
}

.episode{
background:#171d2b;
border:1px solid #ffffff0d;
}

.episode button{
white-space:nowrap;
}

.trailer-overlay{
position:fixed;
inset:0;
z-index:120;
background:#000e;
display:none;
align-items:center;
justify-content:center;
padding:15px;
}

.trailer-overlay.show{
display:flex;
}

.trailer-window{
width:min(850px,100%);
background:#121212;
border:1px solid #ffffff22;
border-radius:12px;
padding:15px;
}

.trailer-top{
display:flex;
align-items:center;
justify-content:space-between;
gap:10px;
margin-bottom:12px;
}

.trailer-top h3{
font-size:14px;
margin:0;
}

.trailer-window iframe{
width:100%;
aspect-ratio:16/9;
border:0;
background:#000;
display:block;
}

@media(max-width:700px){
.detail-layout{padding:13px}
.detail-cover{width:125px}
.detail-main-title{font-size:20px}
.recommendations{gap:10px}
.recommendations .card h3{font-size:11px}
}
.season-select{width:100%;max-width:260px;padding:11px;background:#191919;color:white;border:1px solid #333;border-radius:6px}
.episode-list{display:grid;gap:9px;margin-top:12px}
.episode{display:grid;grid-template-columns:95px 1fr auto;align-items:center;gap:13px;padding:10px;border-radius:8px;background:#1b1b1b}
.episode-thumb{aspect-ratio:16/9;border-radius:5px;background:linear-gradient(135deg,#59313a,#111);background-size:cover;background-position:center}
.episode h4{font-size:12px;margin:0 0 5px}
.episode p{font-size:10px;color:#999;margin:0;line-height:1.5}
.episode button{background:var(--red);border:0;border-radius:5px;padding:9px 12px;font-size:11px}
.player-modal{width:min(1050px,100%)}
.player-video,.player-frame{display:block;width:100%;aspect-ratio:16/9;border:0;background:#000;margin-top:15px}
.player-video{object-fit:contain}
.player-info{color:#aaa;font-size:12px;line-height:1.6}
  .audio-options{
display:flex;
gap:10px;
margin-top:15px;
margin-bottom:10px;
}

.audio-btn{
background:#1d1d1d;
color:#fff;
border:1px solid #333;
border-radius:8px;
padding:10px 18px;
font-size:13px;
font-weight:600;
}

.audio-btn.active{
background:#e50914;
border-color:#e50914;
}
.player-error{color:#ff7373;font-size:12px}
.notice{background:#151515;border:1px solid var(--line);padding:17px;border-radius:8px;margin-bottom:12px}
.notice h3{margin:0 0 7px;font-size:14px}
.notice p{margin:0;color:#aaa;font-size:12px;line-height:1.6}
.notice small{display:block;color:#666;margin-top:10px}
.form-card{max-width:650px;background:#131313;border:1px solid var(--line);border-radius:10px;padding:20px;margin:20px 0 40px}
.form-card label{display:block;font-size:12px;color:#aaa;margin:15px 0 7px}
.form-card input,.form-card textarea,.form-card select{width:100%;background:#090909;border:1px solid #333;color:white;border-radius:6px;padding:12px;outline:none}
.form-card textarea{min-height:100px;resize:vertical}
.form-note{color:#999;font-size:11px;line-height:1.6;margin-top:13px}
.toast{position:fixed;z-index:100;left:50%;bottom:85px;transform:translate(-50%,20px);opacity:0;pointer-events:none;background:#222;border:1px solid #ffffff22;padding:12px 17px;border-radius:8px;font-size:12px;transition:.2s;max-width:90vw;text-align:center}
.toast.show{opacity:1;transform:translate(-50%,0)}
footer{border-top:1px solid var(--line);padding:30px 0 100px;color:#777;font-size:10px}
.footer-actions{display:flex;gap:16px;flex-wrap:wrap;margin-top:12px}
footer button{border:0;background:none;color:#aaa;text-decoration:underline;font-size:11px;padding:5px 0}
.footer-actions{
  display:flex;
  gap:12px;
  flex-wrap:wrap;
  margin-top:20px;
}

.footer-actions button:nth-child(2),
.footer-actions button:nth-child(3){
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:46px;
  padding:12px 20px;
  border-radius:8px;
  font-size:12px;
  font-weight:800;
  text-decoration:none;
  transition:.2s;
}

.footer-actions button:nth-child(2){
  background:#e50914;
  color:#fff;
  border:1px solid #e50914;
}

.footer-actions button:nth-child(3){
  background:#191919;
  color:#fff;
  border:1px solid #e50914;
}

.footer-actions button:nth-child(2):hover,
.footer-actions button:nth-child(3):hover{
  filter:brightness(1.2);
  transform:translateY(-2px);
}

@media(max-width:700px){
  .footer-actions button:nth-child(2),
  .footer-actions button:nth-child(3){
    flex:1 1 140px;
    min-height:48px;
  }
}
.mobile-menu{display:none}
.discord-content{text-align:center;max-width:420px;margin:auto}
.discord-cloud{font-size:42px}
@media(max-width:700px){
.shell{width:calc(100% - 30px)}
.topbar{min-height:61px;gap:8px}
nav.desktop{display:none}
.brand{font-size:17px;letter-spacing:2px}
.brand-mark{width:30px;height:30px}
#searchInput.open{width:115px}
.hero{min-height:590px;background-position:58% center}
.hero-content{padding-bottom:55px}
.hero h1{font-size:48px;letter-spacing:-2px}
.hero p{font-size:12px}
.rail{grid-auto-columns:124px;gap:10px}
.section-heading h2{font-size:16px}
.catalog-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:18px 9px}
.catalog-grid .card{max-width:none}
.art-title{font-size:14px}
.page-title{font-size:25px}
.mobile-menu{position:fixed;z-index:40;display:flex;justify-content:space-around;align-items:center;left:9px;right:9px;bottom:8px;height:59px;background:#171717ed;border:1px solid #ffffff1c;border-radius:15px;backdrop-filter:blur(15px)}
.mobile-menu button{border:0;background:none;display:flex;flex-direction:column;align-items:center;gap:4px;color:#888;font-size:9px}
.mobile-menu button.active{color:white}
.modal{padding:15px}
.detail-body{grid-template-columns:105px 1fr;gap:13px;margin-top:-55px}
.detail-title{font-size:21px}
.detail-banner{min-height:170px}
.detail-rating{padding:6px 8px}
.episode{grid-template-columns:75px 1fr;gap:9px}
.episode button{grid-column:2;justify-self:start}
.recommendations{grid-auto-columns:105px}
}
@media(max-width:380px){.catalog-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.hero h1{font-size:41px}}
@media(orientation:landscape) and (max-height:520px){.hero{min-height:calc(100vh - 60px)}.hero-content{padding-bottom:24px}.hero h1{font-size:clamp(34px,7vh,55px)}.mobile-menu{display:none}.shell{width:min(94%,1500px)}}
@media(min-width:701px) and (orientation:landscape){.catalog-grid{grid-template-columns:repeat(auto-fill,minmax(170px,1fr))}.rail{grid-auto-columns:clamp(145px,12vw,190px)}}

/* DETALHES EM TELA COMPLETA */
#detailsOverlay.details-overlay{
  padding:0;
  align-items:stretch;
  justify-content:stretch;
  background:#090909;
}

#detailsOverlay .details-modal{
  width:100%;
  max-width:none;
  height:100vh;
  height:100dvh;
  max-height:none;
  overflow-y:auto;
  border:0;
  border-radius:0;
  padding:clamp(16px,3vw,35px);
  background:#090909;
}

#detailsOverlay .close{
  position:sticky;
  top:0;
  float:right;
  z-index:10;
}

#detailContent{
  width:100%;
  max-width:1250px;
  margin:0 auto;
}

#detailContent .detail-banner{
  min-height:clamp(220px,35vw,390px);
  margin:12px 0 20px;
}

#detailContent .detail-layout{
  width:100%;
  max-width:100%;
  padding:clamp(16px,3vw,30px);
  background:#11131b;
}

#detailContent .detail-description-box{
  width:100%;
}

#detailContent .detail-section{
  width:100%;
}

#detailContent .recommendations{
  grid-template-columns:repeat(2,minmax(0,1fr));
}

/* =================================
   NEXORA - PLAYER E SERVIDORES
================================= */

/* TELA PRINCIPAL DO PLAYER */
#playerOverlay.player-overlay{
  padding:0;
  align-items:stretch;
  justify-content:stretch;
  background:#050505;
  z-index:100;
}

#playerOverlay .player-modal{
  position:relative;
  display:block;
  width:100%;
  max-width:none;
  height:100vh;
  height:100dvh;
  max-height:none;
  overflow-y:auto;
  border:0;
  border-radius:0;
  padding:clamp(14px,3vw,30px);
  background:#080808;
  color:#fff;
}

/* TÍTULO */
#playerOverlay #playerTitle{
  margin:8px 0 18px;
  font-size:clamp(18px,3vw,25px);
  font-weight:900;
}

/* ÁREA PRETA PERMANENTE */
.player-screen{
  position:relative;
  width:100%;
  aspect-ratio:16/9;
  min-height:210px;
  max-height:75vh;
  background:#000;
  border:1px solid #222;
  border-radius:10px;
  display:flex;
  align-items:center;
  justify-content:center;
  overflow:hidden;
}

/* MENSAGEM ANTES DE ESCOLHER SERVIDOR */
.player-placeholder{
  position:absolute;
  inset:0;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  gap:12px;
  background:#000;
  color:#777;
  text-align:center;
}

.player-placeholder span{
  width:48px;
  height:48px;
  display:flex;
  align-items:center;
  justify-content:center;
  border:1px solid #444;
  border-radius:50%;
  color:#e50914;
  font-size:21px;
}

.player-placeholder p{
  margin:0;
  font-size:12px;
}

/* VÍDEO E IFRAME */
.player-screen iframe,
.player-screen video{
  position:absolute;
  inset:0;
  width:100%;
  height:100%;
  border:0;
  background:#000;
  object-fit:contain;
}

/* CONTEXTO DO CONTEÚDO */
.player-content-info{
  padding:12px 2px;
}

#playerContentContext{
  margin:0;
  color:#aaa;
  font-size:12px;
  font-weight:700;
}

/* SEÇÃO DE SERVIDORES */
#serverSelection{
  margin-top:12px;
}

.server-section-heading{
  margin-bottom:16px;
}

.server-section-heading > span{
  color:#e50914;
  font-size:10px;
  font-weight:900;
  letter-spacing:1.5px;
}

.server-heading{
  margin:7px 0;
  font-size:clamp(18px,3vw,23px);
  font-weight:900;
}

.server-description{
  margin:0;
  color:#999;
  font-size:12px;
  line-height:1.6;
}

/* LISTA DE SERVIDORES */
.server-list{
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
  gap:12px;
}

.server-option{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  width:100%;
  min-height:70px;
  padding:15px;
  text-align:left;
  background:#141414;
  border:1px solid #292929;
  border-radius:10px;
  color:#fff;
  transition:.2s;
}

.server-option:hover{
  border-color:#e50914;
  background:#1c1112;
}

.server-option strong{
  display:block;
  font-size:13px;
}

.server-option small{
  display:block;
  color:#999;
  font-size:10px;
  margin-top:5px;
}

.server-option span{
  color:#e50914;
  font-size:22px;
}

/* BARRA DO SERVIDOR SELECIONADO */
.player-stage{
  margin-top:12px;
}

.player-stage-top{
  display:flex;
  align-items:center;
  justify-content:space-between;
  flex-wrap:wrap;
  gap:12px;
  padding:12px 0;
}

.player-back{
  border:1px solid #333;
  border-radius:8px;
  background:#171717;
  color:white;
  padding:10px 14px;
  font-size:12px;
  font-weight:700;
}

.player-back:hover{
  border-color:#e50914;
}

.player-info{
  color:#aaa;
  font-size:12px;
}

.player-error{
  color:#ff5555;
  font-size:12px;
  margin-top:12px;
}

/* MENSAGENS */
#playerMessage{
  margin-top:12px;
}

/* MANTÉM AJUSTES DAS TELAS DE DETALHES */
@media(max-width:700px){

  #detailsOverlay .details-modal{
    padding:12px;
  }

  #detailContent .detail-banner{
    min-height:190px;
  }

  #detailContent .detail-layout{
    padding:14px;
  }

  #playerOverlay .player-modal{
    padding:14px;
  }

  .player-screen{
    min-height:210px;
    border-radius:7px;
  }

  .server-list{
    grid-template-columns:1fr;
  }
}

@media(min-width:900px){
  #playerOverlay .player-modal{
    padding:25px max(25px,5vw);
  }

  .player-screen{
    max-height:70vh;
  }
}

/* DETALHES NO ESTILO DAS REFERENCIAS */

.ref-detail-page{
  width:100%;
  min-height:100%;
  padding:12px;
  background:#090b12;
  color:#fff;
}

.ref-detail-crumb{
  padding:12px;
  margin-bottom:10px;
  border-radius:12px;
  background:#10131d;
  color:#aebbd4;
  font-size:12px;
}

.ref-detail-crumb span{
  color:#4b8cff;
  cursor:pointer;
}

.ref-detail-card{
  width:100%;
  padding:15px;
  border:1px solid #1b2232;
  border-radius:15px;
  background:#10131d;
  text-align:center;
}

.ref-poster{
  width:min(150px,55%);
  aspect-ratio:2/3;
  margin:0 auto 12px;
  border-radius:11px;
  background-color:#202536;
  background-image:var(--art);
  background-size:cover;
  background-position:center;
  box-shadow:0 5px 18px #0008;
}

.ref-top-buttons{
  width:min(150px,100%);
  margin:auto;
  display:flex;
  flex-direction:column;
  gap:5px;
}

.ref-detail-button{
  min-height:35px;
  border:1px solid #252e42;
  border-radius:9px;
  background:#151c2c;
  color:#fff;
  font-size:12px;
  font-weight:700;
}

.ref-detail-title{
  margin:14px 0 8px;
  font-size:clamp(19px,4vw,25px);
  font-weight:900;
  line-height:1.3;
}

.ref-genres{
  display:flex;
  justify-content:center;
  flex-wrap:wrap;
  gap:6px;
  margin:10px 0;
}

.ref-genres span{
  padding:5px 9px;
  border-radius:20px;
  background:#192238;
  color:#d5e0f5;
  font-size:10px;
  font-weight:700;
}

.ref-rating{
  display:flex;
  justify-content:center;
  align-items:center;
  gap:14px;
  margin:12px 0;
}

.ref-rating strong{
  color:#ffca38;
  font-size:17px;
}

.ref-rating small{
  color:#aaa;
  font-size:11px;
}

.ref-rating button{
  border:0;
  background:none;
  color:#5595ff;
  font-weight:800;
}

.ref-user-actions{
  display:flex;
  justify-content:center;
  flex-wrap:wrap;
  gap:7px;
  margin:12px 0;
}

.ref-user-actions button,
.ref-notify-button{
  padding:8px 11px;
  border:1px solid #29344a;
  border-radius:9px;
  background:#111827;
  color:#fff;
  font-size:11px;
  font-weight:700;
}

.ref-notify-button{
  margin:0 auto 12px;
  display:block;
}

.ref-synopsis{
  padding:13px;
  border:1px solid #20283a;
  border-radius:12px;
  background:#0d111b;
  color:#d5d9e2;
  font-size:12px;
  line-height:1.75;
  text-align:center;
}

.ref-extra{
  color:#aebbd4;
  font-size:11px;
  line-height:1.6;
  margin:10px 0 0;
}

.ref-extra strong{
  color:#fff;
}

.ref-recommendations{
  margin-top:18px;
  padding:13px;
  border:1px solid #20283a;
  border-radius:13px;
  background:#10131d;
}

.ref-recommendations h3{
  margin:0 0 12px;
  font-size:14px;
}

.ref-recommendations .recommendations{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:10px;
}

@media(min-width:700px){
  .ref-detail-page{
    padding:25px;
  }

  .ref-detail-card{
    max-width:650px;
    margin:0 auto;
    padding:25px;
  }

  .ref-poster{
    width:180px;
  }

  .ref-recommendations{
    max-width:900px;
    margin:25px auto 0;
  }
}

/* EPISÓDIOS NEXORA */
.ref-episode{
  display:grid;
  grid-template-columns:105px minmax(0,1fr) auto;
  align-items:center;
  gap:12px;
  padding:12px;
  margin-bottom:10px;
  background:#111;
  border:1px solid #252525;
  border-radius:10px;
}

.ref-episode-thumb{
  width:105px;
  aspect-ratio:16/9;
  background-color:#202020;
  background-size:cover;
  background-position:center;
  border-radius:7px;
  display:flex;
  align-items:center;
  justify-content:center;
  color:#e50914;
}

.ref-episode-info{
  min-width:0;
}

.ref-episode-number{
  color:#e50914;
  font-size:9px;
  font-weight:900;
}

.ref-episode-info h4{
  margin:5px 0;
  font-size:13px;
  color:#fff;
}

.ref-episode-info p{
  margin:0;
  color:#999;
  font-size:11px;
  line-height:1.5;
}

.ref-episode-watch{
  padding:9px 12px;
  border:0;
  border-radius:7px;
  background:#e50914;
  color:white;
  font-size:11px;
  font-weight:800;
}

@media(max-width:480px){
  .ref-episode{
    grid-template-columns:85px minmax(0,1fr);
    gap:9px;
  }

  .ref-episode-thumb{
    width:85px;
  }

  .ref-episode-watch{
    grid-column:2;
    justify-self:start;
  }
}

/* TEMPORADAS NEXORA */
.ref-season-section{
  width:100%;
  margin-top:20px;
  padding:15px;
  background:#101010;
  border:1px solid #252525;
  border-radius:12px;
}

.ref-season-label{
  color:#e50914;
  font-size:10px;
  font-weight:900;
  letter-spacing:1.5px;
}

.ref-season-heading{
  display:flex;
  align-items:center;
  justify-content:space-between;
  flex-wrap:wrap;
  gap:12px;
  margin:12px 0 18px;
}

.ref-season-heading h3{
  margin:0;
  font-size:19px;
}

.ref-season-heading p{
  margin:5px 0 0;
  color:#999;
  font-size:11px;
}

.ref-season-heading select{
  max-width:100%;
  padding:10px;
  border:1px solid #333;
  border-radius:8px;
  background:#191919;
  color:white;
}

.ref-current-season{
  margin:0 0 13px;
  padding-bottom:10px;
  border-bottom:1px solid #292929;
  font-size:14px;
}

/* NEXORA - PADRONIZAÇÃO PRETO E VERMELHO */

.ref-detail-page{
  background:#090909 !important;
  color:#fff;
}

.ref-detail-crumb{
  background:#111 !important;
  color:#aaa !important;
  border:1px solid #252525;
}

.ref-detail-crumb span{
  color:#e50914 !important;
}

.ref-detail-card{
  background:#101010 !important;
  border-color:#292929 !important;
}

.ref-genres span{
  background:#211011 !important;
  color:#ffb5b5 !important;
  border:1px solid #461719;
}

.ref-user-actions button,
.ref-notify-button{
  background:#181111 !important;
  border-color:#492023 !important;
  color:#fff !important;
}

.ref-user-actions button:active,
.ref-notify-button:active{
  background:#e50914 !important;
}

.ref-rating button{
  color:#e50914 !important;
}

.ref-synopsis{
  background:#0c0c0c !important;
  border-color:#292929 !important;
  color:#ddd !important;
}

.ref-recommendations{
  background:#101010 !important;
  border-color:#292929 !important;
}

.ref-recommendations h3{
  color:#fff;
}

.ref-detail-button{
  background:#191111 !important;
  border-color:#492023 !important;
}

.ref-detail-button:hover{
  background:#e50914 !important;
  border-color:#e50914 !important;
}

/* PLAYER - NOVO LAYOUT NEXORA */

#playerOverlay .player-modal{
  display:block;
  width:100%;
  height:100dvh;
  max-width:none;
  max-height:none;
  overflow-y:auto;
  padding:16px;
  border:0;
  border-radius:0;
  background:#090909;
}

#playerOverlay .server-list{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:10px;
}

#playerOverlay .server-option{
  min-height:58px;
  background:#151515;
  border:1px solid #292929;
  border-radius:9px;
}

#playerOverlay .server-option:active{
  background:#271012;
  border-color:#e50914;
}

#playerOverlay .player-content-info{
  margin:12px 0;
  padding:13px;
  text-align:center;
  border:1px solid #292929;
  border-radius:9px;
  background:#111;
}

#playerContentContext{
  color:#fff;
  font-size:14px;
  font-weight:800;
}

#playerOverlay .player-screen{
  width:100%;
  aspect-ratio:16/9;
  min-height:230px;
  max-height:none;
  border:0;
  border-radius:12px;
  background:#000;
}

#playerOverlay .player-actions{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:12px;
  margin:13px 0;
}

#playerOverlay .player-actions button{
  padding:12px 20px;
  border:1px solid #383838;
  border-radius:25px;
  background:#171717;
  color:#fff;
  font-size:13px;
  font-weight:800;
}

#playerOverlay .player-actions button:active{
  background:#e50914;
  border-color:#e50914;
}

#playerOverlay .player-placeholder{
  background:#000;
}

@media(max-width:480px){
  #playerOverlay .player-modal{
    padding:13px;
  }

  #playerOverlay .server-list{
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:8px;
  }

  #playerOverlay .server-option{
    padding:11px 9px;
  }

  #playerOverlay .player-screen{
    min-height:220px;
  }
}

/* NEXORA - PLAYER DE SERIES NA PAGINA */

.series-inline-player{
  margin-top:20px;
  padding:15px;
  background:#101010;
  border:1px solid #292929;
  border-radius:14px;
  color:#fff;
}

.series-inline-player .player-content-info{
  padding:5px 0 15px;
}

.series-inline-player .server-section-heading{
  margin:10px 0 15px;
}

.series-inline-player .server-section-heading > span{
  color:#e50914;
  font-size:10px;
  font-weight:900;
  letter-spacing:1.5px;
}

.series-inline-player .server-heading{
  margin:6px 0;
  font-size:19px;
  font-weight:900;
}

.series-inline-player .server-list{
  display:grid;
  grid-template-columns:repeat(2,minmax(0,1fr));
  gap:10px;
}

.series-inline-player .server-option{
  min-height:65px;
  padding:12px;
  background:#191919;
  border:1px solid #303030;
  border-radius:9px;
  color:#fff;
  text-align:left;
}

.series-inline-player .server-option:active,
.series-inline-player .server-option:hover{
  border-color:#e50914;
  background:#211112;
}

.series-inline-player .player-stage{
  padding:10px 0;
}

.series-inline-player .player-screen{
  width:100%;
  aspect-ratio:16/9;
  min-height:190px;
  max-height:none;
  margin-top:10px;
  background:#000;
  border:1px solid #292929;
  border-radius:9px;
}

.series-inline-player .player-screen iframe,
.series-inline-player .player-screen video{
  position:absolute;
  inset:0;
  width:100%;
  height:100%;
  border:0;
  background:#000;
}

.series-inline-player .player-actions{
  display:flex;
  justify-content:space-between;
  gap:10px;
  margin-top:15px;
}

.series-inline-player .player-actions button{
  flex:1;
  min-height:42px;
  padding:10px;
  border:1px solid #492023;
  border-radius:8px;
  background:#211112;
  color:#fff;
  font-size:12px;
  font-weight:800;
}

.series-inline-player .player-actions button:hover{
  background:#e50914;
}

@media(max-width:600px){
  .series-inline-player .server-list{
    grid-template-columns:1fr;
  }

  .series-inline-player{
    padding:11px;
  }
}

.server-language{
  display:inline-block;
  width:max-content;
  padding:1px 3px;
  margin-bottom:3px;
  border-radius:2px;
  font-size:7px !important;
  line-height:1.2;
  font-weight:800;
  letter-spacing:.2px;
}

.server-language.dub{
  color:#55d98a;
  background:#153322;
}

.server-language.sub{
  color:#70baff;
  background:#142b40;
}

/* SERVIDORES - GRADE DE 2 COLUNAS */

.series-inline-player .server-list{
  display:grid !important;
  grid-template-columns:repeat(2,minmax(0,1fr)) !important;
  gap:8px;
}

.series-inline-player .server-option{
  width:100%;
  min-width:0;
  box-sizing:border-box;
}

/* NEXORA - RECOMENDADOS COMPACTOS */

.ref-recommendations-grid{
  display:grid !important;
  grid-template-columns:repeat(4,minmax(0,1fr)) !important;
  gap:8px !important;
}

.ref-recommendations-grid .card{
  width:100%;
  min-width:0;
  margin:0;
}

.ref-recommendations-grid .poster{
  width:100%;
  aspect-ratio:2/3;
  height:auto;
  border-radius:7px;
}

.ref-recommendations-grid .card h3{
  font-size:11px;
  margin:5px 0 2px;
  line-height:1.3;
}

.ref-recommendations-grid .card-meta{
  font-size:9px;
}

@media(max-width:600px){
  .ref-recommendations-grid{
    grid-template-columns:repeat(3,minmax(0,1fr)) !important;
    gap:7px !important;
  }
}

/* BOTÃO ASSISTIR - DETALHES DO FILME */
.ref-watch-button{
  min-height:42px;
  width:100%;
  border:0;
  border-radius:9px;
  background:#e50914;
  color:#fff;
  font-size:13px;
  font-weight:900;
}

.ref-watch-button:active{
  background:#b80710;
}

/* PLAYER DE FILMES NA PRÓPRIA PÁGINA */
.movie-inline-player .player-screen{
  position:relative;
  overflow:hidden;
  width:100%;
  aspect-ratio:16/9;
  background:#000;
  border-radius:9px;
}

/* ===== NOVO VISUAL NEXORA ===== */

/* Cabeçalho */
header {
  background: linear-gradient(180deg, #080808 0%, #101010f5 100%);
  border-bottom: 1px solid #ffffff12;
  box-shadow: 0 8px 30px #0005;
}

.topbar {
  min-height: 76px;
  gap: 30px;
}

.brand {
  font-size: 23px;
  letter-spacing: 3px;
}

.brand-mark {
  width: 38px;
  height: 38px;
  border-radius: 11px;
  box-shadow: 0 0 18px #e5091430;
}

nav.desktop {
  gap: 22px;
}

nav button {
  font-size: 13px;
  transition: color .2s ease;
}

nav button.active {
  color: #fff;
  font-weight: 800;
}

/* Botões do cabeçalho */
.icon-btn {
  width: 40px;
  height: 40px;
  border: 1px solid transparent;
  transition: .2s ease;
}

.icon-btn:hover {
  background: #ffffff12;
  border-color: #ffffff20;
  transform: translateY(-2px);
}

/* Banner principal */
.hero {
  min-height: min(720px, 82vh);
  background:
    linear-gradient(90deg, #080808 0%, #080808e8 25%, #08080855 65%, transparent 100%),
    linear-gradient(0deg, #090909 0%, transparent 45%),
    var(--hero-image, linear-gradient(135deg,#45151a,#090909)) center/cover;
}

.hero-content {
  max-width: 700px;
  padding-bottom: 75px;
}

.hero h1 {
  font-size: clamp(48px, 8vw, 88px);
  letter-spacing: -4px;
  text-shadow: 0 5px 30px #0009;
}

.hero p {
  font-size: 15px;
  max-width: 560px;
}

.hero-meta {
  font-size: 13px;
}

/* Botão do banner */
.hero .btn {
  min-height: 46px;
  padding: 14px 23px;
  border-radius: 7px;
  font-size: 13px;
}

/* Televisões e telas grandes */
@media (min-width: 1200px) {
  .shell {
    width: min(100% - 90px, 1600px);
  }

  .hero {
    min-height: 78vh;
  }

  .rail {
    grid-auto-columns: 185px;
    gap: 17px;
  }

  .section {
    margin-bottom: 45px;
  }

  .section-heading h2 {
    font-size: 22px;
  }
}

/* Celulares */
@media (max-width: 700px) {
  .topbar {
    min-height: 62px;
  }

  .brand {
    font-size: 17px;
  }

  .brand-mark {
    width: 31px;
    height: 31px;
  }

  .hero {
    min-height: 570px;
    background:
      linear-gradient(90deg, #080808dd, #08080855),
      linear-gradient(0deg, #090909 0%, transparent 65%),
      var(--hero-image, linear-gradient(135deg,#45151a,#090909)) center/cover;
  }

  .hero-content {
    padding-bottom: 55px;
  }

  .hero h1 {
    font-size: 46px;
  }

  .hero p {
    font-size: 12px;
  }
}

/* NOVO CABEÇALHO NEXORA */

.nx-header {
  position: sticky;
  top: 0;
  z-index: 50;
  background: rgba(8,8,8,.96);
  border-bottom: 1px solid #ffffff12;
  backdrop-filter: blur(18px);
}

.nx-header-inner {
  width: min(95%, 1550px);
  min-height: 76px;
  margin: auto;
  display: flex;
  align-items: center;
  gap: 35px;
}

.nx-brand {
  display: flex;
  align-items: center;
  gap: 11px;
  font: 900 22px Manrope, sans-serif;
  letter-spacing: 2px;
  white-space: nowrap;
}

.nx-logo {
  width: 38px;
  height: 38px;
  display: grid;
  place-items: center;
  border: 2px solid #e50914;
  border-radius: 10px;
  color: #e50914;
  font-size: 25px;
}

.nx-red {
  color: #e50914;
}

.nx-nav {
  display: flex;
  align-items: center;
  gap: 22px;
}

.nx-nav button {
  background: none;
  border: 0;
  color: #999;
  font-size: 12px;
  font-weight: 700;
  transition: .2s;
}

.nx-nav button:hover,
.nx-nav button.active {
  color: #fff;
}

.nx-nav button.active::after {
  content: "";
  display: block;
  height: 2px;
  background: #e50914;
  margin-top: 7px;
}

.nx-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 7px;
}

.nx-action {
  width: 37px;
  height: 37px;
  border: 1px solid #ffffff15;
  border-radius: 50%;
  background: #171717;
  color: white;
  font-size: 19px;
}

.nx-action:hover {
  background: #e50914;
  border-color: #e50914;
}

.nx-actions #searchInput.open {
  width: 150px;
  padding: 9px;
  border: 1px solid #333;
  border-radius: 20px;
}

@media(max-width:900px) {
  .nx-header-inner {
    min-height: 65px;
    gap: 12px;
  }

  .nx-nav {
    display: none;
  }

  .nx-brand {
    font-size: 18px;
  }

  .nx-logo {
    width: 33px;
    height: 33px;
  }

  .nx-actions {
    gap: 4px;
  }

  .nx-action {
    width: 33px;
    height: 33px;
  }

  .nx-actions #searchInput.open {
    width: 100px;
  }
}

</style>
</head>

<body>

<header class="nx-header">
  <div class="nx-header-inner">

    <a class="nx-brand" href="#" onclick="showPage('inicio');return false">
      <span class="nx-logo">N</span>
      <span>NEXORA<span class="nx-red">.</span></span>
    </a>

    <nav class="nx-nav">
      <button class="active" data-page="inicio">Início</button>
      <button data-page="filmes">Filmes</button>
      <button data-page="series">Séries</button>
      <button data-page="aovivo">Ao Vivo</button>
      <button data-page="breve">Em breve</button>
      <button data-page="recentes">Novidades</button>
    </nav>

    <div class="nx-actions">
      <input id="searchInput" type="search" placeholder="Buscar...">

      <button id="searchToggle" class="nx-action" title="Pesquisar">⌕</button>
      <button class="nx-action" onclick="showPage('pedido')" title="Pedir conteúdo">+</button>
      <button class="nx-action" onclick="showPage('bug')" title="Relatar bug">!</button>
      <button class="nx-action" onclick="showPage('avisos')" title="Avisos">♧</button>
      <button class="nx-action" onclick="showPage('lista')" title="Minha lista">♡</button>
    </div>

  </div>
</header>


<section class="hero" id="hero">
  <div class="shell hero-content">
    <div class="eyebrow" id="heroEyebrow">UMA EXPERIÊNCIA NEXORA</div>

    <h1 id="heroTitle">NEXORA</h1>

    <div class="hero-meta" id="heroMeta">
      Cinema e séries
    </div>

    <p id="heroDescription">
      Descubra histórias e novidades no catálogo NEXORA.
    </p>

    <button
      class="btn primary"
      id="heroButton"
      onclick="openDetails(window.heroCurrentId)">
      ▶ Mais informações
    </button>

    <div id="heroDots" class="hero-dots"></div>
  </div>
</section>

<main class="shell">
<div id="page-inicio" class="page">
<section class="section hidden" id="continueSection"><div class="section-heading"><h2>Continuar assistindo<small>Conteúdos que você começou</small></h2></div><div class="rail" id="continueRail"></div></section>
<section class="section"><div class="section-heading"><h2>Em alta<small>O que está chamando atenção</small></h2></div><div class="rail" id="trendingRail"></div></section>
<section class="section"><div class="section-heading"><h2>Últimos adicionados<small>Novidades no catálogo</small></h2><button onclick="showPage('recentes')">Ver mais →</button></div><div class="rail" id="latestRail"></div></section>
<section class="section"><div class="section-heading"><h2>Em breve<small>Próximas estreias</small></h2><button onclick="showPage('breve')">Ver mais →</button></div><div class="rail" id="homeUpcoming"></div></section>
<section class="section"><div class="section-heading"><h2>Filmes<small>Escolha sua próxima sessão</small></h2><button onclick="showPage('filmes')">Ver mais →</button></div><div class="rail" id="homeMovies"></div></section>
<section class="section"><div class="section-heading"><h2>Séries<small>Uma história por episódio</small></h2><button onclick="showPage('series')">Ver mais →</button></div><div class="rail" id="homeSeries"></div></section>
</div>

<div id="page-filmes" class="page hidden">
<h1 class="page-title">Filmes</h1><p class="page-description">Explore o catálogo de filmes da NEXORA.</p>
<div class="catalog-toolbar"><div class="catalog-tabs" id="movieTabs">
<button class="active" data-genre="">Todos</button><button data-genre="Ação">Ação</button><button data-genre="Aventura">Aventura</button><button data-genre="Drama">Drama</button><button data-genre="Suspense">Suspense</button><button data-genre="Mistério">Mistério</button><button data-genre="Ficção científica">Ficção científica</button>
</div><div class="filter-row"><select id="movieSort"><option value="recentes">Mais recentes</option><option value="nome">Ordem alfabética</option><option value="ano">Ano de lançamento</option></select></div></div>
<div class="catalog-grid" id="movieGrid"></div>
</div>

<div id="page-series" class="page hidden">
<h1 class="page-title">Séries</h1><p class="page-description">Encontre sua próxima série favorita.</p>
<div class="catalog-toolbar"><div class="catalog-tabs" id="seriesTabs">
<button class="active" data-genre="">Todas</button><button data-genre="Ação">Ação</button><button data-genre="Drama">Drama</button><button data-genre="Suspense">Suspense</button><button data-genre="Mistério">Mistério</button><button data-genre="Policial">Policial</button>
</div><div class="filter-row"><select id="seriesSort"><option value="recentes">Mais recentes</option><option value="nome">Ordem alfabética</option><option value="ano">Ano de lançamento</option></select></div></div>
<div class="catalog-grid" id="seriesGrid"></div>
</div>

  <div id="page-aovivo" class="page hidden">
<h1 class="page-title">🔴 Ao Vivo</h1>
<p class="page-description">Acompanhe canais e transmissões ao vivo na NEXORA.</p>

<div id="liveChannels" class="catalog-grid">
<p class="empty">Carregando canais...</p>
</div>

<div id="livePlayerArea" class="hidden">
<h2 id="liveChannelTitle"></h2>
<iframe id="livePlayer"
class="player-frame"
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowfullscreen
title="Transmissão ao vivo"></iframe>
<div id="liveSchedule"></div>
</div>
</div>

<div id="page-breve" class="page hidden"><h1 class="page-title">Em breve</h1><p class="page-description">Títulos programados para chegar à NEXORA.</p><div class="catalog-grid" id="upcomingGrid"></div></div>
<div id="page-recentes" class="page hidden"><h1 class="page-title">Últimos adicionados</h1><p class="page-description">Os conteúdos mais recentes do catálogo.</p><div class="catalog-grid" id="recentGrid"></div></div>
<div id="page-lista" class="page hidden"><h1 class="page-title">Minha Lista</h1><p class="page-description">Seus filmes e séries salvos neste dispositivo.</p><div class="catalog-grid" id="myListGrid"></div></div>
<div id="page-busca" class="page hidden"><h1 class="page-title">Pesquisa</h1><p class="page-description" id="searchDescription"></p><div class="catalog-grid" id="searchGrid"></div></div>
<div id="page-avisos" class="page hidden"><h1 class="page-title">Avisos da NEXORA</h1><p class="page-description">Novidades e comunicados da plataforma.</p><div id="noticeList"></div></div>

<div id="page-pedido" class="page hidden">
<h1 class="page-title">Pedir conteúdo</h1><p class="page-description">Sugira um filme ou uma série para a NEXORA.</p>
<form class="form-card" id="requestForm">
<label for="requestTitle">Nome do conteúdo</label><input id="requestTitle" required maxlength="100" placeholder="Digite o título">
<label for="requestType">Tipo</label><select id="requestType" class="field"><option>Filme</option><option>Série</option></select>
<label for="requestExtra">Informação adicional (opcional)</label><textarea id="requestExtra" maxlength="500" placeholder="Escreva uma observação..."></textarea>
<button class="btn primary" type="submit">Enviar pedido</button>
<p class="form-note">Sua sugestão será enviada para a equipe NEXORA.</p>
</form>
</div>

<div id="page-bug" class="page hidden">
<h1 class="page-title">Relatar um bug</h1><p class="page-description">Encontrou algum problema? Conte para a equipe.</p>
<form class="form-card" id="bugForm">
<label for="bugType">Tipo de problema</label>
<select id="bugType" class="field"><option>Pesquisa não funciona</option><option>Player não abre</option><option>Página travada</option><option>Imagem não carrega</option><option>Outro problema</option></select>
<label for="bugDescription">Descreva o problema</label><textarea id="bugDescription" required maxlength="1000" placeholder="Explique o que aconteceu..."></textarea>
<button class="btn primary" type="submit">Enviar relato</button>
<p class="form-note">Seu relato será enviado para a equipe NEXORA.</p>
</form>
</div>
</main>

<footer><div class="shell">
<strong style="color:#aaa;letter-spacing:3px">NEX<span style="color:red">ORA</span></strong>
<p>Uma experiência de entretenimento independente.</p><p>© 2026 NEXORA</p>
<div class="footer-actions">
<button onclick="showPage('avisos')">Avisos</button>
<button onclick="showPage('pedido')">+ Pedir conteúdo</button>
<button onclick="showPage('bug')">Relatar bug</button>
</div>
</div></footer>

<nav class="mobile-menu">
<button class="active" data-page="inicio">⌂<span>Início</span></button>
<button data-page="filmes">▤<span>Filmes</span></button>
<button data-page="series">▣<span>Séries</span></button>
<button data-page="aovivo">🔴<span>Ao Vivo</span></button>
<button data-page="lista">♡<span>Minha lista</span></button>
</nav>

<div class="overlay details-overlay" id="detailsOverlay">
  <div class="modal details-modal">
    <button class="close" onclick="closeOverlay('detailsOverlay')">✕</button>
    <div id="detailContent"></div>
  </div>
</div>

<div class="trailer-overlay" id="trailerOverlay">
  <div class="trailer-window">
    <div class="trailer-top">
      <h3 id="trailerTitle">Trailer</h3>
      <button class="close" onclick="closeTrailer()">✕</button>
    </div>

    <div id="trailerFrameArea"></div>
  </div>
</div>


<div class="overlay player-overlay" id="playerOverlay">
  <div class="modal player-modal">

    <button class="close" onclick="closePlayer()">✕</button>

    <h2 id="playerTitle">Assistindo</h2>

    <!-- SERVIDORES -->
    <div id="serverSelection">

      <div class="server-section-heading">
        <span>OPÇÕES DE REPRODUÇÃO</span>
        <h3 class="server-heading">Escolha um servidor</h3>
      </div>

      <div id="serverList" class="server-list"></div>

    </div>

    <!-- SERVIDOR SELECIONADO -->
    <div id="playerStage" class="player-stage hidden">
      <div class="player-stage-top">
        <span id="selectedServerName" class="player-info"></span>

        <button class="player-back" onclick="backToServers()">
          ← Servidores
        </button>
      </div>
    </div>

    <!-- TEMPORADA E EPISÓDIO -->
    <div class="player-content-info">
      <p id="playerContentContext"></p>
    </div>

    <!-- PLAYER PERMANENTE -->
    <div class="player-screen" id="playerScreen">

      <div class="player-placeholder" id="playerPlaceholder">
        <span>▶</span>
        <p>Selecione um servidor para assistir</p>
      </div>

      <video
        id="playerVideo"
        controls
        playsinline
        preload="metadata"
        class="hidden">
      </video>

      <iframe
        id="playerFrame"
        class="hidden"
        allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
        allowfullscreen
        referrerpolicy="strict-origin-when-cross-origin"
        title="Player externo">
      </iframe>

    </div>

    <!-- AÇÕES -->
    <div class="player-actions">
      <button type="button" id="commentButton">
        ▢ Comentar
      </button>

      <button type="button" id="nextEpisodeButton">
        Próximo →
      </button>
    </div>

    <p id="playerMessage" class="player-info"></p>
    <p id="playerError" class="player-error hidden"></p>

  </div>
</div>


<div class="overlay" id="discordOverlay"><div class="modal discord-content">
<button class="close" onclick="closeOverlay('discordOverlay')">✕</button>
<div class="discord-cloud">☁</div><h2>Entre na comunidade NEXORA</h2>
<p style="color:#aaa;font-size:13px">Acompanhe novidades, avisos e lançamentos em nosso servidor Discord.</p>
<a id="discordJoin" class="btn primary" href="#" target="_blank" rel="noopener noreferrer">Entrar no Discord</a>
<button class="btn secondary" onclick="closeOverlay('discordOverlay')">Agora não</button>
</div></div>

<div class="toast" id="toast" role="status" aria-live="polite"></div>

<script>
/* CONFIGURAÇÃO SUPABASE */
const SUPABASE_URL = "https://yhheuiyvxbcevnlgeaha.supabase.co";
const SUPABASE_KEY = "sb_publishable_qtGPrWuhEGdde7FwTwERsw_Bu3HH0Dx";

const db = window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY);

let DISCORD_INVITE="";
let content=[];
window.heroIndex=0;
window.heroTimer=null;
window.heroCurrentId=null;
let notices=[];
let saved=readJSON("nexora-list",[]);
let history=readJSON("nexora-history",[]);
let progress=readJSON("nexora-progress",[]);
let activeProgressMeta=null;
let watched=readJSON("nexora-watched",[]);
let wantToWatch=readJSON("nexora-want-to-watch",[]);
let activeMovieGenre="";
let activeSeriesGenre="";

const $=id=>document.getElementById(id);

function readJSON(key,fallback){
try{const value=JSON.parse(localStorage.getItem(key));return Array.isArray(value)?value:fallback}
catch(e){return fallback}
}

function escapeHTML(value){
return String(value??"").replace(/[&<>"']/g,char=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[char]));
}

function notify(message){
const toast=$("toast");toast.textContent=message;toast.classList.add("show");
clearTimeout(window.toastTimer);window.toastTimer=setTimeout(()=>toast.classList.remove("show"),3000);
}

function saveData(){
  try{
    localStorage.setItem("nexora-list",JSON.stringify(saved));
    localStorage.setItem("nexora-history",JSON.stringify(history));
    localStorage.setItem("nexora-watched",JSON.stringify(watched));
    localStorage.setItem("nexora-want-to-watch",JSON.stringify(wantToWatch));
    localStorage.setItem("nexora-progress",JSON.stringify(progress));
  }catch(e){
    notify("Não foi possível salvar neste dispositivo.");
  }
}

function getContent(id){return content.find(item=>item.id===id)}
function isHTTPS(value){try{return new URL(value).protocol==="https:"}catch(e){return false}}
function safeImageURL(value){return isHTTPS(value)?value:""}
function getYouTubeEmbed(url){
try{
const parsed=new URL(url);
const host=parsed.hostname.replace(/^www\./,"").toLowerCase();
let id="";
if(host==="youtu.be"){
id=parsed.pathname.split("/").filter(Boolean)[0]||"";
}else if(["youtube.com","m.youtube.com","youtube-nocookie.com"].includes(host)){
if(parsed.pathname==="/watch"){
id=parsed.searchParams.get("v")||"";
}else{
const match=parsed.pathname.match(/^\/(embed|shorts|live)\/([A-Za-z0-9_-]{11})/);
if(match)id=match[2];
}
}

if(!/^[A-Za-z0-9_-]{11}$/.test(id))return "";
return "https://www.youtube-nocookie.com/embed/"+id;
}catch(error){
return "";
}
}
function isValidDiscordInvite(value){
try{const url=new URL(value);return url.protocol==="https:"&&["discord.gg","www.discord.gg","discord.com","www.discord.com"].includes(url.hostname)}
catch(e){return false}
}

function formatReleaseDate(value){
if(!value)return "Data a definir";
const date=new Date(value+"T12:00:00");
if(Number.isNaN(date.getTime()))return "Data a definir";
return date.toLocaleDateString("pt-BR",{month:"long",year:"numeric"});
}

/* CARREGAR CATÁLOGO */

async function loadSupabaseData(){
try{
const [cr,rr,catr,sr,er,svr]=await Promise.all([
db.from("conteudos").select("*")
.in("status",["Publicado","Em breve"])
.order("criado_em",{ascending:false}),

db.from("conteudo_categorias")
.select("conteudo_id,categoria_id"),

db.from("categorias").select("id,nome"),

db.from("temporadas").select("*").order("numero"),

db.from("episodios").select("*").order("numero"),

db.from("servidores").select("*").eq("ativo",true)
]);

if(cr.error)throw cr.error;
if(rr.error)throw rr.error;
if(catr.error)throw catr.error;
if(sr.error)throw sr.error;
if(er.error)throw er.error;
if(svr.error)throw svr.error;

const rows=cr.data||[];
const relations=rr.data||[];
const categories=catr.data||[];
const seasons=sr.data||[];
const episodes=er.data||[];
const servers=svr.data||[];

const categoryMap=new Map(
categories.map(c=>[c.id,c.nome])
);

function formatServer(server){
return {
id:server.id,
name:server.nome||"Servidor",
label:server.etiqueta||"",
type:server.tipo,
url:server.url,
sourceType:server.tipo==="embed"?"api":"mp4",
videoUrl:server.tipo==="mp4"?server.url:"",
apiUrl:server.tipo==="embed"?server.url:"",
principal:server.principal===true
};
}

function getMainServer(list){
return list.find(s=>s.principal===true)||list[0]||null;
}

content=rows.map((item,index)=>{

const genres=relations
.filter(r=>r.conteudo_id===item.id)
.map(r=>categoryMap.get(r.categoria_id))
.filter(Boolean);

const itemSeasons=seasons
.filter(s=>s.conteudo_id===item.id)
.map(season=>({

id:season.id,
name:season.titulo||"Temporada "+season.numero,

episodes:episodes
.filter(e=>e.temporada_id===season.id)
.map(episode=>{

const episodeServers=servers
.filter(s=>String(s.episodio_id)===String(episode.id))
.map(formatServer);

const mainEpisodeServer=getMainServer(episodeServers);

return {
id:episode.id,
number:episode.numero,
title:episode.titulo,
description:episode.sinopse||"",
duration:episode.duracao||"",
posterUrl:safeImageURL(episode.capa_url),
servers:episodeServers,
mainServer:mainEpisodeServer,
sourceType:mainEpisodeServer?.sourceType||"",
videoUrl:mainEpisodeServer?.videoUrl||"",
apiUrl:mainEpisodeServer?.apiUrl||""
};
})
}));

const contentServers=servers
.filter(s=>String(s.conteudo_id)===String(item.id)&&s.episodio_id==null)
.map(formatServer);

const mainServer=getMainServer(contentServers);
const upcoming=item.status==="Em breve";

return {
id:item.id,
title:item.titulo,
type:upcoming?"Em breve":item.tipo,
year:item.ano?String(item.ano):"",
genre:genres[0]||"",
genres,

rating:item.avaliacao??"",
duration:item.duracao||"",
synopsis:item.sinopse||"",
cast:item.elenco||"",
director:item.diretor||"",
trailerUrl:safeImageURL(item.trailer_url),
languageLabel:item.etiqueta_idioma||"",
newEpisodeAlerts:item.alerta_novos_episodios===true,
  
posterUrl:safeImageURL(item.capa_url),
bannerUrl:safeImageURL(item.banner_url),
releaseDate:item.data_lancamento||"",
month:formatReleaseDate(item.data_lancamento),
top:item.destaque?index+1:0,
added:rows.length-index,
art:"linear-gradient(135deg,#45151a,#111)",
seasons:itemSeasons,
servers:contentServers,
mainServer:mainServer,
sourceType:mainServer?.sourceType||"",
videoUrl:mainServer?.videoUrl||"",
apiUrl:mainServer?.apiUrl||""
};
});

renderHome();

if(!$("page-filmes").classList.contains("hidden"))
renderCatalog("filmes");

if(!$("page-series").classList.contains("hidden"))
renderCatalog("series");

if(!$("page-breve").classList.contains("hidden"))
renderCatalog("breve");

if(!$("page-recentes").classList.contains("hidden"))
renderCatalog("recentes");

if(!$("page-lista").classList.contains("hidden"))
renderMyList();

}catch(error){
  console.error("ERRO COMPLETO DO SUPABASE:",error);
  alert("ERRO SUPABASE: " + (error.message || error.details || JSON.stringify(error)));
}

await loadPublicNotices();
await loadDiscordInvite();
}

/* AVISOS PÚBLICOS */
async function loadPublicNotices(){
try{
const {data,error}=await db.from("avisos").select("*").eq("ativo",true).order("criado_em",{ascending:false});
if(error)throw error;
notices=(data||[]).map(item=>({
title:item.titulo,message:item.mensagem,
date:item.criado_em?new Date(item.criado_em).toLocaleDateString("pt-BR"):""
}));
renderNotices();
}catch(error){console.error("Erro nos avisos:",error);notices=[];renderNotices()}
}

/* CONVITE DISCORD */
async function loadDiscordInvite(){
try{
const {data,error}=await db.from("configuracoes").select("valor").eq("chave","discord_invite").maybeSingle();
if(error)throw error;
const invite=data?.valor||"";
DISCORD_INVITE=isValidDiscordInvite(invite)?invite:"";
}catch(error){console.error("Erro no convite:",error);DISCORD_INVITE=""}
}

/* NAVEGAÇÃO */
function showPage(page){
document.querySelectorAll(".page").forEach(el=>el.classList.add("hidden"));
const target=$("page-"+page);if(target)target.classList.remove("hidden");
$("hero").classList.toggle("hidden",page!=="inicio");
document.querySelectorAll("[data-page]").forEach(btn=>btn.classList.toggle("active",btn.dataset.page===page));
window.scrollTo({top:0,behavior:"smooth"});
if(page==="lista")renderMyList();
if(page==="avisos")renderNotices();
if(["filmes","series","breve","recentes"].includes(page))renderCatalog(page);
if(page==="inicio")renderHome();
}
document.querySelectorAll("[data-page]").forEach(btn=>btn.addEventListener("click",()=>showPage(btn.dataset.page)));

/* CARTÕES */
function cardHTML(item){
const isSaved=saved.includes(item.id);
const label=item.type==="Em breve"?"EM BREVE":item.top?"TOP "+String(item.top).padStart(2,"0"):"";
const meta=item.type==="Em breve"?item.month||"Data a definir":`${item.year||""} · ${item.genre||item.type}`;
const imageStyle=item.posterUrl?`background-image:url('${escapeHTML(item.posterUrl)}')`:"";
return `<article class="card" onclick="openDetails('${escapeHTML(item.id)}')">
<div class="poster" style="--art:${item.art};${imageStyle}">
${label?`<span class="poster-label">${label}</span>`:""}
<button class="save ${isSaved?"saved":""}" onclick="event.stopPropagation();toggleSaved('${escapeHTML(item.id)}')">${isSaved?"♥":"♡"}</button>
<span class="art-title">${escapeHTML(item.title)}</span></div>
<h3>${escapeHTML(item.title)}</h3><div class="card-meta">${escapeHTML(meta)}</div></article>`;
}
function renderRail(id,items){$(id).innerHTML=items.length?items.map(cardHTML).join(""):'<p class="empty">Nenhum conteúdo disponível.</p>'}

function openProgressEntry(key){
  const entry=progress.find(item=>item.key===key);
  if(!entry)return;

  const item=getContent(entry.contentId);
  if(!item)return;

  openDetails(item.id);

  if(entry.type==="episode"){
    const season=item.seasons?.[entry.seasonIndex];
    const episode=season?.episodes?.[entry.episodeIndex];

    if(episode){
      playEpisode(
        item.id,
        entry.seasonIndex,
        entry.episodeIndex
      );

      const selector=$("seasonSelect");

      if(selector){
        selector.value=String(entry.seasonIndex);
      }
    }
  }
}

function renderHero(){
  const heroItems=content.filter(item=>
    ["Filme","Série","Em breve"].includes(item.type)
  );

  if(!heroItems.length)return;

  if(window.heroIndex>=heroItems.length){
    window.heroIndex=0;
  }

  const item=heroItems[window.heroIndex];

  window.heroCurrentId=item.id;

  const hero=$("hero");
  const title=$("heroTitle");
  const description=$("heroDescription");
  const eyebrow=$("heroEyebrow");
  const meta=$("heroMeta");
  const button=$("heroButton");
  const dots=$("heroDots");

  const image=item.bannerUrl||item.posterUrl;

  hero.style.setProperty(
    "--hero-image",
    image?`url("${image}")`:
    "linear-gradient(135deg,#45151a,#090909)"
  );

  eyebrow.textContent=item.type==="Em breve"
    ?"EM BREVE NA NEXORA"
    :"DESTAQUE NEXORA";

  title.textContent=item.title;
  description.textContent=item.synopsis||"Descubra este conteúdo na NEXORA.";

  meta.textContent=item.type==="Em breve"
    ?item.month||"Data a definir"
    :[item.year,item.genre||item.type].filter(Boolean).join(" · ");

  button.textContent=item.type==="Em breve"
    ?"Saiba mais"
    :"▶ Mais informações";

  dots.innerHTML=heroItems.map((entry,index)=>`
    <button
      class="hero-dot ${index===window.heroIndex?"active":""}"
      onclick="showHeroSlide(${index})"
      aria-label="Banner ${index+1}">
    </button>
  `).join("");

  if(!window.heroTimer && heroItems.length>1){
    window.heroTimer=setInterval(()=>{
      showHeroSlide(
        (window.heroIndex+1)%heroItems.length
      );
    },5000);
  }
}

function showHeroSlide(index){
  const heroContent=document.querySelector(".hero-content");

  if(!heroContent)return;

  heroContent.classList.add("slide-out");

  setTimeout(()=>{
    window.heroIndex=index;
    renderHero();
    heroContent.classList.remove("slide-out");
    heroContent.classList.add("slide-in");

    setTimeout(()=>{
      heroContent.classList.remove("slide-in");
    },450);
  },450);
}

/* INÍCIO */

function renderHome(){
renderHero();
  
  renderRail("trendingRail",
    content.filter(i=>i.top).sort((a,b)=>a.top-b.top)
  );

  renderRail("latestRail",
    [...content]
      .filter(i=>i.type!=="Em breve")
      .sort((a,b)=>b.added-a.added)
      .slice(0,10)
  );

  renderRail("homeUpcoming",
    content.filter(i=>i.type==="Em breve")
  );

  renderRail("homeMovies",
    content.filter(i=>i.type==="Filme")
  );

  renderRail("homeSeries",
    content.filter(i=>i.type==="Série")
  );

  const continueSection=$("continueSection");

  if(!continueSection)return;

  const validProgress=progress
    .filter(entry=>content.some(item=>item.id===entry.contentId))
    .sort((a,b)=>b.updatedAt-a.updatedAt);

  continueSection.classList.toggle(
    "hidden",
    validProgress.length===0
  );

  $("continueRail").innerHTML=validProgress.map(entry=>{

    const item=getContent(entry.contentId);
    if(!item)return "";

    const imageStyle=item.posterUrl
      ?`background-image:url('${escapeHTML(item.posterUrl)}')`
      :"";

    const percent=entry.duration>0
      ?Math.min(100,Math.round(entry.currentTime/entry.duration*100))
      :0;

    const timeText=entry.currentTime>0
      ?"Você parou em "+formatProgressTime(entry.currentTime)
      :"Continue assistindo";

    return `
      <article class="card"
  onclick="openProgressEntry('${escapeHTML(entry.key)}')">

<div class="poster"
          style="--art:${item.art};${imageStyle}">

          <span class="poster-label">CONTINUAR</span>

          <span class="art-title">
            ${escapeHTML(item.title)}
          </span>
        </div>

        <h3>${escapeHTML(
          entry.type==="episode"?entry.title:item.title
        )}</h3>

        <div class="card-meta">${timeText}</div>

        <div style="height:4px;background:#333;border-radius:5px;margin-top:8px;overflow:hidden">
          <div style="height:100%;width:${percent}%;background:#e50914"></div>
        </div>

      </article>
    `;
  }).join("");
}


/* ORDENAÇÃO E CATÁLOGO */
function sortItems(items,sort){
const result=[...items];
if(sort==="nome")result.sort((a,b)=>a.title.localeCompare(b.title,"pt-BR"));
else if(sort==="ano")result.sort((a,b)=>(Number(b.year)||0)-(Number(a.year)||0));
else result.sort((a,b)=>b.added-a.added);
return result;
}

function renderCatalog(page){
if(page==="filmes"){
let items=content.filter(i=>i.type==="Filme");
if(activeMovieGenre)items=items.filter(i=>(i.genres||[i.genre]).includes(activeMovieGenre));
items=sortItems(items,$("movieSort").value);
$("movieGrid").innerHTML=items.map(cardHTML).join("")||'<p class="empty">Nenhum filme encontrado.</p>';
}
if(page==="series"){
let items=content.filter(i=>i.type==="Série");
if(activeSeriesGenre)items=items.filter(i=>(i.genres||[i.genre]).includes(activeSeriesGenre));
items=sortItems(items,$("seriesSort").value);
$("seriesGrid").innerHTML=items.map(cardHTML).join("")||'<p class="empty">Nenhuma série encontrada.</p>';
}
if(page==="breve"){
const items=content.filter(i=>i.type==="Em breve");
$("upcomingGrid").innerHTML=items.map(cardHTML).join("")||'<p class="empty">Nenhuma estreia cadastrada.</p>';
}
if(page==="recentes"){
const items=sortItems(content.filter(i=>i.type!=="Em breve"),"recentes");
$("recentGrid").innerHTML=items.map(cardHTML).join("")||'<p class="empty">Nenhum conteúdo encontrado.</p>';
}
}

document.querySelectorAll("#movieTabs button").forEach(btn=>btn.addEventListener("click",()=>{
activeMovieGenre=btn.dataset.genre;
document.querySelectorAll("#movieTabs button").forEach(b=>b.classList.toggle("active",b===btn));
renderCatalog("filmes");
}));
document.querySelectorAll("#seriesTabs button").forEach(btn=>btn.addEventListener("click",()=>{
activeSeriesGenre=btn.dataset.genre;
document.querySelectorAll("#seriesTabs button").forEach(b=>b.classList.toggle("active",b===btn));
renderCatalog("series");
}));
$("movieSort").addEventListener("change",()=>renderCatalog("filmes"));
$("seriesSort").addEventListener("change",()=>renderCatalog("series"));

/* PESQUISA */
$("searchToggle").addEventListener("click",()=>{
const input=$("searchInput");input.classList.toggle("open");
if(input.classList.contains("open"))input.focus();
else{input.value="";showPage("inicio")}
});
$("searchInput").addEventListener("input",()=>{
const term=$("searchInput").value.trim().toLocaleLowerCase("pt-BR");
if(!term){showPage("inicio");return}
const results=content.filter(item=>
item.title.toLocaleLowerCase("pt-BR").includes(term)||
(item.genre||"").toLocaleLowerCase("pt-BR").includes(term)||
(item.year||"").includes(term)
);
showPage("busca");
$("searchDescription").textContent=`${results.length} resultado(s) encontrado(s)`;
$("searchGrid").innerHTML=results.map(cardHTML).join("")||'<p class="empty">Nenhum título encontrado.</p>';
});

function formatProgressTime(seconds){
  seconds=Math.floor(Number(seconds)||0);

  const minutes=Math.floor(seconds/60);
  const remaining=seconds%60;

  return minutes+":"+String(remaining).padStart(2,"0");
}

function saveProgressEntry(meta,time,duration){
  if(!meta)return;

  const entry={
    key:meta.key,
    contentId:meta.contentId,
    type:meta.type,
    seasonIndex:meta.seasonIndex,
    episodeIndex:meta.episodeIndex,
    title:meta.title,
    currentTime:Number(time)||0,
    duration:Number(duration)||0,
    updatedAt:Date.now()
  };

  progress=progress.filter(item=>item.key!==meta.key);
  progress.unshift(entry);
  progress=progress.slice(0,40);

  saveData();
  renderHome();
}

function removeProgress(key){
  progress=progress.filter(item=>item.key!==key);
  saveData();
  renderHome();
}

function setupProgressVideo(video){
  if(!video||!activeProgressMeta)return;

  const meta={...activeProgressMeta};

  video.onloadedmetadata=()=>{
    const savedProgress=progress.find(item=>item.key===meta.key);

    if(savedProgress&&savedProgress.currentTime>5){
      if(!video.duration||savedProgress.currentTime<video.duration-10){
        video.currentTime=savedProgress.currentTime;
      }
    }
  };

  let lastSave=0;

  video.ontimeupdate=()=>{
    if(!video.duration||!Number.isFinite(video.duration))return;

    const now=Date.now();

    if(now-lastSave<5000)return;

    lastSave=now;

    saveProgressEntry(
      meta,
      video.currentTime,
      video.duration
    );
  };

  video.onpause=()=>{
    if(video.duration&&Number.isFinite(video.duration)){
      saveProgressEntry(meta,video.currentTime,video.duration);
    }
  };

  video.onended=()=>{
    removeProgress(meta.key);
    notify("Conteúdo concluído!");
  };
}

function beginEmbedProgress(){
  if(!activeProgressMeta)return;

  const meta=activeProgressMeta;

  if(!progress.some(item=>item.key===meta.key)){
    saveProgressEntry(meta,0,0);
  }
}

function completeActiveProgress(){
  if(!activeProgressMeta)return;

  removeProgress(activeProgressMeta.key);
  notify("Conteúdo marcado como concluído!");
}
  
function registerHistory(id){
  const item=content.find(i=>i.id===id);
  if(!item)return;

  history=history.filter(entry=>entry.id!==id);

  history.unshift({
    id:id,
    date:Date.now()
  });

  history=history.slice(0,20);

  saveData();
  renderHome();
}

/* MINHA LISTA */
function toggleSaved(id){
if(saved.includes(id)){saved=saved.filter(item=>item!==id);notify("Removido da Minha Lista.")}
else{saved.push(id);notify("Adicionado à Minha Lista.")}
saveData();renderHome();
if(!$("page-lista").classList.contains("hidden"))renderMyList();
if($("detailsOverlay").classList.contains("show"))openDetails(id);
}

function toggleWatched(id){
  if(watched.includes(id)){
    watched=watched.filter(item=>item!==id);
    notify("Removido de Já vi.");
  }else{
    watched.push(id);
    wantToWatch=wantToWatch.filter(item=>item!==id);
    notify("Adicionado a Já vi.");
  }

  saveData();
  renderHome();

  if($("detailsOverlay").classList.contains("show")){
    openDetails(id);
  }
}

function toggleWantToWatch(id){
  if(wantToWatch.includes(id)){
    wantToWatch=wantToWatch.filter(item=>item!==id);
    notify("Removido de Quero ver.");
  }else{
    wantToWatch.push(id);
    notify("Adicionado a Quero ver.");
  }

  saveData();
  renderHome();

  if($("detailsOverlay").classList.contains("show")){
    openDetails(id);
  }
}

function renderMyList(){
const items=saved.map(getContent).filter(Boolean);
$("myListGrid").innerHTML=items.length?items.map(cardHTML).join(""):'<p class="empty">Sua lista ainda está vazia. Use o coração dos cartazes para salvar títulos.</p>';
}

/* DETALHES */

function openDetails(id){
  const item=getContent(id);
  if(!item)return;

  const isSeries=item.type==="Série";
  const isUpcoming=item.type==="Em breve";
  const isMovie=item.type==="Filme";

  const recommendations=content.filter(other=>
    other.id!==item.id &&
    other.type!=="Em breve"
  ).sort((a,b)=>{
    const sameGenreA=(a.genres||[a.genre]).some(g=>
      (item.genres||[item.genre]).includes(g)
    );
    const sameGenreB=(b.genres||[b.genre]).some(g=>
      (item.genres||[item.genre]).includes(g)
    );
    return Number(sameGenreB)-Number(sameGenreA);
  }).slice(0,8);

  const posterStyle=item.posterUrl
    ?`background-image:url('${escapeHTML(item.posterUrl)}')`
    :"";

  const trailerEmbed=getYouTubeEmbed(item.trailerUrl||"");
  const genres=(item.genres||[item.genre]).filter(Boolean);

  const trailerButton=trailerEmbed
    ?`<button class="ref-detail-button"
        onclick="openTrailer('${escapeHTML(trailerEmbed)}','${escapeHTML(item.title)}')">
        ▶ Trailer
      </button>`
    :"";

  const rating=item.rating!==""&&item.rating!==null
    ?escapeHTML(String(item.rating))
    :"—";

  const seasonsHTML=isSeries?renderSeasons(item):"";

  const moviePlaybackHTML=isMovie
    ?'<div id="moviePlaybackArea"></div>'
    :"";

  const recommendationsHTML=recommendations.length
    ?`
      <section class="ref-recommendations">
        <h3>Recomendado para você</h3>
        <div class="recommendations ref-recommendations-grid">
          ${recommendations.map(cardHTML).join("")}
        </div>
      </section>
    `
    :"";

  $("detailContent").innerHTML=`
    <main class="ref-detail-page">

      <div class="ref-detail-crumb">
        <span onclick="closeOverlay('detailsOverlay')">Início</span>
        › ${isSeries?"Séries":isUpcoming?"Em breve":"Filmes"}
        › ${escapeHTML(item.title)}
      </div>

      <section class="ref-detail-card">

        <div class="ref-poster"
          style="--art:${item.art};${posterStyle}">
        </div>

        <div class="ref-top-buttons">
          ${trailerButton}

          <button class="ref-detail-button"
            onclick="toggleSaved('${escapeHTML(item.id)}')">
            ♧ Listas
          </button>
        </div>

        <h1 class="ref-detail-title">
          ${escapeHTML(item.title)}
          ${item.year?" ("+escapeHTML(item.year)+")":""}
        </h1>

        <div class="ref-genres">
          ${genres.map(g=>`<span>${escapeHTML(g)}</span>`).join("")}
          ${item.duration?`<span>• ${escapeHTML(item.duration)}</span>`:""}
        </div>

        <div class="ref-rating">
          <strong>★ ${rating}<small>/10</small></strong>
          <button onclick="notify('Avaliação ainda não disponível.')">
            ☆ Avaliar
          </button>
        </div>

        <div class="ref-user-actions">
  <button onclick="toggleWatched('${escapeHTML(item.id)}')">
    ${watched.includes(item.id)?"✓ Já vi":"+ Já vi"}
  </button>

  <button onclick="toggleWantToWatch('${escapeHTML(item.id)}')">
    ${wantToWatch.includes(item.id)?"✓ Quero ver":"+ Quero ver"}
  </button>
</div>

        ${isSeries?`
          <button class="ref-notify-button"
            onclick="notify('Aviso de novos episódios ainda será conectado.')">
            ♧ Avisar novos episódios
          </button>
        `:""}

        <div class="ref-synopsis">
          ${escapeHTML(item.synopsis||"Sinopse ainda não cadastrada.")}
        </div>

        ${item.director?`
          <p class="ref-extra"><strong>Direção:</strong> ${escapeHTML(item.director)}</p>
        `:""}

        ${item.cast?`
          <p class="ref-extra"><strong>Elenco:</strong> ${escapeHTML(item.cast)}</p>
        `:""}

      </section>

      ${isSeries?seasonsHTML:moviePlaybackHTML}

      ${recommendationsHTML}

    </main>
  `;

  $("detailsOverlay").classList.add("show");

  if(isSeries && item.seasons?.[0]?.episodes?.length){

  const lastProgress=progress
    .filter(entry=>
      entry.contentId===item.id &&
      entry.type==="episode"
    )
    .sort((a,b)=>b.updatedAt-a.updatedAt)[0];

  const seasonIndex=lastProgress?.seasonIndex??0;
  const episodeIndex=lastProgress?.episodeIndex??0;

  const season=item.seasons[seasonIndex];

  if(season?.episodes?.[episodeIndex]){
    playEpisode(item.id,seasonIndex,episodeIndex);

    const selector=$("seasonSelect");

    if(selector){
      selector.value=String(seasonIndex);
    }
  }else{
    playEpisode(item.id,0,0);
  }
}

  if(isMovie){
    playMovieInline(item.id);
  }
}
        
function openTrailer(url,title){
if(!isHTTPS(url))return;

$("trailerTitle").textContent="Trailer — "+title;

$("trailerFrameArea").innerHTML=`
<iframe
src="${escapeHTML(url)}?autoplay=1"
title="Trailer de ${escapeHTML(title)}"
allow="autoplay; encrypted-media; picture-in-picture"
allowfullscreen>
</iframe>`;

$("trailerOverlay").classList.add("show");
}

function closeTrailer(){
$("trailerFrameArea").innerHTML="";
$("trailerOverlay").classList.remove("show");
}

/* TEMPORADAS E EPISÓDIOS */

function renderSeasons(item){
  if(!item.seasons||!item.seasons.length){
    return `
      <div class="ref-season-section">
        <h3>Temporadas e episódios</h3>
        <p class="detail-info">Episódios ainda não cadastrados.</p>
      </div>
    `;
  }

  const options=item.seasons.map((season,index)=>`
    <option value="${index}">
      T${index+1} - ${escapeHTML(season.name)}
    </option>
  `).join("");

  return `
    <div class="ref-season-section">

      <div id="seriesPlaybackArea"></div>

      <span class="ref-season-label">LISTA DE EPISÓDIOS</span>

      <div class="ref-season-heading">
        <div>
          <h3>Temporadas e episódios</h3>
          <p>${item.seasons.length} temporada(s) disponível(is)</p>
        </div>

        <select
          class="season-select"
          id="seasonSelect"
          onchange="renderEpisodes('${escapeHTML(item.id)}',this.value)">
          ${options}
        </select>
      </div>

      <h4 class="ref-current-season" id="currentSeasonTitle">
        ${escapeHTML(item.seasons[0].name)}
      </h4>

      <div class="episode-list" id="episodeList">
        ${episodeHTML(item,0)}
      </div>

    </div>
  `;
}

function episodeHTML(item,seasonIndex){
  const season=item.seasons?.[Number(seasonIndex)];

  if(!season||!season.episodes?.length){
    return '<p class="detail-info">Nenhum episódio cadastrado nesta temporada.</p>';
  }

  return season.episodes.map((episode,index)=>{
    const thumb=episode.posterUrl
      ?`background-image:url('${escapeHTML(episode.posterUrl)}')`
      :"";

    const number=episode.number||index+1;
    const title=episode.title||"Episódio "+(index+1);
    const description=episode.description||"Descrição não cadastrada.";

    return `
      <div class="episode ref-episode"
        onclick="playEpisode('${escapeHTML(item.id)}',${Number(seasonIndex)},${index})">

        <div class="episode-thumb ref-episode-thumb" style="${thumb}">
          ${thumb?"":'<span>▶</span>'}
        </div>

        <div class="ref-episode-info">
          <span class="ref-episode-number">
            EPISÓDIO ${escapeHTML(number)}
          </span>

          <h4>${escapeHTML(title)}</h4>
          <p>${escapeHTML(description)}</p>
        </div>

      </div>
    `;
  }).join("");
}

function renderEpisodes(id,index){
  const item=getContent(id);
  if(!item)return;

  const seasonIndex=Number(index);
  const season=item.seasons?.[seasonIndex];

  if(!season)return;

  $("episodeList").innerHTML=episodeHTML(item,seasonIndex);

  const title=$("currentSeasonTitle");

  if(title){
    title.textContent=season.name||"Temporada "+(seasonIndex+1);
  }

  const playback=$("seriesPlaybackArea");
  if(playback){
    playback.innerHTML="";
  }

  if(season.episodes?.length){
    playEpisode(id,seasonIndex,0);
  }
}

function closeOverlay(id){$(id).classList.remove("show")}

/* PLAYER E SELEÇÃO DE SERVIDORES */

let currentAudioPlayers=[];

function startContent(id){
  const item=getContent(id);
  if(!item)return;

  if(item.type==="Série"){
    notify("Escolha uma temporada e um episódio.");
    return;
  }

  activeProgressMeta={
    key:"movie:"+item.id,
    contentId:item.id,
    type:"movie",
    title:item.title
  };

  playSource(item.title,item);
}

function playEpisode(id,seasonIndex,episodeIndex){
  const item=getContent(id);
  const season=item?.seasons?.[seasonIndex];
  const episode=season?.episodes?.[episodeIndex];

  if(!item||!season||!episode)return;

  currentAudioPlayers=episode.servers||[];

  const playback=$("seriesPlaybackArea");
  if(!playback)return;

  const episodeTitle=episode.title||"Episódio "+(episodeIndex+1);
  const episodeNumber=episode.number||episodeIndex+1;
  const seasonName=season.name||"Temporada "+(seasonIndex+1);
  activeProgressMeta={
  key:"episode:"+item.id+":"+episode.id,
  contentId:item.id,
  type:"episode",
  seasonIndex:seasonIndex,
  episodeIndex:episodeIndex,
  title:seasonName+" · EP "+episodeNumber+" — "+episodeTitle
};

  const servers=currentAudioPlayers.length
    ?currentAudioPlayers.map((server,index)=>{
      const language=String(server.language||server.audio||server.label||"").toLowerCase();

      const isDub=language.includes("dubl");
      const isSub=language.includes("legend")||language.includes("leg");

      const tags=`
        ${isDub?'<span class="server-language dub">DUBLADO</span>':""}
        ${isSub?'<span class="server-language sub">LEGENDADO</span>':""}
      `;

      return `
        <button class="server-option" type="button"
          onclick="selectSeriesServer('${escapeHTML(server.id)}')">
          <div>
            ${tags}
            <strong>${escapeHTML(server.name||"Servidor "+(index+1))}</strong>
          </div>
          <span>›</span>
        </button>
      `;
    }).join("")
    :'<p class="empty">Nenhum servidor cadastrado para este episódio.</p>';

  const previous=episodeIndex>0
    ?`<button type="button" onclick="playEpisode('${escapeHTML(id)}',${seasonIndex},${episodeIndex-1})">← Anterior</button>`
    :"";

  const next=episodeIndex<season.episodes.length-1
    ?`<button type="button" onclick="playEpisode('${escapeHTML(id)}',${seasonIndex},${episodeIndex+1})">Próximo episódio →</button>`
    :"";

  playback.innerHTML=`
    <section class="series-inline-player">

      <div class="player-content-info">
        <p>${escapeHTML(seasonName)} · EP ${escapeHTML(episodeNumber)} — ${escapeHTML(episodeTitle)}</p>
      </div>

      <div class="server-section-heading">
        <span>OPÇÕES DE REPRODUÇÃO</span>
        <h3 class="server-heading">Escolha um servidor</h3>
      </div>

      <div class="server-list">
        ${servers}
      </div>

      <div class="player-stage">
        <span id="seriesSelectedServer" class="player-info"></span>
      </div>

      <div class="player-screen">
        <div class="player-placeholder" id="seriesPlayerPlaceholder">
          <span>▶</span>
          <p>Selecione um servidor para assistir</p>
        </div>

        <video id="seriesPlayerVideo" controls playsinline
          preload="metadata" class="hidden"></video>

        <iframe id="seriesPlayerFrame" class="hidden"
          allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
          allowfullscreen
          referrerpolicy="strict-origin-when-cross-origin"
          title="Player da série"></iframe>
      </div>

      <div class="player-actions">
        ${previous}
        ${next}
      </div>

      <p id="seriesPlayerMessage" class="player-info"></p>
      <button
  type="button"
  id="seriesCompleteButton"
  class="btn secondary hidden"
  onclick="completeActiveProgress()">
  Marcar como concluído
</button>

    </section>
  `;

}

function playSource(title,source){
  currentAudioPlayers=source.servers||[];

  $("playerTitle").textContent=title;
  $("playerError").classList.add("hidden");
  $("playerError").textContent="";
  $("playerMessage").textContent="";

  // Limpa a reprodução anterior
  $("playerVideo").pause();
  $("playerVideo").removeAttribute("src");
  $("playerVideo").load();

  $("playerFrame").src="about:blank";

  $("playerVideo").classList.add("hidden");
  $("playerFrame").classList.add("hidden");

  // Mantém a tela preta visível
  $("playerPlaceholder").classList.remove("hidden");

  // Esconde somente a barra de servidor selecionado
  $("playerStage").classList.add("hidden");

  // Mantém a lista de servidores abaixo do player
  $("serverSelection").classList.remove("hidden");

  const list=$("serverList");
  list.innerHTML="";

  if(!currentAudioPlayers.length){
    list.innerHTML=
      '<p class="empty">Nenhum servidor cadastrado para este conteúdo.</p>';
  }else{
    currentAudioPlayers.forEach((server,index)=>{
      const button=document.createElement("button");
      button.type="button";
      button.className="server-option";

      const info=document.createElement("div");

      const name=document.createElement("strong");
      name.textContent=server.name||"Servidor "+(index+1);

      const description=document.createElement("small");
      description.textContent=
        (server.label?server.label+" · ":"")+
        (server.principal?"Servidor principal":"Servidor alternativo");

      info.appendChild(name);
      info.appendChild(description);

      const arrow=document.createElement("span");
      arrow.textContent="›";

      button.appendChild(info);
      button.appendChild(arrow);

      button.addEventListener("click",()=>{
        selectServer(server.id);
      });

      list.appendChild(button);
    });
  }

  $("playerOverlay").classList.add("show");
}

function playMovieInline(id){
  const item=getContent(id);
  if(!item)return;

  currentAudioPlayers=item.servers||[];
  activeProgressMeta={
  key:"movie:"+item.id,
  contentId:item.id,
  type:"movie",
  title:item.title
};

  const playback=$("moviePlaybackArea");
  if(!playback)return;

  const servers=currentAudioPlayers.length
    ?currentAudioPlayers.map((server,index)=>{
      const language=String(
  server.etiqueta||server.label||server.language||server.audio||""
).toLowerCase();

      const isDub=language.includes("dubl");
      const isSub=language.includes("legend")||language.includes("leg");

      const tags=`
        ${isDub?'<span class="server-language dub">DUBLADO</span>':""}
        ${isSub?'<span class="server-language sub">LEGENDADO</span>':""}
      `;

      return `
        <button class="server-option" type="button"
          onclick="selectMovieInlineServer('${escapeHTML(server.id)}')">
          <div>
            ${tags}
            <strong>${escapeHTML(server.name||"Servidor "+(index+1))}</strong>
          </div>
          <span>›</span>
        </button>
      `;
    }).join("")
    :'<p class="empty">Nenhum servidor cadastrado para este filme.</p>';

  playback.innerHTML=`
    <section class="series-inline-player movie-inline-player">

      <div class="server-section-heading">
        <span>OPÇÕES DE REPRODUÇÃO</span>
        <h3 class="server-heading">Escolha um servidor</h3>
      </div>

      <div class="server-list">${servers}</div>

      <div class="player-stage">
        <span id="movieSelectedServer" class="player-info"></span>
      </div>

      <div class="player-screen">
        <div class="player-placeholder" id="moviePlayerPlaceholder">
          <span>▶</span>
          <p>Selecione um servidor para assistir</p>
        </div>

        <video id="moviePlayerVideo"
          controls playsinline preload="metadata" class="hidden">
        </video>

        <iframe id="moviePlayerFrame" class="hidden"
          allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
          allowfullscreen
          referrerpolicy="strict-origin-when-cross-origin"
          title="Player do filme">
        </iframe>
      </div>

      <p id="moviePlayerMessage" class="player-info"></p>
      <button
  type="button"
  id="movieCompleteButton"
  class="btn secondary hidden"
  onclick="completeActiveProgress()">
  Marcar como concluído
</button>

    </section>
  `;

}

function selectMovieInlineServer(serverId){
  const server=currentAudioPlayers.find(
    item=>String(item.id)===String(serverId)
  );

  if(!server)return;

  const video=$("moviePlayerVideo");
  const frame=$("moviePlayerFrame");
  const placeholder=$("moviePlayerPlaceholder");
  const message=$("moviePlayerMessage");
  const selected=$("movieSelectedServer");

  if(!video||!frame||!placeholder||!message)return;

  video.pause();
  video.removeAttribute("src");
  video.load();

  frame.src="about:blank";

  video.classList.add("hidden");
  frame.classList.add("hidden");

  placeholder.classList.remove("hidden");
  message.textContent="";

  const url=server.url||
    (server.sourceType==="mp4"?server.videoUrl:server.apiUrl);

  if(!url||!isHTTPS(url)){
    message.textContent="Link de reprodução inválido ou indisponível.";
    return;
  }

  const type=server.type||
    (server.sourceType==="mp4"?"mp4":"embed");

  if(type==="mp4"){
    video.src=url;
    video.classList.remove("hidden");
    video.load();

    setupProgressVideo(video);
    $("movieCompleteButton")?.classList.add("hidden");

  }else if(type==="embed"){
    frame.src=url;
    frame.classList.remove("hidden");

    beginEmbedProgress();
    $("movieCompleteButton")?.classList.remove("hidden");

  }else{
    message.textContent="Tipo de servidor não reconhecido.";
    return;
  }

  placeholder.classList.add("hidden");

  if(selected){
    selected.textContent="Servidor selecionado: "+(server.name||"Servidor");
  }

  message.textContent="Reprodução carregada.";
}


function selectSeriesServer(serverId){
  const server=currentAudioPlayers.find(
    item=>String(item.id)===String(serverId)
  );

  if(!server)return;

  const video=$("seriesPlayerVideo");
  const frame=$("seriesPlayerFrame");
  const placeholder=$("seriesPlayerPlaceholder");
  const message=$("seriesPlayerMessage");
  const selected=$("seriesSelectedServer");

  if(!video||!frame||!placeholder||!message)return;

  video.pause();
  video.removeAttribute("src");
  video.load();

  frame.src="about:blank";

  video.classList.add("hidden");
  frame.classList.add("hidden");

  placeholder.classList.remove("hidden");
  message.textContent="";

  const url=server.url||
    (server.sourceType==="mp4"?server.videoUrl:server.apiUrl);

  if(!url||!isHTTPS(url)){
    message.textContent="Link de reprodução inválido ou indisponível.";
    return;
  }

  const type=server.type||
    (server.sourceType==="mp4"?"mp4":"embed");

  if(type==="mp4"){
    video.src=url;
    video.classList.remove("hidden");
    video.load();

    setupProgressVideo(video);
    $("seriesCompleteButton")?.classList.add("hidden");

  }else if(type==="embed"){
    frame.src=url;
    frame.classList.remove("hidden");

    beginEmbedProgress();
    $("seriesCompleteButton")?.classList.remove("hidden");

  }else{
    message.textContent="Tipo de servidor não reconhecido.";
    return;
  }

  placeholder.classList.add("hidden");

  if(selected){
    selected.textContent="Servidor selecionado: "+(server.name||"Servidor");
  }

  message.textContent="Reprodução carregada.";
}


function selectServer(serverId){
  const server=currentAudioPlayers.find(
    item=>String(item.id)===String(serverId)
  );

  if(!server)return;

  $("selectedServerName").textContent=
    server.name||"Servidor selecionado";

  $("playerError").classList.add("hidden");
  $("playerError").textContent="";
  $("playerMessage").textContent="";

  // Limpa reprodução anterior
  $("playerVideo").pause();
  $("playerVideo").removeAttribute("src");
  $("playerVideo").load();

  $("playerFrame").src="about:blank";

  $("playerVideo").classList.add("hidden");
  $("playerFrame").classList.add("hidden");

  const url=server.url||
    (server.sourceType==="mp4"?server.videoUrl:server.apiUrl);

  if(!url||!isHTTPS(url)){
    $("playerMessage").textContent=
      "Link de reprodução inválido ou indisponível.";
    return;
  }

  const type=server.type||(
    server.sourceType==="mp4"?"mp4":"embed"
  );

  if(type==="mp4"){
    $("playerVideo").src=url;
    $("playerVideo").classList.remove("hidden");
    $("playerVideo").load();

  }else if(type==="embed"){
    $("playerFrame").src=url;
    $("playerFrame").classList.remove("hidden");

  }else{
    $("playerMessage").textContent=
      "Tipo de servidor não reconhecido.";
    return;
  }

  // Esconde a mensagem de espera
  $("playerPlaceholder").classList.add("hidden");

  // Mantém a mesma tela e a lista de servidores
  $("playerStage").classList.remove("hidden");
  $("serverSelection").classList.remove("hidden");

  $("playerMessage").textContent=
    "Servidor selecionado: "+(server.name||"Servidor");
}

function backToServers(){
  // Para o vídeo
  $("playerVideo").pause();
  $("playerVideo").removeAttribute("src");
  $("playerVideo").load();

  // Limpa o iframe
  $("playerFrame").src="about:blank";

  $("playerVideo").classList.add("hidden");
  $("playerFrame").classList.add("hidden");

  // Restaura a tela preta
  $("playerPlaceholder").classList.remove("hidden");

  // Mantém os servidores visíveis
  $("playerStage").classList.add("hidden");
  $("serverSelection").classList.remove("hidden");

  $("playerMessage").textContent="";
  $("playerError").textContent="";
  $("playerError").classList.add("hidden");
}

function closePlayer(){
  currentAudioPlayers=[];

  // Parar e limpar vídeo
  $("playerVideo").pause();
  $("playerVideo").removeAttribute("src");
  $("playerVideo").load();

  // Limpar iframe
  $("playerFrame").src="about:blank";

  // Esconder reprodução
  $("playerVideo").classList.add("hidden");
  $("playerFrame").classList.add("hidden");

  // Restaurar tela preta
  $("playerPlaceholder").classList.remove("hidden");

  // Restaurar informações
  $("playerTitle").textContent="Assistindo";
  $("playerContentContext").textContent="";
  $("selectedServerName").textContent="";
  $("playerMessage").textContent="";

  $("playerError").textContent="";
  $("playerError").classList.add("hidden");

  // Restaurar servidores
  $("playerStage").classList.add("hidden");
  $("serverSelection").classList.remove("hidden");

  // Fechar player
  $("playerOverlay").classList.remove("show");
}

/* AVISOS */
function renderNotices(){
$("noticeList").innerHTML=notices.length?notices.map(n=>`
<div class="notice"><h3>${escapeHTML(n.title)}</h3><p>${escapeHTML(n.message)}</p><small>${escapeHTML(n.date||"")}</small></div>
`).join(""):'<p class="empty">Nenhum aviso publicado no momento.</p>';
}

/* ENVIAR PEDIDO PARA SUPABASE */
$("requestForm").addEventListener("submit",async event=>{
event.preventDefault();
const button=$("requestForm").querySelector('button[type="submit"]');
const titulo=$("requestTitle").value.trim();
const tipo=$("requestType").value;
const detalhes=$("requestExtra").value.trim();
if(!titulo)return;
button.disabled=true;button.textContent="Enviando...";
try{
const {error}=await db.from("solicitacoes").insert([{
nome_conteudo:titulo,
tipo:tipo,
mensagem:detalhes,
status:"Pendente"
}]);
if(error)throw error;
notify("Pedido enviado com sucesso!");
$("requestForm").reset();
}catch(error){
console.error("Erro ao enviar pedido:",error);
notify("Não foi possível enviar. Confira a tabela e as permissões.");
}finally{button.disabled=false;button.textContent="Enviar pedido"}
});

/* ENVIAR RELATO DE BUG PARA SUPABASE */
$("bugForm").addEventListener("submit",async event=>{
event.preventDefault();
const button=$("bugForm").querySelector('button[type="submit"]');
const assunto=$("bugType").value;
const descricao=$("bugDescription").value.trim();
if(!descricao)return;
button.disabled=true;button.textContent="Enviando...";
try{
const {error}=await db.from("relatos_bugs").insert([{
assunto:assunto,
descricao:descricao,
pagina:"Site principal NEXORA",
status:"Novo"
}]);
if(error)throw error;
notify("Relato enviado com sucesso! Obrigado.");
$("bugForm").reset();
}catch(error){
console.error("Erro ao enviar relato:",error);
notify("Não foi possível enviar. Confira a tabela e as permissões.");
}finally{button.disabled=false;button.textContent="Enviar relato"}
});

/* POPUP DISCORD */
function showDiscordPopup(){
if(!DISCORD_INVITE)return;
try{if(sessionStorage.getItem("nexora-popup-seen"))return}catch(e){}
$("discordJoin").href=DISCORD_INVITE;
$("discordOverlay").classList.add("show");
try{sessionStorage.setItem("nexora-popup-seen","1")}catch(e){}
}

let liveChannelsCache = [];

async function carregarProgramacaoAoVivo(canalId) {
  const area = document.getElementById("liveSchedule");

  if (!area) return;

  if (window.liveCountdownInterval) {
    clearInterval(window.liveCountdownInterval);
  }

  area.innerHTML = `
    <p style="color:#999;padding:15px 0">
      Carregando programação...
    </p>
  `;

  try {
    const agora = new Date();
    const ontem = new Date(agora);
    ontem.setDate(ontem.getDate() - 1);

    const { data, error } = await db
      .from("programacao_importada")
      .select("titulo,descricao,inicio_em,fim_em")
      .eq("canal_id", Number(canalId))
      .eq("ativo", true)
      .gte("inicio_em", ontem.toISOString())
      .order("inicio_em", { ascending: true })
      .limit(500);

    if (error) throw error;

    if (!data || !data.length) {
      area.innerHTML = `
        <h3 style="margin-top:22px">📺 Programação</h3>
        <p style="color:#999">
          Nenhuma programação disponível para este canal.
        </p>
      `;
      return;
    }

    function chaveData(data) {
      const d = new Date(data);

      return [
        d.getFullYear(),
        String(d.getMonth() + 1).padStart(2, "0"),
        String(d.getDate()).padStart(2, "0")
      ].join("-");
    }

    function formatarHora(data) {
      if (!data) return "--:--";

      return new Date(data).toLocaleTimeString("pt-BR", {
        hour: "2-digit",
        minute: "2-digit"
      });
    }

    function formatarData(data) {
      const [ano, mes, dia] = data.split("-");

      return `${dia}/${mes}/${ano}`;
    }

    const horario = data
  .map(programa => {
    const inicio = new Date(programa.inicio_em);

    if (!Number.isFinite(inicio.getTime())) {
      return null;
    }

    let fim = programa.fim_em
      ? new Date(programa.fim_em)
      : null;

    const fimValido =
      fim &&
      Number.isFinite(fim.getTime()) &&
      fim > inicio &&
      (fim - inicio) <= 24 * 60 * 60 * 1000;

    if (!fimValido) {
      fim = null;
    }

    return {
      ...programa,
      inicio,
      fim,
      data: chaveData(inicio)
    };
  })
  .filter(p => p !== null)
  .sort((a, b) => a.inicio - b.inicio);

horario.forEach((programa, index) => {
  if (!programa.fim && horario[index + 1]) {
    const proximoInicio = horario[index + 1].inicio;
    const duracao = proximoInicio - programa.inicio;

    if (
      proximoInicio > programa.inicio &&
      duracao <= 24 * 60 * 60 * 1000
    ) {
      programa.fim = proximoInicio;
    }
  }
});

    const datasDisponiveis = [
      ...new Set(horario.map(p => p.data))
    ].sort();

    const hoje = chaveData(agora);

    let dataSelecionada = datasDisponiveis.includes(hoje)
      ? hoje
      : (datasDisponiveis.find(d => d > hoje) || datasDisponiveis[0]);

    function renderizarProgramacao() {
      const agoraAtual = new Date();

      const programasDia = horario.filter(p =>
        p.data === dataSelecionada
      );

      const mostrandoHoje = dataSelecionada === hoje;

      const atual = mostrandoHoje
        ? horario.find(p =>
            p.inicio <= agoraAtual &&
            p.fim &&
            p.fim > agoraAtual
          )
        : null;

      const proximos = programasDia.filter(p =>
        p !== atual &&
        (!mostrandoHoje || p.inicio > agoraAtual)
      );

      area.innerHTML = `
        <div style="margin-top:22px">

          <h3 style="font-size:19px;margin-bottom:14px">
            📺 Programação do canal
          </h3>

          <div style="margin-bottom:17px">
            <label style="
              display:block;
              color:#aaa;
              font-size:12px;
              margin-bottom:8px;
            ">
              CONSULTAR OUTRO DIA
            </label>

            <select id="liveDateSelect" style="
              width:100%;
              padding:12px;
              border-radius:8px;
              background:#171717;
              color:white;
              border:1px solid #333;
              font-size:13px;
            ">
              ${datasDisponiveis.map(d => `
                <option value="${d}"
                  ${d === dataSelecionada ? "selected" : ""}>
                  ${formatarData(d)}
                  ${d === hoje ? " — Hoje" : ""}
                </option>
              `).join("")}
            </select>
          </div>

          ${atual ? `
            <div style="
              background:#241315;
              border:1px solid #e50914;
              border-radius:9px;
              padding:15px;
              margin-bottom:14px;
            ">
              <span style="
                color:#ff4545;
                font-size:10px;
                font-weight:bold;
              ">
                ● AO VIVO AGORA
              </span>

              <h3 style="margin:9px 0;color:white">
                ${escapeHTML(atual.titulo)}
              </h3>

              <p style="color:#aaa;font-size:12px">
                ${formatarHora(atual.inicio)}
                –
                ${formatarHora(atual.fim)}
              </p>

              <div style="
                margin-top:14px;
                padding:12px;
                background:#160c0d;
                border-radius:7px;
              ">
                <p style="
                  color:#aaa;
                  font-size:11px;
                  margin-bottom:5px;
                ">
                  TERMINA EM
                </p>

                <strong id="liveCountdown" style="
                  color:#ff4545;
                  font-size:23px;
                  letter-spacing:2px;
                ">
                  --:--:--
                </strong>
              </div>

              ${atual.descricao ? `
                <p style="
                  color:#bbb;
                  font-size:12px;
                  line-height:1.6;
                  margin-top:12px;
                ">
                  ${escapeHTML(atual.descricao)}
                </p>
              ` : ""}
            </div>
          ` : `
            <div style="
              background:#171717;
              border:1px solid #ffffff15;
              border-radius:8px;
              padding:14px;
              margin-bottom:14px;
            ">
              <p style="color:#aaa;font-size:13px">
                ${mostrandoHoje
                  ? "Nenhum programa identificado como ao vivo neste momento."
                  : "Programação do dia selecionado."}
              </p>
            </div>
          `}

          <h4 style="
            color:#aaa;
            font-size:12px;
            margin:15px 0;
          ">
            ${mostrandoHoje ? "PRÓXIMOS PROGRAMAS" : "PROGRAMAÇÃO DO DIA"}
          </h4>

          <div style="display:grid;gap:9px">
            ${proximos.length ? proximos.map(p => `
              <div style="
                background:#171717;
                border:1px solid #ffffff15;
                border-radius:8px;
                padding:13px;
              ">
                <strong style="
                  font-size:13px;
                  color:white;
                ">
                  ${escapeHTML(p.titulo)}
                </strong>

                <p style="
                  color:#e50914;
                  font-size:11px;
                  margin:7px 0;
                ">
                  ${formatarHora(p.inicio)}
                  –
                  ${formatarHora(p.fim)}
                </p>

                ${p.descricao ? `
                  <p style="
                    color:#999;
                    font-size:11px;
                    line-height:1.5;
                  ">
                    ${escapeHTML(p.descricao)}
                  </p>
                ` : ""}
              </div>
            `).join("") : `
              <p style="color:#999;font-size:12px">
                Não há outros programas disponíveis nesta data.
              </p>
            `}
          </div>

        </div>
      `;

      const seletor = document.getElementById("liveDateSelect");

      if (seletor) {
        seletor.addEventListener("change", function() {
          dataSelecionada = this.value;
          renderizarProgramacao();
        });
      }

      atualizarContagem();
    }

    function atualizarContagem() {
  const contador = document.getElementById("liveCountdown");

  if (!contador) return;

  const agoraAtual = new Date();

  const programaAtual = horario.find(p =>
    p.inicio <= agoraAtual &&
    p.fim &&
    p.fim > agoraAtual &&
    (p.fim - p.inicio) <= 24 * 60 * 60 * 1000
  );

  if (!programaAtual) {
    contador.textContent = "--:--:--";
    return;
  }

  const restante = Math.floor(
    (programaAtual.fim - agoraAtual) / 1000
  );

  const horas = String(
    Math.floor(restante / 3600)
  ).padStart(2, "0");

  const minutos = String(
    Math.floor((restante % 3600) / 60)
  ).padStart(2, "0");

  const segundos = String(
    restante % 60
  ).padStart(2, "0");

  contador.textContent = `${horas}:${minutos}:${segundos}`;
}

    renderizarProgramacao();

    window.liveCountdownInterval = setInterval(() => {
      atualizarContagem();
    }, 1000);

  } catch (error) {
    console.error("Erro na programação:", error);

    area.innerHTML = `
      <p style="color:#ff7373;margin-top:20px">
        Não foi possível carregar a programação.
      </p>
    `;
  }
}
  
async function loadLiveChannels(){
  const container = document.getElementById("liveChannels");

  try {
    const {data: categorias, error: erroCategorias} = await db
      .from("categorias_ao_vivo")
      .select("id,nome,ordem,ativo")
      .eq("ativo", true)
      .order("ordem", {ascending:true});

    if(erroCategorias) throw erroCategorias;

    const {data: canais, error: erroCanais} = await db
      .from("conteudos_ao_vivo")
      .select(`
        id,
        titulo,
        capa_url,
        logo_url,
        banner_url,
        player_url,
        categoria_id,
        ativo
      `)
      .eq("ativo", true)
      .order("criado_em", {ascending:false});

    if(erroCanais) throw erroCanais;

    liveChannelsCache = canais || [];

    if(!liveChannelsCache.length){
      container.innerHTML = '<p class="empty">Nenhum canal disponível no momento.</p>';
      return;
    }

    const escape = value => String(value || "").replace(/[&<>"']/g, c => ({
      '&':'&amp;',
      '<':'&lt;',
      '>':'&gt;',
      '"':'&quot;',
      "'":'&#39;'
    })[c]);

    const criarCard = channel => {
      const imagem = channel.logo_url || channel.capa_url || channel.banner_url || "";

      return `
        <div style="
          flex:0 0 180px;
          width:180px;
          background:#141414;
          border-radius:12px;
          overflow:hidden;
          padding:9px;
        ">
          ${imagem ? `
            <img
              src="${escape(imagem)}"
              alt=""
              style="
                width:100%;
                aspect-ratio:16/9;
                object-fit:cover;
                border-radius:8px;
              "
            >
          ` : `
            <div style="
              width:100%;
              aspect-ratio:16/9;
              background:#222;
              border-radius:8px;
              display:flex;
              align-items:center;
              justify-content:center;
              color:#aaa;
            ">📺</div>
          `}

          <h3 style="font-size:15px;margin:10px 0;">
            ${escape(channel.titulo)}
          </h3>

          <button
            style="
              background:#e50914;
              color:white;
              border:0;
              padding:10px;
              border-radius:8px;
              font-weight:bold;
              width:100%;
              cursor:pointer;
            "
            onclick="playLiveChannel(${Number(channel.id)})">
            ▶ Assistir
          </button>
        </div>
      `;
    };

    const secoes = [];

    (categorias || []).forEach(categoria => {
      const canaisDaCategoria = liveChannelsCache.filter(
        channel => Number(channel.categoria_id) === Number(categoria.id)
      );

      if(!canaisDaCategoria.length) return;

      secoes.push(`
        <section style="margin-bottom:28px;">
          <h2 style="
            color:white;
            font-size:21px;
            font-weight:800;
            margin:0 0 14px;
          ">
            ${escape(categoria.nome)}
          </h2>

          <div style="
            display:flex;
            gap:13px;
            overflow-x:auto;
            padding-bottom:12px;
            scrollbar-width:thin;
          ">
            ${canaisDaCategoria.map(criarCard).join("")}
          </div>
        </section>
      `);
    });

    const semCategoria = liveChannelsCache.filter(
      channel => !(categorias || []).some(
        categoria => Number(categoria.id) === Number(channel.categoria_id)
      )
    );

    if(semCategoria.length){
      secoes.push(`
        <section style="margin-bottom:28px;">
          <h2 style="color:white;font-size:21px;margin-bottom:14px;">
            Outros canais
          </h2>
          <div style="display:flex;gap:13px;overflow-x:auto;padding-bottom:12px;">
            ${semCategoria.map(criarCard).join("")}
          </div>
        </section>
      `);
    }

    container.innerHTML = secoes.length
      ? secoes.join("")
      : '<p class="empty">Nenhuma categoria possui canais disponíveis.</p>';

  } catch(error) {
    console.error("Erro ao carregar canais:", error);
    container.innerHTML = '<p class="empty">Não foi possível carregar os canais.</p>';
  }
}

async function playLiveChannel(id) {
  const channel = liveChannelsCache.find(
    item => Number(item.id) === Number(id)
  );

  if (!channel) return;

  const player = document.getElementById("livePlayer");
  const area = document.getElementById("livePlayerArea");
  const title = document.getElementById("liveChannelTitle");

  if (!channel.player_url ||
      !channel.player_url.startsWith("https://")) {
    alert("Endereço de transmissão inválido.");
    return;
  }

  title.textContent = channel.titulo;
  player.src = channel.player_url;

  area.classList.remove("hidden");

  area.scrollIntoView({
    behavior: "smooth",
    block: "start"
  });

  await carregarProgramacaoAoVivo(channel.id);

  window.liveChannelAtual = channel.id;

  clearInterval(window.liveScheduleInterval);

  window.liveScheduleInterval = setInterval(() => {
    if (window.liveChannelAtual) {
      carregarProgramacaoAoVivo(
        window.liveChannelAtual
      );
    }
  }, 300000);
}

/* INICIALIZAÇÃO */
async function init(){
  renderHome();
  renderNotices();
  await loadSupabaseData();
  await loadLiveChannels();
  setTimeout(showDiscordPopup,900);
}

init();
</script>
</body>
</html>