/* Queue list + Conversation thread + playback / composer */
const { useRef, useEffect } = React;

function Queue({ items, activeId, onPick }) {
  return (
    <aside className="queue">
      <div className="queue-head">
        <h3>Live queue</h3>
        <span className="queue-count">{items.length}</span>
      </div>
      <div className="queue-tabs">
        {['Assigned to me', 'Team', 'Resolved'].map((t, i) => (
          <button key={t} className={'qtab' + (i === 0 ? ' active' : '')}>{t}</button>
        ))}
      </div>
      <div className="queue-list">
        {items.map(it => (
          <div key={it.id} className={'iitem' + (it.id === activeId ? ' active' : '') + (it.active ? '' : ' inert')}
            title={it.active ? '' : 'Demo focuses on the live interaction'} onClick={() => onPick(it.id)}>
            <div className="av" style={{ background: CXData.avColor(it.seed) }}>{it.initials}</div>
            <div className="body">
              <div className="name">{it.name}
                <span className="chan"><Icon name={CXData.CHANNEL_ICON[it.channel]} size={15} /></span>
              </div>
              <div className="prev">{it.preview}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
              {it.active ? <span className="live-badge">live</span> : <span className="time">{it.time}</span>}
              {it.unread && !it.active && <span className="unread"></span>}
            </div>
          </div>
        ))}
      </div>
    </aside>
  );
}

function Conversation(props) {
  const { convo, messages, resolved, onResolve, onReopen } = props;
  const threadRef = useRef(null);
  useEffect(() => {
    if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
  }, [messages, resolved]);

  return (
    <section className="convo">
      <div className="convo-head">
        <div className="av" style={{ background: CXData.avColor(convo.seed) }}>{convo.initials}</div>
        <div>
          <div className="who">{convo.name}</div>
          <div className="sub">{convo.account} &middot; {convo.policy}</div>
        </div>
        <div className="actions">
          <button className="icon-btn" title="Customer profile"><Icon name="person" size={21} /></button>
          <button className="icon-btn" title="Transfer"><Icon name="swap_horiz" size={21} /></button>
          <button className="nice-btn nice-btn--primary nice-btn--sm resolve-btn" onClick={onResolve}>
            <Icon name="check_circle" size={18} />Resolve
          </button>
        </div>
      </div>

      <div className="thread" ref={threadRef}>
        <div className="daystamp">Today · theft claim</div>
        {messages.length === 0 && (
          <div className="empty-thread">
            <Icon name="forum" size={26} style={{ color: 'var(--fg3)' }} />
            <p>Press <strong>Start</strong> to play the interaction. Switch the agent in the top bar to compare a strong vs. struggling handling — the Coaching Copilot scores each turn live.</p>
          </div>
        )}
        {messages.map((m, i) => (
          <div key={i} className={'msg ' + m.from}>
            <div className="meta">{m.from === 'in' ? convo.name : 'Maya · agent'} · {m.time}</div>
            <div className="bubble">{m.t}</div>
          </div>
        ))}
      </div>

      {props.mode === 'cognigy'
        ? <Composer suggestions={props.suggestions} onSend={props.onSend} text={props.text}
            setText={props.setText} sending={props.sending} />
        : <PlaybackBar started={props.started} atEnd={props.atEnd} onNext={props.onNext} onReset={props.onReset} />}

      {resolved && (
        <div className="resolved">
          <div className="resolved-card">
            <img className="av" src="assets/nice-smile-avatar.svg" alt="" />
            <h2>All sorted</h2>
            <p>{convo.name}&rsquo;s claim is on its way. That&rsquo;s so NiCE!</p>
            <button className="nice-btn nice-btn--dark" onClick={onReopen}>Back to queue</button>
          </div>
        </div>
      )}
    </section>
  );
}

function PlaybackBar({ started, atEnd, onNext, onReset }) {
  return (
    <div className="composer playback">
      <button className="nice-btn nice-btn--dark" onClick={onReset} title="Reset">
        <Icon name="swap_horiz" size={18} />Reset
      </button>
      <button className="nice-btn nice-btn--primary play-next" onClick={onNext} disabled={atEnd}>
        {atEnd ? 'Interaction complete' : !started ? 'Start interaction' : 'Next turn'}
        {!atEnd && <Icon name="send" size={18} />}
      </button>
    </div>
  );
}

function Composer({ suggestions, onSend, text, setText, sending }) {
  const submit = () => { if (text.trim() && !sending) { onSend(text.trim()); } };
  return (
    <div className="composer">
      <div className="suggest-row">
        {(suggestions || []).map((s, i) => (
          <button key={i} className="suggest" onClick={() => setText(s)} title={'Insert suggested reply:\n' + s}>
            <Icon name="auto_awesome" size={16} />{s.length > 56 ? s.slice(0, 54) + '…' : s}
          </button>
        ))}
      </div>
      <div className="composer-box">
        <textarea rows={1} placeholder={sending ? 'Scoring with Cognigy…' : 'Type the agent’s reply — Copilot scores it live…'} value={text}
          onChange={e => setText(e.target.value)} disabled={sending}
          onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }} />
        <button className={'send' + (sending ? ' sending' : '')} onClick={submit} disabled={!text.trim() || sending}
          title={sending ? 'Scoring…' : 'Send'}>
          {sending ? <span className="spinner spinner--send"></span> : <Icon name="send" size={22} />}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Queue, Conversation });
