// ──────────────────────────────────────────────────────────────────
// Splash cube — black background, small white 3D cube.
// 6 faces showcase the brand marks. Auto-rotates, then settles.
// Sides:
//   FRONT  · T-monogram (PNG)
//   BACK   · TKDN 2×2 letter grid (TD / DN)
//   RIGHT  · TAKEDOWN wordmark (PNG, horizontal)
//   LEFT   · Vertical "TAKEDOWN" set in Figtree
//   TOP    · Orange-red signature with hairline rule
//   BOTTOM · System label "EST · 2026 · CMBT/SPORT"
// ──────────────────────────────────────────────────────────────────

const CUBE_SIZE = 120;
const HALF = CUBE_SIZE / 2;

const cubeFaceBase = {
  position: "absolute",
  width: CUBE_SIZE,
  height: CUBE_SIZE,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  background: "transparent",
  overflow: "visible",
};

// Pose representation — 5 fixed rotation slots so each pose differs from
// the next in exactly one slot. CSS transition then interpolates that one
// slot linearly, producing a pure single-axis roll.
//
// Sequence (5 poses, 4 transitions). BACK is visited twice with a content
// swap (TKDN → TAP THE T) while it's hidden during pose 1 + 2.
//   pose 0  BACK   — TKDN                   (start at rotateY(180))
//   pose 1  LEFT   — BUILT FOR PROS         (T0 left  = rotateY -90)
//   pose 2  TOP    — PRESENT AND FUTURE     (T1 down  = rotateX -90)
//   pose 3  BACK*  — TAP THE T  (content swap) (T2 right = rotateY +90)
//   pose 4  RIGHT  — T-monogram             (T3 down  = rotateX -90)
//
// Slot layout (leftmost in CSS string = applied LAST = world axis):
//   [X3, Y2, X1, Y0, Yb]
const CUBE_POSES = [
  // [ X3,  Y2,  X1,  Y0, Yb ]
  [   0,   0,   0,   0, 180],  // 0 · BACK   (TKDN)
  [   0,   0,   0, -90, 180],  // 1 · LEFT   (BUILT FOR PROS)
  [   0,   0, -90, -90, 180],  // 2 · TOP    (PRESENT AND FUTURE)
  [   0,  90, -90, -90, 180],  // 3 · BACK*  (TAP THE T)
  [ -90,  90, -90, -90, 180],  // 4 · RIGHT  (T-monogram)
];

const CUBE_FACE_TRANSFORMS = {
  front:  (h) => `translateZ(${h}px)`,
  right:  (h) => `rotateY(90deg) translateZ(${h}px)`,
  top:    (h) => `rotateX(90deg) translateZ(${h}px)`,
  left:   (h) => `rotateY(-90deg) translateZ(${h}px)`,
  bottom: (h) => `rotateX(-90deg) translateZ(${h}px)`,
  back:   (h) => `rotateY(180deg) translateZ(${h}px)`,
};

const SplashCube = ({ size = CUBE_SIZE, autoRotate = true, paused = false, transitionMs = 2600, stopOnLast = true, onSettled, loop = false }) => {
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    if (!autoRotate || paused) return;
    let timer;
    let i = 0;
    const tick = () => {
      if (i + 1 >= CUBE_POSES.length) {
        if (loop) {
          // hold on final pose, then reset and continue
          timer = setTimeout(() => {
            i = 0;
            setIdx(0);
            timer = setTimeout(tick, transitionMs);
          }, transitionMs * 2);
          return;
        }
        if (stopOnLast && onSettled) timer = setTimeout(onSettled, transitionMs);
        return;
      }
      timer = setTimeout(() => {
        i += 1;
        setIdx(i);
        tick();
      }, transitionMs);
    };
    tick();
    return () => clearTimeout(timer);
  }, [autoRotate, paused, transitionMs, stopOnLast, onSettled, loop]);

  const h = size / 2;
  const p = CUBE_POSES[idx];
  const xform = `rotateX(${p[0]}deg) rotateY(${p[1]}deg) rotateX(${p[2]}deg) rotateY(${p[3]}deg) rotateY(${p[4]}deg)`;

  return (
    <div
      style={{
        width: size,
        height: size,
        perspective: size * 6,
        perspectiveOrigin: "50% 50%",
        margin: "0 auto",
      }}
    >
      <div
        style={{
          position: "relative",
          width: size,
          height: size,
          transformStyle: "preserve-3d",
          transform: xform,
          transition: `transform ${transitionMs}ms cubic-bezier(.4,.0,.2,1)`,
        }}
      >
        {/* BACK — TKDN at start, TAP THE T after the right turn at pose 3.
            Content swap happens while BACK is hidden (backface) during the
            pose 1 → pose 2 turn; no flicker. */}
        {idx < 3 ? (
          <CubeFace transform={CUBE_FACE_TRANSFORMS.back(h)}>
            <TkdnVertices size={size} />
          </CubeFace>
        ) : (
          <CubeFace transform={CUBE_FACE_TRANSFORMS.back(h)} spin={-90}>
            <CubeLabel text="TAP THE T" size={size} />
            <CubeCorner corner="tr" />
          </CubeFace>
        )}
        {/* LEFT — BUILT FOR PROS (pose 1) */}
        <CubeFace transform={CUBE_FACE_TRANSFORMS.left(h)}>
          <CubeLabel text="BUILT FOR PROS" size={size} />
          <CubeCorner corner="tr" />
        </CubeFace>
        {/* TOP — PRESENT AND FUTURE (pose 2, spin +90) */}
        <CubeFace transform={CUBE_FACE_TRANSFORMS.top(h)} spin={90}>
          <CubeLabel text="PRESENT AND FUTURE" size={size} />
          <CubeCorner corner="br" />
        </CubeFace>
        {/* RIGHT — T-monogram (pose 4, spin -90) */}
        <CubeFace transform={CUBE_FACE_TRANSFORMS.right(h)} spin={-90}>
          <img src="assets/tkdn-t.png" alt="" style={{ width: "92%", height: "92%", objectFit: "contain", filter: "var(--logo-filter, none)" }} />
        </CubeFace>
        {/* FRONT — removed from sequence; left empty. */}
        <CubeFace transform={CUBE_FACE_TRANSFORMS.front(h)} />
        {/* BOTTOM — removed from sequence; left empty. */}
        <CubeFace transform={CUBE_FACE_TRANSFORMS.bottom(h)} />
      </div>
    </div>
  );
};

