/* ============================================================
 * Hostelova — shared site chrome (Nav + Footer + theme)
 * The ONE nav bar + footer, reused by BOTH the landing (app.jsx)
 * and the booking app (book-app.jsx). No duplication: edit here,
 * both pages update.
 *
 * Links are page-aware: in-page anchors (#features …) point to
 * `index.html#…` when we're NOT on the landing, so the same nav
 * works from book.html / login / etc.
 *
 * Hooks are called as React.useX so this file never collides with
 * the top-level `const { useState } = React` in app.jsx / book-app.jsx.
 * ========================================================== */

// True when the current page is the marketing landing (index.html / root).
const ON_LANDING = (function () {
  const p = location.pathname;
  return p === "/" || p === "" || p.endsWith("/") || /\/index\.html?$/i.test(p);
})();

// Prefix an in-page anchor with index.html when we're off the landing.
const L = (hash) => (ON_LANDING ? hash : "index.html" + hash);
const resolveHref = (href) => (href && href.charAt(0) === "#" ? L(href) : href);

// ---------- THEME ----------
const useTheme = () => {
  const [theme, setTheme] = React.useState(() => {
    try {
      const saved = localStorage.getItem("hostelova-theme");
      if (saved === "light" || saved === "dark") return saved;
    } catch (e) {}
    return document.documentElement.getAttribute("data-theme") ||
      (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
  });
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("hostelova-theme", theme); } catch (e) {}
  }, [theme]);
  return [theme, setTheme];
};

const ThemeToggle = ({ theme, setTheme }) => (
  <button
    className="theme-toggle"
    onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
    aria-label={"Switch to " + (theme === "dark" ? "light" : "dark") + " mode"}
    title={theme === "dark" ? "Light mode" : "Dark mode"}
  >
    <Icon.Sun className="sun" />
    <Icon.Moon className="moon" />
  </button>
);

// ---------- NAV DATA ----------
const NAV_GROUPS = [
  {
    key: "explore",
    label: "Explore",
    GroupIcon: () => <Icon.Sparkle width="16" height="16" />,
    items: [
      { href: "#top",      I: Icon.Home,      text: "Home" },
      { href: "#features", I: Icon.Verified,  text: "Features" },
      { href: "#students", I: Icon.Users,     text: "For Students" },
      { href: "#owners",   I: Icon.Building,  text: "For Owners" },
      { href: "book.html", I: Icon.Play,      text: "Book Online", external: true },
    ],
  },
  {
    key: "company",
    label: "Company",
    GroupIcon: () => <Icon.Building width="16" height="16" />,
    items: [
      { href: "pages/about.html", I: Icon.Sparkle, text: "About Us", external: true },
      { href: "claim-hostel.html", I: Icon.Building, text: "Claim Hostel", external: true },
      { href: "#contact",         I: Icon.Mail,    text: "Contact Us" },
      { href: "#faq",             I: Icon.Chat,    text: "FAQ" },
    ],
  },
  {
    key: "legal",
    label: "Legal & Policies",
    GroupIcon: () => <Icon.Shield width="16" height="16" />,
    items: [
      { href: "pages/privacy-policy.html",        I: Icon.Shield,   text: "Privacy Policy",        external: true },
      { href: "pages/terms.html",                 I: Icon.Flag,     text: "Terms & Conditions",    external: true },
      { href: "pages/account-deletion-policy.html", I: Icon.Shield, text: "Account Deletion",      external: true },
      { href: "pages/disclaimer.html",            I: Icon.Eye,      text: "Disclaimer",            external: true },
      { href: "pages/refund-policy.html",         I: Icon.Tag,      text: "Refund & Cancellation", external: true },
      { href: "pages/community-guidelines.html",  I: Icon.Users,    text: "Community Guidelines",  external: true },
      { href: "pages/cookie-policy.html",         I: Icon.Verified, text: "Cookie Policy",         external: true },
    ],
  },
];

