// ============================================================================
// chrome.jsx — TopNav + MobileMenu + Footer + AnimatedName + router
//
// Desktop: name left, tabs centre, language right. Tabs in bold sans.
// Mobile : hamburger left, language right. Hamburger opens a fullscreen white
// panel listing the same items.
// Inspired by Tiago Madaleno (cover + nav layout) and Clara de Cápua
// (content organisation in lists).
// ============================================================================

const { useState: useStateChr, useEffect: useEffectChr } = React;

// ---- Router --------------------------------------------------------------
function parseHash() {
  const raw = (window.location.hash || '').replace(/^#\/?/, '');
  if (!raw) return { name: 'home', params: {} };
  const parts = raw.split('/').filter(Boolean);
  const [p0, p1] = parts;
  switch (p0) {
    case 'home':        return { name: 'home', params: {} };
    case 'sobre':       return { name: 'sobre', params: {} };
    case 'trabalhos':   return { name: p1 ? 'trabalhosCat' : 'trabalhos', params: { category: p1 } };
    case 'obra':        return { name: 'obra', params: { id: p1 } };
    case 'sons':        return { name: 'sons', params: {} };
    case 'som':         return { name: 'som', params: { id: p1 } };
    case 'exposicoes':  return { name: 'exposicoes', params: {} };
    case 'exposicao':   return { name: 'exposicao',  params: { id: p1 } };
    case 'contacto':    return { name: 'contacto', params: {} };
    case 'cv':          return { name: 'cv', params: {} };
    default:            return { name: 'home', params: {} };
  }
}
function go(path) { window.location.hash = path; }
function useRoute() {
  const [route, setRoute] = useStateChr(parseHash());
  useEffectChr(() => {
    const on = () => {
      setRoute(parseHash());
      window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return route;
}

// ---- Name (logo) ---------------------------------------------------------
function BrandName({ light }) {
  return (
    <a
      href="#/home"
      data-cursor-hover
      style={{
        fontFamily: 'var(--sans)',
        fontWeight: light ? 800 : 700,
        fontSize: light ? 21 : 14,
        letterSpacing: '-0.015em',
        color: light ? '#ffffff' : 'var(--ink)',
        whiteSpace: 'nowrap',
        textShadow: light ? '0 1px 14px rgba(0,0,0,0.18)' : 'none',
        transition: 'color 240ms ease',
      }}
      aria-label="Carolina Leal — início"
    >
      carolina leal
    </a>
  );
}

// ---- Hamburger ------------------------------------------------------------
function HamburgerIcon({ open, light }) {
  const color = light ? '#ffffff' : 'var(--ink)';
  const base = {
    position: 'absolute', left: 0, width: 22, height: 1.5,
    background: color,
    boxShadow: light ? '0 1px 4px rgba(0,0,0,0.2)' : 'none',
    transition: 'transform 380ms cubic-bezier(.7,0,.3,1), opacity 240ms ease, top 380ms cubic-bezier(.7,0,.3,1), background 240ms ease',
  };
  return (
    <span aria-hidden="true" style={{ position: 'relative', display: 'inline-block', width: 22, height: 14 }}>
      <span style={{ ...base, top: open ? 6.25 : 0, transform: open ? 'rotate(45deg)' : 'rotate(0deg)' }} />
      <span style={{ ...base, top: 6.25, opacity: open ? 0 : 1, transform: 'scaleX(0.85)' }} />
      <span style={{ ...base, top: open ? 6.25 : 12.5, transform: open ? 'rotate(-45deg)' : 'rotate(0deg)' }} />
    </span>
  );
}

// ---- TopNav --------------------------------------------------------------
function TopNav({ route, lang, setLang, onOpenMenu, menuOpen, transparent }) {
  const t = T[lang];
  const light = !!transparent;
  const whiteInk = '#ffffff';
  const tabWeight = 700;
  const whiteShadow = '0 1px 14px rgba(0,0,0,0.18)';

  const tabs = [
    { key: 'sobre',      label: t.nav.sobre,      href: '#/sobre',
      active: route.name === 'sobre' },
    { key: 'trabalhos',  label: t.nav.trabalhos,  href: '#/trabalhos',
      active: ['trabalhos', 'trabalhosCat', 'obra'].includes(route.name) },
    { key: 'sons',      label: t.nav.sons,      href: '#/sons',
      active: ['sons', 'som'].includes(route.name) },
    { key: 'exposicoes', label: t.nav.exposicoes, href: '#/exposicoes',
      active: ['exposicoes', 'exposicao'].includes(route.name) },
    { key: 'contacto',   label: t.nav.contacto,   href: '#/contacto',
      active: route.name === 'contacto' },
    { key: 'cv',         label: t.nav.cv,         href: '#/cv',
      active: route.name === 'cv' },
  ];

  /* ── Inner pages: stacked layout ── */
  if (!light) {
    return (
      <header style={{ position: 'sticky', top: 0, width: '100%', zIndex: 60, background: 'var(--bg)' }}>

        {/* Name row: [hamburger] [carolina leal] [PT·EN] */}
        <div className="topnav-inner-row">
          <div style={{ flex: 1 }}>
            <button
              className="topnav-burger"
              onClick={onOpenMenu}
              aria-label={menuOpen ? 'Fechar menu' : 'Abrir menu'}
              aria-expanded={menuOpen}
              data-cursor-hover
              style={{ display: 'none', alignItems: 'center', color: 'var(--ink)' }}
            >
              <HamburgerIcon open={menuOpen} light={false} />
            </button>
          </div>

          <a href="#/home" data-cursor-hover style={{
            fontFamily: 'var(--sans)', fontWeight: 700, fontSize: 15,
            letterSpacing: '-0.015em', color: 'var(--ink)', whiteSpace: 'nowrap',
          }}>carolina leal</a>

          <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
            <button
              onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}
              data-cursor-hover
              style={{
                fontFamily: 'var(--sans)', fontWeight: 700, fontSize: 10.5,
                letterSpacing: '0.03em', color: 'var(--ink)', opacity: 0.45,
                transition: 'opacity 240ms ease',
              }}
              onMouseOver={e => e.currentTarget.style.opacity = '1'}
              onMouseOut={e => e.currentTarget.style.opacity = '0.45'}
              aria-label="Toggle language"
            >{t.misc.language}</button>
          </div>
        </div>

        {/* Rule */}
        <div style={{ height: 1, background: 'rgba(26,26,26,0.1)' }} />

        {/* Nav tabs */}
        <nav className="topnav-inner-tabs">
          {tabs.map(tab => (
            <a key={tab.key} href={tab.href} data-cursor-hover
              style={{
                fontFamily: 'var(--sans)',
                fontWeight: tab.active ? 700 : 400,
                fontSize: 11, letterSpacing: '-0.005em',
                color: 'var(--ink)',
                opacity: tab.active ? 1 : 0.42,
                transition: 'opacity 240ms ease',
              }}
              onMouseOver={e => e.currentTarget.style.opacity = '1'}
              onMouseOut={e => e.currentTarget.style.opacity = tab.active ? '1' : '0.42'}
            >{tab.label}</a>
          ))}
        </nav>

        {/* Bottom border */}
        <div style={{ height: 1, background: 'rgba(26,26,26,0.07)' }} />

        <style>{`
          .topnav-inner-row {
            display: flex; align-items: center;
            padding: 16px 40px;
          }
          .topnav-inner-tabs {
            display: flex; justify-content: center;
            gap: 36px; padding: 12px 40px;
          }
          @media (max-width: 820px) {
            .topnav-inner-tabs { display: none !important; }
            .topnav-burger { display: inline-flex !important; }
          }
          @media (max-width: 540px) {
            .topnav-inner-row { padding: 14px 20px; }
          }
        `}</style>
      </header>
    );
  }

  /* ── Home: minimal fixed bar — hamburger (mobile) + PT/EN only ── */
  return (
    <header style={{
      position: 'fixed', top: 0, width: '100%', zIndex: 60,
      background: 'transparent', padding: '14px 40px',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        maxWidth: 1440, margin: '0 auto',
      }}>
        <button
          className="topnav-burger"
          onClick={onOpenMenu}
          aria-label={menuOpen ? 'Fechar menu' : 'Abrir menu'}
          aria-expanded={menuOpen}
          data-cursor-hover
          style={{ display: 'none', alignItems: 'center', color: '#ffffff' }}
        >
          <HamburgerIcon open={menuOpen} light={true} />
        </button>
        <div style={{ flex: 1 }} />
        <button
          onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}
          data-cursor-hover
          className="home-lang-btn"
          style={{
            fontFamily: 'var(--sans)', fontWeight: 800, fontSize: 13,
            letterSpacing: '0.03em', color: '#4e7c2f',
          }}
          aria-label="Toggle language"
        >{t.misc.language}</button>

      </div>
      <style>{`
        .home-lang-btn { margin-right: -84px; }
        @media (max-width: 820px) {
          .topnav-burger { display: inline-flex !important; }
          .home-lang-btn { margin-right: 8px; }
        }
        @media (max-width: 720px) {
          header { padding: 12px 20px !important; }
          .home-lang-btn { margin-right: 0; }
        }
      `}</style>
    </header>
  );
}

// ---- Mobile fullscreen menu ----------------------------------------------
function MobileMenu({ open, onClose, route, lang, setLang }) {
  const t = T[lang];
  const [worksOpen, setWorksOpen] = useStateChr(
    ['trabalhos', 'trabalhosCat', 'obra'].includes(route.name)
  );

  useEffectChr(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  useEffectChr(() => {
    if (open) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const isActive = (key) => {
    if (key === 'trabalhos') return ['trabalhos', 'trabalhosCat', 'obra'].includes(route.name);
    return route.name === key;
  };

  const item = (key, label, href, expander) => {
    const active = isActive(key);
    return (
      <a
        href={expander ? undefined : href}
        onClick={(e) => {
          if (expander) { e.preventDefault(); setWorksOpen(o => !o); return; }
          setTimeout(onClose, 220);
        }}
        data-cursor-hover
        style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          gap: 20, padding: '20px 0',
          color: 'var(--ink)',
        }}
      >
        <span style={{
          fontFamily: 'var(--sans)',
          fontWeight: 700,
          fontSize: 'clamp(28px, 7vw, 38px)',
          letterSpacing: '-0.02em',
          lineHeight: 1,
          opacity: active ? 1 : 0.55,
        }}>{label}</span>
        {expander && (
          <span style={{
            fontFamily: 'var(--mono)',
            fontSize: 14,
            color: 'var(--ink-2)',
            alignSelf: 'center',
          }}>
            {worksOpen ? '\u2212' : '+'}
          </span>
        )}
      </a>
    );
  };

  return (
    <div
      role="dialog" aria-modal="true" aria-label="Menu"
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'var(--bg)',
        transform: open ? 'translateY(0)' : 'translateY(-101%)',
        transition: 'transform 520ms cubic-bezier(.7,0,.3,1)',
        display: 'flex', flexDirection: 'column',
      }}
    >
      {/* Top bar */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '22px',
      }}>
        <a href="#/home" onClick={() => setTimeout(onClose, 220)}
           data-cursor-hover
           style={{
             fontFamily: 'var(--sans)',
             fontWeight: 700,
             fontSize: 17,
             letterSpacing: '-0.005em',
             color: 'var(--ink)',
           }}>carolina leal</a>
        <button
          onClick={onClose}
          data-cursor-hover
          aria-label="Fechar menu"
          style={{ position: 'relative', width: 22, height: 22 }}
        >
          <span style={{ position: 'absolute', left: 0, top: 10.25, width: 22, height: 1.5, background: 'var(--ink)', transform: 'rotate(45deg)' }} />
          <span style={{ position: 'absolute', left: 0, top: 10.25, width: 22, height: 1.5, background: 'var(--ink)', transform: 'rotate(-45deg)' }} />
        </button>
      </div>

      {/* Items */}
      <nav style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '12px 22px' }}>
        {item('sobre',      t.nav.sobre,      '#/sobre')}
        {item('trabalhos',  t.nav.trabalhos,  '#/trabalhos', true)}

        <div style={{
          overflow: 'hidden',
          maxHeight: worksOpen ? 600 : 0,
          opacity: worksOpen ? 1 : 0,
          transition: 'max-height 520ms cubic-bezier(.7,0,.3,1), opacity 320ms ease',
        }}>
          <div style={{ padding: '4px 0 18px 8px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <a href="#/trabalhos"
               onClick={() => setTimeout(onClose, 220)}
               data-cursor-hover
               style={{
                 fontFamily: 'var(--sans)', fontSize: 18,
                 color: route.name === 'trabalhos' ? 'var(--ink)' : 'var(--ink-2)',
               }}>— {t.works.all}</a>
            {CATEGORIES.map(c => {
              const active = route.name === 'trabalhosCat' && route.params.category === c.id;
              return (
                <a key={c.id} href={`#/trabalhos/${c.id}`}
                   onClick={() => setTimeout(onClose, 220)}
                   data-cursor-hover
                   style={{
                     fontFamily: 'var(--sans)', fontSize: 18,
                     color: active ? 'var(--ink)' : 'var(--ink-2)',
                   }}>— {c[lang]}</a>
              );
            })}
          </div>
        </div>

        {item('sons',       t.nav.sons,       '#/sons')}
        {item('exposicoes', t.nav.exposicoes, '#/exposicoes')}
        {item('contacto',   t.nav.contacto,   '#/contacto')}
        {item('cv',         t.nav.cv,         '#/cv')}
      </nav>

      {/* Bottom */}
      <div style={{
        padding: '24px 22px',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div style={{ display: 'flex', gap: 18 }}>
          <a href={CONTACT.instagram} target="_blank" rel="noreferrer" className="link" data-cursor-hover>Instagram</a>
          <a href={CONTACT.linkedin}  target="_blank" rel="noreferrer" className="link" data-cursor-hover>LinkedIn</a>
          <a href={`mailto:${CONTACT.email}`} className="link" data-cursor-hover>{lang === 'pt' ? 'Correio' : 'Email'}</a>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', color: 'var(--ink-3)' }}>
          <span className="mono">© 2026 Carolina Leal</span>
          <button
            onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}
            data-cursor-hover
            style={{
              fontFamily: 'var(--sans)',
              fontWeight: 700,
              fontSize: 14,
              color: 'var(--ink)',
            }}
          >
            {lang === 'pt' ? 'EN \u2192' : 'PT \u2192'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---- Footer --------------------------------------------------------------
function Footer({ lang }) {
  const t = T[lang];
  return (
    <footer
      style={{
        padding: '64px 0 24px',
        maxWidth: 1280,
        margin: '64px auto 0',
        display: 'flex',
        flexDirection: 'column',
        gap: 16,
      }}
    >
      <div style={{
        display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between',
        alignItems: 'baseline', gap: 16,
      }}>
        <a href={`mailto:${CONTACT.email}`} className="link"
           style={{ fontSize: 15, color: 'var(--ink)' }}>{CONTACT.email}</a>
        <div style={{ display: 'flex', gap: 18, fontSize: 15 }}>
          <a href={CONTACT.instagram} target="_blank" rel="noreferrer" className="link">Instagram</a>
          <a href={CONTACT.linkedin}  target="_blank" rel="noreferrer" className="link">LinkedIn</a>
          <a href={CONTACT.cv} download className="link">CV</a>
        </div>
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        color: 'var(--ink-3)',
      }}>
        <span className="mono">© 2026 Carolina Leal</span>
        <span className="mono">{t.footer.based}</span>
      </div>
    </footer>
  );
}

// ---- Back button ----------------------------------------------------------
function BackButton({ route, lang }) {
  const dest = {
    sobre:        '#/home',
    trabalhos:    '#/home',
    trabalhosCat: '#/trabalhos',
    obra:         '#/trabalhos',
    sons:         '#/home',
    som:          '#/sons',
    exposicoes:   '#/home',
    exposicao:    '#/exposicoes',
    contacto:     '#/home',
    cv:           '#/home',
  }[route.name];

  if (!dest) return null;

  return (
    <>
      <a
        href={dest}
        className="back-btn"
        data-cursor-hover
        onMouseOver={e => e.currentTarget.style.opacity = '1'}
        onMouseOut={e => e.currentTarget.style.opacity = '0.75'}
      >
        ← {lang === 'pt' ? 'voltar' : 'back'}
      </a>
      <style>{`
        .back-btn {
          position: fixed;
          bottom: 32px;
          left: 40px;
          z-index: 55;
          font-family: var(--mono);
          font-size: 11.5px;
          letter-spacing: 0.04em;
          color: var(--ink-3);
          opacity: 0.75;
          display: inline-flex;
          align-items: center;
          gap: 5px;
          transition: opacity 240ms ease;
          user-select: none;
          text-decoration: none;
        }
        @media (max-width: 720px) {
          .back-btn { left: 20px; bottom: 22px; }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { TopNav, MobileMenu, Footer, BrandName, BackButton, useRoute, parseHash, go });
