// BOOK A DEMO PAGE - /demo
// Form-centric, minimal copy. Reuses the homepage CTA copy as the headline.
//
// SUBMISSION HANDLING
// ───────────────────
// 1. If DEMO_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 DEMO_FORM_ENDPOINT below
//
// On submission, the form is replaced with an inline thank-you message.

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

const { EdCtx: DemoCtx, EdTag: DemoTag, EdBtn: DemoBtn, EdChrome: DemoChrome,
        useIsMobile: demoUseIsMobile } = window;

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

function DemoLabel({ htmlFor, children, required }) {
  const ED = React.useContext(DemoCtx);
  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 DemoField({ id, label, type = 'text', required, autoComplete, placeholder, value, onChange }) {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <DemoLabel htmlFor={id} required={required}>{label}</DemoLabel>
      <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 DemoSelect({ id, label, required, value, onChange, options }) {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <DemoLabel htmlFor={id} required={required}>{label}</DemoLabel>
      <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 DemoTextarea({ id, label, placeholder, value, onChange, rows = 5 }) {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <DemoLabel htmlFor={id}>{label}</DemoLabel>
      <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 DemoThankYou() {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const isMobile = demoUseIsMobile();
  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 - we&rsquo;ll be in touch.
      </h2>
      <p style={{ ...edText.sans, fontSize: isMobile ? 18 : 19, lineHeight: 1.6, color: ED.ink, margin: '16px auto 0', maxWidth: 540 }}>
        Your request has reached James and the team. We&rsquo;ll come back to you within one working day to schedule a 30-minute walkthrough.
      </p>
      <div style={{ marginTop: 32 }}>
        <DemoBtn kind="ghost" href="/">Back to home</DemoBtn>
      </div>
    </div>
  );
}

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

function DemoForm() {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const isMobile = demoUseIsMobile();

  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 (DEMO_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', `Demo request - ${name}${company ? ' (' + company + ')' : ''}`);
        const r = await fetch(DEMO_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 = `Demo request - ${name}${company ? ' (' + company + ')' : ''}`;
      const lines = [
        `Name: ${name}`,
        `Work email: ${email}`,
        `Company: ${company || '-'}`,
        `Phone: ${phone || '-'}`,
        `Business type: ${businessType || '-'}`,
        '',
        'Notes:',
        notes || '-',
      ].join('\n');
      const url = `mailto:${DEMO_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 <DemoThankYou />;

  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 }}>
        <DemoField
          id="name"
          label="Full name"
          required
          autoComplete="name"
          placeholder="Your name"
          value={name}
          onChange={setName}
        />
        <DemoField
          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 }}>
        <DemoField
          id="company"
          label="Company name"
          autoComplete="organization"
          placeholder="Optional"
          value={company}
          onChange={setCompany}
        />
        <DemoField
          id="phone"
          label="Phone"
          type="tel"
          autoComplete="tel"
          placeholder="Optional"
          value={phone}
          onChange={setPhone}
        />
      </div>

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

      <DemoTextarea
        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 schedule your demo and stay in touch.
          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…' : <>Request a demo <span aria-hidden="true">→</span></>}
        </button>
      </div>
    </form>
  );
}

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

function DemoBody() {
  const ED = React.useContext(DemoCtx);
  const edText = ED.text;
  const isMobile = demoUseIsMobile();
  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' }}>
            See what <span style={{ ...edText.displayBold, color: ED.red, fontStyle: 'normal' }}>real ownership</span> looks like.
          </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 }}>
            Book a 30-minute walkthrough. We&rsquo;ll show you the platform with a real scheme - quoting, binding, document generation, distribution, bordereaux - and the ProductWriter integration that makes the products you build yours.
          </p>
        </div>
        <DemoForm />
      </div>
    </section>
  );
}

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

function DemoSite({ accent, fontMode = 'serif' }) {
  return (
    <DemoChrome accent={accent} fontMode={fontMode} current="/demo">
      <DemoBody />
    </DemoChrome>
  );
}

Object.assign(window, { DemoSite });