// Reads the signed-in user from the shared client, if it's loaded on the page.
const getNavUser = () =>
  (window.HostelovaAPI && window.HostelovaAPI.isLoggedIn())
    ? window.HostelovaAPI.currentUser()
    : null;

// Profile avatar, inline-styled so it renders correctly on EVERY page —
// including the landing, which doesn't load book.css. Persisted login
// (localStorage session) means it shows on the landing too once signed in.
const NavAvatar = ({ user, active }) => {
  const name = (user.user_metadata && user.user_metadata.name) || user.email || "?";
  const initial = String(name).trim().charAt(0).toUpperCase();
  return (
    <a
      href="book.html#/profile"
      className="nav-avatar"
      aria-label="My profile"
      title={(user.user_metadata && user.user_metadata.name) || user.email || "My profile"}
      style={{
        width: 38, height: 38, borderRadius: "50%", display: "inline-grid", placeItems: "center",
        color: "#fff", fontWeight: 800, fontSize: 15, textDecoration: "none", flex: "0 0 auto",
        background: "linear-gradient(135deg, var(--primary), #7a93ff)",
        boxShadow: "0 8px 16px -6px var(--primary-glow)",
        outline: active ? "2px solid var(--primary)" : "none", outlineOffset: "2px",
      }}
    >
      {initial}
    </a>
  );
};

// ---------- NAV ----------
// Props:
//   theme, setTheme  — required
//   brandHref        — where the logo links (default: landing home)
//   rightActions     — JSX rendered in nav-right instead of the default CTA
//                      (book.html passes My bookings + profile here)
//   drawerActions    — JSX shown at the top of the mobile drawer body
const Nav = ({ theme, setTheme, brandHref, rightActions, drawerActions }) => {
  // Default right side (landing): profile avatar when signed in + Book CTA.
  const me = rightActions ? null : getNavUser();
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  React.useEffect(() => {
    if (!menuOpen) return;
    const onResize = () => { if (window.innerWidth > 880) setMenuOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    window.addEventListener("resize", onResize);
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("resize", onResize);
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [menuOpen]);
  const closeMenu = () => setMenuOpen(false);
  const home = brandHref || (ON_LANDING ? "#top" : "index.html");

  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "") + (menuOpen ? " menu-open" : "")}>
      <div className="container nav-inner">
        <a href={home} className="brand" onClick={closeMenu}>
          <span className="brand-mark"><Icon.Logo /></span>
          Hostelova
        </a>

        {/* Desktop inline links */}
        <div className="nav-links-desktop">
          <a className="nav-link nav-link-desktop" href={L("#features")} onClick={closeMenu}>Features</a>
          <a className="nav-link nav-link-desktop" href={L("#students")} onClick={closeMenu}>Students</a>
          <a className="nav-link nav-link-desktop" href={L("#owners")} onClick={closeMenu}>Owners</a>
          <a className="nav-link nav-link-desktop" href="book.html">Book Online</a>
          <a className="nav-link nav-link-desktop" href={L("#faq")} onClick={closeMenu}>FAQ</a>
        </div>

        <div className="nav-right">
          <ThemeToggle theme={theme} setTheme={setTheme} />
          {rightActions || (
            <>
              {me && <NavAvatar user={me} />}
              <a href="book.html" className="nav-cta nav-cta-desktop">
                Book a hostel <Icon.ArrowRight width="14" height="14" />
              </a>
            </>
          )}
          <button
            className="nav-toggle"
            onClick={() => setMenuOpen((o) => !o)}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
          >
            <span className="nt-bar"></span>
            <span className="nt-bar"></span>
            <span className="nt-bar"></span>
          </button>
        </div>
      </div>

      {ReactDOM.createPortal(
        <>
          <div
            className={"side-backdrop" + (menuOpen ? " show" : "")}
            onClick={closeMenu}
            aria-hidden="true"
          ></div>
          <aside className={"side-drawer" + (menuOpen ? " open" : "")} aria-hidden={!menuOpen}>
            <div className="sd-header">
              <a href={home} className="brand sd-brand" onClick={closeMenu}>
                <span className="brand-mark"><Icon.Logo /></span>
                Hostelova
              </a>
              <button type="button" className="sd-close" onClick={closeMenu} aria-label="Close menu">
                <Icon.X width="18" height="18" />
              </button>
            </div>

            <div className="sd-body">
              {drawerActions && <div className="sd-section">{drawerActions}</div>}
              {NAV_GROUPS.map((g) => (
                <div key={g.key} className="sd-section">
                  <div className="sd-section-title">
                    <span className="sd-sec-ico"><g.GroupIcon /></span>
                    <span>{g.label}</span>
                  </div>
                  <div className="sd-list">
                    {g.items.map((it) => (
                      <a
                        key={it.text}
                        className="sd-link"
                        href={resolveHref(it.href)}
                        onClick={it.external ? undefined : closeMenu}
                      >
                        <span className="sd-link-ico"><it.I width="16" height="16" /></span>
                        <span className="sd-link-text">{it.text}</span>
                        <span className="sd-link-arrow"><Icon.ArrowRight width="14" height="14" /></span>
                      </a>
                    ))}
                  </div>
                </div>
              ))}
            </div>

            <div className="sd-footer">
              <a href="book.html" className="sd-cta" onClick={closeMenu}>
                <Icon.Play width="16" height="16" /> Book a hostel
              </a>
              <div className="sd-foot-meta">
                <span>© 2026 Hostelova</span>
              </div>
            </div>
          </aside>
        </>,
        document.body
      )}
    </nav>
  );
};

