/* global React, ReactDOM */

const DC = {
  bg: '#0B0C0E', bg1: '#141518', bone: '#E6DCCB', softBone: 'rgba(230,220,203,0.72)',
  grey: '#8A8A86', mute: '#52524F', border: '#1F2024', borderHi: '#33353A',
  cyan: '#59A3B3',
};
const DF = {
  display: "'Playfair Display', Georgia, serif",
  sans: "'IBM Plex Sans', system-ui, sans-serif",
  mono: "'IBM Plex Mono', monospace",
};
const dease = 'cubic-bezier(0.2,0.7,0.2,1)';
const dwrap = { width: 'min(720px, calc(100% - 48px))', margin: '0 auto' };

function NewsletterPage() {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | loading | success | error | duplicate
  const [issues, setIssues] = React.useState(null);
  const [archiveError, setArchiveError] = React.useState(false);

  React.useEffect(() => {
    fetch('/api/newsletter/archive')
      .then(r => r.json())
      .then(d => setIssues(d.issues || []))
      .catch(() => setArchiveError(true));
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!email.trim()) return;
    setStatus('loading');
    try {
      const res = await fetch('/api/newsletter/subscribe', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      const data = await res.json();
      if (!res.ok) { setStatus('error'); return; }
      setStatus(data.alreadySubscribed ? 'duplicate' : 'success');
    } catch {
      setStatus('error');
    }
  }

  const statusMsg = {
    success:   { text: "You're subscribed. First issue arrives when it's ready.", color: DC.cyan },
    duplicate: { text: "That address is already subscribed.",                     color: DC.grey },
    error:     { text: "Something went wrong — try again or email hello@showgaze.app.", color: '#B25555' },
  };

  return (
    <div style={{ background: DC.bg, minHeight: '100vh', color: DC.bone }}>
      {/* Nav */}
      <header style={{ position: 'sticky', top: 0, zIndex: 20, background: 'rgba(11,12,14,0.92)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', borderBottom: `1px solid ${DC.border}` }}>
        <div style={{ ...dwrap, minHeight: 56, display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 8, paddingBottom: 8 }}>
          <a href="/" style={{ fontFamily: DF.display, fontSize: 16, color: DC.bone, textDecoration: 'none' }}>Showgaze</a>
          <a href="/apply/" style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', textDecoration: 'none', color: DC.bg, background: DC.cyan, border: `1px solid ${DC.cyan}`, borderRadius: 2, padding: '7px 12px' }}>Apply now</a>
        </div>
      </header>

      <main>
        {/* Hero */}
        <section style={{ borderBottom: `1px solid ${DC.border}` }}>
          <div style={{ ...dwrap, padding: '72px 0 64px' }}>
            <div style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase', color: DC.cyan, marginBottom: 20 }}>Newsletter</div>
            <h1 style={{ margin: '0 0 18px', fontFamily: DF.display, fontSize: 'clamp(30px, 4.5vw, 52px)', lineHeight: 1.06, fontWeight: 400, color: DC.bone }}>
              Monthly notes on live event media.
            </h1>
            <p style={{ margin: '0 0 36px', fontFamily: DF.sans, fontSize: 'clamp(15px, 1.3vw, 17px)', lineHeight: 1.84, color: DC.softBone, maxWidth: 560 }}>
              A short monthly digest on audience footage, post-show workflow, and what's happening in live event media — written for promoters, venues, and artists who take this seriously.
            </p>

            {/* Signup form */}
            {status === 'success' || status === 'duplicate' ? (
              <div style={{ fontFamily: DF.sans, fontSize: 15, color: statusMsg[status].color, paddingLeft: 16, borderLeft: `2px solid ${statusMsg[status].color}` }}>
                {statusMsg[status].text}
              </div>
            ) : (
              <form onSubmit={handleSubmit} style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
                <input
                  type="email"
                  placeholder="your@email.com"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  required
                  style={{ fontFamily: DF.mono, fontSize: 13, background: DC.bg1, border: `1px solid ${DC.borderHi}`, color: DC.bone, borderRadius: 2, padding: '10px 14px', outline: 'none', width: 260, transition: `border-color 140ms ${dease}` }}
                />
                <button
                  type="submit"
                  disabled={status === 'loading'}
                  style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', background: status === 'loading' ? DC.mute : DC.cyan, color: DC.bg, border: 'none', borderRadius: 2, padding: '11px 16px', cursor: status === 'loading' ? 'default' : 'pointer', transition: `background 140ms ${dease}` }}
                >
                  {status === 'loading' ? 'Subscribing...' : 'Subscribe'}
                </button>
                {status === 'error' && (
                  <span style={{ fontFamily: DF.sans, fontSize: 13, color: '#B25555' }}>{statusMsg.error.text}</span>
                )}
              </form>
            )}
          </div>
        </section>

        {/* Archive */}
        <section>
          <div style={{ ...dwrap, padding: '56px 0 80px' }}>
            <div style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase', color: DC.mute, marginBottom: 32 }}>Past issues</div>

            {issues === null && !archiveError && (
              <div style={{ fontFamily: DF.sans, fontSize: 14, color: DC.mute }}>Loading...</div>
            )}
            {archiveError && (
              <div style={{ fontFamily: DF.sans, fontSize: 14, color: DC.mute }}>Could not load archive.</div>
            )}
            {issues !== null && issues.length === 0 && (
              <div style={{ paddingLeft: 20, borderLeft: `1px solid ${DC.borderHi}` }}>
                <p style={{ margin: 0, fontFamily: DF.display, fontStyle: 'italic', fontSize: 22, color: DC.softBone, lineHeight: 1.3 }}>
                  First issue coming soon.
                </p>
                <p style={{ margin: '12px 0 0', fontFamily: DF.sans, fontSize: 14, color: DC.grey, lineHeight: 1.7 }}>
                  Subscribe above to receive it when it's ready.
                </p>
              </div>
            )}
            {issues !== null && issues.length > 0 && (
              <div>
                {issues.map((issue, i) => (
                  <a
                    key={issue.slug}
                    href={`/newsletter/${issue.slug}`}
                    style={{ display: 'grid', gridTemplateColumns: '100px minmax(0,1fr)', gap: '0 24px', padding: '20px 0', borderTop: `1px solid ${DC.border}`, textDecoration: 'none', alignItems: 'baseline' }}
                  >
                    <div style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.12em', color: DC.mute, textTransform: 'uppercase', paddingTop: 2 }}>
                      {issue.published_at ? new Date(issue.published_at).toLocaleDateString('en-AU', { month: 'short', year: 'numeric' }) : ''}
                    </div>
                    <div>
                      <div style={{ fontFamily: DF.display, fontSize: 'clamp(18px, 1.8vw, 22px)', fontWeight: 400, color: DC.bone, lineHeight: 1.2, marginBottom: 6 }}>
                        {issue.title}
                      </div>
                      {issue.summary && (
                        <div style={{ fontFamily: DF.sans, fontSize: 13, color: DC.grey, lineHeight: 1.6 }}>{issue.summary}</div>
                      )}
                    </div>
                  </a>
                ))}
                <div style={{ height: 1, background: DC.border }} />
              </div>
            )}
          </div>
        </section>
      </main>

      <footer style={{ borderTop: `1px solid ${DC.border}` }}>
        <div style={{ ...dwrap, padding: '20px 0 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <span style={{ fontFamily: DF.display, fontSize: 14, color: DC.bone }}>Showgaze</span>
          <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
            {[['Bio', '/about/'], ['Privacy', '/privacy.html'], ['Terms', '/terms.html'], ['hello@showgaze.app', 'mailto:hello@showgaze.app']].map(([label, href]) => (
              <a key={label} href={href} style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: DC.mute, textDecoration: 'none', transition: 'color 150ms ease-out' }} onMouseEnter={(e) => e.target.style.color = DC.grey} onMouseLeave={(e) => e.target.style.color = DC.mute}>{label}</a>
            ))}
            <span style={{ fontFamily: DF.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: DC.mute }}>© 2026 Showgaze</span>
          </div>
        </div>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<NewsletterPage />);
