/* ============================================================
   Phils 5K — Tab Components (React)
   ------------------------------------------------------------
   Drop into your project alongside tabs.css. Load with:
     <link rel="stylesheet" href="tabs.css">
     <script type="text/babel" src="Tabs.jsx"></script>

   Exposes on window:
     <YearStripTabs>   — for Photos / Results pages
     <SegmentedTabs>   — for Runner Info

   ── PROPS — YearStripTabs ────────────────────────────────
     years         { year: 2026, distance: '5K' }[]   required
     value         number (selected year)              required
     onChange      (year) => void                      required
     fadeBg        CSS color of surrounding bg          default '#fff'

   ── PROPS — SegmentedTabs ────────────────────────────────
     options       { id: 'race-day', label: 'Race Day' }[]  required
     value         string (selected id)                     required
     onChange      (id) => void                             required
     fadeBg        CSS color of surrounding bg              default '#fff'
   ============================================================ */

const { useEffect, useRef, useCallback } = React;

/* ── Internal hook: scroll-fade + arrow controls ─────────── */
function useScrollShell(barRef, shellRef) {
  const update = useCallback(() => {
    const bar = barRef.current;
    const shell = shellRef.current;
    if (!bar || !shell) return;
    const maxScroll = bar.scrollWidth - bar.clientWidth;
    const overflows = maxScroll > 2;
    const atStart   = bar.scrollLeft <= 4;
    const atEnd     = bar.scrollLeft >= maxScroll - 4;
    shell.style.setProperty('--ph-fade-left',  overflows && !atStart ? 1 : 0);
    shell.style.setProperty('--ph-fade-right', overflows && !atEnd   ? 1 : 0);
    const leftBtn  = shell.querySelector('.ph-tabs-shell__arrow--left');
    const rightBtn = shell.querySelector('.ph-tabs-shell__arrow--right');
    if (leftBtn)  leftBtn.classList.toggle('is-visible',  overflows && !atStart);
    if (rightBtn) rightBtn.classList.toggle('is-visible', overflows && !atEnd);
  }, [barRef, shellRef]);

  useEffect(() => {
    const bar = barRef.current;
    if (!bar) return;
    update();
    bar.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      bar.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [update, barRef]);

  const scrollBy = (delta) => {
    if (barRef.current) barRef.current.scrollBy({ left: delta, behavior: 'smooth' });
  };

  return { scrollBy };
}

/* ── Internal: shell with arrows ────────────────────────── */
function TabsShell({ children, fadeBg = '#fff' }) {
  const shellRef = useRef(null);
  const barRef   = useRef(null);
  const { scrollBy } = useScrollShell(barRef, shellRef);

  return (
    <div ref={shellRef} className="ph-tabs-shell" style={{ '--ph-fade-bg': fadeBg }}>
      <div ref={barRef} className="ph-tabs-shell__bar">
        {children}
      </div>
      <button
        type="button"
        className="ph-tabs-shell__arrow ph-tabs-shell__arrow--left"
        aria-label="Scroll tabs left"
        onClick={() => scrollBy(-260)}
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="15 18 9 12 15 6" />
        </svg>
      </button>
      <button
        type="button"
        className="ph-tabs-shell__arrow ph-tabs-shell__arrow--right"
        aria-label="Scroll tabs right"
        onClick={() => scrollBy(260)}
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="9 18 15 12 9 6" />
        </svg>
      </button>
    </div>
  );
}

/* ── PUBLIC: YearStripTabs ──────────────────────────────── */
function YearStripTabs({ years, value, onChange, fadeBg }) {
  return (
    <TabsShell fadeBg={fadeBg}>
      <div className="ph-year-tabs" role="tablist" aria-label="Race year">
        {years.map(({ year, distance }) => {
          const selected = year === value;
          return (
            <button
              key={year}
              role="tab"
              type="button"
              className="ph-year-tabs__btn"
              aria-selected={selected}
              tabIndex={selected ? 0 : -1}
              onClick={(e) => {
                onChange(year);
                e.currentTarget.scrollIntoView({ inline: 'center', block: 'nearest', behavior: 'smooth' });
              }}
            >
              <span className="ph-year-tabs__year">{year}</span>
              <span className="ph-year-tabs__caption">{distance}</span>
            </button>
          );
        })}
      </div>
    </TabsShell>
  );
}

/* ── PUBLIC: SegmentedTabs ──────────────────────────────── */
function SegmentedTabs({ options, value, onChange, fadeBg }) {
  return (
    <TabsShell fadeBg={fadeBg}>
      <div className="ph-segmented" role="tablist" aria-label="Runner info section">
        {options.map(({ id, label }) => {
          const selected = id === value;
          return (
            <button
              key={id}
              role="tab"
              type="button"
              className="ph-segmented__btn"
              aria-selected={selected}
              tabIndex={selected ? 0 : -1}
              onClick={(e) => {
                onChange(id);
                e.currentTarget.scrollIntoView({ inline: 'center', block: 'nearest', behavior: 'smooth' });
              }}
            >
              {label}
            </button>
          );
        })}
      </div>
    </TabsShell>
  );
}

/* Export to window (matches the existing components.jsx pattern) */
Object.assign(window, { YearStripTabs, SegmentedTabs });
