// kitchen.jsx — Illustrated kitchen interior + human figure + overwhelming
// piles of plastic packaging. Everything is stroked in ink on paper,
// matching the line-weight and corner radius of packaging.jsx.

const K_INK = '#0a0a0a';
const K_MUTE = '#8a867e';
const K_SOFT = 'rgba(10,10,10,0.35)';

// ─── Kitchen background drawing ──────────────────────────────────────
// A thoughtfully detailed apartment kitchen. Back wall w/ window + curtain,
// upper cabinets with molding, a counter w/ sink + cutting board + fruit
// bowl, a gas range w/ kettle, a fridge with magnets, pendant light,
// skirting + floor tiles, a rug. Helvetica-clean line work.
function KitchenRoom() {
  return (
    <g>
      {/* ── Wall panels & subtle background ── */}
      <rect x="0" y="0" width="1280" height="520" fill="#ece9e2" />
      <rect x="0" y="520" width="1280" height="200" fill="#e1ddd3" />

      <g stroke={K_INK} fill="none" strokeLinejoin="round" strokeLinecap="round">
        {/* Floor seam */}
        <line x1="0" y1="520" x2="1280" y2="520" strokeWidth="1.6" />
        {/* Skirting */}
        <line x1="0" y1="532" x2="1280" y2="532" strokeWidth="1" strokeOpacity="0.35" />
        {/* Floor tile hints (faint) */}
        {Array.from({ length: 10 }, (_, i) => (
          <line key={i} x1={0} y1={560 + i * 20} x2={1280} y2={560 + i * 20}
            strokeWidth="0.5" strokeOpacity="0.08" />
        ))}

        {/* ── Upper cabinetry run — crown molding above ── */}
        <line x1="60" y1="60" x2="1220" y2="60" strokeWidth="1.6" />
        <line x1="60" y1="70" x2="1220" y2="70" strokeWidth="0.8" strokeOpacity="0.4" />

        {/* Left cabinet bank */}
        <rect x="90" y="90" width="140" height="150" strokeWidth="1.6" />
        <rect x="230" y="90" width="140" height="150" strokeWidth="1.6" />
        <line x1="155" y1="160" x2="165" y2="160" strokeWidth="3" />
        <line x1="295" y1="160" x2="305" y2="160" strokeWidth="3" />
        {/* Inner panel lines */}
        <rect x="100" y="100" width="120" height="130" strokeWidth="0.8" strokeOpacity="0.3" />
        <rect x="240" y="100" width="120" height="130" strokeWidth="0.8" strokeOpacity="0.3" />

        {/* Center — open shelving above window */}
        <line x1="420" y1="100" x2="860" y2="100" strokeWidth="1.4" />
        <line x1="420" y1="145" x2="860" y2="145" strokeWidth="1.4" />
        {/* small jars/canisters on shelf */}
        <Jars />

        {/* Window */}
        <rect x="460" y="170" width="360" height="210" strokeWidth="1.6" />
        {/* mullions */}
        <line x1="640" y1="170" x2="640" y2="380" strokeWidth="1" strokeOpacity="0.5" />
        <line x1="460" y1="275" x2="820" y2="275" strokeWidth="1" strokeOpacity="0.5" />
        {/* window frame inner border */}
        <rect x="470" y="180" width="340" height="190" strokeWidth="0.6" strokeOpacity="0.25" />
        {/* simple horizon line inside */}
        <line x1="470" y1="320" x2="810" y2="320" strokeWidth="0.8" strokeOpacity="0.2" />
        {/* curtain tieback ghost */}
        <path d="M 450 170 Q 440 240 456 320 Q 460 370 450 380" strokeWidth="1.2" strokeOpacity="0.4" />
        <path d="M 830 170 Q 840 240 824 320 Q 820 370 830 380" strokeWidth="1.2" strokeOpacity="0.4" />

        {/* Pendant light over counter */}
        <line x1="560" y1="60" x2="560" y2="130" strokeWidth="0.8" strokeOpacity="0.6" />
        <path d="M 544 130 L 576 130 L 570 156 Q 560 162 550 156 Z" strokeWidth="1.4" fill="#d4cfc1" />
        <line x1="720" y1="60" x2="720" y2="130" strokeWidth="0.8" strokeOpacity="0.6" />
        <path d="M 704 130 L 736 130 L 730 156 Q 720 162 710 156 Z" strokeWidth="1.4" fill="#d4cfc1" />

        {/* Right cabinet bank */}
        <rect x="910" y="90" width="140" height="150" strokeWidth="1.6" />
        <rect x="1050" y="90" width="140" height="150" strokeWidth="1.6" />
        <line x1="975" y1="160" x2="985" y2="160" strokeWidth="3" />
        <line x1="1115" y1="160" x2="1125" y2="160" strokeWidth="3" />
        <rect x="920" y="100" width="120" height="130" strokeWidth="0.8" strokeOpacity="0.3" />
        <rect x="1060" y="100" width="120" height="130" strokeWidth="0.8" strokeOpacity="0.3" />

        {/* ── Countertop ── */}
        <line x1="60" y1="410" x2="1220" y2="410" strokeWidth="1.8" />
        <line x1="60" y1="422" x2="1220" y2="422" strokeWidth="0.8" strokeOpacity="0.35" />
        {/* counter front face, tiled skirt below */}
        <line x1="60" y1="410" x2="60" y2="520" strokeWidth="1.4" />
        <line x1="1220" y1="410" x2="1220" y2="520" strokeWidth="1.4" />

        {/* Cabinet doors under counter */}
        <rect x="90" y="440" width="120" height="80" strokeWidth="1" strokeOpacity="0.5" />
        <rect x="210" y="440" width="120" height="80" strokeWidth="1" strokeOpacity="0.5" />
        <line x1="204" y1="478" x2="216" y2="478" strokeWidth="2" strokeOpacity="0.5" />
        <line x1="324" y1="478" x2="336" y2="478" strokeWidth="2" strokeOpacity="0.5" />
        <rect x="930" y="440" width="120" height="80" strokeWidth="1" strokeOpacity="0.5" />
        <rect x="1050" y="440" width="120" height="80" strokeWidth="1" strokeOpacity="0.5" />
        <line x1="1044" y1="478" x2="1056" y2="478" strokeWidth="2" strokeOpacity="0.5" />
        <line x1="1164" y1="478" x2="1176" y2="478" strokeWidth="2" strokeOpacity="0.5" />

        {/* Sink on counter */}
        <rect x="480" y="422" width="200" height="14" strokeWidth="1.2" strokeOpacity="0.5" />
        <rect x="484" y="422" width="192" height="10" fill="#d8d3c6" stroke="none" />
        {/* Faucet */}
        <path d="M 560 422 L 560 376 Q 560 364 572 364 L 596 364" strokeWidth="2" />
        <circle cx="596" cy="370" r="3" fill={K_INK} />
        <line x1="548" y1="406" x2="572" y2="406" strokeWidth="2" />
        {/* cutting board */}
        <rect x="160" y="394" width="180" height="18" strokeWidth="1.4" fill="#e6e1d4" />
        <circle cx="332" cy="403" r="3" strokeWidth="1" />
        {/* fruit bowl */}
        <path d="M 770 410 Q 770 394 810 394 Q 850 394 850 410" strokeWidth="1.4" />
        <ellipse cx="810" cy="410" rx="40" ry="6" strokeWidth="1.2" />
        <circle cx="800" cy="400" r="5" strokeWidth="1.2" />
        <circle cx="812" cy="398" r="6" strokeWidth="1.2" />
        <circle cx="822" cy="402" r="5" strokeWidth="1.2" />

        {/* ── Stove (built-in, right-of-sink) ── */}
        {/* stove is embedded in counter; show the cooktop outline + back panel */}
        <rect x="880" y="380" width="20" height="30" strokeWidth="1" strokeOpacity="0.3" />
        <circle cx="935" cy="405" r="10" strokeWidth="1.2" />
        <circle cx="935" cy="405" r="3" strokeWidth="1" />
        {/* kettle */}
        <g transform="translate(1100, 390)">
          <path d="M -14 16 L -18 -4 Q -18 -14 0 -14 Q 18 -14 18 -4 L 14 16 Z" strokeWidth="1.6" fill="#d8d3c6" />
          <path d="M -20 -4 L -28 -10" strokeWidth="1.4" />
          <path d="M 18 -8 Q 28 -14 30 -20" strokeWidth="1.4" fill="none" />
          <circle cx="0" cy="-18" r="3" strokeWidth="1.2" fill="#d8d3c6" />
        </g>

        {/* ── Apron/rug under human ── */}
        <ellipse cx="230" cy="668" rx="160" ry="14" strokeWidth="1" strokeOpacity="0.35" fill="#d4cfc1" />

        {/* Baseboard outlet (charm) */}
        <rect x="380" y="540" width="14" height="18" strokeWidth="0.8" strokeOpacity="0.4" />
        <circle cx="385" cy="548" r="1" fill={K_INK} opacity="0.4" />
        <circle cx="389" cy="548" r="1" fill={K_INK} opacity="0.4" />
      </g>

      {/* A framed picture on the right wall segment */}
      <g stroke={K_INK} fill="none" strokeWidth="1.2">
        <rect x="1090" y="280" width="86" height="64" fill="#f6f4ef" />
        <path d="M 1100 326 L 1120 300 L 1140 320 L 1156 296 L 1170 326" strokeWidth="1" />
        <circle cx="1158" cy="294" r="3" strokeWidth="1" />
      </g>
    </g>
  );
}

