"use client";

import React, { useEffect, useMemo, useState } from "react";
import Header from "../Header/Header";
import ChatSidebar from "./ChatSidebar";
import "./style.css";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { useAppDispatch } from "@/app/lib/hooks";
import { toggleChat } from "@/app/store/chatSlice";
export default function LayoutShell({
  children,
}: {
  children: React.ReactNode;
}) {
  const [isMobile, setIsMobile] = useState(false);

  const dispatch = useAppDispatch();
  // sidebar widths
  const openWidth = 320; // px
  const closedWidth = 0; // px (fully hidden). If you want small strip, set 56.
  const chatOpen = useSelector((state: any) => state.ui.chatOpen);
  const sidebarWidth = chatOpen ? openWidth : closedWidth;

  const gridStyle = useMemo(
    () => ({
      gridTemplateColumns: isMobile ? "1fr" : `${sidebarWidth}px 1fr`,
      transition: "grid-template-columns 300ms ease",
    }),
    [sidebarWidth, isMobile],
  );

  useEffect(() => {
    const mq = window.matchMedia("(max-width: 767px)");
    const onChange = () => setIsMobile(mq.matches);
    onChange();
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);

  return (
    <div className="min-h-screen">
      <Header />

      {/* Page layout below header */}
      <div className="grid w-full" style={gridStyle}>
        <div
          className={
            isMobile
              ? "fixed left-0 top-10 bottom-0 z-50"
              : "relative overflow-visible"
          }
          style={
            isMobile
              ? {
                  width: openWidth,
                  transform: chatOpen ? "translateX(0)" : "translateX(-100%)",
                  transition: "transform 300ms ease",
                }
              : {
                  width: openWidth,
                  transform: chatOpen ? "translateX(0)" : "translateX(-100%)",
                  transition: "transform 300ms ease",
                }
          }
        >
          {/* Sidebar (overflow hidden yahan rahega) */}
          <div className=" overflow-hidden">
            <ChatSidebar open={chatOpen} />
          </div>

          {/* Toggle Arrow (overflow se bahar) */}
          <button
            onClick={() => dispatch(toggleChat())}
            className="
      absolute
      -right-6
      bottom-16
      h-6 w-6
      z-50
      px-1
      bg-white/10 hover:bg-white/20
      flex items-center justify-center
    "
          >
            <img
              src="/images/chatbot/left.png"
              alt=""
              className={`transition-transform ${chatOpen ? "" : "rotate-180"}`}
            />
          </button>
        </div>

        {/* RIGHT: Website content */}
        <main className="min-w-0 px-6 h-[calc(100dvh-94px)] overflow-auto nice-scrollbar">
          {children}
        </main>
      </div>
    </div>
  );
}
