// chat-light.jsx — Immersive light-mode chat (Ask α)
//
// This is the room where the analyst converses with the corpus.
// Different vocabulary from the rest of the app: cream stage, dark
// warm carbon ink, generous editorial typography. The axis chips
// become large topic cards — they're the conversational starting
// points and they earn that visual weight.

// ────────────────────────────────────────────────────────────
// TOPIC CARDS — big axis-coded conversation starters
// ────────────────────────────────────────────────────────────
function TopicCards({ companyId, onPick, dense = false }) {
  const c = COMPANIES.find(x => x.id === companyId);
  if (!c) return null;
  // worst-first so the most-needed conversation is first
  const order = worstFirst(c).slice(0, dense ? 5 : 6);

  return (
    <div style={{
      display: 'flex', gap: 2, overflowX: 'auto', overflowY: 'hidden',
      paddingBottom: 4,
    }} className="no-scrollbar">
      {order.map((axisIdx, i) => {
        const axis = AXES[axisIdx];
        const score = c.axes[axisIdx];
        const rag = ragOf(score);
        return (
          <button key={axis.key}
            className={`dept-card --${rag} ${dense ? '--dense' : ''}`}
            onClick={() => onPick(axis, score, rag)}>
            <div className="dc-rank">
              <span>{String(i+1).padStart(2,'0')} · {rag}</span>
            </div>
            <div className="dc-name">{axis.label}</div>
            <div className="dc-score">{score}</div>
            <div className="dc-foot">
              <span>/ 100 · α</span>
              <span className="dc-cta">Ask →</span>
            </div>
          </button>
        );
      })}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// IMMERSIVE BRIEF — light-mode AI response, magazine voice
// ────────────────────────────────────────────────────────────
function ImmersiveBrief({ m }) {
  const b = m.brief;
  return (
    <article style={{ padding: '32px 0 24px' }}>
      {/* α masthead */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        paddingBottom: 18, borderBottom: '1px solid var(--elev-3)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
          <span className="wordmark" style={{ fontSize: 24, color: 'var(--ink)' }}>
            AlphaSuite<span className="dot" style={{ color: 'var(--accent-deep)' }}>.</span>
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.22em',
            textTransform: 'uppercase', color: 'var(--ink-3)' }}>
            Intelligence Briefing · {m.time}
          </span>
        </div>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.16em',
          color: 'var(--ink-3)' }}>
          <span style={{ color: 'var(--green)' }}>●</span> Confidence {b.confidence} · {b.sources} docs · {b.atoms} atoms
        </span>
      </div>

      {/* Lead — drop cap optional */}
      <div style={{ fontFamily: 'var(--serif)', fontSize: 28, lineHeight: 1.34,
        color: 'var(--ink)', letterSpacing: '-0.012em', marginTop: 26 }}>
        {b.lead}
      </div>

      {/* Inline axis card on light surface */}
      {b.axis && (
        <BriefAxisCard axis={b.axis} />
      )}

      {/* Signals as a numbered editorial list */}
      {b.signals && b.signals.length > 0 && (
        <section style={{ marginTop: 32 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
            <Kicker color="var(--ink-3)">Signals from the corpus</Kicker>
            <span style={{ flex: 1, height: 1, background: 'var(--elev-3)' }}/>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)',
              letterSpacing: '0.16em', textTransform: 'uppercase' }}>{b.signals.length} cited</span>
          </div>
          {b.signals.map((s, i) => (
            <div key={i} style={{
              padding: '16px 0', display: 'grid',
              gridTemplateColumns: '34px 1fr 180px', gap: 16, alignItems: 'start',
              borderTop: i === 0 ? 'none' : '1px solid var(--elev-2)',
            }}>
              <span style={{ fontFamily: 'var(--serif)', fontSize: 22, color: 'var(--ink-3)',
                fontStyle: 'italic', lineHeight: 1, marginTop: 2 }}>{String(i+1).padStart(2,'0')}</span>
              <span style={{ fontFamily: 'var(--serif)', fontSize: 18, lineHeight: 1.45,
                color: 'var(--ink)' }}>
                {s.t}
                {s.ref > 0 && (
                  <sup style={{ fontFamily: 'var(--mono)', fontSize: 10,
                    color: 'var(--gold)', marginLeft: 4, fontStyle: 'normal' }}>[{s.ref}]</sup>
                )}
              </span>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em',
                color: 'var(--ink-3)', textTransform: 'uppercase', textAlign: 'right', marginTop: 6 }}>
                {s.src}
              </span>
            </div>
          ))}
        </section>
      )}

      {/* Cluster + Comparison row */}
      <section style={{ marginTop: 32, display: 'grid',
        gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        {b.cluster && <BriefCluster atoms={b.cluster} />}
        {b.compareAxis && <BriefComparison axisKey={b.compareAxis} focusCompanyId="smithfield"
          label={AXES.find(a => a.key === b.compareAxis)?.label} />}
      </section>

      {/* Citation table (light) */}
      {b.citedAtoms && <BriefCitationTable atoms={b.citedAtoms} />}

      {/* Recommendation — featured pull-quote */}
      {b.verdict && (
        <section style={{ marginTop: 38, padding: '26px 30px 28px',
          background: 'var(--ink)', color: 'var(--canvas)', position: 'relative' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.2em',
            textTransform: 'uppercase', color: 'var(--gold)' }}>
            Recommendation
          </div>
          <div style={{ marginTop: 14, fontFamily: 'var(--serif)', fontSize: 24, lineHeight: 1.4,
            letterSpacing: '-0.005em', color: 'var(--canvas)' }}>
            {b.verdict}
          </div>
        </section>
      )}
    </article>
  );
}

