/* Industrial Union UI Kit — shared primitives
   Loaded first. Exports building blocks to window. */
const { useState, useRef, useEffect } = React;

/* Mono uppercase label */
function Label({ children, soft, style, className = "", as = "span" }) {
  const Tag = as;
  return (
    <Tag
      className={"iu-label " + (soft ? "iu-label--soft " : "") + className}
      style={style}
    >
      {children}
    </Tag>
  );
}

/* A single rounded-top bracket hairline */
function Bracket({ style }) {
  return <div className="iu-bracket" style={style} />;
}

/* The label / content bracket row. Pass `cols` to override grid. */
function BracketRow({ children, cols, style, className = "" }) {
  return (
    <div
      className={"iu-bracket-row " + className}
      style={{ gridTemplateColumns: cols, ...style }}
    >
      {children}
    </div>
  );
}

/* Section scaffold: two brackets, then a label column + content column */
function Section({ label, counter, children, id, cols = "minmax(150px,1fr) 3fr" }) {
  return (
    <section id={id} className="sk-section">
      <BracketRow cols={cols} style={{ marginBottom: 18 }}>
        <Bracket />
        <Bracket />
      </BracketRow>
      <BracketRow cols={cols} className="sk-section-head">
        <Label>{label}</Label>
        <div className="sk-section-body">
          {counter && (
            <Label soft className="sk-counter">{counter}</Label>
          )}
          {children}
        </div>
      </BracketRow>
    </section>
  );
}

/* Arrow-led link. kind: 'down' ↳ , 'right' → , 'corner' ↘ */
function ArrowLink({ children, kind = "down", underline, href = "#", onClick, style }) {
  const glyph = kind === "right" ? "→" : kind === "corner" ? "↘" : "↳";
  return (
    <a
      className={"iu-link " + (underline ? "iu-link--underline" : "")}
      href={href}
      onClick={(e) => { if (onClick) { e.preventDefault(); onClick(e); } }}
      style={style}
    >
      <span className="sk-arrow" aria-hidden="true">{glyph}</span>
      <span>{children}</span>
    </a>
  );
}

function Pill({ children, onClick, active, style }) {
  return (
    <button
      className="iu-pill"
      onClick={onClick}
      style={{ background: active ? "#E2E1DB" : undefined, ...style }}
    >
      {children}
    </button>
  );
}

/* Figure: a labelled blank image slot (fill your own photo later) or a real
   photo via `src`. Blank slots show a soft mono tag so you know what goes where.
   bw applies the documentary grayscale treatment when a src is present. */
function Figure({ src, tone, tag, bw, ratio = "4 / 3", onClick, style }) {
  return (
    <div
      className={"sk-figure " + (src ? "" : "sk-figure--blank")}
      style={{ aspectRatio: ratio, cursor: onClick ? "pointer" : "default", ...style }}
      onClick={onClick}
    >
      {src ? (
        <img className={"iu-img " + (bw ? "iu-img--bw" : "")} src={src} alt={tag || ""} />
      ) : (
        <span className="sk-figure-tag iu-label">{tag}</span>
      )}
    </div>
  );
}

/* Industrial Union brand mark.
   variant 'icon' = factory mark only (horizontal nav);
   variant 'lockup' = full stacked lockup (footer).
   light inverts the black mark to white for dark surfaces. */
function Wordmark({ size = 30, light, variant = "icon", style }) {
  if (variant === "icon") return <FactoryMark size={size} light={light} style={style} />;
  return (
    <img
      src="../../assets/iu-lockup.jpg"
      alt="Industrial Union"
      style={{
        height: size, width: "auto", display: "block",
        filter: light ? "invert(1)" : "none",
        mixBlendMode: light ? "screen" : "multiply",
        ...style,
      }}
    />
  );
}

/* Industrial Union factory mark — the ORIGINAL artwork, pixel-for-pixel.
   The factory body is the real logo raster (white removed → transparent ink),
   and only the smoke ribbon is replaced by a vector path that matches the
   original's exact metrics (center y≈57, amplitude≈15, stroke≈41, x24–363) and
   ripples like a wave. Endpoints are amplitude-anchored so the silhouette holds
   while the ribbon undulates. SVG coords are the original 470×470 space. */
function FactoryMark({ size = 30, light, style }) {
  const color = light ? "#fff" : "#111110";
  // endpoints inset by the cap radius (≈stroke/2) so round caps land at x24/x363
  const x0 = 45, x1 = 343, cy = 57, amp = 15;
  const width = x1 - x0;
  // build one d-string for a given phase; amplitude envelope → 0 at both ends
  const dFor = (phase) => {
    const pts = [];
    for (let x = x0; x <= x1; x += 4) {
      const t = (x - x0) / width;            // 0..1
      const env = Math.sin(Math.PI * t);     // 0 at ends, 1 mid
      const y = cy + amp * env * Math.sin(2 * Math.PI * t + phase);
      pts.push(x + "," + y.toFixed(2));
    }
    return "M" + pts.join(" L");
  };
  const N = 24;
  const frames = [];
  for (let k = 0; k <= N; k++) frames.push(dFor((k / N) * 2 * Math.PI));
  const restD = frames[0];
  return (
    <svg
      viewBox="0 0 470 470"
      role="img"
      aria-label="Industrial Union"
      style={{ height: size, width: size, display: "block", overflow: "visible", ...style }}
    >
      <image href="assets/iu-building.png" x="0" y="0" width="470" height="470"
             style={{ filter: light ? "brightness(0) invert(1)" : "none" }} />
      <path d={restD} fill="none" stroke={color} strokeWidth="41"
            strokeLinecap="round" strokeLinejoin="round">
        <animate attributeName="d" dur="3.6s" repeatCount="indefinite"
                 calcMode="spline"
                 keySplines={Array(N).fill("0.42 0 0.58 1").join(";")}
                 values={frames.join(";")} />
      </path>
    </svg>
  );
}

/* Full nav brand lockup: factory icon + INDUSTRIAL UNION wordmark */
function Brand({ light, onClick, size = 30 }) {
  return (
    <a className="sk-brand" href="#" onClick={(e) => { e.preventDefault(); onClick && onClick(); }}>
      <Wordmark size={size} light={light} variant="icon" />
      <span className={"sk-brand-word" + (light ? " sk-brand-word--light" : "")}>
        Industrial<br/>Union
      </span>
    </a>
  );
}

/* Money formatter */
function Money({ value, style }) {
  return <span style={style}>${value}</span>;
}

Object.assign(window, { Label, Bracket, BracketRow, Section, ArrowLink, Pill, Figure, Wordmark, Brand, Money, useState, useRef, useEffect });
