/* Viamar Ops — Support inbox (reply to customer chats) */

function OpsBubble({ m }) {
  const agent = m.from === 'agent';
  return (
    <div style={{ display: 'flex', justifyContent: agent ? 'flex-end' : 'flex-start', marginBottom: 10 }}>
      <div style={{ maxWidth: '74%' }}>
        <div style={{
          background: agent ? T.navy : '#fff', color: agent ? '#fff' : T.ink,
          borderRadius: agent ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
          padding: '10px 14px', fontFamily: FB, fontSize: 13.5, lineHeight: 1.45,
          border: agent ? 'none' : '1px solid ' + T.line2, boxShadow: '0 1px 2px rgba(10,27,46,0.05)',
        }}>{m.t}</div>
        <div style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, marginTop: 3, textAlign: agent ? 'right' : 'left', padding: '0 4px' }}>{m.time}{agent ? ' · Marco' : ''}</div>
      </div>
    </div>
  );
}

function InboxScreen({ onToast }) {
  const [sel, setSel] = React.useState(OPS_THREADS[0].id);
  const [store, setStore] = React.useState(() => { const o = {}; OPS_THREADS.forEach(t => o[t.id] = t.msgs.slice()); return o; });
  const [input, setInput] = React.useState('');
  const [readSet, setReadSet] = React.useState({});
  const scrollRef = React.useRef(null);
  const t = OPS_THREADS.find(x => x.id === sel);
  const msgs = store[sel] || [];

  React.useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [msgs, sel]);
  React.useEffect(() => { setReadSet(r => ({ ...r, [sel]: true })); }, [sel]);

  const now = () => new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
  const send = (txt) => {
    const text = (txt != null ? txt : input).trim(); if (!text) return;
    setInput('');
    setStore(s => ({ ...s, [sel]: [...s[sel], { from: 'agent', t: text, time: now() }] }));
  };
  const suggestion = t.ship === 'VMR-48217'
    ? "Your BMW is at sea aboard MV Atlantic Crown — about 62% of the way, ETA Bremerhaven Jun 14."
    : "Thanks for reaching out — let me check that for you right away.";

  return (
    <div style={{ display: 'flex', height: '100%' }}>
      {/* thread list */}
      <div style={{ width: 320, flexShrink: 0, borderRight: '1px solid ' + T.line, background: '#FBFBFC', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '24px 20px 12px' }}>
          <Display size={21} color={T.ink}>Inbox</Display>
          <div style={{ fontFamily: FM, fontSize: 11, color: T.muted, marginTop: 4 }}>{OPS_THREADS.filter(x => x.unread && !readSet[x.id]).length} unread</div>
        </div>
        <div className="vscroll" style={{ flex: 1, overflowY: 'auto', padding: '4px 0 20px' }}>
          {OPS_THREADS.map(x => {
            const active = sel === x.id, unread = x.unread && !readSet[x.id];
            return (
              <div key={x.id} onClick={() => setSel(x.id)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 18px', cursor: 'pointer', background: active ? '#fff' : 'transparent', borderLeft: active ? '3px solid ' + T.red : '3px solid transparent' }}>
                <div style={{ width: 38, height: 38, borderRadius: '50%', background: T.navy, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FD, fontWeight: 800, fontSize: 14, flexShrink: 0 }}>{x.avatar}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <span style={{ fontFamily: FB, fontWeight: 700, fontSize: 13, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.customer}</span>
                    <span style={{ fontFamily: FM, fontSize: 9.5, color: T.faint, flexShrink: 0 }}>{x.time}</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ flex: 1, fontFamily: FB, fontSize: 11.5, color: unread ? T.ink : T.muted, fontWeight: unread ? 600 : 400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.last}</span>
                    {unread && <span style={{ width: 7, height: 7, borderRadius: '50%', background: T.red, flexShrink: 0 }} />}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* conversation */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.paper }}>
        <div style={{ flexShrink: 0, padding: '16px 24px', borderBottom: '1px solid ' + T.line, background: '#fff', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 40, height: 40, borderRadius: '50%', background: T.navy, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FD, fontWeight: 800, fontSize: 15 }}>{t.avatar}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FD, fontWeight: 800, fontSize: 16, color: T.ink, fontStretch: '110%' }}>{t.customer}</div>
            <div style={{ fontFamily: FM, fontSize: 10.5, color: T.muted }}>{t.ship} · customer</div>
          </div>
          <Btn variant="ghost" size="sm" icon="box" onClick={() => onToast('Opening ' + t.ship)}>View shipment</Btn>
        </div>
        <div ref={scrollRef} className="vscroll" style={{ flex: 1, overflowY: 'auto', padding: '18px 24px' }}>
          {msgs.map((m, i) => <OpsBubble key={i} m={m} />)}
        </div>
        {/* suggested reply */}
        <div style={{ flexShrink: 0, padding: '8px 24px 0' }}>
          <div onClick={() => send(suggestion)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'rgba(221,28,36,0.06)', border: '1px solid rgba(221,28,36,0.2)', borderRadius: 999, padding: '7px 13px', cursor: 'pointer', maxWidth: '100%' }}>
            <Icon name="spark" size={14} color={T.red} stroke={2} />
            <span style={{ fontFamily: FB, fontSize: 12, color: T.body, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Suggested · {suggestion}</span>
          </div>
        </div>
        {/* input */}
        <div style={{ flexShrink: 0, padding: '12px 24px 22px', display: 'flex', alignItems: 'center', gap: 11 }}>
          <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') send(); }}
            placeholder={'Reply to ' + t.customer + '…'} style={{ flex: 1, border: '1.5px solid ' + T.line, borderRadius: 999, padding: '12px 18px', fontSize: 14, color: T.ink, outline: 'none', background: '#fff' }} />
          <div onClick={() => send()} style={{ width: 44, height: 44, borderRadius: '50%', background: input.trim() ? T.red : T.line, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0, transition: 'background .15s' }}>
            <Icon name="arrowR" size={20} color="#fff" stroke={2.4} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InboxScreen });
