// Email sign-up - insights + product updates.
//
// SUBMISSION HANDLING (mirrors directions/demo.jsx and contact.jsx)
// ─────────────────────────────────────────────────────────────────
// 1. If SIGNUP_FORM_ENDPOINT is set, the form POSTs there as
//    multipart/form-data. Formspree mails the submission to the address
//    registered on their dashboard.
// 2. If left blank, it falls back to a mailto: link prefilled with the values.
//
// To give sign-ups their own Formspree inbox (recommended, so they don't mix
// in with demo requests):
//   1. formspree.io → New Form → name it "Newsletter sign-up"
//   2. Set the destination to hello@outrun.insure
//   3. Paste the new form's endpoint URL into SIGNUP_FORM_ENDPOINT below
// Until then it shares the demo form's endpoint; the `_subject` line
// ("Newsletter sign-up - Name") is what distinguishes them in the inbox.
//
// <SignupBlock layout="band|inline|stacked" tone="light|warm|dark" />

const SIGNUP_FORM_ENDPOINT = 'https://formspree.io/f/myeggnwv';
const SIGNUP_FORM_EMAIL = 'hello@outrun.insure';

function useSignupTone(tone) {
  const ED = React.useContext(EdCtx);
  if (tone === 'dark') return { ...ED, surface: ED.ink, fg: '#FFFFFF', fgMuted: 'rgba(255,255,255,0.62)', line: 'rgba(255,255,255,0.28)', lineStrong: 'rgba(255,255,255,0.75)', field: 'transparent' };
  if (tone === 'warm') return { ...ED, surface: ED.bgWarm, fg: ED.ink, fgMuted: ED.ink2, line: ED.rule, lineStrong: ED.ink, field: 'transparent' };
  return { ...ED, surface: ED.bg, fg: ED.ink, fgMuted: ED.ink2, line: ED.rule, lineStrong: ED.ink, field: 'transparent' };
}

function SignupField({ id, label, type = 'text', value, onChange, autoComplete, placeholder, T, flex }) {
  const edText = T.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', flex: flex || 1, minWidth: 0 }}>
      <label htmlFor={id} style={{ ...edText.tag, fontSize: 10, color: T.fgMuted, marginBottom: 8 }}>{label}</label>
      <input
        id={id}
        name={id}
        type={type}
        value={value}
        placeholder={placeholder}
        autoComplete={autoComplete}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          ...edText.sans, fontSize: 16, color: T.fg, padding: '10px 0 11px',
          border: 'none', borderBottom: `1.5px solid ${focused ? T.lineStrong : T.line}`,
          background: T.field, outline: 'none', width: '100%', boxSizing: 'border-box',
          transition: 'border-color 120ms ease', letterSpacing: '-0.005em', borderRadius: 0,
        }}
      />
    </div>
  );
}

function SignupSubmit({ T, submitting, wide }) {
  const edText = T.text;
  const [hover, setHover] = React.useState(false);
  return (
    <button
      type="submit"
      disabled={submitting}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        ...edText.med, fontSize: 15, letterSpacing: '-0.005em',
        padding: '13px 28px', borderRadius: 2, cursor: submitting ? 'default' : 'pointer',
        border: `1.5px solid ${T.tone === 'dark' ? '#FFFFFF' : T.ink}`,
        background: hover && !submitting ? (T.tone === 'dark' ? '#FFFFFF' : T.ink) : 'transparent',
        color: hover && !submitting ? (T.tone === 'dark' ? T.ink : '#FFFFFF') : T.fg,
        transition: 'background 140ms ease, color 140ms ease',
        whiteSpace: 'nowrap', opacity: submitting ? 0.55 : 1, width: wide ? '100%' : undefined,
      }}
    >
      {submitting ? 'Sending…' : 'Sign up'}
    </button>
  );
}

function SignupPrivacy({ T, align }) {
  const edText = T.text;
  return (
    <p style={{ ...edText.sans, fontSize: 13, lineHeight: 1.5, color: T.fgMuted, margin: 0, maxWidth: 560, textAlign: align }}>
      Monthly insights and product update email. No sharing with third parties, unsubscribe any time. Outrun is committed to protecting your information, which will be used in accordance with our <a href="/privacy" style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: '2px' }}>Privacy Policy</a>.
    </p>
  );
}

