 
/* ==========================================================================
   SITE HEADER HAMBURGER MENU
   ========================================================================== */

/**
 * EverWardrobe Navigation Script
 * Handles hamburger menu toggle functionality
 */

function initHamburger() {
    const hamburger = document.querySelector('.site-header .hamburger');
    const nav = document.querySelector('.site-header .primary-nav');
  
    if (!hamburger || !nav) return;
  
    // Initialize aria-expanded attributes
    hamburger.setAttribute('aria-expanded', 'false');
    nav.setAttribute('aria-expanded', 'false');
  
    // Toggle navigation on hamburger click
    hamburger.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      const isExpanded = hamburger.getAttribute('aria-expanded') === 'true';
      
      hamburger.setAttribute('aria-expanded', !isExpanded);
      nav.setAttribute('aria-expanded', !isExpanded);
    });
  
    // Close menu when a nav link is clicked
    const navLinks = nav.querySelectorAll('a');
    navLinks.forEach(link => {
      link.addEventListener('click', function() {
        hamburger.setAttribute('aria-expanded', 'false');
        nav.setAttribute('aria-expanded', 'false');
      });
    });
  
    // Close menu when clicking outside
    document.addEventListener('click', function(event) {
      const isClickInsideHeader = event.target.closest('.site-header');
      
      if (!isClickInsideHeader && hamburger.getAttribute('aria-expanded') === 'true') {
        hamburger.setAttribute('aria-expanded', 'false');
        nav.setAttribute('aria-expanded', 'false');
      }
    });
  }
  
  // Initialize on DOM ready or immediately if already loaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initHamburger);
  } else {
    initHamburger();
  }
/* ==========================================================================
      CAPSULE ROOM FUNCTIONALITY — Shared across all persona capsule pages
      ========================================================================== */
      (() => {
        const page = document.getElementById('capsule-persona');
        if (!page) return;
        
        const tabsContainer = page.querySelector('[data-capsule="cap-tabs"]');
        const tabs = Array.from(tabsContainer.querySelectorAll('button[role="tab"]'));
        const panels = Array.from(page.querySelectorAll('section[data-capsule="cap-theme"]'));
        
        const themeOf = (tab) => tab?.getAttribute('data-theme') || 'everyday';
        
        // ARIA wiring
        tabs.forEach((tab) => {
          const theme = themeOf(tab);
          const panel = panels.find(p => p.getAttribute('data-theme') === theme);
          if (panel) {
            const id = panel.id || `cap-panel-${theme}`;
            panel.id = id;
            tab.setAttribute('aria-controls', id);
          }
        });
        
        const activeTab = () => tabs.find(t => t.getAttribute('aria-selected') === 'true') || tabs[0];
        
        function showTheme(theme, { focus = false } = {}) {
          tabs.forEach(t => t.setAttribute('aria-selected', String(themeOf(t) === theme)));
          panels.forEach(p => { p.hidden = !(theme === 'all' || p.getAttribute('data-theme') === theme); });
          
          const url = new URL(location.href);
          if (theme === 'all') url.searchParams.delete('theme');
          else url.searchParams.set('theme', theme);
          history.replaceState({}, '', url);
          
          if (focus) {
            const t = tabs.find(x => themeOf(x) === theme);
            if (t) t.focus();
          }
        }
        
        tabs.forEach(t => t.addEventListener('click', () => showTheme(themeOf(t))));
        
        tabsContainer.addEventListener('keydown', (e) => {
          const i = tabs.indexOf(activeTab());
          if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
            e.preventDefault();
            showTheme(themeOf(tabs[(i + 1) % tabs.length]), { focus: true });
          }
          if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
            e.preventDefault();
            showTheme(themeOf(tabs[(i - 1 + tabs.length) % tabs.length]), { focus: true });
          }
          if (e.key === 'Home') {
            e.preventDefault();
            showTheme(themeOf(tabs[0]), { focus: true });
          }
          if (e.key === 'End') {
            e.preventDefault();
            showTheme(themeOf(tabs[tabs.length - 1]), { focus: true });
          }
        });
        
        // initial from URL
        const initial = new URLSearchParams(location.search).get('theme') || 'everyday';
        showTheme(initial);
      })();

