// navigation.jsx — Site-feel navigation widgets that always sit on top of slides.
// Includes: SideArrows (← →), StoryCarousel (bottom row of numbered thumbnails),
// PaginationBullets (right-side dots for editorial sections).

// ── SideArrows ───────────────────────────────────────────────────────────
function SideArrows({ canPrev, canNext, onPrev, onNext }) {
  const arrowStyle = (enabled) => ({
    position: 'absolute', top: '50%',
    transform: 'translateY(-50%)',
    width: 48, height: 48,
    borderRadius: Tokens.radius.pill,
    background: 'rgba(20,20,28,0.55)',
    border: `1px solid ${Tokens.inkLine}`,
    backdropFilter: 'blur(20px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: enabled ? 'pointer' : 'not-allowed',
    opacity: enabled ? 1 : 0.3,
    zIndex: 60,
    color: Tokens.ink,
  });
  return (
    <>
      <button
        onClick={canPrev ? onPrev : undefined}
        disabled={!canPrev}
        aria-label="Previous slide"
        style={{ ...arrowStyle(canPrev), left: 24 }}
      >
        <IconArrow dir="left" size={20}/>
      </button>
      <button
        onClick={canNext ? onNext : undefined}
        disabled={!canNext}
        aria-label="Next slide"
        style={{ ...arrowStyle(canNext), right: 24 }}
      >
        <IconArrow dir="right" size={20}/>
      </button>
    </>
  );
}

