/* Lead form — 9-step survey ported from elevate-home-offers.
 *
 * Flow:
 *   1. Property Type    (disqualifies condo/mobile/land/other)
 *   2. Legal Owner      (disqualifies "no")
 *   3. Ownership Length (disqualifies <3 years — no equity)
 *   4. Listed on Market (disqualifies if listed)
 *   5. Timeline
 *   6. Condition
 *   7. Reason
 *   8. Contact (name/email/phone with validation)
 *
 * Address comes pre-filled from the hero address pill.
 *
 * Submits to the same n8n webhook as elevate-home-offers so leads
 * land in the same flow.
 */
const { useState: useStateLF, useEffect: useEffectLF, useRef: useRefLF } = React;

const WEBHOOK_URL = 'https://n8n.srv1197128.hstgr.cloud/webhook/2250ea76-ada8-4e4b-ab8f-4e2a41a73ab3';
const SUPPORT_PHONE_DISPLAY = '(813) 213-3578';
const SUPPORT_PHONE_TEL = '+18132133578';

const PROPERTY_TYPE_OPTIONS = [
  { id: 'single-family', label: 'Single Family Home' },
  { id: 'multi-family', label: 'Multi-Family (Duplex, Triplex, etc.)' },
  { id: 'condo-townhouse', label: 'Condo / Townhouse' },
  { id: 'mobile-home', label: 'Mobile / Manufactured Home' },
  { id: 'land', label: 'Vacant Land / Lot' },
  { id: 'other', label: 'Other' },
];
const LEGAL_OWNER_OPTIONS = [
  { id: 'yes-owner', label: 'Yes, I am the legal homeowner' },
  { id: 'yes-family', label: 'Yes, I am a family member with the legal right to sell' },
  { id: 'no', label: 'No, I am not' },
];
const OWNERSHIP_LENGTH_OPTIONS = [
  { id: '3-5-years', label: '3 to 5 years' },
  { id: '5-10-years', label: '5 to 10 years' },
  { id: '10-plus-years', label: '10+ years' },
  { id: '1-3-years', label: 'Less than 3 years' },
];
const LISTED_OPTIONS = [
  { id: 'not-listed', label: 'No, it is not listed' },
  { id: 'listed-realtor', label: 'Yes, listed with a realtor' },
  { id: 'listed-fsbo', label: 'Yes, listed for sale by owner' },
];
const TIMELINE_OPTIONS = [
  { id: 'asap', label: 'ASAP (Within 7 days)' },
  { id: '2-weeks', label: 'Within 2 weeks' },
  { id: '30-days', label: 'Within 30 days' },
  { id: '60-days', label: 'Within 60 days' },
  { id: 'flexible', label: "I'm flexible" },
];
const CONDITION_OPTIONS = [
  { id: 'excellent', label: 'Excellent. Move-in ready' },
  { id: 'good', label: 'Good. Minor repairs needed' },
  { id: 'fair', label: 'Fair. Needs some work' },
  { id: 'poor', label: 'Poor. Major repairs needed' },
  { id: 'distressed', label: 'Distressed. Significant issues' },
];
const REASON_OPTIONS = [
  { id: 'foreclosure', label: 'Facing foreclosure' },
  { id: 'behind-payments', label: 'Behind on payments' },
  { id: 'inherited', label: 'Inherited property' },
  { id: 'divorce', label: 'Divorce or separation' },
  { id: 'relocation', label: 'Job relocation' },
  { id: 'downsizing', label: 'Downsizing' },
  { id: 'repairs', label: "Can't afford repairs" },
  { id: 'other', label: 'Other' },
];

