// Router + shared utilities (hash-based routing)
function useHashRoute() {
  const parse = () => {
    const h = window.location.hash.replace(/^#\/?/, '') || 'home';
    return h.split('?')[0] || 'home';
  };
  const [route, setRoute] = React.useState(parse());
  React.useEffect(() => {
    const onHash = () => {
      setRoute(parse());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function navigate(route) {
  window.location.hash = '/' + route;
}

// Reveal-on-scroll hook
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!('IntersectionObserver' in window)) {
      els.forEach(el => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -60px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

// Lock body scroll when modal open
function useScrollLock(locked) {
  React.useEffect(() => {
    if (locked) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [locked]);
}

// ----- Logo -----
function Logo({ dark = false, size = 'md', onClick }) {
  const s = size === 'sm' ? 32 : size === 'lg' ? 56 : 40;
  const color = dark ? '#F5EFE6' : '#1A1814';
  const accent = '#C8624A';
  return (
    <a href="#/home" onClick={(e) => { e.preventDefault(); navigate('home'); onClick && onClick(); }} className="logo-link" style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>
      <svg width={s} height={s} viewBox="0 0 56 56" fill="none" style={{ flexShrink: 0 }}>
        {/* Anchor / wave mark */}
        <circle cx="28" cy="28" r="27" stroke={color} strokeWidth="1.5" />
        <path d="M14 36 Q19 32, 24 36 T34 36 T44 36" stroke={accent} strokeWidth="2" fill="none" strokeLinecap="round"/>
        <path d="M28 14 L28 28 M22 22 L34 22" stroke={color} strokeWidth="2" strokeLinecap="round"/>
        <circle cx="28" cy="14" r="2.5" fill={accent}/>
      </svg>
      <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
        <span style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 600,
          fontSize: size === 'lg' ? 28 : 22,
          color,
          letterSpacing: '0.02em',
        }}>Kain Ama</span>
        <span style={{
          fontSize: 9,
          letterSpacing: '0.28em',
          textTransform: 'uppercase',
          color: dark ? 'rgba(245,239,230,0.7)' : 'rgba(26,24,20,0.6)',
          marginTop: 4,
          fontWeight: 500,
        }}>Málaga · Mediterráneo</span>
      </div>
    </a>
  );
}

// ----- Language switcher -----
function LangSwitcher({ dark = false }) {
  const { lang, setLang } = useI18n();
  const langs = ['ro', 'en', 'es'];
  return (
    <div className="lang-switch" data-dark={dark}>
      {langs.map((l, i) => (
        <React.Fragment key={l}>
          {i > 0 && <span className="lang-sep">·</span>}
          <button
            className={'lang-btn ' + (lang === l ? 'active' : '')}
            onClick={() => setLang(l)}
            aria-label={`Switch to ${l}`}
          >
            {l.toUpperCase()}
          </button>
        </React.Fragment>
      ))}
    </div>
  );
}

// ----- Header -----
function Header({ openBooking }) {
  const { t } = useI18n();
  const route = useHashRoute();
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => { setMobileOpen(false); }, [route]);
  useScrollLock(mobileOpen);

  const links = [
    { id: 'home', label: t.nav.home },
    { id: 'cruises', label: t.nav.cruises },
    { id: 'about', label: t.nav.about },
    { id: 'gallery', label: t.nav.gallery },
    { id: 'routes', label: t.nav.routes },
    { id: 'faq', label: t.nav.faq },
    { id: 'contact', label: t.nav.contact },
  ];

  return (
    <>
      <header className={'site-header ' + (scrolled ? 'scrolled' : '')}>
        <div className="container header-inner">
          <Logo />
          <nav className="nav-desktop">
            {links.map(l => (
              <a
                key={l.id}
                href={'#/' + l.id}
                onClick={(e) => { e.preventDefault(); navigate(l.id); }}
                className={'nav-link ' + (route === l.id ? 'active' : '')}
              >{l.label}</a>
            ))}
          </nav>
          <div className="header-right">
            <LangSwitcher />
            <button className="btn btn-primary btn-sm header-cta" onClick={openBooking}>
              {t.nav.book}
            </button>
            <button
              className="hamburger"
              onClick={() => setMobileOpen(true)}
              aria-label="Open menu"
            >
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>
      </header>

      {/* Mobile menu */}
      <div className={'mobile-menu ' + (mobileOpen ? 'open' : '')}>
        <div className="mobile-menu-head">
          <Logo dark onClick={() => setMobileOpen(false)} />
          <button className="close-btn" onClick={() => setMobileOpen(false)} aria-label="Close menu">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <path d="M18 6L6 18M6 6l12 12" strokeLinecap="round"/>
            </svg>
          </button>
        </div>
        <nav className="mobile-nav">
          {links.map((l, i) => (
            <a
              key={l.id}
              href={'#/' + l.id}
              onClick={(e) => { e.preventDefault(); navigate(l.id); }}
              className={'mobile-link ' + (route === l.id ? 'active' : '')}
              style={{ animationDelay: `${i * 50}ms` }}
            >
              <span className="mobile-link-num">{String(i + 1).padStart(2, '0')}</span>
              {l.label}
            </a>
          ))}
        </nav>
        <div className="mobile-menu-foot">
          <LangSwitcher dark />
          <button className="btn btn-primary btn-lg" onClick={() => { setMobileOpen(false); openBooking(); }}>
            {t.nav.book} →
          </button>
        </div>
      </div>
    </>
  );
}

// ----- Footer -----
function Footer({ openBooking }) {
  const { t } = useI18n();
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <Logo dark />
            <p className="footer-tagline">{t.footer.tagline}</p>
            <div className="footer-socials">
              <a href="#/contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }} aria-label="Instagram"><InstagramIcon /></a>
              <a href="#/contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }} aria-label="WhatsApp"><WhatsAppIcon /></a>
              <a href="#/contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }} aria-label="Email"><MailIcon /></a>
            </div>
          </div>
          <div className="footer-col">
            <h4>{t.footer.pages}</h4>
            <a href="#/home" onClick={(e) => { e.preventDefault(); navigate('home'); }}>{t.nav.home}</a>
            <a href="#/cruises" onClick={(e) => { e.preventDefault(); navigate('cruises'); }}>{t.nav.cruises}</a>
            <a href="#/about" onClick={(e) => { e.preventDefault(); navigate('about'); }}>{t.nav.about}</a>
            <a href="#/gallery" onClick={(e) => { e.preventDefault(); navigate('gallery'); }}>{t.nav.gallery}</a>
            <a href="#/routes" onClick={(e) => { e.preventDefault(); navigate('routes'); }}>{t.nav.routes}</a>
          </div>
          <div className="footer-col">
            <h4>{t.footer.contact}</h4>
            <a href={`tel:${t.contact.info.phoneVal}`}>{t.contact.info.phoneVal}</a>
            <a href={`mailto:${t.contact.info.emailVal}`}>{t.contact.info.emailVal}</a>
            <span style={{ opacity: 0.7 }}>{t.contact.info.locationVal}</span>
            <button className="btn btn-ghost on-dark btn-sm" style={{ marginTop: 16, alignSelf: 'flex-start' }} onClick={openBooking}>
              {t.nav.book} →
            </button>
          </div>
          <div className="footer-col">
            <h4>{t.footer.legal}</h4>
            <a href="#" onClick={(e) => e.preventDefault()}>{t.footer.terms}</a>
            <a href="#" onClick={(e) => e.preventDefault()}>{t.footer.privacy}</a>
            <a href="#" onClick={(e) => e.preventDefault()}>{t.footer.cancel}</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Kain Ama · {t.footer.rights}</span>
          <span>{t.footer.built}</span>
        </div>
      </div>
    </footer>
  );
}

// ----- Floating WhatsApp -----
function WhatsAppFloat() {
  const { t, lang } = useI18n();
  const msg = encodeURIComponent({
    ro: 'Bună! Aș vrea să rezerv o croazieră.',
    en: 'Hi! I\'d like to book a cruise.',
    es: '¡Hola! Me gustaría reservar un crucero.',
  }[lang]);
  return (
    <a
      href={`https://wa.me/34612345678?text=${msg}`}
      target="_blank"
      rel="noopener"
      className="wa-float"
      aria-label="WhatsApp"
    >
      <WhatsAppIcon />
      <span className="wa-pulse"></span>
    </a>
  );
}

// ----- Icons -----
function InstagramIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></svg>;
}
function WhatsAppIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><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 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-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 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.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 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413"/></svg>;
}
function MailIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>;
}
function PhoneIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg>;
}
function PinIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>;
}
function ClockIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>;
}
function UsersIcon() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>;
}
function ArrowRight({ size = 16 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>;
}
function CheckIcon() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>;
}
function ChevronDown() {
  return <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg>;
}
function StarIcon() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2-6.3-4.6-6.3 4.6 2.3-7.2-6-4.4h7.6z"/></svg>;
}

Object.assign(window, {
  useHashRoute, navigate, useReveal, useScrollLock,
  Logo, LangSwitcher, Header, Footer, WhatsAppFloat,
  InstagramIcon, WhatsAppIcon, MailIcon, PhoneIcon, PinIcon, ClockIcon, UsersIcon,
  ArrowRight, CheckIcon, ChevronDown, StarIcon,
});
