// scenes_c.jsx — Scene 5 (Rooms & the neediest) + Scene 6 (Outro)

// ─── Scene 5 ───────────────────────────────────────────────────────────────
// Many small circles representing rooms of the home. One glows: the neediest.
// A line of text appears describing the rhythm.

const ROOMS = [
  { label: 'kitchen',  days: 2 },
  { label: 'living',   days: 5 },
  { label: 'bed',      days: 3 },
  { label: 'bath',     days: 7 },
  { label: 'entry',    days: 4 },
  { label: 'dining',   days: 6 },
  { label: 'office',   days: 9 },  // neediest
  { label: 'laundry',  days: 3 },
  { label: 'garage',   days: 8 },
  { label: 'yard',     days: 5 },
  { label: 'closet',   days: 6 },
  { label: 'pantry',   days: 4 },
];
const NEEDIEST_IDX = 6;

function SceneRooms({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      <RoomsInner />
    </Sprite>
  );
}

function RoomsInner() {
  const { localTime, duration } = useSprite();
  const fade = useSpriteFade({ inDur: 0.5, outDur: 0.5 });

  // Layout: scatter circles in a loose composition around canvas.
  // Stable positions from index.
  const layouts = React.useMemo(() => {
    const positions = [
      [520, 540], [780, 380], [1040, 560], [1300, 400],
      [420, 760], [700, 720], [960, 820], [1220, 720],
      [1480, 580], [380, 400], [1460, 820], [1160, 360],
    ];
    return ROOMS.map((r, i) => ({
      ...r,
      x: positions[i][0],
      y: positions[i][1],
      radius: 36 + r.days * 6, // bigger = more days since last tended
      appear: 0.2 + i * 0.08,
    }));
  }, []);

  // Neediest pulse
  const pulse = (Math.sin(localTime * 2.0) + 1) / 2;

  return (
    <div style={{ opacity: fade }}>
      <Eyebrow x={140} y={140} text="Fun fact  ·  №  0 3  ·  the neediest room" size={16} />
      <Rule x={140} y={186} w={520} color={PAL.ink} sw={1} />

      {/* Headline */}
      <div style={{
        position: 'absolute', left: 140, top: 230,
        fontFamily: FONT.serif, fontSize: 90, color: PAL.ink,
        letterSpacing: '-0.025em', lineHeight: 1,
        maxWidth: 1000,
        opacity: Easing.easeOutCubic(clamp((localTime - 0.2) / 0.8, 0, 1)),
        transform: `translateY(${(1 - Easing.easeOutCubic(clamp((localTime - 0.2) / 0.8, 0, 1))) * 24}px)`,
      }}>
        Your home has <span style={{ fontStyle: 'italic', color: PAL.sub }}>a rhythm</span> of its own.
      </div>
      <div style={{
        position: 'absolute', left: 140, top: 400,
        fontFamily: FONT.serif, fontStyle: 'italic',
        fontSize: 40, color: PAL.sub,
        letterSpacing: '-0.01em', maxWidth: 720, lineHeight: 1.25,
        opacity: Easing.easeOutCubic(clamp((localTime - 0.7) / 0.8, 0, 1)),
      }}>
        Each circle is a room. The bigger it grows, the longer since it&rsquo;s been tended to.
      </div>

      {/* Rooms SVG */}
      <svg width={W} height={H} style={{ position: 'absolute', inset: 0 }}>
        {layouts.map((room, i) => {
          const a = Easing.easeOutBack(clamp((localTime - room.appear) / 0.6, 0, 1));
          const isNeediest = i === NEEDIEST_IDX;
          const breathe = Math.sin(localTime * 0.8 + i) * 2;
          const r = room.radius * a + breathe;

          const strokeOp = a;
          const fillOp = isNeediest ? 0.08 + pulse * 0.12 : 0;

          return (
            <g key={i} transform={`translate(${room.x} ${room.y})`}>
              <circle r={r + (isNeediest ? 20 * pulse : 0)}
                fill="none" stroke={PAL.ink} strokeWidth={isNeediest ? 0 : 0}
                opacity={isNeediest ? (0.2 + pulse * 0.3) * a : 0}
              />
              <circle r={r} fill={PAL.ink} opacity={fillOp * a} />
              <circle r={r} fill="none" stroke={PAL.ink}
                strokeWidth={isNeediest ? 2.2 : 1.3}
                opacity={strokeOp * (isNeediest ? 1 : 0.6)} />
              {/* tick mark at top */}
              <line x1={0} y1={-r} x2={0} y2={-r - 8}
                stroke={PAL.ink} strokeWidth={1} opacity={strokeOp * 0.5} />
              {/* label */}
              <text y={r + 28} textAnchor="middle"
                style={{
                  fontFamily: FONT.serif,
                  fontSize: isNeediest ? 30 : 22,
                  fill: isNeediest ? PAL.ink : PAL.sub,
                  fontStyle: 'italic',
                  letterSpacing: '-0.01em',
                }}
                opacity={strokeOp}>
                {room.label}
              </text>
              <text y={r + 54} textAnchor="middle"
                style={{
                  fontFamily: FONT.mono, fontSize: 13,
                  fill: isNeediest ? PAL.ink : PAL.mute,
                  letterSpacing: '0.12em',
                }}
                opacity={strokeOp}>
                {room.days}d
              </text>
            </g>
          );
        })}
      </svg>

      {/* Callout that points to neediest after arrivals */}
      <div style={{
        position: 'absolute',
        left: layouts[NEEDIEST_IDX].x + layouts[NEEDIEST_IDX].radius + 120,
        top: layouts[NEEDIEST_IDX].y - 30,
        opacity: Easing.easeOutCubic(clamp((localTime - 2.6) / 0.8, 0, 1)),
        transform: `translateX(${(1 - Easing.easeOutCubic(clamp((localTime - 2.6) / 0.8, 0, 1))) * -20}px)`,
      }}>
        <div style={{
          fontFamily: FONT.mono, fontSize: 12,
          letterSpacing: '0.28em', color: PAL.sub,
          textTransform: 'uppercase',
        }}>
          next &rarr;
        </div>
        <div style={{
          fontFamily: FONT.serif, fontStyle: 'italic',
          fontSize: 44, color: PAL.ink,
          marginTop: 6, letterSpacing: '-0.01em',
        }}>
          the one most waiting.
        </div>
      </div>
    </div>
  );
}

