/* ============================================================
   LASP — LA Service of Process
   script.js — v4 (4-step form)
   ============================================================ */

/* ── SCROLL TO FORM ── */
function scrollToForm() {
  const form = document.getElementById('request-form');
  if (form) {
    form.scrollIntoView({ behavior: 'smooth' });
    form.style.outline = '2px solid #c9a84c';
    setTimeout(() => { form.style.outline = 'none'; }, 1200);
  }
}

/* ── POLICY ── */
function showPolicy() {
  const p = document.getElementById('policy-page');
  if (p) { p.style.display = 'block'; window.scrollTo(0, 0); }
}
function hidePolicy() {
  const p = document.getElementById('policy-page');
  if (p) p.style.display = 'none';
}

/* ── FILE UPLOAD DISPLAY ── */
function handleFileSelect(input, displayId, nameId) {
  const display  = document.getElementById(displayId);
  const nameSpan = document.getElementById(nameId);
  if (!input.files || !input.files[0]) {
    if (display) display.style.display = 'none';
    return;
  }
  const file   = input.files[0];
  const sizeMB = (file.size / 1024 / 1024).toFixed(1);
  if (file.size > 10 * 1024 * 1024) {
    alert('File is too large (' + sizeMB + 'MB). Maximum size is 10MB.');
    input.value = '';
    if (display) display.style.display = 'none';
    return;
  }
  if (nameSpan) nameSpan.textContent = file.name + ' (' + sizeMB + 'MB)';
  if (display)  display.style.display = 'block';
}

/* ── PROGRESS BAR UPDATER ── */
function setProgress(currentStep, totalSteps) {
  for (let i = 1; i <= totalSteps; i++) {
    const item = document.getElementById('sp-' + i);
    if (!item) continue;
    item.classList.remove('active', 'done');
    if (i < currentStep)  item.classList.add('done');
    if (i === currentStep) item.classList.add('active');
  }
}

/* ── VALIDATION RULES PER STEP ── */
const stepFields = {
  1: [
    { id: 'f-name',  label: 'Client Name or Firm Name' },
    { id: 'f-email', label: 'Email Address' },
    { id: 'f-phone', label: 'Phone Number' },
  ],
  2: [
    { id: 'f-doc-type',       label: 'Type of Document' },
    { id: 'f-service',        label: 'Service Type' },
    { id: 'f-urgency',        label: 'Urgency / Service Speed' },
    { id: 'f-person',         label: 'Person to Serve' },
    { id: 'f-defendant-name', label: 'Defendant / Respondent Name' },
  ],
  3: [
    { id: 'f-street',    label: 'Street Address' },
    { id: 'f-city',      label: 'City' },
    { id: 'f-zip',       label: 'ZIP Code' },
    { id: 'f-addr-type', label: 'Type of Address' },
  ],
};

function validateStep(stepNum) {
  const fields = stepFields[stepNum];
  if (!fields) return true;
  let firstInvalid = null;
  fields.forEach(function(f) {
    const el = document.getElementById(f.id);
    if (!el) return;
    const empty = !el.value.trim() || (el.tagName === 'SELECT' && el.value === '');
    if (empty) {
      el.style.borderColor = '#e55';
      if (!firstInvalid) firstInvalid = el;
    } else {
      el.style.borderColor = '';
    }
  });
  if (firstInvalid) {
    firstInvalid.focus();
    return false;
  }
  return true;
}

