// CONTACT PAGE - /contact
// Form-centric. Standard contact form, mirrors the /demo page structure.
//
// SUBMISSION HANDLING
// ───────────────────
// 1. If CONTACT_FORM_ENDPOINT is set (e.g. a Formspree endpoint), the form
//    POSTs there as multipart/form-data. Formspree mails the submission
//    to the address registered on their dashboard.
// 2. If left blank, the form falls back to opening a mailto: link in the
//    user's email client, prefilled with all the field values.
//
// To wire it up properly:
//   1. Sign up at https://formspree.io (free tier handles ~50 submissions/mo)
//   2. Add james.hill@outrun.insure as the destination
//   3. Paste the form endpoint URL into CONTACT_FORM_ENDPOINT below
//
// On submission, the form is replaced with an inline thank-you message.

const CONTACT_FORM_ENDPOINT = 'https://formspree.io/f/mdajpovg'; // ← paste Formspree URL here when ready
const CONTACT_FORM_EMAIL = 'james.hill@outrun.insure';

const { EdCtx: ContactCtx, EdTag: ContactTag, EdBtn: ContactBtn, EdChrome: ContactChrome,
        useIsMobile: contactUseIsMobile } = window;

// ─── input primitives ──────────────────────────────────────────

function ContactLabel({ htmlFor, children, required }) {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  return (
    <label htmlFor={htmlFor} style={{ ...edText.tag, fontSize: 11, color: ED.ink2, display: 'block', marginBottom: 8 }}>
      {children}
      {required && <span style={{ color: ED.red, marginLeft: 4 }}>*</span>}
    </label>
  );
}

function ContactField({ id, label, type = 'text', required, autoComplete, placeholder, value, onChange }) {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <ContactLabel htmlFor={id} required={required}>{label}</ContactLabel>
      <input
        id={id}
        name={id}
        type={type}
        required={required}
        autoComplete={autoComplete}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          ...edText.sans,
          fontSize: 17,
          color: ED.ink,
          padding: '14px 16px',
          borderRadius: 2,
          border: `1px solid ${focused ? ED.ink : ED.rule}`,
          background: ED.bg,
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          transition: 'border-color 120ms ease',
          letterSpacing: '-0.005em',
        }}
      />
    </div>
  );
}

function ContactSelect({ id, label, required, value, onChange, options }) {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <ContactLabel htmlFor={id} required={required}>{label}</ContactLabel>
      <select
        id={id}
        name={id}
        required={required}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          ...edText.sans,
          fontSize: 17,
          color: value ? ED.ink : ED.ink2,
          padding: '14px 16px',
          borderRadius: 2,
          border: `1px solid ${focused ? ED.ink : ED.rule}`,
          background: ED.bg,
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          transition: 'border-color 120ms ease',
          letterSpacing: '-0.005em',
          appearance: 'none',
          backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1l5 5 5-5' stroke='${encodeURIComponent(ED.ink)}' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>")`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'right 18px center',
          paddingRight: 44,
          cursor: 'pointer',
        }}
      >
        <option value="" disabled>Choose one</option>
        {options.map(o => (
          <option key={o} value={o}>{o}</option>
        ))}
      </select>
    </div>
  );
}

function ContactTextarea({ id, label, placeholder, value, onChange, rows = 5 }) {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <ContactLabel htmlFor={id}>{label}</ContactLabel>
      <textarea
        id={id}
        name={id}
        rows={rows}
        placeholder={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          ...edText.sans,
          fontSize: 17,
          color: ED.ink,
          padding: '14px 16px',
          borderRadius: 2,
          border: `1px solid ${focused ? ED.ink : ED.rule}`,
          background: ED.bg,
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          resize: 'vertical',
          transition: 'border-color 120ms ease',
          letterSpacing: '-0.005em',
          fontFamily: 'inherit',
          lineHeight: 1.5,
        }}
      />
    </div>
  );
}

// ─── thank you state ───────────────────────────────────────────

function ContactThankYou() {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const isMobile = contactUseIsMobile();
  return (
    <div style={{ textAlign: 'center', padding: isMobile ? '48px 0 24px' : '64px 0 32px' }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: ED.red, color: ED.inverse,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 28, fontWeight: 700, lineHeight: 1,
      }}>✓</div>
      <h2 style={{ ...edText.display, fontSize: isMobile ? 'clamp(28px, 7.5vw, 34px)' : 44, lineHeight: 1.1, color: ED.ink, margin: '24px 0 0', letterSpacing: '-0.025em' }}>
        Thanks - message received.
      </h2>
      <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 19, lineHeight: 1.6, color: ED.ink, margin: '16px auto 0', maxWidth: 540 }}>
        Your message has reached James and the team. We&rsquo;ll come back to you within one working day.
      </p>
      <div style={{ marginTop: 32 }}>
        <ContactBtn kind="ghost" href="/">Back to home</ContactBtn>
      </div>
    </div>
  );
}

// ─── form ──────────────────────────────────────────────────────

