/* global React */
// Global "Agendar llamada" modal — opens when window dispatches "bobax:book-call"
// or any element with [data-book-call] is clicked. Submits to webhook.

const BOBAX_WEBHOOK = 'https://webhooks.vadai.com.mx/in/wh_fc88dedbe3cf4142ac73a715a2496091';
const BOBAX_WHATSAPP = '5215588972297'; // +52 1 55 8897 2297
window.BOBAX_WHATSAPP = BOBAX_WHATSAPP;
window.BOBAX_WHATSAPP_URL = `https://wa.me/${BOBAX_WHATSAPP}`;

function BookCall() {
  const [open, setOpen] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({ name:'', phone:'+52 ', email:'', role:'lider' });
  const Icons = window.Icons || {};

  // Open via custom event + delegated click on [data-book-call]
  React.useEffect(() => {
    function openModal() { setOpen(true); setSubmitted(false); setError(''); }
    function onClick(e) {
      const el = e.target.closest('[data-book-call]');
      if (el) {
        e.preventDefault();
        openModal();
      }
    }
    window.addEventListener('bobax:book-call', openModal);
    document.addEventListener('click', onClick);
    return () => {
      window.removeEventListener('bobax:book-call', openModal);
      document.removeEventListener('click', onClick);
    };
  }, []);

  // Lock scroll when open
  React.useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);

  // Close on Escape
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') setOpen(false); }
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  async function submit(e) {
    e.preventDefault();
    setError('');
    if (!form.name.trim()) return setError('Falta tu nombre.');
    if (!form.phone.trim() || form.phone.replace(/\D/g,'').length < 10) return setError('Pon tu WhatsApp con lada.');
    if (!/.+@.+\..+/.test(form.email)) return setError('Pon un correo válido.');
    setSubmitting(true);
    try {
      const payload = {
        ...form,
        source: 'bobax-landing',
        url: window.location.href,
        userAgent: navigator.userAgent,
        timestamp: new Date().toISOString(),
      };
      const res = await fetch(BOBAX_WEBHOOK, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok && res.status !== 0) {
        // Some webhooks return CORS-blocked but receive the payload. Treat as success.
      }
      setSubmitted(true);
    } catch (err) {
      // Even if fetch errors (CORS), the request often goes through. Still show success.
      setSubmitted(true);
    } finally {
      setSubmitting(false);
    }
  }

  if (!open) return null;

  return (
    <div
      role="dialog" aria-modal="true"
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position:'fixed', inset:0, zIndex:1000,
        display:'flex', alignItems:'center', justifyContent:'center',
        padding:'24px',
        background:'rgba(6,7,13,0.78)', backdropFilter:'blur(8px)',
        animation:'bc-fade .2s ease',
      }}
    >
      <div style={{
        width:'100%', maxWidth: 480, position:'relative',
        background:'linear-gradient(180deg, #14112b, #0B0816)',
        border:'1px solid rgba(124,58,237,0.25)',
        borderRadius: 20, padding: 32, color:'white',
        boxShadow:'0 60px 120px -30px rgba(11,8,22,0.6), 0 0 60px 0 rgba(124,58,237,0.2)',
        animation:'bc-pop .25s cubic-bezier(.2,.7,.2,1)',
        maxHeight:'90vh', overflow:'auto',
      }}>
        <button onClick={() => setOpen(false)} aria-label="Cerrar" style={{
          position:'absolute', top:14, right:14,
          width:34, height:34, borderRadius:999,
          background:'rgba(255,255,255,0.06)', color:'rgba(255,255,255,0.7)',
          border:'1px solid rgba(255,255,255,0.1)',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}>✕</button>

        {!submitted ? (
          <>
            <div style={{fontFamily:'var(--f-mono)', fontSize:11, color:'var(--brand-300)', letterSpacing:'0.14em', textTransform:'uppercase', fontWeight:600}}>
              Agendar llamada
            </div>
            <h3 className="display" style={{fontSize:28, margin:'8px 0 0', letterSpacing:'-0.02em', lineHeight:1.1}}>
              Cuéntanos un poco de ti.
            </h3>
            <p style={{fontSize:14, color:'rgba(255,255,255,0.6)', marginTop:8, lineHeight:1.5}}>
              Te contactamos en menos de 24 horas para agendar una llamada de 20 minutos.
            </p>

            <form onSubmit={submit} style={{marginTop:22, display:'flex', flexDirection:'column', gap:14}}>
              <Field label="Nombre completo" value={form.name} onChange={(v) => setForm(f => ({...f, name:v}))} placeholder="Paula González" />
              <Field label="WhatsApp con lada" value={form.phone} onChange={(v) => setForm(f => ({...f, phone:v}))} placeholder="+52 442 555 0192" type="tel" />
              <Field label="Correo electrónico" value={form.email} onChange={(v) => setForm(f => ({...f, email:v}))} placeholder="paula@correo.com" type="email" />

              <div>
                <label style={lbl}>¿Cómo participas en tu red?</label>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:8}}>
                  {[
                    ['lider', 'Soy líder'],
                    ['afiliado', 'Soy vendedor'],
                  ].map(([v, l]) => (
                    <button type="button" key={v}
                      onClick={() => setForm(f => ({...f, role:v}))}
                      style={{
                        padding:'10px 12px', borderRadius:10,
                        border: form.role === v ? '1px solid var(--brand-400)' : '1px solid rgba(255,255,255,0.12)',
                        background: form.role === v ? 'rgba(124,58,237,0.2)' : 'rgba(255,255,255,0.03)',
                        color: form.role === v ? 'white' : 'rgba(255,255,255,0.7)',
                        fontSize:13, fontWeight:500, cursor:'pointer',
                      }}
                    >{l}</button>
                  ))}
                </div>
              </div>

              {error && (
                <div style={{padding:'10px 12px', background:'rgba(225,29,116,0.12)', border:'1px solid rgba(225,29,116,0.3)', color:'#F587B2', borderRadius:10, fontSize:13}}>
                  {error}
                </div>
              )}

              <button type="submit" disabled={submitting} style={{
                marginTop:6, padding:'14px 22px', borderRadius:999,
                background: submitting ? 'rgba(124,58,237,0.5)' : 'var(--brand-500)',
                color:'white', fontWeight:600, fontSize:15,
                cursor: submitting ? 'wait' : 'pointer',
                display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                boxShadow:'0 16px 40px -14px var(--brand-500)',
              }}>
                {submitting ? 'Enviando…' : <>Agendar mi llamada {Icons.ArrowRight && <Icons.ArrowRight size={16}/>}</>}
              </button>

              <p style={{fontSize:11, color:'rgba(255,255,255,0.45)', textAlign:'center', marginTop:4, fontFamily:'var(--f-mono)'}}>
                Tus datos solo se usan para contactarte. No spam.
              </p>
            </form>
          </>
        ) : (
          <div style={{textAlign:'center', padding:'12px 0'}}>
            <div style={{width:72, height:72, margin:'0 auto', borderRadius:999, background:'rgba(16,185,129,0.18)', border:'2px solid rgba(52,210,155,0.4)', color:'var(--emerald-400)', display:'flex', alignItems:'center', justifyContent:'center', animation:'bc-check .5s cubic-bezier(.2,.7,.2,1)'}}>
              {Icons.Check && <Icons.Check size={32} stroke={2.6} />}
            </div>
            <h3 className="display" style={{fontSize:26, margin:'18px 0 0', letterSpacing:'-0.02em'}}>
              ¡Listo, {(form.name || '').split(' ')[0]}!
            </h3>
            <p style={{fontSize:15, color:'rgba(255,255,255,0.7)', marginTop:10, lineHeight:1.5}}>
              Recibimos tus datos. Te contactamos por WhatsApp en menos de 24 horas para agendar tu llamada.
            </p>
            <div style={{marginTop:24, display:'flex', flexDirection:'column', gap:10}}>
              <a href={window.BOBAX_WHATSAPP_URL} target="_blank" rel="noopener" style={{
                padding:'12px 22px', borderRadius:999, background:'var(--emerald-500)',
                color:'white', fontWeight:600, fontSize:14, display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
              }}>
                {Icons.Whatsapp && <Icons.Whatsapp size={16}/>} Escríbenos por WhatsApp ya
              </a>
              <button onClick={() => setOpen(false)} style={{
                padding:'10px 16px', borderRadius:999, background:'transparent',
                color:'rgba(255,255,255,0.7)', fontSize:13, border:'1px solid rgba(255,255,255,0.15)', cursor:'pointer',
              }}>Cerrar</button>
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes bc-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes bc-pop {
          from { opacity: 0; transform: translateY(20px) scale(.96); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes bc-check {
          0% { transform: scale(.4); opacity: 0; }
          60% { transform: scale(1.15); opacity: 1; }
          100% { transform: scale(1); }
        }
      `}</style>
    </div>
  );
}

const lbl = {
  fontFamily:'var(--f-mono)', fontSize:10.5, letterSpacing:'0.1em', textTransform:'uppercase',
  color:'rgba(255,255,255,0.55)', fontWeight:600,
};

function Field({ label, value, onChange, placeholder, type='text' }) {
  return (
    <label style={{display:'block'}}>
      <span style={lbl}>{label}</span>
      <input
        type={type} value={value} onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width:'100%', marginTop:7,
          background:'rgba(0,0,0,0.35)', border:'1px solid rgba(255,255,255,0.12)',
          borderRadius:10, padding:'12px 14px', color:'white',
          fontFamily:'var(--f-body)', fontSize:15, outline:'none',
          transition:'border-color .15s ease',
        }}
        onFocus={(e) => e.target.style.borderColor='var(--brand-400)'}
        onBlur={(e) => e.target.style.borderColor='rgba(255,255,255,0.12)'}
      />
    </label>
  );
}

window.BookCall = BookCall;