/* =========================================================
   EverWardrobe Quiz — JS helpers (semantic alignment)
   - Multi-select caps (data-max-select)
   - Quote card equal heights
   - Toggleable radios (click again to deselect) + dim reset
   - Fallback for browsers without :has() to enable Next buttons
   ========================================================= */
   "use strict";

   /* -----------------------------------------
      1) MULTI-SELECT CAPS — enforce per section
   ----------------------------------------- */
   (function () {
     function initSection(section) {
       const max = parseInt(section.getAttribute("data-max-select"), 10) || Infinity;
       const inputs = Array.from(section.querySelectorAll('.options input[type="checkbox"]'));
       if (!inputs.length) return;
   
       let live = section.querySelector(".live-max-select");
       if (!live) {
         live = document.createElement("div");
         live.className = "live-max-select";
         live.setAttribute("aria-live", "polite");
         Object.assign(live.style, {
           position: "absolute",
           width: "1px",
           height: "1px",
           margin: "-1px",
           border: "0",
           padding: "0",
           clip: "rect(0 0 0 0)",
           overflow: "hidden",
         });
         section.appendChild(live);
       }
   
       const update = () => {
         const checked = inputs.filter((i) => i.checked);
         const count = checked.length;
   
         inputs.forEach((input) => {
           const shouldDisable = !input.checked && count >= max;
           input.disabled = shouldDisable;
           input.setAttribute("aria-disabled", shouldDisable ? "true" : "false");
         });
   
         live.textContent =
           count >= max ? `You can pick up to ${max} options in this question.` : "";
       };
   
       inputs.forEach((input) => input.addEventListener("change", update));
       update();
     }
   
     function initMultiSelectCaps() {
       document
         .querySelectorAll(".quiz-section.multi-select[data-max-select]")
         .forEach(initSection);
     }
   
     if (document.readyState === "loading") {
       document.addEventListener("DOMContentLoaded", initMultiSelectCaps);
     } else {
       initMultiSelectCaps();
     }
   })();
   
   /* -----------------------------------------
      2) QUOTE CARD EQUAL HEIGHTS — .quiz-section--quotes
   ----------------------------------------- */
   (function () {
     const SECTIONS = () =>
       Array.from(document.querySelectorAll(".quiz-section--quotes"));
   
     function equalizeSection(section) {
       const cards = Array.from(section.querySelectorAll(".quote-card"));
       if (!cards.length) return;
   
       section.style.removeProperty("--quote-card-min-h");
   
       let max = 0;
       cards.forEach((c) => {
         c.style.minHeight = "";
         const h = c.getBoundingClientRect().height;
         if (h > max) max = h;
       });
   
       section.style.setProperty("--quote-card-min-h", Math.ceil(max) + "px");
     }
   
     function run() {
       SECTIONS().forEach(equalizeSection);
     }
   
     function onReady() {
       run();
       window.addEventListener(
         "resize",
         (() => { let t; return () => { clearTimeout(t); t = setTimeout(run, 120); }; })()
       );
       if (document.fonts && document.fonts.ready) {
         document.fonts.ready.then(run).catch(() => {});
       }
     }
   
     if (document.readyState === "loading") {
       document.addEventListener("DOMContentLoaded", onReady);
     } else {
       onReady();
     }
   })();
   
   
   
   /* -----------------------------------------
      4) :has() FALLBACK — enable Next buttons if :has is unsupported
   ----------------------------------------- */
   (function () {
     const HAS_SUPPORT =
       typeof CSS !== "undefined" && CSS.supports?.("selector(:has(*))");
   
     if (HAS_SUPPORT) return;
   
     function initSection(section) {
       const nextBtn = section.querySelector(".nav-buttons a:last-child");
       if (!nextBtn) return;
   
       const inputs = Array.from(
         section.querySelectorAll('.options input[type="checkbox"], .options input[type="radio"]')
       );
       if (!inputs.length) return;
   
       const update = () => {
         const anyChecked = inputs.some((i) => i.checked);
         if (anyChecked) {
           nextBtn.style.pointerEvents = "auto";
           nextBtn.style.opacity = "1";
           nextBtn.setAttribute("aria-disabled", "false");
           nextBtn.removeAttribute("tabindex");
         } else {
           nextBtn.style.pointerEvents = "none";
           nextBtn.style.opacity = ".55";
           nextBtn.setAttribute("aria-disabled", "true");
           nextBtn.setAttribute("tabindex", "-1");
         }
       };
   
       inputs.forEach((i) => i.addEventListener("change", update));
       update();
     }
   
     function onReady() {
       document.querySelectorAll(".quiz-section").forEach(initSection);
     }
   
     if (document.readyState === "loading") {
       document.addEventListener("DOMContentLoaded", onReady);
     } else {
       onReady();
     }
   })();
   
   /* Single-select radios: allow deselect on second click/tap or Space/Enter.
      Works even when inputs are hidden with pointer-events:none (label click).
   */
   (() => {
     const root = document.getElementById('quiz-page');
   
     // Mark if the radio was checked at pointer down time
     root.addEventListener('pointerdown', (e) => {
       const label = e.target.closest('label');
       if (!label) return;
       const radio = label.querySelector('input[type="radio"]');
       if (!radio) return;
       if (!radio.closest('.quiz-section.single-select')) return;
       radio.dataset.wasChecked = radio.checked ? '1' : '';
     }, true);
   
     // If it was already checked, cancel the label's default toggle and uncheck
     root.addEventListener('click', (e) => {
       const label = e.target.closest('label');
       const radio = label ? label.querySelector('input[type="radio"]')
                           : e.target.closest('input[type="radio"]');
       if (!radio) return;
       if (!radio.closest('.quiz-section.single-select')) return;
   
       if (radio.dataset.wasChecked === '1') {
         e.preventDefault();                  // <-- stop label from re-checking it
         radio.checked = false;
         radio.dispatchEvent(new Event('change', { bubbles: true }));
       }
       delete radio.dataset.wasChecked;
     }, true);
   
     // Keyboard: Space/Enter while focused on a checked radio should uncheck
     root.addEventListener('keydown', (e) => {
       const radio = e.target.closest('input[type="radio"]');
       if (!radio) return;
       if (!radio.closest('.quiz-section.single-select')) return;
   
       if ((e.key === ' ' || e.key === 'Spacebar' || e.key === 'Enter') && radio.checked) {
         e.preventDefault();
         radio.checked = false;
         radio.dispatchEvent(new Event('change', { bubbles: true }));
       }
     }, true);
   })();

   /* =========================================================
      5) SCORING SYSTEM — calculate persona scores & redirect
      ========================================================= */
   (function () {
     const PERSONA_MAP = {
       street_muse: { slug: 'street-muse', bodyId: 'persona-result-street-muse', label: 'Street Muse' },
       style_rebel: { slug: 'style-rebel', bodyId: 'persona-result-style-rebel', label: 'Style Rebel' },
       effortlessly_polished: { slug: 'effortlessly-polished', bodyId: 'persona-result-effortlessly-polished', label: 'Effortlessly Polished' },
       romantic_dreamer: { slug: 'romantic-dreamer', bodyId: 'persona-result-romantic-dreamer', label: 'Romantic Dreamer' }
     };
   
     const submitBtn = document.getElementById('submit-btn');
     if (!submitBtn) return;
   
     submitBtn.addEventListener('click', function (e) {
       e.preventDefault();
   
       // Collect all checked inputs
       const inputs = Array.from(
         document.querySelectorAll('.quiz-section input[type="radio"]:checked, .quiz-section input[type="checkbox"]:checked')
       );
   
       // Initialize scores
       const scores = {
         street_muse: 0,
         style_rebel: 0,
         effortlessly_polished: 0,
         romantic_dreamer: 0
       };
   
       // Sum up points from each checked input
       // Point system: primary persona +3, secondary persona +1, others +0
       inputs.forEach((input) => {
         Object.keys(scores).forEach((persona) => {
           const attrName = `data-${persona}`;
           const points = parseInt(input.getAttribute(attrName), 10) || 0;
           scores[persona] += points;
         });
       });
   
       // Calculate total and percentages
       const total = Object.values(scores).reduce((sum, val) => sum + val, 0);
       const percentages = {};
       Object.keys(scores).forEach((persona) => {
         percentages[persona] = total > 0 ? Math.round((scores[persona] / total) * 100) : 0;
       });
   
       // Find the persona with the highest score
       const winnerPersona = Object.keys(scores).reduce((prev, current) =>
         scores[current] > scores[prev] ? current : prev
       );
   
       // Store results in sessionStorage
       sessionStorage.setItem('quizScores', JSON.stringify(scores));
       sessionStorage.setItem('quizPercentages', JSON.stringify(percentages));
       sessionStorage.setItem('winnerPersona', winnerPersona);
   
       // Redirect to persona results page
       const slug = PERSONA_MAP[winnerPersona].slug;
       window.location.href = `personas/${slug}.html`;
     });
   })();
  
   /* Capsule Room — minimal behavior + row alignment (scoped) */
