/* ─────────────────────────────────────────────
   DR. BISWAS SKINCARE — MAIN JAVASCRIPT
───────────────────────────────────────────── */

const NAV_HTML = `
<nav class="navbar" id="navbar">
  <a class="nav-logo" href="index.html">
    <span class="name">Dr. Biswas</span>
    <span class="tagline">Aesthetic Physician &amp; Model · Kolkata</span>
  </a>
  <div class="nav-links">
    <a href="index.html">Home</a>
    <a href="about.html">About</a>
    <a href="doctor-portfolio.html">Doctor</a>
    <a href="model-portfolio.html">Model</a>
    <a href="services.html">Services</a>
    <a href="gallery.html">Gallery</a>
    <a href="contact.html">Contact</a>
    <a href="booking.html" class="nav-cta">Book Now</a>
  </div>
  <div class="hamburger" id="hamburger" aria-label="Menu">
    <span></span><span></span><span></span>
  </div>
</nav>
<div class="mobile-nav" id="mobileNav">
  <a href="index.html">Home</a>
  <a href="about.html">About</a>
  <a href="doctor-portfolio.html">Doctor Portfolio</a>
  <a href="model-portfolio.html">Model Portfolio</a>
  <a href="services.html">Services</a>
  <a href="gallery.html">Gallery</a>
  <a href="contact.html">Contact</a>
  <a href="booking.html" class="mobile-cta">Book Appointment</a>
</div>
`;

const FOOTER_HTML = `
<footer class="site-footer">
  <div class="container">
    <div class="footer-grid">
      <div class="footer-brand">
        <div class="f-logo">Dr. Biswas<span>Aesthetic Physician &amp; Model · Kolkata</span></div>
        <p>"Inner beauty is paramount — but a little Botox or Filler can add a beautiful chapter to your story." Redefining beauty through science &amp; art.</p>
        <div class="social-row">
          <a href="https://www.facebook.com/drbiswasskincare/" target="_blank" rel="noopener" class="soc-link" title="Facebook"><i class="fab fa-facebook-f"></i></a>
          <a href="https://www.instagram.com/drbiswasskincare/" target="_blank" rel="noopener" class="soc-link" title="Instagram"><i class="fab fa-instagram"></i></a>
          <a href="https://www.youtube.com/@drbiswasskincare" target="_blank" rel="noopener" class="soc-link" title="YouTube"><i class="fab fa-youtube"></i></a>
          <a href="https://wa.me/919830XXXXXX" target="_blank" rel="noopener" class="soc-link" title="WhatsApp"><i class="fab fa-whatsapp"></i></a>
        </div>
      </div>
      <div class="footer-col">
        <h4>Navigation</h4>
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About Dr. Biswas</a></li>
          <li><a href="doctor-portfolio.html">Medical Portfolio</a></li>
          <li><a href="model-portfolio.html">Model Portfolio</a></li>
          <li><a href="gallery.html">Photo Gallery</a></li>
        </ul>
      </div>
      <div class="footer-col">
        <h4>Treatments</h4>
        <ul>
          <li><a href="service-detail.html">Botox &amp; Fillers</a></li>
          <li><a href="service-detail.html">Laser Treatments</a></li>
          <li><a href="service-detail.html">Chemical Peels</a></li>
          <li><a href="service-detail.html">PRP Therapy</a></li>
          <li><a href="service-detail.html">Hair Treatments</a></li>
          <li><a href="services.html">All Services</a></li>
        </ul>
      </div>
      <div class="footer-col">
        <h4>Clinics</h4>
        <ul>
          <li><a href="contact.html">📍 Salt Lake, Kolkata</a></li>
          <li><a href="contact.html">📍 Park Street, Kolkata</a></li>
          <li><a href="contact.html">📍 Ballygunge, Kolkata</a></li>
          <li><a href="tel:+919830XXXXXX">📞 +91 98300 XXXXX</a></li>
          <li><a href="booking.html">📅 Book Appointment</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div style="background:rgba(0,0,0,0.35)">
    <div class="container">
      <div class="footer-bottom">
        <div>&copy; 2025 <span class="accent">Dr. Debasish Biswas Skincare</span>. All Rights Reserved. Kolkata, West Bengal.</div>
        <div><a href="#">Privacy Policy</a> &nbsp;&middot;&nbsp; <a href="#">Terms of Service</a> &nbsp;&middot;&nbsp; Designed with <span class="accent">&hearts;</span> in Kolkata</div>
      </div>
    </div>
  </div>
</footer>
`;

