function initSmile360HorizonSlider() {
  const track = document.getElementById("slide-track");
  const prevBtn = document.getElementById("prev-slide");
  const nextBtn = document.getElementById("next-slide");
  const progressBar = document.getElementById("progress-bar");
  const currentIndexEl = document.getElementById("current-index");
  let currentIdx = 0;
  const totalSlides = track.children.length;
  function updateSlider() {
    track.style.transform = `translateX(-${currentIdx * 100}%)`;
    const progress = ((currentIdx + 1) / totalSlides) * 100;
    progressBar.style.width = `${progress}%`;
    currentIndexEl.textContent = `0${currentIdx + 1}`;
  }
  nextBtn.addEventListener("click", () => {
    currentIdx = (currentIdx + 1) % totalSlides;
    updateSlider();
  });
  prevBtn.addEventListener("click", () => {
    currentIdx = (currentIdx - 1 + totalSlides) % totalSlides;
    updateSlider();
  });
  updateSlider();
}
document.addEventListener("DOMContentLoaded", initSmile360HorizonSlider);

// navbar js
/**
 * Smile 360 Navigation Logic
 * Encapsulated to handle overlay transitions and state.
 */
(function () {
  const menuToggle = document.getElementById("menu-toggle");
  const closeMenu = document.getElementById("close-menu");
  const navOverlay = document.getElementById("nav-overlay");
  const body = document.body;

  const toggleMenu = (isOpen) => {
    if (isOpen) {
      navOverlay.classList.remove("translate-y-[-100%]");
      navOverlay.classList.add("translate-y-0");
      body.style.overflow = "hidden";
    } else {
      navOverlay.classList.remove("translate-y-0");
      navOverlay.classList.add("translate-y-[-100%]");
      body.style.overflow = "";
    }
  };

  menuToggle.addEventListener("click", () => toggleMenu(true));
  closeMenu.addEventListener("click", () => toggleMenu(false));

  // Close on escape key
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && navOverlay.classList.contains("translate-y-0")) {
      toggleMenu(false);
    }
  });

  // Handle link clicks (smooth close)
  const links = navOverlay.querySelectorAll("a");
  links.forEach((link) => {
    link.addEventListener("click", () => {
      setTimeout(() => toggleMenu(false), 300);
    });
  });
})();

// treatment calc js
const phases = [
  {
    tag: "PHASE 01",
    title: "Diagnostics",
    status: "Active Diagnostics",
    desc: "Every masterpiece begins with a blueprint. Using high-resolution CBCT scans and AI-driven bone density mapping, we create a sub-millimeter accurate digital double of your current dental anatomy.",
    accuracy: "99.9%",
    imaging: "4K CBCT",
    ai: "Enabled",
    icon: "biotech",
    label: "CLINICAL<br/>ACCURACY",
    dash: 216,
    image:
      "https://lh3.googleusercontent.com/aida-public/AB6AXuCGQa9vimu8cdfdi46L3Puic9hDmOXjcDoTtLHCvKR_-Dl3xZpmpK2FsaiQyi4u4jmXZMnlu08W555AXZ9ULMOQfAyrmOaRut0EMnuT5ZTQHS1NhvLNjXiqN-Wg9wzmwywuqQzBArPD2GmtPeDmnxVEZXg_7gGyeGywjOZ9A0r6Jw97L2YpjnQgEK0X6RSuhCUsoGPKd7j_JdYgatkFnqKorj31nkPABY0LcJhtp-Xu5L4VCM_zAnh66FDy1KABAdiwiTzm6TawqkwT",
  },
  {
    tag: "PHASE 02",
    title: "Mockup",
    status: "Simulation Lab",
    desc: "Virtual prototyping of your smile. We craft multiple aesthetic variations using 3D facial scanning, allowing you to preview and approve your new look before any physical intervention occurs.",
    accuracy: "100%",
    imaging: "3D Face Scan",
    ai: "Optimized",
    icon: "model_training",
    label: "VISUAL<br/>FIDELITY",
    dash: 144,
    image:
      "https://lh3.googleusercontent.com/aida-public/AB6AXuAfn_VvMag66REj7tAV8xF4JrUJlnNsSZKLPgzVyb9EWZUjT2Byp09gKMnhvxT4DkUOuhFriHYjTkBYsNgN8jplgGTLpRrWCqsDiDFO1N4aTeU4BD1dRL_eTT8GFzi-bXGnAakhShF0zd0lxgfzzHd1VHeMCji1yBdgKZPsVUWb-d05YncZNiiX2uMCiIUHGlJVhG24lRlvaoxdtqI-Cb8CkaZhylKdLSuPGXVO7SLrqagYXJJ_Ck5aw7vRE5kIkR7AHDlAoi8TjWCq",
  },
  {
    tag: "PHASE 03",
    title: "Execution",
    status: "Surgical Suite",
    desc: "Precision in motion. Guided surgery systems and robotic-assisted placement ensure that the digital plan is executed with flawless mechanical accuracy and minimal downtime.",
    accuracy: "99.98%",
    imaging: "Real-time Nav",
    ai: "Monitoring",
    icon: "precision_manufacturing",
    label: "ROBOTIC<br/>PRECISION",
    dash: 72,
    image:
      "https://lh3.googleusercontent.com/aida-public/AB6AXuCGQa9vimu8cdfdi46L3Puic9hDmOXjcDoTtLHCvKR_-Dl3xZpmpK2FsaiQyi4u4jmXZMnlu08W555AXZ9ULMOQfAyrmOaRut0EMnuT5ZTQHS1NhvLNjXiqN-Wg9wzmwywuqQzBArPD2GmtPeDmnxVEZXg_7gGyeGywjOZ9A0r6Jw97L2YpjnQgEK0X6RSuhCUsoGPKd7j_JdYgatkFnqKorj31nkPABY0LcJhtp-Xu5L4VCM_zAnh66FDy1KABAdiwiTzm6TawqkwT",
  },
  {
    tag: "PHASE 04",
    title: "Maintenance",
    status: "Post-Clinical",
    desc: "Long-term excellence. Our proprietary monitoring protocol ensures that your results remain stable and vibrant, backed by our concierge clinical support team for lifetime care.",
    accuracy: "100%",
    imaging: "Bio-feedback",
    ai: "Continuous",
    icon: "verified",
    label: "LIFETIME<br/>STANDARDS",
    dash: 0,
    image:
      "https://lh3.googleusercontent.com/aida-public/AB6AXuAfn_VvMag66REj7tAV8xF4JrUJlnNsSZKLPgzVyb9EWZUjT2Byp09gKMnhvxT4DkUOuhFriHYjTkBYsNgN8jplgGTLpRrWCqsDiDFO1N4aTeU4BD1dRL_eTT8GFzi-bXGnAakhShF0zd0lxgfzzHd1VHeMCji1yBdgKZPsVUWb-d05YncZNiiX2uMCiIUHGlJVhG24lRlvaoxdtqI-Cb8CkaZhylKdLSuPGXVO7SLrqagYXJJ_Ck5aw7vRE5kIkR7AHDlAoi8TjWCq",
  },
];

