/* ═══════════════════════════════════════════
   ECOBE ACADEMY — MAIN JS
   ═══════════════════════════════════════════ */

// ── NAV SCROLL ────────────────────────────
const nav = document.getElementById('mainNav');
const navToggle = document.getElementById('navToggle');
const navLinks  = document.getElementById('navLinks');

window.addEventListener('scroll', () => {
  const scrolled = window.scrollY > 40;
  nav.classList.toggle('scrolled', scrolled);
  navLinks.classList.toggle('scrolled', scrolled);
}, { passive: true });

navToggle?.addEventListener('click', () => {
  navLinks.classList.toggle('open');
});

// Close nav when clicking outside the drawer
document.addEventListener('click', (e) => {
  if (navLinks.classList.contains('open') && !navLinks.contains(e.target) && e.target !== navToggle && !navToggle.contains(e.target)) {
    navLinks.classList.remove('open');
  }
});

// Close nav on link click (mobile)
navLinks?.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', () => {
    navLinks.classList.remove('open');
  });
});

// ── COOKIE BANNER ─────────────────────────
function dismissCookie() {
  const banner = document.getElementById('cookieBanner');
  if (!banner) return;
  banner.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
  banner.style.opacity = '0';
  banner.style.transform = 'translateY(16px)';
  setTimeout(() => banner.remove(), 300);
}
// Auto-dismiss after 20s
setTimeout(() => {
  const b = document.getElementById('cookieBanner');
  if (b) b.style.display = 'none';
}, 20000);

// ── REVEAL ON SCROLL ──────────────────────
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach((entry, i) => {
    if (entry.isIntersecting) {
      setTimeout(() => entry.target.classList.add('visible'), i * 60);
      revealObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });

document.querySelectorAll('.reveal').forEach(el => revealObserver.observe(el));

// Stagger grid children
document.querySelectorAll(
  '.programs-grid, .mentors-grid, .team-grid, .resources-grid, .testimonials-grid, .process-grid, .promise-grid'
).forEach(grid => {
  grid.querySelectorAll('[class*="card"], [class*="step"], [class*="promise"]').forEach((card, i) => {
    card.style.transitionDelay = `${i * 0.08}s`;
    card.classList.add('reveal');
    revealObserver.observe(card);
  });
});

// ── FAQ ACCORDION ─────────────────────────
document.querySelectorAll('.faq-question').forEach(btn => {
  btn.addEventListener('click', () => {
    const item = btn.closest('.faq-item');
    const isOpen = item.classList.contains('open');
    document.querySelectorAll('.faq-item.open').forEach(el => el.classList.remove('open'));
    if (!isOpen) item.classList.add('open');
  });
});

// ── CONTACT FORM ──────────────────────────
const contactForm = document.getElementById('contactForm');
if (contactForm) {
  contactForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const btn = contactForm.querySelector('button[type="submit"]');
    const orig = btn.textContent;
    btn.textContent = 'Sending…';
    btn.disabled = true;
    try {
      const res = await fetch('/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: contactForm.name.value,
          email: contactForm.email.value,
          message: contactForm.message?.value
        })
      });
      const data = await res.json();
      if (data.success) {
        const success = document.getElementById('formSuccess');
        if (success) success.style.display = 'block';
        contactForm.reset();
      }
    } catch (err) { console.error(err); }
    finally {
      btn.textContent = orig;
      btn.disabled = false;
    }
  });
}

// ── NEWSLETTER ────────────────────────────
document.querySelectorAll('.newsletter-form').forEach(form => {
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const btn = form.querySelector('button');
    btn.textContent = '✓ Subscribed';
    btn.style.background = 'var(--emerald-d)';
    setTimeout(() => {
      btn.textContent = 'Subscribe';
      btn.style.background = '';
      form.reset();
    }, 3500);
  });
});

// ── FILTER TABS (resources page) ──────────
document.querySelectorAll('.filter-tab').forEach(tab => {
  tab.addEventListener('click', () => {
    document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
  });
});

