// Shell — header, phase nav, viewpoint toggle, layout
// Depends on: SCENARIO, Icons, Thermometer, AgentBadge

const PHASES = [
  { id: 'style', label: '00 · Style', short: '00' },
  { id: 'topic', label: '01 · Topic lock', short: '01' },
  { id: 'intake', label: '02 · Pretext', short: '02' },
  { id: 'opening', label: '03 · Blind opening', short: '03' },
  { id: 'steelman', label: '04 · Steel-man gate', short: '04' },
  { id: 'room', label: '05 · The room', short: '05' },
  { id: 'callout', label: '06 · Pattern callout', short: '06' },
  { id: 'apology', label: '07 · Apology on-ramp', short: '07' },
  { id: 'artifact', label: '08 · Artifact', short: '08' },
];

function PhaseNav({ current, onSelect }) {
  const currentIdx = PHASES.findIndex(p => p.id === current);
  // Partner presence: read shared.cursor[otherSeat].phase in live MP
  const [, tick] = React.useState(0);
  React.useEffect(() => CG.session.onState(() => tick(t => t + 1)), []);
  const mp = CG.session.isMultiplayer && CG.session.isMultiplayer();
  const mySeat = CG.session.getSeat && CG.session.getSeat();
  const otherSeat = mySeat === 'A' ? 'B' : mySeat === 'B' ? 'A' : null;
  const otherCursor = (mp && otherSeat && CG.session.shared?.cursor?.[otherSeat]) || null;
  const otherPhase = otherCursor && otherCursor.phase || null;
  const otherActivity = otherCursor && otherCursor.activity || null;
  const otherIdx = otherPhase ? PHASES.findIndex(p => p.id === otherPhase) : -1;
  const names = CG.session.getNames ? CG.session.getNames() : { A: null, B: null };
  const otherName = otherSeat && names[otherSeat] ? names[otherSeat] : (otherSeat === 'A' ? 'host' : 'guest');
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
      {PHASES.map((p, i) => {
        const state = i < currentIdx ? 'done' : i === currentIdx ? 'active' : '';
        const otherHere = otherIdx === i;
        return (
          <React.Fragment key={p.id}>
            <div style={{ position: 'relative' }}>
              <div
                className={`phase-pip ${state}`}
                onClick={() => onSelect(p.id)}
                title={p.label}
              >
                {p.short}
              </div>
              {otherHere && (
                <span
                  title={`${otherName} is on ${p.label}`}
                  style={{
                    position: 'absolute',
                    top: -3, right: -3,
                    width: 7, height: 7, borderRadius: '50%',
                    background: 'var(--blue)',
                    border: '1.5px solid var(--paper)',
                    pointerEvents: 'none',
                  }}
                />
              )}
            </div>
            {i < PHASES.length - 1 && (
              <div style={{ width: 14, height: 1, borderTop: '1px dashed var(--rule)' }} />
            )}
          </React.Fragment>
        );
      })}
      <div style={{ marginLeft: 14, fontFamily: 'var(--font-mono)', fontSize: '0.75rem', color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
        {PHASES[currentIdx]?.label.toLowerCase()}
      </div>
      {mp && otherPhase && (
        <div
          title={`${otherName} is on ${PHASES[otherIdx]?.label || otherPhase}${otherActivity ? ` · ${otherActivity}` : ''}`}
          style={{
            marginLeft: 6,
            fontFamily: 'var(--font-mono)', fontSize: '0.68rem',
            color: otherIdx === currentIdx ? 'var(--ink-3)' : 'var(--blue)', letterSpacing: '0.04em',
            display: 'inline-flex', alignItems: 'center', gap: 5,
          }}
        >
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: otherIdx === currentIdx ? 'var(--ink-4)' : 'var(--blue)' }} />
          {otherName} · {PHASES[otherIdx]?.short || '??'}{otherActivity ? ` · ${otherActivity}` : ''}
        </div>
      )}
    </div>
  );
}

