/* NRI Property Guard — shared site behaviour (nav, WhatsApp widget, FAQ, lead forms) */

// Public Supabase project config (anon/publishable key — safe for client use, protected by RLS)
window.NRIPG_SUPABASE = {
  url: 'https://kwzjscbvyuotwhrcbxkw.supabase.co',
  anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt3empzY2J2eXVvdHdocmNieGt3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODQ5NTE0NTQsImV4cCI6MjEwMDUyNzQ1NH0.2VazaDXTR95k5Gs4dGcwOI6a6rnY5-1aPumiyqO9BtE'
};
window.NRIPG_WHATSAPP_NUMBER = '919948039325';
window.NRIPG_PHONE_DISPLAY = '+91 99480 39325';

document.addEventListener('DOMContentLoaded', function () {
  /* ---------- Mobile nav toggle ---------- */
  var toggle = document.querySelector('.nav-toggle');
  var links = document.querySelector('.nav-links');
  var navbar = document.querySelector('.navbar');
  if (toggle && links) {
    // The mobile drawer must start exactly below the header, but the header's
    // own height changes with viewport width (the topbar text wraps to more
    // lines on narrow phones), so a fixed CSS offset can't work at every
    // width. Measure the real header height whenever the drawer opens (and
    // again on resize/orientation-change while it's open) and hand it to CSS
    // as a custom property.
    function syncDrawerOffset() {
      if (navbar) {
        document.documentElement.style.setProperty('--nav-drawer-top', navbar.getBoundingClientRect().bottom + 'px');
      }
    }
    toggle.addEventListener('click', function () {
      var opening = !links.classList.contains('open');
      if (opening) syncDrawerOffset();
      links.classList.toggle('open');
      toggle.setAttribute('aria-expanded', links.classList.contains('open'));
    });
    window.addEventListener('resize', function () {
      if (links.classList.contains('open')) syncDrawerOffset();
    });
    links.querySelectorAll('a').forEach(function (a) {
      a.addEventListener('click', function () { links.classList.remove('open'); });
    });
  }

  /* ---------- Mark active nav link (same-directory pages only — skips the portal login link) ---------- */
  var path = location.pathname.split('/').pop() || 'index.html';
  document.querySelectorAll('.nav-links a[href]').forEach(function (a) {
    var href = a.getAttribute('href');
    if (href.indexOf('/') === -1 && href === path) a.classList.add('active');
  });

  /* ---------- FAQ accordion ---------- */
  document.querySelectorAll('.accordion-item').forEach(function (item) {
    var q = item.querySelector('.accordion-q');
    var a = item.querySelector('.accordion-a');
    if (!q || !a) return;
    q.addEventListener('click', function () {
      var isOpen = item.classList.contains('open');
      document.querySelectorAll('.accordion-item.open').forEach(function (other) {
        if (other !== item) { other.classList.remove('open'); other.querySelector('.accordion-a').style.maxHeight = null; }
      });
      item.classList.toggle('open', !isOpen);
      a.style.maxHeight = !isOpen ? (a.scrollHeight + 20) + 'px' : null;
    });
  });

  /* ---------- WhatsApp floating widget ---------- */
  buildWhatsAppWidget();

  /* ---------- Lead / contact forms -> website_leads table ---------- */
  document.querySelectorAll('form[data-lead-form]').forEach(bindLeadForm);

  /* ---------- Reveal-on-scroll ---------- */
  var revealEls = document.querySelectorAll('.reveal');
  if ('IntersectionObserver' in window && revealEls.length) {
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.12 });
    revealEls.forEach(function (el) { io.observe(el); });
  }
});

