// Top-level App: tab state, file-open routing, layout composition.

const { useState: useStateA } = React;

function App() {
  const { FOLDERS } = window.PORTFOLIO_DATA;

  // Tabs: always-present "home" + dynamically opened files.
  const [tabs, setTabs] = useStateA([
    { id: "home", kind: "home", label: "Home" },
  ]);
  const [activeId, setActiveId] = useStateA("home");

  const openFile = (path) => {
    const id = `file:${path}`;
    setTabs((prev) => {
      if (prev.find((t) => t.id === id)) return prev;
      const meta = window.PORTFOLIO_DATA.FILES[path];
      const label = path.split("/").pop();
      return [...prev, { id, kind: "file", path, label, title: meta?.title }];
    });
    setActiveId(id);
  };

  const closeTab = (id) => {
    setTabs((prev) => {
      const idx = prev.findIndex((t) => t.id === id);
      if (idx < 0) return prev;
      const next = prev.filter((t) => t.id !== id);
      if (activeId === id) {
        const fallback = next[idx - 1] || next[idx] || next[0];
        setActiveId(fallback.id);
      }
      return next;
    });
  };

  const activeTab = tabs.find((t) => t.id === activeId) || tabs[0];
  const openPath = activeTab?.kind === "file" ? activeTab.path : null;
  const openMeta = openPath ? window.PORTFOLIO_DATA.FILES[openPath] : null;
  const contentClass =
    activeTab.kind === "home"
      ? "content is-home"
      : openMeta?.kind === "binary"
      ? "content is-binary"
      : "content";

  return (
    <div className="app">
      <window.ChatSidebar />

      <main className="main">
        <window.TabBar
          tabs={tabs}
          activeId={activeId}
          onSelect={setActiveId}
          onClose={closeTab}
        />

        <div className="main-body">
          <window.FileTree
            folders={FOLDERS}
            openPath={openPath}
            onOpenFile={openFile}
          />

          <section className={contentClass} key={activeTab.id}>
            {activeTab.kind === "home"
              ? <window.HomeView onOpenFile={openFile} />
              : <window.FileView path={activeTab.path} />}
          </section>
        </div>
      </main>
    </div>
  );
}

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