const { useState, useEffect } = React;

/* ── useIsMobile ─────────────────────────────────── */
const useIsMobile = (breakpoint = 768) => {
  const [mobile, setMobile] = useState(() => window.innerWidth < breakpoint);
  useEffect(() => {
    const handler = () => setMobile(window.innerWidth < breakpoint);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, [breakpoint]);
  return mobile;
};

/* ── Nav ─────────────────────────────────────────── */
const Nav = ({ page, setPage, onContact }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const isMobile = useIsMobile();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const links = [
    { id: 'empieza',     label: 'Empieza aquí' },
    { id: 'articulos',   label: 'Artículos' },
    { id: 'laboratorio', label: 'Laboratorio' },
    { id: 'sobre',       label: 'Sobre mí' },
  ];

  const go = (id) => { setPage(id); setOpen(false); window.scrollTo(0, 0); };

  const bar = (rot, ty, opacity = 1) => ({
    display: 'block', width: 22, height: 2, background: 'var(--primary)',
    borderRadius: 2, transformOrigin: 'center',
    transition: 'all 0.3s cubic-bezier(0.4,0,0.2,1)',
    transform: `rotate(${rot}deg) translateY(${ty}px)`,
    opacity,
  });

  return (
    <>
      <nav style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200,
        transition: 'all 0.35s ease',
        background: (scrolled || open) ? 'rgba(247,244,239,0.97)' : 'transparent',
        backdropFilter: (scrolled || open) ? 'blur(14px)' : 'none',
        borderBottom: (scrolled || open) ? '1px solid rgba(45,90,79,0.09)' : 'none',
      }}>
        <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 64 }}>
          <button onClick={() => go('home')} style={{ display: 'flex', alignItems: 'baseline', gap: 6, background: 'none', border: 'none', cursor: 'pointer' }}>
            <span style={{ fontFamily: 'Playfair Display', fontStyle: 'italic', fontSize: 19, color: 'var(--primary)', fontWeight: 600 }}>
              la consulta
            </span>
            <span style={{ fontSize: 10, fontWeight: 500, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--primary-light)' }}>
              de javi
            </span>
          </button>

          {!isMobile && (
            <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
              {links.map(l => (
                <button key={l.id} onClick={() => go(l.id)} style={{
                  padding: '8px 16px', borderRadius: 8, fontSize: 14,
                  fontWeight: page === l.id ? 500 : 400,
                  color: page === l.id ? 'var(--primary)' : 'var(--text-mid)',
                  background: page === l.id ? 'rgba(45,90,79,0.08)' : 'transparent',
                  transition: 'all 0.2s', border: 'none', cursor: 'pointer',
                }}>
                  {l.label}
                </button>
              ))}
              <button onClick={() => onContact && onContact()} style={{
                marginLeft: 8, padding: '10px 22px', borderRadius: 9, fontSize: 14,
                fontWeight: 500, background: 'var(--primary)', color: 'var(--white)',
                transition: 'all 0.25s', border: 'none', cursor: 'pointer',
              }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--primary-mid)'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 20px rgba(45,90,79,0.25)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'var(--primary)'; e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}
              >
                Déjame tu consulta
              </button>
            </div>
          )}

          {isMobile && (
            <button
              onClick={() => setOpen(o => !o)}
              aria-label={open ? 'Cerrar menú' : 'Abrir menú'}
              style={{
                width: 40, height: 40, display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 5,
                background: 'none', border: 'none', cursor: 'pointer', borderRadius: 8,
                padding: 0,
              }}
            >
              <span style={open ? bar(45, 7)   : bar(0, 0)} />
              <span style={open ? bar(0, 0, 0) : bar(0, 0)} />
              <span style={open ? bar(-45, -7) : bar(0, 0)} />
            </button>
          )}
        </div>
      </nav>

      {isMobile && (
        <>
          <div
            onClick={() => setOpen(false)}
            style={{
              position: 'fixed', inset: 0, zIndex: 190,
              background: 'rgba(26,43,38,0.3)',
              backdropFilter: 'blur(2px)',
              opacity: open ? 1 : 0,
              pointerEvents: open ? 'all' : 'none',
              transition: 'opacity 0.3s ease',
            }}
          />
          <div style={{
            position: 'fixed', top: 64, left: 0, right: 0, zIndex: 195,
            background: 'rgba(247,244,239,0.98)',
            backdropFilter: 'blur(16px)',
            borderBottom: '1px solid var(--border)',
            transform: open ? 'translateY(0)' : 'translateY(-8px)',
            opacity: open ? 1 : 0,
            pointerEvents: open ? 'all' : 'none',
            transition: 'all 0.32s cubic-bezier(0.4,0,0.2,1)',
            padding: '16px 0 24px',
          }}>
            <div className="container" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {links.map((l, i) => (
                <button key={l.id} onClick={() => go(l.id)} style={{
                  padding: '14px 16px', borderRadius: 10, fontSize: 16,
                  fontWeight: page === l.id ? 600 : 400,
                  color: page === l.id ? 'var(--primary)' : 'var(--text)',
                  background: page === l.id ? 'rgba(45,90,79,0.07)' : 'transparent',
                  textAlign: 'left', border: 'none', cursor: 'pointer',
                  transition: 'all 0.2s',
                  transform: open ? 'translateX(0)' : 'translateX(-12px)',
                  transitionDelay: `${i * 40}ms`,
                  fontFamily: 'DM Sans',
                }}
                  onMouseEnter={e => e.currentTarget.style.background = 'rgba(45,90,79,0.06)'}
                  onMouseLeave={e => e.currentTarget.style.background = page === l.id ? 'rgba(45,90,79,0.07)' : 'transparent'}
                >
                  {l.label}
                </button>
              ))}
              <div style={{ height: 1, background: 'var(--border)', margin: '8px 0 12px' }} />
              <button onClick={() => { setOpen(false); onContact && onContact(); }} style={{
                padding: '14px 20px', borderRadius: 12,
                background: 'var(--primary)', color: 'var(--white)',
                fontSize: 15, fontWeight: 500, border: 'none', cursor: 'pointer',
                fontFamily: 'DM Sans', textAlign: 'center',
                transform: open ? 'translateX(0)' : 'translateX(-12px)',
                transition: 'all 0.2s', transitionDelay: `${links.length * 40}ms`,
              }}>
                ✉ Déjame tu consulta
              </button>
            </div>
          </div>
        </>
      )}
    </>
  );
};

