const DSm = window.RallyAIBusiness_2d8789;
const { PixelIcon: MIcon, PixelChar: MChar, Chip: MChip, Button: MButton, Input: MInput } = DSm;

function MessagesScreen({ custs, scopeId, nav }) {
  const list = custs.filter(c => scopeId === 'brand' || c.outlet === scopeId);
  const open = list.filter(c => c.on);
  return <div style={{ '--accent': 'var(--orange)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 16px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Chats</h1>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>{open.length} of {list.length} customers opted in</div>
    </div>
    <div style={{ background: 'var(--sage)', padding: '12px 24px', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <MIcon name="alert" size={18} style={{ flexShrink: 0, marginTop: 1 }} />
      <span style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35 }}>You can only message customers who opted in. They can switch off anytime — and choose not to reply.</span>
    </div>
    <div style={{ flex: 1 }}>
      {list.map(c => {
        const last = c.msgs[c.msgs.length - 1];
        return <div key={c.id} onClick={c.on ? () => nav('thread', c.id) : undefined} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 24px', borderBottom: '1px solid rgba(32,36,27,.2)', cursor: c.on ? 'pointer' : 'default', opacity: c.on ? 1 : 0.45 }}>
          <MChar name={c.char} size={44} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{ fontSize: 16, fontWeight: 700 }}>{c.name}</span>
              <span className="u-label" style={{ color: 'var(--text-muted)' }}>{c.seg} · {RallyData.outlets[c.outlet].tag}</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {c.on ? (last ? (last.f === 'm' ? 'You: ' : '') + last.t : 'No messages yet — say hello') : 'Customer switched off messages'}
            </div>
          </div>
          <MChip pixel variant={c.on ? 'accent' : 'outline'}>{c.on ? 'OPEN' : 'OFF'}</MChip>
        </div>;
      })}
    </div>
    <div style={{ padding: '14px 24px', borderTop: '1px solid var(--ink)' }}>
      <span className="u-label" style={{ color: 'var(--text-muted)' }}>Customers grant messaging permission when completing a quest</span>
    </div>
  </div>;
}

function ThreadScreen({ custs, id, onSend, nav }) {
  const c = custs.find(x => x.id === id);
  const [text, setText] = React.useState('');
  const endRef = React.useRef(null);
  React.useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [c && c.msgs.length]);
  if (!c) return null;
  const send = () => { if (!text.trim()) return; onSend(c.id, text.trim()); setText(''); };
  const sentUnanswered = c.msgs.length && c.msgs[c.msgs.length - 1].f === 'm' && !c.reply;
  return <div style={{ '--accent': 'var(--orange)', height: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--ink)', display: 'flex', alignItems: 'center', gap: 14 }}>
      <span onClick={() => nav('messages')} style={{ cursor: 'pointer', display: 'flex' }}><MIcon name="arrow-right" size={16} style={{ transform: 'scaleX(-1)' }} /></span>
      <MChar name={c.char} size={40} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 16, fontWeight: 700 }}>{c.name}</div>
        <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{c.seg} · {RallyData.outlets[c.outlet].name}</div>
      </div>
      <MChip pixel variant="accent">OPEN</MChip>
    </div>
    <div ref={endRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {c.msgs.map((m, i) => m.f === 'c'
        ? <div key={i} style={{ maxWidth: '85%' }}>
            <div className="u-pixel" style={{ marginBottom: 4 }}>{c.name.toUpperCase()} · {m.time.toUpperCase()}</div>
            <div style={{ fontSize: 16, fontWeight: 500, lineHeight: 1.35 }}>{m.t}</div>
          </div>
        : <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '80%' }}>
            <div style={{ background: 'var(--ink)', color: 'var(--white)', padding: '10px 14px', fontSize: 15, lineHeight: 1.35 }}>{m.t}</div>
            <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 4, textAlign: 'right' }}>Sent · {m.time}</div>
          </div>)}
      {sentUnanswered && <div className="u-label" style={{ color: 'var(--text-muted)', alignSelf: 'flex-end' }}>Delivered · {c.name} may choose not to reply</div>}
    </div>
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end', padding: '12px 24px 16px', borderTop: '1px solid var(--ink)' }}>
      <MInput placeholder={'Message ' + c.name} value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} style={{ flex: 1 }} />
      <MButton variant="accent" size="sm" onClick={send} aria-label="send"><MIcon name="send" size={16} /></MButton>
    </div>
  </div>;
}

Object.assign(window, { MessagesScreen, ThreadScreen });
