/* App shell, nav + view router + theme */

const { useState, useEffect, useCallback } = React;

const THEME_KEY = "portfolio-theme";

function useTheme() {
  const [theme, setTheme] = useState(() => {
    if (typeof window === "undefined") return "light";
    return localStorage.getItem(THEME_KEY) || "light";
  });

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem(THEME_KEY, theme);
  }, [theme]);

  const toggle = useCallback(() => {
    setTheme((t) => (t === "dark" ? "light" : "dark"));
  }, []);

  return [theme, toggle];
}

function readView() {
  const m = window.location.pathname.match(/^\/case\/([\w-]+)\/?$/);
  if (m) return { name: "case", slug: m[1] };
  return { name: "home" };
}

function App() {
  const [view, setView] = useState(readView);
  const [theme, toggleTheme] = useTheme();
  const [activeSection, setActiveSection] = useState("work");

  // Path routing — each case study has its own URL /case/<slug>.
  // popstate handles browser back/forward; goHome/goCase below
  // pushState for SPA-style navigation.
  useEffect(() => {
    const sync = () => setView(readView());
    window.addEventListener("popstate", sync);
    return () => window.removeEventListener("popstate", sync);
  }, []);

  // Active section tracking on home page
  useEffect(() => {
    if (view.name !== "home") return;
    const sectionIds = ["work", "about", "resume", "experience", "honors", "philosophy", "contact"];
    const handler = () => {
      let current = "work";
      for (const id of sectionIds) {
        const el = document.getElementById(id);
        if (!el) continue;
        const rect = el.getBoundingClientRect();
        if (rect.top < window.innerHeight * 0.4) current = id;
      }
      setActiveSection(current);
    };
    handler();
    window.addEventListener("scroll", handler, { passive: true });
    return () => window.removeEventListener("scroll", handler);
  }, [view.name]);

  const goHome = useCallback(() => {
    window.history.pushState({}, "", "/");
    setView({ name: "home" });
    window.scrollTo(0, 0);
  }, []);
  const goCase = useCallback((slug) => {
    window.history.pushState({}, "", `/case/${slug}`);
    setView({ name: "case", slug });
    window.scrollTo(0, 0);
  }, []);

  const { PROFILE } = window.PORTFOLIO_DATA;

  const navItems = [
    { id: "work", label: "Work" },
    { id: "about", label: "About" },
    { id: "resume", label: "Résumé" },
    { id: "experience", label: "Experience" },
    { id: "honors", label: "Honors" },
    { id: "contact", label: "Contact" },
  ];

  return (
    <>
      <nav className="nav">
        <div className="nav-inner">
          <div className="brand" onClick={goHome}>
            <span className="brand-mark">Mazdak Shakiba</span>
          </div>

          <div className="nav-links">
            {navItems.map((item) => (
              <a
                key={item.id}
                className={"nav-link" + (activeSection === item.id && view.name === "home" ? " active" : "")}
                href={view.name === "home" ? `#${item.id}` : `/#${item.id}`}
                onClick={(e) => {
                  if (view.name !== "home") {
                    e.preventDefault();
                    window.history.pushState({}, "", "/");
                    setView({ name: "home" });
                    setTimeout(() => {
                      const el = document.getElementById(item.id);
                      if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
                    }, 50);
                  }
                }}
              >
                {item.label}
              </a>
            ))}
          </div>

          <div className="nav-right">
            <ThemeToggle theme={theme} onToggle={toggleTheme} />
            <a className="nav-cta" href={view.name === "home" ? "#contact" : `mailto:${PROFILE.email}`}>
              Get in touch
            </a>
          </div>
        </div>
      </nav>

      {view.name === "home" ? (
        <Home goCase={goCase} />
      ) : (
        <CaseStudy slug={view.slug} goHome={goHome} goCase={goCase} />
      )}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
