function EstimateModal({ open, onClose, ctaLabel }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (!open) {
      setTimeout(() => { setStep(0); setAnswers({}); setErrors({}); setSubmitted(false); }, 400);
    }
  }, [open]);

  // Browser back button navigates steps
  React.useEffect(() => {
    if (!open) return;
    window.history.pushState({ modalStep: step }, '');
    const onPopState = (e) => {
      if (step > 0 && step < 4) {
        setStep(s => Math.max(0, s - 1));
        window.history.pushState({ modalStep: step - 1 }, '');
      } else if (step === 0) {
        onClose();
      }
    };
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, [open, step]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const totalSteps = 5; // q1..q3, contact, success
  const disqualified = answers.owner === "No";

  const select = (key, val) => {
    setAnswers(a => ({ ...a, [key]: val }));
    setErrors(e => ({ ...e, [key]: null }));
    // Fire pixel events on first question
    if (key === "owner") {
      if (val === "Yes" && window.fbq) fbq('trackCustom', 'QualifiedLead');
      if (val === "No" && window.fbq) fbq('trackCustom', 'Disqualified');
    }
    // auto-advance for single-choice steps
    if (["owner", "reason", "timeline"].includes(key)) {
      setTimeout(() => {
        if (key === "owner" && val === "No") return; // show disqualify screen
        setStep(s => s + 1);
      }, 180);
    }
  };

  const progress = disqualified ? 100 : Math.min(100, ((step) / (totalSteps - 1)) * 100);

  const validateContact = () => {
    const errs = {};
    if (!answers.name?.trim()) errs.name = "Please enter your name";
    if (!answers.email?.trim()) errs.email = "Please enter your email";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(answers.email)) errs.email = "Please enter a valid email";
    if (!answers.phone?.trim()) errs.phone = "Please enter your phone";
    else if (answers.phone.replace(/\D/g,'').length < 10) errs.phone = "Please enter a valid phone";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const submit = () => {
    if (!validateContact()) return;
    if (window.fbq) fbq('track', 'Lead');

    // Read UTM params from URL
    const params = new URLSearchParams(window.location.search);
    const payload = {
      timestamp: new Date().toLocaleString('en-US', {timeZone: 'America/Los_Angeles'}),
      name: answers.name,
      email: answers.email,
      phone: answers.phone,
      reason: answers.reason || '',
      timeline: answers.timeline || '',
      utm_source: params.get('utm_source') || '',
      utm_campaign: params.get('utm_campaign') || '',
      utm_adset: params.get('utm_adset') || '',
      utm_content: params.get('utm_content') || '',
    };

    fetch('https://script.google.com/macros/s/AKfycbzaHdG4jgyeb8lDouDaplW5JBqLVRLj5VyXk7CEpRuuTn6ScmZxZGOBTcWoRvoDKFNr/exec', {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }).catch(() => {}); // silent fail — don't block UX

    setSubmitted(true);
    setStep(4);
  };

  // DISQUALIFIED screen
  if (disqualified && !submitted) {
    return (
      <div className="modal-backdrop" onClick={onClose}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          <div className="modal-header">
            <div />
            <button className="modal-close" onClick={onClose}><Ic.close /></button>
          </div>
          <div className="modal-body">
            <div className="modal-disqualify">
              <div className="emoji">🙏</div>
              <h3 style={{marginBottom:14}}>Thanks for reaching out.</h3>
              <p style={{color:'var(--ink-2)', lineHeight:1.6, margin:'0 auto', maxWidth:360}}>
                Unfortunately we're only able to work with homeowners in the Greater Seattle area right now. We appreciate your interest in New Day Construction and wish you the best with your project.
              </p>
              <button className="btn btn-ghost" style={{marginTop:24}} onClick={onClose}>Close</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          {step > 0 && step < 4 ? (
            <button className="modal-back" onClick={() => setStep(s => Math.max(0, s-1))} aria-label="Go back">
              <Ic.arrow style={{transform:'rotate(180deg)'}} /> Back
            </button>
          ) : <span className="modal-back modal-back--placeholder" aria-hidden="true" />}
          <div className="modal-progress">
            <div className="modal-progress-bar" style={{width: progress + "%"}} />
          </div>
          <div className="modal-step-count">Step {Math.min(step+1, 4)} of 4</div>
          <button className="modal-close" onClick={onClose}><Ic.close /></button>
        </div>

        <div className="modal-body">
          {step === 0 && (
            <Step
              eyebrow="Quick question"
              title="Do you own your home in the Greater Seattle area?"
              sub="We can only work with homeowners. This helps us confirm a quick fit."
              options={["Yes", "No"]}
              value={answers.owner}
              onSelect={v => select("owner", v)}
            />
          )}
          {step === 1 && (
            <Step
              eyebrow="Your project"
              title="What's the main reason you want to remodel your kitchen?"
              sub="Pick whichever fits best — we'll tailor the consultation around it."
              options={[
                "Outdated design",
                "Lack of space / poor layout",
                "Damaged or worn materials",
                "Preparing to sell",
                "Other",
              ]}
              value={answers.reason}
              onSelect={v => select("reason", v)}
            />
          )}
          {step === 2 && (
            <Step
              eyebrow="Your timeline"
              title="When would you ideally like your project completed?"
              sub="A rough target is fine — we can refine this in the consultation."
              options={[
                "ASAP",
                "Next 2–4 weeks",
                "Within 1–2 months",
                "Within 3–6 months",
              ]}
              value={answers.timeline}
              onSelect={v => select("timeline", v)}
            />
          )}
          {step === 3 && (
            <>
              <span className="eyebrow" style={{marginBottom:12}}>Almost done</span>
              <h3>Where should we send your estimate?</h3>
              <p className="sub modal-promise">
                We promise not to spam you or sell your information <Ic.lock />
              </p>
              <div className="step-fields">
                <Field label="Full name" name="name" value={answers.name || ""} error={errors.name} onChange={v => setAnswers(a => ({...a, name: v}))} placeholder="Jane Doe" />
                <Field label="Email address" name="email" type="email" value={answers.email || ""} error={errors.email} onChange={v => setAnswers(a => ({...a, email: v}))} placeholder="jane@example.com" />
                <Field label="Phone number" name="phone" type="tel" value={answers.phone || ""} error={errors.phone} onChange={v => {
                  const digits = v.replace(/\D/g, '').slice(0, 10);
                  let formatted = digits;
                  if (digits.length >= 7) formatted = `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`;
                  else if (digits.length >= 4) formatted = `(${digits.slice(0,3)}) ${digits.slice(3)}`;
                  else if (digits.length > 0) formatted = `(${digits}`;
                  setAnswers(a => ({...a, phone: formatted}));
                }} placeholder="(206) 555-0199" />
              </div>
            </>
          )}
          {step === 4 && submitted && (
            <div className="modal-success">
              <div className="check-big"><Ic.check size={32} /></div>
              <h3 style={{marginBottom:10}}>You're on the list.</h3>
              <p style={{color:'var(--ink-2)', lineHeight:1.6, margin:'0 auto 24px', maxWidth:380}}>
                Thanks, {answers.name?.split(' ')[0] || "friend"}! A senior designer will reach out within one business day to schedule your free in-home consultation and confirm your free pot filler offer.
              </p>
              <div style={{background:'var(--green-tint)', borderRadius:12, padding:'16px 18px', textAlign:'left', maxWidth:400, margin:'0 auto 24px', display:'flex', gap:12}}>
                <div style={{color:'var(--green)', flexShrink:0}}><Ic.gift size={22} /></div>
                <div>
                  <div style={{fontWeight:600, fontSize:14, color:'var(--ink)'}}>Your offer is reserved</div>
                  <div style={{fontSize:13, color:'var(--ink-2)', marginTop:2}}>Free pot filler ($1,500) + free 3D rendering ($500) + $250/day late guarantee.</div>
                </div>
              </div>
              <a
                href="https://www.newdayconstruction.co/projects/"
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                  width:'100%', maxWidth:400, margin:'0 auto',
                  padding:'13px 20px', borderRadius:10,
                  border:'1.5px solid var(--green)',
                  color:'var(--green)', fontWeight:600, fontSize:14,
                  textDecoration:'none', letterSpacing:'0.01em',
                  transition:'background 0.15s, color 0.15s',
                }}
                onMouseEnter={e => { e.currentTarget.style.background='var(--green)'; e.currentTarget.style.color='#fff'; }}
                onMouseLeave={e => { e.currentTarget.style.background='transparent'; e.currentTarget.style.color='var(--green)'; }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                See our recent kitchen projects
              </a>
            </div>
          )}
        </div>

        {step === 3 && (
          <div className="modal-footer">
            <button className="btn btn-primary btn-lg" onClick={submit}>
              {ctaLabel || "Get Free Estimate & Offer"} <Ic.arrow />
            </button>
            <div className="modal-disclaimer">
              By clicking "{ctaLabel || "Get Free Estimate & Offer"}", I am providing my electronic signature and express written consent to calls, text messages, and emails from New Day Construction.
            </div>
          </div>
        )}
        {step === 4 && (
          <div className="modal-footer modal-footer--divider">
            <button className="btn btn-dark btn-lg" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Step({ eyebrow, title, sub, options, value, onSelect }) {
  return (
    <>
      <span className="eyebrow" style={{marginBottom:12}}>{eyebrow}</span>
      <h3>{title}</h3>
      <p className="sub">{sub}</p>
      <div className="step-options">
        {options.map(opt => (
          <button
            key={opt}
            className={"step-option " + (value === opt ? "is-selected" : "")}
            onClick={() => onSelect(opt)}
          >
            <span className="radio" />
            <span>{opt}</span>
          </button>
        ))}
      </div>
    </>
  );
}

function Field({ label, name, type="text", value, onChange, error, placeholder }) {
  return (
    <div className={"field " + (error ? "has-error" : "")}>
      <label htmlFor={name}>{label}</label>
      <input id={name} type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} autoComplete={type === "email" ? "email" : type === "tel" ? "tel" : "name"} />
      {error && <div className="err">{error}</div>}
    </div>
  );
}

window.EstimateModal = EstimateModal;
