/* global React, Eyebrow, PlaqueTag, Button, Icon, useBreakpoint */
const { useState, useEffect, useRef } = React;

function SiteNav({ onJump, onSchedule }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const { isMobile, isTablet } = useBreakpoint();
  const compact = isMobile || isTablet;

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (!compact && menuOpen) setMenuOpen(false);
  }, [compact, menuOpen]);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  const links = [
    { id: 'home',     label: 'Home' },
    { id: 'services', label: 'Services' },
    { id: 'approach', label: 'Approach' },
    { id: 'about',    label: 'About' },
    { id: 'contact',  label: 'Contact' },
  ];

  const handleJump = (id) => {
    setMenuOpen(false);
    onJump(id);
  };

  const logoHeight = isMobile ? 44 : 56;
  const brandFontSize = isMobile ? 19 : 22;
  const subFontSize = isMobile ? 10 : 11;

  return (
    <>
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: scrolled ? 'rgba(247, 249, 250, 0.92)' : 'rgba(247, 249, 250, 0.6)',
      backdropFilter: 'blur(14px)',
      WebkitBackdropFilter: 'blur(14px)',
      borderBottom: scrolled ? '1px solid var(--border-subtle)' : '1px solid transparent',
      transition: 'background var(--dur-base) var(--ease-standard), border-color var(--dur-base) var(--ease-standard)',
    }}>
      <div style={{
        maxWidth: 1200, margin: '0 auto',
        padding: isMobile ? '14px 20px' : '18px 32px',
        display: 'flex', alignItems: 'center', gap: 28,
      }}>
        <a onClick={() => handleJump('home')} style={{ display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', textDecoration: 'none', flexShrink: 0 }}>
          <img
            src="assets/mountain-view-logo.png"
            style={{
              height: logoHeight, width: 'auto',
              filter: 'drop-shadow(0 1px 2px rgba(27, 49, 37, 0.18))',
            }}
            alt="Mountain View Group"
          />
          <div style={{ lineHeight: 1.0, whiteSpace: 'nowrap' }}>
            <div style={{ fontFamily: 'var(--font-serif)', fontWeight: 900, fontSize: brandFontSize, color: 'var(--mvg-forest)', letterSpacing: '-0.01em' }}>Mountain View</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: subFontSize, letterSpacing: '0.2em', color: 'var(--mvg-slate-700)', textTransform: 'uppercase', marginTop: 4 }}>Group&nbsp;·&nbsp;LLC</div>
          </div>
        </a>

        {!compact && (
          <nav style={{ display: 'flex', gap: 28, marginLeft: 24 }}>
            {links.map(l => (
              <a key={l.id} onClick={() => handleJump(l.id)} style={{
                cursor: 'pointer', textDecoration: 'none',
                fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500,
                color: 'var(--fg-2)',
                paddingBottom: 3,
                transition: 'color var(--dur-fast) var(--ease-standard)',
              }}
              onMouseEnter={e => e.currentTarget.style.color = 'var(--mvg-forest)'}
              onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-2)'}
              >{l.label}</a>
            ))}
          </nav>
        )}

        <div style={{ marginLeft: 'auto', display: 'flex', gap: 14, alignItems: 'center' }}>
          {!compact && <Button size="sm" onClick={() => onSchedule && onSchedule()}>Schedule a Consultation</Button>}
          {compact && (
            <button
              aria-label={menuOpen ? 'Close menu' : 'Open menu'}
              aria-expanded={menuOpen}
              onClick={() => setMenuOpen(o => !o)}
              style={{
                width: 44, height: 44,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: 'transparent', border: '1px solid var(--border-default)',
                borderRadius: 8, color: 'var(--mvg-forest)', cursor: 'pointer',
                padding: 0,
              }}
            >{menuOpen ? <Icon.X size={22}/> : <Icon.Menu size={22}/>}</button>
          )}
        </div>
      </div>
    </header>

    {compact && (
      <div
        aria-hidden={!menuOpen}
        style={{
          position: 'fixed', inset: '0 0 0 0', top: 0,
          background: 'rgba(20, 38, 25, 0.35)',
          opacity: menuOpen ? 1 : 0,
          pointerEvents: menuOpen ? 'auto' : 'none',
          transition: 'opacity var(--dur-base) var(--ease-standard)',
          zIndex: 70,
        }}
        onClick={() => setMenuOpen(false)}
      />
    )}

    {compact && (
      <nav
        aria-hidden={!menuOpen}
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0,
          width: 'min(86vw, 360px)',
          background: 'var(--mvg-offwhite)',
          boxShadow: '-16px 0 40px rgba(20, 38, 25, 0.18)',
          transform: menuOpen ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform var(--dur-slow) var(--ease-standard)',
          zIndex: 80,
          display: 'flex', flexDirection: 'column',
          padding: '24px 24px 32px',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28 }}>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 900, color: 'var(--mvg-forest)' }}>Menu</div>
          <button
            aria-label="Close menu"
            onClick={() => setMenuOpen(false)}
            style={{
              width: 40, height: 40,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: 'transparent', border: '1px solid var(--border-default)',
              borderRadius: 8, color: 'var(--mvg-forest)', cursor: 'pointer', padding: 0,
            }}
          ><Icon.X size={20}/></button>
        </div>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>
          {links.map(l => (
            <li key={l.id}>
              <a onClick={() => handleJump(l.id)} style={{
                display: 'block', padding: '14px 12px',
                fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 600,
                color: 'var(--fg-1)', cursor: 'pointer', textDecoration: 'none',
                borderRadius: 8,
              }}>{l.label}</a>
            </li>
          ))}
        </ul>
        <div style={{ marginTop: 24, paddingTop: 24, borderTop: '1px solid var(--border-subtle)' }}>
          <Button size="md" onClick={() => { setMenuOpen(false); onSchedule && onSchedule(); }}>Schedule a Consultation <Icon.ArrowRight size={14}/></Button>
        </div>
      </nav>
    )}
    </>
  );
}

