const WEBHOOK_URL = 'https://script.google.com/macros/s/AKfycbznsFokT6hMRaKhASqrfb6FbbRW2xW1ViGaEYaJxZFCeP321m-bMwnisAlWh3Iy6YiYGw/exec';

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

  React.useEffect(() => {
    if (open && window.fbq) fbq('track', 'Contact');
  }, [open]);

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

  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;
  const renter = answers.homeowner === "No - I rent";
  const justResearching = answers.timeline === "Just researching";

  const select = (key, val) => {
    setAnswers(a => ({ ...a, [key]: val }));
    setErrors(e => ({ ...e, [key]: null }));

    if (key === "homeowner" && val === "No - I rent" && window.fbq) {
      fbq('trackCustom', 'Disqualified', { reason: 'renter' });
    }

    if (["homeowner", "projectType", "timeline"].includes(key)) {
      setTimeout(() => {
        if (key === "homeowner" && val === "No - I rent") return;
        setStep(s => s + 1);
      }, 180);
    }
  };

  const toggleCondition = (val) => {
    setAnswers(a => {
      const current = a.roofCondition || [];
      const next = current.includes(val)
        ? current.filter(x => x !== val)
        : [...current, val];
      return { ...a, roofCondition: next };
    });
  };

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

  const sendToSheet = (payload) => {
    fetch(WEBHOOK_URL, {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }).catch(() => {});
  };

  const getPayload = () => {
    const params = new URLSearchParams(window.location.search);
    const fullName = [answers.firstName || '', answers.lastName || ''].join(' ').trim();
    return {
      name: fullName,
      email: answers.email || '',
      phone: answers.phone || '',
      homeowner: answers.homeowner || '',
      projectType: answers.projectType || '',
      roofCondition: answers.roofCondition || [],
      timeline: answers.timeline || '',
      utmSource: params.get('utm_source') || '',
      utmMedium: params.get('utm_medium') || '',
      utmCampaign: params.get('utm_campaign') || '',
      utmAdset: params.get('utm_adset') || '',
      utmContent: params.get('utm_content') || '',
      utmTerm: params.get('utm_term') || '',
      offerPage: offerPage || 'unknown',
      fbclid: params.get('fbclid') || '',
      gclid: params.get('gclid') || '',
      pageUrl: window.location.href,
      referrer: document.referrer || '',
      userAgent: navigator.userAgent || '',
    };
  };

  const validateContact = () => {
    const errs = {};
    if (!answers.firstName?.trim()) errs.firstName = "Please enter your first name";
    if (!answers.lastName?.trim()) errs.lastName = "Please enter your last 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');
      if (justResearching) fbq('trackCustom', 'NurtureLead');
      else fbq('trackCustom', 'QualifiedLead');
    }

    sendToSheet(getPayload());
    setSubmitted(true);
    setStep(5);
  };

  // RENTER disqualify screen
  if (renter && !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:380}}>
                We're not able to help with this one. We only do roof work for property owners. Best of luck with your project.
              </p>
              <button
                className="btn btn-dark btn-lg"
                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 < 5 ? (
            <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, 5)} of 5</div>
          <button className="modal-close" onClick={onClose}><Ic.close /></button>
        </div>

        <div className="modal-body">
          {step === 0 && (
            <Step
              eyebrow="Quick question"
              title="Are you the homeowner?"
              sub="We can only do roof work for property owners — this confirms a quick fit."
              options={["Yes - I own this home", "No - I rent", "I'm helping family"]}
              value={answers.homeowner}
              onSelect={v => select("homeowner", v)}
            />
          )}
          {step === 1 && (
            <Step
              eyebrow="Your project"
              title="What kind of roofing project are you planning?"
              sub="Pick the closest fit — we'll get into details on the call."
              options={[
                "Full roof replacement",
                "Major repair (more than just a patch)",
                "Not sure yet — want a pro to look",
              ]}
              value={answers.projectType}
              onSelect={v => select("projectType", v)}
            />
          )}
          {step === 2 && (
            <MultiStep
              eyebrow="Roof condition"
              title="What's going on with your current roof?"
              sub="Select all that apply — we want the full picture before we visit."
              options={[
                "It's leaking",
                "Missing or damaged shingles",
                "15+ years old",
                "Storm or wind damage",
                "Moss or algae buildup",
                "Upgrading before selling",
              ]}
              values={answers.roofCondition || []}
              onToggle={toggleCondition}
              onNext={() => setStep(s => s + 1)}
            />
          )}
          {step === 3 && (
            <Step
              eyebrow="Your timeline"
              title="When do you want the work done?"
              sub="A rough target is fine — we'll lock dates in on the consultation."
              options={[
                "ASAP (within 30 days)",
                "Within 3 months",
                "3-6 months",
                "Just researching",
              ]}
              value={answers.timeline}
              onSelect={v => select("timeline", v)}
            />
          )}
          {step === 4 && (
            <>
              <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">
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
                  <Field label="First name" name="firstName" value={answers.firstName || ""} error={errors.firstName} onChange={v => setAnswers(a => ({...a, firstName: v}))} placeholder="Jane" />
                  <Field label="Last name" name="lastName" value={answers.lastName || ""} error={errors.lastName} onChange={v => setAnswers(a => ({...a, lastName: v}))} placeholder="Doe" />
                </div>
                <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 === 5 && 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:400}}>
                {justResearching
                  ? `Thanks, ${answers.firstName || "friend"}! We'll send a quick homeowner's roof guide to your inbox. When you're ready for the estimate, just reply and we'll set it up.`
                  : `Thanks, ${answers.firstName || "friend"}! Our team will call you within one business day to confirm your free estimate and your offer.`}
              </p>
              {!justResearching && (
                <div style={{background:'var(--brand-tint)', borderRadius:12, padding:'16px 18px', textAlign:'left', maxWidth:420, margin:'0 auto 24px', display:'flex', gap:12}}>
                  <div style={{color:'var(--brand-primary-deep)', 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}}>Plus our 5-yr workmanship warranty + No-Sting Roof price-in-writing guarantee.</div>
                  </div>
                </div>
              )}
              <p style={{fontSize:13, color:'var(--ink-3)', marginTop:8}}>
                Questions? Email us at <a href="mailto:pete@buzybeeroofing.com" style={{color:'var(--brand-primary-deep)', fontWeight:600}}>pete@buzybeeroofing.com</a>
              </p>
            </div>
          )}
        </div>

        {step === 2 && (
          <div className="modal-footer">
            <button
              className="btn btn-primary btn-lg"
              onClick={() => setStep(s => s + 1)}
              disabled={(answers.roofCondition || []).length === 0}
              style={{opacity: (answers.roofCondition || []).length === 0 ? 0.5 : 1}}
            >
              Continue <Ic.arrow />
            </button>
          </div>
        )}
        {step === 4 && (
          <div className="modal-footer">
            <button className="btn btn-primary btn-lg" onClick={submit}>
              {ctaLabel || "Get My Free Estimate & Offer"} <Ic.arrow />
            </button>
            <div className="modal-disclaimer">
              By clicking "{ctaLabel || "Get My Free Estimate & Offer"}", I am providing my electronic signature and express written consent to calls, text messages, and emails from BuzyBee Roofing.
            </div>
          </div>
        )}
        {step === 5 && (
          <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 MultiStep({ eyebrow, title, sub, options, values, onToggle, onNext }) {
  return (
    <>
      <span className="eyebrow" style={{marginBottom:12}}>{eyebrow}</span>
      <h3>{title}</h3>
      <p className="sub">{sub}</p>
      <div className="step-options">
        {options.map(opt => {
          const checked = values.includes(opt);
          return (
            <button
              key={opt}
              className={"step-option " + (checked ? "is-selected" : "")}
              onClick={() => onToggle(opt)}
              type="button"
            >
              <span className="checkbox" style={{
                width:18, height:18, borderRadius:4,
                border:'2px solid ' + (checked ? 'var(--brand-primary-deep)' : 'var(--line-strong)'),
                background: checked ? 'var(--brand-primary)' : '#fff',
                display:'flex', alignItems:'center', justifyContent:'center',
                flexShrink:0,
              }}>
                {checked && <Ic.check size={11} />}
              </span>
              <span>{opt}</span>
            </button>
          );
        })}
      </div>
    </>
  );
}

function Field({ label, name, type="text", value, onChange, onBlur, 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)}
        onBlur={onBlur}
        placeholder={placeholder}
        autoComplete={type === "email" ? "email" : type === "tel" ? "tel" : "off"}
      />
      {error && <div className="err">{error}</div>}
    </div>
  );
}

window.EstimateModal = EstimateModal;
