const { useState, useEffect, useRef } = React;

function IntakeModal({ onClose }) {
  const [step, setStep] = useState(0); // 0 property, 1 owner, 2 review, 3 success
  const tier = 'Frontline';
  const [form, setForm] = useState({
    cad: '',
    address: '',
    city: 'Galveston',
    zip: '',
    name: '',
    email: '',
    phone: '',
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const firstField = useRef(null);

  useEffect(() => {
    if (firstField.current) firstField.current.focus();
    function key(e) { if (e.key === 'Escape') onClose(); }
    window.addEventListener('keydown', key);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', key);
      document.body.style.overflow = '';
    };
  }, []);

  function update(field, value) {
    setForm(f => ({ ...f, [field]: value }));
    setErrors(e => ({ ...e, [field]: undefined }));
  }

  function validateStep(s) {
    const errs = {};
    if (s === 0) {
      if (!/^R-?\d{6,8}$/i.test(form.cad.trim())) errs.cad = 'Use the R-number from your Notice (e.g. R-145203).';
      if (form.address.trim().length < 5) errs.address = 'Required.';
      if (!/^\d{5}$/.test(form.zip.trim())) errs.zip = 'Five-digit zip.';
    }
    if (s === 1) {
      if (form.name.trim().length < 2) errs.name = 'Required.';
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim())) errs.email = 'Use a real email — that\'s where the packet goes.';
      if (form.phone && !/^[\d\s\-().+]{7,}$/.test(form.phone)) errs.phone = 'Optional — but if filled, use a real number.';
    }
    return errs;
  }

  function next() {
    const errs = validateStep(step);
    if (Object.keys(errs).length) { setErrors(errs); return; }
    if (step === 2) { submit(); return; }
    setStep(s => s + 1);
  }

  function back() {
    setStep(s => Math.max(0, s - 1));
  }

  function submit() {
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setStep(3);
    }, 1400);
  }

  const conf = 'LP-' + Math.random().toString(36).slice(2, 7).toUpperCase() + '-' + new Date().getFullYear();

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target.classList.contains('modal-backdrop')) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="modal-ttl">
        <div className="modal-head">
          <div>
            <div className="t">Latchpin Tax · Intake</div>
            <div className="ttl" id="modal-ttl">
              {step === 3 ? 'Packet queued.' : 'Start your protest'}
            </div>
          </div>
          <button className="x" onClick={onClose} aria-label="Close">×</button>
        </div>

        {step < 3 && (
          <>
            <div className="modal-body">
              <div className="progress" aria-hidden="true">
                <span className={step >= 0 ? 'on' : ''}></span>
                <span className={step >= 1 ? 'on' : ''}></span>
                <span className={step >= 2 ? 'on' : ''}></span>
              </div>

              {step === 0 && (
                <>
                  <label htmlFor="cad">Galveston CAD account number</label>
                  <input
                    id="cad"
                    ref={firstField}
                    value={form.cad}
                    onChange={e => update('cad', e.target.value)}
                    placeholder="R-145203"
                    className={errors.cad ? 'err' : ''}
                  />
                  {errors.cad && <div className="err-msg">{errors.cad}</div>}

                  <label htmlFor="address">Property street address</label>
                  <input
                    id="address"
                    value={form.address}
                    onChange={e => update('address', e.target.value)}
                    placeholder="2418 Pelican Loop"
                    className={errors.address ? 'err' : ''}
                  />
                  {errors.address && <div className="err-msg">{errors.address}</div>}

                  <div className="row">
                    <div>
                      <label htmlFor="city">City</label>
                      <input id="city" value={form.city} onChange={e => update('city', e.target.value)} />
                    </div>
                    <div>
                      <label htmlFor="zip">Zip</label>
                      <input
                        id="zip"
                        value={form.zip}
                        onChange={e => update('zip', e.target.value)}
                        placeholder="77554"
                        className={errors.zip ? 'err' : ''}
                      />
                      {errors.zip && <div className="err-msg">{errors.zip}</div>}
                    </div>
                  </div>
                </>
              )}

              {step === 1 && (
                <>
                  <label htmlFor="name">Owner name (as on the Notice)</label>
                  <input
                    id="name"
                    ref={firstField}
                    value={form.name}
                    onChange={e => update('name', e.target.value)}
                    placeholder="Jordan A. Reyes"
                    className={errors.name ? 'err' : ''}
                  />
                  {errors.name && <div className="err-msg">{errors.name}</div>}

                  <label htmlFor="email">Email — where the packet goes</label>
                  <input
                    id="email"
                    type="email"
                    value={form.email}
                    onChange={e => update('email', e.target.value)}
                    placeholder="jordan@example.com"
                    className={errors.email ? 'err' : ''}
                  />
                  {errors.email && <div className="err-msg">{errors.email}</div>}

                  <label htmlFor="phone">Phone (optional)</label>
                  <input
                    id="phone"
                    type="tel"
                    value={form.phone}
                    onChange={e => update('phone', e.target.value)}
                    placeholder="(409) 555-0182"
                    className={errors.phone ? 'err' : ''}
                  />
                  {errors.phone && <div className="err-msg">{errors.phone}</div>}

                  <div style={{ background: 'var(--paper)', border: '1px solid var(--rule)', padding: 14, fontSize: 13, color: 'var(--slate-2)', marginTop: 4 }}>
                    We use this email once — to send your packet. No newsletter. No marketing. No resale. See <a href="#" style={{ color: 'var(--navy)' }}>privacy policy</a>.
                  </div>
                </>
              )}

              {step === 2 && (
                <>
                  <div className="review">
                    <div className="rrow"><span>Packet</span><span>Frontline · $149</span></div>
                    <div className="rrow"><span>CAD account</span><span>{form.cad.toUpperCase()}</span></div>
                    <div className="rrow"><span>Property</span><span>{form.address}, {form.city} {form.zip}</span></div>
                    <div className="rrow"><span>Owner</span><span>{form.name}</span></div>
                    <div className="rrow"><span>Delivery email</span><span>{form.email}</span></div>
                    <div className="rrow"><span>ETA</span><span>&lt; 5 minutes</span></div>
                  </div>

                  <div style={{ fontSize: 13, color: 'var(--slate-2)', lineHeight: 1.55, padding: '12px 0', borderTop: '1px solid var(--rule-soft)' }}>
                    By clicking <strong>Pay $149</strong>, you authorize a one-time charge to your card and confirm that you are the property owner of record (or a person authorized by them) and have read the <a href="#" style={{ color: 'var(--navy)' }}>TDLR disclosure</a> in our footer. Latchpin Tax is not a TDLR-licensed property tax consultant.
                  </div>
                </>
              )}
            </div>

            <div className="modal-foot">
              <button className="back" onClick={back} disabled={step === 0}>← Back</button>
              <button className="btn btn-primary" onClick={next} disabled={submitting}>
                {submitting ? 'Building packet…' : step === 2 ? 'Pay $149 →' : 'Continue →'}
              </button>
            </div>
          </>
        )}

        {step === 3 && (
          <div className="modal-success">
            <div className="check">✓</div>
            <h3>Packet queued. Check your inbox in 5 minutes.</h3>
            <p style={{ color: 'var(--slate-2)', maxWidth: 44 + 'ch', margin: '12px auto 0' }}>
              We're pulling your CAD record and same-street comparables from the Galveston County ArcGIS service right now. You'll get a zip with all five documents at <strong>{form.email}</strong>.
            </p>
            <div className="receipt">
              <div className="conf"><span>Confirmation</span><strong>{conf}</strong></div>
              <div><span>Packet</span><span>Frontline · $149</span></div>
              <div><span>Account</span><span>{form.cad.toUpperCase()}</span></div>
              <div><span>Property</span><span>{form.address}</span></div>
              <div><span>ETA</span><span>&lt; 5 min</span></div>
            </div>
            <button className="btn btn-outline" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

function CTAManager() {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    function handle(e) {
      const btn = e.target.closest('[data-cta]');
      if (!btn) return;
      e.preventDefault();
      setOpen(true);
    }
    document.addEventListener('click', handle);
    return () => document.removeEventListener('click', handle);
  }, []);

  if (!open) return null;
  return <IntakeModal onClose={() => setOpen(false)} />;
}

ReactDOM.createRoot(document.getElementById('modal-mount')).render(<CTAManager />);
