// tiles.jsx — geometric primitive tiles (panot circles, stripes, checker)

const {
  useLayoutEffect: useLayoutEffectT,
  useRef: useRefT,
  useState: useStateT,
} = React;

const Stripes = ({ dir = "h", c1 = "var(--sb-red)", c2 = "var(--sb-yellow)", bands = 8 }) => {
  const pct = 100 / bands;
  const grad = dir === "h"
    ? `repeating-linear-gradient(to bottom, ${c1} 0 ${pct}%, ${c2} ${pct}% ${pct * 2}%)`
    : `repeating-linear-gradient(to right, ${c1} 0 ${pct}%, ${c2} ${pct}% ${pct * 2}%)`;
  return <div style={{ width: "100%", height: "100%", background: grad }} />;
};

// Legacy alias kept for compatibility: now rendered as a 2x2 circle grid
// so the system no longer produces the old diamond/star negative space.
const PanotTile = ({ bg = "var(--sb-bone)", dot = "var(--sb-red)" }) => (
  <div style={{
    width: "100%", height: "100%", background: bg, display: "grid",
    gridTemplateColumns: "repeat(2, 1fr)", gridTemplateRows: "repeat(2, 1fr)",
    padding: 0, gap: 0,
  }}>
    {Array.from({ length: 4 }).map((_, i) => (
      <div key={i} style={{ background: dot, borderRadius: "50%" }} />
    ))}
  </div>
);

// Single 4-pointed star (Bilbao panot motif): the original sharp star.
const StarTile = ({ bg = "var(--sb-coral)", star = "var(--sb-bone)" }) => (
  <div style={{ width: "100%", height: "100%", background: star, position: "relative", overflow: "hidden" }}>
    {[
      { left: "-50%", top: "-50%" },
      { right: "-50%", top: "-50%" },
      { left: "-50%", bottom: "-50%" },
      { right: "-50%", bottom: "-50%" },
    ].map((pos, i) => (
      <div key={i} style={{ position: "absolute", width: "100%", height: "100%", borderRadius: "50%", background: bg, ...pos }} />
    ))}
  </div>
);

// 4-petal flower tile: four full circles, each fitting exactly inside one
// of the tile's four quadrants (diameter = 50% of tile side), plus a fifth
// centre circle layered on top.
const FlowerTile = ({ bg = "transparent", petal = "var(--sb-coral)", core = "var(--sb-red)" }) => {
  // Each quadrant circle: diameter = 50% of the tile side, centered in its quadrant.
  const quads = [
    { left: "25%", top: "25%" }, // top-left quadrant
    { left: "75%", top: "25%" }, // top-right quadrant
    { left: "25%", top: "75%" }, // bottom-left quadrant
    { left: "75%", top: "75%" }, // bottom-right quadrant
  ];
  return (
    <div style={{ width: "100%", height: "100%", background: bg, position: "relative", overflow: "hidden" }}>
      {quads.map((pos, i) => (
        <div key={i} style={{
          position: "absolute", width: "50%", aspectRatio: "1 / 1",
          borderRadius: "50%", background: petal,
          transform: "translate(-50%, -50%)", ...pos,
        }} />
      ))}
      <div style={{
        position: "absolute", left: "50%", top: "50%",
        width: "50%", aspectRatio: "1 / 1",
        transform: "translate(-50%, -50%)",
        borderRadius: "50%", background: core,
      }} />
    </div>
  );
};

// 2x2 small dot grid — circles fully fill each subcell, edges flush to tile
const DotGrid = ({ bg = "var(--sb-bone)", dot = "var(--sb-ink)", n = 2 }) => (
  <div style={{ width: "100%", height: "100%", background: bg, display: "grid",
    gridTemplateColumns: `repeat(${n}, 1fr)`, gridTemplateRows: `repeat(${n}, 1fr)`,
    padding: 0, gap: 0 }}>
    {Array.from({ length: n * n }).map((_, i) => (
      <div key={i} style={{ background: dot, borderRadius: "50%" }} />
    ))}
  </div>
);

// Checker
const Checker = ({ a = "var(--sb-coral)", b = "var(--sb-ink)", n = 2 }) => (
  <div style={{ width: "100%", height: "100%", display: "grid",
    gridTemplateColumns: `repeat(${n}, 1fr)`, gridTemplateRows: `repeat(${n}, 1fr)` }}>
    {Array.from({ length: n * n }).map((_, i) => {
      const r = Math.floor(i / n);
      const c = i % n;
      return <div key={i} style={{ background: (r + c) % 2 === 0 ? a : b }} />;
    })}
  </div>
);

const SborMark = ({ size = 22, invert = false }) => (
  <img src="assets/icons/logo-sborka-mark.svg" alt="" style={{
    height: size, width: "auto", display: "block",
    filter: invert ? "invert(1)" : undefined,
  }} />
);

// ── pattern composers — each cell is a strict 1×1 module square ──

