// ═══════════════════════════════════════════════════════════════════════════
// THE NINE ROOMS
//
// Every room below is one call to window.TemplateRoom. There is no per-room
// layout left in this file, which is the point: a room can change what it
// says, never how it is built. Three rooms carry a real asset in the media
// slot; the slot sits in the same place in each of them.
//
// Tone alternates by register, not by taste:
//   problem · fix · proof · moat · why now · team   dark   (the problem, the product)
//   scale · market · ask                            light  (the business)
// ═══════════════════════════════════════════════════════════════════════════

const { useState: useS, useEffect: useE } = React;

// ── A media strip. Nothing is ever cropped or letterboxed: the strip takes
//    the lesser of the column width and its own ratio at the shared ceiling,
//    then lets height follow. The Otto screenshot is the argument in the moat
//    room, so it has to be readable, not a texture.
const STRIP_H = 'min(236px, 25vh)';
function MediaStrip({ src, ratio, alt }) {
  return (
    <div style={{
      width: `min(100%, calc(${STRIP_H} * ${ratio}))`, aspectRatio: String(ratio),
      borderRadius: 12, overflow: 'hidden', background: 'var(--card)',
      boxShadow: '0 24px 60px -30px rgba(57,54,48,0.5)',
    }}>
      <img src={src} alt={alt || ''} style={{
        width: '100%', height: '100%', objectFit: 'cover', display: 'block',
      }} />
    </div>
  );
}

// Reads one room out of the template content block.
function useTpl(id) {
  const lang = window.__useLang();
  const T = window.TDATA[lang];
  return [(T.tpl || {})[id] || {}, T, lang];
}

function shell(id, extra) {
  const [R] = useTpl(id);
  window.__useRoomTelemetry(id);
  return <window.TemplateRoom
    tone={R.tone} label={R.label} headline={R.headline}
    support={R.support} figures={R.figures} room={id}
    {...(extra || {})} />;
}

// ───────────────────────── 01 · Problem
function ProblemRoom() { return shell('problem'); }

// ───────────────────────── 03 · Proof it works
// The stock list a paying customer opens each morning: real products, real
// cover, and two of the three rows already flagged as overstock. The KPI
// strip that used to sit here showed totals; this shows the decision, which
// is the thing being paid for. The screenshot is the argument that it exists,
// so it stays on the screen.
function ProofRoom() {
  return shell('proof', {
    media: <MediaStrip src="heroes/ui-stocklist.png" ratio={1273 / 259}
                       alt="Stock list showing in-stock and overstock products with cover, min, max and forecast" />,
  });
}

// ───────────────────────── 04 · Proof it scales
// Five rows of commercial terms used to sit here as a table. They are now in
// Otto in full, which is where a reader who wants them will ask for them.
function ScaleRoom() { return shell('scale'); }

// ───────────────────────── 05 · Hard to copy
function MoatRoom() {
  return shell('moat', {
    media: <MediaStrip src="heroes/ui-otto.png" ratio={757 / 346} alt="Otto answering a purchasing question from live stock data" />,
  });
}

// ───────────────────────── 06 · Market and model
function MarketRoom() { return shell('market'); }

// ───────────────────────── 07 · Unit economics
// The churn note goes in the `after` slot rather than as a second paragraph,
// because it is not support for the headline: it is the thing we are refusing
// to claim. It stays verbatim. There is deliberately no LTV and no LTV to CAC
// ratio in this room, and Otto is told the same.
function UnitRoom() {
  const [R] = useTpl('unit');
  return shell('unit', {
    after: (
      <div style={{ maxWidth: '68ch' }}>
        <div style={{
          fontFamily: 'var(--sans)', fontSize: 'var(--t-label)', fontWeight: 600,
          letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--rt-label)',
        }}>{R.churnLabel}</div>
        <div style={{
          marginTop: 'var(--s1)', fontFamily: 'var(--sans)', fontSize: 18,
          lineHeight: 1.5, color: 'var(--rt-muted)',
        }}>{R.churn}</div>
      </div>
    ),
  });
}

// ───────────────────────── 08 · Why now
// The competitive view lives here rather than in a room of its own: who else
// is in the category IS the timing argument, and splitting them into two
// rooms would let a reader take the funding news without the absence that
// follows it. Four rows, no rules and no boxes. The name is the only thing
// carrying weight; everything else is space.
function WhyNowRoom() {
  const [R] = useTpl('whynow');
  const rivals = R.rivals || [];
  return shell('whynow', {
    media: rivals.length ? (
      <div className="rivals">
        {rivals.map((r, i) => (
          <div key={i} className="rival">
            <div className="rival-n">{r.n}</div>
            <div className="rival-w">{r.w}</div>
          </div>
        ))}
      </div>
    ) : undefined,
  });
}