const WA_FLOAT = `
<a href="https://wa.me/919830XXXXXX?text=Hello%20Dr.%20Biswas!%20I%20would%20like%20to%20book%20an%20appointment."
   class="whatsapp-float" target="_blank" rel="noopener" title="Chat on WhatsApp">
  <i class="fab fa-whatsapp"></i>
  <span class="wa-tip">Chat on WhatsApp</span>
</a>
<div id="toast"><i class="fas fa-check-circle"></i> <span id="toastMsg">Success!</span></div>
`;

const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
let calState = { year: new Date().getFullYear(), month: new Date().getMonth(), selected: null };

document.addEventListener('DOMContentLoaded', function () {
  injectSharedElements();
  initNavbar();
  initHamburger();
  highlightActiveNav();
  initCounters();
  initHeroSlider();
  initCalendar();
  initGalleryFilter();
  initScrollAnimations();
});

function injectSharedElements() {
  const n = document.getElementById('nav-mount');
  if (n) n.innerHTML = NAV_HTML;
  const f = document.getElementById('footer-mount');
  if (f) f.innerHTML = FOOTER_HTML;
  const w = document.getElementById('wa-mount');
  if (w) w.innerHTML = WA_FLOAT;
}

function initNavbar() {
  const nav = document.getElementById('navbar');
  if (!nav) return;
  window.addEventListener('scroll', () => nav.classList.toggle('scrolled', window.scrollY > 60));
}

function initHamburger() {
  document.addEventListener('click', function (e) {
    const ham = document.getElementById('hamburger');
    const mob = document.getElementById('mobileNav');
    if (!ham || !mob) return;
    if (ham.contains(e.target)) {
      ham.classList.toggle('open');
      mob.classList.toggle('open');
    } else if (!mob.contains(e.target)) {
      ham.classList.remove('open');
      mob.classList.remove('open');
    }
  });
}

function highlightActiveNav() {
  const page = window.location.pathname.split('/').pop() || 'index.html';
  document.querySelectorAll('.nav-links a, .mobile-nav a').forEach(a => {
    const href = (a.getAttribute('href') || '').split('?')[0];
    if (href === page) a.classList.add('active');
  });
}

function initCounters() {
  const counters = document.querySelectorAll('[data-count]');
  if (!counters.length) return;
  const obs = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (!entry.isIntersecting) return;
      animateNum(entry.target, parseInt(entry.target.dataset.count));
      obs.unobserve(entry.target);
    });
  }, { threshold: 0.6 });
  counters.forEach(c => obs.observe(c));
}

function animateNum(el, target) {
  let val = 0;
  const step = Math.max(1, Math.ceil(target / 55));
  const iv = setInterval(() => {
    val = Math.min(val + step, target);
    el.textContent = val.toLocaleString();
    if (val >= target) clearInterval(iv);
  }, 30);
}

function initHeroSlider() {
  const slides = document.querySelectorAll('.slide');
  const dots = document.querySelectorAll('.h-dot');
  if (!slides.length) return;
  let idx = 0, timer = null;
  function go(n) {
    slides[idx].classList.remove('active');
    if (dots[idx]) dots[idx].classList.remove('active');
    idx = (n + slides.length) % slides.length;
    slides[idx].classList.add('active');
    if (dots[idx]) dots[idx].classList.add('active');
  }
  function reset() { clearInterval(timer); timer = setInterval(() => go(idx + 1), 5800); }
  dots.forEach((d, i) => d.addEventListener('click', () => { go(i); reset(); }));
  const prev = document.getElementById('heroPrev');
  const next = document.getElementById('heroNext');
  if (prev) prev.addEventListener('click', () => { go(idx - 1); reset(); });
  if (next) next.addEventListener('click', () => { go(idx + 1); reset(); });
  reset();
}

function initCalendar() {
  if (!document.getElementById('calDays')) return;
  renderCalendar();
  document.getElementById('calPrev')?.addEventListener('click', () => {
    calState.month--; if (calState.month < 0) { calState.month = 11; calState.year--; }
    calState.selected = null; renderCalendar(); hideTimeSlots();
  });
  document.getElementById('calNext')?.addEventListener('click', () => {
    calState.month++; if (calState.month > 11) { calState.month = 0; calState.year++; }
    calState.selected = null; renderCalendar(); hideTimeSlots();
  });
}