function SiteFooter({ onJump, onSchedule }) {
  const { isMobile, isTablet } = useBreakpoint();
  const cols = isMobile ? '1fr' : isTablet ? '1fr 1fr' : '1.6fr 1fr 1fr 1fr';
  const gap = isMobile ? 40 : isTablet ? 40 : 56;
  const jump = (id) => () => onJump && onJump(id);
  const schedule = () => onSchedule && onSchedule();
  return (
    <footer style={{ background: 'var(--mvg-forest)', color: 'var(--mvg-offwhite)', padding: isMobile ? '56px 20px 28px' : '72px 32px 28px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'grid', gridTemplateColumns: cols, gap }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
            <img
              src="assets/mountain-view-logo.png"
              style={{
                height: 56, width: 'auto',
                filter: [
                  'drop-shadow(1px 0 0 rgba(247,249,250,0.85))',
                  'drop-shadow(-1px 0 0 rgba(247,249,250,0.85))',
                  'drop-shadow(0 1px 0 rgba(247,249,250,0.85))',
                  'drop-shadow(0 -1px 0 rgba(247,249,250,0.85))',
                  'drop-shadow(0 0 6px rgba(247,249,250,0.35))',
                  'drop-shadow(0 3px 8px rgba(0,0,0,0.5))',
                ].join(' '),
              }}
              alt=""
            />
            <div>
              <div style={{ fontFamily: 'var(--font-serif)', fontWeight: 900, fontSize: 22, letterSpacing: '-0.01em' }}>Mountain View</div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.2em', color: 'var(--mvg-sky)', textTransform: 'uppercase', marginTop: 3 }}>Group&nbsp;·&nbsp;LLC</div>
            </div>
          </div>
          <p style={{ fontSize: 14, lineHeight: 1.65, color: 'rgba(247,249,250,0.72)', margin: 0, maxWidth: 340 }}>
            Outsourced accounting support to help your business reach its summit.
          </p>
          <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
            <SocialChip href="https://www.linkedin.com/in/mikehaley10/" external aria-label="Mike Haley on LinkedIn"><Icon.Linkedin size={16}/></SocialChip>
            <SocialChip href="mailto:hello@mountainviewgroupllc.com" aria-label="Email Mountain View Group"><Icon.Mail size={16}/></SocialChip>
          </div>
        </div>
        <FooterCol title="Services" links={[
          { label: 'Monthly Close & Bookkeeping', onClick: jump('services') },
          { label: 'GAAP Financial Statements',   onClick: jump('services') },
          { label: 'Audit-Readiness Support',     onClick: jump('services') },
          { label: 'Special Projects',            onClick: jump('services') },
          { label: 'Software Implementations',    onClick: jump('services') },
          { label: 'Budgeting & Forecasting',     onClick: jump('services') },
        ]}/>
        <FooterCol title="Company" links={[
          { label: 'About',         onClick: jump('about') },
          { label: 'Our Approach',  onClick: jump('approach') },
          { label: 'Who We Help',   onClick: jump('who-we-help') },
          { label: 'Contact',       onClick: jump('contact') },
        ]}/>
        <FooterCol title="Contact" links={[
          { label: 'hello@mountainviewgroupllc.com', href: 'mailto:hello@mountainviewgroupllc.com' },
          { label: 'Schedule a Consultation',        onClick: schedule },
          { label: 'LinkedIn ↗',                     href: 'https://www.linkedin.com/in/mikehaley10/', target: '_blank' },
        ]}/>
      </div>
      <div style={{ maxWidth: 1200, margin: '56px auto 0', paddingTop: 24, borderTop: '1px solid rgba(247,249,250,0.12)', display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'rgba(247,249,250,0.55)', flexWrap: 'wrap', gap: 12 }}>
        <div>© 2026 Mountain View Group, LLC. All rights reserved.</div>
        <div style={{ display: 'flex', gap: 20 }}>
          <a href="/privacy" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(247,249,250,0.55)', textDecoration: 'none', cursor: 'pointer', transition: 'color var(--dur-fast) var(--ease-standard)' }} onMouseEnter={e => e.currentTarget.style.color = '#fff'} onMouseLeave={e => e.currentTarget.style.color = 'rgba(247,249,250,0.55)'}>Privacy Policy</a>
          <a href="/terms" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(247,249,250,0.55)', textDecoration: 'none', cursor: 'pointer', transition: 'color var(--dur-fast) var(--ease-standard)' }} onMouseEnter={e => e.currentTarget.style.color = '#fff'} onMouseLeave={e => e.currentTarget.style.color = 'rgba(247,249,250,0.55)'}>Terms of Use</a>
        </div>
      </div>
    </footer>
  );
}

function SocialChip({ children, onClick, href, external, ...rest }) {
  const baseStyle = { width: 36, height: 36, borderRadius: 999, border: '1px solid rgba(247,249,250,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'rgba(247,249,250,0.85)', transition: 'background var(--dur-fast) var(--ease-standard)', textDecoration: 'none' };
  const onEnter = e => e.currentTarget.style.background = 'rgba(247,249,250,0.08)';
  const onLeave = e => e.currentTarget.style.background = 'transparent';
  if (href) {
    return (
      <a href={href} target={external ? '_blank' : undefined} rel={external ? 'noopener noreferrer' : undefined} style={baseStyle} onMouseEnter={onEnter} onMouseLeave={onLeave} {...rest}>{children}</a>
    );
  }
  return (
    <div onClick={onClick} style={baseStyle} onMouseEnter={onEnter} onMouseLeave={onLeave} {...rest}>{children}</div>
  );
}

function FooterCol({ title, links }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--mvg-sky)', marginBottom: 16 }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
        {links.map((l, i) => {
          const item = typeof l === 'string' ? { label: l } : l;
          const baseStyle = { fontSize: 14, color: 'rgba(247,249,250,0.82)', cursor: item.onClick || item.href ? 'pointer' : 'default', lineHeight: 1.4, textDecoration: 'none', transition: 'color var(--dur-fast) var(--ease-standard)' };
          const onEnter = e => e.currentTarget.style.color = '#fff';
          const onLeave = e => e.currentTarget.style.color = 'rgba(247,249,250,0.82)';
          if (item.href) {
            return (
              <li key={i}>
                <a href={item.href} target={item.target} rel={item.target === '_blank' ? 'noopener noreferrer' : undefined} style={baseStyle} onMouseEnter={onEnter} onMouseLeave={onLeave}>{item.label}</a>
              </li>
            );
          }
          return (
            <li key={i} onClick={item.onClick} style={baseStyle} onMouseEnter={onEnter} onMouseLeave={onLeave}>{item.label}</li>
          );
        })}
      </ul>
    </div>
  );
}

/* ============================================================
   CONSULTATION MODAL
   ============================================================ */
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/mqevrnln';

const SERVICES_OPTIONS = [
  'Bookkeeping',
  'Tax preparation',
  'CFO/advisory services',
  'Financial statements',
  'Cleanup/catch-up work',
  'Audit support',
];

const LEGAL_STRUCTURES = [
  'LLC',
  'S-Corp',
  'C-Corp',
  'Partnership',
  'Sole proprietorship',
  'Non-profit',
  'Other',
];

const inputBase = {
  width: '100%',
  padding: '11px 13px',
  fontFamily: 'var(--font-sans)',
  fontSize: 14.5,
  color: 'var(--fg-1)',
  background: 'var(--mvg-white)',
  border: '1px solid var(--border-default)',
  borderRadius: 'var(--radius-md)',
  outline: 'none',
  transition: 'border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard)',
  boxSizing: 'border-box',
};

function FormField({ label, required, children, hint, full }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6, gridColumn: full ? '1 / -1' : 'auto' }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '0.005em' }}>
        {label}{required && <span style={{ color: 'var(--mvg-evergreen-700)', marginLeft: 4 }}>*</span>}
      </span>
      {children}
      {hint && <span style={{ fontSize: 12, color: 'var(--fg-3)', lineHeight: 1.4 }}>{hint}</span>}
    </label>
  );
}

