"use client";

import { cn } from "@/lib/utils";
import { Sidebar } from "./Sidebar";
import { Header } from "./Header";
import { useState } from "react";
import { useMarketStore } from "@/stores/marketStore";
import { usePathname } from "next/navigation";

export interface MainLayoutProps {
  children: React.ReactNode;
  className?: string;
}

// Map of paths to titles
const pathTitles: Record<string, string> = {
  "/": "Dashboard",
  "/trading": "Trading Terminal",
  "/orders": "Order History",
  "/agents": "Agents Overview",
  "/exchanges": "Exchange Connections",
  "/config": "System Configuration",
};

export function MainLayout({
  children,
  className,
}: MainLayoutProps) {
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const pathname = usePathname();
  const isConnected = useMarketStore((state) => state.isConnected);

  // Determine title based on current path
  const getTitle = () => {
    const path = pathname || "/";
    if (pathTitles[path]) return pathTitles[path];
    if (path.startsWith("/agents/")) return "Agent Details";
    return "OpenClaw";
  };

  const toggleSidebar = () => setIsSidebarOpen(!isSidebarOpen);
  const closeSidebar = () => setIsSidebarOpen(false);

  return (
    <div className={cn("min-h-screen bg-[#121212] text-[#e1e1e1]", className)}>
      <Sidebar isOpen={isSidebarOpen} />

      <div
        className={cn(
          "flex flex-col min-h-screen transition-all duration-300",
          isSidebarOpen ? "ml-64" : "ml-0",
        )}
      >
        <Header
          title={getTitle()}
          isConnected={isConnected}
          onMenuClick={toggleSidebar}
          isSidebarOpen={isSidebarOpen}
        />

        <main
          className="flex-1 p-6 overflow-auto"
          onClick={isSidebarOpen && typeof window !== "undefined" && window.innerWidth < 1024 ? closeSidebar : undefined}
        >
          {children}
        </main>
      </div>
    </div>
  );
}

export default MainLayout;
