// Shared layout: top nav, mobile drawer, footer, small UI atoms.

const { useState, useEffect, useMemo, useRef } = React;

const NAV = [
  { label: "Start Here", route: "/start" },
  { label: "Lessons", route: "/lessons" },
  { label: "Chapters", route: "/chapters" },
  { label: "Resources", route: "/resources" },
  { label: "Interview Insights", route: "/interviews" },
  { label: "About", route: "/about" },
];

// --- minimal hash router ---------------------------------------------------
function useRoute() {
  const get = () => {
    const h = window.location.hash || "#/";
    return h.replace(/^#/, "") || "/";
  };
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const onHash = () => setRoute(get());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function navigate(route) {
  window.location.hash = "#" + route;
  window.scrollTo({ top: 0, behavior: "instant" });
}

function Link({ to, children, className = "", style = {}, onClick, ...rest }) {
  return (
    <a
      href={"#" + to}
      className={className}
      style={style}
      onClick={(e) => {
        // let cmd/ctrl-click open new tab
        if (e.metaKey || e.ctrlKey) return;
        e.preventDefault();
        if (onClick) onClick(e);
        navigate(to);
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

// --- top nav --------------------------------------------------------------
function TopNav() {
  const route = useRoute();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);

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

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const isActive = (r) => {
    if (r === "/") return route === "/";
    return route === r || route.startsWith(r + "/");
  };

  return (
    <>
      <header className={"site-nav " + (scrolled ? "is-scrolled" : "")}>
        <div className="nav-inner">
          <Link to="/" className="brand" aria-label="Lessons from a Fintech home">
            <span className="brand-mark" aria-hidden="true">
              <span className="brand-dot" />
            </span>
            <span className="brand-name">
              <span className="brand-line">Lessons from</span>
              <span className="brand-line brand-line-2">a Fintech</span>
            </span>
          </Link>

          <nav className="nav-links" aria-label="Primary">
            {NAV.map((n) => (
              <Link
                key={n.route}
                to={n.route}
                className={"nav-link " + (isActive(n.route) ? "is-active" : "")}
              >
                {n.label}
              </Link>
            ))}
          </nav>

          <div className="nav-cta">
            <Link to="/lessons" className="btn btn-primary btn-sm">Explore the lessons</Link>
          </div>

          <button
            className="nav-toggle"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen(!open)}
          >
            <span className={"nav-toggle-bars " + (open ? "is-open" : "")}>
              <span /><span /><span />
            </span>
          </button>
        </div>
      </header>

      <div className={"mobile-drawer " + (open ? "is-open" : "")} role="dialog" aria-modal="true" aria-label="Menu">
        <div className="drawer-inner">
          <div className="drawer-eyebrow mono">Menu</div>
          <nav className="drawer-links">
            {NAV.map((n, i) => (
              <Link
                key={n.route}
                to={n.route}
                className={"drawer-link " + (isActive(n.route) ? "is-active" : "")}
                onClick={() => setOpen(false)}
              >
                <span className="drawer-num mono">{String(i + 1).padStart(2, "0")}</span>
                <span className="drawer-label">{n.label}</span>
              </Link>
            ))}
          </nav>
          <div className="drawer-ctas">
            <Link to="/lessons" className="btn btn-primary" onClick={() => setOpen(false)}>Explore the lessons</Link>
            <Link to="/resources" className="btn btn-ghost" onClick={() => setOpen(false)}>Download worksheets</Link>
          </div>
        </div>
      </div>
    </>
  );
}

// --- footer ---------------------------------------------------------------
function SiteFooter() {
  return (
    <footer className="site-footer">
      <div className="footer-grid">
        <div className="footer-brand">
          <div className="footer-mark">
            <span className="brand-mark"><span className="brand-dot" /></span>
            <span className="footer-title">Lessons from a Fintech</span>
          </div>
          <p className="footer-tag">A founder field guide for the hard lessons that usually arrive too late.</p>
          <p className="footer-tag muted">lessons.jamesvarga.com</p>
        </div>

        <div className="footer-col">
          <div className="footer-h mono">Project</div>
          <Link to="/start" className="footer-link">Start Here</Link>
          <Link to="/lessons" className="footer-link">Lessons</Link>
          <Link to="/chapters" className="footer-link">Chapters</Link>
          <Link to="/resources" className="footer-link">Resources</Link>
          <Link to="/interviews" className="footer-link">Interview Insights</Link>
        </div>

        <div className="footer-col">
          <div className="footer-h mono">Elsewhere</div>
          <a className="footer-link" href="https://jamesvarga.com" target="_blank" rel="noopener noreferrer">jamesvarga.com ↗</a>
          <a className="footer-link" href="#" onClick={(e) => e.preventDefault()}>LinkedIn</a>
          <Link to="/contact" className="footer-link">Contact</Link>
          <Link to="/privacy" className="footer-link">Privacy</Link>
        </div>

        <div className="footer-col">
          <div className="footer-h mono">Contribute</div>
          <p className="footer-small">
            Share a lesson, suggest a topic, or use the material with founders.
          </p>
          <Link to="/contact" className="btn btn-ghost btn-sm">Get in touch</Link>
        </div>
      </div>
      <div className="footer-rule" />
      <div className="footer-meta">
        <span className="mono">© 2026 — Lessons from a Fintech</span>
        <span className="mono muted">A founder-led project by James Varga</span>
      </div>
    </footer>
  );
}

// --- small atoms ----------------------------------------------------------
function Tag({ children, tone = "default" }) {
  // If a known category name is passed as text, auto-color via data-cat
  const text = typeof children === "string" ? children : null;
  const known = [
    "Revenue","Sales","Banks","Procurement","Funding","Resilience","International Growth","Ecosystem",
    "Traction","Fundraising","Failure","Recovery","Scaling"
  ];
  const cat = text && known.includes(text) ? text : null;
  return <span className={"tag tag-" + tone} data-cat={cat || undefined}>{children}</span>;
}

function SectionHeader({ eyebrow, title, kicker, action }) {
  return (
    <div className="section-header">
      <div className="section-header-text">
        {eyebrow && <div className="eyebrow mono">{eyebrow}</div>}
        <h2 className="section-title">{title}</h2>
        {kicker && <p className="section-kicker">{kicker}</p>}
      </div>
      {action && <div className="section-action">{action}</div>}
    </div>
  );
}

function Page({ children, className = "" }) {
  return <main className={"page " + className}>{children}</main>;
}

// --- per-route document title + meta description --------------------------
// Updates <title>, <meta description>, canonical URL, OG tags as the user
// navigates. Helps when share links resolve to a specific lesson/chapter
// (the page-load social-share preview is still the default homepage one,
// since meta tags in the HTML <head> are read once before JS runs — but
// browser tabs and post-navigation behaviours pick this up).
const SITE_BASE_URL = "https://lessons.jamesvarga.com";

function setMeta(name, content, attr = "name") {
  if (!content) return;
  let el = document.querySelector(`meta[${attr}="${name}"]`);
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute(attr, name);
    document.head.appendChild(el);
  }
  el.setAttribute("content", content);
}

function setCanonical(url) {
  let el = document.querySelector('link[rel="canonical"]');
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", "canonical");
    document.head.appendChild(el);
  }
  el.setAttribute("href", url);
}

function metaForRoute(route) {
  const siteName = SITE.name;
  const fallback = {
    title: `${siteName} | Practical Founder Lessons for Fintech Builders`,
    description: SITE.shortDescription,
    canonical: SITE_BASE_URL + "/",
  };

  if (route === "/" || route === "") return fallback;
  if (route === "/start") return {
    title: `Start Here · ${siteName}`,
    description: START_HERE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/start",
  };
  if (route === "/lessons") return {
    title: `Lessons · ${siteName}`,
    description: LIBRARY_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/lessons",
  };
  if (route.startsWith("/lessons/")) {
    const l = lessonBySlug(route.split("/")[2]);
    if (l) return {
      title: `${l.title} · ${siteName}`,
      description: l.summary,
      canonical: SITE_BASE_URL + "/#/lessons/" + l.slug,
    };
  }
  if (route === "/chapters") return {
    title: `Chapters · ${siteName}`,
    description: CHAPTERS_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/chapters",
  };
  if (route.startsWith("/chapters/")) {
    const c = chapterByN(route.split("/")[2]);
    if (c) return {
      title: `Chapter ${c.n}: ${c.title} · ${siteName}`,
      description: c.headline,
      canonical: SITE_BASE_URL + "/#/chapters/" + c.n,
    };
  }
  if (route === "/resources") return {
    title: `Resources · ${siteName}`,
    description: RESOURCES_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/resources",
  };
  if (route.startsWith("/resources/")) {
    const r = resourceBySlug(route.split("/")[2]);
    if (r) return {
      title: `${r.title} · ${siteName}`,
      description: r.summary,
      canonical: SITE_BASE_URL + "/#/resources/" + r.slug,
    };
  }
  if (route === "/interviews") return {
    title: `Interview Insights · ${siteName}`,
    description: INSIGHTS_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/interviews",
  };
  if (route === "/about") return {
    title: `About · ${siteName}`,
    description: ABOUT_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/about",
  };
  if (route === "/contact") return {
    title: `Contact · ${siteName}`,
    description: CONTACT_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/contact",
  };
  if (route === "/privacy") return {
    title: `Privacy · ${siteName}`,
    description: PRIVACY_PAGE.hero.subheadline,
    canonical: SITE_BASE_URL + "/#/privacy",
  };

  return fallback;
}

function useDocumentMeta(route) {
  useEffect(() => {
    const m = metaForRoute(route);
    document.title = m.title;
    setMeta("description", m.description);
    setMeta("og:title", m.title, "property");
    setMeta("og:description", m.description, "property");
    setMeta("og:url", m.canonical, "property");
    setMeta("twitter:title", m.title);
    setMeta("twitter:description", m.description);
    setCanonical(m.canonical);
  }, [route]);
}

Object.assign(window, {
  NAV, useRoute, navigate, Link,
  TopNav, SiteFooter, Tag, SectionHeader, Page,
  useDocumentMeta, metaForRoute,
});
