// Nested squares visualization. The container is a square; the base square
// sits inside it inset by SQ_PAD on all four sides, so the chart stays
// geometrically centered in the column and the count tags (BASE label
// above, × tags to the right) have breathing room without overflowing the
// container.
//
// Sizing is fluid: container fills its parent column's width (capped at
// --squares-max-w, floored at SQ_MIN_W) and its height matches its width.
// To resize the chart, edit --squares-max-w in styles/responsive.css —
// there's a desktop value at :root and a wrapped (<=1080px) override.

const SQ_MIN_W = 220;
const SQ_PAD = 40; // breathing room around the base square (each side)
const SQ_DEFAULT_SHRINK = 0.72;
const SQ_MIN_INNER_RATIO = 88 / 252; // floor on the innermost (ME) square as % of base

function NestedSquares({ active, pool }) {
  const activeFilters = window.RARE_FILTERS.filter((f) => active[f.id]);
  const hasMe = activeFilters.length > 0;

  // Measure the container's rendered width so internal pixel math (positions,
  // square sizes, font sizes) scales with whatever space the parent gives us.
  const containerRef = React.useRef(null);
  const [W, setW] = React.useState(SQ_MIN_W);

  React.useLayoutEffect(() => {
    if (!containerRef.current) return;
    const el = containerRef.current;
    const measure = () => {
      const w = el.offsetWidth;
      if (w > 0) setW(w);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  // Container is square (W × W). Base square is inset by SQ_PAD on every
  // side so labels can overflow the base into the padding zone without
  // leaving the container.
  const SQ_BASE = Math.max(0, W - 2 * SQ_PAD);
  const SQ_MIN_INNER = SQ_BASE * SQ_MIN_INNER_RATIO;

  // Pick the largest SHRINK between the default and the one needed to keep
  // the innermost (ME) square ≥ SQ_MIN_INNER so its label/text stays legible.
  const innerLevels = activeFilters.length + (hasMe ? 1 : 0);
  let shrink = SQ_DEFAULT_SHRINK;
  if (innerLevels > 0) {
    const minShrink = Math.pow(SQ_MIN_INNER / SQ_BASE, 1 / innerLevels);
    shrink = Math.max(SQ_DEFAULT_SHRINK, minShrink);
  }

  const sides = [SQ_BASE];
  for (let i = 0; i < activeFilters.length; i++) {
    sides.push(sides[sides.length - 1] * shrink);
  }
  if (hasMe) sides.push(sides[sides.length - 1] * shrink);

  const rendered = sides;
  const bottom = W - SQ_PAD;

  // Layout:
  //   i=0                       → base (BASE tag)
  //   i=1..activeFilters.length → one ring per active filter (count tag)
  //   i=activeFilters.length+1  → ME (only if hasMe; mustard, ME label, no tag)
  const squares = [];
  let running = window.BASE_POP;
  for (let i = 0; i < rendered.length; i++) {
    const size = rendered[i];
    const y = bottom - size;
    if (i === 0) {
      squares.push({
        kind: "base",
        id: "__base",
        x: SQ_PAD,
        y,
        size,
        count: window.BASE_POP,
      });
    } else if (i <= activeFilters.length) {
      const f = activeFilters[i - 1];
      running *= f.passRate;
      squares.push({
        kind: "filter",
        id: f.id,
        x: SQ_PAD,
        y,
        size,
        color: f.color,
        colorRgb: f.colorRgb,
        count: running,
        filter: f,
      });
    } else {
      squares.push({ kind: "me", id: "__me", x: SQ_PAD, y, size });
    }
  }

  const pctText = window.formatPct((pool / window.BASE_POP) * 100);

  return (
    <div
      ref={containerRef}
      style={{
        fontFamily: "var(--font-mono)",
        position: "relative",
        width: "100%",
        maxWidth: "var(--squares-max-w)",
        minWidth: SQ_MIN_W,
        height: W,
      }}
    >
      {squares.map((s, i) => {
        const isMe = s.kind === "me";
        const isBase = s.kind === "base";
        const total = squares.length;
        const depthT = total > 1 ? i / (total - 1) : 0;
        const borderAlpha = (50 + depthT * 130) / 255;
        const fillAlpha = (8 + depthT * 22) / 255;
        const borderColor = isMe
          ? "var(--accent)"
          : isBase
            ? `rgba(var(--fg-rgb), ${borderAlpha.toFixed(3)})`
            : `rgba(${s.colorRgb}, ${borderAlpha.toFixed(3)})`;
        const borderWidth = isMe ? 2 : Math.max(0.75, 0.5 + depthT * 0.9);
        const meGlow = isMe
          ? "0 0 0 1px rgba(var(--accent-rgb), 0.35), 0 0 18px rgba(var(--accent-rgb), 0.28)"
          : "none";
        const cornerRadius = isMe ? 2 : 0;
        const bgFill = isMe
          ? "var(--accent)"
          : isBase
            ? `rgba(var(--fg-rgb), ${fillAlpha.toFixed(3)})`
            : `rgba(${s.colorRgb}, ${fillAlpha.toFixed(3)})`;

        const innerWidth = s.size - 12;
        const pctFontSize = isMe
          ? Math.min(20, Math.max(11, innerWidth / (pctText.length * 0.6)))
          : 0;

        return (
          <React.Fragment key={s.id}>
            <div
              style={{
                position: "absolute",
                left: s.x,
                top: s.y,
                width: s.size,
                height: s.size,
                border: `${borderWidth}px solid ${borderColor}`,
                background: bgFill,
                borderRadius: cornerRadius,
                boxShadow: meGlow,
                transition:
                  "left 0.55s cubic-bezier(0.22,0.9,0.3,1), top 0.55s cubic-bezier(0.22,0.9,0.3,1), width 0.55s cubic-bezier(0.22,0.9,0.3,1), height 0.55s cubic-bezier(0.22,0.9,0.3,1), background 0.3s, border-color 0.3s, box-shadow 0.3s",
                zIndex: i + 1,
                display: isMe ? "flex" : "block",
                alignItems: "center",
                justifyContent: "center",
                pointerEvents: "none",
                boxSizing: "border-box",
                overflow: "hidden",
              }}
            >
              {isMe && (
                <div
                  style={{
                    fontFamily: "var(--font-mono)",
                    color: "#0a0807",
                    fontWeight: 700,
                    lineHeight: 1.05,
                    textAlign: "center",
                    padding: 4,
                    width: "100%",
                    boxSizing: "border-box",
                  }}
                >
                  <div
                    style={{
                      fontSize: Math.max(7, Math.min(10, s.size / 9)),
                      letterSpacing: "0.18em",
                      opacity: 0.85,
                    }}
                  >
                    ME
                  </div>
                  <div
                    style={{
                      fontSize: pctFontSize,
                      marginTop: 2,
                      letterSpacing: "-0.01em",
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {pctText}
                  </div>
                  <div
                    style={{
                      fontSize: Math.max(6.5, Math.min(8.5, s.size / 11)),
                      letterSpacing: "0.14em",
                      opacity: 0.6,
                      marginTop: 1,
                    }}
                  >
                    OF ALL DEVS
                  </div>
                </div>
              )}
            </div>

            {!isMe && (
              <div
                style={{
                  position: "absolute",
                  left: s.x + s.size,
                  top: s.y - 8,
                  transform: "translateX(-2px)",
                  fontFamily: "var(--font-mono)",
                  color: isBase
                    ? "rgba(var(--fg-rgb), 0.5)"
                    : `rgba(${s.colorRgb}, 0.85)`,
                  background: "var(--bg)",
                  padding: "1px 6px",
                  whiteSpace: "nowrap",
                  fontVariantNumeric: "tabular-nums",
                  transition:
                    "left 0.55s cubic-bezier(0.22,0.9,0.3,1), top 0.55s cubic-bezier(0.22,0.9,0.3,1), color 0.3s",
                  zIndex: 30,
                  pointerEvents: "none",
                  lineHeight: 1.15,
                }}
              >
                {isBase ? (
                  <>
                    <div style={{ fontSize: 9, letterSpacing: "0.04em" }}>
                      {window.formatPool(s.count)}
                    </div>
                    <div
                      style={{
                        fontSize: 7.5,
                        letterSpacing: "0.16em",
                        opacity: 0.55,
                      }}
                    >
                      BASE
                    </div>
                  </>
                ) : (
                  (() => {
                    const r = s.filter.passRate;
                    const txt =
                      r < 0.01
                        ? `${(r * 100).toFixed(2)}%`
                        : `${(r * 100).toFixed(1)}%`;
                    return (
                      <div
                        style={{
                          fontSize: 9,
                          letterSpacing: "0.06em",
                        }}
                      >
                        × {txt}
                      </div>
                    );
                  })()
                )}
              </div>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

window.NestedSquares = NestedSquares;
