import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';

export const DRAWER_WIDTH = 240;
export const DRAWER_WIDTH_COLLAPSED = 64;
export const CHAT_PANEL_MIN_WIDTH = 360;
export const CHAT_PANEL_MAX_WIDTH = 720;

interface LayoutContextType {
  sidebarCollapsed: boolean;
  chatPanelOpen: boolean;
  chatPanelWidth: number;
  toggleSidebar: () => void;
  toggleChatPanel: () => void;
  setChatPanelOpen: (open: boolean) => void;
  setChatPanelWidth: (width: number) => void;
}

const LayoutContext = createContext<LayoutContextType | undefined>(undefined);

function getInitialCollapsed(): boolean {
  try {
    const stored = localStorage.getItem('sidebar-collapsed');
    return stored === 'true';
  } catch {
    return false;
  }
}

function getInitialChatPanelWidth(): number {
  try {
    const stored = localStorage.getItem('chat-panel-width');
    if (stored) {
      const parsed = parseInt(stored, 10);
      if (!isNaN(parsed)) {
        return Math.min(Math.max(parsed, CHAT_PANEL_MIN_WIDTH), CHAT_PANEL_MAX_WIDTH);
      }
    }
  } catch {
    // ignore storage errors
  }
  return CHAT_PANEL_MIN_WIDTH;
}

interface LayoutProviderProps {
  children: ReactNode;
}

export const LayoutProvider: React.FC<LayoutProviderProps> = ({ children }) => {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(getInitialCollapsed);
  const [chatPanelOpen, setChatPanelOpenState] = useState(false);
  const [chatPanelWidth, setChatPanelWidthState] = useState(getInitialChatPanelWidth);

  const toggleSidebar = useCallback(() => {
    setSidebarCollapsed((prev) => {
      const next = !prev;
      try {
        localStorage.setItem('sidebar-collapsed', String(next));
      } catch {
        // ignore storage errors
      }
      return next;
    });
  }, []);

  const toggleChatPanel = useCallback(() => {
    setChatPanelOpenState((prev) => !prev);
  }, []);

  const setChatPanelOpen = useCallback((open: boolean) => {
    setChatPanelOpenState(open);
  }, []);

  const setChatPanelWidth = useCallback((width: number) => {
    const clamped = Math.min(Math.max(width, CHAT_PANEL_MIN_WIDTH), CHAT_PANEL_MAX_WIDTH);
    setChatPanelWidthState(clamped);
    try {
      localStorage.setItem('chat-panel-width', String(clamped));
    } catch {
      // ignore storage errors
    }
  }, []);

  const value: LayoutContextType = {
    sidebarCollapsed,
    chatPanelOpen,
    chatPanelWidth,
    toggleSidebar,
    toggleChatPanel,
    setChatPanelOpen,
    setChatPanelWidth,
  };

  return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
};

export const useLayout = (): LayoutContextType => {
  const context = useContext(LayoutContext);
  if (context === undefined) {
    throw new Error('useLayout must be used within a LayoutProvider');
  }
  return context;
};

