// The main room — disagreement map + rebuttal + established truths
// Depends on: SCENARIO, Icons, ScribbleCheck, InkLine, AgentBadge, Thermometer

function MapCard({ item, onDrag, compact, showSource }) {
  const S = window.SCENARIO;
  const isAgreed = item.bucket === 'agreed';
  const pinColor = item.pin || 'red';
  const rot = `rot-${(item.id.charCodeAt(0) % 4) + 1}`;

  return (
    <div className={`map-card ${rot}`} style={{ marginBottom: 14, marginTop: 10, position: 'relative' }}>
      {pinColor && <Pin color={pinColor} />}
      {isAgreed && (
        <div style={{ position: 'absolute', top: -8, right: -8 }}>
          <ScribbleCheck />
        </div>
      )}
      <div style={{ lineHeight: 1.4 }}>
        {isAgreed ? <span className="highlight">{item.text}</span> : item.text}
      </div>
      <div className="micro mt-2" style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
        <span>
          raised by{' '}
          {item.raisedBy === 'mediator' ? (
            <span style={{ color: 'var(--ink-3)' }}>mediator</span>
          ) : item.raisedBy === 'A' ? (
            <span style={{ color: S.parties.A.accent }}>maya</span>
          ) : (
            <span style={{ color: S.parties.B.accent }}>jordan</span>
          )}
        </span>
        {item.confirmedBy && (
          <span className="stamp" style={{ fontSize: '0.55rem', padding: '1px 5px', transform: 'rotate(-1deg)', color: 'var(--green)', borderColor: 'var(--green)' }}>
            confirmed · {item.confirmedBy === 'both' ? 'both' : item.confirmedBy.toLowerCase()}
          </span>
        )}
      </div>
    </div>
  );
}