// ─── Scene 6 ───────────────────────────────────────────────────────────────
// Outro: rooms collapse back into 5 circles → into 1 → text closes the piece.

function SceneOutro({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      <OutroInner />
    </Sprite>
  );
}

function OutroInner() {
  const { localTime, duration } = useSprite();
  const fade = useSpriteFade({ inDur: 0.4, outDur: 0.8 });

  // Phase 1 (0-1.4): many dots collapse to 5
  // Phase 2 (1.4-2.6): 5 circles rotate and merge to 1
  // Phase 3 (2.6-): text mantra holds

  const t1 = Easing.easeInOutCubic(clamp(localTime / 1.4, 0, 1));
  const t2 = Easing.easeInOutCubic(clamp((localTime - 1.4) / 1.2, 0, 1));
  const t3 = clamp((localTime - 2.6) / 0.8, 0, 1);

  const N = 60;
  const dots = React.useMemo(() => {
    const out = [];
    for (let i = 0; i < N; i++) {
      const a = (i / N) * Math.PI * 2;
      const r = 280 + ((i * 31) % 240);
      out.push({
        ax: CX + Math.cos(a) * r,
        ay: CY + Math.sin(a) * r * 0.7,
        size: 3 + ((i * 11) % 5),
      });
    }
    return out;
  }, []);

  // 5 target positions forming a small pinwheel
  const fiveTarget = (i) => {
    const a = -Math.PI / 2 + (i / 5) * Math.PI * 2;
    const r = 160 * (1 - t2);
    return [CX + Math.cos(a) * r, CY + Math.sin(a) * r - 40];
  };

  return (
    <div style={{ opacity: fade }}>
      <svg width={W} height={H} style={{ position: 'absolute', inset: 0 }}>
        {/* scatter dots collapse to 5 attractors */}
        {dots.map((d, i) => {
          const bucket = i % 5;
          const [fx, fy] = fiveTarget(bucket);
          const x = d.ax + (fx - d.ax) * t1;
          const y = d.ay + (fy - d.ay) * t1;
          const size = d.size * (1 - t1 * 0.5) * (1 - t2);
          return (
            <circle key={i} cx={x} cy={y} r={size}
              fill={PAL.ink} opacity={(1 - t2) * 0.9} />
          );
        })}

        {/* 5 circles that collapse to 1 */}
        {[0, 1, 2, 3, 4].map((i) => {
          const [fx, fy] = fiveTarget(i);
          const rot = (localTime * 40) % 360;
          const r = (80 + 20 * (1 - t2)) * (1 - t3 * 0.4);
          const cx = CX + (fx - CX) * (1);
          const cy = (CY - 40) + (fy - (CY - 40)) * (1);
          return (
            <g key={i} transform={`rotate(${rot * 0.15}, ${CX}, ${CY - 40})`} opacity={t1 * (1 - t3 * 0.6)}>
              <circle cx={cx} cy={cy} r={r} fill="none" stroke={PAL.ink} strokeWidth={1.5} />
            </g>
          );
        })}

        {/* final unified circle */}
        <circle cx={CX} cy={CY - 40} r={60 + t3 * 80}
          fill="none" stroke={PAL.ink} strokeWidth={1.5}
          opacity={t2} />
        <circle cx={CX} cy={CY - 40} r={8 + t3 * 4}
          fill={PAL.ink} opacity={t2} />
      </svg>

      {/* Closing text */}
      <div style={{
        position: 'absolute', left: 0, top: 720, width: W, textAlign: 'center',
        opacity: Easing.easeOutCubic(clamp((localTime - 2.4) / 0.8, 0, 1)),
      }}>
        <div style={{
          fontFamily: FONT.serif, fontStyle: 'italic',
          fontSize: 130, color: PAL.ink,
          letterSpacing: '-0.025em', lineHeight: 1,
        }}>
          breathe.
        </div>
        <div style={{
          fontFamily: FONT.serif, fontSize: 44, color: PAL.sub,
          marginTop: 36, letterSpacing: '-0.01em',
          fontStyle: 'italic',
        }}>
          one room. one task. one day at a time.
        </div>
        <div style={{
          fontFamily: FONT.sans, fontSize: 13, fontWeight: 500,
          letterSpacing: '0.3em', textTransform: 'uppercase',
          color: PAL.mute, marginTop: 64,
        }}>
          calmer home  ·  the 5 s, at home
        </div>
      </div>
    </div>
  );
}