(function () {
    const scope = document.getElementById('capsule-room');
    if (!scope) return;
  
    // Visual active state (purely cosmetic)
    scope.querySelectorAll('.capsule-grid > li > a').forEach(card => {
      card.addEventListener('pointerenter', () => card.classList.add('is-active'), { passive: true });
      card.addEventListener('pointerleave', () => card.classList.remove('is-active'), { passive: true });
      card.addEventListener('focus', () => card.classList.add('is-active'));
      card.addEventListener('blur',  () => card.classList.remove('is-active'));
    });
  
    // Row synchronizer: aligns hero start across cards in the same row
    function syncRows() {
      const list = scope.querySelector('.capsule-grid');
      if (!list) return;
  
      list.querySelectorAll('.previews').forEach(p => p.style.removeProperty('--head-gap-comp'));
  
      const items = Array.from(list.children);
      if (!items.length) return;
  
      const rows = [];
      const TOL = 3; // px tolerance
      items.forEach(li => {
        const top = Math.round(li.getBoundingClientRect().top);
        let row = rows.find(r => Math.abs(r.top - top) <= TOL);
        if (!row) rows.push(row = { top, items: [] });
        row.items.push(li);
      });
  
      rows.forEach(row => {
        let maxBlock = 0;
        row.items.forEach(li => {
          const head = li.querySelector('header');
          const prev = li.querySelector('.previews');
          if (!head || !prev) return;
          const hTop = head.getBoundingClientRect().top;
          const pBot = prev.getBoundingClientRect().bottom;
          maxBlock = Math.max(maxBlock, pBot - hTop);
        });
  
        row.items.forEach(li => {
          const head = li.querySelector('header');
          const prev = li.querySelector('.previews');
          if (!head || !prev) return;
          const hTop = head.getBoundingClientRect().top;
          const pBot = prev.getBoundingClientRect().bottom;
          const diff = Math.max(0, Math.round(maxBlock - (pBot - hTop)));
          prev.style.setProperty('--head-gap-comp', diff + 'px');
        });
      });
    }
  
    let raf, to;
    const requestSync = () => {
      clearTimeout(to);
      to = setTimeout(() => {
        cancelAnimationFrame(raf);
        raf = requestAnimationFrame(syncRows);
      }, 60);
    };
  
    // lifecycle + assets
    window.addEventListener('load', requestSync);
    if (document.fonts?.ready) document.fonts.ready.then(requestSync);
  
    scope.querySelectorAll('.capsule-grid img').forEach(img => {
      if (!img.complete) {
        img.addEventListener('load', requestSync, { once: true });
        img.addEventListener('error', requestSync, { once: true });
      }
    });
  
    window.addEventListener('resize', requestSync);
    window.addEventListener('orientationchange', requestSync);
  
    const grid = scope.querySelector('.capsule-grid');
    if (grid && 'ResizeObserver' in window) {
      const ro = new ResizeObserver(requestSync);
      ro.observe(grid);
    }
  })();
  /* =========================================================
   5) SCORING SYSTEM — calculate persona scores & redirect
   ========================================================= */
