// Section dot navigation — labels always visible.
// Visual motif: a vertical "spectrum bar" of light, with each section as a node on the bar.
// The active node lights up like a lamp; the connector line behind reads as a wavelength gradient.
function Remote({ active, variant, setVariant }) {
  const { locale, t } = useI18n();
  // Detect whether the dot nav currently sits over a dark or light region of the page,
  // so we can flip the colors for legibility. The nav's vertical center is fixed at 50vh,
  // so we sample the element directly under that point and read its background luminance.
  const [theme, setTheme] = React.useState('dark');
  const [sections, setSections] = React.useState(() => window.SoladuoNavigation.getRemoteSections(t));
  React.useEffect(() => {
    const compute = () => {
      const x = window.innerWidth - 28 - 7; // approx node center
      const y = window.innerHeight / 2;
      const stack = document.elementsFromPoint(x, y) || [];
      // Explicit override: any ancestor with data-nav-theme wins over bg detection
      for (const el of stack) {
        if (el.closest('[aria-label="Section navigation"]')) continue;
        const themed = el.closest('[data-nav-theme]');
        if (themed) {
          const t = themed.getAttribute('data-nav-theme');
          if (t === 'dark' || t === 'light') { setTheme(t); return; }
        }
        break;
      }
      // Walk up the stack and find the first element with a non-transparent bg
      for (const el of stack) {
        if (el.closest('[aria-label="Section navigation"]')) continue;
        const cs = getComputedStyle(el);
        const bg = cs.backgroundColor;
        const m = bg.match(/rgba?\(([^)]+)\)/);
        if (!m) continue;
        const parts = m[1].split(',').map(s => parseFloat(s.trim()));
        const a = parts[3] === undefined ? 1 : parts[3];
        if (a < 0.5) continue;
        const [r, g, b] = parts;
        // Perceived luminance
        const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        setTheme(lum < 0.55 ? 'dark' : 'light');
        return;
      }
    };
    compute();
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(compute);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    // Re-sample periodically so Hero slide cross-fades (which don't fire scroll) update too
    const iv = setInterval(compute, 600);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf);
      clearInterval(iv);
    };
  }, []);

  React.useEffect(() => {
    let alive = true;
    const fallbackSections = window.SoladuoNavigation.getRemoteSections(t);
    setSections(fallbackSections);
    window.SoladuoNavigation.loadRemoteSections(locale, t).then((items) => {
      if (alive) setSections(items);
    });
    return () => { alive = false; };
  }, [locale]);

  const onDark = theme === 'dark';
  const labelActive   = onDark ? 'var(--bone)' : 'var(--ink)';
  const labelInactive = onDark ? 'rgba(244,238,228,0.55)' : 'rgba(22,19,16,0.45)';
  const labelShadow   = onDark ? '0 1px 2px rgba(0,0,0,0.35)' : 'none';
  const dotInactiveBg = onDark ? 'rgba(244,238,228,0.55)' : 'rgba(22,19,16,0.40)';
  const railGrad      = onDark
    ? 'linear-gradient(180deg, rgba(248,200,120,0.65) 0%, rgba(244,238,228,0.55) 35%, rgba(244,238,228,0.42) 70%, rgba(244,238,228,0.30) 100%)'
    : 'linear-gradient(180deg, rgba(232,154,60,0.55) 0%, rgba(22,19,16,0.32) 35%, rgba(22,19,16,0.22) 70%, rgba(22,19,16,0.14) 100%)';

  const activeIdx = Math.max(0, sections.findIndex(s => s.match.includes(active)));
  // 0..1 normalized progress along the spectrum
  const progress = sections.length > 1 ? activeIdx / (sections.length - 1) : 0;

  return (
    <aside aria-label={t('nav.sectionNavigation')}
      className="dotnav-hide-mobile"
      style={{
        position: 'fixed',
        right: 28,
        top: '50%',
        transform: 'translateY(-50%)',
        zIndex: 35,
        pointerEvents: 'auto',
        display: 'grid',
        gridTemplateColumns: 'auto 14px',
        columnGap: 18,
        rowGap: 0,
        alignItems: 'center',
      }}>

      {/* === Spectrum rail (column 2) — runs full height behind the dots === */}
      <span aria-hidden="true" style={{
        gridColumn: 2,
        gridRow: `1 / span ${sections.length}`,
        justifySelf: 'center',
        width: 1,
        height: '100%',
        background: railGrad,
        position: 'relative',
        transition: 'background 480ms var(--ease-settled)',
      }}>
        {/* Glow puck that travels along the rail to the active section */}
        <span style={{
          position: 'absolute',
          left: '50%',
          top: `calc(${progress * 100}% )`,
          transform: 'translate(-50%, -50%)',
          width: 14, height: 14,
          borderRadius: '50%',
          background: 'radial-gradient(circle at 50% 45%, rgba(248,200,120,0.85), rgba(232,154,60,0.4) 55%, rgba(232,154,60,0) 75%)',
          filter: 'blur(0.5px)',
          transition: 'top 540ms cubic-bezier(.2,.7,.2,1)',
          pointerEvents: 'none',
        }} />
      </span>

      {/* === Rows: label (col 1) + node (col 2) === */}
      {sections.map((s, i) => {
        const isActive = s.match.includes(active);
        const goTo = (e) => {
          e.preventDefault();
          const el = document.getElementById(s.id);
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
          else window.location.hash = s.href || `#${s.id}`;
        };
        return (
          <React.Fragment key={s.id}>
            {/* Label — always visible, clickable */}
            <a
              href={s.href || `#${s.id}`}
              onClick={goTo}
              className="dotnav-row"
              aria-label={t('nav.jumpTo', { label: s.label })}
              style={{
                gridColumn: 1,
                gridRow: i + 1,
                display: 'flex',
                alignItems: 'baseline',
                justifyContent: 'flex-end',
                gap: 8,
                padding: '11px 0',
                cursor: 'pointer',
                textDecoration: 'none',
              }}>
              <span className="dotnav-l" style={{
                font: '600 11px/1 var(--font-nav)',
                letterSpacing: '0.14em',
                textTransform: 'uppercase',
                color: isActive ? labelActive : labelInactive,
                transition: 'color 360ms var(--ease-settled), letter-spacing 240ms',
                whiteSpace: 'nowrap',
                textShadow: labelShadow,
              }}>
                {s.label}
              </span>
            </a>

            {/* Node on the rail — column 2, same row, clickable */}
            <a
              href={s.href || `#${s.id}`}
              onClick={goTo}
              aria-label={s.label}
              aria-current={isActive ? 'true' : undefined}
              className="dotnav-node-wrap"
              style={{
                gridColumn: 2,
                gridRow: i + 1,
                position: 'relative',
                width: 14, height: 14,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: '11px 0',
                cursor: 'pointer',
                textDecoration: 'none',
              }}>
              {/* outer halo when active */}
              {isActive && (
                <span aria-hidden="true" style={{
                  position: 'absolute', inset: -6,
                  borderRadius: '50%',
                  background: 'radial-gradient(circle, rgba(232,154,60,0.35), rgba(232,154,60,0) 70%)',
                  pointerEvents: 'none',
                }} />
              )}
              {/* dot */}
              <span className="dotnav-dot" style={{
                width: isActive ? 9 : 5,
                height: isActive ? 9 : 5,
                borderRadius: '50%',
                background: isActive
                  ? 'radial-gradient(circle at 35% 30%, #FFFDF8, #FFE8C2 55%, #E89A3C)'
                  : dotInactiveBg,
                boxShadow: isActive
                  ? '0 0 12px rgba(232,154,60,0.55), inset 0 0 2px rgba(255,232,194,0.6)'
                  : 'none',
                transition: 'width 280ms var(--ease-quick), height 280ms var(--ease-quick), background 280ms, box-shadow 280ms',
              }} />
            </a>
          </React.Fragment>
        );
      })}

      <style>{`
        @media (max-width: 980px) {
          .dotnav-hide-mobile { display: none !important; }
        }
        .dotnav-row:hover .dotnav-l {
          letter-spacing: 0.18em;
        }
        .dotnav-node-wrap:hover .dotnav-dot {
          width: 7px !important;
          height: 7px !important;
          background: radial-gradient(circle at 35% 30%, #FFFDF8, #FFE8C2 60%, #E89A3C) !important;
          box-shadow: 0 0 8px rgba(248,200,120,0.55) !important;
        }
      `}</style>
    </aside>
  );
}

window.Remote = Remote;
