/* global window, React */
// ============================================================
// Bottom — TP Agent ORA strip
// ============================================================

const { useState: useAgentState } = React;

function OraCard({ kind, item }) {
  return (
    <div className={`ora-card ora-card--${kind} ${item.dimmed ? 'ora-card--dimmed' : ''}`}>
      <div className="ora-card__head">
        <span className="ora-card__label">{item.label}</span>
        {item.wave && <span className="ora-card__wave">{item.wave}</span>}
      </div>
      <div className="ora-card__text" dangerouslySetInnerHTML={{ __html: item.text }}></div>
      {item.action && !item.dimmed && (
        <button className="ora-action">
          {item.action}
          <span className="arr">→</span>
        </button>
      )}
    </div>
  );
}

function AgentStrip({ trip, expanded, onToggle, overview }) {
  const ora = overview ? window.CROSS_ORA : trip.ora;
  // wave attribution: how many waves the signals span
  const wavesTouched = !overview && trip
    ? Array.from(new Set([...ora.observe, ...ora.reason, ...ora.act].map(c => (c.wave || '').split(' ')[0]).filter(Boolean)))
    : [];
  return (
    <div className={`agent ${expanded ? 'agent--expanded' : 'agent--collapsed'} ${overview ? 'agent--overview' : ''}`}>
      <div className="agent__bar" onClick={onToggle}>
        <span className="agent__icon">TP</span>
        <span className="agent__title">TP Agent</span>
        <span className="agent__state">
          {overview ? (
            <>
              <span>Reasoning across</span>
              <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink)' }}>Wave 7 · all trips</span>
            </>
          ) : (
            <>
              <span>Suggestions for</span>
              <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink)' }}>{trip.id}</span>
              <span className="sep">·</span>
              <span>signals from</span>
              <span style={{ display: 'inline-flex', gap: 4 }}>
                {wavesTouched.map(w => <span key={w} className="agent__wave-chip">{w}</span>)}
              </span>
            </>
          )}
          <span className="sep">·</span>
          <span className="ready">{ora.act.filter(a => !a.dimmed).length} action{ora.act.filter(a=>!a.dimmed).length===1?'':'s'} ready</span>
        </span>
        <span className="agent__chev">⌃</span>
      </div>

      {expanded && (
        <>
          <div className="agent__body">
            <div className="agent__col agent__col--observe">
              <div className="agent__col-head">
                <span className="step-n">1</span>
                <span>Observe</span>
                <span className="step-divider"></span>
              </div>
              {ora.observe.map((o, i) => <OraCard key={i} kind="observe" item={o} />)}
            </div>

            <div className="agent__col agent__col--reason">
              <div className="agent__col-head">
                <span className="step-n">2</span>
                <span>Reason</span>
                <span className="step-divider"></span>
              </div>
              {ora.reason.map((o, i) => <OraCard key={i} kind="reason" item={o} />)}
            </div>

            <div className="agent__col agent__col--act">
              <div className="agent__col-head">
                <span className="step-n">3</span>
                <span>Act</span>
                <span className="step-divider"></span>
              </div>
              {ora.act.map((o, i) => <OraCard key={i} kind="act" item={o} />)}
            </div>
          </div>

          <ChatBar />
        </>
      )}
    </div>
  );
}

function ChatBar() {
  const [text, setText] = useAgentState('');
  const [reply, setReply] = useAgentState(null);
  const send = () => {
    if (!text.trim()) return;
    // Canned demo reply
    setReply(`On Wave 7, <span style="font-family:var(--font-mono);color:var(--ink)">TR-4879</span> and <span style="font-family:var(--font-mono);color:var(--ink)">TR-4889</span> have ≥24h slack. <span style="font-family:var(--font-mono);color:var(--ink)">TR-4883</span> is held on inventory and will not move regardless. Defer-safe: 2.`);
    setText('');
  };
  return (
    <>
      <div className="agent__chat">
        <span className="agent__chat-icon">→</span>
        <input
          placeholder="Ask the agent…  e.g. Which loads can wait 24h without missing the window?"
          value={text}
          onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') send(); }}
        />
        <button className="agent__send" onClick={send}>Send</button>
      </div>
      {reply && (
        <div className="agent-reply">
          <span className="who">Agent</span>
          <div dangerouslySetInnerHTML={{ __html: reply }}></div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { AgentStrip });
