// Web3Forms access key — get yours free (no signup) at https://web3forms.com
// Paste your key here. Safe to commit: it's rate-limited & domain-locked server-side.
const WEB3FORMS_ACCESS_KEY = '85293180-6d2e-4d4e-979f-592161a5c540';

function ContactModal({ open, onClose }) {
  const [hover, setHover] = React.useState(false);
  const [closeHover, setCloseHover] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);

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

  React.useEffect(() => {
    if (open) { setSent(false); setError(null); setSending(false); }
  }, [open]);

  if (!open) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError(null); 

    const formData = new FormData(e.target);
    formData.append('access_key', WEB3FORMS_ACCESS_KEY);
    formData.append('subject', 'New Rayzor contact form submission');
    formData.append('from_name', 'Rayzor Website');

    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        body: formData
      });
      const data = await res.json();
      if (data.success) {
        setSent(true);
      } else {
        setError(data.message || 'Something went wrong. Please try again.');
      }
    } catch (err) {
      setError('Network error. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:200,
      background:'rgba(22,23,23,0.72)', backdropFilter:'blur(8px)', WebkitBackdropFilter:'blur(8px)',
      display:'flex', alignItems:'center', justifyContent:'center',
      padding:'24px',
      animation:'rz-modal-fade 220ms cubic-bezier(.22,1,.36,1) both'
    }}>
      <div className="rz-contact-modal" onClick={(e)=>e.stopPropagation()} style={{
        background:'#F9FAFB', color:'#25282C',
        width:'100%', maxWidth:560, padding:'48px 52px',
        border:'1px solid rgba(55,60,66,0.20)', position:'relative',
        animation:'rz-modal-rise 320ms cubic-bezier(.22,1,.36,1) both'
      }}>
        <button onClick={onClose} aria-label="Close"
          onMouseEnter={()=>setCloseHover(true)} onMouseLeave={()=>setCloseHover(false)}
          style={{
            position:'absolute', top:18, right:18,
            background:'transparent', border:'none', cursor:'pointer',
            font:'400 22px/1 var(--rz-font-mono)',
            color: closeHover ? '#f73f34' : '#5D656E',
            padding:'8px 12px',
            transition:'color 220ms ease'
          }}>×</button>

        <div style={{ font:'400 12px/1 var(--rz-font-mono)', color:'#5D656E', letterSpacing:'0.16em', marginBottom:14 }}>
          <span className="rz-accent-dot"/>CONTACT
        </div>
        <div style={{ font:'700 32px/1.05 var(--rz-font-display)', letterSpacing:'-0.01em', marginBottom:8 }}>
          Let's talk.
        </div>
        <div style={{ font:'400 14px/1.55 var(--rz-font-mono)', color:'#5D656E', marginBottom:28 }}>
          Tell us a bit about your rink, your team, or what you're hoping to build with us.
        </div>

        {sent ? (
          <div>
            <div style={{
              border:'1px solid rgba(247,63,52,0.45)', padding:'24px 28px',
              font:'400 15px/1.55 var(--rz-font-mono)', color:'#25282C',
              marginBottom:20
            }}>
              <span className="rz-accent-dot"/>Message queued. We'll be in touch at the email you provided.
            </div>
            <CloseButton onClose={onClose}/>
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <ContactField label="Name" name="name" type="text" required/>
            <ContactField label="Email" name="email" type="email" required/>
            <ContactField label="Organization" name="org" type="text"/>
            <ContactField label="Message" name="message" textarea required/>
            <div style={{ height:8 }}/>
            <button type="submit" disabled={sending}
              onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
              style={{
                background: sending ? '#5D656E' : (hover ? '#f73f34' : '#25282C'),
                color:'#F9FAFB', border:'none', cursor: sending ? 'wait' : 'pointer',
                padding:'14px 28px',
                font:'400 13px/1 var(--rz-font-mono)', letterSpacing:'0.12em', textTransform:'uppercase',
                transform: hover && !sending ? 'translateY(-1px)' : 'translateY(0)',
                transition:'background 280ms ease, transform 280ms cubic-bezier(.22,1,.36,1)'
              }}>{sending ? 'Sending…' : 'Send message →'}</button>
            {error && (
              <div style={{
                marginTop:16, padding:'12px 16px',
                border:'1px solid rgba(247,63,52,0.45)',
                font:'400 13px/1.5 var(--rz-font-mono)', color:'#25282C'
              }}>{error}</div>
            )}
          </form>
        )}
      </div>
    </div>
  );
}

function CloseButton({ onClose }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button type="button" onClick={onClose}
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{
        background: hover ? '#f73f34' : '#25282C',
        color:'#F9FAFB', border:'none', cursor:'pointer',
        padding:'14px 28px',
        font:'400 13px/1 var(--rz-font-mono)', letterSpacing:'0.12em', textTransform:'uppercase',
        transform: hover ? 'translateY(-1px)' : 'translateY(0)',
        transition:'background 280ms ease, transform 280ms cubic-bezier(.22,1,.36,1)'
      }}>Close →</button>
  );
}

function ContactField({ label, name, type='text', textarea=false, required=false }) {
  const [focus, setFocus] = React.useState(false);
  const inputStyle = {
    width:'100%', padding:'12px 0', background:'transparent',
    border:'none',
    borderBottom:`1px solid ${focus ? '#f73f34' : 'rgba(55,60,66,0.20)'}`,
    font:'400 15px/1.4 var(--rz-font-mono)', color:'#25282C',
    outline:'none', resize: textarea ? 'vertical' : 'none',
    transition:'border-color 220ms ease',
    fontFamily:'inherit'
  };
  return (
    <div style={{ marginBottom:18 }}>
      <label style={{
        display:'block',
        font:'400 11px/1 var(--rz-font-mono)', color:'#5D656E',
        letterSpacing:'0.16em', textTransform:'uppercase', marginBottom:6
      }}>{label}{required && <span style={{ color:'#f73f34' }}> *</span>}</label>
      {textarea
        ? <textarea name={name} required={required} rows={3}
            onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)}
            style={inputStyle}/>
        : <input type={type} name={name} required={required}
            onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)}
            style={inputStyle}/>}
    </div>
  );
}

window.ContactModal = ContactModal;