// ============================================================
// LEAD SCORING + QUALIFICATION
// ============================================================
// Score table — William's adjusted matrix (2026-04-27)
const SCORE_TIMELINE = {
  'asap': 3, '2-weeks': 2, '30-days': 1, '60-days': 0, 'flexible': 0,
};
const SCORE_OWNERSHIP = {
  '10-plus-years': 3, '5-10-years': 1, '3-5-years': 0, '1-3-years': 0,
};
const SCORE_REASON = {
  'foreclosure': 3, 'behind-payments': 3,
  'inherited': 2, 'repairs': 2,
  'other': 1,
  'relocation': 0, 'divorce': 0, 'downsizing': 0,
};
const SCORE_CONDITION = {
  'poor': 1, 'distressed': 1,
  'fair': 0, 'good': 0, 'excellent': 0,
};

function calculateLeadScore(d) {
  return (SCORE_TIMELINE[d.timeline] || 0)
       + (SCORE_OWNERSHIP[d.ownershipLength] || 0)
       + (SCORE_REASON[d.reason] || 0)
       + (SCORE_CONDITION[d.condition] || 0);
}

// Qualify gate for the Meta `Lead` event.
// Per William: only fire `Lead` when the property is single/multi-family,
// NOT listed on market, and the user is the legal owner. Everyone else
// still gets submitted to the CRM but fires `LeadLowIntent` instead.
function isQualifiedForMeta(d) {
  const okType = d.propertyType === 'single-family' || d.propertyType === 'multi-family';
  const okListed = d.listedOnMarket === 'not-listed';
  const okOwner = d.isLegalOwner !== 'no';
  return okType && okListed && okOwner;
}

function disqualifyReason(d) {
  if (d.propertyType === 'condo-townhouse') return 'condo_townhouse';
  if (d.propertyType === 'mobile-home') return 'mobile_home';
  if (d.propertyType === 'land') return 'vacant_land';
  if (d.propertyType === 'other') return 'other_property_type';
  if (d.listedOnMarket === 'listed-realtor' || d.listedOnMarket === 'listed-fsbo') return 'listed_on_market';
  if (d.isLegalOwner === 'no') return 'not_legal_owner';
  return 'unspecified';
}

function leadQuality(score) {
  if (score >= 6) return 'premium';
  if (score >= 3) return 'standard';
  return 'low';
}

// NANP valid area codes (subset, matches elevate-home-offers source of truth)
const VALID_AREA_CODES = new Set(["201","202","203","205","206","207","208","209","210","212","213","214","215","216","217","218","219","220","223","224","225","228","229","231","234","239","240","248","251","252","253","254","256","260","262","267","269","270","272","276","279","281","301","302","303","304","305","307","308","309","310","312","313","314","315","316","317","318","319","320","321","323","325","326","327","330","331","332","334","336","337","339","340","341","346","347","351","352","360","361","364","380","385","386","401","402","404","405","406","407","408","409","410","412","413","414","415","417","419","423","424","425","430","432","434","435","440","442","443","445","447","448","458","463","469","470","475","478","479","480","484","501","502","503","504","505","507","508","509","510","512","513","515","516","517","518","520","530","531","534","539","540","541","551","559","561","562","563","564","567","570","571","573","574","575","580","585","586","601","602","603","605","606","607","608","609","610","612","614","615","616","617","618","619","620","623","626","628","629","630","631","636","641","646","650","651","657","659","660","661","662","667","669","678","680","681","682","689","701","702","703","704","706","707","708","712","713","714","715","716","717","718","719","720","724","725","726","727","728","731","732","734","737","740","743","747","754","757","760","762","763","765","769","770","772","773","774","775","779","781","785","786","801","802","803","804","805","806","808","810","812","813","814","815","816","817","818","820","828","830","831","832","838","843","845","847","848","850","854","856","857","858","859","860","862","863","864","865","870","872","878","901","903","904","906","907","908","909","910","912","913","914","915","916","917","918","919","920","925","928","929","930","931","934","936","937","938","940","941","943","947","949","951","952","954","956","959","970","971","972","973","978","979","980","984","985","989"]);
const DISPOSABLE_DOMAINS = new Set(["mailinator.com","guerrillamail.com","tempmail.com","throwaway.email","yopmail.com","sharklasers.com","guerrillamail.info","grr.la","spam4.me","trashmail.com","trashmail.me","trashmail.net","mytemp.email","mohmal.com","tempail.com","dispostable.com","maildrop.cc","10minutemail.com","temp-mail.org","fakeinbox.com","mailnesia.com","getnada.com","emailondeck.com","33mail.com","harakirimail.com","jetable.org","meltmail.com","mailcatch.com","tempinbox.com","spamgourmet.com","mailexpire.com","incognitomail.org","getairmail.com","mailnull.com","safeemail.xyz","tempmailo.com","burnermail.io"]);
const BLOCKED_WORDS = new Set(["fuck","shit","ass","damn","bitch","bastard","dick","cock","pussy","cunt","whore","slut","fag","retard","penis","vagina","anus","dildo","porn","xxx","viagra","cialis","casino","bitcoin","crypto","forex","mlm","scam","spam","test123","asdf","qwerty","aaaaaa","zzzzzz","abcdef","123456"]);