// ── SMOOTH SCROLL ─────────────────────────
document.querySelectorAll('a[href^="#"]').forEach(link => {
  link.addEventListener('click', (e) => {
    const target = document.querySelector(link.getAttribute('href'));
    if (target) {
      e.preventDefault();
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  });
});

/* ═══════════════════════════════════════════
   FLOATING CHAT WIDGET
   ═══════════════════════════════════════════ */
const chatFab    = document.getElementById('chatFab');
const chatPanel  = document.getElementById('chatPanel');
const chatClose  = document.getElementById('chatClose');
const chatBody   = document.getElementById('chatBody');
const chatInput  = document.getElementById('chatInput');
const chatSend   = document.getElementById('chatSend');
const chatQuickBtns = document.getElementById('chatQuickBtns');

if (chatFab && chatPanel) {
  // Toggle panel
  chatFab.addEventListener('click', () => {
    const isOpen = chatPanel.classList.contains('visible');
    if (isOpen) {
      closeChat();
    } else {
      openChat();
    }
  });
  chatClose?.addEventListener('click', closeChat);

  function openChat() {
    chatPanel.classList.add('visible');
    chatFab.classList.add('open');
    setTimeout(() => chatInput?.focus(), 300);
  }
  function closeChat() {
    chatPanel.classList.remove('visible');
    chatFab.classList.remove('open');
  }

  // Quick buttons
  chatQuickBtns?.querySelectorAll('.chat-quick-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const msg = btn.getAttribute('data-msg');
      sendChatMessage(msg);
      // Hide quick buttons after first use
      chatQuickBtns.style.display = 'none';
    });
  });

  // Send on button click or Enter
  chatSend?.addEventListener('click', () => {
    const msg = chatInput.value.trim();
    if (msg) {
      sendChatMessage(msg);
      chatInput.value = '';
      chatQuickBtns.style.display = 'none';
    }
  });
  chatInput?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      const msg = chatInput.value.trim();
      if (msg) {
        sendChatMessage(msg);
        chatInput.value = '';
        chatQuickBtns.style.display = 'none';
      }
    }
  });

  function addMessage(text, isUser) {
    const msg = document.createElement('div');
    msg.className = `chat-msg ${isUser ? 'chat-msg-user' : 'chat-msg-bot'}`;
    const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    msg.innerHTML = `
      <div class="chat-bubble">${text}</div>
      <div class="chat-time">${time}</div>
    `;
    chatBody.appendChild(msg);
    chatBody.scrollTop = chatBody.scrollHeight;
  }

  function showTyping() {
    const el = document.createElement('div');
    el.className = 'chat-typing';
    el.id = 'chatTyping';
    el.innerHTML = '<span></span><span></span><span></span>';
    chatBody.appendChild(el);
    chatBody.scrollTop = chatBody.scrollHeight;
  }
  function hideTyping() {
    document.getElementById('chatTyping')?.remove();
  }

  const RESPONSES = {
    programs: `We have three programs:<br><br>
      🥈 <strong>Silver</strong> — CHF 1,980 — Self-directed with Q&A support<br>
      🥇 <strong>Gold</strong> — CHF 3,980 — Guided mentoring + we apply for roles<br>
      💎 <strong>Platinum</strong> — CHF 5,980 — Executive fast-track with 1:1 coaching<br><br>
      <a href="/our-programs">Explore all programs →</a>`,
    pricing: `Our programs start at CHF 1,980 (Silver) up to CHF 5,980 (Platinum), with EUR pricing also available. All programs include an option to pay in installments to make the investment manageable during your transition.<br><br><a href="/our-programs">See full pricing →</a>`,
    start: `Getting started is simple:<br><br>
      1. <a href="https://calendly.com/miriamscioratto/30min" target="_blank">Book a free 30-min call</a><br>
      2. We'll understand your situation<br>
      3. We recommend the right program — no pressure<br><br>
      Or <a href="/contact-us">send us a message</a> first.`,
    call: `<a href="https://calendly.com/miriamscioratto/30min" target="_blank">Book your free 30-minute mentor call here →</a><br><br>We'll discuss your situation, your goals, and which program makes the most sense for you.`,
    default: `Thanks for reaching out! For the best help, <a href="/contact-us">send us a message</a> or <a href="https://calendly.com/miriamscioratto/30min" target="_blank">book a free call</a> and we'll be happy to answer your questions in detail.`
  };

  function getResponse(msg) {
    const m = msg.toLowerCase();
    if (m.includes('program') || m.includes('course') || m.includes('silver') || m.includes('gold') || m.includes('platinum')) return RESPONSES.programs;
    if (m.includes('cost') || m.includes('price') || m.includes('pricing') || m.includes('chf') || m.includes('eur') || m.includes('pay')) return RESPONSES.pricing;
    if (m.includes('start') || m.includes('begin') || m.includes('how') || m.includes('join') || m.includes('enroll')) return RESPONSES.start;
    if (m.includes('call') || m.includes('book') || m.includes('schedule') || m.includes('calendly')) return RESPONSES.call;
    if (m.includes('tell me about') && m.includes('program')) return RESPONSES.programs;
    return RESPONSES.default;
  }

  function sendChatMessage(text) {
    addMessage(text, true);
    showTyping();
    setTimeout(() => {
      hideTyping();
      addMessage(getResponse(text), false);
    }, 1200 + Math.random() * 600);
  }
}
