// ===== Shared Components =====
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// Simple hash-based router
function useHashRoute() {
  const parse = () => {
    const h = window.location.hash.replace(/^#\/?/, "") || "beranda";
    const [path, ...rest] = h.split("/");
    return { path, params: rest };
  };
  const [route, setRoute] = useState(parse());
  useEffect(() => {
    const onChange = () => {
      setRoute(parse());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return route;
}

function navigate(path) {
  window.location.hash = "/" + path;
}

// Link component
function L({ to, children, className, onClick, ...rest }) {
  const handle = (e) => {
    e.preventDefault();
    if (onClick) onClick(e);
    navigate(to);
  };
  return (
    <a href={"#/" + to} className={className} onClick={handle} {...rest}>
      {children}
    </a>
  );
}

// Placeholder image
function PH({ label, tint, className, style, ratio, children }) {
  const tintClass = tint ? "tinted-" + tint : "";
  const aspectStyle = ratio ? { aspectRatio: ratio, ...style } : style;
  return (
    <div className={"ph " + tintClass + " " + (className || "")} style={aspectStyle}>
      {children || (label && <span className="ph-label">{label}</span>)}
    </div>
  );
}

// FontAwesome icon helper
// <Icon name="leaf" size={20} /> or <Icon name="leaf" box="green" boxSize={56} fontSize={24} />
function Icon({ name, size, box, boxSize, fontSize, style, className, brand }) {
  const prefix = brand ? "fa-brands" : "fa-solid";
  const i = <i className={prefix + " fa-" + name} style={{ fontSize: fontSize || size || "inherit" }} />;
  if (!box) {
    return <span className={"ic-wrap " + (className || "")} style={style}>{i}</span>;
  }
  return (
    <span
      className={"ic-wrap ic-box " + box + " " + (className || "")}
      style={{ width: boxSize || 48, height: boxSize || 48, ...style }}
    >
      {i}
    </span>
  );
}

// Logo / brand mark
function Brand({ size = 38 }) {
  return (
    <L to="beranda" className="brand">
      <span className="brand-mark" style={{ width: size, height: size }}>
        BZ
      </span>
      <span>BatamZoo</span>
    </L>
  );
}

// Navigation
function Nav() {
  const route = useHashRoute();
  const [open, setOpen] = useState(false);
  const links = [
    { to: "beranda", label: "Beranda" },
    { to: "fauna", label: "Fauna" },
    { to: "fasilitas", label: "Fasilitas" },
    { to: "tiket", label: "Beli Tiket" },
    { to: "edukasi", label: "Edukasi" },
    { to: "galeri", label: "Galeri" },
    { to: "tentang", label: "Tentang" },
    { to: "kontak", label: "Kontak" }
  ];
  return (
    <>
      <div className="banner-strip">
        <Icon name="gift" style={{ color: "var(--yellow)", marginRight: 8 }} />
        Promo Family Pack — <strong>Hemat 23%</strong> untuk pembelian online minggu ini · Berakhir Minggu pukul 23:59
      </div>
      <nav className="nav">
        <div className="nav-inner">
          <Brand />
          <div className="nav-links">
            {links.map((l) => (
              <L key={l.to} to={l.to} className={route.path === l.to ? "active" : ""}>
                {l.label}
              </L>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <L to="tiket" className="btn btn-primary btn-sm">Beli Tiket</L>
            <button
              className="nav-mobile-toggle"
              onClick={() => setOpen(!open)}
              aria-label="Menu"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="3" y1="6" x2="21" y2="6"/>
                <line x1="3" y1="12" x2="21" y2="12"/>
                <line x1="3" y1="18" x2="21" y2="18"/>
              </svg>
            </button>
          </div>
        </div>
        {open && (
          <div style={{ background: "white", padding: "12px 28px 20px", borderTop: "1px solid var(--line)" }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {links.map((l) => (
                <L
                  key={l.to}
                  to={l.to}
                  onClick={() => setOpen(false)}
                  style={{
                    padding: "12px 14px",
                    borderRadius: 12,
                    background: route.path === l.to ? "var(--cream-warm)" : "transparent",
                    fontWeight: 600
                  }}
                >
                  {l.label}
                </L>
              ))}
            </div>
          </div>
        )}
      </nav>
    </>
  );
}

// Footer
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <span className="brand-mark" style={{ background: "var(--yellow)", color: "var(--navy)" }}>BZ</span>
              <span style={{ color: "white", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22 }}>BatamZoo</span>
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.7, maxWidth: 320 }}>
              Kebun binatang modern di jantung Pulau Batam — rumah konservasi 150+ satwa Nusantara
              dan dunia, dibangun di atas 18 hektar lahan hijau.
            </p>
            <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
              {[
                { n: "instagram", l: "Instagram" },
                { n: "facebook-f", l: "Facebook" },
                { n: "tiktok", l: "TikTok" },
                { n: "youtube", l: "YouTube" },
                { n: "whatsapp", l: "WhatsApp" }
              ].map(s => (
                <a key={s.n} href="#" className="sm-btn" aria-label={s.l}>
                  <i className={"fa-brands fa-" + s.n}></i>
                </a>
              ))}
            </div>
          </div>
          <div>
            <h4>Jelajahi</h4>
            <ul style={{ listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li><L to="beranda">Beranda</L></li>
              <li><L to="fauna">Detail Fauna</L></li>
              <li><L to="fasilitas">Detail Fasilitas</L></li>
              <li><L to="edukasi">Program Edukasi</L></li>
              <li><L to="galeri">Galeri</L></li>
            </ul>
          </div>
          <div>
            <h4>Layanan</h4>
            <ul style={{ listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li><L to="tiket">Beli Tiket Online</L></li>
              <li><L to="faq">FAQ</L></li>
              <li><L to="kontak">Hubungi Kami</L></li>
              <li><L to="lokasi">Lokasi & Akses</L></li>
              <li><L to="konservasi">Donasi Konservasi</L></li>
            </ul>
          </div>
          <div>
            <h4>Kontak</h4>
            <ul style={{ listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li>Jl. Hang Lekiu KM 4<br/>Nongsa, Batam 29466</li>
              <li>+62 778 711 2233</li>
              <li>halo@batamzoo.id</li>
              <li>Buka harian 08:30 – 17:30 WIB</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 BatamZoo Konservasi Nusantara. Semua hak dilindungi.</div>
          <div style={{ display: "flex", gap: 16 }}>
            <a href="#">Syarat & Ketentuan</a>
            <a href="#">Privasi</a>
            <a href="#">Sitemap</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Page head reusable
function PageHead({ crumb, title, sub, tone }) {
  return (
    <header className={"pagehead " + (tone || "")}>
      <div className="container" style={{ position: "relative", zIndex: 2 }}>
        {crumb && <div className="crumb">{crumb}</div>}
        <h1>{title}</h1>
        {sub && <p>{sub}</p>}
      </div>
    </header>
  );
}

// Section header
function SectionHeader({ eyebrow, title, sub, align = "left", action }) {
  return (
    <div style={{
      display: "flex",
      flexDirection: align === "center" ? "column" : "row",
      gap: 24,
      alignItems: align === "center" ? "center" : "flex-end",
      justifyContent: "space-between",
      marginBottom: 44,
      textAlign: align
    }}>
      <div style={{ maxWidth: 640 }}>
        {eyebrow && <div className="eyebrow" style={{ marginBottom: 12 }}>{eyebrow}</div>}
        <h2>{title}</h2>
        {sub && <p className="lead" style={{ marginTop: 12, marginBottom: 0 }}>{sub}</p>}
      </div>
      {action && <div style={{ flexShrink: 0 }}>{action}</div>}
    </div>
  );
}

// Toast
function Toast({ text, onDone }) {
  useEffect(() => {
    const t = setTimeout(onDone, 2400);
    return () => clearTimeout(t);
  }, [text, onDone]);
  return (
    <div className="toast">
      <span className="dot"></span>
      {text}
    </div>
  );
}

// Counter for tickets
function Counter({ value, onChange, min = 0, max = 20 }) {
  return (
    <div className="counter">
      <button onClick={() => onChange(Math.max(min, value - 1))} disabled={value <= min}>−</button>
      <span className="count">{value}</span>
      <button onClick={() => onChange(Math.min(max, value + 1))} disabled={value >= max}>+</button>
    </div>
  );
}

// Format Rupiah
function rupiah(n) {
  return "Rp" + n.toLocaleString("id-ID");
}

Object.assign(window, {
  useHashRoute, navigate, L, PH, Brand, Nav, Footer,
  PageHead, SectionHeader, Toast, Counter, rupiah,
  useState, useEffect, useMemo, useRef, useCallback
});