let currentPhaseIdx = 0;

function setPhase(idx) {
  currentPhaseIdx = idx;
  const phase = phases[idx];

  // 1. Portal Image Transition
  const img = document.getElementById("phase-image");
  img.classList.remove("animate-portal");
  void img.offsetWidth; // Trigger reflow
  img.style.opacity = "0";
  setTimeout(() => {
    img.src = phase.image;
    img.classList.add("animate-portal");
  }, 50);

  // 2. Synchronized Text & Spec Staggered Reveal
  const revealGroups = [
    { id: "status-text", content: phase.status, stagger: "stagger-1" },
    { id: "spec-container", type: "specs", stagger: "stagger-2" },
    { id: "phase-head", type: "header", stagger: "stagger-3" },
    { id: "phase-desc", content: phase.desc, stagger: "stagger-4" },
  ];

  revealGroups.forEach((group) => {
    const el = document.getElementById(group.id);
    if (!el) return;

    el.style.opacity = "0";
    el.classList.remove(
      "animate-fade-slide",
      "stagger-1",
      "stagger-2",
      "stagger-3",
      "stagger-4",
    );

    setTimeout(() => {
      if (group.id === "status-text") el.textContent = phase.status;
      if (group.id === "phase-desc") el.textContent = phase.desc;
      if (group.type === "specs") {
        document.getElementById("spec-accuracy").textContent = phase.accuracy;
        document.getElementById("spec-imaging").textContent = phase.imaging;
        document.getElementById("spec-ai").textContent = phase.ai;
      }
      if (group.type === "header") {
        document.getElementById("phase-tag").textContent = phase.tag;
        document.getElementById("phase-title").textContent = phase.title;
        document.getElementById("phase-icon").textContent = phase.icon;
        document.getElementById("phase-label").innerHTML = phase.label;
      }

      el.classList.add("animate-fade-slide", group.stagger);
    }, 100);
  });

  // 3. Update Arc & UI Helpers
  document.getElementById("arc-progress").style.strokeDashoffset = phase.dash;

  document.querySelectorAll(".phase-btn").forEach((btn, i) => {
    const isActive = i === idx;
    btn.className = `phase-btn pointer-events-auto absolute ${isActive ? "w-10 h-10 bg-white text-smile-blue scale-110 shadow-lg" : "w-8 h-8 bg-white/20 text-white hover:bg-white hover:text-smile-blue"} rounded-full flex items-center justify-center font-bold transition-all z-20`;
    if (i === 0)
      btn.classList.add(
        "top-0",
        "left-1/2",
        "-translate-x-1/2",
        "-translate-y-1/2",
      );
    if (i === 1)
      btn.classList.add(
        "top-1/2",
        "right-0",
        "translate-x-1/2",
        "-translate-y-1/2",
      );
    if (i === 2)
      btn.classList.add(
        "bottom-0",
        "left-1/2",
        "-translate-x-1/2",
        "translate-y-1/2",
      );
    if (i === 3)
      btn.classList.add(
        "top-1/2",
        "left-0",
        "-translate-x-1/2",
        "-translate-y-1/2",
      );
  });

  document.querySelectorAll(".indicator-bar").forEach((bar, i) => {
    const isActive = i === idx;
    bar.style.opacity = isActive ? "1" : "0.4";
    bar.querySelector("div").className =
      `w-12 h-0.5 ${isActive ? "bg-white" : "bg-white/40"} rounded-full transition-all duration-500`;
  });
}

