/* 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');
}

/* 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>
      <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="#programs" onClick={(e) => go(e, 'programs')}>Programs</a></li>
          <li><a href="#talk" onClick={(e) => go(e, 'talk')}>Contact</a></li>
        </ul>
      </nav>
    </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">
        <img className="hero-logo reveal" src="assets/logo.png" alt="ECM Real Estate Services" />
        <span className="hero-rule reveal" />
        <h1 className="reveal reveal-delay-1">Realize Your<br />Real Estate Dreams</h1>
        <p className="reveal reveal-delay-2">
          ECM Real Estate Services is New York's premier private real estate lending source.
          We provide private, hard money loans to professional real estate investors. Our focus
          is funding non-owner-occupied property for renovation and investment purposes.
        </p>
        <button className="btn-apply reveal reveal-delay-3" onClick={openApplication}>
          <span className="lock">🔒</span> Apply Now
        </button>
      </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 a combined experience of over 30 years in finance and real estate, ECM Real
            Estate Services is New York's premier private real estate lending company. We provide
            private, hard money loans to professional real estate investors. Our focus is funding
            non-owner-occupied property for renovation and investment purposes. As a direct
            lender, we give our clients the ability to get 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 to our clients and to provide the best
            customer service. We do not want to close just one deal — we want to build a
            relationship that will grow for years to come.
          </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, 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: 'ecmcompanies@hotmail.com', photo: 'assets/director-michael.jpg' },
  { name: 'Louis Germano', role: 'Member, Board of Trustees', email: 'lgermano@ecmrealestate.co', photo: 'assets/director-louis.jpg' },
  { name: 'Herb McLaughlin', role: 'Member, Board of Trustees', email: 'hmclaughlin@ecmrealestate.co', 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 SERVICES = [
  { glyph: '⌂', title: 'Residential Rehab Lending',
    desc: 'Offering real estate investors purchase rehab or rehab-only financing up to 75%.' },
  { glyph: '$', title: 'Equity Lending',
    desc: 'Offering real estate investors equity lending on investment property up to 70% LTV for purchase, refinance or cash-out.' },
  { glyph: '▦', title: 'Commercial Bridge Lending',
    desc: 'Offering commercial bridge lending up to 75% on most commercial property types.' },
  { glyph: '◧', title: 'Invest with ECM',
    desc: 'ECM is seeking note and trust-deed investors to join our private lending network. Get in touch to learn about this great opportunity.' },
  { glyph: '◇', title: 'For Sale',
    desc: 'We are buying and selling properties. Contact us to put your property listing or send us a wholesale property you are trying to sell.' },
  { glyph: '∞', title: 'Long Term Hold Program',
    desc: 'We offer investors financing up to 30 years to hold investment properties as rental property.' },
];
function Services() {
  return (
    <section className="services" id="services">
      <SectHead>Our Services</SectHead>
      <div className="service-grid">
        {SERVICES.map((s, i) => (
          <article className={`service reveal reveal-delay-${(i % 3) + 1}`} key={s.title}>
            <div className="service-icon">{s.glyph}</div>
            <div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
            </div>
          </article>
        ))}
      </div>
    </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@ecmrealestate.co.");
    } 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>
  );
}

/* ───── Loan Programs table ───── */
const PROGRAMS = [
  {
    label: 'Purchase Rehab',
    fee: ['starting at 4%', '$2,500 minimum fee'],
    rate: ['from 13–15%', 'interest only'],
    down: ['Low money down', 'determined by risk'],
    term: ['6–12 month term'],
    req: ['Up to 65% ARV/LTV', 'No minimum credit score', 'Light Doc', 'Residential investment'],
  },
  {
    label: 'Rehab Only',
    fee: ['starting at 4%', '$2,500 minimum fee'],
    rate: ['from 13–15%', 'interest only'],
    down: ['0%', 'for free and clear homes'],
    term: ['6–12 month term'],
    req: ['Up to 50% ARV/LTV', 'No minimum credit score', 'Light Doc', 'Residential investment'],
  },
  {
    label: 'Equity Lending',
    fee: ['starting at 4%', '$2,500 minimum fee'],
    rate: ['15%', 'interest only'],
    down: ['Purchase — 20% min', 'Ref / Cash-Out — 0%'],
    term: ['1–5 year terms'],
    req: ['Up to 75% LTV', 'No Doc Loan', 'Commercial / Residential investment'],
  },
  {
    label: 'Transactional Funding',
    fee: ['$2,000 min fee'],
    rate: ['NONE'],
    down: ['NONE'],
    term: ['1–3 days'],
    req: ['Up to 100%', 'BC contract required', 'Residential investment'],
  },
];
function Programs() {
  function cell(arr) {
    return arr.map((line, i) => (
      <React.Fragment key={i}>
        {i === 0 ? <strong>{line}</strong> : <div>{line}</div>}
      </React.Fragment>
    ));
  }
  return (
    <section className="loans" id="programs">
      <SectHead>Loan Programs</SectHead>
      <div className="loans-table-wrap reveal reveal-delay-1">
        <table className="loans-table">
          <thead>
            <tr>
              <th />
              {PROGRAMS.map((p) => <th key={p.label}>{p.label}</th>)}
            </tr>
          </thead>
          <tbody>
            <tr>
              <th>Lender Fee</th>
              {PROGRAMS.map((p) => <td key={p.label} data-col={`${p.label} · Lender Fee`}>{cell(p.fee)}</td>)}
            </tr>
            <tr>
              <th>Interest Rate</th>
              {PROGRAMS.map((p) => <td key={p.label} data-col={`${p.label} · Interest Rate`}>{cell(p.rate)}</td>)}
            </tr>
            <tr>
              <th>Down Payment</th>
              {PROGRAMS.map((p) => <td key={p.label} data-col={`${p.label} · Down Payment`}>{cell(p.down)}</td>)}
            </tr>
            <tr>
              <th>Term</th>
              {PROGRAMS.map((p) => <td key={p.label} data-col={`${p.label} · Term`}>{cell(p.term)}</td>)}
            </tr>
            <tr>
              <th>Requirements</th>
              {PROGRAMS.map((p) => <td key={p.label} data-col={`${p.label} · Requirements`}>{cell(p.req)}</td>)}
            </tr>
          </tbody>
        </table>
      </div>
      <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">
            90 State Street, Suite 700&nbsp;D<br />
            Albany, NY · USA<br />
            <a href="mailto:info@ecmrealestate.co">info@ecmrealestate.co</a><br />
            <a href="tel:+15184455959">+1 (518) 445-5959</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@ecmrealestate.co">jobs@ecmrealestate.co</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@ecmrealestate.co or call 518-445-5959.");
    } 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:ecmcompanies@hotmail.com">ecmcompanies@hotmail.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',
  '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: '',
  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); }
    window.addEventListener('ecm:open-application', onOpen);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('ecm:open-application', onOpen);
      window.removeEventListener('keydown', onKey);
    };
  }, []);

  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);
    } catch (err) {
      setSubmitError("Sorry, your application didn't go through. Please email info@ecmrealestate.co or call 518-445-5959.");
    } 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:+15184455959">518-445-5959</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('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>
  );
}

/* ───── Footer ───── */
function Footer() {
  return (
    <footer className="footer">
      <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, Talk, Contact, ApplicationModal, Footer
});
