// ==========================================================
// ============ FUNÇÕES DE SEGURANÇA E UTILIDADE ============
// ==========================================================
function isAllowedImage(url) {
  try {
    if (!url) return false;
    // Permite caminhos relativos (ex: "imagem/foto.jpg") e URLs seguras
    if (!url.startsWith("http")) return true;
    const u = new URL(url);
    return (
      ["i.postimg.cc", "clinicabiavatti.com.br"].includes(u.hostname) &&
      u.protocol === "https:"
    );
  } catch {
    return false;
  }
}

function isAllowedVideo(url) {
  try {
    if (!url) return false;
    const u = new URL(url);
    return (
      (u.hostname.endsWith("youtube.com") ||
        u.hostname === "www.youtube-nocookie.com" ||
        u.hostname === "drive.google.com") &&
      u.protocol === "https:"
    );
  } catch {
    return false;
  }
}

// Função ksort para JavaScript (necessária para ordenar o pódio)
function ksort(obj) {
  let keys = Object.keys(obj).sort(),
    sortedObj = {};
  for (let i in keys) {
    sortedObj[keys[i]] = obj[keys[i]];
  }
  return sortedObj;
}

// ==========================================================
// ============ LÓGICA PRINCIPAL DE CARREGAMENTO ============
// ==========================================================
document.addEventListener("DOMContentLoaded", () => {
  async function loadIntranetData() {
    try {
      const response = await fetch("api.php");
      if (!response.ok) throw new Error("Falha ao carregar dados da API.");
      const data = await response.json();

      populateLinks("#quick-access-dropdown", data.quickAccessLinks || []);
      populateLinks("#useful-links-dropdown", data.usefulLinks || []);
      populateNews(data.news || []);
      populateBirthdays(data.birthdayFlyerImage || "");
      populateVideos(data.videos || []);
      populateRankingsCarousel(data.rankings || {});
    } catch (error) {
      console.error("Erro ao carregar dados da intranet:", error);
      const mainContainer = document.querySelector(".main-container");
      if (mainContainer) {
        mainContainer.innerHTML =
          '<p style="text-align: center; color: red; font-size: 1.2rem;">Não foi possível carregar o conteúdo da intranet. Tente novamente mais tarde.</p>';
      }
    }
  }
  loadIntranetData();
});

// ==========================================================
// ========= FUNÇÕES PARA POPULAR O CONTEÚDO DA PÁGINA ======
// ==========================================================
function populateImageCarousel(slides) {
  const track = document.querySelector(
    "#image-carousel-section .carousel-track"
  );
  if (!track) return;
  track.innerHTML = "";
  if (slides && slides.length > 0) {
    slides.forEach((slide) => {
      const item = document.createElement("div");
      item.className = "carousel-item";
      if (isAllowedImage(slide.image)) {
        item.style.backgroundImage = `url('${slide.image}')`;
      }
      const caption = document.createElement("div");
      caption.className = "carousel-caption";
      const title = document.createElement("h3");
      title.textContent = slide.title;
      const text = document.createElement("p");
      text.textContent = slide.text;
      caption.appendChild(title);
      caption.appendChild(text);
      item.appendChild(caption);
      track.appendChild(item);
    });
  }
  setupGenericCarousel(
    "image-carousel-section",
    ".prev-btn",
    ".next-btn",
    true
  );
}

function populateLinks(containerId, links) {
  const container = document.querySelector(containerId);
  if (!container) return;
  container.innerHTML = "";
  if (links && links.length > 0) {
    links.forEach((link) => {
      const a = document.createElement("a");
      a.href = link.url;
      a.target = "_blank";
      a.rel = "noopener noreferrer";
      a.textContent = link.text;
      container.appendChild(a);
    });
  } else {
    const p = document.createElement("p");
    p.textContent = "Nenhum link cadastrado.";
    p.style.textAlign = "center";
    p.style.color = "#777";
    p.style.padding = "10px";
    container.appendChild(p);
  }
}
function populateNews(newsItems) {
  const container = document.querySelector("#news-container");
  if (!container) return;
  container.innerHTML = "";
  if (newsItems) {
    newsItems.forEach((item) => {
      const article = document.createElement("article");
      const title = document.createElement("h4");
      title.textContent = item.title;
      const content = document.createElement("p");
      content.innerHTML = item.content;
      let imgElement = null;
      if (item.image && isAllowedImage(item.image)) {
        imgElement = document.createElement("img");
        imgElement.src = item.image;
        imgElement.alt = item.title;
        imgElement.className = "news-image";
        const width = item.image_width || 300;
        const height = item.image_height || 250;
        const layout = item.layout || "image-left";
        if (layout === "image-left" || layout === "image-right") {
          imgElement.style.width = `${width}px`;
          imgElement.style.height = `${height}px`;
        } else if (layout.includes("full")) {
          imgElement.style.height = `${height}px`;
        }
      }
      const layout = item.layout || "image-left";
      article.className = `news-item news-layout-${layout}`;
      if (imgElement) {
        if (layout === "image-full-bottom") {
          article.appendChild(title);
          article.appendChild(content);
          article.appendChild(imgElement);
        } else {
          article.appendChild(imgElement);
          article.appendChild(title);
          article.appendChild(content);
        }
      } else {
        article.appendChild(title);
        article.appendChild(content);
      }
      container.appendChild(article);
    });
  }
}

