(function(){
  const init = (box) => {
    const navBtns = box.querySelectorAll('.vcb-tabs__nav button');
    const panes   = box.querySelectorAll('.vcb-pane');

    const activate = (key, pushHash = false) => {
      navBtns.forEach(b => b.classList.toggle('is-active', b.dataset.tab === key));
      panes.forEach(p => p.classList.toggle('is-active', p.id === 'vcb-pane-' + key));
      if (pushHash) history.replaceState(null, '', '#' + key);
    };

    // 初期表示（URL #line/#photo/#catalog に対応）
    const initKey = (location.hash || '#line').replace('#','');
    const validKey = ['line','photo','catalog'].includes(initKey) ? initKey : 'line';
    activate(validKey, false);

    // クリック / キーボード操作
    navBtns.forEach(btn => {
      btn.setAttribute('role','tab');
      btn.addEventListener('click', () => activate(btn.dataset.tab, true));
      btn.addEventListener('keydown', (e) => {
        if (!['ArrowRight','ArrowLeft'].includes(e.key)) return;
        const arr = Array.from(navBtns);
        const i = arr.indexOf(btn);
        const next = e.key === 'ArrowRight' ? (i+1)%arr.length : (i-1+arr.length)%arr.length;
        arr[next].focus();
        activate(arr[next].dataset.tab, true);
      });
    });

    // スワイプ対応
    let sx=0; box.addEventListener('touchstart',e=>{sx=e.touches[0].clientX;},{passive:true});
    box.addEventListener('touchend',e=>{
      const dx = e.changedTouches[0].clientX - sx;
      if (Math.abs(dx) < 40) return;
      const keys = ['line','photo','catalog'];
      const current = keys.findIndex(k => box.querySelector('#vcb-pane-'+k).classList.contains('is-active'));
      const next = dx < 0 ? Math.min(current+1, keys.length-1) : Math.max(current-1, 0);
      activate(keys[next], true);
    }, {passive:true});
  };

  document.querySelectorAll('[data-vcb-tabs]').forEach(init);
})();