import { useState, useEffect, useCallback } from "react";
import { AppSidebar } from "@/components/layout/AppSidebar";
import { DungeonPage } from "@/components/dungeon/DungeonPage";
import { dungeonDataMap } from "@/data";

const DEFAULT_DUNGEON = "nexus-point-xenas";

function getHashDungeon(): string {
  const hash = window.location.hash.replace("#", "");
  return hash && hash in dungeonDataMap ? hash : DEFAULT_DUNGEON;
}

export default function App() {
  const [activeDungeonId, setActiveDungeonId] = useState(getHashDungeon);

  const handleSelectDungeon = useCallback((id: string) => {
    setActiveDungeonId(id);
    window.location.hash = id;
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  useEffect(() => {
    const onHashChange = () => {
      setActiveDungeonId(getHashDungeon());
    };
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, []);

  const dungeon = dungeonDataMap[activeDungeonId];

  if (!dungeon) return null;

  return (
    <div className="min-h-screen bg-bg-primary">
      <AppSidebar
        activeDungeonId={activeDungeonId}
        activeDungeon={dungeon}
        onSelectDungeon={handleSelectDungeon}
      />
      <div className="md:pl-[320px]">
        <main className="mx-auto max-w-7xl px-6 py-8 pb-20">
          <DungeonPage dungeon={dungeon} />
        </main>
      </div>
    </div>
  );
}
