// ═══════════════════════════════════════════════════════════════════════════
// SOLUTION ROOM — five beats.
//
// The room closes the loop the Problem room opens. The buyer cannot see his
// stockouts, so he rationally over-orders; beat 3 is that blind spot being
// removed, and it is the peak of the deck. Reconciliation (beat 2) is
// plumbing and is deliberately given a fifth of the attention, not half.
//
// Same interaction model as before: auto-advance, click to advance early.
// ═══════════════════════════════════════════════════════════════════════════

const { useState: useFS, useEffect: useFE, useRef: useFR } = React;

// Beat 3 holds longest because it carries the argument.
// Beat 4 is the fifth panel and holds longest.
const FIX_HOLD = [4000, 5000, 4000, 6000, 4000, 4000];

function fixReduced() {
  if (window.__STATIC) return true;
  try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; }
  catch (e) { return false; }
}

// ── shared atoms. No cards, borders or fills anywhere except the four
//    readouts in beat 2, where the separation is the argument.
function FLabel({ children, tone }) {
  return (
    <div style={{
      fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
      letterSpacing: '0.08em', textTransform: 'uppercase',
      color: tone || 'var(--rt-label)',
    }}>{children}</div>
  );
}

function FBody({ children, size, style }) {
  return (
    <p style={{
      margin: 0, maxWidth: '62ch',
      fontFamily: 'var(--sans)', fontSize: size || 18, lineHeight: 1.5,
      color: 'var(--rt-muted)', ...style,
    }}>{children}</p>
  );
}

// ───────────────────────── BEAT 1 · the item
function Beat1({ C }) {
  return (
    <div>
      <FLabel>{C.label}</FLabel>
      <h2 style={{
        margin: 'var(--s3) 0 0', maxWidth: '20ch',
        fontFamily: 'var(--serif)', fontWeight: 500,
        fontSize: 'clamp(32px, 4vw, 52px)', lineHeight: 1.1,
        letterSpacing: '-0.015em', color: 'var(--rt-fg)',
      }}>{C.head}</h2>
      <FBody style={{ marginTop: 'var(--s3)' }}>{C.body}</FBody>
    </div>
  );
}

// ───────────────────────── BEAT 2 · what his systems say
// Fast. A step, not a destination.
function Beat2({ C }) {
  return (
    <div>
      <FLabel>{C.label}</FLabel>

      {/* The only separated elements in the room. */}
      <div style={{
        marginTop: 'var(--s2)', display: 'flex', flexWrap: 'wrap',
        alignItems: 'baseline', gap: 'var(--s3)',
      }}>
        {C.reads.map((r, i) => (
          <React.Fragment key={r.k}>
            {i > 0 && <span style={{ color: 'var(--ink-30)', fontSize: 18 }}>·</span>}
            <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{
                fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
                letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--rt-label)',
              }}>{r.k}</span>
              <span style={{
                fontFamily: 'var(--sans)', fontWeight: 700, fontSize: 26,
                lineHeight: 1, color: 'var(--coral)',
              }}>{r.v}</span>
            </span>
          </React.Fragment>
        ))}
      </div>

      <div style={{ marginTop: 'var(--s3)' }}>
        {C.lines.map((l, i) => (
          <div key={i} style={{
            fontFamily: 'var(--sans)', fontSize: 18, lineHeight: 1.5,
            color: 'var(--rt-muted)',
          }}>{l}</div>
        ))}
        <div style={{
          marginTop: 6, fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 600,
          lineHeight: 1.5, color: 'var(--rt-fg)', maxWidth: '62ch',
        }}>{C.total}</div>
      </div>

      <FBody style={{ marginTop: 'var(--s3)' }}>{C.close}</FBody>
    </div>
  );
}


// ───────────────────────── BEATS 2, 3 and 4 · the original stage
// The four panel simulation is reused exactly as built. The room drives its
// phase; nothing about the panels or their copy is changed here.
function SimBeat({ phase, fifth, below }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <div style={{ flex: below ? '1 1 66%' : '1 1 auto', minHeight: 0 }}>
        {React.createElement(window.MissingLinkSlide, { embedPhase: phase, fifth: fifth })}
      </div>
      {below}
    </div>
  );
}

// ───────────────────────── BEAT 3 · what no system says
// The peak. Largest type, longest hold, most space.
function Beat3({ C }) {
  return (
    <div>
      <FLabel>{C.label}</FLabel>
      <div style={{
        marginTop: 'var(--s2)',
        fontFamily: 'var(--serif)', fontWeight: 600,
        fontSize: 'clamp(64px, 9vw, 140px)', lineHeight: 0.9,
        letterSpacing: '-0.03em', color: 'var(--rt-action)',
      }}>{C.hero}</div>
      <FLabel>{C.heroLabel}</FLabel>
      <FBody size={24} style={{ marginTop: 'var(--s3)', color: 'var(--rt-fg)' }}>{C.body}</FBody>
      <FBody style={{ marginTop: 'var(--s3)' }}>{C.kicker}</FBody>
    </div>
  );
}