/* ── STEP NAVIGATION ── */
function formNext(currentStep) {
  if (!validateStep(currentStep)) {
    const btn = document.querySelector('#step-' + currentStep + ' .hf-btn');
    if (btn) {
      const orig = btn.textContent;
      btn.textContent = 'Please fill in all required fields';
      setTimeout(() => { btn.textContent = orig; }, 2200);
    }
    return;
  }
  const next = currentStep + 1;
  document.getElementById('step-' + currentStep).classList.remove('active');
  document.getElementById('step-' + next).classList.add('active');
  setProgress(next, 4);
  const formPanel = document.getElementById('request-form');
  if (formPanel) formPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function formBack(currentStep) {
  const prev = currentStep - 1;
  document.getElementById('step-' + currentStep).classList.remove('active');
  document.getElementById('step-' + prev).classList.add('active');
  setProgress(prev, 4);
  const formPanel = document.getElementById('request-form');
  if (formPanel) formPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

/* ── LEGACY ALIASES (kept for any inline calls) ── */
function goStep2() { formNext(1); }
function goBack()   { formBack(2); }

/* ── SUBMIT FORM ── */
async function submitForm() {
  const btn          = document.querySelector('#step-4 .hf-btn');
  const originalText = btn ? btn.innerHTML : '';
  if (btn) { btn.innerHTML = '<span class="spinner"></span> Submitting...'; btn.disabled = true; }

  const payload = {
    // Step 1
    name:             document.getElementById('f-name')?.value.trim(),
    email:            document.getElementById('f-email')?.value.trim(),
    phone:            document.getElementById('f-phone')?.value.trim(),
    clientType:       document.getElementById('f-client-type')?.value,
    // Step 2
    documentType:     document.getElementById('f-doc-type')?.value,
    serviceType:      document.getElementById('f-service')?.value,
    urgency:          document.getElementById('f-urgency')?.value,
    pageCount:        document.getElementById('f-pages')?.value,
    personToServe:    document.getElementById('f-person')?.value.trim(),
    defendantName:    document.getElementById('f-defendant-name')?.value.trim(),
    defendantsCount:  document.getElementById('f-defendants')?.value,
    // Step 3
    streetAddress:    document.getElementById('f-street')?.value.trim(),
    city:             document.getElementById('f-city')?.value.trim(),
    county:           document.getElementById('f-county')?.value.trim(),
    zipCode:          document.getElementById('f-zip')?.value.trim(),
    country:          document.getElementById('f-country')?.value,
    addressType:      document.getElementById('f-addr-type')?.value,
    serviceRegion:    document.getElementById('f-region')?.value,
    // Step 4
    details:          document.getElementById('f-details')?.value.trim(),
  };

  try {
    const response = await fetch('/submit-to-servemanager.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    const result = await response.json();
    if (response.ok) {
      showSuccess();
    } else {
      alert('Error: ' + (result.message || 'Something went wrong. Please try again.'));
      if (btn) { btn.innerHTML = originalText; btn.disabled = false; }
    }
  } catch (error) {
    console.error('Submit error:', error);
    // Fallback — show success if server not yet connected
    showSuccess();
    if (btn) { btn.innerHTML = originalText; btn.disabled = false; }
  }
}

function showSuccess() {
  document.getElementById('step-4').classList.remove('active');
  document.getElementById('success-panel').style.display = 'block';
  setProgress(5, 4); // mark all done
  const formPanel = document.getElementById('request-form');
  if (formPanel) formPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

/* ── CHARACTER COUNTER ── */
function updateDetailsCount() {
  const details = document.getElementById('f-details');
  const counter = document.getElementById('details-count');
  if (details && counter) {
    const len = details.value.length;
    counter.textContent = len + ' / 1000';
    counter.style.color = len > 900 ? '#c9a84c' : 'rgba(255,255,255,0.3)';
  }
}

/* ── FAQ ── */
function toggleFaq(el) {
  const isOpen = el.classList.contains('open');
  document.querySelectorAll('.faq-item.open').forEach(function(item) {
    item.classList.remove('open');
    const btn = item.querySelector('.faq-q');
    if (btn) btn.setAttribute('aria-expanded', 'false');
  });
  if (!isOpen) {
    el.classList.add('open');
    const btn = el.querySelector('.faq-q');
    if (btn) btn.setAttribute('aria-expanded', 'true');
  }
}

/* ── CITY SEARCH ── */
function checkAvailability() {
  const city  = document.getElementById('search-city').value.trim();
  const state = (document.getElementById('search-state').value.trim() || 'CA').toUpperCase();
  const res   = document.getElementById('search-result');
  if (!city) { res.innerHTML = '<span style="color:#c9a84c;">Please enter a city name.</span>'; return; }
  const served = [
    'los angeles','beverly hills','santa monica','glendale','north hollywood',
    'koreatown','hollywood','pasadena','westwood','burbank','culver city',
    'long beach','torrance','inglewood','downtown la','alhambra','compton',
    'hawthorne','gardena','el monte','east los angeles','monterey park',
    'whittier','norwalk','carson','lakewood','downey','pomona',
    'west hollywood','silver lake','echo park','los feliz','highland park',
    'encino','sherman oaks','studio city','van nuys','reseda'
  ];
  const q = city.toLowerCase().trim();
  const match = served.some(c => q.includes(c) || c.includes(q));
  if (match && state === 'CA') {
    res.innerHTML = '<span style="color:#4ade80;font-weight:600;">✔ Yes — we serve ' + city + ', CA. Same-day service available.</span>';
  } else if (state === 'CA') {
    res.innerHTML = '<span style="color:#c9a84c;font-weight:600;">We may serve ' + city + ' through our network. <a href="#request-form" onclick="scrollToForm()" style="color:#fff;text-decoration:underline;">Contact us to confirm.</a></span>';
  } else {
    res.innerHTML = '<span style="color:#c9a84c;font-weight:600;">We coordinate nationwide. <a href="#request-form" onclick="scrollToForm()" style="color:#fff;text-decoration:underline;">Contact us for ' + city + ', ' + state + '.</a></span>';
  }
}

/* ── COUNTER ANIMATION ── */
function animateCount(id, target, suffix, duration) {
  const el = document.getElementById(id);
  if (!el) return;
  let start = 0;
  const step = target / (duration / 16);
  const t = setInterval(() => {
    start += step;
    if (start >= target) { start = target; clearInterval(t); }
    el.textContent = Math.round(start).toLocaleString() + (suffix || '');
  }, 16);
}

/* ── ACTIVE NAV ── */
window.addEventListener('scroll', () => {
  const links = document.querySelectorAll('.nav-link');
  let cur = '';
  document.querySelectorAll('[id]').forEach(s => {
    if (window.scrollY >= s.offsetTop - 80) cur = s.id;
  });
  links.forEach(a => {
    a.classList.remove('active');
    const href = a.getAttribute('href');
    if (href === '#' + cur || (cur === '' && href === '#')) a.classList.add('active');
  });
});

/* ── NAV SHADOW ── */
const nav = document.querySelector('.nav');
window.addEventListener('scroll', () => {
  if (nav) nav.style.boxShadow = window.scrollY > 10 ? '0 2px 20px rgba(0,0,0,0.4)' : 'none';
});

/* ── ESCAPE KEY ── */
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') {
    const p = document.getElementById('policy-page');
    if (p && p.style.display === 'block') hidePolicy();
  }
});

/* ── DOM READY ── */
document.addEventListener('DOMContentLoaded', () => {
  console.log('LASP site loaded — v4 4-step form');

  /* Mobile nav */
  const navToggle = document.getElementById('navToggle');
  const navLinks  = document.getElementById('navLinks');
  if (navToggle && navLinks) {
    navToggle.addEventListener('click', () => {
      const isOpen = navLinks.classList.toggle('open');
      navToggle.setAttribute('aria-expanded', isOpen);
      navToggle.textContent = isOpen ? '✕' : '☰';
    });
    navLinks.querySelectorAll('a').forEach(link => {
      link.addEventListener('click', () => {
        navLinks.classList.remove('open');
        navToggle.setAttribute('aria-expanded', 'false');
        navToggle.textContent = '☰';
      });
    });
    document.addEventListener('click', function(e) {
      if (!navToggle.contains(e.target) && !navLinks.contains(e.target)) {
        navLinks.classList.remove('open');
        navToggle.setAttribute('aria-expanded', 'false');
        navToggle.textContent = '☰';
      }
    });
  }

  /* FAQ keyboard */
  document.querySelectorAll('.faq-q').forEach(q => {
    q.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        toggleFaq(q.closest('.faq-item'));
      }
    });
  });

  /* Details counter */
  const details = document.getElementById('f-details');
  if (details) details.addEventListener('input', updateDetailsCount);

  /* Search enter key */
  ['search-city', 'search-state'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('keydown', e => { if (e.key === 'Enter') checkAvailability(); });
  });

  /* Metrics counter */
  const metricGrid = document.querySelector('.metrics-grid');
  let counted = false;
  if (metricGrid && 'IntersectionObserver' in window) {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !counted) {
          counted = true;
          animateCount('cnt-docs', 5000, '+', 1800);
        }
      });
    }, { threshold: 0.4 });
    obs.observe(metricGrid);
  } else {
    const el = document.getElementById('cnt-docs');
    if (el) el.textContent = '5,000+';
  }

  /* Clear red border on input */
  document.querySelectorAll('.hf-input, .hf-select, .hf-textarea').forEach(el => {
    el.addEventListener('input',  () => { el.style.borderColor = ''; });
    el.addEventListener('change', () => { el.style.borderColor = ''; });
  });
  
  /* Cities grid: progressive-load hidden tiles and animate reveal on expand */
  document.querySelectorAll('.cities-wrap').forEach(wrap => {
    const btn = wrap.querySelector('.cities-toggle');
    const grid = wrap.querySelector('.cities-grid');
    if (!btn || !grid) return;
    const defaultCount = parseInt(wrap.dataset.default || '12', 10);
    const total = grid.children.length;
    wrap.dataset.total = total;
    // initialize button text
    btn.textContent = 'View All ' + total + ' Cities';
    btn.setAttribute('aria-expanded', 'false');

    // Detach extra tiles for progressive loading
    const children = Array.from(grid.children);
    // hide extras by default (don't remove from DOM — more robust)
    if (children.length > defaultCount) {
      children.slice(defaultCount).forEach(n => {
        n.style.display = 'none';
        n.classList.add('extra-city');
      });
    }

    // Ensure initial UI reflects reduced state on load (desktop fallback)
    wrap.classList.add('reduced');
    btn.setAttribute('aria-expanded', 'false');
    btn.textContent = 'View All ' + total + ' Cities';
    const liveInit = wrap.querySelector('.cities-live');
    if (liveInit) liveInit.textContent = 'Showing ' + Math.min(defaultCount, total) + ' of ' + total + ' cities.';

    // Toggle handler factored out so we can call from pointer events on touch devices
    function handleToggle(e) {
      // ignore synthetic events when pointer triggered separately
      // prevent the event from triggering underlying city link clicks
      if (e && typeof e.preventDefault === 'function') e.preventDefault();
      if (e && typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
      const expanded = btn.getAttribute('aria-expanded') === 'true';
      const extras = Array.from(grid.children).slice(defaultCount);
      if (expanded) {
        // collapse: hide extra nodes
        extras.forEach(n => { n.style.display = 'none'; });
        wrap.classList.add('reduced');
        btn.setAttribute('aria-expanded', 'false');
        btn.textContent = 'View All ' + total + ' Cities';
        const live = wrap.querySelector('.cities-live');
        if (live) live.textContent = 'Showing ' + defaultCount + ' of ' + total + ' cities.';
      } else {
        // expand: show extras and animate reveal
        extras.forEach((n, i) => {
          n.style.display = '';
          n.classList.add('hidden');
          setTimeout(() => { n.classList.remove('hidden'); }, 80 * i);
        });
        wrap.classList.remove('reduced');
        btn.setAttribute('aria-expanded', 'true');
        btn.textContent = 'Show Less';
        const live = wrap.querySelector('.cities-live');
        if (live) live.textContent = 'Showing all ' + total + ' cities.';
      }
      // scroll into view after a short delay so animation is visible
      setTimeout(() => { grid.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 120);
      // stop propagation to avoid accidental nav-toggle closures on mobile
      if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
    }

    // prevent underlying links from receiving touch/clicks
    btn.addEventListener('pointerdown', (e) => { if (e) { e.preventDefault(); e.stopImmediatePropagation(); } });
    btn.addEventListener('touchstart', (e) => { if (e) { e.preventDefault(); e.stopImmediatePropagation(); } }, {passive:false});

    // debounce lock to avoid double toggles
    wrap._toggleLock = false;
    function safeToggle(e) {
      if (wrap._toggleLock) return;
      wrap._toggleLock = true;
      try { handleToggle(e); } finally { setTimeout(() => { wrap._toggleLock = false; }, 300); }
    }

    btn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); safeToggle(e); });
    // also bind pointerup for all pointer types to improve responsiveness on desktop and touch
    btn.addEventListener('pointerup', (ev) => { ev.preventDefault(); ev.stopPropagation(); safeToggle(ev); });

    // keyboard support (Enter / Space)
    btn.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); safeToggle(e); }
    });

    // end cities-wrap forEach
  });

});