(function () {
    const PERSONA_MAP = {
      street_muse: { slug: 'street-muse', bodyId: 'persona-result-street-muse', label: 'Street Muse' },
      style_rebel: { slug: 'style-rebel', bodyId: 'persona-result-style-rebel', label: 'Style Rebel' },
      effortlessly_polished: { slug: 'effortlessly-polished', bodyId: 'persona-result-effortlessly-polished', label: 'Effortlessly Polished' },
      romantic_dreamer: { slug: 'romantic-dreamer', bodyId: 'persona-result-romantic-dreamer', label: 'Romantic Dreamer' }
    };
  
    const submitBtn = document.getElementById('submit-btn');
    if (!submitBtn) return;
  
    submitBtn.addEventListener('click', function (e) {
      e.preventDefault();
  
      // Collect all checked inputs
      const inputs = Array.from(
        document.querySelectorAll('.quiz-section input[type="radio"]:checked, .quiz-section input[type="checkbox"]:checked')
      );
  
      // Initialize scores
      const scores = {
        street_muse: 0,
        style_rebel: 0,
        effortlessly_polished: 0,
        romantic_dreamer: 0
      };
  
      // Sum up points from each checked input
      inputs.forEach((input) => {
        Object.keys(scores).forEach((persona) => {
          const attrName = `data-${persona}`;
          const points = parseInt(input.getAttribute(attrName), 10) || 0;
          scores[persona] += points;
        });
      });
  
      // Calculate total and percentages
      const total = Object.values(scores).reduce((sum, val) => sum + val, 0);
      const percentages = {};
      Object.keys(scores).forEach((persona) => {
        percentages[persona] = total > 0 ? Math.round((scores[persona] / total) * 100) : 0;
      });
  
      // Find the persona with the highest score
      const winnerPersona = Object.keys(scores).reduce((prev, current) =>
        scores[current] > scores[prev] ? current : prev
      );
  
      // Store results in sessionStorage
      sessionStorage.setItem('quizScores', JSON.stringify(scores));
      sessionStorage.setItem('quizPercentages', JSON.stringify(percentages));
      sessionStorage.setItem('winnerPersona', winnerPersona);
  
      // Redirect to persona results page
      const slug = PERSONA_MAP[winnerPersona].slug;
      window.location.href = `personas/${slug}.php`;  // ✅ Changed to .php
    });
  })();