<style></style>
</head>
<body>

<div class="container">
  <div class="tabs-wrapper">
    <div class="tabs" id="tabs"></div>
  </div>
  <div id="content"></div>
</div>

<script>
  window.wpUserLoggedIn = false;
  window.currentLang = "en";
</script>

<script>
function traducirDiaSemana(dia) {
  const traducciones = {
    'Lunes': 'Monday',
    'Martes': 'Tuesday',
    'Miércoles': 'Wednesday',
    'Miercoles': 'Wednesday',
    'Jueves': 'Thursday',
    'Viernes': 'Friday',
    'Sábado': 'Saturday',
    'Sabado': 'Saturday',
    'Domingo': 'Sunday'
  };

  return traducciones[dia] || dia;
}

function limpiarPrograma(valor) {
  return valor
    .replace(/^"(.*)"$/, '$1')
    .replace(/\bS\d{1,3}E\d{1,3}\b/gi, '')
    .replace(/\b\d{1,2}:\d{2}:\d{2}\b/g, '')
    .replace(/\(\d+\)/g, '')
    .replace(/[\s\-–—\/\\]+$/g, '')
    .replace(/\s+/g, ' ')
    .trim();
}

/*
 * Detecta información auxiliar de la programación que no debe
 * mostrarse en el front como si fuera el nombre de un programa.
 *
 * Ejemplos:
 * 30 Cap.
 * 52 Cap.
 * 30 Cap
 * Cap. 30
 * 30 capítulos
 * Capítulo 30
 * S01E17
 * 00:22:00
 */
