// GetContent — Berichten (chat). Gesprekkenlijst + live thread. Een gesprek
// ontstaat bij de match; beide deelnemers chatten hier realtime (Supabase Realtime).

function ChatThread({ conversation, auth, onBack }) {
  const NS = window.GetContentDesignSystem_aa0f52;
  const { Button } = NS;
  const [messages, setMessages] = React.useState(null); // null = laden
  const [text, setText] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    let alive = true;
    window.GC_STORE.loadMessages(conversation.id).then(function (rows) { if (alive) setMessages(rows); });
    const unsub = window.GC_STORE.subscribeMessages(conversation.id, function (m) {
      setMessages(function (prev) {
        const list = prev || [];
        if (list.some(function (x) { return x.id === m.id; })) return list;
        return list.concat(m);
      });
    });
    return function () { alive = false; unsub(); };
  }, [conversation.id]);

  // naar onderen scrollen bij nieuwe berichten
  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
    try { window.lucide && window.lucide.createIcons(); } catch (e) {}
  }, [messages]);

  const send = async (e) => {
    e.preventDefault();
    const body = text.trim();
    if (!body || sending) return;
    setSending(true);
    const res = await window.GC_STORE.sendMessage(conversation.id, body);
    setSending(false);
    if (res && res.ok) {
      setText('');
      setMessages(function (prev) {
        const list = prev || [];
        return list.some(function (x) { return x.id === res.message.id; }) ? list : list.concat(res.message);
      });
    }
  };

  const other = conversation.other || {};
  const initial = (other.name || '?').charAt(0).toUpperCase();
  const fmtTime = (iso) => { try { return new Date(iso).toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; } };

  const card = { background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)' };

  return (
    <div style={Object.assign({}, card, { display: 'flex', flexDirection: 'column', overflow: 'hidden' })}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderBottom: '1px solid var(--border-subtle)' }}>
        <button type="button" onClick={onBack} aria-label="Terug naar berichten" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, flex: 'none', border: 'none', borderRadius: 'var(--radius-sm)', background: 'transparent', cursor: 'pointer', color: 'var(--text-muted)' }}>
          <i data-lucide="arrow-left" style={{ width: 18, height: 18 }}></i>
        </button>
        {other.avatar
          ? <img src={other.avatar} alt="" style={{ width: 40, height: 40, flex: 'none', borderRadius: '50%', objectFit: 'cover' }} />
          : <span style={{ width: 40, height: 40, flex: 'none', borderRadius: '50%', background: 'var(--accent-tint)', color: 'var(--accent-press)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 15, fontWeight: 'var(--fw-bold)' }}>{initial}</span>}
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 15.5, fontWeight: 'var(--fw-semibold)', color: 'var(--text-strong)' }}>{other.name}</div>
          {conversation.jobTitle && <div style={{ fontSize: 12.5, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{conversation.jobTitle}</div>}
        </div>
      </div>

      {/* berichten */}
      <div ref={scrollRef} style={{ flex: 1, minHeight: 320, maxHeight: '56vh', overflowY: 'auto', padding: '18px', display: 'flex', flexDirection: 'column', gap: 10, background: 'var(--surface-sunken)' }}>
        {messages === null ? (
          <div style={{ margin: 'auto', color: 'var(--text-muted)', fontSize: 14 }}>Even laden…</div>
        ) : messages.length === 0 ? (
          <div style={{ margin: 'auto', textAlign: 'center', color: 'var(--text-muted)', fontSize: 14, maxWidth: 280 }}>Nog geen berichten. Stuur het eerste bericht om af te stemmen.</div>
        ) : messages.map(function (m) {
          const mine = m.sender_id === auth.id;
          return (
            <div key={m.id} style={{ alignSelf: mine ? 'flex-end' : 'flex-start', maxWidth: '78%' }}>
              <div style={{
                padding: '9px 13px', borderRadius: 14,
                background: mine ? 'var(--accent)' : 'var(--surface-card)',
                color: mine ? 'var(--on-accent)' : 'var(--text-strong)',
                border: mine ? 'none' : '1px solid var(--border-subtle)',
                fontSize: 14.5, lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word',
              }}>{m.body}</div>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 3, textAlign: mine ? 'right' : 'left' }}>{fmtTime(m.created_at)}</div>
            </div>
          );
        })}
      </div>

      {/* invoer */}
      <form onSubmit={send} style={{ display: 'flex', gap: 10, padding: 14, borderTop: '1px solid var(--border-subtle)' }}>
        <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Typ een bericht…"
          style={{ flex: 1, minWidth: 0, height: 44, border: '1.5px solid var(--border-strong)', borderRadius: 'var(--radius-pill)', background: 'var(--surface-inset)', padding: '0 16px', fontFamily: 'var(--font-sans)', fontSize: 15, color: 'var(--text-strong)', outline: 'none' }}
          onFocus={(e) => { e.target.style.borderColor = 'var(--accent)'; }}
          onBlur={(e) => { e.target.style.borderColor = 'var(--border-strong)'; }} />
        <Button type="submit" variant="primary" disabled={sending || !text.trim()}>Versturen</Button>
      </form>
    </div>
  );
}

function Messages({ onNav }) {
  const s = window.useStore();
  const auth = s.auth;
  const convId = (s.ui || {}).conversationId || null;

  React.useEffect(() => { window.GC_STORE.loadConversations(); }, []);
  React.useEffect(() => { try { window.lucide && window.lucide.createIcons(); } catch (e) {} });

  if (!auth) return null;
  const conversations = s.conversations || [];
  const active = conversations.find(function (c) { return c.id === convId; }) || null;

  const card = { background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)' };
  const fmtWhen = (iso) => { try { const d = new Date(iso); const t = d.toDateString() === new Date().toDateString(); return t ? d.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' }) : d.toLocaleDateString('nl-NL', { day: 'numeric', month: 'short' }); } catch (e) { return ''; } };

  return (
    <window.AppPage eyebrow="Berichten" title="Berichten" subtitle="Chat met je match over de details van de opdracht." maxWidth="760px" onNav={onNav}>
      {active ? (
        <ChatThread key={active.id} conversation={active} auth={auth} onBack={() => window.GC_STORE.openConversation(null)} />
      ) : conversations.length === 0 ? (
        <window.EmptyState icon="messages-square" title="Nog geen gesprekken" text="Zodra er een match is (een opdrachtgever kiest een creator), verschijnt hier je gesprek." />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {conversations.map(function (c) {
            const other = c.other || {};
            const initial = (other.name || '?').charAt(0).toUpperCase();
            return (
              <div key={c.id} onClick={() => window.GC_STORE.openConversation(c.id)} style={Object.assign({}, card, { padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' })}>
                {other.avatar
                  ? <img src={other.avatar} alt="" style={{ width: 46, height: 46, flex: 'none', borderRadius: '50%', objectFit: 'cover' }} />
                  : <span style={{ width: 46, height: 46, flex: 'none', borderRadius: '50%', background: 'var(--accent-tint)', color: 'var(--accent-press)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 17, fontWeight: 'var(--fw-bold)' }}>{initial}</span>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 16, fontWeight: 'var(--fw-semibold)', color: 'var(--text-strong)' }}>{other.name}</div>
                  {c.jobTitle && <div style={{ fontSize: 13, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.jobTitle}</div>}
                </div>
                <div style={{ flex: 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{fmtWhen(c.lastMessageAt)}</span>
                  <i data-lucide="chevron-right" style={{ width: 18, height: 18, color: 'var(--text-faint)' }}></i>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </window.AppPage>
  );
}
window.Messages = Messages;
