// ui_kits/website/NewsletterBar.jsx
// Slim newsletter signup bar on the homepage, between the category strip and
// "Últimas historias". Posts to window.NEWSLETTER_ENDPOINT — the same backend
// as <Newsletter/>, which also upserts each signup into Brevo.

const barStyles = {
  wrap: { background: 'var(--brand-leaf)', borderBottom: '1px solid var(--color-divider)' },
  inner: {
    maxWidth: 1200, margin: '0 auto', padding: '22px 32px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    gap: 24, flexWrap: 'wrap',
  },
  lead: { display: 'flex', alignItems: 'center', gap: 20, minWidth: 0, flex: '1 1 600px' },
  cover: {
    width: 104, height: 'auto', flexShrink: 0, borderRadius: 10, display: 'block',
    boxShadow: '0 6px 18px rgba(0,0,0,0.28)', border: '2px solid rgba(255,255,255,0.9)',
  },
  copy: { display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0 },
  title: { fontFamily: 'var(--font-serif)', color: '#fff', fontSize: 22, lineHeight: 1.15, margin: 0 },
  sub:   { fontFamily: 'var(--font-sans)', color: 'rgba(255,255,255,0.82)', fontSize: 14, margin: 0 },
  form:  { display: 'flex', gap: 8, flex: '0 1 460px' },
  input: {
    flex: 1, minWidth: 0, padding: '12px 16px',
    fontFamily: 'var(--font-sans)', fontSize: 15,
    border: '1px solid rgba(255,255,255,0.35)', borderRadius: 10,
    background: '#fff', color: 'var(--color-fg)', outline: 'none',
  },
  success: {
    fontFamily: 'var(--font-sans)', color: '#fff', fontSize: 15,
    background: 'rgba(255,255,255,0.14)', padding: '10px 16px', borderRadius: 10,
  },
  error: { fontFamily: 'var(--font-sans)', fontSize: 13, color: '#FFD9D2', marginTop: 6 },
};

function NewsletterBar() {
  const tr = useT();
  const lang = React.useContext(LangContext);
  const isMobile = useIsMobile();
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    setErrorMsg('');
    setSubmitting(true);

    const endpoint = window.NEWSLETTER_ENDPOINT;
    if (!endpoint) { setSent(true); setSubmitting(false); return; }

    try {
      // FormData keeps this a "simple" CORS request (no preflight) for the
      // Apps Script backend — same contract as <Newsletter/>.
      const fd = new FormData();
      fd.append('email', email);
      fd.append('language', lang || 'es');
      fd.append('source', 'website-newsletter-bar');
      fd.append('userAgent', navigator.userAgent || '');

      const res = await fetch(endpoint, { method: 'POST', body: fd });
      const data = await res.json().catch(() => ({ ok: res.ok }));

      if (data.ok) {
        setSent(true);
      } else {
        setErrorMsg(data.error === 'invalid_email'
          ? (lang === 'en' ? 'Please enter a valid email address.' : 'Por favor introduce un correo válido.')
          : (lang === 'en' ? 'Something went wrong. Please try again.' : 'Algo salió mal. Inténtalo de nuevo.'));
      }
    } catch (err) {
      console.warn('[newsletter-bar] submit failed:', err);
      setErrorMsg(lang === 'en' ? 'Network error. Please try again.' : 'Error de conexión. Inténtalo de nuevo.');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div style={barStyles.wrap}>
      <div style={{ ...barStyles.inner, ...(isMobile ? { flexDirection: 'column', alignItems: 'stretch', textAlign: 'center', padding: '20px', gap: 14 } : {}) }}>
        <div style={{ ...barStyles.lead, ...(isMobile ? { flexDirection: 'column', alignItems: 'center', gap: 14 } : {}) }}>
          <img
            src="/assets/guide-cover.jpg"
            alt={tr('news.bar.title')}
            style={{ ...barStyles.cover, ...(isMobile ? { width: 128 } : {}) }}
          />
          <div style={{ ...barStyles.copy, ...(isMobile ? { alignItems: 'center' } : {}) }}>
            <p style={barStyles.title}>{tr('news.bar.title')}</p>
            <p style={barStyles.sub}>{tr('news.bar.sub')}</p>
          </div>
        </div>

        {sent ? (
          <div style={barStyles.success}>{tr('news.success')}</div>
        ) : (
          <div style={{ flex: isMobile ? 'none' : '0 1 420px' }}>
            <form style={{ ...barStyles.form, ...(isMobile ? { flexDirection: 'column' } : {}) }} onSubmit={handleSubmit}>
              <input
                type="email" placeholder={tr('news.placeholder')}
                value={email} onChange={(e) => setEmail(e.target.value)}
                style={barStyles.input} required disabled={submitting}
                aria-label={tr('news.bar.title')}
              />
              <button className="btn btn--secondary" type="submit" disabled={submitting} style={{ whiteSpace: 'nowrap' }}>
                {submitting ? (lang === 'en' ? 'Sending…' : 'Enviando…') : tr('news.submit')}
              </button>
            </form>
            {errorMsg && <div style={barStyles.error}>{errorMsg}</div>}
          </div>
        )}
      </div>
    </div>
  );
}

window.NewsletterBar = NewsletterBar;