function renderCalendar() {
  const label = document.getElementById('calMonthLabel');
  const grid = document.getElementById('calDays');
  if (!label || !grid) return;
  label.textContent = MONTHS[calState.month] + ' ' + calState.year;
  grid.innerHTML = '';
  const today = new Date();
  const firstDay = new Date(calState.year, calState.month, 1).getDay();
  const daysInMonth = new Date(calState.year, calState.month + 1, 0).getDate();
  for (let i = 0; i < firstDay; i++) {
    const e = document.createElement('div'); e.className = 'cal-day empty'; grid.appendChild(e);
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const cell = document.createElement('div');
    const date = new Date(calState.year, calState.month, d);
    const isPast = date < new Date(today.getFullYear(), today.getMonth(), today.getDate());
    cell.className = 'cal-day'; cell.textContent = d;
    if (isPast) { cell.classList.add('disabled'); }
    else {
      if (d === today.getDate() && calState.month === today.getMonth() && calState.year === today.getFullYear()) cell.classList.add('today');
      if (d === calState.selected) cell.classList.add('selected');
      cell.addEventListener('click', () => { calState.selected = d; renderCalendar(); showTimeSlots(); });
    }
    grid.appendChild(cell);
  }
}

function showTimeSlots() {
  const w = document.getElementById('timeSlotsWrap');
  if (w) { w.classList.remove('hidden'); w.classList.add('fade-in'); }
}
function hideTimeSlots() {
  const w = document.getElementById('timeSlotsWrap');
  if (w) w.classList.add('hidden');
}

document.addEventListener('click', function (e) {
  if (e.target.classList.contains('ts') && !e.target.classList.contains('taken')) {
    document.querySelectorAll('.ts.active').forEach(t => t.classList.remove('active'));
    e.target.classList.add('active');
  }
});

function initGalleryFilter() {
  const filters = document.querySelectorAll('.gf-btn');
  if (!filters.length) return;
  filters.forEach(btn => {
    btn.addEventListener('click', function () {
      filters.forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      const cat = this.dataset.filter;
      document.querySelectorAll('.masonry-item').forEach(item => {
        item.style.display = (cat === 'all' || item.dataset.cat === cat) ? 'block' : 'none';
      });
    });
  });
}

function initScrollAnimations() {
  const obs = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) { entry.target.classList.add('fade-in'); obs.unobserve(entry.target); }
    });
  }, { threshold: 0.1 });
  document.querySelectorAll('.service-tile, .doc-card, .testi-card, .clinic-card, .srv-card').forEach(el => {
    el.style.opacity = '0'; obs.observe(el);
  });
}

function submitBooking() {
  const name = document.getElementById('bName')?.value.trim();
  const phone = document.getElementById('bPhone')?.value.trim();
  const clinic = document.getElementById('bClinic')?.value;
  const service = document.getElementById('bService')?.value;
  const selectedTime = document.querySelector('.ts.active')?.textContent;
  if (!name || !phone || !clinic || !service) { showToast('Please fill in all required fields.', true); return; }
  if (!calState.selected) { showToast('Please select an appointment date.', true); return; }
  if (!selectedTime) { showToast('Please choose a time slot.', true); return; }
  const msg = `Hello Dr. Biswas! Appointment request: ${service} at ${clinic} on ${MONTHS[calState.month]} ${calState.selected}, ${calState.year} at ${selectedTime}. Name: ${name}, Phone: ${phone}.`;
  window.open('https://wa.me/919830XXXXXX?text=' + encodeURIComponent(msg), '_blank');
  showToast('Booking sent via WhatsApp! We\'ll confirm shortly.');
}

function submitContact() {
  const name = document.getElementById('cName')?.value.trim();
  const email = document.getElementById('cEmail')?.value.trim();
  if (!name || !email) { showToast('Please enter your name and email.', true); return; }
  showToast('Message sent! We\'ll get back to you within 24 hours.');
}

function showToast(msg, isError) {
  const toast = document.getElementById('toast');
  const tm = document.getElementById('toastMsg');
  if (!toast || !tm) return;
  tm.textContent = msg;
  const ic = toast.querySelector('i');
  if (ic) ic.style.color = isError ? '#ff6b6b' : 'var(--gold)';
  toast.classList.add('show');
  setTimeout(() => toast.classList.remove('show'), 4500);
}
