// studio-messages.jsx — the admin's view of the contact form's inbox.
//
// Every submission is emailed to hi@modaboard.com and kept here as a backup,
// so a mail outage never loses a message. Admin-only: mb_is_admin() inside
// mb_list_contact_messages() decides what comes back, and the policies on
// contact_messages are what refuse everyone else.

const { useState: useStateMS, useEffect: useEffectMS } = React;

function StudioMessages({ isAdmin }) {
  const [messages, setMessages] = useStateMS([]);
  const [loading, setLoading] = useStateMS(true);
  const [error, setError] = useStateMS(null);
  const [openId, setOpenId] = useStateMS(null);
  const [confirmId, setConfirmId] = useStateMS(null);
  const [busy, setBusy] = useStateMS(false);

  const load = async () => {
    const res = await window.MBContact.list(200);
    if (res.error) setError(res.error);
    else setMessages(res.messages);
    setLoading(false);
  };

  useEffectMS(() => { if (isAdmin) load(); else setLoading(false); }, [isAdmin]);

  const remove = async (m) => {
    if (busy) return;
    setBusy(true);
    const res = await window.MBContact.remove(m.id);
    setBusy(false);
    setConfirmId(null);
    if (res.error) { setError(res.error); return; }
    setMessages(prev => prev.filter(x => x.id !== m.id));
  };

  if (!isAdmin) {
    return (
      <div>
        <StudioHeader kicker="Studio · Messages" title="Admins only."/>
        <Card>
          <div style={{ fontSize: 14, color: '#5a5a54', lineHeight: 1.6, maxWidth: '52ch' }}>
            The contact inbox is for modaBoard admins. Your account doesn’t have that flag.
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div>
      <StudioHeader
        kicker="Studio · Messages"
        title="Contact inbox."
        sub="Every message from the contact form. Each one was emailed to hi@modaboard.com as well — this is the copy."
      />

      {error && (
        <div style={{
          marginBottom: 14, padding: '11px 14px', borderRadius: 10, fontSize: 12.5,
          background: 'rgba(168,51,26,0.07)', border: '1px solid rgba(168,51,26,0.25)', color: '#a8331a',
        }}>{error}</div>
      )}

      <Card padding={0}>
        {loading && <div style={{ padding: 20, fontSize: 13, color: '#8a8580' }}>Loading messages…</div>}

        {!loading && !error && messages.length === 0 && (
          <div style={{ padding: 28, textAlign: 'center' }}>
            <div style={{ fontSize: 15, color: '#3a3a36' }}>No messages yet.</div>
            <p style={{ marginTop: 8, fontSize: 13, color: '#8a8580' }}>
              Anything sent through the contact form lands here.
            </p>
          </div>
        )}

        {!loading && messages.map((m, i) => {
          const open = openId === m.id;
          return (
            <div key={m.id} data-message={m.id} style={{
              padding: '14px 18px',
              borderTop: i === 0 ? 'none' : '1px solid rgba(20,20,18,0.06)',
              background: open ? '#FAFAF7' : 'transparent',
            }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'start' }}>
                <button onClick={() => setOpenId(open ? null : m.id)} style={{
                  appearance: 'none', border: 'none', background: 'transparent', padding: 0,
                  textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit', minWidth: 0,
                }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 14.5 }}>{m.subject || 'No subject'}</span>
                    {m.category && (
                      <span style={{
                        fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
                        padding: '3px 8px', borderRadius: 999, background: '#F2EFE7', color: '#5a5a54',
                      }}>{m.category}</span>
                    )}
                  </div>
                  <div style={{ fontSize: 12, color: '#8a8580', marginTop: 3 }}>
                    {m.name} · {m.email}
                    {m.createdAt && ' · ' + new Date(m.createdAt).toLocaleString(undefined, {
                      day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
                    })}
                  </div>
                  {!open && (
                    <div style={{
                      fontSize: 12.5, color: '#5a5a54', marginTop: 5, maxWidth: '70ch',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>{m.message}</div>
                  )}
                </button>

                <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  <a href={'mailto:' + encodeURIComponent(m.email)
                       + '?subject=' + encodeURIComponent('Re: ' + (m.subject || 'your message'))}
                     style={{ ...msgBtnGhost, textDecoration: 'none', display: 'inline-block' }}>Reply</a>
                  {confirmId === m.id ? (
                    <>
                      <button onClick={() => remove(m)} disabled={busy} style={{ ...msgBtnGhost, borderColor: '#a8331a', color: '#a8331a' }}>
                        {busy ? 'Deleting…' : 'Delete for good'}
                      </button>
                      <button onClick={() => setConfirmId(null)} style={msgBtnGhost}>Cancel</button>
                    </>
                  ) : (
                    <button onClick={() => setConfirmId(m.id)} style={{ ...msgBtnGhost, color: '#8a8580' }}>Delete</button>
                  )}
                </div>
              </div>

              {open && (
                <div style={{
                  marginTop: 12, padding: '14px 16px', borderRadius: 10, background: '#fff',
                  border: '1px solid rgba(20,20,18,0.08)', fontSize: 13.5, lineHeight: 1.6,
                  whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                }}>{m.message}</div>
              )}
            </div>
          );
        })}
      </Card>
    </div>
  );
}

const msgBtnGhost = {
  appearance: 'none', border: '1px solid rgba(20,20,18,0.16)', background: 'transparent',
  color: '#1a1a18', fontSize: 11, padding: '8px 12px', letterSpacing: '0.12em',
  textTransform: 'uppercase', fontWeight: 500, borderRadius: 999, cursor: 'pointer',
  fontFamily: 'inherit', lineHeight: 1.2,
};

Object.assign(window, { StudioMessages });
