/* global React, AylaRouter, AYLA_WAITLIST, AYLA_GUIDE_API */
const { useState, useMemo, useEffect, useRef } = React;

const GOAL_OPTIONS = [
  ['cycle', 'Cycle awareness'],
  ['sleep', 'Sleep'],
  ['energy', 'Energy'],
  ['mood', 'Mood'],
  ['nutrition', 'Nutrition'],
  ['symptoms', 'Hormonal symptoms'],
  ['fertility', 'Fertility'],
];

const isValidEmail = (e) =>
  /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test((e || '').trim());

function recommendChapter(goals) {
  if (goals.has('symptoms')) return { title: 'The symptom decoder', why: 'Translates the small, daily things into the larger picture they are part of.' };
  if (goals.has('sleep')) return { title: 'Phase by phase', why: 'Begin with the luteal phase, where sleep changes the most.' };
  if (goals.has('nutrition')) return { title: 'Food, simplified', why: 'A plate diagram and five swaps. No meal plans, no rules.' };
  if (goals.has('energy')) return { title: 'Movement by phase', why: 'When to push, when to pull back. One page, four weeks.' };
  if (goals.has('fertility')) return { title: 'A clean glossary', why: 'Testosterone, SHBG, DHEAS, and the androgen picture. In plain English.' };
  if (goals.has('mood')) return { title: 'The symptom decoder', why: 'Begin with the row about Wednesdays. It tends to land.' };
  return { title: 'A letter to begin with', why: 'A short opening note. The rest follows.' };
}

function apiErrorMessage(status, data) {
  if (data?.error) return data.error;
  if (status === 403) return 'Verification failed. Please try again.';
  if (status === 429) return 'Too many requests. Please wait a little and try again.';
  if (status === 502) return 'We could not send the email. Please try again.';
  return 'Something went wrong. Please try again.';
}