/* ── Footer ───────────────────────────────────────── */
const Footer = ({ setPage }) => {
  const go = (id) => { setPage(id); window.scrollTo(0, 0); };
  return (
    <footer style={{ background: 'var(--primary)', color: 'rgba(255,255,255,0.75)', padding: '56px 0 32px', marginTop: 'auto' }}>
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 40, marginBottom: 48 }}>
          <div>
            <div style={{ fontFamily: 'Playfair Display', fontStyle: 'italic', fontSize: 22, color: '#fff', marginBottom: 10 }}>
              la consulta de javi
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.7, maxWidth: 260, opacity: 0.7 }}>
              Psicología honesta para quien quiere entenderse mejor.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 60 }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', marginBottom: 16 }}>
                Secciones
              </div>
              {[['empieza', 'Empieza aquí'], ['articulos', 'Artículos'], ['laboratorio', 'Laboratorio'], ['sobre', 'Sobre mí']].map(([id, label]) => (
                <div key={id} style={{ marginBottom: 10 }}>
                  <button onClick={() => go(id)} style={{ color: 'rgba(255,255,255,0.65)', fontSize: 14, transition: 'color 0.2s' }}
                    onMouseEnter={e => e.currentTarget.style.color = '#fff'}
                    onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.65)'}
                  >{label}</button>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{ borderTop: '1px solid rgba(255,255,255,0.1)', paddingTop: 24, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <span style={{ fontSize: 12, opacity: 0.4 }}>© 2026 Laconsultadejavi.es · Todos los derechos reservados</span>
          <span style={{ fontSize: 12, opacity: 0.4 }}>Hecho con honestidad, sin tecnicismos innecesarios</span>
        </div>
      </div>
    </footer>
  );
};

/* ── Shared UI ────────────────────────────────────── */
const Btn = ({ onClick, variant = 'solid', children, small }) => {
  const [hov, setHov] = useState(false);

  if (variant === 'ghost') {
    return (
      <button onClick={onClick} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
        background: 'transparent', color: hov ? 'var(--primary)' : 'var(--primary-mid)',
        border: 'none', fontSize: small ? 13 : 15, fontWeight: 500,
        padding: small ? '9px 0' : '13px 0', transition: 'all 0.2s',
        textDecoration: hov ? 'underline' : 'none',
      }}
        onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      >{children}</button>
    );
  }

  if (variant === 'outline') {
    return (
      <button onClick={onClick} className="btn-outline" style={{
        display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
        borderRadius: 10, fontWeight: 500,
        fontSize: small ? 13 : 15,
        padding: small ? '9px 18px' : '13px 26px',
        border: '1.5px solid var(--primary)',
        color: 'var(--primary)',
        background: 'transparent',
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>{children}</span>
      </button>
    );
  }

  return (
    <button onClick={onClick} className="btn-solid" style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
      borderRadius: 10, fontWeight: 500,
      fontSize: small ? 13 : 15,
      padding: small ? '9px 18px' : '13px 26px',
      color: 'var(--white)', border: 'none',
      letterSpacing: '0.01em',
    }}>
      {children}
    </button>
  );
};

const SectionLabel = ({ children }) => (
  <div className="label-tag" style={{ marginBottom: 18 }}>{children}</div>
);

const Card = ({ children, onClick, hover = true, style = {} }) => {
  const [hov, setHov] = useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => hover && setHov(true)}
      onMouseLeave={() => hover && setHov(false)}
      style={{
        background: 'var(--white)',
        borderRadius: 'var(--radius-lg)',
        border: '1px solid var(--border)',
        boxShadow: hov ? 'var(--shadow-md)' : 'var(--shadow)',
        transform: hov && onClick ? 'translateY(-3px)' : 'translateY(0)',
        transition: 'all 0.25s ease',
        cursor: onClick ? 'pointer' : 'default',
        ...style,
      }}
    >
      {children}
    </div>
  );
};