function FormSection({ eyebrow, title, children }) {
  return (
    <fieldset style={{ border: 'none', padding: 0, margin: 0, marginBottom: 28 }}>
      <legend style={{ padding: 0, marginBottom: 14 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', color: 'var(--mvg-evergreen-700)', textTransform: 'uppercase' }}>{eyebrow}</div>
        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 19, fontWeight: 700, color: 'var(--fg-1)', marginTop: 4, letterSpacing: '-0.01em' }}>{title}</div>
      </legend>
      {children}
    </fieldset>
  );
}

function ServiceCheckbox({ value, defaultChecked }) {
  const [checked, setChecked] = useState(!!defaultChecked);
  return (
    <label style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 13px',
      background: checked ? 'var(--mvg-evergreen-50)' : 'var(--mvg-white)',
      border: `1px solid ${checked ? 'var(--mvg-evergreen)' : 'var(--border-default)'}`,
      borderRadius: 'var(--radius-md)',
      cursor: 'pointer',
      transition: 'all var(--dur-fast) var(--ease-standard)',
      fontSize: 14, color: 'var(--fg-1)', fontWeight: 500,
      userSelect: 'none',
    }}>
      <input
        type="checkbox"
        name="services[]"
        value={value}
        checked={checked}
        onChange={(e) => setChecked(e.target.checked)}
        style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }}
      />
      <span style={{
        width: 18, height: 18, borderRadius: 4,
        background: checked ? 'var(--mvg-evergreen)' : 'transparent',
        border: checked ? 'none' : '1.5px solid var(--border-default)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        color: '#fff',
      }}>{checked && <Icon.Check size={12}/>}</span>
      <span>{value}</span>
    </label>
  );
}