// ---------- FOOTER ----------
const FLink = ({ href, children }) => <a href={resolveHref(href)}>{children}</a>;

const Footer = () => (
  <footer className="footer">
    <div className="container footer-inner">
      <div className="footer-meta">
        <div className="brand">
          <span className="brand-mark"><Icon.Logo /></span>
          Hostelova
        </div>
        <p>Find trusted hostels near your college. Compare rooms, see real photos, and book securely — all in one place.</p>
        <div className="footer-cta">
          <a href="book.html" className="footer-cta-btn"><Icon.Play width="14" height="14" /> Book a hostel</a>
        </div>
      </div>
      <div className="footer-cols">
        <div className="footer-col">
          <h4>Product</h4>
          <FLink href="#features">Features</FLink>
          <FLink href="#students">For students</FLink>
          <FLink href="#owners">For owners</FLink>
          <a href="book.html">Book online</a>
          <FLink href="#download">Download</FLink>
        </div>
        <div className="footer-col">
          <h4>Company</h4>
          <a href="pages/about.html">About Us</a>
          <a href="claim-hostel.html">Claim a hostel</a>
          <FLink href="#contact">Contact Us</FLink>
          <FLink href="#faq">FAQ</FLink>
        </div>
        <div className="footer-col">
          <h4>Legal</h4>
          <a href="pages/privacy-policy.html">Privacy Policy</a>
          <a href="pages/terms.html">Terms &amp; Conditions</a>
          <a href="pages/account-deletion-policy.html">Account Deletion</a>
          <a href="pages/disclaimer.html">Disclaimer</a>
          <a href="pages/refund-policy.html">Refund &amp; Cancellation</a>
          <a href="pages/cookie-policy.html">Cookie Policy</a>
        </div>
        <div className="footer-col">
          <h4>Trust &amp; Safety</h4>
          <a href="pages/community-guidelines.html">Community Guidelines</a>
          <FLink href="#contact">Report a listing</FLink>
          <FLink href="#contact">Help center</FLink>
        </div>
      </div>
    </div>
    <div className="container footer-bot">
      <span>© 2026 Hostelova. All rights reserved.</span>
      <span>Made in Lucknow for students across India.</span>
    </div>
  </footer>
);