function esDatoAuxiliar(valor) {
  if (valor === null || valor === undefined) {
    return true;
  }

  const texto = String(valor)
    .replace(/^"(.*)"$/, '$1')
    .replace(/\u00A0/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();

  if (!texto) {
    return true;
  }

  const esDuracion =
    /^\d{1,2}:\d{2}(?::\d{2})?$/.test(texto);

  const esEpisodio =
    /^S\d{1,3}E\d{1,3}$/i.test(texto);

  const esSoloNumeros =
    /^[0-9:]+$/.test(texto);

  const esCantidadCapitulos =
    /^(?:\d+\s*CAP(?:[ÍI]TULOS?)?\.?|CAP(?:[ÍI]TULOS?)?\.?\s*\d+)$/i.test(texto);

  return (
    esDuracion ||
    esEpisodio ||
    esSoloNumeros ||
    esCantidadCapitulos
  );
}

function parseCSV(data) {
  const rows = [];
  let insideQuote = false;
  let row = [];
  let cell = '';

  for (let i = 0; i < data.length; i++) {
    const char = data[i];
    const nextChar = data[i + 1];

    if (char === '"') {
      if (insideQuote && nextChar === '"') {
        cell += '"';
        i++;
      } else {
        insideQuote = !insideQuote;
      }
    } else if (char === ',' && !insideQuote) {
      row.push(cell);
      cell = '';
    } else if ((char === '\n' || char === '\r') && !insideQuote) {
      row.push(cell);

      if (row.length > 0) {
        rows.push(row);
      }

      row = [];
      cell = '';

      if (char === '\r' && nextChar === '\n') {
        i++;
      }
    } else {
      cell += char;
    }
  }

  if (cell || cell === '') {
    row.push(cell);
  }

  if (row.length > 0) {
    rows.push(row);
  }

  return rows;
}

const csvUrl = 'https://docs.google.com/spreadsheets/d/1PJNvhJMM_2Xq0KIEgbezn2iUbyKQOKfXj9E-9_-1lsQ/export?format=csv&gid=0';

fetch(csvUrl)
  .then(response => response.text())
  .then(data => {
    const rows = parseCSV(data);

    const headers = rows[0].slice(1).map((dia, idx) => {
      const fechaCruda = rows[1]?.[idx + 1]?.trim() || '';
      const soloDia = fechaCruda.split('-')[0];

      const diaMayus = dia.trim();
      const diaCapitalizado =
        diaMayus.charAt(0).toUpperCase() +
        diaMayus.slice(1).toLowerCase();

      let diaTraducido = diaCapitalizado;

      if (window.currentLang === 'en') {
        diaTraducido = traducirDiaSemana(diaCapitalizado);
      }

      return `${diaTraducido.toUpperCase()} ${soloDia}`;
    });

    rows.splice(1, 1);

    const contentByDay = {};
    const today = new Date();

    today.setHours(0, 0, 0, 0);

    const marcadoresAExcluir = [
      'SÁBADOS DE CINE',
      'MOVIES MEXICANAS CLASICAS',
      'MOVIES MEXICANAS CLASICAS: GÉNERO DRAMA / COMEDIA / ROMANCE',
      'MOVIES MEXICANAS CLASICAS: ACCIÓN / CRIME / WESTERN / ADVENTURE',
      'CINE DE TERROR',
      'MOVIE'
    ];

    function parseDateFromHeader(header) {
      const match = header.match(/\d{1,2}$/);

      if (!match) {
        return null;
      }

      const day = parseInt(match[0]);
      const currentMonth = today.getMonth();
      const currentYear = today.getFullYear();

      let date = new Date(
        currentYear,
        currentMonth,
        day
      );

      if (date < today) {
        date.setMonth(currentMonth + 1);
      }

      return date;
    }

    let validCount = 0;

    for (let col = 1; col < rows[0].length; col++) {
      const day = headers[col - 1].trim();
      const parsedDate = parseDateFromHeader(day);

      if (!parsedDate) {
        continue;
      }

      const diffDays = Math.floor(
        (parsedDate - today) /
        (1000 * 60 * 60 * 24)
      );

      if (diffDays < 0 || diffDays > 6) {
        continue;
      }

      if (validCount >= 7) {
        break;
      }

      contentByDay[day] = [];
      validCount++;

      for (let i = 1; i < rows.length; i++) {
        const hora = rows[i][0];
        let valor = rows[i][col];

        if (!valor) {
          continue;
        }

        valor = valor
          .replace(/^"(.*)"$/, '$1')
          .trim();

        if (valor.includes('(F)')) {
          continue;
        }

        const valorLimpioParaValidar =
          limpiarPrograma(valor);

        const tieneTexto =
          /[A-Za-zÁÉÍÓÚáéíóúÑñ]/.test(
            valorLimpioParaValidar
          );

        if (
          marcadoresAExcluir.includes(
            valor.toUpperCase()
          )
        ) {
          const maxFilasABuscar = 5;
          let encontrado = false;

          for (
            let offset = 1;
            offset <= maxFilasABuscar;
            offset++
          ) {
            const nextRow = rows[i + offset];

            if (!nextRow) {
              break;
            }

            let siguienteValor = nextRow[col];

            if (!siguienteValor) {
              continue;
            }

            siguienteValor = siguienteValor
              .replace(/^"(.*)"$/, '$1')
              .trim();

            const siguienteValorLimpio =
              limpiarPrograma(siguienteValor);

            const esValido =
              siguienteValorLimpio &&
              !esDatoAuxiliar(siguienteValor) &&
              /[A-Za-zÁÉÍÓÚáéíóúÑñ]/.test(
                siguienteValorLimpio
              ) &&
              !siguienteValor.includes('(F)') &&
              !marcadoresAExcluir.includes(
                siguienteValor.toUpperCase()
              );

            if (esValido) {
              contentByDay[day].push({
                hora,
                programa: siguienteValorLimpio
              });

              i = i + offset;
              encontrado = true;
              break;
            }
          }

          if (!encontrado) {
            console.warn(
              `No se encontró contenido válido después del marcador "${valor}"`
            );
          }

          continue;
        }

        /*
         * Ignora duraciones, episodios, números y campos
         * adicionales como "30 Cap." o "52 Cap.".
         */
        if (esDatoAuxiliar(valor)) {
          continue;
        }

        if (tieneTexto) {
          const valorFinal = limpiarPrograma(valor);

          if (
            valorFinal &&
            !esDatoAuxiliar(valorFinal)
          ) {
            contentByDay[day].push({
              hora,
              programa: valorFinal
            });
          }
        }
      }
    }

    const tabsContainer =
      document.getElementById('tabs');

    const contentContainer =
      document.getElementById('content');

    Object.keys(contentByDay).forEach((day, idx) => {
      const tab = document.createElement('div');

      tab.className =
        'tab' + (idx === 0 ? ' active' : '');

      tab.innerText = day;

      tab.onclick = () => {
        document
          .querySelectorAll('.tab')
          .forEach(t => t.classList.remove('active'));

        document
          .querySelectorAll('.day-content')
          .forEach(c => c.classList.remove('active'));

        tab.classList.add('active');

        document
          .getElementById(`day-${day}`)
          .classList.add('active');
      };

      tabsContainer.appendChild(tab);

      const dayDiv = document.createElement('div');

      dayDiv.className =
        'day-content' +
        (idx === 0 ? ' active' : '');

      dayDiv.id = `day-${day}`;

      contentByDay[day].forEach(entry => {
        const prog = document.createElement('div');
        prog.className = 'program';

        const hora = document.createElement('div');
        hora.className = 'hora';
        hora.textContent = entry.hora;

        const info = document.createElement('div');
        info.textContent = entry.programa;

        prog.appendChild(hora);
        prog.appendChild(info);
        dayDiv.appendChild(prog);
      });

      contentContainer.appendChild(dayDiv);
    });
  });
</script>

</body>
</html>{"id":581,"date":"2025-07-27T17:17:59","date_gmt":"2025-07-27T17:17:59","guid":{"rendered":"https:\/\/popcorncentraltv.com\/tv-schedule\/"},"modified":"2025-07-31T06:27:23","modified_gmt":"2025-07-31T06:27:23","slug":"tv-schedule","status":"publish","type":"page","link":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/","title":{"rendered":"TV SCHEDULE"},"content":{"rendered":"<div class=\"wpb-content-wrapper\"><p>[vc_row el_id=&#8221;conteprogra&#8221;][vc_column][vc_column_text css=&#8221;&#8221;][\/vc_column_text][\/vc_column][\/vc_row]<\/p>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>[vc_row el_id=&#8221;conteprogra&#8221;][vc_column][vc_column_text css=&#8221;&#8221;][\/vc_column_text][\/vc_column][\/vc_row]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-581","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>TV SCHEDULE - Popcorn Central<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"TV SCHEDULE - Popcorn Central\" \/>\n<meta property=\"og:description\" content=\"[vc_row el_id=&#8221;conteprogra&#8221;][vc_column][vc_column_text css=&#8221;&#8221;][\/vc_column_text][\/vc_column][\/vc_row]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/\" \/>\n<meta property=\"og:site_name\" content=\"Popcorn Central\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/PopcornCentralTV\" \/>\n<meta property=\"article:modified_time\" content=\"2025-07-31T06:27:23+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/\",\"url\":\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/\",\"name\":\"TV SCHEDULE - Popcorn Central\",\"isPartOf\":{\"@id\":\"https:\/\/popcorncentraltv.com\/#website\"},\"datePublished\":\"2025-07-27T17:17:59+00:00\",\"dateModified\":\"2025-07-31T06:27:23+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Portada\",\"item\":\"https:\/\/popcorncentraltv.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"TV SCHEDULE\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/popcorncentraltv.com\/#website\",\"url\":\"https:\/\/popcorncentraltv.com\/\",\"name\":\"Popcorn Central\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/popcorncentraltv.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/popcorncentraltv.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/popcorncentraltv.com\/#organization\",\"name\":\"Popcorn Central\",\"url\":\"https:\/\/popcorncentraltv.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/popcorncentraltv.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/popcorncentraltv.com\/wp-content\/uploads\/2025\/08\/logow-1024x665.png\",\"contentUrl\":\"https:\/\/popcorncentraltv.com\/wp-content\/uploads\/2025\/08\/logow-1024x665.png\",\"width\":1024,\"height\":665,\"caption\":\"Popcorn Central\"},\"image\":{\"@id\":\"https:\/\/popcorncentraltv.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/PopcornCentralTV\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"TV SCHEDULE - Popcorn Central","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/","og_locale":"en_US","og_type":"article","og_title":"TV SCHEDULE - Popcorn Central","og_description":"[vc_row el_id=&#8221;conteprogra&#8221;][vc_column][vc_column_text css=&#8221;&#8221;][\/vc_column_text][\/vc_column][\/vc_row]","og_url":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/","og_site_name":"Popcorn Central","article_publisher":"https:\/\/www.facebook.com\/PopcornCentralTV","article_modified_time":"2025-07-31T06:27:23+00:00","twitter_card":"summary_large_image","schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/","url":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/","name":"TV SCHEDULE - Popcorn Central","isPartOf":{"@id":"https:\/\/popcorncentraltv.com\/#website"},"datePublished":"2025-07-27T17:17:59+00:00","dateModified":"2025-07-31T06:27:23+00:00","breadcrumb":{"@id":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/popcorncentraltv.com\/en\/tv-schedule\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/popcorncentraltv.com\/en\/tv-schedule\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Portada","item":"https:\/\/popcorncentraltv.com\/en\/"},{"@type":"ListItem","position":2,"name":"TV SCHEDULE"}]},{"@type":"WebSite","@id":"https:\/\/popcorncentraltv.com\/#website","url":"https:\/\/popcorncentraltv.com\/","name":"Popcorn Central","description":"","publisher":{"@id":"https:\/\/popcorncentraltv.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/popcorncentraltv.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/popcorncentraltv.com\/#organization","name":"Popcorn Central","url":"https:\/\/popcorncentraltv.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/popcorncentraltv.com\/#\/schema\/logo\/image\/","url":"https:\/\/popcorncentraltv.com\/wp-content\/uploads\/2025\/08\/logow-1024x665.png","contentUrl":"https:\/\/popcorncentraltv.com\/wp-content\/uploads\/2025\/08\/logow-1024x665.png","width":1024,"height":665,"caption":"Popcorn Central"},"image":{"@id":"https:\/\/popcorncentraltv.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/PopcornCentralTV"]}]}},"_links":{"self":[{"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/pages\/581","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/comments?post=581"}],"version-history":[{"count":1,"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/pages\/581\/revisions"}],"predecessor-version":[{"id":582,"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/pages\/581\/revisions\/582"}],"wp:attachment":[{"href":"https:\/\/popcorncentraltv.com\/en\/wp-json\/wp\/v2\/media?parent=581"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}