
function toggleTheme(){
  var r=document.documentElement,n=r.getAttribute('data-theme')==='dark'?'light':'dark';
  r.setAttribute('data-theme',n);try{localStorage.setItem('pantheon-theme',n)}catch(e){}
}
(function(){
  var t=null;try{t=localStorage.getItem('pantheon-theme')}catch(e){}
  if(!t)t=document.documentElement.getAttribute('data-theme');
  if(!t)t=(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light';
  document.documentElement.setAttribute('data-theme',t);
})();
/* nav solid on scroll */
var nav=document.getElementById('nav');

/* reveal */
if('IntersectionObserver' in window){
  var io=new IntersectionObserver(function(es){es.forEach(function(e){if(e.isIntersecting){e.target.classList.add('in');io.unobserve(e.target)}})},{threshold:.12});
  document.querySelectorAll('.rv').forEach(function(el){io.observe(el)});
}else{
  document.querySelectorAll('.rv').forEach(function(el){el.classList.add('in')});
}
/* oracle */
var Q=["מי ששואל - כבר החל את המסע. מי שבטוח - עצר מזמן.","הידע אינו נאגר בכדים. הוא נאגר במעשים שחוזרים על עצמם.","אל תבקש דרך קצרה. בקש רגליים שאינן מתעייפות.","הארכיון הגדול ביותר הוא הזיכרון של מי שהקשיב באמת.","עמוד יחיד אינו מקדש. אך בלעדיו - הגג נופל.","שאל פעמיים. כתוב פעם אחת. קרא שוב אחרי שנה."],qi=0;
function askOracle(){
  var el=document.getElementById('oq'),n;if(!el)return;
  do{n=Math.floor(Math.random()*Q.length)}while(n===qi);
  qi=n;el.classList.add('fade');
  setTimeout(function(){el.textContent='"'+Q[n]+'"';el.classList.remove('fade')},320);
}

/* reading progress */
var pb=document.querySelector('.progress');
if(pb){var onS=function(){var h=document.documentElement,m=h.scrollHeight-h.clientHeight;pb.style.width=(m>0?(h.scrollTop/m)*100:0)+'%'};addEventListener('scroll',onS,{passive:true});onS();}
/* optional client-only archive tabs (the WordPress archive uses real category links) */
var tabs=document.querySelectorAll('.tab[data-client-filter]'),ents=document.querySelectorAll('.entry[data-cat]');
if(tabs.length&&ents.length){
  function sel(c){tabs.forEach(function(t){t.setAttribute('aria-selected',t.dataset.cat===c?'true':'false')});
    ents.forEach(function(e){e.style.display=(c==='all'||e.dataset.cat===c)?'':'none'})}
  tabs.forEach(function(t){t.addEventListener('click',function(e){e.preventDefault();sel(t.dataset.cat)})});
}

/* contact segmented controls */
document.querySelectorAll('.seg').forEach(function(seg){
  seg.querySelectorAll('button').forEach(function(b){b.addEventListener('click',function(){
    seg.querySelectorAll('button').forEach(function(x){x.setAttribute('aria-pressed','false')});
    b.setAttribute('aria-pressed','true');
    var form=seg.closest('form'),target=form?form.querySelector('[data-hapantheon-contact-type]'):null;
    if(target)target.value=b.getAttribute('data-contact-type')||b.textContent.trim();
  })})
});

/* copy-link controls */
document.querySelectorAll('[data-copy-url]').forEach(function(button){
  button.addEventListener('click',function(){
    var value=button.getAttribute('data-copy-url')||location.href;
    if(navigator.clipboard&&navigator.clipboard.writeText){
      navigator.clipboard.writeText(value).then(function(){
        button.classList.add('copied');
        button.setAttribute('data-copy-label',(window.hapantheonData&&hapantheonData.copySuccess)||'Link copied');
        setTimeout(function(){button.classList.remove('copied')},1400);
      }).catch(function(){});
    }
  });
});

/* ===== search modal ===== */
var sm=document.getElementById('smodal');
function openSearch(){if(!sm)return;sm.classList.add('open');document.body.classList.add('modal-open');
  setTimeout(function(){var i=sm.querySelector('input');if(i)i.focus()},120)}
function closeSearch(){if(!sm)return;sm.classList.remove('open');document.body.classList.remove('modal-open')}
document.querySelectorAll('.search-btn').forEach(function(b){b.addEventListener('click',openSearch)});
if(sm){
  sm.addEventListener('click',function(e){if(e.target===sm)closeSearch()});
  sm.querySelector('.smodal-close').addEventListener('click',closeSearch);
  addEventListener('keydown',function(e){
    if(e.key==='Escape')closeSearch();
    if(e.key==='/'&&!sm.classList.contains('open')&&!/INPUT|TEXTAREA/.test(document.activeElement.tagName)){e.preventDefault();openSearch()}
  });
  /* The native WordPress search form submits directly to the site. */
}
/* ===== mobile menu ===== */
var mm=document.getElementById('mmodal');
function openMenu(){if(!mm)return;
  var src=document.querySelector('.nav .links');
  if(src)mm.querySelector('.mm-links').innerHTML=src.innerHTML;
  mm.querySelectorAll('.mm-links a').forEach(function(a){a.addEventListener('click',closeMenu)});
  mm.classList.add('open');document.body.classList.add('modal-open');}
function closeMenu(){if(!mm)return;mm.classList.remove('open');document.body.classList.remove('modal-open');}
document.querySelectorAll('.burger').forEach(function(b){b.addEventListener('click',openMenu)});
if(mm){
  mm.querySelector('.mm-close').addEventListener('click',closeMenu);
  mm.querySelector('.mm-search').addEventListener('click',function(){closeMenu();setTimeout(openSearch,80)});
  mm.querySelector('.mm-theme').addEventListener('click',toggleTheme);
  addEventListener('keydown',function(e){if(e.key==='Escape')closeMenu()});
}

/* ===== V5 ===== */

/* countup - מספרים רצים בחשיפה ראשונה */
(function(){
  var els=document.querySelectorAll('[data-count]');if(!els.length)return;
  function fmt(v,k){if(k==='k'&&v>=1000)return (v/1000).toFixed(1).replace(/\.0$/,'')+'K';return Math.round(v).toLocaleString('en-US')}
  function animate(el){
    var target=parseFloat(el.dataset.count),k=el.dataset.fmt,t0=null,dur=1600;
    if(matchMedia('(prefers-reduced-motion: reduce)').matches||document.documentElement.classList.contains('acc-motion')){el.textContent=fmt(target,k);return}
    function step(t){if(!t0)t0=t;var p=Math.min((t-t0)/dur,1);p=1-Math.pow(1-p,3);
      el.textContent=fmt(target*p,k);if(p<1)requestAnimationFrame(step)}
    requestAnimationFrame(step);
  }
  if(!('IntersectionObserver' in window)){els.forEach(animate);return}
  var cio=new IntersectionObserver(function(es){es.forEach(function(e){
    if(!e.isIntersecting)return;cio.unobserve(e.target);animate(e.target);
  })},{threshold:.4});
  els.forEach(function(el){cio.observe(el)});
})();

/* 10 הגדולים - טאבים */
(function(){
  var tabs=document.querySelectorAll('.t10tab');if(!tabs.length)return;
  tabs.forEach(function(t){t.addEventListener('click',function(){
    tabs.forEach(function(x){x.setAttribute('aria-selected','false')});
    t.setAttribute('aria-selected','true');
    document.querySelectorAll('.t10-panel').forEach(function(p){p.classList.toggle('act',p.id===t.dataset.panel)});
  })});
})();

/* היירו מובייל - סליידשואו עם אותיות יווניות */
(function(){
  var pag=document.querySelector('.gate-pag'),slices=document.querySelectorAll('.gate .slice');
  if(!pag||!slices.length)return;
  var letters=['\u0391','\u0392','\u0393','\u0394','\u0395'],cur=0,timer=null,DUR=6000,mob=matchMedia('(max-width:760px)');
  document.documentElement.style.setProperty('--slide-ms',DUR+'ms');
  slices.forEach(function(s,i){
    var b=document.createElement('button');
    b.type='button';b.textContent=letters[i]||(i+1);
    b.setAttribute('aria-label','אולם '+(i+1));
    b.addEventListener('click',function(){go(i,true)});
    pag.appendChild(b);
  });
  var btns=pag.querySelectorAll('button');
  function go(i,manual){
    cur=i;
    slices.forEach(function(s,j){s.classList.toggle('act',j===i)});
    btns.forEach(function(b,j){b.setAttribute('aria-current',j===i?'true':'false')});
    if(manual)restart();
  }
  function next(){go((cur+1)%slices.length)}
  function restart(){clearInterval(timer);
    if(!matchMedia('(prefers-reduced-motion: reduce)').matches&&!document.documentElement.classList.contains('acc-motion'))
      timer=setInterval(next,DUR)}
  function apply(){
    if(mob.matches){go(0);restart()}
    else{clearInterval(timer);slices.forEach(function(s){s.classList.remove('act')})}
  }
  mob.addEventListener?mob.addEventListener('change',apply):mob.addListener(apply);
  apply();
  /* swipe - גרירה לצדדים (מגע + עכבר) */
  var track=document.querySelector('.gate-track');
  var px=null,swiped=false;
  track.addEventListener('dragstart',function(e){e.preventDefault()});
  track.addEventListener('pointerdown',function(e){
    if(!mob.matches)return;
    px=e.clientX;swiped=false;
  });
  addEventListener('pointerup',function(e){
    if(px===null||!mob.matches)return;
    var dx=e.clientX-px;px=null;
    if(Math.abs(dx)<40)return;
    swiped=true;
    go(dx>0?(cur+1)%slices.length:(cur-1+slices.length)%slices.length,true); /* RTL */
  });
  addEventListener('pointercancel',function(){px=null});
  /* גרירה לא מפעילה ניווט */
  track.addEventListener('click',function(e){
    if(swiped){e.preventDefault();e.stopPropagation();swiped=false}
  },true);
})();

/* ארכיון - מחליף תצוגות */
(function(){
  var sw=document.querySelector('.view-switch');if(!sw)return;
  var grid=document.querySelector('.entries'),btns=sw.querySelectorAll('.vbtn');
  var saved=null;try{saved=localStorage.getItem('pantheon-view')}catch(e){}
  function set(v){
    grid.classList.remove('v-list','v-masonry');
    if(v==='list')grid.classList.add('v-list');
    if(v==='masonry')grid.classList.add('v-masonry');
    btns.forEach(function(b){b.setAttribute('aria-pressed',b.dataset.view===v?'true':'false')});
    try{localStorage.setItem('pantheon-view',v)}catch(e){}
  }
  btns.forEach(function(b){b.addEventListener('click',function(){set(b.dataset.view)})});
  if(saved&&saved!=='cards')set(saved);
})();

/* ===== ממשק נגישות מובנה ===== */
(function(){
  var OPTS=[
    {k:'font1',t:'הגדלת טקסט',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 18 10 5l6 13M6.2 14h7.6M18 9v8M14.5 13H21.5" stroke-width="1.9"/></svg>'},
    {k:'font2',t:'טקסט גדול מאוד',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 19 9 4l6 15M5.2 14.5h7.6M17 8v10M12.8 13H21.2"/></svg>'},
    {k:'contrast',t:'ניגודיות גבוהה',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9"><circle cx="12" cy="12" r="9"/><path d="M12 3v18A9 9 0 0 0 12 3Z" fill="currentColor"/></svg>'},
    {k:'gray',t:'גווני אפור',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M12 3c-4 5-7 8.2-7 12a7 7 0 0 0 14 0c0-3.8-3-7-7-12Z"/><path d="M12 21V7"/></svg>'},
    {k:'links',t:'הדגשת קישורים',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M10 14a4 4 0 0 0 6 .5l3-3a4 4 0 0 0-5.7-5.7l-1.6 1.6"/><path d="M14 10a4 4 0 0 0-6-.5l-3 3a4 4 0 0 0 5.7 5.7l1.6-1.6"/></svg>'},
    {k:'motion',t:'עצירת אנימציות',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><rect x="7" y="5" width="3.4" height="14" rx="1"/><rect x="13.6" y="5" width="3.4" height="14" rx="1"/></svg>'},
    {k:'readable',t:'גופן קריא',svg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6h16M4 12h16M4 18h10"/></svg>'}
  ];
  var saved={};try{saved=JSON.parse(localStorage.getItem('pantheon-a11y')||'{}')}catch(e){}
  Object.keys(saved).forEach(function(k){if(saved[k])document.documentElement.classList.add('acc-'+k)});
  /* font1/font2 mutual exclusion on load handled by save logic */

  var btn=document.createElement('button');
  btn.className='a11y-btn';btn.type='button';
  btn.setAttribute('aria-label','פתיחת תפריט נגישות');btn.setAttribute('aria-haspopup','dialog');
  btn.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="5" r="1.6" fill="currentColor" stroke="none"/><path d="M5 8.5c2.3.8 4.6 1.2 7 1.2s4.7-.4 7-1.2M12 9.7v4.1M12 13.8 9 20M12 13.8 15 20"/></svg>';

  var panel=document.createElement('div');
  panel.className='a11y-panel';panel.setAttribute('role','dialog');panel.setAttribute('aria-label','הגדרות נגישות');
  var h='<h3>הגדרות נגישות<button type="button" class="a11y-close" aria-label="סגירה"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg></button></h3><div class="a11y-grid">';
  OPTS.forEach(function(o){
    h+='<button type="button" class="a11y-opt" data-acc="'+o.k+'" aria-pressed="'+(saved[o.k]?'true':'false')+'">'+o.svg+o.t+'</button>';
  });
  h+='</div><button type="button" class="a11y-reset">איפוס הגדרות</button><p class="a11y-note"><a href="#">להצהרת הנגישות המלאה</a></p>';
  panel.innerHTML=h;
  var statement=panel.querySelector('.a11y-note a');
  if(statement&&window.hapantheonData&&hapantheonData.accessibilityUrl)statement.href=hapantheonData.accessibilityUrl;
  document.body.appendChild(btn);document.body.appendChild(panel);

  function save(){try{localStorage.setItem('pantheon-a11y',JSON.stringify(saved))}catch(e){}}
  btn.addEventListener('click',function(){panel.classList.toggle('open')});
  panel.querySelector('.a11y-close').addEventListener('click',function(){panel.classList.remove('open')});
  addEventListener('keydown',function(e){if(e.key==='Escape')panel.classList.remove('open')});
  document.addEventListener('click',function(e){if(!panel.contains(e.target)&&!btn.contains(e.target))panel.classList.remove('open')});
  panel.querySelectorAll('.a11y-opt').forEach(function(o){
    o.addEventListener('click',function(){
      var k=o.dataset.acc,on=!saved[k];
      /* גדלי גופן - בלעדיים זה לזה */
      if(on&&(k==='font1'||k==='font2')){
        var other=k==='font1'?'font2':'font1';
        saved[other]=false;document.documentElement.classList.remove('acc-'+other);
        var ob=panel.querySelector('[data-acc="'+other+'"]');if(ob)ob.setAttribute('aria-pressed','false');
      }
      saved[k]=on;
      document.documentElement.classList.toggle('acc-'+k,on);
      o.setAttribute('aria-pressed',on?'true':'false');
      save();
    });
  });
  panel.querySelector('.a11y-reset').addEventListener('click',function(){
    Object.keys(saved).forEach(function(k){document.documentElement.classList.remove('acc-'+k)});
    saved={};save();
    panel.querySelectorAll('.a11y-opt').forEach(function(o){o.setAttribute('aria-pressed','false')});
  });
})();

/* ===== שו"ת: פתיחה יחידה + טאבים ===== */
(function(){
  var faqs=document.querySelectorAll('.faq-wrap .faq');if(!faqs.length)return;
  faqs.forEach(function(d){
    d.querySelector('summary').addEventListener('click',function(){
      faqs.forEach(function(o){if(o!==d)o.removeAttribute('open')});
    });
  });
  var ftabs=document.querySelectorAll('.faq-tabs .tab');
  ftabs.forEach(function(t){t.addEventListener('click',function(){
    ftabs.forEach(function(x){x.setAttribute('aria-selected','false')});
    t.setAttribute('aria-selected','true');
    var c=t.dataset.fcat,first=true;
    faqs.forEach(function(f){
      var show=(c==='all'||f.dataset.fcat===c);
      f.hidden=!show;f.removeAttribute('open');
      if(show&&first){f.setAttribute('open','');first=false}
    });
  })});
})();

/* ===== V5.2 ===== */

/* חדרי הפנתאון - גרירה בעכבר/מגע */
(function(){
  var g=document.querySelector('.rooms-grid');if(!g)return;
  var down=false,startX=0,startS=0,moved=false;
  g.addEventListener('dragstart',function(e){e.preventDefault()});
  g.addEventListener('pointerdown',function(e){
    if(innerWidth>760)return;
    down=true;moved=false;startX=e.clientX;startS=g.scrollLeft;
  });
  addEventListener('pointermove',function(e){
    if(!down)return;
    var dx=e.clientX-startX;
    if(Math.abs(dx)>6){moved=true;g.classList.add('dragging')}
    if(moved)g.scrollLeft=startS-dx;
  });
  addEventListener('pointerup',function(){
    if(!down)return;down=false;
    g.classList.remove('dragging');
  });
  g.addEventListener('click',function(e){if(moved){e.preventDefault();e.stopPropagation();moved=false}},true);
})();

/* טאבים - גלילת הטאב הפעיל למרכז במובייל (כל האתר) */
(function(){
  document.querySelectorAll('.t10tab, .tabs .tab').forEach(function(t){
    t.addEventListener('click',function(){
      if(innerWidth<=760&&t.scrollIntoView)t.scrollIntoView({behavior:'smooth',inline:'center',block:'nearest'});
    });
  });
})();

/* גלריית מתכון - לייטבוקס */
(function(){
  var frames=document.querySelectorAll('.gframe');if(!frames.length)return;
  var lb=document.createElement('div');lb.className='lightbox';lb.setAttribute('role','dialog');lb.setAttribute('aria-label','תצוגת תמונה');
  lb.innerHTML='<button class="lb-close" type="button" aria-label="סגירה"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg></button><img alt=""><figcaption></figcaption>';
  document.body.appendChild(lb);
  var img=lb.querySelector('img'),cap=lb.querySelector('figcaption');
  function close(){lb.classList.remove('open');document.body.classList.remove('modal-open')}
  frames.forEach(function(f){f.addEventListener('click',function(){
    var i=f.querySelector('img');
    img.src=i.src.replace('w=500','w=1400');img.alt=i.alt;
    cap.textContent=(f.querySelector('figcaption')||{}).textContent||'';
    lb.classList.add('open');document.body.classList.add('modal-open');
  })});
  lb.querySelector('.lb-close').addEventListener('click',close);
  lb.addEventListener('click',function(e){if(e.target===lb)close()});
  addEventListener('keydown',function(e){if(e.key==='Escape')close()});
})();

/* כתבה עם סייד-בר - סקרולספיי לתוכן עניינים */
(function(){
  var links=document.querySelectorAll('.toc a');if(!links.length)return;
  var map=[];
  links.forEach(function(a){
    var id=a.getAttribute('href').slice(1),el=document.getElementById(id);
    if(el)map.push({a:a,el:el});
  });
  function top(el){return el.getBoundingClientRect().top+scrollY}
  function spy(){
    var y=scrollY+160,best=map[0];
    map.forEach(function(m){if(top(m.el)<=y)best=m});
    map.forEach(function(m){m.a.classList.toggle('on',m===best)});
  }
  addEventListener('scroll',spy,{passive:true});spy();
})();

/* פס פעולות צף בכתבות */
(function(){
  var fb=document.querySelector('.float-bar');if(!fb)return;
  addEventListener('scroll',function(){fb.classList.toggle('show',scrollY>500)},{passive:true});
  var cp=fb.querySelector('[data-fb="copy"]');
  if(cp)cp.addEventListener('click',function(){
    var value=cp.getAttribute('data-copy-url')||location.href;
    if(navigator.clipboard)navigator.clipboard.writeText(value);
    cp.style.color='var(--teal)';setTimeout(function(){cp.style.color=''},1200);
  });
  var up=fb.querySelector('[data-fb="top"]');
  if(up)up.addEventListener('click',function(){scrollTo({top:0,behavior:'smooth'})});
})();

/* וידאו מתכון - טעינה בלחיצה */
function playRecipeVideo(el){
  var id=el.dataset.yt;
  el.innerHTML='<iframe src="https://www.youtube-nocookie.com/embed/'+id+'?autoplay=1&rel=0" title="סרטון הכנה" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
  el.style.cursor='default';
}