function populateBirthdays(imageUrl) {
  const container = document.querySelector("#birthdays-container");
  const section = document.getElementById("birthdays-section");
  if (!container || !section) return;
  container.innerHTML = "";
  if (imageUrl && isAllowedImage(imageUrl)) {
    const wrapper = document.createElement("div");
    wrapper.className = "birthday-image-wrapper";
    const img = document.createElement("img");
    img.src = imageUrl;
    img.alt = "Aniversariantes do Mês";
    wrapper.appendChild(img);
    container.appendChild(wrapper);
    section.style.display = "flex";
  } else {
    section.style.display = "none";
  }
}

function populateVideos(videos) {
  const track = document.querySelector(
    "#video-carousel-section .carousel-track"
  );
  if (!track) return;
  track.innerHTML = "";
  if (videos && videos.length > 0) {
    videos.forEach((video) => {
      if (!isAllowedVideo(video.url)) return;
      const item = document.createElement("div");
      item.className = "carousel-item video-item";
      item.dataset.title = video.title;
      item.dataset.url = video.url;

      if (video.preview && isAllowedImage(video.preview)) {
        item.innerHTML = `<div class="video-preview-container"><img src="${video.preview}" alt="${video.title}" class="video-preview-img"><div class="play-button-overlay"><svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 24 24" fill="rgba(255,255,255,0.9)"><path d="M8 5v14l11-7z"/><path d="M0 0h24v24H0z" fill="none"/></svg></div></div>`;
      } else {
        item.innerHTML = `<iframe src="${video.url}" allowfullscreen title="${video.title}"></iframe>`;
      }
      track.appendChild(item);
    });
    const carouselControls = setupGenericCarousel(
      "video-carousel-section",
      ".prev-video-btn",
      ".next-video-btn",
      true
    );
    track.querySelectorAll(".video-preview-container").forEach((container) => {
      container.addEventListener(
        "click",
        function () {
          if (
            carouselControls &&
            typeof carouselControls.stopAutoPlay === "function"
          ) {
            carouselControls.stopAutoPlay();
          }
          const parentItem = this.closest(".video-item");
          let videoUrl = parentItem.dataset.url;
          const videoTitle = parentItem.dataset.title;
          if (
            videoUrl.includes("youtube.com") ||
            videoUrl.includes("youtu.be")
          ) {
            videoUrl += videoUrl.includes("?") ? "&autoplay=1" : "?autoplay=1";
          }
          parentItem.innerHTML = `<iframe src="${videoUrl}" allow="autoplay; fullscreen" title="${videoTitle}"></iframe>`;
        },
        { once: true }
      );
    });
  } else {
    const videoSection = document.getElementById("video-carousel-section");
    if (videoSection) videoSection.style.display = "none";
  }
}