// Build a generator for a panel of `cols × rows` square cells.
// `cells` is an array of pattern descriptors (length cols*rows); each descriptor
// is { kind, ...props } — kind ∈ panot|star|stripes|dots|check
const TileCell = ({ desc }) => {
  if (!desc) return null;
  switch (desc.kind) {
    case "panot": return <PanotTile bg={desc.bg} dot={desc.dot} />;
    case "star":  return <StarTile bg={desc.bg || "var(--sb-coral)"} star={desc.star || "var(--sb-bone)"} />;
    case "flower": return <FlowerTile bg={desc.bg || "transparent"} petal={desc.petal || desc.star} core={desc.core || "var(--sb-red)"} />;
    case "stripes": return <Stripes dir={desc.dir} c1={desc.c1} c2={desc.c2} bands={desc.bands || 8} />;
    case "dots":  return <DotGrid bg={desc.bg} dot={desc.dot} n={desc.n || 2} />;
    case "check": return <Checker a={desc.a} b={desc.b} n={desc.n || 2} />;
    case "solid": return <div style={{ width: "100%", height: "100%", background: desc.bg }} />;
    default: return null;
  }
};

const TILE_ALIGN = {
  start: "flex-start",
  center: "center",
  end: "flex-end",
};

const useTileBox = () => {
  const ref = useRefT(null);
  const [box, setBox] = useStateT({ width: 0, height: 0 });

  useLayoutEffectT(() => {
    const el = ref.current;
    if (!el) return undefined;

    let frame = 0;
    const update = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => {
        const next = {
          width: el.clientWidth,
          height: el.clientHeight,
        };
        setBox((prev) => (
          prev.width === next.width && prev.height === next.height ? prev : next
        ));
      });
    };

    update();

    let ro;
    if (window.ResizeObserver) {
      ro = new window.ResizeObserver(update);
      ro.observe(el);
    } else {
      window.addEventListener("resize", update);
    }

    return () => {
      cancelAnimationFrame(frame);
      if (ro) ro.disconnect();
      else window.removeEventListener("resize", update);
    };
  }, []);

  return [ref, box];
};