function ContactForm() {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const isMobile = contactUseIsMobile();

  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [businessType, setBusinessType] = React.useState('');
  const [notes, setNotes] = 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('');

    // Honeypot-free for now; just hard validation
    if (!name.trim() || !email.trim()) {
      setError('Name and work email are required.');
      return;
    }

    setSubmitting(true);

    if (CONTACT_FORM_ENDPOINT) {
      try {
        const fd = new FormData();
        fd.append('name', name);
        fd.append('email', email);
        fd.append('company', company);
        fd.append('phone', phone);
        fd.append('businessType', businessType);
        fd.append('notes', notes);
        fd.append('_subject', `Contact form - ${name}${company ? ' (' + company + ')' : ''}`);
        const r = await fetch(CONTACT_FORM_ENDPOINT, {
          method: 'POST',
          headers: { Accept: 'application/json' },
          body: fd,
        });
        if (!r.ok) throw new Error('Submission failed');
        setSubmitted(true);
      } catch (err) {
        setError('Something went wrong. Please try again, or email james.hill@outrun.insure directly.');
        setSubmitting(false);
      }
    } else {
      // Mailto fallback - opens the user's email client pre-filled
      const subject = `Contact form - ${name}${company ? ' (' + company + ')' : ''}`;
      const lines = [
        `Name: ${name}`,
        `Work email: ${email}`,
        `Company: ${company || '-'}`,
        `Phone: ${phone || '-'}`,
        `Business type: ${businessType || '-'}`,
        '',
        'Notes:',
        notes || '-',
      ].join('\n');
      const url = `mailto:${CONTACT_FORM_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(lines)}`;
      window.location.href = url;
      // Small delay so the mailto handoff completes before the form unmounts
      setTimeout(() => setSubmitted(true), 400);
    }
  }

  if (submitted) return <ContactThankYou />;

  return (
    <form
      onSubmit={handleSubmit}
      noValidate
      style={{ display: 'flex', flexDirection: 'column', gap: isMobile ? 20 : 24 }}
    >
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 20 : 20 }}>
        <ContactField
          id="name"
          label="Full name"
          required
          autoComplete="name"
          placeholder="Your name"
          value={name}
          onChange={setName}
        />
        <ContactField
          id="email"
          label="Work email"
          type="email"
          required
          autoComplete="email"
          placeholder="you@company.com"
          value={email}
          onChange={setEmail}
        />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 20 : 20 }}>
        <ContactField
          id="company"
          label="Company name"
          autoComplete="organization"
          placeholder="Optional"
          value={company}
          onChange={setCompany}
        />
        <ContactField
          id="phone"
          label="Phone"
          type="tel"
          autoComplete="tel"
          placeholder="Optional"
          value={phone}
          onChange={setPhone}
        />
      </div>

      <ContactSelect
        id="businessType"
        label="Type of business"
        value={businessType}
        onChange={setBusinessType}
        options={['MGA', 'Schemes broker', 'Both', 'Other']}
      />

      <ContactTextarea
        id="notes"
        label="Anything you&rsquo;d like us to know"
        placeholder="Lines of business, specific schemes, what you'd like to see on the demo, timelines..."
        value={notes}
        onChange={setNotes}
      />

      {error && (
        <div style={{ ...edText.sans, fontSize: 15, color: ED.red, padding: '12px 16px', border: `1px solid ${ED.red}`, borderRadius: 2 }}>
          {error}
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', justifyContent: 'space-between', alignItems: isMobile ? 'stretch' : 'center', gap: isMobile ? 16 : 24, marginTop: 8 }}>
        <p style={{ ...edText.sans, fontSize: 13, lineHeight: 1.5, color: ED.ink2, margin: 0, maxWidth: 420 }}>
          We&rsquo;ll only use these details to reply to your message.
          Required fields are marked <span style={{ color: ED.red }}>*</span>.
        </p>
        <button
          type="submit"
          disabled={submitting}
          style={{
            ...edText.med,
            fontSize: 15,
            letterSpacing: '-0.005em',
            padding: '14px 22px',
            borderRadius: 2,
            border: `1px solid ${ED.ink}`,
            background: submitting ? ED.ink2 : ED.ink,
            color: ED.inverse,
            cursor: submitting ? 'wait' : 'pointer',
            whiteSpace: 'nowrap',
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 10,
            transition: 'background 160ms ease',
          }}
        >
          {submitting ? 'Sending…' : <>Send message <span aria-hidden="true">→</span></>}
        </button>
      </div>
    </form>
  );
}

// ─── hero + form section ───────────────────────────────────────

function ContactBody() {
  const ED = React.useContext(ContactCtx);
  const edText = ED.text;
  const isMobile = contactUseIsMobile();
  return (
    <section style={{ padding: isMobile ? '40px 24px 64px' : '88px 144px 120px', background: ED.bg }}>
      <div style={{ maxWidth: 760, margin: '0 auto' }}>
        <div style={{ textAlign: isMobile ? 'left' : 'center', marginBottom: isMobile ? 32 : 56 }}>
          <h1 style={{ ...edText.display, fontSize: isMobile ? 'clamp(40px, 11vw, 46px)' : 'clamp(56px, 7vw, 88px)', lineHeight: isMobile ? 1.05 : 1.02, color: ED.ink, margin: 0, letterSpacing: '-0.035em' }}>
            Get <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>in touch</span>.
          </h1>
          <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 19, lineHeight: 1.55, color: ED.ink, margin: isMobile ? '20px 0 0' : '28px auto 0', maxWidth: 620 }}>
            Drop us a line. Whether it&rsquo;s a question about the platform, a partnership, or something else - we&rsquo;re happy to talk.
          </p>
        </div>
        <ContactForm />
      </div>
    </section>
  );
}

// ─── root ──────────────────────────────────────────────────────

function ContactSite({ accent, fontMode = 'serif' }) {
  return (
    <ContactChrome accent={accent} fontMode={fontMode} current="/contact">
      <ContactBody />
    </ContactChrome>
  );
}

Object.assign(window, { ContactSite });
