// First-engagement email capture popup
// Triggers after first click/scroll/keydown anywhere on the page.
// Stores submission + dismiss state in localStorage so it never re-prompts.

function NewsletterPopup(){
  const STORAGE_KEY = 'thraxel-newsletter-popup-v1';
  const [open, setOpen] = React.useState(false);
  const [form, setForm] = React.useState({ name:'', email:'', phone:'', opt:true });
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(()=>{
    let prior;
    try { prior = localStorage.getItem(STORAGE_KEY); } catch(e){}
    if (prior) return; // already shown / dismissed / submitted

    let triggered = false;
    const trigger = () => {
      if (triggered) return;
      triggered = true;
      // Small delay so the click doesn't feel hijacked
      setTimeout(()=> setOpen(true), 450);
      cleanup();
    };
    const onClick = (e) => {
      // Don't fire on the popup itself or on links inside the nav opening within first frame
      if (e.target.closest && e.target.closest('.nl-popup')) return;
      trigger();
    };
    const onScroll = () => {
      if (window.scrollY > 200) trigger();
    };
    const onKey = () => trigger();

    window.addEventListener('click', onClick, { passive:true });
    window.addEventListener('scroll', onScroll, { passive:true });
    window.addEventListener('keydown', onKey, { passive:true });
    function cleanup(){
      window.removeEventListener('click', onClick);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('keydown', onKey);
    }
    return cleanup;
  },[]);

  const close = () => {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ dismissed:true, t:Date.now() })); } catch(e){}
    setOpen(false);
  };

  const submit = (e) => {
    e.preventDefault();
    setError('');
    if (!form.name.trim()) return setError('Please enter your name.');
    if (!/^\S+@\S+\.\S+$/.test(form.email)) return setError('Please enter a valid email.');
    if (!form.phone.trim() || form.phone.replace(/\D/g,'').length < 7) return setError('Please enter a valid phone number.');
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ submitted:true, t:Date.now(), email:form.email })); } catch(e){}
    setSubmitted(true);
    setTimeout(()=> setOpen(false), 2200);
  };

  if (!open) return null;

  return (
    <div className="nl-popup" role="dialog" aria-modal="true" aria-labelledby="nl-popup-title" style={{
      position:'fixed', inset:0, zIndex:9000,
      background:'rgba(0,0,0,0.78)', backdropFilter:'blur(6px)',
      display:'flex', alignItems:'center', justifyContent:'center',
      padding:'24px',
      animation:'nlFade 0.28s ease-out',
    }}>
      <div style={{
        position:'relative',
        width:'min(560px, 100%)',
        background:'linear-gradient(180deg, #0c0608 0%, #0a0a0a 100%)',
        border:'1px solid rgba(200,16,46,0.45)',
        boxShadow:'0 0 0 1px rgba(255,255,255,0.03), 0 30px 80px rgba(200,16,46,0.18), 0 0 120px rgba(200,16,46,0.12) inset',
        padding:'40px 40px 36px',
        animation:'nlPop 0.36s cubic-bezier(.2,.9,.3,1)',
      }}>
        {/* Close */}
        <button onClick={close} aria-label="Close" style={{
          position:'absolute', top:14, right:14,
          width:36, height:36, padding:0,
          background:'transparent', border:'1px solid #2a2a2e',
          color:'var(--thraxel-light-grey)',
          cursor:'pointer', fontFamily:'Orbitron,sans-serif', fontSize:14, lineHeight:1,
          display:'flex', alignItems:'center', justifyContent:'center',
          transition:'all .2s ease',
        }} onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--thraxel-red)'; e.currentTarget.style.color='#fff';}} onMouseLeave={e=>{e.currentTarget.style.borderColor='#2a2a2e'; e.currentTarget.style.color='var(--thraxel-light-grey)';}}>
          ×
        </button>

        {!submitted ? (
          <>
            <div className="eyebrow-red" style={{marginBottom:14}}>THRAXEL INSIDER</div>
            <h2 id="nl-popup-title" className="chrome-text" style={{fontSize:'clamp(28px,3.6vw,42px)', letterSpacing:'0.02em', lineHeight:1.05}}>
              Get on the list.
            </h2>
            <p style={{color:'var(--thraxel-light-grey)', fontSize:15, lineHeight:1.55, marginTop:14, maxWidth:'46ch'}}>
              Drop your details below for early access to seasonal install windows, member-only discounts, and the occasional behind-the-scenes from the field. No spam — that's a promise.
            </p>

            <form onSubmit={submit} style={{marginTop:24, display:'grid', gap:12}}>
              <NLInput label="Name" value={form.name} onChange={v=>setForm(f=>({...f, name:v}))} autoFocus/>
              <NLInput label="Email" type="email" value={form.email} onChange={v=>setForm(f=>({...f, email:v}))}/>
              <NLInput label="Phone" type="tel" value={form.phone} onChange={v=>setForm(f=>({...f, phone:v}))} placeholder="(555) 555-5555"/>

              <label style={{display:'flex', alignItems:'flex-start', gap:10, marginTop:6, cursor:'pointer', userSelect:'none'}}>
                <input type="checkbox" checked={form.opt} onChange={e=>setForm(f=>({...f, opt:e.target.checked}))} style={{
                  marginTop:3, accentColor:'var(--thraxel-red)', width:16, height:16, cursor:'pointer',
                }}/>
                <span style={{color:'var(--thraxel-light-grey)', fontSize:13, lineHeight:1.5}}>
                  Yes — keep me posted on news, discounts, and updates from Thraxel. I can unsubscribe any time.
                </span>
              </label>

              {error && <div style={{color:'var(--thraxel-red)', fontSize:13, marginTop:4, fontFamily:'Orbitron,sans-serif', letterSpacing:'0.05em'}}>{error}</div>}

              <div style={{display:'flex', gap:10, marginTop:14, alignItems:'center'}}>
                <button type="submit" className="btn-red" style={{flex:1}}>Join the list →</button>
                <button type="button" onClick={close} style={{
                  background:'transparent', border:'1px solid #2a2a2e', color:'var(--thraxel-light-grey)',
                  padding:'14px 18px', cursor:'pointer',
                  fontFamily:'Orbitron,sans-serif', fontSize:11, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase',
                  transition:'all .2s ease',
                }} onMouseEnter={e=>{e.currentTarget.style.color='#fff'; e.currentTarget.style.borderColor='#3a3a3e';}} onMouseLeave={e=>{e.currentTarget.style.color='var(--thraxel-light-grey)'; e.currentTarget.style.borderColor='#2a2a2e';}}>No thanks</button>
              </div>
            </form>
          </>
        ) : (
          <div style={{textAlign:'center', padding:'24px 8px'}}>
            <div style={{width:64, height:64, margin:'0 auto', borderRadius:'50%', border:'1.5px solid var(--thraxel-red)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 0 30px rgba(200,16,46,0.4)'}}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <h2 className="chrome-text" style={{fontSize:'clamp(24px,3vw,36px)', marginTop:20, letterSpacing:'0.02em'}}>You're in.</h2>
            <p style={{color:'var(--thraxel-light-grey)', fontSize:15, marginTop:10}}>Welcome to the inside. We'll be in touch.</p>
          </div>
        )}
      </div>

      <style>{`
        @keyframes nlFade { from{opacity:0} to{opacity:1} }
        @keyframes nlPop { from{opacity:0; transform:translateY(20px) scale(.96)} to{opacity:1; transform:translateY(0) scale(1)} }
        .nl-popup input::placeholder{color:#5a5a5e}
      `}</style>
    </div>
  );
}

function NLInput({ label, value, onChange, type='text', placeholder, autoFocus }){
  return (
    <label style={{display:'block'}}>
      <span style={{display:'block', fontFamily:'Orbitron,sans-serif', fontSize:10, fontWeight:700, letterSpacing:'0.18em', color:'var(--thraxel-light-grey)', marginBottom:6, textTransform:'uppercase'}}>{label}</span>
      <input
        type={type}
        value={value}
        autoFocus={autoFocus}
        placeholder={placeholder||''}
        onChange={e=>onChange(e.target.value)}
        style={{
          width:'100%', padding:'13px 14px',
          background:'#050505', border:'1px solid #2a2a2e',
          color:'#fff', fontFamily:'Inter,sans-serif', fontSize:15,
          outline:'none', transition:'border-color .15s ease, box-shadow .15s ease',
        }}
        onFocus={e=>{e.currentTarget.style.borderColor='var(--thraxel-red)'; e.currentTarget.style.boxShadow='0 0 0 3px rgba(200,16,46,0.15)';}}
        onBlur={e=>{e.currentTarget.style.borderColor='#2a2a2e'; e.currentTarget.style.boxShadow='none';}}
      />
    </label>
  );
}

Object.assign(window, { NewsletterPopup });