// Light-version axis card (used inside the brief)
function BriefAxisCard({ axis }) {
  const ragColor = { red: 'var(--red)', amber: 'var(--amber)', green: 'var(--green)' }[axis.rag];
  return (
    <div style={{
      marginTop: 22, background: 'var(--surface)',
      padding: '20px 24px', display: 'grid',
      gridTemplateColumns: '1fr auto', gap: 20, alignItems: 'center', position: 'relative',
    }}>
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0,
        width: 4, background: ragColor }}/>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em',
            textTransform: 'uppercase', color: ragColor }}>
            ● {axis.rag} · AXIS
          </span>
        </div>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 26, lineHeight: 1.05,
          letterSpacing: '-0.01em', color: 'var(--ink)' }}>
          {axis.name}
        </div>
        {axis.note && (
          <div style={{ marginTop: 8, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            {axis.note}
          </div>
        )}
        <div style={{ marginTop: 14 }}>
          <AxisBar score={axis.score} rag={axis.rag} h={4} bg="var(--elev-3)" />
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="serif-num" style={{
          fontSize: 64, lineHeight: 0.9, color: 'var(--ink)', letterSpacing: '-0.04em',
        }}>{axis.score}</div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.16em',
          color: 'var(--ink-3)', textTransform: 'uppercase', marginTop: 6 }}>/ 100</div>
      </div>
    </div>
  );
}

// Light-version cluster (atoms mini-graph)
function BriefCluster({ atoms }) {
  const width = 420, height = 200;
  const nodes = atoms.map(aid => ATOM_BY_ID[aid]).filter(Boolean);
  const minX = Math.min(...nodes.map(n => n.x));
  const maxX = Math.max(...nodes.map(n => n.x));
  const minY = Math.min(...nodes.map(n => n.y));
  const maxY = Math.max(...nodes.map(n => n.y));
  const rngX = Math.max(0.1, maxX - minX);
  const rngY = Math.max(0.1, maxY - minY);
  const mapX = (x) => 32 + ((x - minX) / rngX) * (width - 200);
  const mapY = (y) => 30 + ((y - minY) / rngY) * (height - 70);

  const edges = [];
  nodes.forEach(a => (a.edges || []).forEach(e => {
    if (atoms.includes(e)) edges.push({ a, b: ATOM_BY_ID[e] });
  }));
  const ragColor = { red: 'var(--red)', amber: 'var(--amber)', green: 'var(--green)' };

  return (
    <div style={{ background: 'var(--surface)', padding: '18px 0 16px', position: 'relative' }}>
      <div style={{ padding: '0 22px 8px', display: 'flex',
        justifyContent: 'space-between', alignItems: 'baseline' }}>
        <Kicker color="var(--ink-3)">Atom cluster · {nodes.length} nodes</Kicker>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-3)',
          letterSpacing: '0.14em', textTransform: 'uppercase' }}>From the corpus</span>
      </div>
      <svg width="100%" viewBox={`0 0 ${width} ${height}`}
        preserveAspectRatio="xMidYMid meet" style={{ display: 'block' }}>
        {edges.map((e, i) => (
          <line key={i} x1={mapX(e.a.x)} y1={mapY(e.a.y)}
            x2={mapX(e.b.x)} y2={mapY(e.b.y)}
            stroke="var(--ink-3)" strokeWidth="0.8" opacity="0.4" strokeDasharray="3 3"/>
        ))}
        {nodes.map((a) => (
          <g key={a.id}>
            <circle cx={mapX(a.x)} cy={mapY(a.y)} r={7} fill={ragColor[a.rag]}
              stroke="var(--canvas)" strokeWidth="1.5"/>
            <text x={mapX(a.x) + 12} y={mapY(a.y) + 4}
              fill="var(--ink)" fontFamily="var(--mono)" fontSize="10" letterSpacing="0.04em">
              {a.label}
            </text>
          </g>
        ))}
      </svg>
    </div>
  );
}