// ─── Scene transition dots (the 5 phase markers live across the whole timeline) ─
// A persistent tiny 5-dot row in the bottom-left that updates its "current"
// dot by scene. Ambient, not the focus.
function SceneProgress({ totalDuration, chapters }) {
  const time = useTime();
  // Which chapter (by scene start times) are we in?
  let cur = 0;
  for (let i = 0; i < chapters.length; i++) {
    if (time >= chapters[i].start) cur = i;
  }
  return (
    <div style={{
      position: 'absolute', left: 140, bottom: 90,
      display: 'flex', alignItems: 'center', gap: 16,
      fontFamily: FONT.mono, fontSize: 13,
      color: PAL.sub, letterSpacing: '0.18em',
      textTransform: 'uppercase',
    }}>
      <div style={{ display: 'flex', gap: 10 }}>
        {chapters.map((c, i) => (
          <div key={i} style={{
            width: i === cur ? 22 : 8,
            height: 8,
            borderRadius: 4,
            background: i <= cur ? PAL.ink : 'transparent',
            border: `1px solid ${PAL.ink}`,
            transition: 'width 400ms cubic-bezier(0.4,0,0.2,1)',
            opacity: i <= cur ? 1 : 0.4,
          }} />
        ))}
      </div>
      <div>{chapters[cur].label}</div>
    </div>
  );
}

// Footer time counter, top-right
function SceneClock({ totalDuration }) {
  const time = useTime();
  const t = Math.max(0, time);
  const m = Math.floor(t / 60);
  const s = Math.floor(t % 60);
  const cs = Math.floor((t * 100) % 100);
  const td = totalDuration;
  const tm = Math.floor(td / 60);
  const ts = Math.floor(td % 60);
  return (
    <div style={{
      position: 'absolute', right: 140, top: 140,
      fontFamily: FONT.mono, fontSize: 14,
      color: PAL.sub, letterSpacing: '0.15em',
      fontVariantNumeric: 'tabular-nums',
    }}>
      {`${String(m).padStart(1,'0')}:${String(s).padStart(2,'0')}.${String(cs).padStart(2,'0')}`}
      <span style={{ color: PAL.ghost, margin: '0 10px' }}>/</span>
      {`${String(tm).padStart(1,'0')}:${String(ts).padStart(2,'0')}.00`}
    </div>
  );
}

Object.assign(window, { SceneRooms, SceneOutro, SceneProgress, SceneClock });
