/* Subscribe.jsx — quiet editorial sign-up for book news and talk dates.
   Submits to a Google Form (responses land in the linked Google Sheet) and
   keeps a local copy so the confirmation state persists on reload. */

const STL_SUB_KEY = 'stl-subscribe';

/* Google Form integration.
   GFORM_ACTION is the form's /formResponse endpoint (same URL as the public
   form, with "viewform" → "formResponse"). The entry.XXXXXXXXX field IDs come
   from the form's ⋮ menu → "Get pre-filled link". */
const GFORM_ACTION =
  'https://docs.google.com/forms/d/e/1FAIpQLSe12Io_ObWTMGNdZQDWwZvmi-U7wq8G8xQtOHSTurv7il1Cyw/formResponse';
const GFORM_FIELDS = {
  name: 'entry.953845504',
  email: 'entry.742023032',
  country: 'entry.594625785',
  institution: 'entry.1650360449',
  comments: 'entry.2053267878',
};

function Subscribe() {
  const { t } = useI18n();

  const [saved, setSaved] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(STL_SUB_KEY) || 'null'); }
    catch (e) { return null; }
  });

  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [country, setCountry] = React.useState('');
  const [institution, setInstitution] = React.useState('');
  const [comments, setComments] = React.useState('');
  const [error, setError] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  async function onSubmit(e) {
    e.preventDefault();
    const value = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      setError(t('subscribe.errEmail'));
      return;
    }
    const entry = {
      name: name.trim(),
      email: value,
      country: country.trim(),
      institution: institution.trim(),
      comments: comments.trim(),
      ts: new Date().toISOString(),
    };
    setSubmitting(true);

    // Post to the Google Form. Google doesn't send CORS headers, so we submit
    // with mode:'no-cors' — the request goes through and the row lands in the
    // Sheet, but the response is opaque (we can't read success/failure). A
    // resolved fetch is treated as success; a thrown error means the network
    // failed, in which case we still confirm and keep the entry locally.
    const body = new URLSearchParams();
    body.append(GFORM_FIELDS.name, entry.name);
    body.append(GFORM_FIELDS.email, entry.email);
    body.append(GFORM_FIELDS.country, entry.country);
    body.append(GFORM_FIELDS.institution, entry.institution);
    body.append(GFORM_FIELDS.comments, entry.comments);
    try {
      await fetch(GFORM_ACTION, { method: 'POST', mode: 'no-cors', body });
    } catch (err) {
      console.warn('[subscribe] could not reach Google Form — stored locally instead:', err);
    }

    try { localStorage.setItem(STL_SUB_KEY, JSON.stringify(entry)); } catch (err) {}
    setSubmitting(false);
    setSaved(entry);
  }

  function reset() {
    try { localStorage.removeItem(STL_SUB_KEY); } catch (err) {}
    setSaved(null);
    setName(''); setEmail(''); setCountry(''); setInstitution(''); setComments('');
    setError('');
  }

  return (
    <section className="section subscribe" id="subscribe">
      <div className="container subscribe-grid">
        <div className="subscribe-intro">
          <SectionMark thai={t('subscribe.markThai')} en={t('subscribe.markEn')} />
          <h2>{t('subscribe.heading')}</h2>
          <p className="subscribe-lede">{rich(t('subscribe.lede'))}</p>
          <p className="subscribe-fineprint">{t('subscribe.fineprint')}</p>
        </div>

        <div className="subscribe-panel">
          {saved ? (
            <div className="subscribe-done" role="status" aria-live="polite">
              <span className="subscribe-done-thread" aria-hidden="true"></span>
              <div className="subscribe-done-eyebrow">{t('subscribe.doneEyebrow')}</div>
              <p className="subscribe-done-msg">
                {rich(t('subscribe.doneMsg'))}
              </p>
              <p className="subscribe-done-email">{saved.email}</p>
              <button type="button" className="subscribe-reset" onClick={reset}>
                {t('subscribe.useDifferent')} <span className="arrow">→</span>
              </button>
            </div>
          ) : (
            <form className="subscribe-form" onSubmit={onSubmit} noValidate>
              <div className="field">
                <label htmlFor="sub-name">{t('subscribe.nameLabel')}</label>
                <input
                  id="sub-name"
                  type="text"
                  autoComplete="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={t('subscribe.namePlaceholder')}
                />
              </div>

              <div className="field">
                <label htmlFor="sub-email">{t('subscribe.emailLabel')}</label>
                <input
                  id="sub-email"
                  type="email"
                  inputMode="email"
                  autoComplete="email"
                  required
                  aria-invalid={error ? 'true' : 'false'}
                  className={error ? 'has-error' : ''}
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); if (error) setError(''); }}
                  placeholder={t('subscribe.emailPlaceholder')}
                />
                {error ? <span className="field-error">{error}</span> : null}
              </div>

              <div className="field">
                <label htmlFor="sub-country">{t('subscribe.countryLabel')}</label>
                <input
                  id="sub-country"
                  type="text"
                  autoComplete="country-name"
                  value={country}
                  onChange={(e) => setCountry(e.target.value)}
                  placeholder={t('subscribe.countryPlaceholder')}
                />
              </div>

              <div className="field">
                <label htmlFor="sub-institution">{t('subscribe.institutionLabel')}</label>
                <input
                  id="sub-institution"
                  type="text"
                  autoComplete="organization"
                  value={institution}
                  onChange={(e) => setInstitution(e.target.value)}
                  placeholder={t('subscribe.institutionPlaceholder')}
                />
              </div>

              <div className="field">
                <label htmlFor="sub-comments">{t('subscribe.commentsLabel')}</label>
                <textarea
                  id="sub-comments"
                  rows={3}
                  value={comments}
                  onChange={(e) => setComments(e.target.value)}
                  placeholder={t('subscribe.commentsPlaceholder')}
                ></textarea>
              </div>

              <button type="submit" className="btn accent subscribe-submit" disabled={submitting}>
                {submitting ? t('subscribe.submitting') : t('subscribe.submit')} <span className="arrow">→</span>
              </button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

window.Subscribe = Subscribe;