// ── StoryCarousel ────────────────────────────────────────────────────────
// Bottom row of numbered thumbnails. Always shows 6 cards centered on the
// active slide so the user gets a "Netflix row" feel.
function StoryCarousel({ slides, sections, currentIdx, onJump, forceSectionId }) {
  const VISIBLE = 6;
  // forceSectionId override — used when the MorphScroll cover reports that
  // the user has scrolled into a bucket's preview. The carousel retargets
  // to that bucket's slides even though we're still on the cover.
  const currentSectionId = forceSectionId || slides[currentIdx]?.sectionId;
  const section = sections && currentSectionId
    ? sections.find(s => s.id === currentSectionId)
    : null;

  // Filter: when in a bucket section, only show slides from that section
  // (acts like a footer/breadcrumb scoped to the current chapter).
  const filteredEntries = slides
    .map((s, idx) => ({ s, idx }))
    .filter(({ s }) => !currentSectionId || s.sectionId === currentSectionId);

  // If forceSectionId is active, the current slide isn't in the filtered
  // list — center the window on its FIRST slide instead.
  const currentInFiltered = filteredEntries.findIndex(e => e.idx === currentIdx);
  const total = filteredEntries.length;
  const anchor = currentInFiltered >= 0 ? currentInFiltered : 0;
  let start = Math.max(0, Math.min(Math.max(0, total - VISIBLE), anchor - 2));
  const windowEntries = filteredEntries.slice(start, start + VISIBLE);

  return (
    <div style={{
      position: 'absolute',
      left: 80, right: 80, bottom: 36,
      zIndex: 50,
    }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 14,
        marginBottom: 14,
      }}>
        <div style={{
          fontFamily: Tokens.fontMono, fontSize: 12,
          color: Tokens.inkSoft, letterSpacing: '0.22em',
          textTransform: 'uppercase',
        }}>
          Select a Slide
        </div>
        {section && (
          <div style={{
            fontFamily: Tokens.fontMono, fontSize: 11,
            color: Tokens.inkSoft, letterSpacing: '0.18em',
            textTransform: 'uppercase',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{
              width: 6, height: 6, background: section.color, borderRadius: 1,
            }}/>
            {section.label}
            <span style={{ color: Tokens.inkFaint, marginLeft: 6 }}>· {total} slide</span>
          </div>
        )}
      </div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: `repeat(${VISIBLE}, 1fr)`,
        gap: 14,
      }}>
        {windowEntries.map(({ s, idx }) => {
          const active = idx === currentIdx;
          return (
            <button key={idx}
              onClick={() => onJump(idx)}
              style={{
                position: 'relative',
                background: 'none',
                border: 'none',
                padding: 0, margin: 0,
                cursor: 'pointer',
                height: 96,
                borderRadius: Tokens.radius.md,
                overflow: 'hidden',
                outline: active ? `2px solid ${Tokens.ink}` : `1px solid ${Tokens.inkLine}`,
                outlineOffset: active ? 2 : 0,
                textAlign: 'left',
              }}>
              {/* card bg */}
              <div style={{
                position: 'absolute', inset: 0,
                background: s.thumb
                  ? `linear-gradient(0deg, rgba(0,0,0,0.78) 0%, rgba(0,0,0,0.3) 60%, transparent 100%), url(${s.thumb}) center/cover`
                  : (s.scheme ? SCHEMES[s.scheme].surface : Tokens.bgSurface),
              }}/>
              {/* corner brackets if active */}
              {active && (
                <CornerBrackets color={Tokens.ink} size={16} thickness={2} gap={0}/>
              )}
              {/* number + label */}
              <div style={{
                position: 'absolute', left: 12, top: 10,
                display: 'flex', alignItems: 'center', gap: 6,
                fontFamily: Tokens.fontMono, fontSize: 10,
                color: Tokens.ink, letterSpacing: '0.18em',
                fontWeight: Tokens.weight.semibold,
              }}>
                <span aria-hidden="true" style={{
                  width: 6, height: 6,
                  background: (s.scheme ? SCHEMES[s.scheme].accentBold : Tokens.purple400),
                }}/>
                {String(idx + 1).padStart(2, '0')}
              </div>
              <div style={{
                position: 'absolute', left: 12, right: 12, bottom: 10,
                fontFamily: Tokens.fontDisplay,
                fontSize: 12, fontWeight: Tokens.weight.semibold,
                color: Tokens.ink,
                letterSpacing: '-0.005em',
                lineHeight: 1.2,
                overflow: 'hidden',
                display: '-webkit-box',
                WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
              }}>
                {s.shortLabel || s.title}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── PaginationBullets ────────────────────────────────────────────────────
// Vertical bullets on the right side for editorial slides with sections.
function PaginationBullets({ total, current, onJump }) {
  return (
    <div style={{
      position: 'absolute',
      right: 36, top: '50%',
      transform: 'translateY(-50%)',
      display: 'flex', flexDirection: 'column', gap: 10,
      zIndex: 40,
    }}>
      {Array.from({ length: total }).map((_, i) => {
        const active = i === current;
        return (
          <button key={i}
            onClick={() => onJump && onJump(i)}
            aria-label={`Section ${i + 1}`}
            style={{
              width: active ? 22 : 10,
              height: 10,
              borderRadius: Tokens.radius.pill,
              background: active ? Tokens.ink : Tokens.inkFaint,
              border: 'none',
              cursor: 'pointer',
              transition: 'all 200ms',
            }}/>
        );
      })}
    </div>
  );
}

// ── MenuOverlay ──────────────────────────────────────────────────────────
// "Explore by theme" full-screen overlay (opened from the hamburger).
function MenuOverlay({ slides, open, onClose, onJump }) {
  if (!open) return null;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'rgba(8,8,14,0.96)',
      zIndex: 100,
      padding: 80,
      overflow: 'auto',
    }}>
      <button onClick={onClose} aria-label="Close" style={{
        position: 'absolute', top: 44, right: 80,
        background: 'rgba(20,20,28,0.5)',
        border: `1px solid ${Tokens.inkLine}`,
        borderRadius: Tokens.radius.pill,
        width: 44, height: 44,
        color: Tokens.ink, fontSize: 20, fontWeight: 300,
        cursor: 'pointer',
      }}>×</button>

      {/* Hero title with corner brackets */}
      <div style={{
        position: 'relative',
        textAlign: 'center',
        maxWidth: 900, margin: '40px auto 60px',
        padding: '60px 80px',
      }}>
        <CornerBrackets color={Tokens.purple300} size={80} thickness={2}/>
        <div style={{
          fontFamily: Tokens.fontDisplay,
          fontSize: 84, fontWeight: Tokens.weight.black,
          color: Tokens.ink,
          letterSpacing: '-0.02em',
          textTransform: 'uppercase',
          lineHeight: 0.95,
        }}>Explore by theme</div>
        <div style={{
          marginTop: 18,
          fontFamily: Tokens.fontDisplay,
          fontSize: 17, color: Tokens.inkDim,
          lineHeight: 1.5,
        }}>
          This page helps you find what you're looking for across the deck.<br/>
          Choose a slide from the cards below to jump there.
        </div>
      </div>

      {/* 3-col grid of slides */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 18,
        maxWidth: 1700,
        margin: '0 auto',
      }}>
        {slides.map((s, i) => {
          const panel = s.panelColor || 'purpleMid';
          const p = CARD_PANELS[panel];
          return (
            <button key={i} onClick={() => { onJump(i); onClose(); }}
              style={{
                background: 'none',
                border: 'none',
                padding: 0, margin: 0,
                cursor: 'pointer',
                display: 'flex',
                height: 200,
                borderRadius: Tokens.radius.xl,
                overflow: 'hidden',
                textAlign: 'left',
              }}>
              <div style={{
                flex: 1,
                backgroundImage: s.thumb ? `url(${s.thumb})` : 'none',
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                background: s.thumb ? undefined : (s.scheme ? SCHEMES[s.scheme].surface : Tokens.bgSurface),
              }}/>
              <div style={{
                flex: 1.1,
                background: p.fill,
                color: p.text,
                padding: '24px 26px',
                display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              }}>
                <div style={{
                  fontFamily: Tokens.fontMono, fontSize: 11,
                  letterSpacing: '0.24em', opacity: 0.7,
                }}>SLIDE {String(i + 1).padStart(2, '0')}</div>
                <div style={{
                  fontFamily: Tokens.fontDisplay,
                  fontSize: 24, fontWeight: Tokens.weight.extrabold,
                  letterSpacing: '-0.02em',
                  lineHeight: 1.05,
                  textTransform: 'uppercase',
                }}>{s.shortLabel || s.title}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { SideArrows, StoryCarousel, PaginationBullets, MenuOverlay });
