'use strict';

// ─── Chart management ─────────────────────────────────────────────────────────
const _charts = {};

function initCharts() {
  document.querySelectorAll('script[type="application/json"][id$="-data"]').forEach(el => {
    const id = el.id.slice(0, -5); // strip '-data'
    const canvas = document.getElementById(id);
    if (!canvas) return;
    try {
      if (_charts[id]) { _charts[id].destroy(); delete _charts[id]; }
      _charts[id] = new Chart(canvas.getContext('2d'), JSON.parse(el.textContent));
    } catch (e) { console.warn('Chart init failed:', id, e); }
  });
}

document.addEventListener('htmx:afterSettle', initCharts);

// ─── Slider ↔ number sync ─────────────────────────────────────────────────────
document.addEventListener('input', e => {
  const el = e.target;
  if (el.type === 'range') {
    const num = el.closest('.slider-combo')?.querySelector('[data-sync]');
    if (num) num.value = el.value;
  } else if (el.dataset.sync) {
    const rng = el.closest('.slider-combo')?.querySelector('[type="range"]');
    if (rng) { rng.value = el.value; rng.dispatchEvent(new InputEvent('input', { bubbles: true })); }
  }
});

// ─── Toggle buttons (venue / own / glassType / lightingType / country) ────────
function setToggle(btn, key, val) {
  const h = document.getElementById('h-' + key);
  if (h) h.value = val;
  document.querySelectorAll(`[data-toggle="${key}"]`).forEach(b => {
    const on = b.dataset.val === val;
    b.classList.toggle('toggle-btn--active', on);
    b.classList.toggle('pill-btn--active', on);
  });
  updateWizardSections();
}

function setCountryPreset(code) {
  const p = (window.__COUNTRY_PRESETS__ || {})[code];
  if (!p) return;
  Object.entries(p).forEach(([k, v]) => {
    const inp = document.querySelector(`#planner-form [name="${k}"]`);
    const sync = document.querySelector(`[data-sync="${k}"]`);
    if (inp) inp.value = v;
    if (sync) sync.value = v;
  });
}

// ─── Conditional wizard sections ──────────────────────────────────────────────
function _setSection(el, visible) {
  el.style.display = visible ? '' : 'none';
  // Disable inputs in hidden sections so they're excluded from form submission
  el.querySelectorAll('input[name]').forEach(i => { i.disabled = !visible; });
}

function updateWizardSections() {
  const venue = document.getElementById('h-venue')?.value || 'indoor';
  const own   = document.getElementById('h-own')?.value   || 'rent';
  const combo = venue + '-' + own;
  document.querySelectorAll('[data-show-venue]').forEach(el =>
    _setSection(el, el.dataset.showVenue === venue));
  document.querySelectorAll('[data-show-capex]').forEach(el => {
    const v = el.dataset.showCapex;
    _setSection(el, v === combo || v === venue);
  });
  document.querySelectorAll('[data-show-opex]').forEach(el => {
    const v = el.dataset.showOpex;
    _setSection(el, v === combo || v === venue || v === own);
  });
}

// ─── Tab switching ────────────────────────────────────────────────────────────
function setActiveTab(tab) {
  const isWiz = tab === 'assumptions';
  document.getElementById('h-activeTab').value = tab;
  document.getElementById('planner-wizard').style.display = isWiz ? '' : 'none';
  document.getElementById('tab-content').style.display   = isWiz ? 'none' : '';
  // Sync both top and bottom nav active states
  document.querySelectorAll('.tab-btn').forEach(b =>
    b.classList.toggle('tab-btn--active', b.dataset.tab === tab));
  document.querySelectorAll('.bottom-nav__btn').forEach(b =>
    b.classList.toggle('bottom-nav__btn--active', b.dataset.tab === tab));
  // Mobile CTA bar: show on result tabs, hide on wizard
  const ctaBar = document.getElementById('ctaBottomBar');
  if (ctaBar && !ctaBar.dataset.dismissed) {
    ctaBar.classList.toggle('visible', !isWiz);
  }
}

// ─── Wizard navigation ────────────────────────────────────────────────────────
function showWizStep(n) {
  const steps = document.querySelectorAll('.wizard-step');
  steps.forEach(s => s.classList.toggle('active', +s.dataset.wiz === n));
  document.querySelectorAll('.wiz-dot').forEach(d =>
    d.classList.toggle('wiz-dot--active', +d.dataset.wiz === n));
  const nav = document.getElementById('wizNav');
  const back = nav.dataset.back;
  const next = nav.dataset.next;
  const results = nav.dataset.results;
  const isLast = n >= steps.length;
  nav.innerHTML =
    (n > 1 ? `<button type="button" class="wiz-btn--back" onclick="showWizStep(${n - 1})">${back}</button>` : '<div></div>') +
    (isLast
      ? `<button type="button" class="wiz-btn--next" onclick="document.querySelector('.tab-btn[data-tab=\\'capex\\'],.bottom-nav__btn[data-tab=\\'capex\\']').click()">${results}</button>`
      : `<button type="button" class="wiz-btn--next" onclick="showWizStep(${n + 1})">${next}</button>`);
}

// ─── Quote navigation ────────────────────────────────────────────────────────
function goToQuoteForm() {
  const fd = new FormData(document.getElementById('planner-form'));
  const params = new URLSearchParams({
    courts: fd.get('dblCourts') || '0',
    venue: fd.get('venue') || 'indoor',
  });
  window.location.href = window.__QUOTE_URL__ + '?' + params;
}

// ─── Scenario drawer toggle ─────────────────────────────────────────────────
document.addEventListener('htmx:afterSettle', e => {
  const drawer = document.getElementById('scenario-drawer');
  if (drawer && e.detail.target === drawer && drawer.innerHTML.trim()) {
    drawer.classList.add('open');
  }
});

// ─── Init ─────────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  updateWizardSections();
  // Show signup nudge after 30 s for unauthenticated visitors
  const bar = document.getElementById('signupBar');
  if (bar) setTimeout(() => { bar.style.display = ''; }, 30_000);
});
