// ─────────────────────────────────────────────
// main.js — Come2Canada.Life
// Cloudflare-safe: reiner JS, kein PHP
// Holt Inhalte + News aus API auf christianwehrli.ca
// ─────────────────────────────────────────────

const C2C_API = 'https://christianwehrli.ca/c2c/api/';

(function () {

  // ── Nav scroll ───────────────────────────
  const nav = document.getElementById('mainNav');
  if (nav) {
    window.addEventListener('scroll', () => {
      nav.classList.toggle('inked', window.scrollY > 70);
    }, { passive: true });
  }

  // ── Ticker pausieren bei Hover ───────────
  const track = document.getElementById('tickerTrack');
  if (track) {
    track.addEventListener('mouseenter', () => track.style.animationPlayState = 'paused');
    track.addEventListener('mouseleave', () => track.style.animationPlayState = 'running');
  }

  // ── Smooth scroll ────────────────────────
  document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', e => {
      const el = document.getElementById(a.getAttribute('href').slice(1));
      if (el) { e.preventDefault(); el.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
    });
  });

  // ── Helpers ──────────────────────────────
  function set(id, val) {
    if (val == null || val === '') return;
    const el = document.getElementById(id);
    if (el) el.textContent = val;
  }
  function setHTML(id, val) {
    if (val == null) return;
    const el = document.getElementById(id);
    if (el) el.innerHTML = val;
  }
  function esc(s) {
    return String(s)
      .replace(/&/g,'&amp;').replace(/</g,'&lt;')
      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  // ── Inhalte aus Content-API laden ────────
  async function loadContent() {
    try {
      const res  = await fetch(C2C_API + 'content.php');
      if (!res.ok) return;
      const data = await res.json();
      if (!data.success || !data.content) return;
      const c = data.content;

      // NAV
      set('navCta', c.nav?.cta_label);

      // HERO
      set('heroEyebrow', c.hero?.eyebrow);
      set('heroH1Line1', c.hero?.h1_line1);
      set('heroAccent',  c.hero?.h1_accent);
      setHTML('heroH2',  c.hero?.h2?.replace(/\n/g,'<br>'));
      set('heroBody',    c.hero?.body);
      set('heroCta1',    c.hero?.cta_primary);
      set('heroCta2',    c.hero?.cta_secondary);

      // Chapter cards
      ['1','2','3'].forEach(i => {
        set('ch' + i + 'name', c.services?.['s' + i + '_name']);
        const price = c.services?.['s' + i + '_price'];
        if (price) set('ch' + i + 'price', 'CHF ' + price);
      });

      // Services section
      set('svcTag', c.services?.section_tag);
      setHTML('svcTitle', c.services?.title?.replace(/\n/g,'<br>'));
      ['1','2','3'].forEach(i => {
        set('s' + i + 'name', c.services?.['s' + i + '_name']);
        set('s' + i + 'desc', c.services?.['s' + i + '_desc']);
        const price = c.services?.['s' + i + '_price'];
        if (price) set('s' + i + 'price', 'CHF ' + price);
        const feats = c.services?.['s' + i + '_features'];
        if (feats) {
          const ul = document.getElementById('s' + i + 'feats');
          if (ul) ul.innerHTML = feats.split('\n').filter(f=>f.trim())
            .map(f => '<li>' + esc(f.trim()) + '</li>').join('');
        }
      });
      if (c.services?.s2_badge) set('s2badge', c.services.s2_badge);

      // How
      set('howTag', c.how?.section_tag);
      setHTML('howTitle', c.how?.title?.replace(/\n/g,'<br>'));
      ['1','2','3','4'].forEach(s => {
        set('step' + s + 'icon',  c.how?.['step' + s + '_icon']);
        set('step' + s + 'title', c.how?.['step' + s + '_title']);
        set('step' + s + 'text',  c.how?.['step' + s + '_text']);
      });

      // Quote
      set('quoteText', c.quote?.text);
      set('quoteAttr', c.quote?.author);

      // About
      set('aboutTag',   c.about?.section_tag);
      set('aboutBody1', c.about?.body1);
      set('aboutBody2', c.about?.body2);
      set('aboutSig',   c.about?.signature);
      if (c.about?.headline) {
        const lines = c.about.headline.split('\n').filter(Boolean);
        const last  = lines.pop();
        const el    = document.getElementById('aboutH');
        if (el) el.innerHTML = lines.map(esc).join('<br>') +
          (lines.length ? '<br>' : '') + '<em>' + esc(last) + '</em>';
      }

      // Disclaimer & Footer
      set('disclaimerText', c.disclaimer?.text);
      set('footContact',    c.footer?.contact);
      set('footCta',        c.footer?.cta_label);
      if (c.footer?.email) {
        set('footEmail', c.footer.email);
        const a = document.getElementById('footEmail');
        if (a) a.href = 'mailto:' + c.footer.email;
      }
      if (c.seo?.title) document.title = c.seo.title;

    } catch (e) {
      // Statische Fallback-Inhalte bleiben sichtbar
    }
  }

  // ── News aus API laden ───────────────────
  async function loadNews() {
    try {
      const res  = await fetch(C2C_API + 'news_public.php');
      if (!res.ok) return;
      const data = await res.json();
      if (!data.news?.length) return;

      const news = data.news;

      // Main story
      const main = news[0];
      if (main) {
        set('newsMainTag', 'Aktuell · IRCC');
        set('newsMainHl',  main.title);
        if (main.summary) set('newsMainExcerpt', main.summary.slice(0,280) + '…');
        const meta = document.getElementById('newsMainMeta');
        if (meta && main.published) {
          const d = new Date(main.published);
          let txt = 'Canada.ca IRCC · ' + d.toLocaleDateString('de-CH',{year:'numeric',month:'long',day:'numeric'});
          if (main.link) txt += ' · <a href="' + esc(main.link) + '" target="_blank" rel="noopener">Lesen →</a>';
          meta.innerHTML = txt;
        }
      }

      // Sidebar
      const sidebar = news.slice(1,4);
      if (sidebar.length) {
        const sb = document.getElementById('newsSidebar');
        if (sb) sb.innerHTML = sidebar.map(n => {
          const d = n.published
            ? new Date(n.published).toLocaleDateString('de-CH',{year:'numeric',month:'short'})
            : '';
          return '<a href="' + esc(n.link||'#') + '" class="news-card" target="_blank" rel="noopener">' +
            '<div class="news-tag">IRCC</div>' +
            '<div class="news-card-hl">' + esc(n.title) + '</div>' +
            '<div class="news-meta">' + esc(d) + '</div></a>';
        }).join('');
      }

      // Ticker mit echten News
      if (track) {
        track.innerHTML = [...news,...news]
          .map(n => '<span class="tk-item">'+esc(n.title)+'</span><span class="tk-sep">|</span>')
          .join('');
      }

    } catch (e) {
      // Statische Fallback-News bleiben
    }
  }

  // ── Start ────────────────────────────────
  loadContent();
  loadNews();

})();
