// scenes_b.jsx — Scene 3 (The 5 S) + Scene 4 (Decisions fact)

// ─── Scene 3 ───────────────────────────────────────────────────────────────
// Five phases revealed in sequence. Each phase is one big circle on left with
// kanji inside, with English name + meaning typeset beside it. The previous
// phase shrinks into a small dot that joins a growing row of 5 at the bottom.

const PHASES = [
  { kanji: '整理', name: 'Sort',         meaning: 'keep what matters. let the rest go.',      verb: 'seiri'   },
  { kanji: '整頓', name: 'Set in order', meaning: 'a place for everything, and everything near hand.', verb: 'seiton'  },
  { kanji: '清掃', name: 'Shine',        meaning: 'clean, so you can see what is actually there.', verb: 'seisou'  },
  { kanji: '清潔', name: 'Standardize',  meaning: 'the same small thing, at the same small time.', verb: 'seiketsu' },
  { kanji: '躾',   name: 'Sustain',      meaning: 'rhythm, not rules. come back when you can.',     verb: 'shitsuke' },
];

function SceneFiveS({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      <FiveSInner />
    </Sprite>
  );
}

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

  const perPhase = 1.8;            // seconds per phase card shown
  const introDur = 0.6;
  const outroStart = duration - 0.5;

  // Which phase is active right now?
  const phaseIdx = Math.min(PHASES.length - 1, Math.floor((localTime - introDur) / perPhase));
  const phaseClamped = Math.max(0, phaseIdx);
  const phaseLocal = (localTime - introDur) - phaseClamped * perPhase; // seconds in current phase
  const phaseT = clamp(phaseLocal / perPhase, 0, 1);

  // Big circle position (left)
  const bigCX = 640;
  const bigCY = CY - 20;
  const bigR = 300;

  // Row of 5 small dots at bottom-right
  const rowY = 920;
  const rowX0 = 1150;
  const rowGap = 120;

  return (
    <div style={{ opacity: fade }}>
      <Eyebrow x={140} y={140} text={`The five phases  ·  ${String(phaseClamped + 1).padStart(2, '0')} of 05`} size={16} />

      {/* scene-wide ledger line at top and bottom */}
      <Rule x={140} y={186} w={320 + phaseClamped * 40} color={PAL.ink} sw={1} opacity={0.9} />

      <svg width={W} height={H} style={{ position: 'absolute', inset: 0 }}>
        {/* big phase circle */}
        {PHASES.map((p, i) => {
          if (i !== phaseClamped) return null;
          const inT = Easing.easeOutCubic(clamp(phaseLocal / 0.55, 0, 1));
          const outT = i < PHASES.length - 1 && phaseLocal > perPhase - 0.35
            ? Easing.easeInCubic(clamp((phaseLocal - (perPhase - 0.35)) / 0.35, 0, 1))
            : 0;
          const r = bigR * (0.4 + 0.6 * inT) * (1 - 0.3 * outT);
          const op = inT * (1 - outT);
          return (
            <g key={i}>
              <circle cx={bigCX} cy={bigCY} r={r} fill="none" stroke={PAL.ink} strokeWidth={1.5} opacity={op} />
              {/* spinning inner arc as rhythm indicator */}
              <g transform={`translate(${bigCX} ${bigCY}) rotate(${(localTime * 40) % 360})`}>
                <circle r={r - 28} fill="none" stroke={PAL.ink} strokeWidth={1}
                  strokeDasharray={`${r * 0.6} ${r * 3}`}
                  opacity={op * 0.5} />
              </g>
              {/* inner filled dot sized by phaseT for a fill-up effect */}
              <circle cx={bigCX} cy={bigCY} r={r * phaseT * 0.75}
                fill={PAL.ink} opacity={op * 0.06} />
            </g>
          );
        })}

        {/* row of 5 progress dots */}
        {PHASES.map((_, i) => {
          const x = rowX0 + i * rowGap;
          const visited = i < phaseClamped || (i === phaseClamped && phaseT > 0.3);
          const active = i === phaseClamped;
          const pop = active ? Easing.easeOutBack(clamp(phaseLocal / 0.5, 0, 1)) : 0;
          const r = visited ? 14 : 9;
          return (
            <g key={i}>
              <circle cx={x} cy={rowY} r={r}
                fill={visited ? PAL.ink : 'none'}
                stroke={PAL.ink}
                strokeWidth={1.5}
                opacity={visited ? 1 : 0.5} />
              {active && (
                <circle cx={x} cy={rowY} r={22 + pop * 6}
                  fill="none" stroke={PAL.ink} strokeWidth={1}
                  opacity={Math.max(0, 1 - pop) * 0.8} />
              )}
            </g>
          );
        })}

        {/* connecting line under the row */}
        <line x1={rowX0 - 24} y1={rowY} x2={rowX0 + 4 * rowGap + 24} y2={rowY}
          stroke={PAL.line} strokeWidth={1} />
      </svg>

      {/* Kanji inside the big circle */}
      {PHASES.map((p, i) => {
        if (i !== phaseClamped) return null;
        const inT = Easing.easeOutCubic(clamp(phaseLocal / 0.55, 0, 1));
        const outT = phaseLocal > perPhase - 0.3
          ? Easing.easeInCubic(clamp((phaseLocal - (perPhase - 0.3)) / 0.3, 0, 1))
          : 0;
        const op = inT * (1 - outT);
        return (
          <div key={i} style={{
            position: 'absolute',
            left: bigCX, top: bigCY,
            transform: `translate(-50%, -50%) scale(${0.9 + 0.1 * inT})`,
            fontFamily: FONT.kanji, fontSize: 220, color: PAL.ink,
            opacity: op, lineHeight: 1,
            letterSpacing: '-0.04em',
          }}>
            {p.kanji}
          </div>
        );
      })}

      {/* Right-side text */}
      {PHASES.map((p, i) => {
        if (i !== phaseClamped) return null;
        const inT = Easing.easeOutCubic(clamp((phaseLocal - 0.15) / 0.5, 0, 1));
        const outT = phaseLocal > perPhase - 0.3
          ? Easing.easeInCubic(clamp((phaseLocal - (perPhase - 0.3)) / 0.3, 0, 1))
          : 0;
        const op = inT * (1 - outT);
        const ty = (1 - inT) * 28;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: 1060, top: 360,
            opacity: op,
            transform: `translateY(${ty}px)`,
          }}>
            <div style={{
              fontFamily: FONT.mono, fontSize: 14, letterSpacing: '0.25em',
              color: PAL.sub, textTransform: 'uppercase',
            }}>
              phase {String(i + 1).padStart(2, '0')}  ·  {p.verb}
            </div>
            <div style={{
              fontFamily: FONT.serif, fontSize: 140, color: PAL.ink,
              letterSpacing: '-0.025em', lineHeight: 1, marginTop: 18,
            }}>
              {p.name}.
            </div>
            <div style={{
              fontFamily: FONT.serif, fontStyle: 'italic',
              fontSize: 42, color: PAL.sub,
              letterSpacing: '-0.01em', lineHeight: 1.2, marginTop: 28,
              maxWidth: 640,
            }}>
              {p.meaning}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Scene 4 ───────────────────────────────────────────────────────────────
// "The average adult makes 35,000 decisions a day." Huge mono number that
// counts up, with dots swarming in chaos then resolving into one calm circle:
// "let the rhythm decide."

function SceneDecisions({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      <DecisionsInner />
    </Sprite>
  );
}

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

  // Chaos dots — ~120 tiny circles that swarm then settle.
  const N = 140;
  const dots = React.useMemo(() => {
    const out = [];
    for (let i = 0; i < N; i++) {
      // Random start position, random phase
      const a0 = (i * 2.3994) % (Math.PI * 2); // golden angle
      const r0 = 60 + (i * 17) % 400;
      out.push({
        ax: CX + Math.cos(a0) * r0,
        ay: CY + Math.sin(a0) * r0 * 0.7,
        phase: (i * 0.37) % 1,
        size: 3 + ((i * 7) % 4),
      });
    }
    return out;
  }, []);

  const settleStart = 2.6, settleDur = 1.2;
  const settle = Easing.easeInOutCubic(clamp((localTime - settleStart) / settleDur, 0, 1));

  return (
    <div style={{ opacity: fade }}>
      <Eyebrow x={CX} y={150} align="center" text="Fun fact  ·  №  0 2" size={18} />

      <svg width={W} height={H} style={{ position: 'absolute', inset: 0 }}>
        {dots.map((d, i) => {
          // chaos motion
          const jitterX = Math.sin(localTime * 2.4 + d.phase * 10 + i) * 40;
          const jitterY = Math.cos(localTime * 1.8 + d.phase * 7 + i * 0.3) * 30;
          const chaosX = d.ax + jitterX;
          const chaosY = d.ay + jitterY;

          // final position — a neat ring around center
          const ang = (i / N) * Math.PI * 2;
          const finalX = CX + Math.cos(ang) * 240;
          const finalY = CY + 40 + Math.sin(ang) * 240;

          const x = chaosX + (finalX - chaosX) * settle;
          const y = chaosY + (finalY - chaosY) * settle;

          return (
            <circle key={i} cx={x} cy={y} r={d.size * (1 - settle * 0.4)}
              fill={PAL.ink}
              opacity={0.4 + 0.4 * (1 - settle) + settle * 0.6} />
          );
        })}

        {/* calm center circle forms after settle */}
        <circle cx={CX} cy={CY + 40} r={120 * settle}
          fill="none" stroke={PAL.ink} strokeWidth={1.5}
          opacity={settle} />
        <circle cx={CX} cy={CY + 40} r={10}
          fill={PAL.ink} opacity={settle} />
      </svg>

      {/* Big count-up number */}
      <div style={{
        position: 'absolute', left: 0, top: 260, width: W, textAlign: 'center',
        opacity: Easing.easeOutCubic(clamp(localTime / 0.5, 0, 1)) * (1 - settle * 0.9),
        transform: `scale(${1 - settle * 0.5})`,
        transformOrigin: 'center top',
      }}>
        <div style={{
          fontFamily: FONT.mono, fontSize: 320, fontWeight: 300,
          color: PAL.ink, letterSpacing: '-0.04em',
          fontVariantNumeric: 'tabular-nums', lineHeight: 1,
        }}>
          {Math.round(35000 * Easing.easeOutCubic(clamp(localTime / 1.6, 0, 1))).toLocaleString()}
        </div>
        <div style={{
          fontFamily: FONT.serif, fontStyle: 'italic',
          fontSize: 52, color: PAL.sub,
          letterSpacing: '-0.01em', marginTop: 10,
        }}>
          decisions, on an average day.
        </div>
      </div>

      {/* Resolution text after settle */}
      <div style={{
        position: 'absolute', left: 0, top: 240, width: W, textAlign: 'center',
        opacity: settle,
        transform: `translateY(${(1 - settle) * 20}px)`,
      }}>
        <div style={{
          fontFamily: FONT.sans, fontSize: 14, fontWeight: 500,
          letterSpacing: '0.25em', color: PAL.sub, textTransform: 'uppercase',
        }}>
          &mdash; so, here&rsquo;s the idea &mdash;
        </div>
        <div style={{
          fontFamily: FONT.serif, fontStyle: 'italic',
          fontSize: 110, color: PAL.ink, marginTop: 28,
          letterSpacing: '-0.025em', lineHeight: 1,
        }}>
          let the rhythm decide.
        </div>
        <div style={{
          fontFamily: FONT.serif, fontSize: 36, color: PAL.sub,
          marginTop: 440, letterSpacing: '-0.01em',
          fontStyle: 'italic',
        }}>
          one task. then, whatever comes next.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SceneFiveS, SceneDecisions });
