/* eslint-disable */
// ECM Real Estate Services — production sections.

const { useEffect, useRef, useState } = React;

/* ───── Netlify form helper ───── */
function encodeForm(data) {
  return Object.keys(data)
    .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(data[k] ?? ''))
    .join('&');
}
function submitToNetlify(formName, data) {
  return fetch('/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: encodeForm({ 'form-name': formName, ...data }),
  });
}

/* ───── Open application modal (global) ───── */
function openApplication() {
  window.dispatchEvent(new CustomEvent('ecm:open-application'));
}

/* ───── Input masks ───── */
function maskPhone(v) {
  const d = (v || '').replace(/\D/g, '').slice(0, 10);
  if (!d) return '';
  if (d.length < 4) return `(${d}`;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
}
function maskCurrency(v) {
  const d = (v || '').replace(/\D/g, '').slice(0, 12);
  if (!d) return '';
  return '$' + Number(d).toLocaleString('en-US');
}
function maskSSN(v) {
  const d = (v || '').replace(/\D/g, '').slice(0, 9);
  if (d.length <= 3) return d;
  if (d.length <= 5) return `${d.slice(0, 3)}-${d.slice(3)}`;
  return `${d.slice(0, 3)}-${d.slice(3, 5)}-${d.slice(5)}`;
}

/* Reveal hook */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* Section header helper */
function SectHead({ children, light }) {
  return (
    <div className={`sect-head ${light ? 'light' : ''} reveal`}>
      <h2>{children}</h2>
      <span className="rule" />
    </div>
  );
}

/* ───── Nav ───── */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    function onScroll() { setScrolled(window.scrollY > 80); }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const go = (e, id) => {
    e.preventDefault();
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
  };
  return (
    <header className={`nav ${scrolled ? 'is-scrolled' : ''}`}>
      <a href="#top" className="nav-brand" onClick={(e) => go(e, 'top')} aria-label="ECM Real Estate Services">
        <img src="assets/logo.png" alt="ECM Real Estate Services" />
      </a>
      <div className="nav-right">
        <nav>
          <ul className="nav-links">
            <li><a href="#about" onClick={(e) => go(e, 'about')}>About</a></li>
            <li><a href="#directors" onClick={(e) => go(e, 'directors')}>Directors</a></li>
            <li><a href="#services" onClick={(e) => go(e, 'services')}>Services</a></li>
            <li><a href="/loan-programs/">Loan Programs</a></li>
            <li><a href="#programs" onClick={(e) => go(e, 'programs')}>Process</a></li>
            <li><a href="#talk" onClick={(e) => go(e, 'talk')}>Contact</a></li>
          </ul>
        </nav>
        <button className="btn-apply nav-apply" onClick={openApplication}>
          <span className="lock">🔒</span> Apply Now
        </button>
      </div>
    </header>
  );
}

/* ───── Hero ───── */
function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-photo">
        <div className="hero-slide s1" />
        <div className="hero-slide s2" />
      </div>
      <div className="hero-shade" />
      <div className="hero-inner">
        <span className="hero-rule reveal" />
        <h1 className="reveal reveal-delay-1">Realize Your<br />Real Estate Dreams</h1>
        <p className="hero-tagline reveal reveal-delay-2">
          DSCR Rental Loans Nationwide — No Income Verification
        </p>
        <button className="btn-apply reveal reveal-delay-3" onClick={openApplication}>
          <span className="lock">🔒</span> Apply Now
        </button>
        <a className="hero-phone reveal reveal-delay-3" href="tel:+18442386346">
          <span className="hero-phone-label">Call us today</span>
          <span className="hero-phone-num">📞 1-844-2FUNDING</span>
          <span className="hero-phone-digits">1-844-238-6346</span>
        </a>
      </div>
      <div className="hero-chevron">⌄</div>
    </section>
  );
}

/* ───── Welcome ───── */
function Welcome() {
  return (
    <section className="welcome">
      <p className="reveal">
        Welcome to ECM Real Estate Services, we provide private, hard money loans
        to professional real estate investors.
      </p>
    </section>
  );
}