function SignupBlock({ layout = 'band', tone = 'light', eyebrow = 'Stay in the loop', headline, blurb, bordered = true, inset = true }) {
  const T = { ...useSignupTone(tone), tone };
  const edText = T.text;
  const isMobile = useIsMobile();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    if (!name.trim() || !email.trim() || !/.+@.+\..+/.test(email)) {
      setError('Please add your first name and a valid email address.');
      return;
    }
    setSubmitting(true);
    if (SIGNUP_FORM_ENDPOINT) {
      try {
        const fd = new FormData();
        fd.append('name', name);
        fd.append('email', email);
        fd.append('formType', 'Newsletter sign-up');
        fd.append('_subject', `Newsletter sign-up - ${name}`);
        const r = await fetch(SIGNUP_FORM_ENDPOINT, { method: 'POST', headers: { Accept: 'application/json' }, body: fd });
        if (!r.ok) throw new Error('failed');
        setSubmitted(true);
      } catch (err) {
        setError('Something went wrong. Please try again, or email ' + SIGNUP_FORM_EMAIL + ' directly.');
        setSubmitting(false);
      }
    } else {
      window.location.href = `mailto:${SIGNUP_FORM_EMAIL}?subject=${encodeURIComponent('Newsletter sign-up - ' + name)}&body=${encodeURIComponent('Name: ' + name + '\nEmail: ' + email)}`;
      setTimeout(() => setSubmitted(true), 400);
    }
  }

  const head = headline || <><span style={{ color: T.red }}>Insights and product updates</span>,<br />straight from the team.</>;
  const body = blurb || 'Monthly update on issues impacting MGAs and Schemes Brokers - plus new features we\u2019ve delivered on the platform.';

  const thanks = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <p style={{ ...edText.display, fontSize: isMobile ? 26 : 32, color: T.fg, margin: 0, letterSpacing: '-0.025em', lineHeight: 1.15 }}>
        Thanks{name ? ', ' + name.trim().split(' ')[0] : ''} <span style={{ color: T.red }}>&mdash;</span> you&rsquo;re on the list.
      </p>
      <p style={{ ...edText.sans, fontSize: 16, lineHeight: 1.55, color: T.fgMuted, margin: 0, maxWidth: 460 }}>
        We&rsquo;ll be in touch soon.
      </p>
    </div>
  );

  const fields = (
    <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: isMobile ? 18 : 20, alignItems: isMobile ? 'stretch' : 'flex-end' }}>
      <SignupField id={`su-name-${layout}`} label="First name" value={name} onChange={setName} autoComplete="given-name" placeholder="Your first name" T={T} flex={0.8} />
      <SignupField id={`su-email-${layout}`} label="Work email" type="email" value={email} onChange={setEmail} autoComplete="email" placeholder="you@company.com" T={T} />
      <SignupSubmit T={T} submitting={submitting} wide={isMobile} />
    </div>
  );

  const errBlock = error ? (
    <p style={{ ...edText.sans, fontSize: 14, color: T.red, margin: 0 }}>{error}</p>
  ) : null;

  // ── inline: one compact hairline row, no headline ────────────
  if (layout === 'inline') {
    return (
      <section style={{ background: T.surface, padding: isMobile ? (inset ? '32px 24px' : '32px 0') : (inset ? '36px 144px' : '36px 0'), borderTop: `1.5px solid ${T.tone === 'dark' ? 'rgba(255,255,255,0.2)' : T.ink}`, borderBottom: `1px solid ${T.line}` }}>
        {submitted ? thanks : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: isMobile ? 18 : 40, alignItems: isMobile ? 'stretch' : 'flex-end' }}>
              <div style={{ flex: '0 0 auto', maxWidth: isMobile ? undefined : 290, paddingBottom: isMobile ? 0 : 6 }}>
                <p style={{ ...edText.sans, fontSize: 16, lineHeight: 1.5, color: T.fg, margin: 0 }}>{body}</p>
              </div>
              <form onSubmit={handleSubmit} noValidate style={{ flex: 1, minWidth: 0 }}>{fields}</form>
            </div>
            {errBlock}
            <SignupPrivacy T={T} />
          </div>
        )}
      </section>
    );
  }

  // ── stacked: centred, headline over form ─────────────────────
  if (layout === 'stacked') {
    return (
      <section style={{ background: T.surface, padding: isMobile ? '56px 24px' : '88px 144px', borderTop: bordered ? `1px solid ${T.line}` : 'none' }}>
        <div style={{ maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: isMobile ? 20 : 24 }}>
          {submitted ? thanks : (
            <React.Fragment>
              <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(28px, 8vw, 36px)' : 52, color: T.fg, margin: 0, letterSpacing: '-0.03em', lineHeight: 1.08 }}>{head}</h2>
              <p style={{ ...edText.sans, fontSize: isMobile ? 17 : 18, lineHeight: 1.55, color: T.fg, margin: 0, maxWidth: 540 }}>{body}</p>
              <form onSubmit={handleSubmit} noValidate style={{ width: '100%', maxWidth: 620, marginTop: 8, display: 'flex', flexDirection: 'column', gap: 16, textAlign: 'left' }}>
                {fields}
                {errBlock}
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 4 }}><SignupPrivacy T={T} align="center" /></div>
              </form>
            </React.Fragment>
          )}
        </div>
      </section>
    );
  }

  // ── band (default): headline left, form right ────────────────
  return (
    <section style={{ background: T.surface, padding: isMobile ? '28px 24px' : '44px 144px', borderTop: bordered ? `1px solid ${T.line}` : 'none' }}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 32 : 80, alignItems: 'start', maxWidth: 1320 }}>
        <div>
          <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(28px, 8vw, 36px)' : 52, color: T.fg, margin: 0, letterSpacing: '-0.03em', lineHeight: 1.08 }}>{head}</h2>
        </div>
        <div style={{ paddingTop: isMobile ? 0 : 8 }}>
          {submitted ? thanks : (
            <React.Fragment>
              <p style={{ ...edText.sans, fontSize: isMobile ? 17 : 18, lineHeight: 1.55, color: T.fg, margin: '0 0 28px' }}>{body}</p>
              <form onSubmit={handleSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {fields}
                {errBlock}
                <SignupPrivacy T={T} />
              </form>
            </React.Fragment>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SignupBlock, SignupField, SignupSubmit, SignupPrivacy, SIGNUP_FORM_ENDPOINT });