function DisagreementMap({ godView }) {
  const S = window.SCENARIO;
  const buckets = [
    { id: 'agreed', label: 'established · agreed', desc: 'truths both parties have confirmed. the anchor.', color: 'var(--green)', bg: 'oklch(95% 0.04 140)' },
    { id: 'contested_facts', label: 'contested · facts', desc: 'disputes with a knowable answer.', color: 'var(--red)', bg: 'oklch(96% 0.03 30)' },
    { id: 'contested_interp', label: 'contested · meaning', desc: 'same facts, different readings. this is where the real work is.', color: 'oklch(55% 0.12 85)', bg: 'oklch(96% 0.035 85)' },
    { id: 'needs_info', label: 'needs more info', desc: 'we don\'t have the answer yet.', color: 'var(--blue)', bg: 'oklch(95% 0.03 240)' },
  ];
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div>
          <div className="tiny">right rail · disagreement map · live</div>
          <div style={{ fontFamily: 'var(--font-prose)', fontStyle: 'italic', color: 'var(--ink-2)', marginTop: 4 }}>
            every claim pinned. either of you can drag between columns.
          </div>
        </div>
        <AgentBadge agent="mediator" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, border: '1px solid var(--ink-4)' }}>
        {buckets.map((b, bi) => (
          <div
            key={b.id}
            className="bucket"
            style={{
              background: b.bg,
              borderRight: bi < 3 ? '1px dashed var(--ink-4)' : '0',
              position: 'relative',
              minHeight: 340,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              <div className="pin" style={{ background: b.color, width: 10, height: 10 }} />
              <div className="tiny" style={{ color: b.color }}>{b.label}</div>
            </div>
            <div className="micro mb-3" style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)', lineHeight: 1.3 }}>
              {b.desc}
            </div>
            <div className="dashed" style={{ margin: '8px 0 14px' }} />
            {S.mapItems.filter(m => m.bucket === b.id).map(item => (
              <MapCard key={item.id} item={item} />
            ))}
            {b.id === 'agreed' && (
              <div className="hand" style={{ color: 'var(--green)', fontSize: '1.1rem', marginTop: 10, opacity: 0.8 }}>
                4 so far ✓
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function RebuttalThread({ seat, godView, onTempChange }) {
  const S = window.SCENARIO;
  const [highlighted, setHighlighted] = React.useState(null);

  const renderMsg = (c) => {
    const isCallout = c.type === 'callout';
    const isA = c.by === 'A';
    const isB = c.by === 'B';
    const isMediator = c.by === 'mediator';
    const party = isA ? S.parties.A : isB ? S.parties.B : null;

    if (isCallout) {
      return (
        <div key={c.id} className={`callout ${c.severity === 'yellow' ? 'callout-yellow' : ''} fade-up`} style={{ marginBottom: 14 }}>
          <div style={{ position: 'absolute', left: 14, top: 14 }}>
            <div style={{
              width: 32, height: 32,
              borderRadius: '50%',
              border: `2px solid ${c.severity === 'yellow' ? 'oklch(65% 0.14 85)' : 'var(--red)'}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-mono)',
              fontSize: '0.85rem',
              fontWeight: 'bold',
              color: c.severity === 'yellow' ? 'oklch(45% 0.14 85)' : 'var(--red)',
              transform: 'rotate(-3deg)',
            }}>
              {c.severity === 'yellow' ? '!' : '‼'}
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
            <div className="tiny" style={{ color: c.severity === 'yellow' ? 'oklch(45% 0.14 85)' : 'var(--red)' }}>
              {c.severity} card · {c.patterns.join(' + ')}
            </div>
            <AgentBadge agent="mediator" />
          </div>
          <div style={{ fontFamily: 'var(--font-prose)', lineHeight: 1.5 }}>{c.text}</div>
          <div className="mono mt-2" style={{ color: 'var(--ink-3)' }}>
            → evidence cited · <span style={{ color: 'var(--ink-2)' }}>"{S.patterns.find(p => p.eventId === c.id)?.evidence || '…'}"</span>
          </div>
        </div>
      );
    }

    return (
      <div
        key={c.id}
        className={`msg ${isA ? 'msg-a' : isB ? 'msg-b' : 'msg-mediator'} fade-up`}
        style={{ marginBottom: 10, opacity: highlighted && highlighted !== c.ref ? 0.3 : 1, transition: 'opacity 0.2s' }}
        onMouseEnter={() => setHighlighted(c.ref)}
        onMouseLeave={() => setHighlighted(null)}
      >
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {isMediator ? (
              <AgentBadge agent="mediator" />
            ) : (
              <>
                <div className={`pin ${isB ? 'pin-blue' : ''}`} style={{ width: 8, height: 8 }} />
                <span className="mono" style={{ color: party.accent, fontWeight: 600 }}>{party.name.toLowerCase()}</span>
              </>
            )}
          </div>
          {c.ref && (
            <span className="mono" style={{ color: 'var(--ink-4)', fontSize: '0.68rem' }}>
              → map · {c.ref}
            </span>
          )}
        </div>
        <div style={{ lineHeight: 1.5 }}>{c.text}</div>
      </div>
    );
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div>
          <div className="tiny">center · rebuttal round · turn-tokened</div>
          <div style={{ fontFamily: 'var(--font-prose)', fontStyle: 'italic', color: 'var(--ink-2)', marginTop: 2 }}>
            free-form chat is banned. every message attaches to a map item or a specific claim.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div className="pill pill-active">jordan's turn</div>
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        {S.chat.map(renderMsg)}
      </div>
    </div>
  );
}

function LeftRail({ seat, godView }) {
  const S = window.SCENARIO;
  const [draft, setDraft] = React.useState("you always make me feel like");
  const party = seat === 'B' ? S.parties.B : S.parties.A;
  const coachAgent = seat === 'B' ? 'coachB' : 'coachA';

  if (seat === 'god') {
    return (
      <div style={{ padding: 14, background: 'var(--paper-2)', borderRight: '1px solid var(--rule)' }}>
        <div className="tiny mb-3">god view · both coach threads</div>
        <div className="paper-card p-3 mb-3">
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div className="tiny" style={{ color: S.parties.A.accent }}>maya's coach · last</div>
            <AgentBadge agent="coachA" />
          </div>
          <div style={{ marginTop: 6, fontStyle: 'italic', lineHeight: 1.45 }}>
            "the word 'always' is doing a lot of work. before you send — is it literally true here?"
          </div>
        </div>
        <div className="paper-card p-3">
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div className="tiny" style={{ color: S.parties.B.accent }}>jordan's coach · last</div>
            <AgentBadge agent="coachB" />
          </div>
          <div style={{ marginTop: 6, fontStyle: 'italic', lineHeight: 1.45 }}>
            "she's about to be confronted about apr 9. the vague version won't hold. do you want to preempt it?"
          </div>
        </div>
        <div className="dashed" />
        <div className="tiny mb-2">mediator's queue (pending approval)</div>
        <div className="paper-card p-3" style={{ background: 'var(--paper-3)' }}>
          <div className="mono" style={{ fontSize: '0.72rem', lineHeight: 1.5 }}>
            summary_for_mediator · from coachB · awaiting jordan's sign-off
          </div>
          <div style={{ marginTop: 6, fontFamily: 'var(--font-prose)', lineHeight: 1.45, fontStyle: 'italic' }}>
            "b acknowledges the apr 9 change was less than 1hr notice and the reason given was incomplete."
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
            <button className="btn btn-sm btn-primary">approve</button>
            <button className="btn btn-sm">edit</button>
            <button className="btn btn-sm btn-ghost">hold</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: 14, background: 'var(--paper-2)', borderRight: '1px solid var(--rule)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div className="tiny">left rail · just you &amp; your coach</div>
        <AgentBadge agent={coachAgent} />
      </div>
      <div className="paper-card p-3 mb-3" style={{ boxShadow: 'none', borderLeft: `2px solid ${party.accent}` }}>
        <div className="micro mb-1">coach · latest</div>
        <div style={{ fontStyle: 'italic', lineHeight: 1.45 }}>
          {seat === 'B'
            ? "she's about to be confronted about apr 9. the vague version won't hold. do you want to preempt it?"
            : "the word 'always' is doing a lot of work. before you send — is it literally true here?"}
        </div>
      </div>

      <div className="tiny mb-2">draft composer</div>
      <textarea
        className="paper-input"
        rows={4}
        value={draft}
        onChange={e => setDraft(e.target.value)}
        style={{ marginBottom: 8 }}
      />

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div className="micro">
          tone · <span style={{ color: 'var(--red)' }}>heated</span>
        </div>
        <div className="mono" style={{ fontSize: '0.65rem', color: 'var(--ink-3)' }}>
          claude sees this live
        </div>
      </div>

      <div style={{
        padding: 10,
        background: 'var(--paper)',
        borderLeft: `2px dashed ${party.accent}`,
        marginBottom: 10,
        position: 'relative',
      }}>
        <div className="micro mb-1">
          <span style={{ color: 'var(--blue)' }}>ghost · gentler version</span>
        </div>
        <div style={{ fontStyle: 'italic', color: 'var(--ink-2)', lineHeight: 1.45 }}>
          {seat === 'B'
            ? "i want to say something about apr 9 before she does. i wasn't fully honest in the text."
            : "in the last three instances i've felt dropped, not inconvenienced — and the silence after is mine to own."}
        </div>
        <button className="btn btn-sm btn-ghost" style={{ marginTop: 8 }}>
          <Icons.Check size={10} /> one-tap accept
        </button>
      </div>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        <button className="btn btn-sm">translate to i-statement</button>
        <button className="btn btn-sm btn-ghost">offer apology</button>
      </div>

      <div className="dashed" />

      <div className="tiny mb-2">your private acknowledgments so far</div>
      {(seat === 'B' ? S.acknowledgments.B : S.acknowledgments.A).map((a, i) => (
        <div key={i} className="paper-card p-3 mb-2" style={{ boxShadow: 'none' }}>
          <div style={{ fontStyle: 'italic', lineHeight: 1.4 }}>"{a.text}"</div>
          <div className="micro mt-1">made · {a.at}</div>
        </div>
      ))}
    </div>
  );
}

function RightRail({ seat, godView }) {
  const S = window.SCENARIO;
  const truths = S.mapItems.filter(m => m.bucket === 'agreed');

  return (
    <div style={{ padding: 14, background: 'var(--paper-2)', borderLeft: '1px solid var(--rule)' }}>
      {/* Established truths — the critical must-have */}
      <div className="truth-stack" style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="tiny" style={{ color: 'var(--ink)' }}>
            established truths
          </div>
          <div className="mono" style={{ color: 'var(--ink-3)' }}>{truths.length} · locked</div>
        </div>
        <div className="micro mt-1" style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)', lineHeight: 1.35 }}>
          the anchor. both parties have confirmed these. <span className="hand" style={{ fontSize: '1rem', color: 'var(--blue)' }}>updates as we go.</span>
        </div>
        <div className="dashed" style={{ margin: '10px 0' }} />
        {truths.map((t, i) => (
          <div key={t.id} style={{ marginBottom: 10, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
            <div style={{ marginTop: 2 }}><ScribbleCheck /></div>
            <div style={{ lineHeight: 1.4, fontSize: '0.92rem' }}>
              <span className="highlight">{t.text}</span>
            </div>
          </div>
        ))}
        <div className="dashed" style={{ margin: '10px 0' }} />
        <div className="micro" style={{ lineHeight: 1.4, textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)' }}>
          a truth becomes established only when <b>both parties confirm</b>. mediator can <i>propose</i>; cannot <i>impose</i>.
        </div>
      </div>

      {/* Feelings not-yet-facts */}
      <div className="tiny mb-2">feelings · not yet truths · still valid</div>
      <div className="paper-card p-3 mb-3" style={{ boxShadow: 'none', borderLeft: '3px solid var(--purple)' }}>
        <div className="micro mb-2" style={{ textTransform: 'none', letterSpacing: 0, lineHeight: 1.35 }}>
          held separately from the factual column. a feeling can be unreasonable <i>and</i> real. we don't bargain you out of what you feel, we bargain over what's true.
        </div>
        <div style={{ marginBottom: 8, display: 'flex', gap: 8 }}>
          <div className="pin" style={{ width: 8, height: 8, marginTop: 5 }} />
          <div style={{ lineHeight: 1.4, fontSize: '0.88rem', fontStyle: 'italic' }}>
            maya · "i feel like the fallback, even when i know logically i'm not."
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div className="pin pin-blue" style={{ width: 8, height: 8, marginTop: 5 }} />
          <div style={{ lineHeight: 1.4, fontSize: '0.88rem', fontStyle: 'italic' }}>
            jordan · "her silence feels like a verdict, even when she calls it space."
          </div>
        </div>
      </div>

      {/* Parking lot */}
      <div className="tiny mb-2">parking lot · for another session</div>
      <div className="paper-card p-3" style={{ boxShadow: 'none', background: 'var(--paper-3)' }}>
        {S.parkingLot.map(p => (
          <div key={p.id} className="parked" style={{ marginBottom: 5, fontSize: '0.88rem' }}>{p.text}</div>
        ))}
        <div className="hand mt-2" style={{ fontSize: '1rem', color: 'var(--ink-3)' }}>
          heard, not forgotten.
        </div>
      </div>
    </div>
  );
}

function RoomPhase({ seat, godView }) {
  return (
    <div style={{ padding: '0', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '20px 32px 16px', borderBottom: '1px solid var(--rule)' }}>
        <div className="tiny">phase 05 · the room</div>
        <h1 style={{ marginTop: 4 }}>the room is three panes. the center is public record.</h1>
        <p style={{ color: 'var(--ink-2)', maxWidth: 780, marginTop: 4 }}>
          your left rail is private — you, your coach, your drafts. the right rail is shared — the map, the truths, the parking lot. the center is the one place anything lands that <i>counts</i>.
        </p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr 340px', flex: 1, minHeight: 0, overflow: 'hidden' }}>
        <div style={{ overflow: 'auto' }}><LeftRail seat={seat} godView={godView} /></div>
        <div style={{ overflow: 'auto', padding: '18px 22px' }}>
          <DisagreementMap godView={godView} />
          <div className="dashed" style={{ margin: '22px 0' }} />
          <RebuttalThread seat={seat} godView={godView} />
        </div>
        <div style={{ overflow: 'auto' }}><RightRail seat={seat} godView={godView} /></div>
      </div>
    </div>
  );
}

Object.assign(window, { MapCard, DisagreementMap, RebuttalThread, LeftRail, RightRail, RoomPhase });