// Small decorative jars on the open shelf
function Jars() {
  const jars = [
    { x: 440, w: 22, h: 30 },
    { x: 470, w: 18, h: 34 },
    { x: 500, w: 24, h: 28 },
    { x: 536, w: 16, h: 36 },
    { x: 564, w: 22, h: 30 },
    { x: 596, w: 20, h: 32 },
    { x: 626, w: 24, h: 30 },
    { x: 660, w: 18, h: 34 },
    { x: 690, w: 22, h: 28 },
    { x: 724, w: 20, h: 32 },
    { x: 756, w: 24, h: 30 },
    { x: 790, w: 16, h: 36 },
    { x: 820, w: 22, h: 28 },
  ];
  return (
    <g stroke={K_INK} strokeWidth="1" fill="#e6e1d4">
      {jars.map((j, i) => (
        <g key={i}>
          <rect x={j.x - j.w/2} y={140 - j.h} width={j.w} height={j.h} />
          <line x1={j.x - j.w/2 + 2} y1={140 - j.h + 4} x2={j.x + j.w/2 - 2} y2={140 - j.h + 4} strokeWidth="0.8" strokeOpacity="0.5" />
        </g>
      ))}
    </g>
  );
}

// ─── Human figure — stroked silhouette, stands facing forward ─────────
// Anchor (x, y) is the FEET baseline center. Height ≈ 220px.
function Human({ x = 260, y = 660, scale = 1 }) {
  return (
    <g transform={`translate(${x}, ${y}) scale(${scale})`}>
      {/* clothing fill (soft) */}
      <g>
        <path d="M -36 -170 L -40 -80 L 40 -80 L 36 -170 Z" fill="#d8d3c6" />
        <path d="M -26 -80 L -28 -4 L -8 -4 L -10 -80 Z" fill="#c9c3b2" />
        <path d="M 10 -80 L 8 -4 L 28 -4 L 26 -80 Z" fill="#c9c3b2" />
      </g>
      <g stroke={K_INK} strokeWidth="1.8" fill="none" strokeLinejoin="round" strokeLinecap="round">
        {/* head */}
        <circle cx="0" cy="-210" r="22" fill="#e6e1d4" />
        {/* subtle hair line */}
        <path d="M -20 -220 Q 0 -232 20 -220" strokeWidth="1.4" />
        {/* neck */}
        <line x1="-6" y1="-188" x2="-6" y2="-176" />
        <line x1="6" y1="-188" x2="6" y2="-176" />
        {/* shoulders/collar */}
        <path d="M -38 -170 Q 0 -182 38 -170" />
        {/* torso */}
        <path d="M -36 -170 L -40 -80 L 40 -80 L 36 -170" />
        {/* belt line */}
        <line x1="-40" y1="-80" x2="40" y2="-80" strokeWidth="1.2" strokeOpacity="0.5" />
        {/* left arm holding grocery bag */}
        <path d="M -38 -168 L -52 -110 L -46 -60" />
        {/* right arm relaxed */}
        <path d="M 38 -168 L 50 -110 L 54 -40" />
        {/* legs */}
        <path d="M -26 -80 L -20 -4" />
        <path d="M -10 -80 L -8 -4" />
        <path d="M 10 -80 L 8 -4" />
        <path d="M 26 -80 L 20 -4" />
        {/* shoes */}
        <path d="M -26 -2 Q -30 2 -12 2 Q -6 0 -8 -4" strokeWidth="1.6" fill="#0a0a0a" fillOpacity="0.8" />
        <path d="M 26 -2 Q 30 2 12 2 Q 6 0 8 -4" strokeWidth="1.6" fill="#0a0a0a" fillOpacity="0.8" />

        {/* Grocery t-shirt bag hanging from left hand */}
        <g transform="translate(-50, -38)">
          <path d="M -18 -22 L -10 -22 Q -10 -16 -4 -16 L 4 -16 Q 10 -16 10 -22 L 18 -22 L 22 18 Q 22 28 12 30 L -12 30 Q -22 28 -22 18 Z"
            fill="#e6e1d4" stroke={K_INK} strokeWidth="1.6" />
          {/* bag crinkle */}
          <path d="M -12 -6 Q -6 8 -10 22" strokeWidth="1" strokeOpacity="0.5" />
          <path d="M 12 -6 Q 6 8 10 22" strokeWidth="1" strokeOpacity="0.5" />
        </g>
      </g>
    </g>
  );
}