function nextPhase() {
  setPhase((currentPhaseIdx + 1) % phases.length);
}

document.addEventListener("DOMContentLoaded", () => setPhase(0));

// testimonial js
(function initPremiumSlider() {
  const track = document.getElementById("testimonialTrack");
  const prevBtn = document.getElementById("prevBtn");
  const nextBtn = document.getElementById("nextBtn");
  const indicators = document.querySelectorAll(".indicator");

  let currentIndex = 0;
  const totalSets = 2;

  function updateSlider() {
    const offset = currentIndex * -100;
    track.style.transform = `translateX(${offset}%)`;

    // Update indicators
    indicators.forEach((ind, i) => {
      if (i === currentIndex) {
        ind.classList.replace("w-4", "w-12");
        ind.classList.replace("bg-primary/20", "bg-primary");
      } else {
        ind.classList.replace("w-12", "w-4");
        ind.classList.replace("bg-primary", "bg-primary/20");
      }
    });
  }

  nextBtn.addEventListener("click", () => {
    currentIndex = (currentIndex + 1) % totalSets;
    updateSlider();
  });

  prevBtn.addEventListener("click", () => {
    currentIndex = (currentIndex - 1 + totalSets) % totalSets;
    updateSlider();
  });

  // Initialize
  updateSlider();
})();

// scan function
(function () {
  const canvas = document.getElementById("scan-canvas");
  const overlay = document.getElementById("scan-overlay");
  const beam = document.getElementById("scan-beam");
  const shadeProgress = document.getElementById("shade-progress");
  const alignmentBars = document.getElementById("alignment-metrics").children;
  const symmetryScore = document.getElementById("symmetry-score");
  const retriggerBtn = document.getElementById("retrigger-scan");

  let isAutoScanning = true;
  let autoScanProgress = 0;
  let direction = 1; // 1 for forward, -1 for backward
  let animationFrame;

  const updateUI = (progress) => {
    const p = Math.max(0, Math.min(progress, 100));

    // 1. Move Beam and Reveal Overlay
    beam.style.left = `${p}%`;
    overlay.style.clipPath = `inset(0 ${100 - p}% 0 0)`;

    // 2. Sync Analytics
    shadeProgress.style.width = `${Math.min(p * 0.95, 95)}%`;

    Array.from(alignmentBars).forEach((bar, index) => {
      const threshold = (index + 1) * 20;
      if (p >= threshold) {
        bar.classList.replace("bg-surface-container-high", "bg-primary");
      } else {
        bar.classList.replace("bg-primary", "bg-surface-container-high");
      }
    });

    const targetScore = 98.4;
    const currentScore = (p / 100) * targetScore;
    symmetryScore.textContent = currentScore.toFixed(1);
  };

  const animate = () => {
    if (!isAutoScanning) return;

    autoScanProgress += 0.4 * direction;

    if (autoScanProgress >= 100) {
      direction = -1;
      autoScanProgress = 100;
    } else if (autoScanProgress <= 0) {
      direction = 1;
      autoScanProgress = 0;
    }

    updateUI(autoScanProgress);
    animationFrame = requestAnimationFrame(animate);
  };

  const resetScan = () => {
    cancelAnimationFrame(animationFrame);
    autoScanProgress = 0;
    direction = 1;
    isAutoScanning = true;
    animate();
  };

  // User Interaction
  canvas.addEventListener("mousemove", (e) => {
    isAutoScanning = false;
    cancelAnimationFrame(animationFrame);
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const percentage = (x / rect.width) * 100;
    autoScanProgress = percentage;
    updateUI(percentage);
  });

  canvas.addEventListener("mouseleave", () => {
    // Resume auto-scan after user stops interacting
    isAutoScanning = true;
    animate();
  });

  canvas.addEventListener("touchstart", (e) => {
    isAutoScanning = false;
    cancelAnimationFrame(animationFrame);
  });

  canvas.addEventListener("touchmove", (e) => {
    if (e.touches.length > 0) {
      const rect = canvas.getBoundingClientRect();
      const x = e.touches[0].clientX - rect.left;
      const percentage = (x / rect.width) * 100;
      autoScanProgress = percentage;
      updateUI(percentage);
    }
  });

  retriggerBtn.addEventListener("click", resetScan);

  // Initial Start
  animate();
})();
