document.addEventListener('DOMContentLoaded', () => {

  /* ── Financial Ticker (Live Fetch) ── */
  let tickerData = [
    { id: 'brent', label: 'BRENT', price: 85.34, change: 0.45 },
    { id: 'wti', label: 'WTI', price: 81.20, change: -0.12 },
    { id: 'gas', label: 'NATGAS', price: 1.82, change: -0.04 },
    { id: 'trm', label: 'TRM COP', price: 3855.50, change: 0.00 } // Will be overwritten by API
  ];

  const tickerContainer = document.getElementById('financial-ticker');
  
  if (tickerContainer) {
    function renderTicker() {
      const itemsHtml = tickerData.map(item => {
        const sign = item.change > 0 ? '+' : '';
        const trendClass = item.change > 0 ? 'up' : (item.change < 0 ? 'down' : '');
        const arrow = item.change > 0 ? '▲' : (item.change < 0 ? '▼' : '▬');
        
        const prefix = item.label.includes('COP') ? '$' : (item.label === 'NATGAS' ? '$' : '$');

        return `
          <div class="ticker-item">
            <span style="opacity:0.8">${item.label}:</span>
            <span>${prefix}${item.price.toFixed(2)}</span>
            <span class="ticker-val ${trendClass}">${arrow} ${sign}${item.change.toFixed(2)}</span>
          </div>
        `;
      }).join('');

      tickerContainer.innerHTML = itemsHtml + itemsHtml;
    }

    async function loadLiveData() {
      try {
        // 1. Fetch Real TRM from Datos.gov.co (Socrata Public API)
        const trmResponse = await fetch('https://www.datos.gov.co/resource/32sa-8pi3.json?$limit=2&$order=vigenciadesde DESC');
        const trmDataArray = await trmResponse.json();
        
        if (trmDataArray && trmDataArray.length >= 2) {
          const latestVal = parseFloat(trmDataArray[0].valor);
          const prevVal = parseFloat(trmDataArray[1].valor);
          const variation = latestVal - prevVal;
          
          const trmObj = tickerData.find(t => t.id === 'trm');
          trmObj.price = latestVal;
          trmObj.change = variation;
        }

        /* 
         * 2. Oil & Gas APIs (Brent, WTI) 
         * To fetch these in a real production environment, integrate your AlphaVantage/EIA API key here:
         * const oilRes = await fetch('https://commodities-api.com/api/latest?access_key=YOUR_KEY&base=USD&symbols=BRENT,WTI,NG');
         * ...
         */
      } catch (err) {
        console.error('Error fetching ticker data:', err);
      }
      
      // Initial render after fetch
      renderTicker();
    }

    // Load API data on load
    loadLiveData();

    // Fluctuations for Oil/Gas UI mockup (ignoring the real TRM to keep it stable)
    setInterval(() => {
      tickerData.forEach(item => {
        if (item.id !== 'trm') {
          const variance = (Math.random() - 0.5) * (item.price * 0.002);
          item.price += variance;
          item.change += variance;
        }
      });
      renderTicker();
    }, 4500);
  }

  /* ── Hero Slider ── */
  const heroSlides = [
    {
      tag: 'ANÁLISIS TÉCNICO',
      date: 'EDICIÓN: MARZO 2026',
      title: 'Informe de Taladros y Producción',
      desc: 'Consulte el histórico y estado actual de los equipos de perforación operando en Colombia, junto con las métricas clave de crudo y gas a nivel nacional.',
      linkText: 'Ver boletín →',
      icon: '',
      bg: 'url(images/banners/02-Banner-Informe-Taladros-2603.jpg) center/contain no-repeat #ffffff'
    },
    {
      tag: 'GESTIÓN SECTORIAL',
      date: 'REPORTE 2025',
      title: 'Sostenibilidad e Impacto',
      desc: 'Explore las acciones de la industria de bienes y servicios para construir un entorno energéticamente responsable y alineado con el desarrollo de las regiones.',
      linkText: 'Ver reporte →',
      icon: '',
      bg: 'url(images/banners/Banner-Reporte-Sostenibilidad-2025.jpg) center/contain no-repeat #ffffff'
    },
    {
      tag: 'SPOTLIGHT AFILIADOS',
      date: 'EDICIÓN ESPECIAL',
      title: 'Soluciones con Resiter',
      desc: 'Destacamos las trayectorias de éxito de nuestras empresas afiliadas y los servicios hiper-especializados que fortalecen la cadena de valor colombiana.',
      linkText: 'Ver afiliado →',
      icon: '',
      bg: 'url(images/banners/02-Banner-SpotLight-77-Resiter.jpg) center/contain no-repeat #ffffff'
    }
  ];

  let current = 0;
  let interval;
  const dots = document.querySelectorAll('.hero-dot');
  const heroImg = document.getElementById('hero-img');
  const heroTag = document.getElementById('hero-tag');
  const heroDate = document.getElementById('hero-date');
  const heroTitle = document.getElementById('hero-title');
  const heroDesc = document.getElementById('hero-desc');
  const heroLink = document.getElementById('hero-link');

  function goTo(n) {
    if (!heroImg) return;
    current = (n + heroSlides.length) % heroSlides.length;
    const s = heroSlides[current];
    heroImg.style.background = s.bg;
    heroImg.textContent = s.icon;
    heroTag.textContent = s.tag;
    heroDate.textContent = s.date;
    heroTitle.textContent = s.title;
    heroDesc.textContent = s.desc;
    if(heroLink) heroLink.textContent = s.linkText;
    dots.forEach((d, i) => d.classList.toggle('active', i === current));
  }

  function startInterval() { interval = setInterval(() => goTo(current + 1), 5500); }

  if (heroImg) {
    dots.forEach((d, i) => d.addEventListener('click', () => { clearInterval(interval); goTo(i); startInterval(); }));
    document.getElementById('hero-prev')?.addEventListener('click', () => { clearInterval(interval); goTo(current - 1); startInterval(); });
    document.getElementById('hero-next')?.addEventListener('click', () => { clearInterval(interval); goTo(current + 1); startInterval(); });
    goTo(0);
    startInterval();
  }

  /* ── Header Ghost Spacer & Mega Menu positioning ── */
  const header = document.getElementById('site-header');
  const headerGhost = document.createElement('div');
  headerGhost.style.height = header.offsetHeight + 'px';
  header.parentNode.insertBefore(headerGhost, header.nextSibling);

  function positionMegaMenus() {
    const bottom = header.getBoundingClientRect().bottom;
    document.querySelectorAll('.mega-menu').forEach(m => {
      m.style.top = bottom + 'px';
    });
  }
  window.addEventListener('resize', positionMegaMenus);
  positionMegaMenus();

  /* ── Mobile hamburger ── */
  const hamburger = document.getElementById('hamburger');
  const mobileNav = document.getElementById('mobile-nav');
  const mobileClose = document.getElementById('mobile-close');
  const mobileOverlay = document.getElementById('mobile-overlay');

  function openMobileMenu() {
    mobileNav.classList.add('open');
    mobileOverlay.classList.add('open');
    document.body.style.overflow = 'hidden';
    hamburger?.classList.add('open');
  }

  function closeMobileMenu() {
    mobileNav.classList.remove('open');
    mobileOverlay.classList.remove('open');
    document.body.style.overflow = '';
    hamburger?.classList.remove('open');
  }

  hamburger?.addEventListener('click', openMobileMenu);
  mobileClose?.addEventListener('click', closeMobileMenu);
  mobileOverlay?.addEventListener('click', closeMobileMenu);

  document.querySelectorAll('.mobile-nav-link').forEach(link => {
    link.addEventListener('click', () => {
      const parent = link.parentElement;
      if (!parent.querySelector('.mobile-sub')) return;
      const wasOpen = parent.classList.contains('open');
      document.querySelectorAll('.mobile-nav-item').forEach(i => i.classList.remove('open'));
      if (!wasOpen) parent.classList.add('open');
    });
  });


  /* ── Scroll Reveal ── */
  const observer = new IntersectionObserver(entries => {
    entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('visible'); observer.unobserve(e.target); }});
  }, { threshold: 0.1 });
  document.querySelectorAll('.reveal, .reveal-scale, .reveal-left, .reveal-right').forEach(el => observer.observe(el));

  /* ── Stat counters ── */
  const cObserver = new IntersectionObserver(entries => {
    entries.forEach(e => {
      if (!e.isIntersecting) return;
      const el = e.target;
      const target = parseInt(el.dataset.target, 10);
      const suffix = el.dataset.suffix || '';
      const dur = 1600;
      const start = performance.now();
      const step = ts => {
        const p = Math.min((ts - start) / dur, 1);
        el.textContent = Math.floor((1 - Math.pow(1 - p, 3)) * target) + suffix;
        if (p < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
      cObserver.unobserve(el);
    });
  }, { threshold: 0.5 });
  document.querySelectorAll('.stat-num[data-target]').forEach(el => cObserver.observe(el));

  /* ── Newsletter ── */
  document.getElementById('newsletter-form')?.addEventListener('submit', e => {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    btn.textContent = '✓ Suscrito';
    btn.style.background = '#1a6b3c';
    e.target.querySelector('input').value = '';
    setTimeout(() => { btn.textContent = 'Suscribirse'; btn.style.background = ''; }, 3000);
  });

  /* ── Search form ── */
  document.getElementById('search-form')?.addEventListener('submit', e => e.preventDefault());

  /* ── Sticky shadow and shrink ── */
  window.addEventListener('scroll', () => {
    if (window.scrollY > 150) header.classList.add('scrolled');
    else header.classList.remove('scrolled');
    positionMegaMenus();
  });
  // Ensure mega menus stay attached during the smooth height transition
  header.addEventListener('transitionend', positionMegaMenus);

  /* ── Video Modal Logic ── */
  const btnHistoria = document.getElementById('btn-historia');
  const videoModal = document.getElementById('videoModal');
  if (btnHistoria && videoModal) {
    const overlay = videoModal.querySelector('.video-modal-overlay');
    const closeBtn = videoModal.querySelector('.video-modal-close');
    const container = videoModal.querySelector('.video-container');
    const iframeSrc = 'https://www.youtube-nocookie.com/embed/jcbs-gwg68g?autoplay=1&origin=https://campetrol.org';

    function openModal(e) {
      e.preventDefault();
      container.innerHTML = `<iframe src="${iframeSrc}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`;
      videoModal.classList.add('active');
    }

    function closeModal() {
      videoModal.classList.remove('active');
      setTimeout(() => { container.innerHTML = ''; }, 300); // Clear iframe to stop audio
    }

    if (btnHistoria) btnHistoria.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);
    overlay.addEventListener('click', closeModal);

    // Support for the new SOMOS CAMPETROL thumbnail trigger
    document.querySelectorAll('.video-play-trigger').forEach(trigger => {
        trigger.addEventListener('click', openModal);
    });

  }

  /* ── Like Button Logic ── */
  document.querySelectorAll('.like-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const isLiked = btn.classList.contains('liked');
      const counter = btn.querySelector('.like-count');
      let count = parseInt(counter.textContent.replace(/,/g, ''), 10);

      if (isLiked) {
        btn.classList.remove('liked');
        count--;
      } else {
        btn.classList.add('liked');
        count++;
      }
      counter.textContent = count.toLocaleString('en-US'); // Will format cleanly as 1,105
    });
  });

  /* ── Carousel Logic ── */
  const pressTrack = document.getElementById('press-track');
  const pressPrevBtn = document.getElementById('press-prev');
  const pressNextBtn = document.getElementById('press-next');

  if (pressTrack && pressPrevBtn && pressNextBtn) {
    const getScrollAmount = () => pressTrack.querySelector('.card').offsetWidth + 24; // Card width + gap (1.5rem ~ 24px)
    
    pressPrevBtn.addEventListener('click', () => {
      pressTrack.scrollBy({ left: -getScrollAmount(), behavior: 'smooth' });
    });
    
    pressNextBtn.addEventListener('click', () => {
      pressTrack.scrollBy({ left: getScrollAmount(), behavior: 'smooth' });
    });
  }

  /* ── Social Share Buttons ── */
  document.querySelectorAll('.share-btn').forEach(btn => {
    btn.addEventListener('click', e => {
      e.preventDefault();

      // Get the title from the closest card
      const card = btn.closest('.card, .press-card, [class*="card"]');
      const titleEl = card ? card.querySelector('h3 a, h3') : null;
      const title = titleEl ? titleEl.textContent.trim() : document.title;

      // Use canonical URL or current page
      const canonicalEl = document.querySelector('link[rel="canonical"]');
      const pageUrl = canonicalEl ? canonicalEl.href : window.location.href;

      const encodedUrl   = encodeURIComponent(pageUrl);
      const encodedTitle = encodeURIComponent(title);

      let shareUrl = '';
      if (btn.classList.contains('facebook')) {
        shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
      } else if (btn.classList.contains('twitter')) {
        shareUrl = `https://twitter.com/intent/tweet?text=${encodedTitle}&url=${encodedUrl}`;
      } else if (btn.classList.contains('linkedin')) {
        shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}&title=${encodedTitle}`;
      }

      if (shareUrl) {
        window.open(shareUrl, '_blank', 'width=600,height=480,menubar=no,toolbar=no,resizable=yes,scrollbars=yes');
      }
    });
  });

});
