/* eslint-disable */
// Shared gated-PDF download modal.
// Exposes window.openGatedPdf(src, title) which mounts a form modal,
// and on submit triggers the actual file download.

(function () {
  const { useState, useEffect } = React;

  function GatedPdfModal({ src, title, onClose }) {
    const [form, setForm] = useState({ fn: '', ln: '', email: '', org: '', role: 'Facilities / Operations', consent: true, newsletter: true });
    const upd = (k, v) => setForm((f) => ({ ...f, [k]: v }));
    const valid = form.fn && form.ln && form.email.includes('@') && form.org && form.consent;

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

    const submit = () => {
      if (!valid) return;
      // Trigger download
      const a = document.createElement('a');
      a.href = src;
      a.download = (src.split('/').pop() || 'document.pdf');
      a.target = '_blank';
      a.rel = 'noopener';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      onClose({ submitted: true, name: form.fn });
    };

    const lbl = { fontSize: 12, fontWeight: 700, color: '#1F1F1F', display: 'block', marginBottom: 4 };
    const inp = { width: '100%', padding: '11px 13px', border: '1px solid #D4D4D4', borderRadius: 6, fontSize: 14, fontFamily: 'inherit', background: '#fff', outline: 'none', boxSizing: 'border-box' };

    return (
      <div onClick={() => onClose()} style={{ position: 'fixed', inset: 0, background: 'rgba(15,15,15,.62)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 24 }}>
        <div onClick={(e) => e.stopPropagation()} style={{ background: '#fff', borderRadius: 14, maxWidth: 560, width: '100%', overflow: 'hidden', boxShadow: '0 24px 64px rgba(0,0,0,.32)', position: 'relative', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
          <button onClick={() => onClose()} aria-label="Close" style={{ position: 'absolute', top: 14, right: 14, width: 32, height: 32, background: 'transparent', border: 0, color: '#6B6B6B', fontSize: 24, cursor: 'pointer', lineHeight: 1, zIndex: 2 }}>×</button>
          <div style={{ padding: '28px 36px 20px', borderBottom: '1px solid #E5E5E5', background: '#FAFAFA' }}>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '.12em', textTransform: 'uppercase', color: '#009530', marginBottom: 8 }}>Free download · PDF</div>
            <h3 style={{ fontSize: 19, fontWeight: 800, color: '#0F0F0F', margin: 0, lineHeight: 1.3, paddingRight: 32 }}>{title || 'Download the case study'}</h3>
            <p style={{ fontSize: 13, color: '#6B6B6B', marginTop: 8, lineHeight: 1.5, marginBottom: 0 }}>Tell us a bit about you and we'll send the PDF straight to your browser.</p>
          </div>
          <div style={{ padding: '22px 36px 28px', overflowY: 'auto' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div><label style={lbl}>First name *</label><input style={inp} value={form.fn} onChange={(e) => upd('fn', e.target.value)} /></div>
              <div><label style={lbl}>Last name *</label><input style={inp} value={form.ln} onChange={(e) => upd('ln', e.target.value)} /></div>
            </div>
            <div style={{ marginTop: 12 }}><label style={lbl}>Work email *</label><input type="email" style={inp} value={form.email} onChange={(e) => upd('email', e.target.value)} /></div>
            <div style={{ marginTop: 12 }}><label style={lbl}>Organization *</label><input style={inp} value={form.org} onChange={(e) => upd('org', e.target.value)} placeholder="Agency, district, institution, or operator" /></div>
            <div style={{ marginTop: 12 }}><label style={lbl}>Role</label>
              <select style={inp} value={form.role} onChange={(e) => upd('role', e.target.value)}>
                <option>Facilities / Operations</option>
                <option>Sustainability / Energy</option>
                <option>IT / OT</option>
                <option>Procurement / Finance</option>
                <option>Executive / Director</option>
                <option>Other</option>
              </select>
            </div>
            <label style={{ marginTop: 14, display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 12, color: '#4D4D4D', lineHeight: 1.5, cursor: 'pointer' }}>
              <input type="checkbox" checked={form.consent} onChange={(e) => upd('consent', e.target.checked)} style={{ marginTop: 3, accentColor: '#009530' }} />
              <span>I agree to receive communications from Schneider Electric and have read the <a href="https://www.se.com/ww/en/about-us/legal/privacy-policy.jsp" target="_blank" rel="noopener" style={{ color: '#009530', fontWeight: 700 }}>Privacy Policy</a>.</span>
            </label>
            
            <button disabled={!valid} onClick={submit} style={{ marginTop: 16, width: '100%', background: valid ? '#3DCD58' : '#B3B3B3', color: '#fff', border: 0, fontWeight: 700, padding: '13px', borderRadius: 6, fontSize: 14.5, cursor: valid ? 'pointer' : 'not-allowed', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              Submit and download PDF
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Mount point + global trigger
  let mountEl = null;
  let root = null;

  function ensureMount() {
    if (mountEl) return;
    mountEl = document.createElement('div');
    mountEl.id = '__gated_pdf_mount';
    document.body.appendChild(mountEl);
    root = ReactDOM.createRoot ? ReactDOM.createRoot(mountEl) : null;
  }

  function close() {
    ensureMount();
    if (root) root.render(null);
    else ReactDOM.unmountComponentAtNode(mountEl);
  }

  window.openGatedPdf = function (src, title) {
    if (!src) return;
    ensureMount();
    const el = React.createElement(GatedPdfModal, { src: src, title: title, onClose: close });
    if (root) root.render(el);
    else ReactDOM.render(el, mountEl);
  };
})();