function formatPhoneNumber(value) {
  let digits = String(value || '').replace(/\D/g, '');
  if (digits.startsWith('1')) digits = digits.slice(1);
  if (digits.length > 10) digits = digits.slice(0, 10);
  if (digits.length === 0) return '';
  if (digits.length <= 3) return `(${digits}`;
  if (digits.length <= 6) return `(${digits.slice(0,3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6,10)}`;
}
function validatePhone(phone) {
  const digits = String(phone || '').replace(/\D/g, '').replace(/^1/, '');
  if (digits.length !== 10) return { valid: false, msg: 'Please enter a valid 10-digit US phone number.' };
  const area = digits.slice(0, 3);
  if (!VALID_AREA_CODES.has(area)) return { valid: false, msg: `Area code (${area}) doesn't appear to be valid.` };
  if (/^(\d)\1{9}$/.test(digits)) return { valid: false, msg: 'Please enter a real phone number.' };
  if (['1234567890','0123456789','9876543210'].includes(digits)) return { valid: false, msg: 'Please enter a real phone number.' };
  const exchange = digits.slice(3, 6);
  if (exchange === '555') return { valid: false, msg: 'Please enter a real phone number.' };
  if (exchange.startsWith('0') || exchange.startsWith('1')) return { valid: false, msg: "That doesn't look like a valid phone number." };
  return { valid: true, msg: '' };
}
function validateEmail(email) {
  if (!email || !email.trim()) return { valid: false, msg: 'Email is required.' };
  const e = email.trim().toLowerCase();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) return { valid: false, msg: 'Please enter a valid email address.' };
  const domain = e.split('@')[1];
  if (DISPOSABLE_DOMAINS.has(domain)) return { valid: false, msg: 'Please use a real email address, not a temporary one.' };
  const fakePatterns = ['test@test','fake@fake','asdf@asdf','noemail@','spam@','junk@','nobody@nobody','aaa@aaa','abc@abc','example@example'];
  for (const p of fakePatterns) { if (e.startsWith(p)) return { valid: false, msg: 'Please enter your real email address.' }; }
  for (const part of e.replace('@', ' ').replace(/\./g, ' ').split(/\s+/)) {
    if (BLOCKED_WORDS.has(part)) return { valid: false, msg: 'Please enter a valid email address.' };
  }
  return { valid: true, msg: '' };
}
function validateName(name) {
  const t = String(name || '').trim();
  if (!t) return { valid: false, msg: 'Name is required.' };
  if (t.length < 2) return { valid: false, msg: 'Please enter your full name.' };
  for (const word of t.toLowerCase().split(/\s+/)) {
    if (BLOCKED_WORDS.has(word)) return { valid: false, msg: 'Please enter your real name.' };
  }
  if (/(.)\1{4,}/.test(t)) return { valid: false, msg: 'Please enter your real name.' };
  if (/^\d+$/.test(t)) return { valid: false, msg: 'Please enter your real name, not a number.' };
  return { valid: true, msg: '' };
}

