/* Shared chrome: Header + Footer */

const { useAuth, AuthModal, logoutUser } = window;

// Smooth scroll to an anchor on the landing page.
// If we're NOT on the landing page, navigate to index.html#id first.
function smoothNavTo(e, id) {
  const path = window.location.pathname;
  const onLanding = path.endsWith('/') || path.endsWith('/index.html') || path === '';
  if (!onLanding) {
    // let the browser follow href="#id" by replacing with full path
    e.preventDefault();
    window.location.href = `index.html#${id}`;
    return;
  }
  const target = document.getElementById(id);
  if (target) {
    e.preventDefault();
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    // update hash without re-jumping
    history.replaceState(null, '', `#${id}`);
  }
}

const SiteHeader = ({ active = 'inicio' }) => {
  const user = useAuth();
  const [authOpen, setAuthOpen] = React.useState(false);
  const [authMode, setAuthMode] = React.useState('login');
  const [menuOpen, setMenuOpen] = React.useState(false);

  const openLogin = () => { setAuthMode('login'); setAuthOpen(true); };
  const openRegister = () => { setAuthMode('register'); setAuthOpen(true); };

  return (
    <>
    <header className="site-header">
      <div className="container header-inner">
        <a className="brand" href="index.html">
          <div className="brand-mark">
            <img src="assets/bristol-mark.jpeg" alt="Bristol Academy" />
          </div>
          <div className="brand-text">
            <div className="top">Bristol Academy</div>
            <div className="name">Aptis Exam Trainer</div>
          </div>
        </a>
        <nav className="nav">
          <a className={active==='inicio' ? 'active' : ''} href="#inicio" onClick={(e) => smoothNavTo(e, 'inicio')}>Inicio</a>
          <a className={active==='examenes' ? 'active' : ''} href="#examenes" onClick={(e) => smoothNavTo(e, 'examenes')}>Exámenes</a>
          <a href="https://bristolprivatelessons.es/aptis-cursos-en-granada-ingles/" target="_blank" rel="noopener">Cursos Aptis</a>
          <a className={active==='privacidad' ? 'active' : ''} href="privacidad.html">Privacidad</a>
          <a className={active==='contacto' ? 'active' : ''} href="#contacto" onClick={(e) => smoothNavTo(e, 'contacto')}>Contacto</a>
        </nav>
        <div className="header-cta">
          {user && (
            <div style={{ position: 'relative' }}>
              <button onClick={() => setMenuOpen(o => !o)}
                className="btn btn-sm"
                style={{
                  background: 'var(--accent-soft)',
                  border: '1px solid var(--accent)',
                  color: 'var(--accent-strong)',
                  fontWeight: 600,
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                <span style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: 'var(--accent)', color: '#fff',
                  display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
                }}>{(user.name || user.email).charAt(0).toUpperCase()}</span>
                <span className="hide-mobile" style={{ maxWidth: 140, overflow: 'hidden',
                  textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {user.name || user.email}
                </span>
                <span style={{ fontSize: 10 }}>▾</span>
              </button>
              {menuOpen && (
                <>
                  <div onClick={() => setMenuOpen(false)} style={{
                    position: 'fixed', inset: 0, zIndex: 50,
                  }}></div>
                  <div style={{
                    position: 'absolute', right: 0, top: 'calc(100% + 8px)',
                    background: '#fff', border: '1px solid var(--line)',
                    borderRadius: 12, boxShadow: 'var(--shadow-lg)',
                    minWidth: 220, zIndex: 51, overflow: 'hidden',
                  }}>
                    <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line-soft)' }}>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{user.name || 'Mi cuenta'}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-muted)',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {user.email}
                      </div>
                    </div>
                    <a href="mi-cuenta.html" style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 16px', fontSize: 14, color: 'var(--ink)',
                    }}>
                      <Icon name="user" size={14} /> Mi cuenta
                    </a>
                    <a href="exam-1.html" style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 16px', fontSize: 14, color: 'var(--ink)',
                    }}>
                      <Icon name="play" size={14} /> Mi examen 1
                    </a>
                    <button onClick={() => { logoutUser(); setMenuOpen(false); }} style={{
                      display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                      padding: '10px 16px', fontSize: 14, color: 'var(--danger)',
                      background: 'transparent', border: 'none', borderTop: '1px solid var(--line-soft)',
                      cursor: 'pointer', textAlign: 'left',
                    }}>
                      <Icon name="arrow" size={14} style={{ transform: 'rotate(180deg)' }} /> Cerrar sesión
                    </button>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </header>
    <AuthModal open={authOpen} onClose={() => setAuthOpen(false)} initialMode={authMode} />
    </>
  );
};

const WHATSAPP_NUMBER = '34604935221';  // E.164 for wa.me link
const WHATSAPP_DISPLAY = '604 93 52 21';
const CONTACT_EMAIL = 'contacto@bristolprivatelessons.es';

const SiteFooter = () => {
  return (
    <footer className="site-footer" id="contacto">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="brand">
              <div className="brand-mark">
                <img src="assets/bristol-mark.jpeg" alt="Bristol Academy" />
              </div>
              <div className="brand-text">
                <div className="top">Bristol Academy</div>
                <div className="name">Aptis Exam Trainer</div>
              </div>
            </div>
            <p>
              Plataforma oficial de Bristol Academy para practicar Aptis General online.
              Simulacros completos creados por nuestro equipo docente en Granada.
            </p>
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
              <a style={{ display:'inline-flex', gap: 10, alignItems:'center' }} href={`mailto:${CONTACT_EMAIL}`}>
                <Icon name="mail" size={15} /> {CONTACT_EMAIL}
              </a>
              <a style={{ display:'inline-flex', gap: 10, alignItems:'center', color: '#25D366', fontWeight: 600 }}
                 href={`https://wa.me/${WHATSAPP_NUMBER}`} target="_blank" rel="noopener">
                <Icon name="phone" size={15} /> WhatsApp · {WHATSAPP_DISPLAY}
              </a>
              <a style={{ display:'inline-flex', gap: 10, alignItems:'center' }} href="https://bristolprivatelessons.es" target="_blank" rel="noopener">
                <Icon name="pin" size={15} /> Bristol Academy · Granada
              </a>
            </div>
          </div>

          <div className="footer-col">
            <h4>Plataforma</h4>
            <ul>
              <li><a href="index.html#examenes">Exámenes disponibles</a></li>
              <li><a href="exam-1.html">Examen gratuito</a></li>
              <li><a href="mi-cuenta.html">Mi cuenta</a></li>
              <li><a href="https://bristolprivatelessons.es/aptis-cursos-en-granada-ingles/" target="_blank" rel="noopener">Cursos Aptis Granada ↗</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Envíanos una consulta</h4>
            <form className="footer-form" onSubmit={(e) => { e.preventDefault(); alert('Consulta enviada. Te responderemos en menos de 24h.'); }}>
              <div className="footer-form-row">
                <input type="text" placeholder="Nombre" required />
                <input type="email" placeholder="Email" required />
              </div>
              <input type="tel" placeholder="Teléfono (opcional)" />
              <textarea placeholder="¿En qué podemos ayudarte?" required></textarea>
              <button type="submit" className="btn btn-primary">
                Enviar consulta <Icon name="arrow" size={14} />
              </button>
            </form>
          </div>
        </div>

        <div className="footer-disclaimer">
          <strong style={{ color: 'rgba(255,255,255,0.78)' }}>Aviso legal —</strong>{' '}
          Bristol Academy Aptis Exam Trainer es una plataforma independiente de práctica creada por
          Bristol Academy. Aptis es una marca perteneciente a sus respectivos titulares. Esta
          plataforma no está afiliada oficialmente ni avalada por British Council.
        </div>

        <div className="footer-bottom">
          <div>© {new Date().getFullYear()} Bristol Academy · Granada, España. Todos los derechos reservados.</div>
          <div style={{ display: 'flex', gap: 18 }}>
            <a href="privacidad.html">Aviso legal</a>
            <a href="privacidad.html">Privacidad</a>
            <a href="privacidad.html#cookies">Cookies</a>
          </div>
        </div>
      </div>
    </footer>
  );
};

// Floating WhatsApp button
const WhatsAppFloat = () => (
  <a href={`https://wa.me/${WHATSAPP_NUMBER}`} target="_blank" rel="noopener"
     aria-label="Contactar por WhatsApp"
     style={{
       position: 'fixed', bottom: 24, right: 24, zIndex: 60,
       width: 56, height: 56, borderRadius: '50%',
       background: '#25D366', color: '#fff',
       display: 'grid', placeItems: 'center',
       boxShadow: '0 10px 28px -8px rgba(37, 211, 102, 0.55), 0 4px 12px rgba(0,0,0,0.12)',
       transition: 'transform .2s',
     }}
     onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.08)'}
     onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
    <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor" 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-.347zM12.057 2C6.495 2 2 6.497 2 12.057c0 1.985.59 3.918 1.708 5.587L2 22l4.461-1.671A9.987 9.987 0 0 0 12.057 22c5.561 0 10.057-4.495 10.057-10.057C22.114 6.497 17.618 2 12.057 2z"/>
    </svg>
  </a>
);

window.SiteHeader = SiteHeader;
window.SiteFooter = SiteFooter;
window.WhatsAppFloat = WhatsAppFloat;
window.WHATSAPP_NUMBER = WHATSAPP_NUMBER;
window.WHATSAPP_DISPLAY = WHATSAPP_DISPLAY;
window.CONTACT_EMAIL = CONTACT_EMAIL;