// ─── Item expansion ──────────────────────────────────────────────────
function expandItems(counts, weeks) {
  const items = [];
  const order = ['bag', 'produce', 'clamshell', 'mesh', 'bottle', 'tub', 'chip', 'film', 'tray', 'tie'];
  for (let w = 0; w < weeks; w++) {
    for (const k of order) {
      const n = Math.round(Number(counts[k]) || 0);
      for (let i = 0; i < n; i++) {
        items.push({ kind: k, weekIdx: w, itemIdx: i });
      }
    }
  }
  return items;
}

function hash(i) {
  let x = (i + 1) * 2654435761 >>> 0;
  x = ((x >>> 16) ^ x) * 0x85ebca6b >>> 0;
  x = ((x >>> 13) ^ x) * 0xc2b2ae35 >>> 0;
  x = (x >>> 16) ^ x;
  return (x >>> 0) / 4294967295;
}

const KIND_SIZE = {
  bag: 36, produce: 28, clamshell: 30, mesh: 28,
  bottle: 32, tub: 26, chip: 28, film: 22, tray: 28, tie: 16,
};

// ─── Overwhelming pile layout ────────────────────────────────────────
// Strategy: fill the kitchen from the floor up with packaging, like a
// hoarding tide rising around the human.
//
// - Zone A (floor between human and right wall): a dense tumbled pile
//   that rises as items accumulate. Width ~[360..1220]. Starts low,
//   bulges as counts grow, eventually overflows onto the counter.
// - Zone B (left of human, narrow): smaller stack, rises from floor.
// - Zone C (on the counter): once A is full, items spread along
//   the counter top (y ~400) and climb up into the cabinets.
// - Zone D (against upper cabinets / floating high): final wave,
//   fills upper space so that at many years the human is engulfed.
//
// The human pivot is ~x=260, y=660. We pile AROUND him so his head stays
// visible at moderate counts but becomes buried at year 5+.
function PackagingPile({ counts, weeks, maxRender = 1200 }) {
  const items = React.useMemo(() => expandItems(counts, weeks), [JSON.stringify(counts), weeks]);
  const N = Math.min(items.length, maxRender);

  const glyphs = [];

  // We split N items into proportional buckets that "rise" as N grows.
  // Each zone has a target capacity before the next zone starts
  // receiving more aggressively — but all zones keep accepting items
  // proportionally so growth is continuous.
  //
  // We assign item i to zone by its fractional position.
  for (let i = 0; i < N; i++) {
    const it = items[i];
    const size = KIND_SIZE[it.kind] || 24;
    const frac = i / Math.max(N, 1);

    let pos;
    // Human is at x≈260. We pile in 4 concentric "waves" around him.
    // Wave sizes grow so that as N increases the pile rises & widens
    // overwhelming the figure.
    //
    // Use a spiral-fill from the floor center-right outward and upward.
    //
    // Parameterize: each item gets (col, row) in an outward fill.
    // cols fan across [70, 1210] (the full floor) but avoid the human's
    // feet area [220, 310] at the lowest rows to keep him visible early.

    pos = placeSpiralBury(i, it, size, N);
    const rot = (hash(i * 3 + 7) - 0.5) * 46;

    glyphs.push(
      <Pkg
        key={i}
        kind={it.kind}
        cx={pos.x}
        cy={pos.y}
        size={size * (0.92 + hash(i * 3 + 9) * 0.24)}
        rotation={rot}
        sw={1.4}
        opacity={pos.opacity ?? 1}
      />
    );
  }

  return <g>{glyphs}</g>;
}

