// Quote request form — the conversion endpoint for "Get a Free Quote".
// Short by design (Name, Phone, Zip, Address, What's going on) with inline
// validation, a loading state, and a success state that nudges urgent callers
// back to the phone.

const QuoteForm = ({ accent }) => {
  const SERVICE_OPTIONS = ['Repair', 'New Install', 'Opener', 'Commercial', 'Other'];

  const [form, setForm] = React.useState({
    name: '', phone: '', zip: '', address: '', service: '', message: '',
  });
  const [errors, setErrors] = React.useState({});
  const [touched, setTouched] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | submitting | success | error

  const validate = (f) => {
    const e = {};
    if (!f.name.trim()) e.name = 'Please enter your name.';
    const digits = f.phone.replace(/\D/g, '');
    if (!digits) e.phone = 'Please enter your phone number.';
    else if (digits.length < 10) e.phone = 'That phone number looks too short.';
    if (!f.zip.trim()) e.zip = 'Please enter your ZIP code.';
    else if (!/^\d{5}$/.test(f.zip.trim())) e.zip = 'Enter a 5-digit ZIP.';
    return e;
  };

  const update = (key, val) => {
    const next = { ...form, [key]: val };
    setForm(next);
    if (touched[key]) setErrors(validate(next));
  };

  const blur = (key) => {
    setTouched({ ...touched, [key]: true });
    setErrors(validate(form));
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate(form);
    setErrors(e);
    setTouched({ name: true, phone: true, zip: true });
    if (Object.keys(e).length > 0) {
      // focus first invalid
      const first = ['name', 'phone', 'zip'].find(k => e[k]);
      const el = document.getElementById('qf-' + first);
      if (el) el.focus();
      return;
    }
    setStatus('submitting');
    // Send to inbox via FormSubmit (no backend required). On the first real
    // submission from the live site, FormSubmit emails a one-time activation
    // link to apexindustriesohd@gmail.com — click it once and all future
    // submissions arrive automatically.
    const QUOTE_EMAIL = 'apexindustriesohd@gmail.com';
    const payload = {
      _subject: 'New Quote Request — Apex Overhead Doors',
      _template: 'table',
      _captcha: 'false',
      Name: form.name,
      Phone: form.phone,
      ZIP: form.zip,
      Address: form.address || '—',
      Message: form.message || '—',
    };
    // Send silently in the background. FormSubmit delivers the email
    // server-side, so on success the visitor just sees the success state —
    // no mail client is ever opened. If the request can't get through, we
    // surface an error so they can call instead.
    fetch('https://formsubmit.co/ajax/' + QUOTE_EMAIL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify(payload),
    })
      .then(r => r.json())
      .then(data => {
        // FormSubmit returns { success: "true" } on a delivered message.
        if (data && String(data.success) === 'true') setStatus('success');
        else setStatus('error');
      })
      .catch(() => setStatus('error'));
  };

  const fieldWrap = { display: 'flex', flexDirection: 'column', gap: 7 };
  const labelStyle = { fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,0.85)', letterSpacing: '0.01em' };
  const baseInput = {
    background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.14)',
    borderRadius: 10,
    color: '#fff',
    fontFamily: 'var(--font-body)',
    fontSize: 15,
    padding: '13px 14px',
    width: '100%',
    outline: 'none',
    transition: 'border-color .18s ease, background .18s ease',
  };
  const inputStyle = (key) => ({
    ...baseInput,
    borderColor: errors[key] && touched[key] ? '#e06a6a' : 'rgba(255,255,255,0.14)',
  });
  const errText = (key) => (errors[key] && touched[key]
    ? <span style={{ color: '#ff9a9a', fontSize: 12.5 }}>{errors[key]}</span>
    : null);

  if (status === 'success') {
    return (
      <div style={{
        background: 'rgba(255,255,255,0.025)',
        border: '1px solid rgba(255,255,255,0.1)',
        borderRadius: 16, padding: '48px 36px', textAlign: 'center',
      }}>
        <div style={{
          width: 60, height: 60, borderRadius: 999, margin: '0 auto 22px',
          background: 'rgba(0,72,144,0.18)', color: accent,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="badgeCheck" size={30} />
        </div>
        <h3 style={{ fontSize: 24, fontWeight: 800 }}>Thanks — we'll be in touch.</h3>
        <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: 16, marginTop: 12, maxWidth: 420, marginInline: 'auto', lineHeight: 1.6 }}>
          We've got your request and will call you back within one business day. Need it sorted sooner?
        </p>
        <a href={PHONE_TEL} className="btn btn-primary" style={{ background: accent, marginTop: 22, padding: '14px 24px', fontSize: 16 }}>
          <Icon name="phone" size={16} /> Call {PHONE_DISPLAY}
        </a>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate style={{
      background: 'rgba(255,255,255,0.025)',
      border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: 16, padding: 30,
      display: 'flex', flexDirection: 'column', gap: 18,
    }}>
      <div className="qf-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <label style={fieldWrap}>
          <span style={labelStyle}>Name</span>
          <input id="qf-name" type="text" value={form.name} placeholder="Your name"
                 onChange={e => update('name', e.target.value)} onBlur={() => blur('name')}
                 style={inputStyle('name')} autoComplete="name" />
          {errText('name')}
        </label>
        <label style={fieldWrap}>
          <span style={labelStyle}>Phone</span>
          <input id="qf-phone" type="tel" value={form.phone} placeholder="(406) 555-0123"
                 onChange={e => update('phone', e.target.value)} onBlur={() => blur('phone')}
                 style={inputStyle('phone')} autoComplete="tel" />
          {errText('phone')}
        </label>
      </div>

      <div className="qf-row" style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 16 }}>
        <label style={fieldWrap}>
          <span style={labelStyle}>ZIP code</span>
          <input id="qf-zip" type="text" inputMode="numeric" maxLength={5} value={form.zip} placeholder="59401"
                 onChange={e => update('zip', e.target.value.replace(/[^\d]/g, ''))} onBlur={() => blur('zip')}
                 style={inputStyle('zip')} autoComplete="postal-code" />
          {errText('zip')}
        </label>
        <label style={fieldWrap}>
          <span style={labelStyle}>Address <span style={{ color: 'rgba(255,255,255,0.4)', fontWeight: 400 }}>(optional)</span></span>
          <input id="qf-address" type="text" value={form.address} placeholder="Street address"
                 onChange={e => update('address', e.target.value)}
                 style={baseInput} autoComplete="street-address" />
        </label>
      </div>

      <label style={fieldWrap}>
        <span style={labelStyle}>What's going on?</span>
        <textarea id="qf-message" value={form.message} rows={4}
                  placeholder="Broken spring, won't open, want a new door, quote for a commercial install…"
                  onChange={e => update('message', e.target.value)}
                  style={{ ...baseInput, resize: 'vertical', minHeight: 110, lineHeight: 1.55 }} />
      </label>

      {status === 'error' && (
        <div role="alert" style={{
          display: 'flex', alignItems: 'flex-start', gap: 10,
          background: 'rgba(224,106,106,0.1)', border: '1px solid rgba(224,106,106,0.45)',
          borderRadius: 10, padding: '13px 15px', color: '#f3b0b0', fontSize: 14, lineHeight: 1.55,
        }}>
          <span style={{ paddingTop: 1 }}><Icon name="alertTriangle" size={16} /></span>
          <span>
            Something went wrong sending your request. Please try again, or call us
            directly at <a href={PHONE_TEL} style={{ color: '#fff', fontWeight: 600 }}>{PHONE_DISPLAY}</a>.
          </span>
        </div>
      )}

      <button type="submit" disabled={status === 'submitting'} className="btn btn-primary"
              style={{
                background: accent, padding: '16px 22px', fontSize: 16, justifyContent: 'center',
                marginTop: 4, opacity: status === 'submitting' ? 0.75 : 1,
                cursor: status === 'submitting' ? 'wait' : 'pointer',
              }}>
        {status === 'submitting'
          ? <><Spinner /> Sending…</>
          : <>Request Free Quote <Icon name="arrowRight" size={16} className="arrow" /></>}
      </button>

      <p style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.5)', textAlign: 'center', lineHeight: 1.5 }}>
        Free estimates · No obligation · We'll never share your info.
      </p>

      <style>{`
        #qf-name:focus, #qf-phone:focus, #qf-zip:focus, #qf-address:focus, #qf-message:focus {
          border-color: ${accent} !important;
          background: rgba(255,255,255,0.06) !important;
        }
        input::placeholder, textarea::placeholder { color: rgba(255,255,255,0.35); }
        @media (max-width: 560px) {
          .qf-row { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </form>
  );
};

const Spinner = () => (
  <span style={{
    width: 16, height: 16, borderRadius: 999,
    border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff',
    display: 'inline-block', animation: 'qf-spin .7s linear infinite',
  }}>
    <style>{`@keyframes qf-spin { to { transform: rotate(360deg); } }`}</style>
  </span>
);

window.QuoteForm = QuoteForm;