// Light-version portfolio comparison
function BriefComparison({ axisKey, focusCompanyId, label }) {
  const axisIdx = AXES.findIndex(a => a.key === axisKey);
  if (axisIdx < 0) return null;
  const rows = COMPANIES.map(c => ({
    id: c.id, name: c.name, score: c.axes[axisIdx],
    rag: ragOf(c.axes[axisIdx]),
    primary: c.id === focusCompanyId,
  })).sort((a, b) => b.score - a.score);
  return (
    <div style={{ background: 'var(--surface)', padding: '18px 22px 22px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <Kicker color="var(--ink-3)">Portfolio · {label}</Kicker>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-3)',
          letterSpacing: '0.14em', textTransform: 'uppercase' }}>5 holdings</span>
      </div>
      <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 9 }}>
        {rows.map(r => {
          const ragColor = { red: 'var(--red)', amber: 'var(--amber)', green: 'var(--green)' }[r.rag];
          return (
            <div key={r.id} style={{
              display: 'grid', gridTemplateColumns: '92px 1fr 36px', gap: 12, alignItems: 'center'
            }}>
              <span style={{ fontFamily: r.primary ? 'var(--serif)' : 'var(--mono)',
                fontSize: r.primary ? 15 : 12,
                color: r.primary ? 'var(--ink)' : 'var(--ink-3)' }}>
                {r.name}
              </span>
              <div style={{ height: r.primary ? 12 : 6, background: 'var(--elev-3)',
                position: 'relative' }}>
                <div style={{ position: 'absolute', inset: 0, width: `${r.score}%`,
                  background: ragColor, opacity: r.primary ? 1 : 0.6 }}/>
              </div>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 11, textAlign: 'right',
                color: r.primary ? 'var(--ink)' : 'var(--ink-2)' }}>{r.score}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Light-version citation table
function BriefCitationTable({ atoms, compact = false }) {
  return (
    <section style={{ marginTop: 28 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
        <Kicker color="var(--ink-3)">Provenance</Kicker>
        <span style={{ flex: 1, height: 1, background: 'var(--elev-3)' }}/>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)',
          letterSpacing: '0.16em', textTransform: 'uppercase' }}>{atoms.length} atoms</span>
      </div>
      <div style={{ background: 'var(--surface)' }}>
        <div style={{ padding: '12px 18px', display: 'grid',
          gridTemplateColumns: compact ? '70px 1fr 60px' : '90px 1fr 70px 160px',
          gap: 16, borderBottom: '1px solid var(--elev-3)',
          fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'var(--ink-3)' }}>
          <span>Kind</span><span>Atom · Axis</span>
          {!compact && <span>Conf</span>}
          <span style={{ textAlign: 'right' }}>Source</span>
        </div>
        {atoms.map((aid, i) => {
          const a = ATOM_BY_ID[aid];
          if (!a) return null;
          const s = SOURCE_BY_ID[a.src];
          return (
            <div key={aid + i} style={{
              padding: '14px 18px', display: 'grid',
              gridTemplateColumns: compact ? '70px 1fr 60px' : '90px 1fr 70px 160px',
              gap: 16, borderTop: '1px solid var(--elev-2)', alignItems: 'center',
            }}>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em',
                color: 'var(--gold)' }}>{KIND_LABEL[s?.kind] || 'ATOM'}</span>
              <span style={{ minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 16, lineHeight: 1.3,
                  color: 'var(--ink)' }}>{a.label}</div>
                {!compact && (
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em',
                    textTransform: 'uppercase', color: 'var(--ink-3)', marginTop: 4 }}>
                    <RagDot rag={a.rag} size={5} style={{ marginRight: 4, verticalAlign: 'middle' }}/>
                    {AXES.find(x => x.key === a.axis)?.label || a.axis}
                  </div>
                )}
              </span>
              {!compact && (
                <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-2)' }}>
                  {Math.round(a.conf * 100)}%
                </span>
              )}
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)',
                textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis',
                whiteSpace: 'nowrap', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                {(s?.title || '—').slice(0, compact ? 14 : 26)}
              </span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// User message — light, journal-entry style
function UserPrompt({ m }) {
  return (
    <div style={{ padding: '24px 0 12px' }}>
      <div style={{ display: 'flex', gap: 14, alignItems: 'baseline' }}>
        <span style={{
          fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.2em',
          textTransform: 'uppercase', color: 'var(--ink-3)',
        }}>You · {m.time}</span>
        <span style={{ flex: 1, height: 1, background: 'var(--elev-3)' }} />
      </div>
      <div style={{ marginTop: 14, fontFamily: 'var(--serif)', fontSize: 26, lineHeight: 1.35,
        fontStyle: 'italic', color: 'var(--ink-2)', letterSpacing: '-0.005em' }}>
        "{m.text}"
      </div>
    </div>
  );
}

// Big composer with claim-the-frame feel — uses the prompt-shell CSS module
// `dense` mode (mobile): hides starter chips, single-line input, compact button —
// because the topic cards above the conversation already carry that role.
function ImmersiveComposer({ onSend, companyName = 'Smithfield Digital', dense = false }) {
  const [text, setText] = React.useState('');

  // Conversational starter prompts — locked, always visible above the input.
  const starters = [
    `What's the single biggest risk before Series B?`,
    `How does ${companyName} compare to Helix on AI durability?`,
    `What's changed in the last 7 days?`,
    `Summarise the Tech Audit in 5 bullets.`,
  ];

  const submit = () => {
    if (!text.trim()) return;
    onSend(text);
    setText('');
  };
  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); }
  };

  if (dense) {
    return (
      <div className="prompt-shell" style={{ padding: '12px 16px 14px' }}>
        <div className="prompt-frame" style={{ padding: '12px 14px', alignItems: 'center' }}>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={onKey}
            placeholder={`Ask α about ${companyName}…`}
            className="prompt-input"
            style={{ fontSize: 16 }}
          />
          <button onClick={submit} className="prompt-send" style={{ padding: '10px 14px' }}>
            Send <Arrow size={11} color="#fff" />
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="prompt-shell">
      <div className="prompt-eyebrow" style={{ marginBottom: 14 }}>
        Ask α <span className="accent">·</span> About {companyName} <span className="accent">·</span> Try one of these
      </div>
      <div style={{
        display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18,
      }}>
        {starters.map(s => (
          <button key={s} onClick={() => setText(s)} style={{
            background: 'var(--surface)', border: '1px solid var(--elev-2)',
            color: 'var(--ink-2)', padding: '8px 14px',
            fontFamily: 'var(--sans)', fontSize: 13,
            letterSpacing: '-0.01em', cursor: 'pointer',
            transition: 'all 140ms',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = 'var(--accent-deep)';
            e.currentTarget.style.color = 'var(--ink)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = 'var(--elev-2)';
            e.currentTarget.style.color = 'var(--ink-2)';
          }}>
            {s}
          </button>
        ))}
      </div>

      <div className="prompt-frame">
        <div style={{ minWidth: 0 }}>
          <div className="prompt-eyebrow" style={{ marginBottom: 4 }}>
            <span className="accent">α</span> &nbsp;Prompt
          </div>
          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={onKey}
            placeholder={`What would you like to know about ${companyName}?`}
            rows={1}
            className="prompt-input"
            style={{ minHeight: 32 }}
          />
        </div>
        <button onClick={submit} className="prompt-send">
          Send <Arrow size={12} color="#fff" />
        </button>
      </div>
      <div className="prompt-hint">
        <span>Press <span style={{ color: 'var(--ink-2)' }}>⏎</span> to send · <span style={{ color: 'var(--ink-2)' }}>⇧⏎</span> for new line</span>
        <span>α answers from the corpus · always cited</span>
      </div>
    </div>
  );
}

// Compose a fresh user→alpha pair when a topic is picked or text is sent
function makeUserMsg(text, time = '09:42') {
  return { role: 'user', text, time };
}
function makeAlphaPlaceholder(axisKey, axisLabel, score, rag, time = '09:42') {
  return {
    role: 'alpha', time,
    brief: {
      lead: `Streaming intelligence on ${axisLabel}. The corpus is being interrogated for atoms tagged "${axisKey}" and cross-references back to the Tech Audit, Competitor Teardown and Team Bios.`,
      axis: { name: axisLabel, score, rag,
        note: 'Score view is live · methodology v3.4 · this brief will populate as atoms resolve.' },
      signals: [
        { t: 'Resolving atoms from primary corpus…', src: 'In progress', ref: 0 },
      ],
      citedAtoms: [],
      verdict: '',
      confidence: '—', atoms: 0, sources: 0,
    },
  };
}

Object.assign(window, {
  TopicCards, ImmersiveBrief, UserPrompt, ImmersiveComposer,
  makeUserMsg, makeAlphaPlaceholder,
  BriefAxisCard, BriefCluster, BriefComparison, BriefCitationTable,
});