// A small right-angle accent in the brand color, anchored at one corner of
// the cube face. Position cycles per face so the mark appears to migrate
// around the cube as it rotates through the pose sequence.
function CubeCorner({ corner = "tl", color = "var(--accent, #F04B24)", arm = 16, thickness = 2 }) {
  const off = 10;
  const at =
    corner === "tl" ? { top: off, left: off } :
    corner === "tr" ? { top: off, right: off } :
    corner === "bl" ? { bottom: off, left: off } :
    corner === "br" ? { bottom: off, right: off } :
    { top: off, left: off };
  return (
    <>
      <div style={{ position: "absolute", width: arm, height: thickness, background: color, ...at }} />
      <div style={{ position: "absolute", width: thickness, height: arm, background: color, ...at }} />
    </>
  );
}

// Each face is positioned in 3D and only renders when facing the camera.
// `spin` rotates the content inside the face so it reads upright once the
// cube's pose-sequence has brought that face to the viewer.
function CubeFace({ transform, spin = 0, children }) {
  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        transform,
        backfaceVisibility: "hidden",
        WebkitBackfaceVisibility: "hidden",
      }}
    >
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          transform: spin ? `rotateZ(${spin}deg)` : undefined,
        }}
      >
        {children}
      </div>
    </div>
  );
}

// TKDN letters at the 4 cube vertices (corners of the back face).
function TkdnVertices({ size }) {
  const letterCell = size * 0.42;
  const inset = size * 0.05;
  return (
    <div style={{ position: "absolute", inset: 0 }}>
      {[
        { ch: "T", style: { top: inset, left: inset } },
        { ch: "K", style: { top: inset, right: inset } },
        { ch: "D", style: { bottom: inset, left: inset } },
        { ch: "N", style: { bottom: inset, right: inset } },
      ].map(({ ch, style }) => (
        <div
          key={ch}
          style={{
            position: "absolute",
            width: letterCell,
            height: letterCell,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            ...style,
          }}
        >
          <WordmarkLetter letter={ch} size={letterCell} color="currentColor" fillRatio={0.95} />
        </div>
      ))}
    </div>
  );
}

// Sleek bold-italic Avenir Next label drawn across the cube face.
function CubeLabel({ text, size, color = "currentColor" }) {
  return (
    <div
      style={{
        width: "84%",
        color,
        fontFamily: '"Avenir Next", -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif',
        fontWeight: 700,
        fontStyle: "italic",
        fontSize: size * 0.11,
        letterSpacing: "0.03em",
        textTransform: "uppercase",
        lineHeight: 1.1,
        textAlign: "center",
        textWrap: "balance",
      }}
    >
      {text}
    </div>
  );
}

