// WhatsApp launcher with desktop fallback modal.
// On mobile: opens app directly via wa.me.
// On desktop: shows a modal with 3 options (WhatsApp Web, copy number, email)
// so the flow doesn't break if the user's browser/network blocks api.whatsapp.com.

const CYGNUS_PHONE = '595971223423';
const CYGNUS_EMAIL = 'contacto@cygnus.com.py';

function isMobileDevice() {
  if (typeof navigator === 'undefined') return false;
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function WhatsAppLauncher({ children, message, location, style, className, onMouseEnter, onMouseLeave, ariaLabel }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);

  const text = message || 'Hola Cygnus, me gustaría consultarles sobre…';
  const waMobile = `whatsapp://send?phone=${CYGNUS_PHONE}&text=${encodeURIComponent(text)}`;
  const waMe = `https://wa.me/${CYGNUS_PHONE}?text=${encodeURIComponent(text)}`;
  const waWeb = `https://web.whatsapp.com/send?phone=${CYGNUS_PHONE}&text=${encodeURIComponent(text)}`;
  const mailto = `mailto:${CYGNUS_EMAIL}?subject=${encodeURIComponent('Consulta desde web')}&body=${encodeURIComponent(text)}`;

  const handleClick = (e) => {
    e.preventDefault();
    try { if (window.gtag) window.gtag('event', 'whatsapp_click', { location: location || 'unknown' }); } catch (err) {}
    if (isMobileDevice()) {
      // Mobile: try the app, fall back to wa.me which the OS opens in the app
      window.location.href = waMe;
      return;
    }
    setOpen(true);
  };

  const copyNumber = async () => {
    try {
      await navigator.clipboard.writeText('+' + CYGNUS_PHONE);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      // ignore
    }
  };

  return (
    <>
      <a
        href={waMe}
        onClick={handleClick}
        target="_blank"
        rel="noopener"
        aria-label={ariaLabel}
        className={className}
        style={style}
        onMouseEnter={onMouseEnter}
        onMouseLeave={onMouseLeave}
      >
        {children}
      </a>

      {open && (
        <div
          role="dialog"
          aria-modal="true"
          onClick={() => setOpen(false)}
          style={{
            position: 'fixed', inset: 0, zIndex: 100,
            background: 'rgba(8, 18, 24, 0.72)',
            backdropFilter: 'blur(8px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 24,
            animation: 'wa-fade 0.2s ease-out',
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              background: 'var(--bg)',
              border: '1px solid rgba(255,255,255,0.12)',
              maxWidth: 440, width: '100%',
              padding: '36px 32px',
              position: 'relative',
              animation: 'wa-pop 0.25s cubic-bezier(.2,.8,.3,1)',
            }}
          >
            <button
              onClick={() => setOpen(false)}
              aria-label="Cerrar"
              style={{
                position: 'absolute', top: 12, right: 12,
                width: 32, height: 32,
                background: 'transparent', color: 'var(--muted)',
                border: 'none', cursor: 'pointer',
                fontSize: 20, lineHeight: 1,
              }}
            >×</button>

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <span style={{
                width: 40, height: 40, borderRadius: '50%',
                background: '#25D366', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff" aria-hidden="true">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/>
                </svg>
              </span>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, margin: 0, color: 'var(--fg)' }}>
                Hablemos por WhatsApp
              </h3>
            </div>

            <p style={{ color: 'var(--muted)', fontSize: 14, lineHeight: 1.5, marginTop: 12, marginBottom: 24 }}>
              Elegí cómo querés comunicarte con nosotros:
            </p>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {/* WhatsApp Web direct */}
              <a
                href={waWeb}
                target="_blank"
                rel="noopener"
                onClick={() => { try { if (window.gtag) window.gtag('event', 'whatsapp_route', { route: 'web' }); } catch (e) {} }}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '14px 18px',
                  background: '#25D366', color: '#0a2a16',
                  fontSize: 14, fontWeight: 600, letterSpacing: 0.2, textDecoration: 'none',
                  fontFamily: 'var(--font-display)',
                  transition: 'transform 0.15s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.transform = 'translateY(-1px)'}
                onMouseLeave={(e) => e.currentTarget.style.transform = 'none'}
              >
                <span>Abrir WhatsApp Web</span>
                <span aria-hidden="true">→</span>
              </a>

              {/* wa.me universal */}
              <a
                href={waMe}
                target="_blank"
                rel="noopener"
                onClick={() => { try { if (window.gtag) window.gtag('event', 'whatsapp_route', { route: 'wame' }); } catch (e) {} }}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '14px 18px',
                  background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.12)',
                  color: 'var(--fg)',
                  fontSize: 14, fontWeight: 500, textDecoration: 'none',
                  fontFamily: 'var(--font-display)',
                  transition: 'background 0.15s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.04)'}
              >
                <span>Abrir app de WhatsApp</span>
                <span aria-hidden="true">↗</span>
              </a>

              {/* Copy number */}
              <button
                onClick={copyNumber}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '14px 18px',
                  background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.12)',
                  color: 'var(--fg)',
                  fontSize: 14, fontWeight: 500, fontFamily: 'var(--font-display)',
                  cursor: 'pointer', textAlign: 'left',
                  transition: 'background 0.15s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.04)'}
              >
                <span>{copied ? '✓ Número copiado' : `Copiar número  +${CYGNUS_PHONE}`}</span>
                <span aria-hidden="true">{copied ? '' : '⎘'}</span>
              </button>

              {/* Email fallback */}
              <a
                href={mailto}
                onClick={() => { try { if (window.gtag) window.gtag('event', 'whatsapp_route', { route: 'email' }); } catch (e) {} }}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '14px 18px',
                  background: 'transparent',
                  color: 'var(--muted)',
                  fontSize: 13, fontWeight: 500, textDecoration: 'none',
                  fontFamily: 'var(--font-mono)',
                  transition: 'color 0.15s',
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = 'var(--fg)'}
                onMouseLeave={(e) => e.currentTarget.style.color = 'var(--muted)'}
              >
                <span>O escribinos por email</span>
                <span aria-hidden="true">{CYGNUS_EMAIL}</span>
              </a>
            </div>

            <p style={{ marginTop: 20, fontSize: 12, color: 'var(--muted)', lineHeight: 1.5, fontFamily: 'var(--font-mono)' }}>
              Si tu navegador bloquea WhatsApp Web, copiá el número y escribinos desde tu teléfono.
            </p>
          </div>
        </div>
      )}
    </>
  );
}

// inject modal animation styles once
(function injectWaStyles() {
  if (document.getElementById('wa-launcher-styles')) return;
  const s = document.createElement('style');
  s.id = 'wa-launcher-styles';
  s.textContent = `
    @keyframes wa-fade { from { opacity: 0; } to { opacity: 1; } }
    @keyframes wa-pop  { from { opacity: 0; transform: translateY(8px) scale(0.98); } to { opacity: 1; transform: none; } }
  `;
  document.head.appendChild(s);
})();

Object.assign(window, { WhatsAppLauncher });