/* ───── About (dark band) ───── */
function About() {
  return (
    <React.Fragment>
      <section className="about" id="about">
        <SectHead light>About Us</SectHead>
        <div className="about-body reveal reveal-delay-1">
          <p>
            With over 30 years of combined experience in finance and real estate, ECM Real
            Estate Services is a premier private real estate lending company. We provide private,
            hard money and DSCR loans to professional real estate investors, with a focus on
            business lending — DSCR, fix and flip, and bridge loans nationwide. We give our clients
            quick answers to their loan questions, common-sense underwriting, and fast closings to
            meet their funding needs. Our goal is to offer the most competitive lending options and
            the best customer service. We do not want to close just one deal — we want to build a
            relationship that grows for years to come. As active real estate investors ourselves,
            we understand the importance of quality products, clear communication, and a fast,
            no-surprise closing.
          </p>
        </div>

        <div className="about-houses reveal reveal-delay-2" />
      </section>

      <section className="about-after">
        <div className="about-after-grid">
          <p className="hl reveal">
            Our lending highlights include: hard money loans, rehab lending, ARV lending, private
            lending, equity lending, no-doc lending, asset-based lending, cash-out loans, DSCR loans,
            and commercial bridge lending.
          </p>
          <p className="aim reveal reveal-delay-1">
            We work hard to deliver a high quality service. Our aim is your complete satisfaction.
          </p>
        </div>
      </section>
    </React.Fragment>
  );
}

