/* ANPA Quintán — Web navegable · chrome (header, footer, hero interior, router) */
const { Icon, LogoMark, Btn, t, LangToggle } = window;

/* rutas */
const ROUTES = ['inicio', 'quen', 'comedor', 'madrugadoras', 'extraescolares', 'documentos', 'novas', 'nova', 'contacto'];
function useRoute() {
  const parse = () => {
    const h = (window.location.hash || '#/inicio').replace(/^#\/?/, '') || 'inicio';
    return ROUTES.includes(h) ? h : 'inicio';
  };
  const [route, setRoute] = React.useState(parse());
  React.useEffect(() => {
    const on = () => { setRoute(parse()); window.scrollTo({ top: 0, behavior: 'auto' }); };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return route;
}

/* etiquetas de navegación (gl / es) */
const NAV = [
  { k: 'inicio', gl: 'Inicio', es: 'Inicio' },
  { k: 'quen', gl: 'Quen somos', es: 'Quiénes somos' },
  { k: 'servizos', gl: 'Servizos', es: 'Servicios', sub: [
    { k: 'comedor', gl: 'Comedor', es: 'Comedor', icon: 'utensils' },
    { k: 'madrugadoras', gl: 'Madrugadoras', es: 'Madrugadores', icon: 'sunrise' },
    { k: 'extraescolares', gl: 'Extraescolares', es: 'Extraescolares', icon: 'activity' },
  ] },
  { k: 'documentos', gl: 'Documentos', es: 'Documentos' },
  { k: 'novas', gl: 'Novas', es: 'Noticias' },
];
const SERVIZOS_KEYS = ['comedor', 'madrugadoras', 'extraescolares'];

/* ---------- Barra de avisos ---------- */
function SiteAviso() {
  return (
    <a href="#/novas" className="aviso">
      <div className="wrap">
        <span className="chip chip-gold" style={{ flexShrink: 0 }}><Icon name="bell" style={{ width: 14, height: 14 }} /> {t('Aviso', 'Aviso')}</span>
        <span className="aviso-txt">{t('Asemblea xeral o 12 de xuño ás 18:00 no salón de actos.', 'Asamblea general el 12 de junio a las 18:00 en el salón de actos.')}</span>
        <span className="aviso-more"><span>{t('Máis info', 'Más info')}</span><Icon name="arrow" style={{ width: 15, height: 15 }} /></span>
      </div>
    </a>
  );
}

/* ---------- Header ---------- */
function SiteHeader({ route }) {
  const [menu, setMenu] = React.useState(false);
  const [drop, setDrop] = React.useState(false);
  const dropRef = React.useRef(null);
  React.useEffect(() => {
    if (!drop) return;
    const off = (e) => { if (!dropRef.current || !dropRef.current.contains(e.target)) setDrop(false); };
    document.addEventListener('pointerdown', off, true);
    return () => document.removeEventListener('pointerdown', off, true);
  }, [drop]);
  React.useEffect(() => { setMenu(false); }, [route]);
  const isServ = SERVIZOS_KEYS.includes(route);

  return (
    <React.Fragment>
      <header className="hdr">
        <div className="wrap hdr-inner">
          <a href="#/inicio" className="hdr-brand">
            <LogoMark size={42} />
            <div><div className="bt">ANPA Quintán</div><div className="bs">CEIP Pedro Barrié de la Maza</div></div>
          </a>
          <nav className="hdr-nav">
            {NAV.map(n => n.sub ? (
              <div key={n.k} ref={dropRef} style={{ position: 'relative' }}>
                <a href="#/comedor" onClick={(e) => { e.preventDefault(); setDrop(d => !d); }}
                  className={isServ ? 'active' : ''} style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
                  {t(n.gl, n.es)}<Icon name="chevron" style={{ width: 15, height: 15, opacity: .7, transform: drop ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }} />
                </a>
                {drop && (
                  <div style={{ position: 'absolute', top: 'calc(100% + 14px)', left: '50%', transform: 'translateX(-50%)', background: '#fff', borderRadius: 14, boxShadow: 'var(--sh-lg)', border: '1px solid var(--line-soft)', padding: 8, width: 230, zIndex: 70 }}>
                    {n.sub.map(s => (
                      <a key={s.k} href={`#/${s.k}`} onClick={() => setDrop(false)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px', borderRadius: 10, border: 0, color: 'var(--ink)' }}>
                        <span className={`svc-ico ic-${s.k === 'comedor' ? 'blue' : s.k === 'madrugadoras' ? 'gold' : 'green'}`} style={{ width: 34, height: 34, marginBottom: 0, borderRadius: 9 }}><Icon name={s.icon} style={{ width: 18, height: 18 }} /></span>
                        <span style={{ fontWeight: 700, fontSize: 15 }}>{t(s.gl, s.es)}</span>
                      </a>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <a key={n.k} href={`#/${n.k}`} className={route === n.k ? 'active' : ''}>{t(n.gl, n.es)}</a>
            ))}
          </nav>
          <div className="hdr-right">
            <LangToggle />
            <a href="#/contacto" className="hdr-cta"><Btn kind="primary" size="sm" icon="mail">{t('Contacto', 'Contacto')}</Btn></a>
          </div>
          <button className="burger" onClick={() => setMenu(true)} aria-label={t('Abrir menú', 'Abrir menú')}><Icon name="menu" style={{ width: 23, height: 23 }} /></button>
        </div>
      </header>

      {/* menú móbil */}
      <div className={`msheet${menu ? ' open' : ''}`} onClick={() => setMenu(false)}>
        <div className="msheet-panel" onClick={(e) => e.stopPropagation()}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}><LogoMark size={36} /><span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17 }}>ANPA Quintán</span></div>
            <button className="burger" style={{ display: 'inline-flex' }} onClick={() => setMenu(false)} aria-label={t('Pechar', 'Cerrar')}><Icon name="arrowUpRight" style={{ width: 20, height: 20, transform: 'rotate(45deg)' }} /></button>
          </div>
          {NAV.filter(n => !n.sub).slice(0, 2).map(n => (
            <a key={n.k} href={`#/${n.k}`} className={route === n.k ? 'active' : ''}>{t(n.gl, n.es)}</a>
          ))}
          <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-mute)', padding: '16px 8px 6px' }}>{t('Servizos', 'Servicios')}</div>
          {SERVIZOS_KEYS.map(k => {
            const s = NAV[2].sub.find(x => x.k === k);
            return <a key={k} href={`#/${k}`} className={route === k ? 'active' : ''} style={{ paddingLeft: 8 }}><span style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Icon name={s.icon} style={{ width: 19, height: 19, color: 'var(--blue-700)' }} />{t(s.gl, s.es)}</span></a>;
          })}
          {NAV.filter(n => !n.sub).slice(2).map(n => (
            <a key={n.k} href={`#/${n.k}`} className={route === n.k ? 'active' : ''}>{t(n.gl, n.es)}</a>
          ))}
          <div style={{ padding: '16px 8px 10px', borderTop: '1px solid var(--line-soft)', marginTop: 8 }}><LangToggle compact /></div>
          <a href="#/contacto" style={{ borderBottom: 0 }}><Btn kind="primary" icon="mail">{t('Escríbenos', 'Escríbenos')}</Btn></a>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ---------- Cabeceira de páxina interior ---------- */
function SitePageHero({ tone = 'blue', eyebrow, title, sub }) {
  return (
    <div className={`phero ${tone}`}>
      <div className="deco" style={{ right: -60, top: -50, width: 280, height: 280 }} />
      <div className="deco" style={{ right: 130, bottom: -110, width: 200, height: 200 }} />
      <div className="wrap phero-body">
        <div className="t-eyebrow" style={{ color: 'var(--gold)' }}>{eyebrow}</div>
        <h1>{title}</h1>
        {sub && <p className="t-lead" style={{ color: 'rgba(255,255,255,.86)', marginTop: 14 }}>{sub}</p>}
      </div>
    </div>
  );
}

/* ---------- Footer ---------- */
function SiteFooter() {
  const links = {
    [t('Navegación', 'Navegación')]: [[t('Inicio', 'Inicio'), 'inicio'], [t('Quen somos', 'Quiénes somos'), 'quen'], [t('Documentos', 'Documentos'), 'documentos'], [t('Novas e avisos', 'Noticias y avisos'), 'novas'], [t('Contacto', 'Contacto'), 'contacto']],
    [t('Servizos', 'Servicios')]: [[t('Comedor escolar', 'Comedor escolar'), 'comedor'], [t('Madrugadoras', 'Madrugadores'), 'madrugadoras'], [t('Extraescolares', 'Extraescolares'), 'extraescolares']],
  };
  return (
    <footer style={{ background: 'var(--blue-900)', color: '#fff', paddingBlock: '48px 26px' }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 36, paddingBottom: 32, borderBottom: '1px solid rgba(255,255,255,.12)' }}>
          <div style={{ minWidth: 220 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 13 }}><LogoMark size={44} chip /><div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 19 }}>ANPA Quintán</div></div>
            <p style={{ fontSize: 14.5, color: 'rgba(255,255,255,.7)', lineHeight: 1.6, maxWidth: 280 }}>{t('Asociación de Nais e Pais do CEIP Pedro Barrié de la Maza. Mondego — Sada, A Coruña.', 'Asociación de Madres y Padres del CEIP Pedro Barrié de la Maza. Mondego — Sada, A Coruña.')}</p>
            <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
              {[['facebook', 'https://www.facebook.com/profile.php?id=100063592357611'], ['instagram', '#'], ['mail', 'mailto:info@anpaquintan.org']].map(([s, href]) => (
                <a key={s} href={href} target="_blank" rel="noopener" style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,.1)', display: 'grid', placeItems: 'center', color: '#fff' }}><Icon name={s} style={{ width: 19, height: 19 }} /></a>
              ))}
            </div>
          </div>
          {Object.entries(links).map(([title, items]) => (
            <div key={title}>
              <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)', marginBottom: 14 }}>{title}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {items.map(([l, k]) => <a key={l} href={`#/${k}`} style={{ fontSize: 15, color: 'rgba(255,255,255,.82)' }}>{l}</a>)}
              </div>
            </div>
          ))}
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)', marginBottom: 14 }}>{t('Contacto', 'Contacto')}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <a href="mailto:info@anpaquintan.org" style={{ fontSize: 15, color: 'rgba(255,255,255,.82)', display: 'flex', gap: 9, alignItems: 'center' }}><Icon name="mail" style={{ width: 17, height: 17, color: 'var(--gold)' }} />info@anpaquintan.org</a>
              <span style={{ fontSize: 15, color: 'rgba(255,255,255,.82)', display: 'flex', gap: 9, alignItems: 'center' }}><Icon name="pin" style={{ width: 17, height: 17, color: 'var(--gold)' }} />{t('Rúa Miguel Pereiro Tacón s/n · Mondego, Sada', 'Rúa Miguel Pereiro Tacón s/n · Mondego, Sada')}</span>
              <a href="http://centros.edu.xunta.es/ceippedrobarriedelamaza/" target="_blank" rel="noopener" style={{ fontSize: 14, color: 'rgba(255,255,255,.7)', display: 'flex', gap: 9, alignItems: 'center' }}><Icon name="external" style={{ width: 17, height: 17, color: 'var(--gold)' }} />{t('Web do centro (Xunta)', 'Web del centro (Xunta)')}</a>
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, justifyContent: 'space-between', paddingTop: 20, fontSize: 13, color: 'rgba(255,255,255,.55)' }}>
          <span>© 2026 ANPA Quintán · CEIP Pedro Barrié de la Maza</span>
          <span>{t('Aviso legal · Privacidade', 'Aviso legal · Privacidad')}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { useRoute, ROUTES, SiteAviso, SiteHeader, SitePageHero, SiteFooter });