function populateRankingsCarousel(rankings) {
  const section = document.getElementById("rankings-section");
  if (!section) return;
  const track = section.querySelector(".carousel-track");
  if (!track) return;
  const rankingsComVencedores = Object.values(rankings).filter(
    (r) => r.vencedores && r.vencedores.length > 0
  );
  if (rankingsComVencedores.length === 0) {
    section.innerHTML = `<h2><i class="fas fa-star" style="color: #ffd700;"></i> Quadro de Honra</h2><p style="text-align: center; color: #777;">O Quadro de Honra do mês ainda não foi divulgado.</p>`;
    return;
  }
  rankingsComVencedores.forEach((ranking) => {
    const carouselItem = document.createElement("div");
    carouselItem.className = "carousel-item";
    carouselItem.dataset.title = ranking.titulo;
    let podiumHTML = '<div class="podium">';
    const vencedores = ranking.vencedores;
    let ordemPodio = [];
    vencedores.forEach((v) => {
      if (v.posicao == 2) ordemPodio[0] = v;
      if (v.posicao == 1) ordemPodio[1] = v;
      if (v.posicao == 3) ordemPodio[2] = v;
    });
    ordemPodio = ksort(ordemPodio);
    Object.values(ordemPodio).forEach((vencedor) => {
      if (!vencedor) return;
      const fotoHTML = vencedor.foto
        ? `<img src="${vencedor.foto}" alt="${vencedor.nome}">`
        : `<div class="placeholder-icon"><i class="fas ${
            vencedor.tipo === "clinica" ? "fa-building" : "fa-user"
          }"></i></div>`;
      const scoreHTML = vencedor.score
        ? `<p class="podium-score">${vencedor.score}</p>`
        : "";
      podiumHTML += `<div class="podium-card position-${vencedor.posicao}"><span class="podium-position">${vencedor.posicao}</span><div class="podium-image">${fotoHTML}</div><h3 class="podium-name">${vencedor.nome}</h3>${scoreHTML}</div>`;
    });
    podiumHTML += "</div>";
    carouselItem.innerHTML = podiumHTML;
    track.appendChild(carouselItem);
  });
  setupGenericCarousel(
    "rankings-section",
    ".prev-ranking-btn",
    ".next-ranking-btn",
    true
  );
setTimeout(() => { // Espera um pouquinho para garantir que o HTML existe
        document.querySelectorAll('.podium-card.position-1').forEach(card => {
            card.addEventListener('mouseenter', () => {
                // Configuração da explosão de confetes
                confetti({
                    particleCount: 50,
                    spread: 60,
                    origin: { y: 0.7 },
                    colors: ['#FFD700', '#FDB931', '#FFFFFF'], // Tons dourados
                    disableForReducedMotion: true
                });
            });
        });
    }, 1000);
} 
function setupGenericCarousel(
  sectionId,
  prevBtnClass,
  nextBtnClass,
  hasAutoplay
) {
  const section = document.getElementById(sectionId);
  if (!section) return;

  const track = section.querySelector(".carousel-track");
  const items = section.querySelectorAll(".carousel-item");
  const prevBtn = section.querySelector(prevBtnClass);
  const nextBtn = section.querySelector(nextBtnClass);
  const indicatorsContainer = section.querySelector(".carousel-indicators");

  // ===== A CORREÇÃO ESTÁ AQUI =====
  // As variáveis de título agora são buscadas DENTRO da seção atual
  const videoTitleDisplay = section.querySelector("#video-title-display");
  const rankingTitleDisplay = section.querySelector(".ranking-title-display");
  // ================================

  if (!items || items.length === 0) {
    if (section) section.style.display = "none";
    return;
  }
  if (items.length <= 1) {
    if (prevBtn) prevBtn.style.display = "none";
    if (nextBtn) nextBtn.style.display = "none";
    if (indicatorsContainer) indicatorsContainer.style.display = "none";
  } else {
    if (prevBtn) prevBtn.style.display = "flex";
    if (nextBtn) nextBtn.style.display = "flex";
    if (indicatorsContainer) indicatorsContainer.style.display = "flex";
  }

  let currentIndex = 0;
  let interval;
  let indicators = [];

  function createIndicators() {
    if (!indicatorsContainer) return;
    indicatorsContainer.innerHTML = "";
    indicators = [];
    items.forEach((_, index) => {
      const button = document.createElement("button");
      button.addEventListener("click", () => {
        currentIndex = index;
        update();
        if (hasAutoplay) startAutoplay();
      });
      indicatorsContainer.appendChild(button);
      indicators.push(button);
    });
  }

  function update() {
    if (sectionId === "video-carousel-section") {
      items.forEach((item, index) => {
        if (index !== currentIndex) {
          const iframe = item.querySelector("iframe");
          if (iframe) {
            iframe.src = iframe.src;
          }
        }
      });
    }
    if (items.length > 0) {
      const width = items[0].getBoundingClientRect().width;
      track.style.transform = `translateX(-${width * currentIndex}px)`;
      if (indicators.length > 0) {
        indicators.forEach((ind, i) =>
          ind.classList.toggle("active", i === currentIndex)
        );
      }
      if (
        videoTitleDisplay &&
        items[currentIndex] &&
        items[currentIndex].dataset.title
      ) {
        videoTitleDisplay.textContent = items[currentIndex].dataset.title;
      }
      if (
        rankingTitleDisplay &&
        items[currentIndex] &&
        items[currentIndex].dataset.title
      ) {
        rankingTitleDisplay.innerHTML = `<i class="fas fa-sun" style="color: #FFD700; margin-right: 5px; animation: spinSlow 10s linear infinite;"></i> ${items[currentIndex].dataset.title}`;
      }
    }
  }

  const showNext = () => {
    currentIndex = (currentIndex + 1) % items.length;
    update();
  };
  const showPrev = () => {
    currentIndex = (currentIndex - 1 + items.length) % items.length;
    update();
  };

  if (nextBtn) nextBtn.addEventListener("click", showNext);
  if (prevBtn) prevBtn.addEventListener("click", showPrev);
  window.addEventListener("resize", update);
  createIndicators();
  update();
  const stopAutoPlay = () => clearInterval(interval);
  if (hasAutoplay) {
    const startAutoplay = () => {
      stopAutoPlay();
      interval = setInterval(showNext, 5000);
    };
    section.addEventListener("mouseenter", stopAutoPlay);
    section.addEventListener("mouseleave", startAutoplay);
    startAutoplay();
  }
  return { stopAutoPlay };
}

