// Shared primitives: section header, logos, marquees, page numbers.
const { useEffect, useRef, useState } = React;

function PageNumber({ n, total = 9, label }) {
  if (!window.__NOMEN_STATE__?.showPageNumbers) return null;
  return (
    <div className="page-no">
      <span>— {String(n).padStart(2,'0')} / {String(total).padStart(2,'0')}</span>
      {label && <span style={{ marginLeft: 18 }}>· {label}</span>}
    </div>
  );
}

function SectionLabel({ idx, title, kicker }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
      paddingBottom: 18, borderBottom: '1px solid var(--ink)', marginBottom: 48,
      gap: 24, flexWrap: 'wrap'
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 18 }}>
        <span className="eyebrow" style={{ color: 'var(--red)' }}>
          § {String(idx).padStart(2,'0')}
        </span>
        <span className="titular" style={{ fontSize: 34 }}>{title}</span>
      </div>
      {kicker && <span className="eyebrow" style={{ opacity: .55, maxWidth: 340, textAlign: 'right' }}>{kicker}</span>}
    </div>
  );
}

// Five-bar signature motif as inline SVG. Echoes the red bars from the PDF.
function FiveBars({ width = 120, color = "var(--red)", vertical = true, gap = 6 }) {
  const barW = (width - gap * 4) / 5;
  const barH = vertical ? barW * 2.1 : barW;
  return (
    <svg width={width} height={barH} viewBox={`0 0 ${width} ${barH}`} style={{ display: 'block' }}>
      {[0,1,2,3,4].map(i => (
        <rect key={i} x={i*(barW+gap)} y={0} width={barW} height={barH} fill={color} />
      ))}
    </svg>
  );
}

// NOMEN wordmark using the extracted PNG from the PDF
function NomenMark({ size = 240, src = "assets/logo/nomen-wordmark.png", style = {} }) {
  return <img src={src} alt="NOMEN" style={{ width: size, height: 'auto', ...style }} draggable={false} />;
}

// NOMEN wordmark sliced into 5 letter-columns. On pointer-enter (hover or
// touch), it triggers a 5s "disperse-and-reform" loop: each letter flies
// out in its own direction, holds, then snaps back to position. Implements
// it with 5 absolutely-positioned copies of the same PNG, each clipped via
// inset() to a single letter column. The CSS keyframes drive the motion.
function NomenDispersing({ size = "min(86vw, 1100px)", src = "assets/logo/nomen-wordmark-closing.png" }) {
  const [playing, setPlaying] = React.useState(false);
  const ref = React.useRef(null);

  // Letter column bounds in % of the source PNG (945×945), measured from
  // the actual red pixels — letters have different widths! M is widest.
  //   N1: 6.14 → 22.22 (153px)
  //   O:  22.96 → 39.15 (154px)
  //   M:  39.79 → 60.63 (198px)  ← widest
  //   E:  61.38 → 77.57 (154px)
  //   N2: 78.20 → 94.39 (154px)
  // Cuts go through the inter-letter gaps (~22.6, 39.5, 61, 77.9%).
  // clip-path inset(top right bottom left): right is from the right edge.
  const cuts = [0, 22.6, 39.5, 61.0, 77.9, 100];
  const cols = [];
  for (let i = 0; i < 5; i++) {
    cols.push({ left: cuts[i], right: 100 - cuts[i + 1] });
  }

  // Trigger the 5s disperse loop when the cursor lingers on the mark for a
  // brief moment (not on every grazing pass). Once it plays, ignore further
  // hovers until it finishes — keeps it "fun, not reactive".
  const enterTimer = React.useRef(null);
  function handleEnter() {
    if (playing) return;
    if (enterTimer.current) return;
    enterTimer.current = setTimeout(() => {
      enterTimer.current = null;
      setPlaying(true);
      setTimeout(() => setPlaying(false), 5000);
    }, 250);
  }
  function handleLeave() {
    if (enterTimer.current) { clearTimeout(enterTimer.current); enterTimer.current = null; }
  }

  return (
    <div
      ref={ref}
      className={"nomen-letters" + (playing ? " disperse" : "")}
      style={{ width: size }}
      onMouseEnter={handleEnter}
      onMouseLeave={handleLeave}
      onTouchStart={handleEnter}
      data-name="NOMEN">
      {cols.map((c, i) => (
        <img
          key={i}
          src={src}
          alt={i === 0 ? "NOMEN" : ""}
          aria-hidden={i !== 0}
          draggable={false}
          className={`nomen-letter l${i + 1}`}
          style={{
            // clipPath: inset(top right bottom left) — keep just this letter's column
            clipPath: `inset(0 ${c.right}% 0 ${c.left}%)`,
            WebkitClipPath: `inset(0 ${c.right}% 0 ${c.left}%)`,
          }}
        />
      ))}
    </div>
  );
}

// Modular sign (cross composition)
function NomenCross({ size = 140, src = "assets/logo/nomen-modular-sign.png", style = {} }) {
  return <img src={src} alt="NOMEN modular" style={{ width: size, height: 'auto', ...style }} draggable={false} />;
}

// Marquee
function Marquee({ items }) {
  const track = items.concat(items);
  return (
    <div className="marquee" role="presentation">
      <div className="marquee-track">
        {track.map((t, i) => (
          <React.Fragment key={i}>
            <span>{t}</span>
            <span className="dot">●</span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { PageNumber, SectionLabel, FiveBars, NomenMark, NomenDispersing, NomenCross, Marquee });