/* ───── Directors ───── */
const DIRECTORS = [
  { name: 'Michael Demers', role: 'CEO, Chairman of the Board', email: 'info@ecmrealestateservices.com', photo: 'assets/director-michael.jpg' },
  { name: 'Louis Germano', role: 'Member, Board of Trustees', email: 'lgermano@ecmrealestateservices.com', photo: 'assets/director-louis.jpg' },
  { name: 'Herb McLaughlin', role: 'Member, Board of Trustees', email: 'hmclaughlin@ecmrealestateservices.com', photo: 'assets/director-herb.jpg' },
];
function Directors() {
  return (
    <section className="directors" id="directors">
      <SectHead>Directors</SectHead>
      <div className="directors-row">
        {DIRECTORS.map((d, i) => (
          <div className={`director reveal reveal-delay-${i + 1}`} key={d.name}>
            <div className="director-photo" style={{ backgroundImage: `url(${d.photo})` }} />
            <div className="director-name">{d.name}</div>
            <div className="director-role">{d.role}</div>
            <a className="director-mail" href={`mailto:${d.email}`} aria-label={`Email ${d.name}`}>✉</a>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ───── Services ───── */
const DSCR_FEATURES = [
  { glyph: '◫', title: 'No Tax Returns or Income Verification',
    desc: 'Qualify without tax returns, W-2s, or personal income verification.' },
  { glyph: '$', title: 'Based on Property Cash Flow',
    desc: 'Approval is driven by the property’s rental income (debt-service coverage ratio), not your personal income.' },
  { glyph: '∞', title: 'Terms Up to 40 Years',
    desc: 'Long-term, fully amortizing terms up to 40 years for buy-and-hold investors.' },
  { glyph: '⌂', title: 'Short-Term Rental Allowed',
    desc: 'Airbnb and short-term rental properties are eligible.' },
];
const FIXFLIP_FEATURES = [
  { glyph: '⌂', title: 'Up to 100% of Purchase & Rehab',
    desc: 'Finance up to 100% of the purchase price and rehab costs.' },
  { glyph: '⚡', title: 'Fast Draws',
    desc: 'Quick, hassle-free rehab draw reimbursements to keep your project moving.' },
];
const BRIDGE_FEATURES = [
  { glyph: '⚡', title: 'Close in Days, Not Weeks',
    desc: 'Fast closings so you can move quickly on time-sensitive opportunities.' },
  { glyph: '▦', title: 'Transitional Properties',
    desc: 'Financing for properties in transition or being repositioned.' },
  { glyph: '$', title: 'Cash-Out Options',
    desc: 'Flexible cash-out options to pull equity from your property.' },
];
const SERVICE_GROUPS = [
  { title: 'DSCR Rental Loans', href: '/dscr-loans/', features: DSCR_FEATURES },
  { title: 'Fix & Flip Loans', href: '/fix-and-flip-loans/', features: FIXFLIP_FEATURES },
  { title: 'Bridge Loans', href: '/commercial-bridge-loans/', features: BRIDGE_FEATURES },
];
function Services() {
  const leadStyle = {
    textAlign: 'center',
    fontSize: 'clamp(1.4rem, 3vw, 2.1rem)',
    fontWeight: 800,
    textTransform: 'uppercase',
    letterSpacing: '0.02em',
    margin: '0 0 1.5rem',
  };
  const card = (s, i, href) => (
    <a className={`service service-link reveal reveal-delay-${(i % 3) + 1}`} key={s.title} href={href}>
      <div className="service-icon">{s.glyph}</div>
      <div>
        <h3>{s.title}</h3>
        <p>{s.desc}</p>
      </div>
    </a>
  );
  return (
    <section className="services" id="services">
      <SectHead>Our Services</SectHead>
      {SERVICE_GROUPS.map((g, gi) => (
        <React.Fragment key={g.title}>
          <p className="reveal" style={gi === 0 ? leadStyle : { ...leadStyle, margin: '2.5rem 0 1.5rem' }}>
            <a className="services-head-link" href={g.href}>{g.title}</a>
          </p>
          <div className="service-grid">{g.features.map((s, i) => card(s, i, g.href))}</div>
          <div className="services-more reveal">
            <a href={g.href}>Learn more about {g.title} →</a>
          </div>
        </React.Fragment>
      ))}
    </section>
  );
}

/* ───── Subscribe (newsletter) ───── */
function Subscribe() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState('');

  async function submit(e) {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return;
    setSending(true);
    setError('');
    try {
      const res = await submitToNetlify('newsletter', { name, email });
      if (!res.ok) throw new Error('Submission failed');
      setDone(true);
    } catch (err) {
      setError("Sorry, something went wrong. Please email info@ecmrealestateservices.com.");
    } finally {
      setSending(false);
    }
  }

  return (
    <section className="subscribe">
      <h2 className="reveal">Subscribe to Our Newsletter</h2>
      {done ? (
        <p className="reveal" style={{ maxWidth: 520, margin: '0 auto', color: '#fff' }}>
          Thanks{name ? `, ${name.split(' ')[0]}` : ''} — you're on the list.
        </p>
      ) : (
        <form
          className="subscribe-form reveal reveal-delay-1"
          name="newsletter"
          method="POST"
          data-netlify="true"
          data-netlify-honeypot="bot-field"
          onSubmit={submit}
        >
          <input type="hidden" name="form-name" value="newsletter" />
          <p hidden><label>Don't fill: <input name="bot-field" /></label></p>
          <input type="text" name="name" placeholder="Your Name" value={name} onChange={(e) => setName(e.target.value)} />
          <input type="email" name="email" placeholder="Email Address" value={email} onChange={(e) => setEmail(e.target.value)} required />
          <button type="submit" disabled={sending}>{sending ? 'Sending…' : 'Subscribe'}</button>
        </form>
      )}
      {error && <p className="fineprint" style={{ color: '#ffb4ad' }}>{error}</p>}
      <p className="fineprint">
        Receive news, updates, special offers and property information by email.&nbsp;
        <a href="#">We don't do spam.</a>
      </p>
    </section>
  );
}

/* ───── Simple Process ───── */
const STEPS = [
  { n: '1', title: 'Submit Your Deal',
    desc: 'Send us the basics on your property and scenario.' },
  { n: '2', title: 'Get Terms in 24 Hours',
    desc: 'Receive clear, competitive terms within one business day.' },
  { n: '3', title: 'Close in 5–7 Days',
    desc: 'Fund and close in as little as 5–7 days — nationwide.' },
];
function Programs() {
  return (
    <section className="loans" id="programs">
      <SectHead>Simple Process</SectHead>
      <p className="reveal" style={{
        textAlign: 'center',
        fontSize: 'clamp(1.4rem, 3vw, 2.1rem)',
        fontWeight: 800,
        textTransform: 'uppercase',
        letterSpacing: '0.02em',
        margin: '0 0 1.5rem',
      }}>
        How It Works
      </p>
      <div className="service-grid">
        {STEPS.map((s, i) => (
          <article className={`service reveal reveal-delay-${(i % 3) + 1}`} key={s.n}>
            <div className="service-icon">{s.n}</div>
            <div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
            </div>
          </article>
        ))}
      </div>
      <p className="reveal" style={{
        textAlign: 'center',
        fontSize: 'clamp(1.05rem, 2.2vw, 1.35rem)',
        fontWeight: 700,
        margin: '1.5rem 0 0',
      }}>
        Minimum loan size $200,000 · No maximum loan amount
      </p>
      <div className="loans-apply reveal">
        <button className="btn-apply" onClick={openApplication}>
          <span className="lock">🔒</span> Apply Now
        </button>
      </div>
    </section>
  );
}

/* ───── Recently Funded ───── */
const DEALS = [
  { amount: '$285,000', type: 'Fix & Flip', note: 'Closed in 6 days' },
  { amount: '$410,000', type: 'DSCR Rental', note: 'No income docs' },
  { amount: '$2.5 Million', type: 'Bridge Loan', note: 'Closed in 8 days' },
];
function RecentlyFunded() {
  return (
    <section className="services" id="recently-funded">
      <SectHead>Recently Funded Deals</SectHead>
      <div className="service-grid">
        {DEALS.map((d, i) => (
          <article className={`service reveal reveal-delay-${(i % 3) + 1}`} key={i}>
            <div className="service-icon">✓</div>
            <div>
              <h3>{d.amount} · {d.type}</h3>
              <p>{d.note}</p>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ───── Ready to Fund CTA ───── */
function ReadyCTA() {
  return (
    <section className="services" id="ready">
      <SectHead>Ready to Fund Your Next Deal?</SectHead>
      <div className="loans-apply reveal">
        <button className="btn-apply" onClick={openApplication}>
          <span className="lock">🔒</span> Apply Now
        </button>
      </div>
    </section>
  );
}

/* ───── Let's Talk ───── */
function Talk() {
  return (
    <section className="talk" id="talk">
      <SectHead light>Let's Talk</SectHead>
      <div className="talk-row">
        <div className="talk-col reveal reveal-delay-1">
          <div className="talk-icon" aria-hidden>✋</div>
          <h3>Shake Hands</h3>
          <div className="info">
            175 Central Ave, 3rd Floor<br />
            Albany, NY 12206 · USA<br />
            <a href="mailto:info@ecmrealestateservices.com">info@ecmrealestateservices.com</a><br />
            <a href="tel:+18442386346">1-844-2FUNDING (1-844-238-6346)</a>
          </div>
        </div>
        <div className="talk-col reveal reveal-delay-2">
          <div className="talk-icon" aria-hidden>💬</div>
          <h3>New Business</h3>
          <p>We can offer your scenario to targeted business prospects and match you with our network of lenders and borrowers.</p>
        </div>
        <div className="talk-col reveal reveal-delay-3">
          <div className="talk-icon" aria-hidden>👤<span style={{ fontSize: 18, marginLeft: -4 }}>＋</span></div>
          <h3>Join the Team</h3>
          <p>We're always looking for talented people to join our team.</p>
          <div className="info"><a href="mailto:jobs@ecmrealestateservices.com">jobs@ecmrealestateservices.com</a></div>
        </div>
      </div>
    </section>
  );
}

/* ───── Contact form ───── */
function Contact() {
  const [form, setForm] = useState({ name: '', email: '', subject: '', message: '' });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const [submitError, setSubmitError] = useState('');

  function validate(v = form) {
    const e = {};
    if (!v.name.trim()) e.name = 'Required';
    if (!v.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) e.email = 'Invalid';
    if (!v.message.trim()) e.message = 'Required';
    return e;
  }
  function update(k, val) {
    const next = { ...form, [k]: val };
    setForm(next);
    if (touched[k]) setErrors(validate(next));
  }
  function blur(k) { setTouched({ ...touched, [k]: true }); setErrors(validate()); }
  async function submit(e) {
    e.preventDefault();
    const eMap = validate();
    setErrors(eMap);
    setTouched({ name: true, email: true, subject: true, message: true });
    if (Object.keys(eMap).length > 0) return;

    setSending(true);
    setSubmitError('');
    try {
      const res = await submitToNetlify('contact', form);
      if (!res.ok) throw new Error('Submission failed');
      setDone(true);
    } catch (err) {
      setSubmitError("Sorry, your message didn't go through. Please email info@ecmrealestateservices.com or call 1-844-2FUNDING.");
    } finally {
      setSending(false);
    }
  }
  const fc = (k) => `field ${errors[k] && touched[k] ? 'is-error' : ''} ${k === 'message' ? 'field-msg' : ''}`;

  return (
    <section className="contact" id="contact">
      <SectHead>Get In Touch</SectHead>
      <p className="contact-intro reveal">
        Feel free to contact us anytime to discuss your loan scenarios, general questions and
        funding needs. Contact Michael Demers by email at <a href="mailto:info@ecmrealestateservices.com">info@ecmrealestateservices.com</a>.
      </p>

      <form
        className="contact-form reveal reveal-delay-1"
        name="contact"
        method="POST"
        data-netlify="true"
        data-netlify-honeypot="bot-field"
        onSubmit={submit}
        noValidate
      >
        <input type="hidden" name="form-name" value="contact" />
        <p hidden><label>Don't fill: <input name="bot-field" /></label></p>
        {done ? (
          <div className="success-pane">
            <h3>Message received</h3>
            <p>Thanks{form.name ? `, ${form.name.split(' ')[0]}` : ''} — a member of our team will be in touch shortly.</p>
            <button type="button" onClick={() => { setDone(false); setForm({ name: '', email: '', subject: '', message: '' }); setTouched({}); setErrors({}); }}>
              Send another message
            </button>
          </div>
        ) : (
          <React.Fragment>
            <div className={fc('name')}>
              <input type="text" name="name" placeholder="Your Name" value={form.name}
                onChange={(e) => update('name', e.target.value)} onBlur={() => blur('name')} />
              {errors.name && touched.name && <span className="err">{errors.name}</span>}
            </div>
            <div className={`field field-msg ${errors.message && touched.message ? 'is-error' : ''}`}>
              <textarea name="message" placeholder="Message (Required)" value={form.message}
                onChange={(e) => update('message', e.target.value)} onBlur={() => blur('message')} />
              {errors.message && touched.message && <span className="err">{errors.message}</span>}
            </div>
            <div className={fc('email')}>
              <input type="email" name="email" placeholder="Your Email (Required)" value={form.email}
                onChange={(e) => update('email', e.target.value)} onBlur={() => blur('email')} />
              {errors.email && touched.email && <span className="err">{errors.email}</span>}
            </div>
            <div className="field">
              <input type="text" name="subject" placeholder="Subject" value={form.subject}
                onChange={(e) => update('subject', e.target.value)} />
            </div>
            {submitError && (
              <div style={{ gridColumn: '1 / -1', color: 'var(--accent)', fontSize: 13, textAlign: 'center' }}>
                {submitError}
              </div>
            )}
            <div className="contact-submit">
              <button type="submit" className="btn-apply" disabled={sending}>
                {sending ? 'Sending…' : 'Send Message'}
              </button>
            </div>
          </React.Fragment>
        )}
      </form>
    </section>
  );
}

/* ───── Mortgage Application (modal) ───── */
const LOAN_PROGRAMS = [
  'Purchase Rehab',
  'Rehab Only',
  'Equity Lending',
  'Commercial Bridge',
  'Transactional Funding',
  'Long Term Hold',
  'DSCR Loan',
  'Not sure — please advise',
];
const PROPERTY_TYPES = [
  'Single Family',
  '2–4 Family',
  'Multi-Family (5+)',
  'Mixed Use',
  'Commercial',
  'Land',
  'Other',
];
const EXIT_STRATEGIES = [
  'Sell after rehab (flip)',
  'Refinance into long-term loan',
  'Hold as rental',
  'Cash-out / pay off existing debt',
  'Other',
];

const EMPTY_APP = {
  applicantName: '',
  ssn: '',
  companyName: '',
  taxId: '',
  applicantEmail: '',
  applicantPhone: '',
  loanProgram: '',
  loanAmount: '',
  propertyAddress: '',
  propertyType: '',
  purchasePrice: '',
  afterRepairValue: '',
  creditEstimate: '',
  exitStrategy: '',
  notes: '',
};

function ApplicationModal() {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState(EMPTY_APP);
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const firstFieldRef = useRef(null);

  useEffect(() => {
    function onOpen() { setOpen(true); }
    function onKey(e) { if (e.key === 'Escape') setOpen(false); }
    function onHash() { if (window.location.hash === '#apply') setOpen(true); }
    window.addEventListener('ecm:open-application', onOpen);
    window.addEventListener('keydown', onKey);
    window.addEventListener('hashchange', onHash);
    // Deep link: /#apply (e.g. from the SEO landing pages) opens the application.
    onHash();
    return () => {
      window.removeEventListener('ecm:open-application', onOpen);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('hashchange', onHash);
    };
  }, []);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      setTimeout(() => firstFieldRef.current?.focus(), 50);
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  function validate(v = form) {
    const e = {};
    if (!v.applicantName.trim()) e.applicantName = 'Required';
    if (!v.applicantEmail.trim()) e.applicantEmail = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.applicantEmail)) e.applicantEmail = 'Invalid';
    if (!v.applicantPhone.trim()) e.applicantPhone = 'Required';
    if (!v.loanProgram) e.loanProgram = 'Required';
    if (!v.loanAmount.trim()) e.loanAmount = 'Required';
    if (!v.propertyAddress.trim()) e.propertyAddress = 'Required';
    return e;
  }
  function update(k, val) {
    const next = { ...form, [k]: val };
    setForm(next);
    if (touched[k]) setErrors(validate(next));
  }
  function blur(k) { setTouched({ ...touched, [k]: true }); setErrors(validate()); }

  async function submit(e) {
    e.preventDefault();
    const eMap = validate();
    setErrors(eMap);
    const allTouched = Object.keys(EMPTY_APP).reduce((acc, k) => ({ ...acc, [k]: true }), {});
    setTouched(allTouched);
    if (Object.keys(eMap).length > 0) return;

    setSending(true);
    setSubmitError('');
    try {
      const res = await submitToNetlify('mortgage-application', form);
      if (!res.ok) throw new Error('Submission failed');
      setDone(true);
      // Report the loan application to Google Ads as a conversion.
      if (window.ecmTrackConversion) window.ecmTrackConversion(window.ECM_APP_CONVERSION_LABEL);
    } catch (err) {
      setSubmitError("Sorry, your application didn't go through. Please email info@ecmrealestateservices.com or call 1-844-2FUNDING.");
    } finally {
      setSending(false);
    }
  }

  function close() {
    setOpen(false);
    setTimeout(() => {
      setForm(EMPTY_APP);
      setErrors({});
      setTouched({});
      setDone(false);
      setSubmitError('');
    }, 200);
  }

  if (!open) return null;

  const fieldClass = (k) => `app-field ${errors[k] && touched[k] ? 'is-error' : ''}`;

  return (
    <div className="app-modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="app-modal" role="dialog" aria-modal="true" aria-labelledby="app-modal-title">
        <button className="app-modal-close" onClick={close} aria-label="Close application">×</button>

        {done ? (
          <div className="app-success">
            <h3>Application received</h3>
            <p>
              Thanks{form.applicantName ? `, ${form.applicantName.split(' ')[0]}` : ''} — your loan
              application has been sent to our team. We'll be in touch within one business day to
              discuss your scenario.
            </p>
            <p className="app-success-sub">
              Need to talk sooner? Call <a href="tel:+18442386346">1-844-2FUNDING</a>.
            </p>
            <button className="btn-apply" onClick={close}>Close</button>
          </div>
        ) : (
          <React.Fragment>
            <header className="app-modal-head">
              <h3 id="app-modal-title">Loan Application</h3>
              <p>Tell us about your project. We respond within one business day.</p>
            </header>

            <form
              className="app-form"
              name="mortgage-application"
              method="POST"
              data-netlify="true"
              data-netlify-honeypot="bot-field"
              onSubmit={submit}
              noValidate
            >
              <input type="hidden" name="form-name" value="mortgage-application" />
              <p hidden><label>Don't fill: <input name="bot-field" /></label></p>

              <div className="app-section-label">Applicant</div>

              <div className={fieldClass('applicantName')}>
                <label>Full Name *</label>
                <input ref={firstFieldRef} type="text" name="applicantName" value={form.applicantName}
                  onChange={(e) => update('applicantName', e.target.value)} onBlur={() => blur('applicantName')} />
                {errors.applicantName && touched.applicantName && <span className="err">{errors.applicantName}</span>}
              </div>

              <div className={fieldClass('ssn')}>
                <label>Social Security Number</label>
                <input type="text" name="ssn" inputMode="numeric" autoComplete="off" placeholder="123-45-6789"
                  maxLength={11} value={form.ssn}
                  onChange={(e) => update('ssn', maskSSN(e.target.value))} />
              </div>

              <div className={fieldClass('companyName')}>
                <label>Company Name</label>
                <input type="text" name="companyName" value={form.companyName}
                  onChange={(e) => update('companyName', e.target.value)} />
              </div>

              <div className={fieldClass('taxId')}>
                <label>Tax ID (EIN)</label>
                <input type="text" name="taxId" inputMode="numeric" placeholder="12-3456789" value={form.taxId}
                  onChange={(e) => update('taxId', e.target.value)} />
              </div>

              <div className={fieldClass('applicantEmail')}>
                <label>Email *</label>
                <input type="email" name="applicantEmail" value={form.applicantEmail}
                  onChange={(e) => update('applicantEmail', e.target.value)} onBlur={() => blur('applicantEmail')} />
                {errors.applicantEmail && touched.applicantEmail && <span className="err">{errors.applicantEmail}</span>}
              </div>

              <div className={fieldClass('applicantPhone')}>
                <label>Phone *</label>
                <input type="tel" name="applicantPhone" inputMode="tel" autoComplete="tel"
                  placeholder="(555) 123-4567" maxLength={14} value={form.applicantPhone}
                  onChange={(e) => update('applicantPhone', maskPhone(e.target.value))}
                  onBlur={() => blur('applicantPhone')} />
                {errors.applicantPhone && touched.applicantPhone && <span className="err">{errors.applicantPhone}</span>}
              </div>

              <div className={fieldClass('creditEstimate')}>
                <label>Estimated Credit Score</label>
                <select name="creditEstimate" value={form.creditEstimate}
                  onChange={(e) => update('creditEstimate', e.target.value)}>
                  <option value="">— Select —</option>
                  <option value="Below 600">Below 600</option>
                  <option value="600–649">600–649</option>
                  <option value="650–699">650–699</option>
                  <option value="700–749">700–749</option>
                  <option value="750+">750+</option>
                  <option value="Unknown">Not sure</option>
                </select>
              </div>

              <div className="app-section-label">Loan</div>

              <div className={fieldClass('loanProgram')}>
                <label>Loan Program *</label>
                <select name="loanProgram" value={form.loanProgram}
                  onChange={(e) => update('loanProgram', e.target.value)} onBlur={() => blur('loanProgram')}>
                  <option value="">— Select a program —</option>
                  {LOAN_PROGRAMS.map((p) => <option key={p} value={p}>{p}</option>)}
                </select>
                {errors.loanProgram && touched.loanProgram && <span className="err">{errors.loanProgram}</span>}
              </div>

              <div className={fieldClass('loanAmount')}>
                <label>Loan Amount Requested *</label>
                <input type="text" inputMode="numeric" name="loanAmount" placeholder="$150,000" value={form.loanAmount}
                  onChange={(e) => update('loanAmount', maskCurrency(e.target.value))}
                  onBlur={() => blur('loanAmount')} />
                {errors.loanAmount && touched.loanAmount && <span className="err">{errors.loanAmount}</span>}
              </div>

              <div className={fieldClass('exitStrategy')}>
                <label>Exit Strategy</label>
                <select name="exitStrategy" value={form.exitStrategy}
                  onChange={(e) => update('exitStrategy', e.target.value)}>
                  <option value="">— Select —</option>
                  {EXIT_STRATEGIES.map((p) => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>

              <div className="app-section-label">Property</div>

              <div className={`${fieldClass('propertyAddress')} app-field-wide`}>
                <label>Property Address *</label>
                <input type="text" name="propertyAddress" placeholder="Street, City, State, ZIP" value={form.propertyAddress}
                  onChange={(e) => update('propertyAddress', e.target.value)} onBlur={() => blur('propertyAddress')} />
                {errors.propertyAddress && touched.propertyAddress && <span className="err">{errors.propertyAddress}</span>}
              </div>

              <div className={fieldClass('propertyType')}>
                <label>Property Type</label>
                <select name="propertyType" value={form.propertyType}
                  onChange={(e) => update('propertyType', e.target.value)}>
                  <option value="">— Select —</option>
                  {PROPERTY_TYPES.map((p) => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>

              <div className={fieldClass('purchasePrice')}>
                <label>Purchase Price</label>
                <input type="text" inputMode="numeric" name="purchasePrice" placeholder="$120,000" value={form.purchasePrice}
                  onChange={(e) => update('purchasePrice', maskCurrency(e.target.value))} />
              </div>

              <div className={fieldClass('afterRepairValue')}>
                <label>After Repair Value (ARV)</label>
                <input type="text" inputMode="numeric" name="afterRepairValue" placeholder="$220,000" value={form.afterRepairValue}
                  onChange={(e) => update('afterRepairValue', maskCurrency(e.target.value))} />
              </div>

              <div className="app-field-full">
                <label>Additional Notes</label>
                <textarea name="notes" placeholder="Anything else we should know — timeline, rehab scope, experience, etc." value={form.notes}
                  onChange={(e) => update('notes', e.target.value)} />
              </div>

              {submitError && (
                <div className="app-submit-error">{submitError}</div>
              )}

              <div className="app-actions">
                <button type="button" className="app-cancel" onClick={close} disabled={sending}>Cancel</button>
                <button type="submit" className="btn-apply" disabled={sending}>
                  <span className="lock">🔒</span> {sending ? 'Submitting…' : 'Submit Application'}
                </button>
              </div>

              <p className="app-disclosure">
                By submitting, you authorize ECM Real Estate Services to contact you about this
                request. Required fields are marked with *. We do not sell your information.
              </p>
            </form>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

/* ───── Chat widget ───── */
function ChatWidget() {
  const [open, setOpen] = useState(false);

  function startApplication() {
    setOpen(false);
    openApplication();
  }

  return (
    <div className="chat-widget">
      {open && (
        <div className="chat-panel" role="dialog" aria-label="Chat with ECM Real Estate Services">
          <div className="chat-head">
            <div>
              <strong>Chat with ECM</strong>
              <span>We typically reply within one business day.</span>
            </div>
            <button className="chat-close" onClick={() => setOpen(false)} aria-label="Close chat">×</button>
          </div>
          <div className="chat-body">
            <p className="chat-greeting">👋 Hi! How can we help you today?</p>
            <a className="chat-action" href="tel:+18442386346">
              <span className="chat-ic" aria-hidden>📞</span>
              <span><strong>Call us</strong><small>1-844-2FUNDING</small></span>
            </a>
            <a className="chat-action" href="sms:+18442386346">
              <span className="chat-ic" aria-hidden>📱</span>
              <span><strong>Text us</strong><small>Send a quick message</small></span>
            </a>
            <a className="chat-action" href="mailto:info@ecmrealestateservices.com">
              <span className="chat-ic" aria-hidden>📧</span>
              <span><strong>Email us</strong><small>info@ecmrealestateservices.com</small></span>
            </a>
            <button className="chat-action" onClick={startApplication}>
              <span className="chat-ic" aria-hidden>📝</span>
              <span><strong>Start application</strong><small>Apply for a loan in minutes</small></span>
            </button>
          </div>
        </div>
      )}
      <button
        className={`chat-toggle ${open ? 'is-open' : ''}`}
        onClick={() => setOpen((o) => !o)}
        aria-label={open ? 'Close chat' : 'Open chat'}
        aria-expanded={open}
      >
        {open ? '×' : '💬'}
      </button>
    </div>
  );
}

/* ───── Footer ───── */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-links">
        <a href="/loan-programs/">Loan Programs</a>
        <a href="/dscr-loans/">DSCR Loans</a>
        <a href="/fix-and-flip-loans/">Fix &amp; Flip Loans</a>
        <a href="/construction-loans/">Construction Loans</a>
        <a href="/rehab-loans/">Rehab Loans</a>
        <a href="/equity-lending/">Equity Lending</a>
        <a href="/commercial-bridge-loans/">Commercial Bridge</a>
        <a href="/transactional-funding/">Transactional Funding</a>
      </div>
      <div>ECM Real Estate Services Inc. All Rights Reserved.</div>
      <div className="rights">© {new Date().getFullYear()}</div>
    </footer>
  );
}

Object.assign(window, {
  useReveal, Nav, Hero, Welcome, About, Directors, Services, Subscribe, Programs, RecentlyFunded, ReadyCTA, Talk, Contact, ApplicationModal, ChatWidget, Footer
});
