/* --- Popup modul --- */

/* Překryvná vrstva přes celou stránku */
#custom-popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7); /* Poloprůhledné černé pozadí */
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
}

/* Styl pro zobrazení popupu */
#custom-popup-overlay.visible {
  opacity: 1;
  visibility: visible;
}

/* Samotný kontejner popupu */
#custom-popup-container {
  position: relative;
  background-color: #ffffff;
  padding: 40px 25px 25px 25px;
  border-radius: 5px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

/* Křížek pro zavření vpravo nahoře */
#custom-popup-close {
  position: absolute;
  top: 10px;
  right: 15px;
  font-size: 28px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
  line-height: 1;
}

#custom-popup-close:hover {
  color: #000;
}

/* Obsah načtený ze stránky */
#custom-popup-content .p-detail-inner {
  padding: 0; /* Odstraní výchozí padding Shoptetu */
}

/* Odkaz pro trvalé zavření */
#custom-popup-no-show {
  display: block;
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #888;
  cursor: pointer;
  text-decoration: underline;
}

#custom-popup-no-show:hover {
  color: #333;
}
document.addEventListener('DOMContentLoaded', () => {

  // --- Nastavení ---
  const popupDelay = 30000; // Čas v milisekundách (10s)
  const contentPageUrl = '/popup/'; // URL adresa stránky s obsahem
  const storageKey = 'customPopupClosedTemporarily'; // Klíč pro uložení v localStorage
  const storageTTL = 30 * 60 * 1000; // Platnost v milisekundách (30 minut)

  // 1. Bezpečně zkontrolujeme, zda existuje platný záznam v localStorage
  try {
    const itemStr = localStorage.getItem(storageKey);
    if (itemStr) {
      const item = JSON.parse(itemStr);
      const now = new Date();
      if (now.getTime() < item.expiry) {
        console.log('Popup je dočasně deaktivován.');
        return; // Záznam stále platí, končíme.
      } else {
        localStorage.removeItem(storageKey);
        console.log('Platnost deaktivace popupu vypršela, záznam smazán.');
      }
    }
  } catch (e) {
    console.error('Nalezen neplatný záznam v localStorage, mažu ho.', e);
    localStorage.removeItem(storageKey);
  }

  // 2. Nastavíme časovač pro zobrazení popupu
  setTimeout(() => {
    fetchContentAndShowPopup();
  }, popupDelay);

  // 3. Funkce pro načtení obsahu a zobrazení popupu
  async function fetchContentAndShowPopup() {
    try {
      const response = await fetch(contentPageUrl);

      if (!response.ok) {
        console.error(`Popup se nezobrazí: Stránka ${contentPageUrl} neexistuje nebo je neveřejná. (Status: ${response.status})`);
        return;
      }

      const pageHtml = await response.text();
      const parser = new DOMParser();
      const doc = parser.parseFromString(pageHtml, 'text/html');

      const contentElement = doc.querySelector('#content');

      // Nejdříve zkontrolujeme, zda byl element #content vůbec nalezen
      if (!contentElement) {
        console.error('Popup se nezobrazí: Na cílové stránce nebyl nalezen prvek #content.');
        return;
      }

      // Pokud #content existuje, odstraníme z něj <header> (pokud tam je)
      const headerToRemove = contentElement.querySelector('header');
      if (headerToRemove) {
        headerToRemove.remove();
      }

      // ✨ NOVĚ: Zkontrolujeme, zda po odstranění headeru zbyl nějaký text
      if (contentElement.textContent.trim() === '') {
        console.log('Popup se nezobrazí: Prvek #content po odstranění záhlaví neobsahuje žádný text.');
        return; // Ukončíme funkci, popup se nevytvoří
      }

      // 4. Vytvoření HTML struktury popupu
      const popupOverlay = document.createElement('div');
      popupOverlay.id = 'custom-popup-overlay';

      const popupContainer = document.createElement('div');
      popupContainer.id = 'custom-popup-container';

      const closeButton = document.createElement('span');
      closeButton.id = 'custom-popup-close';
      closeButton.innerHTML = '&times;';
      closeButton.onclick = () => popupOverlay.remove();

      const contentDiv = document.createElement('div');
      contentDiv.id = 'custom-popup-content';
      // Použijeme upravený obsah (bez headeru)
      contentDiv.innerHTML = contentElement.innerHTML;

      const noShowLink = document.createElement('a');
      noShowLink.id = 'custom-popup-no-show';
      noShowLink.textContent = 'Zavřít a příště nezobrazovat';

      noShowLink.onclick = () => {
        const now = new Date();
        const item = {
          value: true,
          expiry: now.getTime() + storageTTL,
        };
        localStorage.setItem(storageKey, JSON.stringify(item));
        popupOverlay.remove();
      };

      popupContainer.append(closeButton, contentDiv, noShowLink);
      popupOverlay.appendChild(popupContainer);
      document.body.appendChild(popupOverlay);

      console.log('Popup úspěšně vytvořen a zobrazen.');
      setTimeout(() => popupOverlay.classList.add('visible'), 10);

    } catch (error) {
      console.error('Došlo k chybě při vytváření popupu:', error);
    }
  }
});
