// Messages tab — list + thread viewer.

function MessagesTab({ pal, threadId, setThreadId }) {
  const t = useTweaks();
  const jm = window.JOY_MOVE;
  const filler = t.demo !== 'clean';
  const threads = filler ? jm.messageThreads : [];
  const current = threadId ? threads.find(th => th.id === threadId) : threads[0];

  return (
    <Page pal={pal}
      kicker="Conversation"
      title="Messages"
      sub="Direct line to your team. For anything that's not tied to a specific request."
    >
      {threads.length === 0 ? (
        <Card pal={pal}>
          <EmptyState pal={pal} icon="✉"
            title="No messages yet"
            body="Say hi anytime — this is your direct line to the team. For specific work, file a request so hours get tracked correctly."
          />
        </Card>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 0, height: 'calc(100vh - 340px)', minHeight: 540 }}>
          {/* Thread list */}
          <Card pal={pal} style={{ overflow: 'hidden', borderTopRightRadius: 0, borderBottomRightRadius: 0, borderRight: 'none' }}>
            <div style={{ padding: '16px 20px', borderBottom: `1px solid ${pal.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: pal.textStrong }}>Inbox</div>
              <BtnText pal={pal}>＋ New</BtnText>
            </div>
            <div style={{ overflow: 'auto' }}>
              {threads.map(th => {
                const active = current?.id === th.id;
                return (
                  <div key={th.id} onClick={() => setThreadId(th.id)} style={{
                    padding: '16px 20px', cursor: 'pointer',
                    borderBottom: `1px solid ${pal.border}`,
                    background: active ? pal.warm : 'transparent',
                    borderLeft: active ? `2px solid ${pal.accent}` : '2px solid transparent',
                  }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: pal.textStrong, display: 'flex', alignItems: 'center', gap: 6 }}>
                        {th.unread && <span style={{ width: 6, height: 6, borderRadius: '50%', background: pal.accent }} />}
                        {th.with}
                      </div>
                      <div style={{ fontSize: 10, color: pal.muted }}>{th.updated}</div>
                    </div>
                    <div style={{ fontSize: 12, color: pal.textStrong, fontWeight: 500, marginBottom: 3 }}>{th.subject}</div>
                    <div style={{ fontSize: 12, color: pal.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {th.messages[th.messages.length - 1].body}
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
          {/* Thread view */}
          <Card pal={pal} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', borderTopLeftRadius: 0, borderBottomLeftRadius: 0 }}>
            <ThreadView pal={pal} th={current} />
          </Card>
        </div>
      )}
    </Page>
  );
}

function ThreadView({ pal, th }) {
  const [reply, setReply] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sentMsg, setSentMsg] = React.useState(null);
  if (!th) return <EmptyState pal={pal} title="Pick a conversation" body="Choose a thread from the left." />;
  const sendMsg = async () => {
    if (!reply.trim()) return;
    setSending(true);
    try {
      const slug = window.getPortalParams().slug;
      await window.Portal.submitMessage(slug, { threadId: th.id, subject: th.subject, body: reply });
      setSentMsg('Sent.');
      setReply('');
      setTimeout(() => setSentMsg(null), 3000);
    } catch (e) {
      setSentMsg('Could not send.');
    } finally {
      setSending(false);
    }
  };
  return (
    <>
      <div style={{ padding: '20px 28px', borderBottom: `1px solid ${pal.border}` }}>
        <Display pal={pal} size={22}>{th.subject}</Display>
        <div style={{ fontSize: 12, color: pal.muted, marginTop: 4 }}>with {th.with}</div>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 28px' }}>
        {th.messages.map((m, i) => (
          <div key={i} style={{ marginBottom: 22, display: 'flex', gap: 14, flexDirection: m.role === 'agency' ? 'row' : 'row-reverse' }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
              background: m.role === 'agency' ? pal.accent : pal.warm,
              color: m.role === 'agency' ? pal.onAccent : pal.textStrong,
              display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
              border: m.role === 'client' ? `1px solid ${pal.border}` : 'none',
            }}>{m.from.split(' ').map(s => s[0]).join('').slice(0, 2)}</div>
            <div style={{ maxWidth: '72%' }}>
              <div style={{
                padding: '12px 16px',
                background: m.role === 'agency' ? pal.warm : pal.accent,
                color: m.role === 'agency' ? pal.textStrong : pal.onAccent,
                border: m.role === 'agency' ? `1px solid ${pal.border}` : 'none',
                borderRadius: 14,
                fontSize: 14, lineHeight: 1.55,
              }}>{m.body}</div>
              <div style={{ fontSize: 10, color: pal.muted, marginTop: 5, textAlign: m.role === 'agency' ? 'left' : 'right' }}>
                {m.from} · {m.when}
              </div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: 20, borderTop: `1px solid ${pal.border}`, background: pal.warm }}>
        <Textarea pal={pal} placeholder="Write a message…" value={reply} onChange={e => setReply(e.target.value)} style={{ minHeight: 70 }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, alignItems: 'center' }}>
          <div style={{ fontSize: 11, color: pal.muted, fontStyle: 'italic' }}>For tracked work, file a request instead.</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {sentMsg && <span style={{ fontSize: 11, color: pal.accent, fontStyle: 'italic' }}>{sentMsg}</span>}
            <BtnPrimary pal={pal} disabled={!reply.trim() || sending} onClick={sendMsg}>{sending ? 'Sending…' : 'Send'}</BtnPrimary>
          </div>
        </div>
      </div>
    </>
  );
}

window.MessagesTab = MessagesTab;