// Spiral fill that buries the human.
//
// Floor row 0: y=655, items tumbled across [70, 1210] (skip 190..330
// for the first few rows so feet show).
// Each subsequent row rises by ROW_H.
// After ~12 rows we reach counter height (~400); rows beyond that fill
// upward onto the counter surface and against the upper cabinets.
// Extra items go into the ceiling band and floating stacks.
function placeSpiralBury(i, item, size, N) {
  const ROW_H = 30;
  const COL_W = 40;
  const FLOOR_Y = 660;

  // Compute row and column using a snake-fill left-to-right / right-to-left.
  // We reserve the left-of-human column band for Zone B.
  //
  // Available horizontal bands per row — rows near the floor skip the
  // human; rows above counter height can cover everything.

  // 1) First figure out which "row" this item is in by simulating snake fill
  //    through a list of per-row capacities.
  //
  // Row capacities (how many glyphs per row, wider as we rise).
  // We precompute cumulative capacity until we find the row containing i.

  const rows = [];
  // Floor rows (y=660 down to y=420)
  for (let r = 0; r < 9; r++) {
    const y = FLOOR_Y - r * ROW_H;
    // First 4 rows skip human feet area
    const skipHuman = r < 4;
    rows.push({ y, xs: skipHuman ? [[60, 210], [340, 1220]] : [[60, 1220]] });
  }
  // Counter-top rows (items sitting on counter y~390, stacking up)
  for (let r = 0; r < 6; r++) {
    const y = 400 - r * ROW_H;
    rows.push({ y, xs: [[60, 460], [680, 1220]] });
  }
  // Human upper-body burial rows (right at the figure, x 150..360)
  for (let r = 0; r < 8; r++) {
    const y = 560 - r * ROW_H;
    rows.push({ y, xs: [[140, 380]] });
  }
  // Ceiling-level / high-back rows — only once we have tons of items
  for (let r = 0; r < 8; r++) {
    const y = 300 - r * ROW_H;
    rows.push({ y, xs: [[60, 1220]] });
  }

  // Build capacities
  let cum = 0;
  for (let r = 0; r < rows.length; r++) {
    const row = rows[r];
    const span = row.xs.reduce((s, [a, b]) => s + (b - a), 0);
    const cap = Math.max(2, Math.floor(span / COL_W));
    row.cap = cap;
    row.start = cum;
    cum += cap;
    row.end = cum;
  }
  const totalCap = cum;

  // If i is within totalCap, use the row fill. Otherwise wrap (second pass
  // layers on top with jitter for density).
  const idx = i % totalCap;
  const pass = Math.floor(i / totalCap);

  let row = rows[0], posInRow = idx;
  for (const r of rows) {
    if (idx < r.end) { row = r; posInRow = idx - r.start; break; }
  }

  // Map posInRow to x within the row's allowed spans (snake direction by row)
  const reversed = (rows.indexOf(row) % 2) === 1;
  const span = row.xs.reduce((s, [a, b]) => s + (b - a), 0);
  const step = span / row.cap;
  let t = (posInRow + 0.5) * step;
  if (reversed) t = span - t;

  // Find x in the concatenated allowed bands
  let x = 0;
  for (const [a, b] of row.xs) {
    const w = b - a;
    if (t <= w) { x = a + t; break; }
    t -= w;
  }

  // Jitter
  const jx = (hash(i * 7 + 1) - 0.5) * 16;
  const jy = (hash(i * 7 + 2) - 0.5) * 10;
  // Stack higher on subsequent passes (densify before rising)
  const passLift = pass * 6;

  return {
    x: x + jx,
    y: row.y + jy - passLift,
    opacity: pass === 0 ? 1 : 0.95,
  };
}

function OverflowBadge({ total, rendered }) {
  if (total <= rendered) return null;
  const extra = total - rendered;
  return (
    <text x={1210} y={36} textAnchor="end"
      fontFamily="'Helvetica Neue', Helvetica, Arial, sans-serif"
      fontSize="13" fontWeight="500" fill={K_INK} opacity="0.7"
      style={{ fontVariantNumeric: 'tabular-nums' }}>
      + {extra.toLocaleString()} more beyond the frame
    </text>
  );
}

Object.assign(window, {
  KitchenRoom, Human, PackagingPile, OverflowBadge, expandItems, KIND_SIZE,
});