// ───────────────────────── 09 · Team
// Six portraits at a size you can actually read a face at. The images are
// head-normalised on disk, so every head lands at the same height in the
// row without per-person CSS nudging.
function TeamRoom() {
  const lang = window.__useLang();
  const M = window.TDATA[lang].team;
  const byName = {};
  (typeof TEAM_FOUNDERS !== 'undefined' ? TEAM_FOUNDERS : []).forEach(f => { byName[f.name] = f; });
  return shell('team', {
    media: (
      <div className="team-row">
        {(M.roster || []).map((m, i) => {
          const f = byName[m.n];
          return (
            <div key={i} className="team-person">
              <div className="team-shot">
                {f && <img src={f.photo} alt="" />}
              </div>
              <div className="team-name">{m.n}</div>
              <div className="team-role">{m.r}</div>
              {/* Every member carries a background line now, so the row reads
                  as one block rather than four names and two biographies. */}
              {m.c && <div className="team-cred">{m.c}</div>}
            </div>
          );
        })}
      </div>
    ),
  });
}

// ───────────────────────── 09 · The ask
// The arithmetic occupies the support slot, because in this room the
// derivation IS the supporting argument. Everything beneath the figure row
// is the close, in the standard position.
function AskRoom() {
  const [R, T] = useTpl('ask');
  const A = T.askRoom;
  window.__useRoomTelemetry('ask');
  const fill = window.__isFill;

  const BODY = { fontFamily: 'var(--sans)', fontSize: 16, lineHeight: 1.5,
                 color: 'var(--rt-muted)' };

  return (
    <window.TemplateRoom
      tone={R.tone} label={R.label} headline={R.headline}
      figures={R.figures} room="ask"
      support={
        <React.Fragment>
          {(A.mathRows || []).map((row, i) => (
            <div key={i} style={{
              display: 'flex', flexWrap: 'wrap', alignItems: 'baseline', gap: 8,
              fontSize: 19, lineHeight: 1.45,
            }}>
              {row.map((cell, j) => (
                <span key={j} style={{
                  color: cell.gold ? 'var(--rt-accent)' : 'var(--rt-muted)',
                  fontWeight: cell.gold ? 600 : 400,
                }}>{cell.t}</span>
              ))}
            </div>
          ))}
          <div style={{ marginTop: 10 }}>{A.downside}</div>
        </React.Fragment>
      }
      after={
        <React.Fragment>
          <div style={{ ...BODY, display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
            <span style={{
              fontSize: 'var(--t-label)', fontWeight: 600, letterSpacing: '0.08em',
              textTransform: 'uppercase', color: 'var(--rt-label)',
            }}>{A.buysLabel}</span>
            <span>{A.buys}</span>
          </div>

          <div style={{ ...BODY, marginTop: 6 }}>
            <span style={fill(A.closesLine) ? { color: 'var(--rt-alert)' } : null}>{A.closesLine}</span>
            {' '}<span>{A.bridge}</span>
          </div>

          <div style={{ marginTop: 'var(--s3)', display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
            <a href={A.close[0].href}
               onClick={() => window.__track('close_action', { action: A.close[0].id })}
               style={{
                 fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600,
                 padding: '10px 22px', borderRadius: 8, textDecoration: 'none',
                 border: '1px solid var(--rt-accent)', color: 'var(--rt-accent)',
                 background: 'transparent',
               }}>{A.close[0].label}</a>
            <a href={A.close[1].href}
               onClick={() => window.__track('close_action', { action: A.close[1].id })}
               style={{ ...BODY, textDecoration: 'underline', textUnderlineOffset: 3 }}>
              {A.close[1].label}
            </a>
          </div>
        </React.Fragment>
      }
    />
  );
}

window.ProblemRoom = ProblemRoom;
window.ProofRoom = ProofRoom;
window.ScaleRoom = ScaleRoom;
window.MoatRoom = MoatRoom;
window.MarketRoom = MarketRoom;
window.WhyNowRoom = WhyNowRoom;
window.UnitRoom = UnitRoom;
window.TeamRoom = TeamRoom;
window.AskRoom = AskRoom;
