// ChatLayout.jsx
import React, { useState, useEffect } from "react";
import ChatHeader from "./ChatHeader";
import ChatWindow from "./ChatWindow";
import ChatInput from "./ChatInput";
import SessionTable from "./SessionTable";
import NoSessionBox from "./NoSessionBox";

export default function ChatLayout({
  theme,
  messages,
  loading,
  onSend,
  onStop,
  onToggleTheme,
  onReloadHistory,
  onFreshStart,
  onCreateSession,
  onEditSession,
  onSelectSession,
  userId,
  sessionId,
  sessionName
}) {
  const [showSessionsPanel, setShowSessionsPanel] = useState(false);

  function getScrollbarWidth() {
    return window.innerWidth - document.documentElement.clientWidth;
  }

  useEffect(() => {
    document.body.classList.toggle("sessions-open", showSessionsPanel);
  }, [showSessionsPanel]);

  const openSessionManager = () => {
    const scrollBarWidth = getScrollbarWidth();
    document.body.style.overflow = "hidden";
    document.body.style.paddingRight = `${scrollBarWidth}px`;
    setShowSessionsPanel(true);
  };

  const closeSessionManager = () => {
    document.body.style.overflow = "";
    document.body.style.paddingRight = "";
    setShowSessionsPanel(false);
    document.body.classList.remove("sessions-open");
  };

  return (
    <>
      <div className={`chat-layout sessions-wrapper ${theme.bodyBg}`}>
        {/* HEADER */}
        <ChatHeader
          theme={theme}
          onToggleTheme={onToggleTheme}
          onReloadHistory={onReloadHistory}
          onFreshStart={onFreshStart}
          onCreateSession={onCreateSession}
          onEditSession={onEditSession}
          onManageSession={openSessionManager}
          sessionId={sessionId}
          sessionName={sessionName}
        />

        {/* AREA SCROLLABILE */}
        <div className="flex-grow-1 overflow-auto" style={{ minHeight: 0 }}>
          <ChatWindow messages={messages} loading={loading} theme={theme} />
        </div>

        {/* INPUT SEMPRE IN BASSO */}
        {sessionId ? (
          <ChatInput
            onSend={onSend}
            onStop={onStop}
            loading={loading}
          />
        ) : (
          <NoSessionBox onCreateSession={onCreateSession} />
        )}
      </div>

      {/* PANEL SESSIONI */}
      <div
        className={`offcanvas offcanvas-start ${showSessionsPanel ? "show" : ""}`}
        tabIndex="-1"
        style={{ visibility: showSessionsPanel ? "visible" : "hidden" }}
      >
        <div className="offcanvas-header">
          <h5 className="offcanvas-title">Manage Sessions</h5>
          <button
            type="button"
            className="btn-close text-reset"
            onClick={closeSessionManager}
          ></button>
        </div>
        <div className="offcanvas-body">
          <SessionTable
            userId={userId}
            onSelectSession={onSelectSession}
            onClosePanel={closeSessionManager}
          />
        </div>
      </div>
    </>
  );
}