(function () {
  const konamiCode = [
    "ArrowUp",
    "ArrowUp",
    "ArrowDown",
    "ArrowDown",
    "ArrowLeft",
    "ArrowRight",
    "ArrowLeft",
    "ArrowRight",
    "b",
    "a",
  ];
  let konamiIndex = 0;
  document.addEventListener("keydown", function (e) {
    if (e.key === konamiCode[konamiIndex]) {
      konamiIndex++;
      if (konamiIndex === konamiCode.length) {
        triggerEasterEgg();
        konamiIndex = 0;
      }
    } else {
      konamiIndex = 0;
    }
  });
  function triggerEasterEgg() {
    console.log("Modo Biavatti Super Liso ativado!");
    const logo = document.querySelector(".hero-logo");
    if (logo) {
      logo.style.transition = "transform 0.5s ease-in-out";
      logo.style.transform = "rotate(360deg) scale(1.2)";
      setTimeout(() => {
        logo.style.transform = "rotate(0deg) scale(1)";
      }, 1000);
    }
    if (typeof confetti === "function") {
      const duration = 3 * 1000;
      const animationEnd = Date.now() + duration;
      const colors = ["#002147", "#059cee", "#ffffff"];
      const frame = () => {
        confetti({
          particleCount: 3,
          angle: 60,
          spread: 55,
          origin: { x: 0 },
          colors: colors,
        });
        confetti({
          particleCount: 3,
          angle: 120,
          spread: 55,
          origin: { x: 1 },
          colors: colors,
        });
        if (Date.now() < animationEnd) {
          requestAnimationFrame(frame);
        }
      };
      frame();
    }
    const messageDiv = document.createElement("div");
    messageDiv.textContent = "IgoR CarvalhO esteve aqui!";
    messageDiv.style.cssText =
      "position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background-color: #002147; color: white; padding: 10px 20px; border-radius: 50px; z-index: 10000; opacity: 0; transition: opacity 0.5s;";
    document.body.appendChild(messageDiv);
    setTimeout(() => {
      messageDiv.style.opacity = "1";
    }, 100);
    setTimeout(() => {
      messageDiv.style.opacity = "0";
      setTimeout(() => {
        messageDiv.remove();
      }, 500);
    }, 3000);
  }
})();

// ==========================================================
// ========== WIDGET DE MOTIVAÇÃO E DATA ====================
// ==========================================================
function initMotivationWidget() {
  // 1. Atualizar Data (Simples e eficiente)
  const dateElement = document.getElementById("current-date");
  if (dateElement) {
    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    const dataFormatada = new Date().toLocaleDateString('pt-BR', options);
    // Deixa primeira letra maiúscula (ex: "Quarta-feira...")
    dateElement.textContent = dataFormatada.charAt(0).toUpperCase() + dataFormatada.slice(1);
  }

  // 2. Sistema de Frases Biavatti
  const phrases = [
    "Você faz a diferença na vida dos nossos pacientes.",
    "Clínica Biavatti: Excelência construída por você.",
    "Obrigado por sua dedicação e carinho diário.",
    "O sorriso do paciente começa no seu trabalho.",
    "Cada detalhe importa. Você é fundamental.",
    "Somos referência porque temos você no time.",
    "Seu talento move a Clínica Biavatti.",
    "Transformamos vidas, começando pela sua.",
    "Juntos somos mais fortes e brilhantes.",
    "A qualidade do seu trabalho é o nosso maior orgulho."
  ];

  const phraseElement = document.getElementById("daily-phrase");
  
  if (phraseElement) {
    let index = 0;

    // Função para trocar a frase com efeito suave
    function changePhrase() {
      // 1. Apaga suavemente
      phraseElement.classList.add('fade-text');
      phraseElement.classList.remove('show-text');

      setTimeout(() => {
        // 2. Troca o texto enquanto está invisível
        index = (index + 1) % phrases.length;
        phraseElement.textContent = phrases[index];
        
        // 3. Aparece suavemente
        phraseElement.classList.remove('fade-text');
        phraseElement.classList.add('show-text');
      }, 1000); // Espera 1 segundo (tempo do CSS) para trocar
    }

    // Inicializa a primeira frase aleatória
    index = Math.floor(Math.random() * phrases.length);
    phraseElement.textContent = phrases[index];
    phraseElement.classList.add('show-text');

    // Troca a frase a cada 6 segundos
    setInterval(changePhrase, 6000);
  }
}

document.addEventListener("DOMContentLoaded", () => {
  // ATENÇÃO: Se ainda tiver chamada para initWeatherWidget, substitua por esta:
  initMotivationWidget();
});