// ───────────────────────── BEAT 4 · the decision, and the honesty
// The pairing is the point, so neither side outweighs the other.
function Beat4({ C, lang }) {
  const [asked, setAsked] = useFS(false);
  const askWhy = () => {
    const q = lang === 'no'
      ? 'Hvorfor anbefaler dere 26 enheter av SKU 45821, og ikke et annet antall?'
      : 'Why do you recommend 26 units of SKU 45821 rather than some other number?';
    setAsked(true);
    window.__track && window.__track('ask_why_qty', { qty: C.qty });
    // A real query to the agent, streamed into the Ask Otto surface. Not a
    // tooltip: this is the one thing in the deck that a printout cannot do.
    if (window.__askDeck) window.__askDeck(q);
  };

  return (
    <div>
      <FLabel>{C.label}</FLabel>
      <div className="fix-b4" style={{
        marginTop: 'var(--s3)', display: 'grid',
        gridTemplateColumns: '1fr 1fr', gap: 'var(--s5)', alignItems: 'start',
      }}>
        <div>
          <FLabel>{C.sku}</FLabel>
          <div style={{
            marginTop: 6, fontFamily: 'var(--serif)', fontWeight: 500,
            fontSize: 'clamp(26px, 3vw, 40px)', lineHeight: 1.1,
            color: 'var(--rt-fg)',
          }}>
            {C.order.split(C.qty)[0]}
            <button onClick={askWhy} className="fix-qty" style={{
              font: 'inherit', color: 'var(--blue)', background: 'none',
              border: 'none', padding: 0, cursor: 'pointer',
              borderBottom: '2px solid var(--blue)', lineHeight: 1,
            }}>{C.qty}</button>
            {C.order.split(C.qty)[1]}
          </div>
          <button onClick={askWhy} style={{
            marginTop: 8, fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'var(--blue)', background: 'none', border: 'none',
            padding: 0, cursor: 'pointer',
          }}>{asked ? '…' : C.askHint}</button>

          <div style={{ marginTop: 'var(--s3)' }}>
            {C.because.map((b, i) => (
              <div key={i} style={{
                fontFamily: 'var(--sans)', fontSize: 18, lineHeight: 1.55,
                color: 'var(--rt-muted)',
              }}>{b}</div>
            ))}
          </div>

          <div style={{ marginTop: 'var(--s3)', display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <FLabel>{C.confLabel}</FLabel>
            <span style={{
              fontFamily: 'var(--sans)', fontWeight: 700, fontSize: 30,
              lineHeight: 1, color: 'var(--green)',
            }}>{C.conf}</span>
          </div>
        </div>

        <div>
          <FLabel>{C.altSku}</FLabel>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <FLabel>{C.confLabel}</FLabel>
            <span style={{
              fontFamily: 'var(--sans)', fontWeight: 700, fontSize: 30,
              lineHeight: 1, color: 'var(--coral)',
            }}>{C.altConf}</span>
          </div>
          <FBody style={{ marginTop: 'var(--s2)' }}>{C.altBody}</FBody>
        </div>
      </div>

      <FBody style={{ marginTop: 'var(--s3)', color: 'var(--rt-fg)' }}>{C.foot}</FBody>
    </div>
  );
}

// ───────────────────────── BEAT 5 · the human, then the money
// Without a visible human in the loop the deck claims autonomy we do not have.
function Beat5({ C }) {
  const [done, setDone] = useFS(false);
  return (
    <div>
      <FLabel>{C.label}</FLabel>

      <div style={{ marginTop: 'var(--s3)', display: 'flex', alignItems: 'center', gap: 'var(--s3)' }}>
        <button
          onClick={() => { setDone(true); window.__track && window.__track('approve_click', {}); }}
          disabled={done}
          style={{
            fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 600,
            padding: '13px 30px', borderRadius: 8, border: 'none',
            cursor: done ? 'default' : 'pointer',
            background: done ? 'var(--green)' : 'var(--blue)',
            color: 'var(--paper)',
            transition: 'background 240ms ease',
          }}>{done ? C.approved : C.approve}</button>
        {!done && (
          <span style={{
            fontFamily: 'var(--sans)', fontSize: 18, color: 'var(--rt-label)',
          }}>{C.override}</span>
        )}
      </div>

      <div style={{
        marginTop: 'var(--s4)',
        opacity: done ? 1 : 0,
        transform: done ? 'none' : 'translateY(10px)',
        transition: 'opacity 500ms ease, transform 500ms ease',
      }}>
        <FLabel>{C.scope}</FLabel>
        <div style={{ marginTop: 'var(--s2)', display: 'flex', alignItems: 'baseline', gap: 'var(--s2)', flexWrap: 'wrap' }}>
          <span style={{
            fontFamily: 'var(--serif)', fontWeight: 600,
            fontSize: 'clamp(48px, 6.5vw, 104px)', lineHeight: 0.92,
            letterSpacing: '-0.03em', color: 'var(--rt-action)',
          }}>{C.hero}</span>
          <span style={{
            fontFamily: 'var(--sans)', fontSize: 24, color: 'var(--rt-muted)',
          }}>{C.heroUnit}</span>
        </div>

        <div style={{ marginTop: 'var(--s3)' }}>
          {C.rows.map((r, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'baseline', gap: 12,
              fontFamily: 'var(--sans)', fontSize: 24, lineHeight: 1.6,
            }}>
              <span style={{ color: 'var(--rt-label)', fontWeight: 600 }}>{r.a}</span>
              <span style={{ color: 'var(--rt-line)' }}>→</span>
              <span style={{ color: 'var(--rt-ok)', fontWeight: 700 }}>{r.b}</span>
              <span style={{ fontSize: 18, color: 'var(--rt-muted)' }}>{r.k}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ───────────────────────── the room
function SolutionRoom() {
  const lang = window.__useLang();
  const T = window.TDATA[lang];
  const C = T.sim.fix;
  window.__useRoomTelemetry('simulation');

  const reduced = fixReduced();
  const [beat, setBeat] = useFS(0);
  const [held, setHeld] = useFS(false);   // a click stops the auto sequence

  useFE(() => {
    if (reduced || held || beat >= 5) return;
    const id = setTimeout(() => setBeat(b => Math.min(5, b + 1)), FIX_HOLD[beat]);
    return () => clearTimeout(id);
  }, [beat, held, reduced]);

  const go = (n) => { setHeld(true); setBeat(Math.max(0, Math.min(5, n))); };

  // 1 item · 2 the four systems · 3 reconciliation · 4 the fifth panel
  // · 5 the decision · 6 the human and the money
  const frames = [
    () => <Beat1 C={C.b1} />,
    () => <SimBeat phase="a" />,
    () => <SimBeat phase="resolve" />,
    () => (
      <SimBeat phase="a" fifth below={
        <div style={{ flex: '0 0 auto', paddingTop: 'var(--s2)' }}>
          <FBody size={22} style={{ color: 'var(--rt-fg)' }}>{C.b3.body}</FBody>
          <FBody style={{ marginTop: 'var(--s2)' }}>{C.b3.kicker}</FBody>
        </div>
      } />
    ),
    () => <Beat4 C={C.b4} lang={lang} />,
    () => <Beat5 C={C.b5} />,
  ];

  return (
    <div className="room room-fix" data-tone="dark" style={{
      position: 'absolute', inset: 0,
      paddingTop: 'calc(56px + var(--s3))', paddingBottom: 'var(--s3)',
      paddingInline: 'var(--margin)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Beat rail. Advancing is the same gesture the room always had. */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--s2)', flex: '0 0 auto' }}>
        {[0, 1, 2, 3, 4, 5].map(i => (
          <button key={i} onClick={() => go(i)} aria-label={'Beat ' + (i + 1)}
            style={{
              width: i === beat ? 26 : 12, height: 4, borderRadius: 2, padding: 0,
              border: 'none', cursor: 'pointer',
              background: i === beat ? 'var(--rt-accent)' : 'var(--rt-line)',
              transition: 'width 240ms ease, background 240ms ease',
            }} />
        ))}
        <button onClick={() => go(beat >= 5 ? 0 : beat + 1)} style={{
          marginLeft: 'var(--s2)', fontFamily: 'var(--sans)', fontSize: 13,
          fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--rt-label)', background: 'none', border: 'none',
          padding: 0, cursor: 'pointer', textAlign: 'left',
        }}>{beat >= 5 ? C.replay : C.next}</button>
      </div>

      {/* Beat 3 gets the most room: the others sit centred in the same frame,
          so the sequence never jumps. */}
      <div key={beat} className="fix-beat" style={{
        flex: '1 1 auto', minHeight: 0,
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
      }}>
        {frames[beat]()}
      </div>

      <window.Objections room="simulation" align="left" onDark />
    </div>
  );
}

window.SolutionRoom = SolutionRoom;
