import { useState } from "react";
import { Outlet } from "react-router-dom";
import { FiMenu } from "react-icons/fi";
import ChatSidebar from "@/components/social/chat/ChatSidebar";

export default function ChatLayout() {
  const [open, setOpen] = useState(true);

  // Close sidebar on mobile when a chat is selected (called from NavLink onClick)
  const handleSelectChat = () => {
    if (window.innerWidth < 640) setOpen(false);
  };

  return (
    // Mobile:  sidebar=100%+0  or  sidebar=0+100%
    // Desktop: sidebar=280px+1fr  or  sidebar=0+1fr
    <div
      className={[
        "grid transition-[grid-template-columns] duration-200",
        "h-full",
        open
          ? "grid-cols-[100%_0] sm:grid-cols-[280px_1fr]"
          : "grid-cols-[0_100%]  sm:grid-cols-[0px_1fr]",
      ].join(" ")}
    >
      {/* Sidebar */}
      <div className="overflow-hidden">
        <ChatSidebar onClose={() => setOpen(false)} onSelectChat={handleSelectChat} />
      </div>

      {/* Chat pane */}
      <section className="relative flex h-full flex-col overflow-hidden">
        {/* Show-sidebar button — only when sidebar is collapsed */}
        {!open && (
          <button
            type="button"
            onClick={() => setOpen(true)}
            className="absolute left-3 top-4 z-20 flex h-7 w-7 items-center justify-center rounded-full bg-brand-bgLight/60 text-brand-text/60 hover:bg-brand-lines/20 hover:text-brand-text transition-colors"
            aria-label="Show sidebar"
          >
            <FiMenu size={15} />
          </button>
        )}
        <Outlet />
      </section>
    </div>
  );
}
