/* CTAButton — the "Check Your Territory" button used everywhere.
   Always opens the ZipModal on click. No inline input.
   2026-06-18: LIVE — opens modal, modal redirects to audits.pmhoa.pro/configure with the ZIP. */
const AUDITS_BASE_URL = 'https://audits.pmhoa.pro';
function CTAButton({ id, microcopy, fullWidth = false, source }) {
  const open = (e) => {
    e && e.preventDefault && e.preventDefault();
    const src = source || id || 'cta';
    window.dispatchEvent(new CustomEvent('pmhoa:open-zip-modal', { detail: { source: src } }));
  };
  return (
    <div style={{ display: 'grid', gap: 12, width: fullWidth ? '100%' : 'auto', maxWidth: fullWidth ? 'none' : 380 }}>
      <button id={id} onClick={open} className="cta-form__btn" style={{ width: '100%' }}>
        <span className="cta-form__btn-main">Check Your Territory</span>
        <span className="cta-form__btn-sub">Enter Your ZIP Codes</span>
      </button>
      {microcopy !== false && (
        <p className="cta-form__micro" style={{ margin: 0 }}>
          {microcopy || 'Free territory check. 5 min to confirm fit.'}
        </p>
      )}
    </div>
  );
}

/* ZipModal — single instance mounted at the App root.
   Listens for pmhoa:open-zip-modal events and presents a Typeform-style
   centered card. */