// SVG letter paths from the canonical Takedown wordmark. Each letter uses
// its native viewBox so the slant + cuts are pixel-perfect. Color follows
// currentColor so a single component handles light/dark + accent tints.
const WORDMARK_LETTERS_SVG = {
  T: {
    viewBox: "0 0 312 273",
    paths: [
      "M312 0.0195312L295.06 63.5795L192.13 64.1495L135.5 273.02H47L120.5 0.0195312H312Z",
      "M78 0.0195312L60.5 64.0195H0L17.5 0.0195312H78Z",
    ],
  },
  K: {
    viewBox: "626 0 393 273",
    paths: [
      // K stem (own coords)
      "M789 0.0195312L716 273.02H626L699 0.0195312H789Z",
      // Branches
      "M1019 0.0195312L880.29 111.51L952 273.02H844C829.19 237.61 813.64 202.48 798.18 167.34C796.35 163.18 791.3 155.63 790.43 152.02C788.34 143.35 805.74 99.5395 806.95 87.4695L912.5 0.0195312H1019Z",
    ],
  },
  D: {
    viewBox: "1290 0 372 273",
    paths: [
      // line (stem)
      "M1451 0.0195312L1377.5 273.02H1290L1362 0.0195312H1451Z",
      // bowl
      "M1477 59.02L1492.19 1.71L1494.49 0H1626.3L1661.83 48.75L1615.98 223.24L1553.5 273.02H1420L1435.1 214.12L1510.48 214L1533.43 195.95L1565.61 77.5L1552.5 59.02H1477Z",
    ],
  },
  N: {
    viewBox: "2469 0 377 273",
    paths: [
      // N stem (own coords)
      "M2621 0.0195312L2547.5 273.02H2469L2542 0.0195312H2621Z",
      // Right stem + diagonal
      "M2846 0.0195312L2773.53 272.04L2657.46 273.09L2655.89 272.43L2619.96 160.56L2660.01 8.01953L2718.99 179.01L2767.5 0.0195312H2846Z",
    ],
  },
};

const WordmarkLetter = ({ letter, size, color = "currentColor", fillRatio = 0.7 }) => {
  const spec = WORDMARK_LETTERS_SVG[letter];
  if (!spec) return null;
  const [vx, vy, vw, vh] = spec.viewBox.split(" ").map(Number);
  // All four letters share the same source height (273). Scaling by height
  // gives a uniform baseline across the 2×2 grid; widths vary (D is widest).
  // fillRatio capped at 273/393 ≈ 0.69 so K's full width still fits a square cell.
  const safeRatio = Math.min(fillRatio, 273 / 393);
  const scale = (size * safeRatio) / vh;
  const renderW = vw * scale;
  const renderH = vh * scale;
  return (
    <div
      style={{
        width: size,
        height: size,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color,
      }}
    >
      <svg
        width={renderW}
        height={renderH}
        viewBox={spec.viewBox}
        xmlns="http://www.w3.org/2000/svg"
        style={{ overflow: "visible" }}
      >
        {spec.paths.map((d, i) => (
          <path
            key={i}
            d={d}
            fill="currentColor"
            transform={spec.transforms ? spec.transforms[i] || undefined : undefined}
          />
        ))}
      </svg>
    </div>
  );
};


const SplashScreen = ({ dark = true, animateOut = false, onDone, label }) => {
  const [stage, setStage] = React.useState(0);
  // stages: 0=cube spinning, 1=cube settled + wordmark in, 2=fade out
  React.useEffect(() => {
    const t1 = setTimeout(() => setStage(1), 2400);
    const t2 = setTimeout(() => onDone && onDone(), 4200);
    return () => {
      clearTimeout(t1);
      clearTimeout(t2);
    };
  }, []);

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        background: "#000",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        gap: 32,
        zIndex: 60,
        color: "#fff",
        opacity: stage === 2 ? 0 : 1,
        transition: "opacity 350ms ease",
      }}
    >
      <SplashCube size={140} paused={stage >= 1} />

      <div
        style={{
          height: 28,
          width: 180,
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          opacity: stage >= 1 ? 1 : 0,
          transform: stage >= 1 ? "translateY(0)" : "translateY(8px)",
          transition: "opacity 600ms ease, transform 600ms ease",
        }}
      >
        <img src="assets/tkdn-wordmark.png" alt="TAKEDOWN" style={{ width: "100%", objectFit: "contain" }} />
      </div>

      {/* tiny status line — matches the industrial vibe */}
      <div
        style={{
          position: "absolute",
          bottom: 64,
          left: 0,
          right: 0,
          display: "flex",
          justifyContent: "center",
          padding: "0 32px",
          color: "rgba(255,255,255,0.45)",
          fontFamily: "Figtree, sans-serif",
          fontSize: 10,
          fontWeight: 700,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
        }}
      >
        <span>COMBAT SPORT LIVES HERE.</span>
      </div>
    </div>
  );
};

Object.assign(window, { SplashCube, SplashScreen, MarkCube, WordmarkLetter, TkdnGrid });

// ── MarkCube — small spinning cube for use as the in-app brand mark
// (32–64px). Slow auto-rotate, all 6 faces from the splash kept.
function MarkCube({ size = 32, speed = 0.4 }) {
  return <SplashCube size={size} autoRotate paused={false} />;
}

// ── TkdnGrid — compact flat 2×2 TKDN grid (the cube's BACK face,
// rendered standalone as a brand mark). Use as a small logomark in
// headers and chrome.
function TkdnGrid({ size = 28, color = "currentColor", gap = 1 }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gridTemplateRows: "1fr 1fr",
        gap,
      }}
    >
      {["T", "K", "D", "N"].map((ch) => (
        <div
          key={ch}
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            overflow: "hidden",
          }}
        >
          <WordmarkLetter letter={ch} size={(size - gap) / 2} color={color} fillRatio={0.85} />
        </div>
      ))}
    </div>
  );
}