function ConsultationModal({ isOpen, onClose, prefillService }) {
  const { isMobile } = useBreakpoint();
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');
  const [closing, setClosing] = useState(false);
  const [countdown, setCountdown] = useState(3);
  const formRef = useRef(null);
  const firstInputRef = useRef(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;

  const beginClose = () => {
    setClosing(true);
    setTimeout(() => { setClosing(false); closeRef.current(); }, 200);
  };

  useEffect(() => {
    if (isOpen) {
      setStatus('idle');
      setError('');
      setClosing(false);
      setCountdown(3);
      const t = setTimeout(() => { try { firstInputRef.current?.focus(); } catch {} }, 80);
      return () => clearTimeout(t);
    }
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') beginClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [isOpen]);

  useEffect(() => {
    if (status !== 'success') return;
    setCountdown(3);
    const tick = setInterval(() => setCountdown(c => Math.max(0, c - 1)), 1000);
    const closer = setTimeout(() => beginClose(), 3000);
    return () => { clearInterval(tick); clearTimeout(closer); };
  }, [status]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'submitting' || status === 'success') return;
    setStatus('submitting');
    setError('');
    try {
      const data = new FormData(formRef.current);
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: 'POST',
        body: data,
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        setStatus('success');
      } else {
        const j = await res.json().catch(() => ({}));
        setError((j?.errors || []).map(x => x.message).filter(Boolean).join(', ') || 'Submission failed. Please try again.');
        setStatus('error');
      }
    } catch {
      setError('Network error. Please try again or email hello@mountainviewgroupllc.com.');
      setStatus('error');
    }
  };

  if (!isOpen && !closing) return null;

  const onBackdropClick = (e) => {
    if (e.target === e.currentTarget) beginClose();
  };

  const focusStyle = (e) => {
    e.currentTarget.style.borderColor = 'var(--mvg-evergreen)';
    e.currentTarget.style.boxShadow = 'var(--shadow-focus)';
  };
  const blurStyle = (e) => {
    e.currentTarget.style.borderColor = 'var(--border-default)';
    e.currentTarget.style.boxShadow = 'none';
  };
  const inputProps = { onFocus: focusStyle, onBlur: blurStyle };

  return (
    <div
      onClick={onBackdropClick}
      role="dialog"
      aria-modal="true"
      aria-labelledby="cm-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(20, 38, 25, 0.55)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: isMobile ? 'flex-end' : 'center', justifyContent: 'center',
        padding: isMobile ? 0 : 24,
        animation: closing ? 'cmFadeOut 200ms var(--ease-standard) forwards' : 'cmFadeIn 240ms var(--ease-standard)',
      }}
    >
      <div style={{
        background: 'var(--bg-page)',
        width: '100%', maxWidth: 720,
        maxHeight: isMobile ? '94vh' : '90vh',
        borderRadius: isMobile ? '16px 16px 0 0' : 'var(--radius-xl)',
        boxShadow: 'var(--shadow-xl)',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
        animation: closing ? 'cmScaleOut 200ms var(--ease-standard) forwards' : 'cmScaleIn 280ms var(--ease-standard)',
      }}>
        {/* Header */}
        <div style={{
          background: 'linear-gradient(135deg, #1B3125 0%, #274734 60%, #2C597A 100%)',
          color: '#fff',
          padding: isMobile ? '22px 22px 24px' : '28px 32px 30px',
          position: 'relative', flexShrink: 0,
        }}>
          <svg viewBox="0 0 200 60" preserveAspectRatio="none" aria-hidden="true" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, width: '100%', height: 36, opacity: 0.18 }}>
            <path d="M0 60 L0 40 L30 22 L55 36 L85 12 L115 30 L145 8 L175 26 L200 18 L200 60 Z" fill="#7AADC1"/>
          </svg>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative' }}>
            <div>
              <div style={{ display: 'inline-block', background: 'var(--mvg-evergreen)', color: '#fff', fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '5px 10px', borderRadius: 3, marginBottom: 12 }}>Free Consultation</div>
              <h2 id="cm-title" style={{ margin: 0, fontFamily: 'var(--font-serif)', fontSize: isMobile ? 22 : 26, fontWeight: 700, lineHeight: 1.2, letterSpacing: '-0.015em', color: '#fff' }}>
                Let's talk about your accounting needs.
              </h2>
              <p style={{ margin: '8px 0 0', fontSize: 14, color: 'rgba(247,249,250,0.78)', lineHeight: 1.5, maxWidth: 520 }}>
                A few quick questions help us prepare for our conversation. Mike will follow up within one business day.
              </p>
            </div>
            <button
              type="button"
              aria-label="Close"
              onClick={beginClose}
              style={{
                width: 38, height: 38,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: 'rgba(247,249,250,0.12)', border: '1px solid rgba(247,249,250,0.2)',
                borderRadius: 999, color: '#fff', cursor: 'pointer', padding: 0,
                flexShrink: 0, marginLeft: 14,
                transition: 'background var(--dur-fast) var(--ease-standard)',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(247,249,250,0.22)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(247,249,250,0.12)'}
            ><Icon.X size={18}/></button>
          </div>
        </div>

        {/* Body */}
        <div style={{ overflowY: 'auto', flex: 1, padding: isMobile ? '24px 22px 28px' : '32px 36px 36px' }}>
          {status === 'success' ? (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '32px 12px 24px', minHeight: 320, justifyContent: 'center' }}>
              <div style={{
                width: 80, height: 80, borderRadius: 999,
                background: 'var(--mvg-evergreen-50)', color: 'var(--mvg-evergreen-700)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginBottom: 22,
                animation: 'cmCheckPop 480ms var(--ease-standard)',
              }}>
                <Icon.Check size={42}/>
              </div>
              <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 24, fontWeight: 700, color: 'var(--fg-1)', margin: '0 0 10px', letterSpacing: '-0.01em' }}>
                Thanks — your request is in.
              </h3>
              <p style={{ fontSize: 15.5, color: 'var(--fg-2)', lineHeight: 1.6, margin: '0 0 18px', maxWidth: 440 }}>
                Mike will review your information and reach out within one business day to schedule your consultation.
              </p>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)', letterSpacing: '0.06em' }}>
                Closing in {countdown}…
              </div>
            </div>
          ) : (
            <form ref={formRef} onSubmit={handleSubmit} noValidate>
              <input type="hidden" name="_subject" value="New consultation request — Mountain View Group"/>

              <FormSection eyebrow="01 · Contact" title="How can we reach you?">
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
                  <FormField label="Full name" required>
                    <input ref={firstInputRef} type="text" name="name" required style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Email" required>
                    <input type="email" name="email" required style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Phone">
                    <input type="tel" name="phone" style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Company name" required>
                    <input type="text" name="company" required style={inputBase} {...inputProps}/>
                  </FormField>
                </div>
              </FormSection>

              <FormSection eyebrow="02 · Company basics" title="A little about your business.">
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
                  <FormField label="Industry" required>
                    <input type="text" name="industry" required placeholder="e.g. Manufacturing, healthcare" style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Years in operation">
                    <input type="text" name="years_operating" placeholder="e.g. 7 years" style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Legal structure">
                    <select name="legal_structure" defaultValue="" style={{ ...inputBase, appearance: 'none', backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%232C597A\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'><polyline points=\'6 9 12 15 18 9\'/></svg>")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', backgroundSize: '16px', paddingRight: 36 }} {...inputProps}>
                      <option value="" disabled>Select one…</option>
                      {LEGAL_STRUCTURES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  </FormField>
                  <FormField label="Owners / partners" hint="Names or count is fine.">
                    <input type="text" name="owners" placeholder="e.g. Jane Doe + 1 partner" style={inputBase} {...inputProps}/>
                  </FormField>
                  <FormField label="Software / systems currently in use" full hint="e.g. QuickBooks Online, NetSuite, Sage Intacct, Excel.">
                    <textarea name="software" rows={2} style={{ ...inputBase, resize: 'vertical', fontFamily: 'var(--font-sans)' }} {...inputProps}/>
                  </FormField>
                </div>
              </FormSection>

              <FormSection eyebrow="03 · Services" title="Which services are you considering?">
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 10 }}>
                  {SERVICES_OPTIONS.map(s => (
                    <ServiceCheckbox key={s} value={s} defaultChecked={prefillService && (s.toLowerCase() === prefillService.toLowerCase() || prefillService.toLowerCase().includes(s.toLowerCase()) || s.toLowerCase().includes(prefillService.toLowerCase()))}/>
                  ))}
                </div>
                <div style={{ marginTop: 16 }}>
                  <FormField label="Anything else we should know?" hint="Timing, recent changes, audit deadlines, pain points — whatever's on your mind.">
                    <textarea name="notes" rows={3} style={{ ...inputBase, resize: 'vertical', fontFamily: 'var(--font-sans)' }} {...inputProps}/>
                  </FormField>
                </div>
              </FormSection>

              {error && (
                <div role="alert" style={{
                  background: 'var(--status-danger-bg)', color: 'var(--status-danger)',
                  border: '1px solid #F5C2BD', borderRadius: 'var(--radius-md)',
                  padding: '12px 14px', fontSize: 13.5, lineHeight: 1.5, marginBottom: 18,
                }}>{error}</div>
              )}

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', borderTop: '1px solid var(--border-subtle)', paddingTop: 22 }}>
                <div style={{ fontSize: 12, color: 'var(--fg-3)', lineHeight: 1.5, maxWidth: 360 }}>
                  Your information goes straight to Mike — no marketing lists, no spam.
                </div>
                <div style={{ display: 'flex', gap: 10 }}>
                  <button type="button" onClick={beginClose} style={{
                    padding: '13px 20px', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14,
                    background: 'transparent', color: 'var(--fg-2)', border: '1px solid var(--border-default)',
                    borderRadius: 'var(--radius-md)', cursor: 'pointer',
                  }}>Cancel</button>
                  <button type="submit" disabled={status === 'submitting'} style={{
                    padding: '13px 22px', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14,
                    background: 'var(--action-primary-bg)', color: '#fff', border: 'none',
                    borderRadius: 'var(--radius-md)',
                    cursor: status === 'submitting' ? 'wait' : 'pointer',
                    opacity: status === 'submitting' ? 0.75 : 1,
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    transition: 'background var(--dur-fast) var(--ease-standard)',
                  }}
                    onMouseEnter={e => { if (status !== 'submitting') e.currentTarget.style.background = 'var(--action-primary-bg-hover)'; }}
                    onMouseLeave={e => e.currentTarget.style.background = 'var(--action-primary-bg)'}
                  >
                    {status === 'submitting' ? (
                      <>
                        <span style={{ width: 14, height: 14, borderRadius: 999, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', display: 'inline-block', animation: 'cmSpin 700ms linear infinite' }}/>
                        Sending…
                      </>
                    ) : (
                      <>Submit request <Icon.ArrowRight size={14}/></>
                    )}
                  </button>
                </div>
              </div>
            </form>
          )}
        </div>
      </div>

      <style>{`
        @keyframes cmFadeIn  { from { opacity: 0 } to { opacity: 1 } }
        @keyframes cmFadeOut { from { opacity: 1 } to { opacity: 0 } }
        @keyframes cmScaleIn  { from { opacity: 0; transform: translateY(12px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
        @keyframes cmScaleOut { from { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 0; transform: translateY(8px) scale(0.985); } }
        @keyframes cmSpin     { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes cmCheckPop { 0% { transform: scale(0.4); opacity: 0; } 60% { transform: scale(1.08); opacity: 1; } 100% { transform: scale(1); opacity: 1; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { SiteNav, SiteFooter, ConsultationModal });