function ZipModal() {
  const [open, setOpen] = React.useState(false);
  const [val, setVal] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [source, setSource] = React.useState('homepage_cta');
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => {
      const src = (e && e.detail && e.detail.source) ? e.detail.source : 'homepage_cta';
      setSource(src);
      setSubmitted(false);
      setVal('');
      setOpen(true);
    };
    window.addEventListener('pmhoa:open-zip-modal', handler);
    return () => window.removeEventListener('pmhoa:open-zip-modal', handler);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    // focus input on open
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 80);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
      clearTimeout(t);
    };
  }, [open]);

  const submit = (e) => {
    e.preventDefault();
    const z = val.trim();
    if (!z || z.length < 5) return;
    setLoading(true);
    // Fire analytics events before redirect
    try {
      if (typeof window.fbq === 'function') window.fbq('track', 'Lead', { content_name: 'territory_zip_start', zip: z });
      if (typeof window.gtag === 'function') window.gtag('event', 'territory_zip_start', { event_category: 'engagement', zip: z });
    } catch (err) { /* tracking is best-effort */ }
    // Hand off to the audit tool — pre-selects this ZIP and skips Question 1
    // NOTE: audits.pmhoa.pro uses React Router's HashRouter, so routes
    // live behind /#/<route>. Sending the path-based form (/configure)
    // would land on the SPA's '*' catch-all and bounce to /report/demo-1.
    const utmMedium = `homepage_${source}`;
    const target = `${AUDITS_BASE_URL}/#/configure?startZip=${encodeURIComponent(z)}&utm_source=pmhoa.pro&utm_medium=${encodeURIComponent(utmMedium)}`;
    // Brief delay so the user sees the loading state before navigation
    setTimeout(() => { window.location.href = target; }, 350);
  };

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="zip-modal-title"
      onMouseDown={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(17,22,28,0.72)',
        backdropFilter: 'blur(6px)',
        zIndex: 100,
        display: 'grid', placeItems: 'center',
        padding: 24,
        animation: 'pmhoaFadeIn 160ms ease-out',
      }}
    >
      <div style={{
        position: 'relative',
        width: '100%',
        maxWidth: 560,
        background: 'white',
        borderRadius: 16,
        padding: 'clamp(32px, 4vw, 48px)',
        boxShadow: '0 40px 120px rgba(0,0,0,0.4)',
        animation: 'pmhoaSlideUp 240ms cubic-bezier(0.16,1,0.3,1)',
      }}>
        <button
          onClick={() => setOpen(false)}
          aria-label="Close"
          style={{
            position: 'absolute', top: 16, right: 16,
            width: 36, height: 36,
            border: 0, background: 'transparent',
            borderRadius: 8,
            cursor: 'pointer',
            display: 'grid', placeItems: 'center',
            color: 'var(--fg-muted)',
            transition: 'background 120ms ease, color 120ms ease',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--neutral-100)'; e.currentTarget.style.color = 'var(--fg)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-muted)'; }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        </button>

        {!submitted ? (
          <>
            <div style={{
              fontSize: 11, fontWeight: 800,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              color: 'var(--pmhoa-blue)',
              marginBottom: 16,
            }}>
              <span style={{ display: 'inline-block', width: 16, height: 1, background: 'currentColor', verticalAlign: 'middle', marginRight: 10, transform: 'translateY(-2px)' }} />
              Territory check · Step 1 of 2
            </div>
            <h2 id="zip-modal-title" style={{
              fontFamily: 'var(--font-display)',
              fontSize: 'clamp(28px, 3.4vw, 40px)',
              fontWeight: 800,
              letterSpacing: '-0.022em',
              lineHeight: 1.1,
              margin: '0 0 14px',
              textWrap: 'balance',
            }}>
              Enter your starting ZIP code.
            </h2>
            <p style={{
              fontSize: 16,
              lineHeight: 1.5,
              color: 'var(--fg-muted)',
              margin: '0 0 32px',
              maxWidth: '46ch',
            }}>
              We'll check availability in your area, then walk you through adding the rest of your service zone.
            </p>

            <form onSubmit={submit} style={{ display: 'grid', gap: 16 }}>
              <div className="cta-form__input-wrap">
                <label className="cta-form__label" htmlFor="modal-zip">
                  Starting ZIP code
                </label>
                <input
                  ref={inputRef}
                  id="modal-zip"
                  type="text"
                  inputMode="numeric"
                  placeholder="e.g., 90210"
                  value={val}
                  onChange={(e) => setVal(e.target.value)}
                  autoComplete="postal-code"
                  className="cta-form__input"
                  maxLength="5"
                  style={{ fontSize: 22, height: 64, fontWeight: 700, letterSpacing: '0.04em' }}
                />
              </div>
              <button type="submit" className="cta-form__btn" disabled={loading || val.length < 5}>
                <span className="cta-form__btn-main">{loading ? 'Loading territory…' : 'Continue'}</span>
                <span className="cta-form__btn-sub">{loading ? 'One moment' : 'Open the territory map'}</span>
              </button>
              <p className="cta-form__micro" style={{ margin: '4px 0 0', textAlign: 'center' }}>
                We only work with 2 contractors per territory per vertical.
              </p>
            </form>
          </>
        ) : (
          <div style={{ padding: '12px 0' }}>
            <div style={{
              width: 48, height: 48,
              borderRadius: 999,
              background: 'rgba(31,157,106,0.12)',
              color: 'var(--success)',
              display: 'grid', placeItems: 'center',
              fontSize: 24, fontWeight: 800,
              marginBottom: 20,
            }}>✓</div>
            <h2 style={{
              fontFamily: 'var(--font-display)',
              fontSize: 'clamp(26px, 3vw, 36px)',
              fontWeight: 800,
              letterSpacing: '-0.022em',
              lineHeight: 1.1,
              margin: '0 0 14px',
            }}>
              Got it — checking {val}.
            </h2>
            <p style={{
              fontSize: 16,
              lineHeight: 1.55,
              color: 'var(--fg-muted)',
              margin: '0 0 28px',
              maxWidth: '48ch',
            }}>
              We'll email you within 1 business day with your territory status and a short
              intake form for the rest of your service area.
            </p>
            <button onClick={() => setOpen(false)} className="btn btn--ghost" style={{ width: '100%', justifyContent: 'center', padding: '14px 22px' }}>
              Close
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.CTAButton = CTAButton;
window.ZipModal = ZipModal;