// Generic square-module tile panel.
// The outer box can be any size; the inner grid self-sizes so every module
// stays square and the pattern anchors within the available space.
const TilePanel = ({ cols, rows, cells, alignX = "center", alignY = "center" }) => {
  const [ref, box] = useTileBox();
  const unit = box.width > 0 && box.height > 0
    ? Math.min(box.width / cols, box.height / rows)
    : 0;
  const gridWidth = unit > 0 ? unit * cols : "100%";
  const gridHeight = unit > 0 ? unit * rows : "100%";

  return (
    <div ref={ref} style={{
      width: "100%",
      height: "100%",
      position: "relative",
      overflow: "hidden",
    }}>
      <div style={{
        position: "absolute",
        inset: 0,
        display: "flex",
        justifyContent: TILE_ALIGN[alignX] || TILE_ALIGN.center,
        alignItems: TILE_ALIGN[alignY] || TILE_ALIGN.center,
      }}>
        <div style={{
          width: gridWidth,
          height: gridHeight,
          display: "grid",
          gridTemplateColumns: `repeat(${cols}, 1fr)`,
          gridTemplateRows: `repeat(${rows}, 1fr)`,
          gridAutoFlow: "dense",
        }}>
          {cells.filter(Boolean).map((desc, i) => {
            const s = desc.span === 2 ? { gridColumn: "span 2", gridRow: "span 2" } : null;
            return (
              <div key={i} style={{ overflow: "hidden", position: "relative", ...s }}>
                <TileCell desc={desc} />
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// HERO pattern: 4 cols × 3 rows of square modules, mixing the four
// approved motif families: flower, dots, stripes, and checker.
const HERO_DEFAULT_CELLS = [
  // big 2×2 flower at top-left
  { kind: "flower", span: 2, bg: "var(--sb-yellow)", petal: "var(--sb-coral)", core: "var(--sb-red)" },
  { kind: "dots", bg: "var(--sb-coral)", dot: "var(--sb-red)", n: 2 },
  { kind: "stripes", dir: "v", c1: "var(--sb-teal)", c2: "var(--sb-yellow)", bands: 8 },
  { kind: "check", a: "var(--sb-periwinkle)", b: "var(--sb-yellow)", n: 2 },
  { kind: "flower", bg: "var(--sb-teal)", petal: "var(--sb-yellow)", core: "var(--sb-periwinkle)" },
  // bottom row (4 cells)
  { kind: "dots", bg: "var(--sb-mint)", dot: "var(--sb-red)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-coral)", c2: "var(--sb-periwinkle)", bands: 8 },
  { kind: "check", a: "var(--sb-yellow)", b: "var(--sb-red)", n: 2 },
  { kind: "flower", bg: "var(--sb-sky)", petal: "var(--sb-coral)", core: "var(--sb-teal)" },
];
const HeroPattern = ({ cells = HERO_DEFAULT_CELLS }) => (
  <TilePanel cols={4} rows={3} cells={cells} />
);

// JUR pattern: 4 cols × 4 rows of squares with one 2×2 mega-flower.
const JUR_DEFAULT_CELLS = [
  { kind: "dots", bg: "var(--sb-coral)", dot: "var(--sb-periwinkle)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-coral)", c2: "var(--sb-periwinkle)", bands: 8 },
  // big 2×2 flower at top-right (cols 3–4, rows 1–2)
  { kind: "flower", span: 2, bg: "var(--sb-teal)", petal: "var(--sb-yellow)", core: "var(--sb-coral)" },
  { kind: "stripes", dir: "v", c1: "var(--sb-yellow)", c2: "var(--sb-red)", bands: 8 },
  { kind: "stripes", dir: "h", c1: "var(--sb-periwinkle)", c2: "var(--sb-bone)", bands: 8 },

  { kind: "check", a: "var(--sb-bone)", b: "var(--sb-red)", n: 2 },
  { kind: "dots", bg: "var(--sb-coral)", dot: "var(--sb-red)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-teal)", c2: "var(--sb-bone)", bands: 8 },
  { kind: "dots", bg: "var(--sb-yellow)", dot: "var(--sb-red)", n: 2 },

  { kind: "check", a: "var(--sb-periwinkle)", b: "var(--sb-coral)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-teal)", c2: "var(--sb-bone)", bands: 8 },
  { kind: "stripes", dir: "v", c1: "var(--sb-coral)", c2: "var(--sb-bone)", bands: 8 },
  { kind: "dots", bg: "var(--sb-yellow)", dot: "var(--sb-red)", n: 2 },
];
const JurPattern = ({ cells = JUR_DEFAULT_CELLS }) => (
  <TilePanel cols={4} rows={4} cells={cells} />
);

// BIG CTA art: 4 cols × 4 rows of squares with one 2×2 mega-flower mid-block.
const BIGCTA_DEFAULT_CELLS = [
  { kind: "check", a: "var(--sb-yellow)", b: "var(--sb-red)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-red)", c2: "var(--sb-yellow)", bands: 8 },
  { kind: "dots", bg: "var(--sb-bone)", dot: "var(--sb-red)", n: 2 },
  { kind: "flower", bg: "var(--sb-coral)", petal: "var(--sb-yellow)", core: "var(--sb-periwinkle)" },

  { kind: "dots",  bg: "var(--sb-coral)", dot: "var(--sb-red)", n: 2 },
  // big 2×2 flower in the middle (cols 2–3, rows 2–3)
  { kind: "flower", span: 2, bg: "var(--sb-teal)", petal: "var(--sb-yellow)", core: "var(--sb-red)" },
  { kind: "stripes", dir: "h", c1: "var(--sb-periwinkle)", c2: "var(--sb-bone)", bands: 8 },

  { kind: "stripes", dir: "v", c1: "var(--sb-bone)", c2: "var(--sb-red)", bands: 8 },
  { kind: "check", a: "var(--sb-coral)", b: "var(--sb-periwinkle)", n: 2 },

  { kind: "dots", bg: "var(--sb-bone)", dot: "var(--sb-red)", n: 2 },
  { kind: "check", a: "var(--sb-yellow)", b: "var(--sb-red)", n: 2 },
  { kind: "stripes", dir: "h", c1: "var(--sb-teal)", c2: "var(--sb-coral)", bands: 8 },
  { kind: "stripes", dir: "h", c1: "var(--sb-periwinkle)", c2: "var(--sb-bone)", bands: 8 },
];
const BigCtaArt = ({ cells = BIGCTA_DEFAULT_CELLS }) => (
  <TilePanel cols={4} rows={4} cells={cells} />
);

// Per-level decorative motif inside course tile bottom-right — fixed 84×84 square
const LevelMotif = ({ kind }) => {
  const sz = { width: 84, height: 84, position: "absolute", right: 16, top: 16, opacity: 0.95 };
  if (kind === 0) return <div style={sz}><DotGrid bg="transparent" dot="var(--sb-ink)" n={2} /></div>;
  if (kind === 1) return <div style={sz}><DotGrid bg="transparent" dot="var(--sb-ink)" n={3} /></div>;
  if (kind === 2) return <div style={sz}><Stripes dir="v" c1="var(--sb-ink)" c2="transparent" bands={4} /></div>;
  if (kind === 3) return <div style={sz}><Checker a="var(--sb-ink)" b="transparent" n={2} /></div>;
  if (kind === 4) return <div style={sz}><FlowerTile bg="transparent" petal="var(--sb-ink)" core="var(--sb-bone)" /></div>;
  return <div style={sz}><DotGrid bg="transparent" dot="var(--sb-ink)" n={4} /></div>;
};

Object.assign(window, {
  Stripes, PanotTile, StarTile, FlowerTile, DotGrid, Checker, SborMark,
  HeroPattern, JurPattern, BigCtaArt, LevelMotif,
  TilePanel, TileCell,
  HERO_DEFAULT_CELLS, JUR_DEFAULT_CELLS, BIGCTA_DEFAULT_CELLS,
});
