// Reader magnet signup — Moonlit Thirst on a Kindle-style e-reader
// Submits directly to MailerLite's JSONP endpoint.
const ML_ACCOUNT_ID = '666415';
const ML_FORM_ID = '185570482125277119';

const NikkiSignup = () => {
  const [email, setEmail] = React.useState('');
  const [name, setName] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [err, setErr] = React.useState('');

  const submit = (e) => {
    e.preventDefault();
    setErr('');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setErr('Please enter a valid email address.');
      return;
    }
    setStatus('sending');

    // MailerLite uses a JSONP-style submission so we can POST cross-origin
    // without CORS. Build a hidden form, target a hidden iframe, submit.
    const form = document.createElement('form');
    form.action = `https://assets.mailerlite.com/jsonp/${ML_ACCOUNT_ID}/forms/${ML_FORM_ID}/subscribe`;
    form.method = 'POST';
    form.target = 'ml-hidden-iframe';
    form.style.display = 'none';

    const addField = (n, v) => {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = n;
      input.value = v;
      form.appendChild(input);
    };
    addField('fields[email]', email);
    if (name) addField('fields[name]', name);
    addField('ml-submit', '1');
    addField('anticsrf', 'true');

    let iframe = document.getElementById('ml-hidden-iframe');
    if (!iframe) {
      iframe = document.createElement('iframe');
      iframe.name = 'ml-hidden-iframe';
      iframe.id = 'ml-hidden-iframe';
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
    }

    document.body.appendChild(form);
    form.submit();
    setTimeout(() => {
      setStatus('success');
      document.body.removeChild(form);
    }, 1200);
  };

  return (
    <section className="nr-signup" id="freebook" data-screen-label="Free book signup">
      <div className="nr-signup-inner">
        {/* Ebook on e-reader — provided art */}
        <div className="nr-signup-art" aria-hidden="true">
          <img
            className="nr-ereader-art"
            src="assets/moonlit-thirst-ecover.png"
            alt=""
          />
          <div className="nr-rose" />
        </div>

        <div className="nr-signup-copy">
          <span className="nr-eyebrow">A gift, for the initiated</span>
          <h2 className="nr-section-head">
            <em>Moonlit Thirst</em> —<br/>
            ebook, yours free.
          </h2>
          <p className="nr-signup-lede">
            Book one of the Midnight Riders. Join her group and the full novel lands in
            your inbox &mdash; plus first looks at new releases, cover reveals, and rare
            words from the desk.
          </p>

          {status !== 'success' ? (
            <form className="nr-form" onSubmit={submit} noValidate>
              <label className="nr-field">
                <span className="nr-field-label">First name</span>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Your name"
                  autoComplete="given-name"
                />
              </label>
              <label className="nr-field">
                <span className="nr-field-label">Email</span>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@domain.com"
                  autoComplete="email"
                  required
                  aria-invalid={!!err}
                />
              </label>
              {err && <div className="nr-form-err" role="alert">{err}</div>}
              <button
                type="submit"
                className="nr-btn nr-btn-primary nr-btn-block"
                disabled={status === 'sending'}
              >
                {status === 'sending' ? 'Summoning…' : 'Send me the book'}
              </button>
              <p className="nr-form-fine">
                No spam. Unsubscribe any time.
              </p>
            </form>
          ) : (
            <div className="nr-form-success" role="status">
              <div className="nr-success-seal" aria-hidden="true">
                <svg width="40" height="40" viewBox="0 0 40 40">
                  <circle cx="20" cy="20" r="18" fill="none" stroke="currentColor" strokeWidth="1"/>
                  <path d="M13 20l5 5 9-11" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h3>Welcome to the group.</h3>
              <p>
                Check <strong>{email}</strong> for a confirmation. Your copy of
                <em> Moonlit Thirst</em> arrives shortly after.
              </p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

window.NikkiSignup = NikkiSignup;