function buildWhatsAppWidget() {
  if (document.querySelector('.wa-fab')) return;
  var wa = window.NRIPG_WHATSAPP_NUMBER;
  var msg = encodeURIComponent("Hi NRI Property Guard, I'd like to know more about your property verification & management service.");

  var fab = document.createElement('button');
  fab.className = 'wa-fab';
  fab.setAttribute('aria-label', 'Speak to an expert');
  fab.innerHTML = '<svg width="30" height="30" viewBox="0 0 32 32" fill="none"><circle cx="16" cy="16" r="16" fill="#25D366"/><path d="M16.04 6.5c-5.4 0-9.8 4.38-9.8 9.78 0 1.72.46 3.4 1.33 4.87l-1.41 5.15 5.28-1.38a9.8 9.8 0 0 0 4.6 1.17h.01c5.4 0 9.8-4.38 9.8-9.78s-4.4-9.81-9.81-9.81zm5.75 13.99c-.24.68-1.19 1.24-1.96 1.4-.52.11-1.2.2-3.51-.75-2.94-1.22-4.84-4.2-4.99-4.4-.15-.2-1.2-1.59-1.2-3.03s.75-2.15.02-2.87c-.29-.28-.63-.28-.9-.28h-.5c-.29 0-.75.1-1.14.51-.39.4-1.5 1.46-1.5 3.55s1.53 4.11 1.75 4.39c.21.29 3.02 4.6 7.31 6.45.36.15 1.02.4 1.5.48.63.11 1.28.06 1.79-.11.6-.19 1.85-1.03 2.11-2.02.26-1 .26-1.85.18-2.02-.08-.18-.29-.28-.6-.44l-1.9-.94z" fill="#fff"/></svg>';

  var panel = document.createElement('div');
  panel.className = 'wa-panel';
  panel.innerHTML =
    '<div class="wa-panel-head"><span>Speak to an Expert</span><button type="button" aria-label="Close" class="wa-close">&times;</button></div>' +
    '<div class="wa-panel-body">' +
      '<a class="wa-action wa" href="https://wa.me/' + wa + '?text=' + msg + '" target="_blank" rel="noopener">' +
        '<span class="ic"><svg width="18" height="18" viewBox="0 0 32 32" fill="#fff"><path d="M16.04 3C9.02 3 3.32 8.7 3.32 15.72c0 2.32.62 4.49 1.7 6.36L3 29l7.13-1.98a12.6 12.6 0 0 0 5.91 1.47h.01c7.02 0 12.71-5.7 12.71-12.72C28.76 8.75 23.06 3 16.04 3zm0 23.05h-.01a10.6 10.6 0 0 1-5.4-1.48l-.39-.23-4.23 1.17 1.13-4.14-.25-.42a10.5 10.5 0 0 1-1.62-5.63c0-5.85 4.77-10.6 10.63-10.6 2.83 0 5.5 1.11 7.5 3.11a10.5 10.5 0 0 1 3.1 7.5c0 5.85-4.77 10.6-10.46 10.72zm5.78-7.94c-.31-.16-1.85-.91-2.14-1.02-.29-.1-.5-.16-.71.16-.21.31-.81 1.02-1 1.23-.18.21-.37.23-.68.08-.31-.16-1.32-.49-2.51-1.55-.93-.83-1.55-1.85-1.74-2.16-.18-.31-.02-.48.14-.63.14-.14.31-.37.47-.55.16-.19.21-.31.31-.52.1-.21.05-.39-.03-.55-.08-.16-.71-1.71-.97-2.34-.26-.62-.52-.53-.71-.54-.18-.01-.39-.01-.6-.01-.21 0-.55.08-.84.39-.29.31-1.1 1.08-1.1 2.63s1.13 3.05 1.29 3.26c.16.21 2.23 3.4 5.4 4.77.75.32 1.34.52 1.8.66.76.24 1.44.21 1.99.13.61-.09 1.85-.76 2.11-1.49.26-.73.26-1.36.18-1.49-.08-.13-.29-.21-.6-.37z"/></svg></span>' +
        '<div><b>WhatsApp</b><span>Quick response</span></div>' +
      '</a>' +
      '<a class="wa-action" href="tel:+' + wa + '">' +
        '<span class="ic"><svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M6.6 10.8c1.4 2.7 3.6 4.9 6.3 6.3l2.1-2.1c.3-.3.7-.4 1-.2 1.1.4 2.4.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1C11 21 3 13 3 5c0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.4 0 .8-.2 1L6.6 10.8z"/></svg></span>' +
        '<div><b>Call Us</b><span>Immediate Response</span></div>' +
      '</a>' +
    '</div>';

  document.body.appendChild(fab);
  document.body.appendChild(panel);

  var fabIconOpen = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.4"><path d="M6 6l12 12M18 6L6 18" stroke-linecap="round"/></svg>';
  var fabIconClosed = fab.innerHTML;
  function setPanel(open) {
    panel.classList.toggle('open', open);
    fab.innerHTML = open ? fabIconOpen : fabIconClosed;
    fab.setAttribute('aria-expanded', open);
  }
  fab.addEventListener('click', function () { setPanel(!panel.classList.contains('open')); });
  panel.querySelector('.wa-close').addEventListener('click', function () { setPanel(false); });
}

function bindLeadForm(form) {
  form.addEventListener('submit', async function (e) {
    e.preventDefault();
    var alertBox = form.querySelector('.form-alert');
    var btn = form.querySelector('button[type="submit"]');
    var originalLabel = btn ? btn.textContent : '';
    var fd = new FormData(form);
    var params = new URLSearchParams(location.search);

    var payload = {
      lead_type: form.getAttribute('data-lead-form') || 'contact',
      name: fd.get('name') || null,
      email: fd.get('email') || null,
      phone: fd.get('phone') || null,
      message: fd.get('message') || null,
      property_city: fd.get('city') || null,
      source_page: location.pathname,
      utm_source: params.get('utm_source'),
      utm_medium: params.get('utm_medium'),
      utm_campaign: params.get('utm_campaign')
    };

    if (btn) { btn.disabled = true; btn.textContent = 'Sending…'; }

    try {
      var res = await fetch(window.NRIPG_SUPABASE.url + '/rest/v1/website_leads', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'apikey': window.NRIPG_SUPABASE.anonKey,
          'Authorization': 'Bearer ' + window.NRIPG_SUPABASE.anonKey,
          'Prefer': 'return=minimal'
        },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error('Request failed: ' + res.status);
      form.reset();
      if (alertBox) { alertBox.textContent = "Thank you! Our NRI property team will reach out within one business day. For anything urgent, message us on WhatsApp."; alertBox.className = 'form-alert success show'; }
    } catch (err) {
      if (alertBox) { alertBox.textContent = 'Something went wrong sending your message. Please try again, or reach us directly on WhatsApp at ' + window.NRIPG_PHONE_DISPLAY + '.'; alertBox.className = 'form-alert error show'; }
    } finally {
      if (btn) { btn.disabled = false; btn.textContent = originalLabel; }
    }
  });
}