function TopBar({ phase, onPhase, seat, onPause, onConnectClaude, onOpenRoom }) {
  const S = window.SCENARIO;
  // Live-mode awareness: read topic + room id from session when we have a key + fresh mode
  const [, forceTick] = React.useState(0);
  React.useEffect(() => {
    const u1 = CG.onStatus(() => forceTick(t => t + 1));
    const u2 = CG.session.onState(() => forceTick(t => t + 1));
    return () => { u1(); u2(); };
  }, []);
  const liveMode = (CG.hasKey() && CG.getMode() === 'fresh') || !!(CG.session && CG.session.isGuest && CG.session.isGuest());
  const shared = CG.session.shared || {};
  const liveTopic = shared.topic && shared.topic.text ? shared.topic.text : null;
  const liveAmendment = shared.topic && shared.topic.amendment ? shared.topic.amendment : '';
  const bothSigned = shared.topic && shared.topic.signedA && shared.topic.signedB;
  const names = CG.session.getNames ? CG.session.getNames() : { A: null, B: null };

  // Room id: live peer room, falls back to a quiet placeholder in live mode
  const peerStatus = CG.peer.status();
  const liveRoomId = peerStatus && peerStatus.roomCode ? peerStatus.roomCode : null;

  const displayRoomId = liveMode ? (liveRoomId || 'solo') : S.room.id;
  const displayTopic = liveMode
    ? (liveTopic
        ? liveTopic + (liveAmendment ? ` ${liveAmendment.startsWith('…') ? liveAmendment : '…' + liveAmendment}` : '')
        : null)
    : S.topic.refined;
  const displayCosign = liveMode
    ? (bothSigned
        ? `co-signed · ${names.A} · ${names.B}`
        : liveTopic
          ? (shared.topic.signedA ? `signed · ${names.A} · waiting on ${names.B}` : `draft · not yet signed`)
          : null)
    : `co-signed · maya · jordan — ${S.room.createdAt}`;

  return (
    <div style={{
      padding: '14px 24px 10px 24px',
      borderBottom: '1px solid var(--rule)',
      background: 'var(--paper)',
      position: 'relative',
      zIndex: 5,
    }}>
      {/* top row */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, marginBottom: 10 }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div>
            <div className="tiny" style={{ marginBottom: 2 }}>clarguments · room {displayRoomId}</div>
            {displayTopic ? (
              <div style={{ fontFamily: 'var(--font-prose)', fontSize: '1.15rem', lineHeight: 1.25, maxWidth: 680, fontStyle: 'italic' }}>
                <span style={{ color: 'var(--ink-3)', fontStyle: 'normal', fontFamily: 'var(--font-mono)', fontSize: '0.7rem', letterSpacing: '0.06em', textTransform: 'uppercase', marginRight: 8 }}>topic ·</span>
                <span className="highlight">{displayTopic}</span>
              </div>
            ) : (
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: '0.8rem', color: 'var(--ink-3)', letterSpacing: '0.04em', maxWidth: 680 }}>
                <span style={{ marginRight: 8, textTransform: 'uppercase' }}>topic ·</span>
                <span style={{ fontStyle: 'italic' }}>not yet locked — phase 01 writes here</span>
              </div>
            )}
            {displayCosign && <div className="micro" style={{ marginTop: 4 }}>{displayCosign}</div>}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <StyleChip />
          <CreditsChip />
          <RoomChip onClick={onOpenRoom} />
          <ClaudeChip onClick={onConnectClaude} />
          <button className="btn btn-sm" onClick={onPause}>
            <Icons.Pause size={10} /> pause
          </button>
        </div>
      </div>

      <div style={{ marginTop: 6 }}>
        <PhaseNav current={phase} onSelect={onPhase} />
      </div>
    </div>
  );
}

// Style chip — shows status of the phase-00 style co-sign. Only rendered in live mode.
function StyleChip() {
  const [, tick] = React.useState(0);
  React.useEffect(() => {
    const u1 = CG.onStatus(() => tick(t => t + 1));
    const u2 = CG.session.onState(() => tick(t => t + 1));
    return () => { u1(); u2(); };
  }, []);
  const liveMode = (CG.hasKey() && CG.getMode() === 'fresh') || !!(CG.session && CG.session.isGuest && CG.session.isGuest());
  if (!liveMode) return null;

  const style = CG.session && CG.session.getStyle ? CG.session.getStyle() : null;
  const locked = !!(style && style.signedA && style.signedB);
  const label = locked
    ? `style · ${style.voice} · ${style.asymmetry} · ${style.directness}`
    : style
      ? 'style · proposed'
      : 'style · not set';

  return (
    <div
      className="btn btn-sm"
      title={locked ? 'style is locked for this session' : 'style not yet co-signed — phase 00'}
      style={{
        cursor: 'default',
        borderColor: locked ? 'var(--green)' : 'var(--ink-3)',
        color: locked ? 'var(--green)' : 'var(--ink-3)',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 6,
      }}
    >
      <span style={{
        width: 7, height: 7, borderRadius: '50%',
        background: locked ? 'var(--green)' : 'var(--ink-4)',
        display: 'inline-block',
      }} />
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.72rem', letterSpacing: '0.03em', textTransform: 'lowercase' }}>
        {label}
      </span>
    </div>
  );
}

// (Admin three-agent transparency panel removed — production UI.)

Object.assign(window, { PHASES, PhaseNav, TopBar, StyleChip });