function GuideSignupForm({
  setRoute,
  onSuccess,
  showGoals = true,
  submitLabel = 'Get the Cycle Guide',
  idPrefix = 'gf',
}) {
  const cfg = window.AYLA_GUIDE_API || {};
  const turnstileSiteKey = cfg.turnstileSiteKey || '';
  const turnstileRef = useRef(null);
  const turnstileWidgetId = useRef(null);

  const [email, setEmail] = useState('');
  const [emailTouched, setEmailTouched] = useState(false);
  const [consent, setConsent] = useState(false);
  const [goals, setGoals] = useState(new Set());
  const [honeypot, setHoneypot] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [consentTouched, setConsentTouched] = useState(false);
  const [status, setStatus] = useState('');

  const emailValid = useMemo(() => isValidEmail(email), [email]);
  const emailError = emailTouched && email.length > 0 && !emailValid
    ? 'That email looks off — check the @ and the dot.' : '';
  const consentError = consentTouched && !consent
    ? 'Please agree to join the waitlist to receive the Cycle Guide.' : '';

  useEffect(() => {
    if (!turnstileSiteKey || !turnstileRef.current) return undefined;

    const renderWidget = () => {
      if (!window.turnstile || !turnstileRef.current || turnstileWidgetId.current) return;
      turnstileWidgetId.current = window.turnstile.render(turnstileRef.current, {
        sitekey: turnstileSiteKey,
        theme: 'light',
      });
    };

    if (window.turnstile) {
      renderWidget();
    } else {
      const timer = window.setInterval(() => {
        if (window.turnstile) {
          window.clearInterval(timer);
          renderWidget();
        }
      }, 100);
      return () => window.clearInterval(timer);
    }

    return () => {
      if (turnstileWidgetId.current && window.turnstile) {
        window.turnstile.remove(turnstileWidgetId.current);
        turnstileWidgetId.current = null;
      }
    };
  }, [turnstileSiteKey]);

  const resetTurnstile = () => {
    if (turnstileWidgetId.current && window.turnstile) {
      window.turnstile.reset(turnstileWidgetId.current);
    }
  };

  const toggleGoal = (g) => {
    const n = new Set(goals);
    n.has(g) ? n.delete(g) : n.add(g);
    setGoals(n);
  };

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    setEmailTouched(true);
    setConsentTouched(true);
    setStatus('');
    if (!emailValid || !consent || submitting) return;

    const turnstileToken =
      turnstileWidgetId.current && window.turnstile
        ? window.turnstile.getResponse(turnstileWidgetId.current) || ''
        : '';

    if (turnstileSiteKey && !turnstileToken) {
      setStatus('Please complete the verification below.');
      return;
    }

    setSubmitting(true);

    const endpoint = cfg.endpoint || '/api/guide-signup';

    try {
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(),
          goals: Array.from(goals),
          consent: true,
          turnstileToken,
          website: honeypot,
        }),
      });

      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data.ok) {
        setStatus(apiErrorMessage(response.status, data));
        resetTurnstile();
        setSubmitting(false);
        return;
      }

      let welcomeNote = '';
      if (window.claude && window.claude.complete) {
        try {
          const goalLabels = Array.from(goals)
            .map((id) => (GOAL_OPTIONS.find(([g]) => g === id) || [, ''])[1])
            .filter(Boolean);
          const prompt = `Write one short, calm, literary sentence (max 20 words) acknowledging a new reader has just signed up for the Ayla Cycle Guide by email. Tone: quiet, warm, never marketing. No exclamation marks, no emoji.
${goalLabels.length ? `They told us they want help with: ${goalLabels.join(', ')}.` : ''}
Reply with ONLY the sentence — no quotes, no preface.`;
          const text = await window.claude.complete(prompt);
          welcomeNote = (text || '').trim().replace(/^["']|["']$/g, '');
        } catch (_) {}
      }

      setSubmitting(false);
      onSuccess({
        email: email.trim(),
        duplicate: false,
        recommended: recommendChapter(goals),
        welcomeNote,
      });
    } catch (_) {
      setStatus('Could not reach the server. Check your connection and try again.');
      resetTurnstile();
      setSubmitting(false);
    }
  };

  return (
    <form className="gf-form" onSubmit={handleSubmit} noValidate>
      <input
        type="text"
        name="website"
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
        style={{ position: 'absolute', left: '-9999px', opacity: 0, height: 0, width: 0 }}
        value={honeypot}
        onChange={(ev) => setHoneypot(ev.target.value)}
      />

      <div className="gf-field">
        <label htmlFor={idPrefix + '-email'}>Your email</label>
        <input
          id={idPrefix + '-email'}
          type="email"
          placeholder="you@yours.com"
          value={email}
          onChange={(ev) => setEmail(ev.target.value)}
          onBlur={() => setEmailTouched(true)}
          autoComplete="email"
          required
          aria-invalid={emailError ? 'true' : 'false'}
          className={emailError ? 'gf-input err' : 'gf-input'}
        />
        {emailError && <span className="gf-err">{emailError}</span>}
      </div>

      {showGoals && (
        <div className="gf-field">
          <label>
            What do you most want help with?
            <span className="gf-optional">optional · pick any</span>
          </label>
          <div className="gf-chips">
            {GOAL_OPTIONS.map(([id, label]) => (
              <button
                type="button"
                key={id}
                className={'gf-chip' + (goals.has(id) ? ' on' : '')}
                onClick={() => toggleGoal(id)}
                aria-pressed={goals.has(id)}
              >{label}</button>
            ))}
          </div>
        </div>
      )}

      <div className="gf-field gf-field-consent">
        <label className={'gf-consent' + (consentError ? ' gf-consent-err' : '')}>
          <input
            type="checkbox"
            checked={consent}
            onChange={(ev) => setConsent(ev.target.checked)}
            onBlur={() => setConsentTouched(true)}
            required
          />
          <span className="gf-consent-text">{AYLA_WAITLIST.CONSENT_TEXT}</span>
        </label>
        {consentError && <span className="gf-err">{consentError}</span>}
      </div>

      {turnstileSiteKey && (
        <div className="gf-field gf-turnstile">
          <div ref={turnstileRef} id={idPrefix + '-turnstile'} />
        </div>
      )}

      {status && <p className="gf-status" role="alert">{status}</p>}

      <button
        type="submit"
        className="btn gf-submit"
        disabled={!emailValid || !consent || submitting}
      >
        {submitting ? 'Sending…' : <>{submitLabel} <span className="arr">→</span></>}
      </button>

      <p className="gf-fine">{AYLA_WAITLIST.FINE_PRINT}</p>
    </form>
  );
}

function GuideSignupSuccess() {
  return (
    <div className="gf-thanks">
      <h2>Your Cycle Guide is on its way!</h2>
      <p className="gf-fine">We've sent it to the email address you used to join the Ayla waitlist. Please check your inbox, and if you don't see it within a few minutes, be sure to check your spam, junk, or promotions folder.</p>
      <p className="gf-fine"> If you can't find the email, reach out to us at <a href="mailto:contact@ayla-wellness.com">contact@ayla-wellness.com</a> and we'll help get it to you.</p>
    </div>
  );
}

Object.assign(window, { GuideSignupForm, GuideSignupSuccess, GOAL_OPTIONS });