/* ── Contact Modal ────────────────────────────────── */
const ContactModal = ({ onClose }) => {
  const [name, setName]       = useState('');
  const [email, setEmail]     = useState('');
  const [msg, setMsg]         = useState('');
  const [sent, setSent]       = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError]     = useState('');

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

    try {
      const res = await fetch('/api/v1/contacts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), email: email.trim(), message: msg.trim() }),
      });

      const json = await res.json();

      if (!res.ok) {
        const detail = json?.error?.message || 'Error al enviar. Inténtalo de nuevo.';
        setError(detail);
        setSending(false);
        return;
      }

      setSent(true);
    } catch (_) {
      setError('No se pudo conectar con el servidor. Comprueba tu conexión.');
    } finally {
      setSending(false);
    }
  };

  const inputStyle = {
    width: '100%', padding: '12px 16px', borderRadius: 10, fontSize: 15,
    border: '1.5px solid var(--border)', background: 'var(--white)',
    fontFamily: 'DM Sans', color: 'var(--text)', outline: 'none',
    transition: 'border-color 0.2s',
  };

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 300,
        background: 'rgba(26,43,38,0.45)', backdropFilter: 'blur(6px)',
        animation: 'fadeUp 0.2s ease',
      }} />

      <div style={{
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        zIndex: 400, width: 'min(520px, 92vw)',
        background: 'var(--white)', borderRadius: 20,
        boxShadow: '0 24px 80px rgba(26,43,38,0.2)',
        animation: 'fadeUp 0.3s ease',
        overflow: 'hidden',
      }}>
        <div style={{ background: 'var(--primary)', padding: '28px 32px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontFamily: 'Playfair Display', fontStyle: 'italic', fontSize: 22, color: '#fff', marginBottom: 4 }}>
                Déjame tu consulta
              </div>
              <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', lineHeight: 1.6 }}>
                Es privada. Te respondo personalmente.
              </p>
            </div>
            <button onClick={onClose} style={{
              width: 32, height: 32, borderRadius: '50%', background: 'rgba(255,255,255,0.15)',
              color: '#fff', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: 'none', cursor: 'pointer', transition: 'background 0.2s', flexShrink: 0,
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.25)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.15)'}
            >✕</button>
          </div>
        </div>

        <div style={{ padding: '28px 32px 32px' }} className="contact-modal-body">
          {sent ? (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{ fontSize: 40, marginBottom: 16 }}>✉️</div>
              <h3 style={{ fontFamily: 'Playfair Display', fontSize: 22, marginBottom: 10 }}>¡Consulta enviada!</h3>
              <p style={{ color: 'var(--text-mid)', fontSize: 15, lineHeight: 1.7, marginBottom: 24 }}>
                He recibido tu mensaje. Te respondo en menos de 48 horas de forma personal y privada.
              </p>
              <button onClick={onClose} style={{
                padding: '11px 24px', borderRadius: 10, background: 'var(--primary)',
                color: 'var(--white)', border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 500,
                fontFamily: 'DM Sans',
              }}>Cerrar</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              <div style={{ display: 'flex', gap: 12, marginBottom: 14 }} className="contact-modal-row">
                <div style={{ flex: 1 }}>
                  <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-soft)', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Nombre</label>
                  <input required value={name} onChange={e => setName(e.target.value)} placeholder="Tu nombre" style={inputStyle}
                    onFocus={e => e.target.style.borderColor = 'var(--primary-light)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}
                  />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-soft)', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Email</label>
                  <input required type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="tu@email.com" style={inputStyle}
                    onFocus={e => e.target.style.borderColor = 'var(--primary-light)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}
                  />
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-soft)', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Tu consulta</label>
                <textarea required value={msg} onChange={e => setMsg(e.target.value)}
                  placeholder="Cuéntame qué está pasando, qué te preocupa o qué te gustaría trabajar. No hace falta que lo tengas claro."
                  rows={5}
                  style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }}
                  onFocus={e => e.target.style.borderColor = 'var(--primary-light)'}
                  onBlur={e => e.target.style.borderColor = 'var(--border)'}
                />
              </div>
              {error && (
                <div style={{ marginBottom: 14, padding: '10px 14px', borderRadius: 8, background: 'rgba(192,120,120,0.1)', border: '1px solid rgba(192,120,120,0.3)', color: '#C07878', fontSize: 13 }}>
                  {error}
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: 12, color: 'var(--text-soft)' }}>🔒 Solo lo leerás tú y yo</span>
                <button type="submit" disabled={sending} className="btn-solid" style={{
                  padding: '12px 28px', borderRadius: 10, color: 'var(--white)',
                  border: 'none', fontSize: 14, fontWeight: 500, cursor: sending ? 'not-allowed' : 'pointer',
                  fontFamily: 'DM Sans',
                  opacity: sending ? 0.7 : 1,
                }}>
                  {sending ? 'Enviando…' : 'Enviar consulta →'}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { Nav, Footer, Btn, SectionLabel, Card, ContactModal, useIsMobile });