function captureTracking() {
  if (typeof window === 'undefined') return {};
  const params = new URLSearchParams(window.location.search);
  return {
    utm_source:   params.get('utm_source')   || '',
    utm_medium:   params.get('utm_medium')   || '',
    utm_campaign: params.get('utm_campaign') || '',
    utm_content:  params.get('utm_content')  || '',
    utm_term:     params.get('utm_term')     || '',
    fbclid:       params.get('fbclid')       || '',
    gclid:        params.get('gclid')        || '',
    msclkid:      params.get('msclkid')      || '',
    ttclid:       params.get('ttclid')       || '',
    referrer:     document.referrer || '',
    landing_page: window.location.href,
    user_agent:   navigator.userAgent || '',
  };
}
async function getIP() {
  try {
    const ctrl = new AbortController();
    setTimeout(() => ctrl.abort(), 3000);
    const res = await fetch('https://api.ipify.org?format=json', { signal: ctrl.signal });
    const data = await res.json();
    return data.ip || '';
  } catch (e) { return ''; }
}

function LeadForm({ address, onClose }) {
  const [step, setStep] = useStateLF(1);             // 1..8
  const [data, setData] = useStateLF({
    propertyType: '', isLegalOwner: '', ownershipLength: '',
    listedOnMarket: '', timeline: '', condition: '', reason: '',
    name: '', email: '', phone: '',
  });
  const [submitted, setSubmitted] = useStateLF(false);
  const [disqualified, setDisqualified] = useStateLF(false);
  const [disqualifyReason, setDisqualifyReason] = useStateLF('');
  const [submitting, setSubmitting] = useStateLF(false);
  const [errors, setErrors] = useStateLF({});
  const [honeypot, setHoneypot] = useStateLF('');
  const formStart = useRefLF(Date.now());
  const tracking = useRefLF(captureTracking());

  useEffectLF(() => { getIP().then((ip) => { tracking.current.ip = ip; }); }, []);
  useEffectLF(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  const total = 8;
  const progress = submitted ? 100 : Math.round(((step - 1) / total) * 100);

  const advance = () => { if (step < total) setStep(step + 1); };
  const back = () => { if (step > 1) setStep(step - 1); };

  const setField = (key, value) => setData({ ...data, [key]: value });

  const handleOption = (key, value) => {
    setField(key, value);

    // Hard disqualifiers — these four are 1000% non-buyable. Show the
    // disqualified screen and do NOT submit to CRM, do NOT fire any pixel.
    if (key === 'propertyType' && (value === 'condo-townhouse' || value === 'mobile-home')) {
      setTimeout(() => { setDisqualifyReason('propertyType'); setDisqualified(true); }, 280);
      return;
    }
    if (key === 'isLegalOwner' && value === 'no') {
      setTimeout(() => { setDisqualifyReason('notOwner'); setDisqualified(true); }, 280);
      return;
    }
    if (key === 'listedOnMarket' && (value === 'listed-realtor' || value === 'listed-fsbo')) {
      setTimeout(() => { setDisqualifyReason('listed'); setDisqualified(true); }, 280);
      return;
    }

    // Everyone else (including land/other property type and <3 yr ownership)
    // continues through the form. They'll submit to n8n on completion;
    // Meta `Lead` event only fires if isQualifiedForMeta() is true at submit.
    setTimeout(advance, 220);
  };

  const submit = async () => {
    const errs = {};
    const n = validateName(data.name);   if (!n.valid) errs.name = n.msg;
    const e = validateEmail(data.email); if (!e.valid) errs.email = e.msg;
    const p = validatePhone(data.phone); if (!p.valid) errs.phone = p.msg;
    if (Object.keys(errs).length) { setErrors(errs); return; }

    // Anti-bot: <3s = bot, honeypot = bot. Show a fake-success to bots.
    const elapsed = Date.now() - formStart.current;
    if (elapsed < 3000 || honeypot) { setSubmitted(true); return; }

    setSubmitting(true);

    // Compute qualification + lead score
    const qualified = isQualifiedForMeta(data);
    const score = calculateLeadScore(data);
    const quality = leadQuality(score);
    const dqReason = qualified ? null : disqualifyReason(data);
    // Stable event id so a future Conversions API call can dedupe with this
    // browser-side pixel event (Meta dedupes on event_id).
    const eventId = 'elv_' + Date.now() + '_' + Math.random().toString(36).slice(2, 10);

    // Meta Pixel — fire `Lead` ONLY for qualified, scored submissions.
    // Disqualified ones fire a custom `LeadLowIntent` event so Meta doesn't
    // optimize for them but we still see engagement in Events Manager.
    try {
      if (typeof window !== 'undefined' && window.fbq) {
        if (qualified) {
          window.fbq('track', 'Lead', {
            value: score * 25,           // 0pts→$0, 6pts→$150, 10pts→$250
            currency: 'USD',
            content_name: 'Elevate Home Buyer Survey',
            content_category: 'real_estate',
            lead_score: score,
            lead_quality: quality,
          }, { eventID: eventId });
        } else {
          window.fbq('trackCustom', 'LeadLowIntent', {
            content_name: 'Elevate Home Buyer Survey',
            content_category: 'real_estate',
            disqualify_reason: dqReason,
            lead_score: score,
          }, { eventID: eventId });
        }
      }
    } catch (err) {}

    const payload = Object.assign({}, data, tracking.current, {
      address,
      source: 'Elevate Home Buyer - Survey',
      submittedAt: new Date().toISOString(),
      qualified,
      lead_score: score,
      lead_quality: quality,
      disqualify_reason: dqReason,
      meta_event_id: eventId,
      meta_event_name: qualified ? 'Lead' : 'LeadLowIntent',
      meta_value: qualified ? score * 25 : 0,
    });

    try {
      await fetch(WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        mode: 'cors',
        keepalive: true,
      });
    } catch (err) {
      console.error('Webhook submit error', err);
    }
    try { localStorage.setItem('elv_last_lead', JSON.stringify(payload)); } catch (e2) {}

    setSubmitting(false);
    setSubmitted(true);
  };

  const optionsForStep = {
    1: { key: 'propertyType',   options: PROPERTY_TYPE_OPTIONS,   q: 'What type of property is it?',          sub: 'Select the option that best describes your property.' },
    2: { key: 'isLegalOwner',   options: LEGAL_OWNER_OPTIONS,     q: 'Are you the legal homeowner?',          sub: "This helps us understand who we'll be working with." },
    3: { key: 'ownershipLength',options: OWNERSHIP_LENGTH_OPTIONS,q: 'How long have you owned the home?',     sub: 'This helps us estimate your equity position.' },
    4: { key: 'listedOnMarket', options: LISTED_OPTIONS,          q: 'Is the property currently listed?',     sub: "Let us know if it's currently for sale." },
    5: { key: 'timeline',       options: TIMELINE_OPTIONS,        q: 'How fast are you looking to sell?',     sub: 'Select your ideal timeline for closing.' },
    6: { key: 'condition',      options: CONDITION_OPTIONS,       q: 'What condition is the property in?',    sub: 'Be honest. We buy houses in any condition.' },
    7: { key: 'reason',         options: REASON_OPTIONS,          q: "What's your reason for selling?",       sub: 'This helps us understand your situation.' },
  };

  // Disqualified screen
  if (disqualified) {
    const messages = {
      notOwner: {
        title: "We're unable to assist",
        message: 'Unfortunately, we can only work with individuals who have the legal right to sell the property.',
        detail: 'If you have power of attorney, are an executor of estate, or a court-appointed representative, please call us directly.',
      },
      listed: {
        title: "We can't make an offer right now",
        message: "We're unable to make an offer on properties that are currently listed.",
        detail: "If your listing expires or you take it off the market, we'd love to help. Reach out then.",
      },
      propertyType: {
        title: "We're unable to assist",
        message: "Unfortunately, we're not able to make an offer on this type of property at this time.",
        detail: "We primarily purchase single-family and multi-family homes. If you have a different property to sell, give us a call.",
      },
      noEquity: {
        title: "We're unable to make an offer",
        message: "Properties owned for less than 3 years typically don't have enough equity for us to make a fair cash offer.",
        detail: "If your situation changes, we're always happy to talk.",
      },
    };
    const msg = messages[disqualifyReason] || messages.notOwner;
    return (
      <div className="lf-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="lf-modal" role="dialog" aria-modal="true">
          <button className="lf-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
          <div style={{ textAlign: 'center', padding: '20px 0 8px' }}>
            <div style={{ width: 64, height: 64, borderRadius: 999, background: 'rgba(244,63,94,0.15)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="#f43f5e" strokeWidth="2"/><path d="M8 8L16 16M16 8L8 16" stroke="#f43f5e" strokeWidth="2" strokeLinecap="round"/></svg>
            </div>
            <h3 className="lf-question" style={{ marginBottom: 10 }}>{msg.title}</h3>
            <p style={{ color: 'rgba(255,255,255,0.78)', fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.55, maxWidth: 480, margin: '0 auto 12px' }}>{msg.message}</p>
            <p style={{ color: 'rgba(255,255,255,0.55)', fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.55, maxWidth: 480, margin: '0 auto 24px' }}>{msg.detail}</p>
            <a href={`tel:${SUPPORT_PHONE_TEL}`} className="lf-next" style={{ textDecoration: 'none', display: 'inline-block' }}>
              Call Us: {SUPPORT_PHONE_DISPLAY}
            </a>
          </div>
        </div>
      </div>
    );
  }

  // Submitted screen
  if (submitted) {
    return (
      <div className="lf-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="lf-modal" role="dialog" aria-modal="true">
          <button className="lf-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
          <div style={{ textAlign: 'center', padding: '20px 0 10px' }}>
            <div className="lf-success-icon">
              <svg width="28" height="28" viewBox="0 0 28 28" fill="none"><path d="M6 14L12 20L22 8" stroke="#3bb8f4" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3 className="lf-question" style={{ marginBottom: 10 }}>Thank you, {(data.name || '').split(' ')[0] || 'friend'}.</h3>
            <p style={{ color: 'rgba(255,255,255,0.78)', fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.55, maxWidth: 480, margin: '0 auto' }}>
              We've received your information and will be in touch within <strong style={{ color: '#fff' }}>24 hours</strong> with your cash offer.
            </p>
            <div style={{ background: 'rgba(255,255,255,0.04)', borderRadius: 12, padding: 16, margin: '20px auto 0', maxWidth: 480, textAlign: 'left', fontSize: 14, color: 'rgba(255,255,255,0.7)' }}>
              <div style={{ marginBottom: 6 }}><strong style={{ color: '#fff' }}>Property:</strong> {address}</div>
              <div style={{ marginBottom: 6 }}><strong style={{ color: '#fff' }}>Email:</strong> {data.email}</div>
              <div><strong style={{ color: '#fff' }}>Phone:</strong> {data.phone}</div>
            </div>
            <button className="lf-next" style={{ marginTop: 24 }} onClick={onClose}>Done</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="lf-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="lf-modal" role="dialog" aria-modal="true">
        <button className="lf-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
        </button>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <img src="assets/elevate-logo-clean.png" alt="" style={{ width: 36, height: 36, borderRadius: '50%', objectFit: 'contain' }} />
            <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, letterSpacing: '0.04em', fontSize: 13, textTransform: 'uppercase', color: 'rgba(255,255,255,0.85)' }}>Elevate Home Buyer</span>
          </div>
          <a href={`tel:${SUPPORT_PHONE_TEL}`} style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 13, color: 'var(--accent)', textDecoration: 'none', whiteSpace: 'nowrap' }}>
            {SUPPORT_PHONE_DISPLAY}
          </a>
        </div>

        <div className="lf-progress"><div className="lf-progress-bar" style={{ width: `${progress}%` }} /></div>

        {address && (
          <div className="lf-address-summary">
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M6 1C3.8 1 2 2.8 2 5c0 3 4 6 4 6s4-3 4-6c0-2.2-1.8-4-4-4z" stroke="currentColor" strokeWidth="1.2"/><circle cx="6" cy="5" r="1.3" stroke="currentColor" strokeWidth="1.2"/></svg>
            {address}
          </div>
        )}

        {/* Steps 1-7: option choices */}
        {step <= 7 && (() => {
          const cfg = optionsForStep[step];
          return (
            <>
              <p className="lf-step-label">Step {step} of {total}</p>
              <h3 className="lf-question">{cfg.q}</h3>
              <p style={{ marginTop: -14, marginBottom: 18, fontSize: 14, color: 'rgba(255,255,255,0.55)' }}>{cfg.sub}</p>
              <div className={cfg.key === 'reason' ? 'lf-options' : 'lf-options'} style={cfg.key === 'reason' ? { gridTemplateColumns: '1fr 1fr' } : { gridTemplateColumns: '1fr' }}>
                {cfg.options.map((opt) => (
                  <button
                    key={opt.id}
                    type="button"
                    className={`lf-option ${data[cfg.key] === opt.id ? 'selected' : ''}`}
                    onClick={() => handleOption(cfg.key, opt.id)}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </>
          );
        })()}

        {/* Step 8: Contact info */}
        {step === 8 && (
          <>
            <p className="lf-step-label">Step 8 of {total}</p>
            <h3 className="lf-question">Almost done. How can we reach you?</h3>
            <p style={{ marginTop: -14, marginBottom: 18, fontSize: 14, color: 'rgba(255,255,255,0.55)' }}>We'll send your cash offer within 24 hours.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div>
                <input
                  className="lf-input"
                  placeholder="Your full name"
                  value={data.name}
                  onChange={(e) => { setField('name', e.target.value); setErrors({ ...errors, name: '' }); }}
                  style={errors.name ? { borderColor: '#f43f5e' } : {}}
                />
                {errors.name && <p style={{ color: '#f43f5e', fontSize: 12, margin: '6px 0 0' }}>{errors.name}</p>}
              </div>
              <div>
                <input
                  className="lf-input"
                  type="email"
                  placeholder="Email address"
                  value={data.email}
                  onChange={(e) => { setField('email', e.target.value); setErrors({ ...errors, email: '' }); }}
                  style={errors.email ? { borderColor: '#f43f5e' } : {}}
                />
                {errors.email && <p style={{ color: '#f43f5e', fontSize: 12, margin: '6px 0 0' }}>{errors.email}</p>}
              </div>
              <div>
                <input
                  className="lf-input"
                  type="tel"
                  placeholder="(813) 555-0000"
                  value={data.phone}
                  maxLength={14}
                  onChange={(e) => { setField('phone', formatPhoneNumber(e.target.value)); setErrors({ ...errors, phone: '' }); }}
                  style={errors.phone ? { borderColor: '#f43f5e' } : {}}
                />
                {errors.phone && <p style={{ color: '#f43f5e', fontSize: 12, margin: '6px 0 0' }}>{errors.phone}</p>}
              </div>
              {/* Honeypot — hidden from real users, bots will fill it */}
              <input
                type="text"
                name="website"
                value={honeypot}
                onChange={(e) => setHoneypot(e.target.value)}
                style={{ position: 'absolute', left: -9999, opacity: 0, pointerEvents: 'none' }}
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
              />
            </div>
          </>
        )}

        <div className="lf-actions">
          <button className="lf-back" onClick={back} disabled={step === 1} style={{ visibility: step === 1 ? 'hidden' : 'visible' }}>Back</button>
          <button
            className="lf-next"
            onClick={step === 8 ? submit : advance}
            disabled={step === 8 ? submitting : !data[(optionsForStep[step] || {}).key]}
          >
            {step === 8
              ? (submitting ? 'Submitting…' : 'Get my cash offer')
              : 'Continue'}
          </button>
        </div>
      </div>
    </div>
  );
}

window.LeadForm = LeadForm;
