// Multi-step opt-in form for Estimado beta launch list.
// Flow: first/last name -> phone -> email -> company -> redirect.
//
// Webhook firing:
//   After phone: wait 3 minutes, then POST name + phone if the visitor stops there.
//   After email: cancel the phone-only timer, wait 3 minutes, then POST name + phone + email.
//   After company: cancel pending timers and POST the complete lead immediately.
//   Then redirect -> confirmation.html?name=<first>&event_id=<event_id>

const TRADES = [
  'Roofing',
  'Painting',
  'General contractor',
  'Remodeling / Renovation',
  'Flooring',
  'HVAC',
  'Electrical',
  'Plumbing',
  'Concrete / Masonry',
  'Landscaping',
  'Drywall',
  'Other',
];

// US phone formatter: keeps only digits, formats as (XXX) XXX-XXXX as the user types.
function formatUSPhone(value) {
  const d = (value || '').replace(/\D/g, '').slice(0, 10);
  if (d.length === 0) return '';
  if (d.length < 4)   return `(${d}`;
  if (d.length < 7)   return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
}

function OptInForm({ compact = false }) {
  const [step, setStep] = React.useState(0);
  const [first, setFirst] = React.useState('');
  const [last, setLast]   = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [busy, setBusy]   = React.useState(false);

  const inputRef = React.useRef(null);
  const leadTimerRef = React.useRef(null);
  React.useEffect(() => {
    // Auto-focus first input on each step (except the first, to avoid mobile keyboard popping on load)
    if (step > 0) setTimeout(() => inputRef.current?.focus?.(), 80);
  }, [step]);
  React.useEffect(() => () => clearPendingLead(), []);

  const nameOk    = first.trim().length >= 1 && last.trim().length >= 1;
  const emailOk   = /.+@.+\..+/.test(email.trim());
  const phoneDigits = phone.replace(/[^0-9]/g, '');
  const phoneOk   = phoneDigits.length === 10;
  const companyOk = company.trim().length > 0;

  function leadPayload(extra = {}) {
    return {
      firstName: first.trim(),
      lastName:  last.trim(),
      name:      `${first.trim()} ${last.trim()}`.trim(),
      phone:     phoneDigits,
      ...extra,
    };
  }

  function clearPendingLead() {
    if (leadTimerRef.current) {
      clearTimeout(leadTimerRef.current);
      leadTimerRef.current = null;
    }
  }

  function scheduleLead(extra) {
    clearPendingLead();
    leadTimerRef.current = setTimeout(() => {
      window.postLead(leadPayload(extra));
      leadTimerRef.current = null;
    }, 180000);
  }

  function next() {
    if (busy) return;
    if (step === 0 && !nameOk)    return;
    if (step === 1 && !phoneOk)   return;
    if (step === 2 && !emailOk)   return;
    if (step === 3 && !companyOk) return;

    if (step === 1) {
      scheduleLead({ stage: 'with_phone' });
    }

    if (step === 2) {
      scheduleLead({ email: email.trim(), stage: 'with_email' });
    }

    if (step === 3) {
      setBusy(true);
      clearPendingLead();
      window.postLead(leadPayload({
        email:     email.trim(),
        company:   company.trim(),
        stage:     'complete',
      }));
      setTimeout(() => {
        const url = new URL('confirmation.html', window.location.href);
        url.searchParams.set('name', first.trim());
        const eventId = sessionStorage.getItem('estimado_event_id');
        if (eventId) url.searchParams.set('event_id', eventId);
        window.location.href = url.toString();
      }, 650);
      return;
    }
    setStep((s) => s + 1);
  }

  function back() {
    if (busy) return;
    if (step > 0) setStep((s) => s - 1);
  }

  const STEPS = [
    { label: "Join The Waitlist Now", caption: "We launch July 1 — you get a 7-day free trial." },
    { label: "What's your phone?" },
    { label: "What's your email?" },
    { label: "What does your company do?" },
  ];

  const cur = STEPS[step];
  const totalSteps = STEPS.length;
  const PAD_Y = compact ? 14 : 16;
  const PAD_X = compact ? 14 : 16;
  const FS    = 16;        // ≥16px so iOS doesn't zoom on focus

  const inp = {
    width: '100%',
    padding: `${PAD_Y}px ${PAD_X}px`,
    background: '#fff',
    color: C.ink,
    border: `1px solid ${C.rule}`,
    borderRadius: 12,
    fontFamily: F.ui, fontSize: FS, outline: 'none',
    boxSizing: 'border-box',
    transition: 'border-color 0.15s ease, box-shadow 0.15s ease',
    WebkitAppearance: 'none',
  };
  const inpFocus = (e) => {
    e.currentTarget.style.borderColor = C.ink;
    e.currentTarget.style.boxShadow = `0 0 0 3px rgba(21,20,15,0.08)`;
  };
  const inpBlur = (e) => {
    e.currentTarget.style.borderColor = C.rule;
    e.currentTarget.style.boxShadow = 'none';
  };

  function fieldFor(idx) {
    if (idx === 0) {
      return (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <input ref={inputRef} type="text" value={first}
            onChange={(e) => setFirst(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
            placeholder="First name" autoComplete="given-name"
            style={inp} onFocus={inpFocus} onBlur={inpBlur} />
          <input type="text" value={last}
            onChange={(e) => setLast(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
            placeholder="Last name" autoComplete="family-name"
            style={inp} onFocus={inpFocus} onBlur={inpBlur} />
        </div>
      );
    }
    if (idx === 1) {
      return (
        <div style={{
          display: 'grid',
          gridTemplateColumns: '74px 1fr',
          alignItems: 'stretch',
          gap: 8,
        }}>
          <div aria-label="United States country code" style={{
            ...inp,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 6,
            paddingLeft: 10,
            paddingRight: 10,
            fontWeight: 500,
          }}>
            <span aria-hidden="true">🇺🇸</span>
            <span>+1</span>
          </div>
          <input ref={inputRef} type="tel" value={phone}
            onChange={(e) => setPhone(formatUSPhone(e.target.value))}
            onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
            placeholder="(555) 123-4567" autoComplete="tel"
            inputMode="tel" maxLength={14}
            style={inp} onFocus={inpFocus} onBlur={inpBlur} />
        </div>
      );
    }
    if (idx === 2) {
      return (
        <input ref={inputRef} type="email" value={email}
          onChange={(e) => setEmail(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
          placeholder="you@yourcompany.com" autoComplete="email"
          inputMode="email"
          style={inp} onFocus={inpFocus} onBlur={inpBlur} />
      );
    }
    if (idx === 3) {
      return (
        <input ref={inputRef} type="text" value={company}
          onChange={(e) => setCompany(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
          placeholder="e.g. roofing, painting, GC…" autoComplete="organization"
          style={inp} onFocus={inpFocus} onBlur={inpBlur} />
      );
    }
  }

  const valid = [nameOk, phoneOk, emailOk, companyOk][step];
  const isFinal = step === totalSteps - 1;

  return (
    <div style={{
      width: '100%',
      background: C.paper,
      border: `1px solid ${C.rule}`,
      borderRadius: 16,
      padding: compact ? '14px 14px 14px' : '18px 18px 16px',
      boxSizing: 'border-box',
      boxShadow: '0 1px 0 rgba(21,20,15,0.02), 0 14px 40px -28px rgba(21,20,15,0.18)',
    }}>
      {/* No step counter, no back button — keeps the form feeling short. */}

      {/* Label */}
      <div style={{ marginBottom: compact ? 10 : 12 }}>
        <h2 style={{
          fontFamily: F.display, fontWeight: 420,
          fontSize: compact ? 22 : 24, letterSpacing: '-0.022em',
          margin: cur.caption ? '0 0 4px' : 0, lineHeight: 1.1, color: C.ink,
        }}>{cur.label}</h2>
        {cur.caption && (
          <p style={{
            margin: 0, fontFamily: F.ui, fontSize: 13, lineHeight: 1.4,
            color: C.muted,
          }}>{cur.caption}</p>
        )}
      </div>

      {/* Field */}
      <div style={{ marginBottom: compact ? 10 : 12 }}>
        {fieldFor(step)}
      </div>

      {/* Continue button */}
      <button onClick={next} disabled={!valid || busy} style={{
        width: '100%',
        padding: `${compact ? 14 : 15}px 18px`,
        background: C.ink, color: C.paper,
        border: 'none', borderRadius: 12,
        fontFamily: F.ui, fontWeight: 500, fontSize: 15,
        letterSpacing: '-0.005em',
        cursor: valid && !busy ? 'pointer' : 'not-allowed',
        opacity: valid || busy ? 1 : 0.45,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        transition: 'opacity 0.15s ease, transform 0.12s ease',
      }}
        onMouseDown={(e) => { if (valid && !busy) e.currentTarget.style.transform = 'translateY(1px)'; }}
        onMouseUp={(e)   => e.currentTarget.style.transform = 'translateY(0)'}
        onMouseLeave={(e)=> e.currentTarget.style.transform = 'translateY(0)'}>
        {busy ? 'Securing your spot…' : isFinal ? 'Join the beta list' : 'Continue'}
        {!busy && <Arrow color={C.paper} />}
      </button>
    </div>
  );
}

window.OptInForm = OptInForm;
