import { renderHook, act } from '@testing-library/react';
import { useStore } from '../store';

// Mock localStorage
const localStorageMock = (() => {
  let store: { [key: string]: string } = {};
  return {
    getItem: jest.fn((key: string) => store[key] || null),
    setItem: jest.fn((key: string, value: string) => {
      store[key] = value;
    }),
    removeItem: jest.fn((key: string) => {
      delete store[key];
    }),
    clear: jest.fn(() => {
      store = {};
    }),
  };
})();

Object.defineProperty(window, 'localStorage', { value: localStorageMock });

describe('useStore', () => {
  beforeEach(() => {
    // Reset store state between tests
    const { result } = renderHook(() => useStore());
    act(() => {
      result.current.setNodes([]);
      result.current.setEdges([]);
      result.current.setSelectedNode(null);
      result.current.setSelectedEdge(null);
      result.current.setSelectedNodes([]);
      result.current.setSelectedEdges([]);
      result.current.setComponents([]);
      result.current.setModelData(null);
      result.current.setVisibleStartNodeIds(null);
    });
  });

  describe('nodes management', () => {
    it('should initialize with empty nodes array', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.nodes).toEqual([]);
    });

    it('should set nodes with array', () => {
      const { result } = renderHook(() => useStore());
      const testNodes = [
        { id: 'node_1', position: { x: 0, y: 0 }, data: { label: 'Node 1' } },
        { id: 'node_2', position: { x: 100, y: 100 }, data: { label: 'Node 2' } },
      ];

      act(() => {
        result.current.setNodes(testNodes);
      });

      expect(result.current.nodes).toEqual(testNodes);
    });

    it('should set nodes with function', () => {
      const { result } = renderHook(() => useStore());
      const initialNode = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };

      act(() => {
        result.current.setNodes([initialNode]);
      });

      act(() => {
        result.current.setNodes(prev => [...prev, { id: 'node_2', position: { x: 100, y: 100 }, data: {} }]);
      });

      expect(result.current.nodes).toHaveLength(2);
    });

    it('should add a node', () => {
      const { result } = renderHook(() => useStore());
      const newNode = { id: 'node_1', position: { x: 0, y: 0 }, data: { label: 'New Node' } };

      act(() => {
        result.current.addNode(newNode);
      });

      expect(result.current.nodes).toContainEqual(newNode);
    });

    it('should remove a node', () => {
      const { result } = renderHook(() => useStore());
      const node1 = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };
      const node2 = { id: 'node_2', position: { x: 100, y: 100 }, data: {} };

      act(() => {
        result.current.setNodes([node1, node2]);
      });

      act(() => {
        result.current.removeNode('node_1');
      });

      expect(result.current.nodes).toHaveLength(1);
      expect(result.current.nodes[0].id).toBe('node_2');
    });

    it('should remove connected edges when removing a node', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setNodes([
          { id: 'node_1', position: { x: 0, y: 0 }, data: {} },
          { id: 'node_2', position: { x: 100, y: 100 }, data: {} },
        ]);
        result.current.setEdges([
          { id: 'edge_1', source: 'node_1', target: 'node_2' },
        ]);
      });

      act(() => {
        result.current.removeNode('node_1');
      });

      expect(result.current.edges).toHaveLength(0);
    });

    it('should update a node', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: { label: 'Original' } };

      act(() => {
        result.current.setNodes([node]);
      });

      act(() => {
        result.current.updateNode('node_1', { data: { label: 'Updated' } });
      });

      expect(result.current.nodes[0].data.label).toBe('Updated');
    });
  });

  describe('edges management', () => {
    it('should initialize with empty edges array', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.edges).toEqual([]);
    });

    it('should add an edge', () => {
      const { result } = renderHook(() => useStore());
      const newEdge = { id: 'edge_1', source: 'node_1', target: 'node_2' };

      act(() => {
        result.current.addEdge(newEdge);
      });

      expect(result.current.edges).toContainEqual(newEdge);
    });

    it('should remove an edge', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setEdges([
          { id: 'edge_1', source: 'node_1', target: 'node_2' },
          { id: 'edge_2', source: 'node_2', target: 'node_3' },
        ]);
      });

      act(() => {
        result.current.removeEdge('edge_1');
      });

      expect(result.current.edges).toHaveLength(1);
      expect(result.current.edges[0].id).toBe('edge_2');
    });

    it('should update an edge', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setEdges([
          { id: 'edge_1', source: 'node_1', target: 'node_2', data: { label: 'Original' } },
        ]);
      });

      act(() => {
        result.current.updateEdge('edge_1', { data: { label: 'Updated' } });
      });

      expect(result.current.edges[0].data.label).toBe('Updated');
    });
  });

  describe('selection management', () => {
    it('should set selected node', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };

      act(() => {
        result.current.setSelectedNode(node);
      });

      expect(result.current.selectedNode).toEqual(node);
    });

    it('should clear selected node', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };

      act(() => {
        result.current.setSelectedNode(node);
      });

      act(() => {
        result.current.setSelectedNode(null);
      });

      expect(result.current.selectedNode).toBeNull();
    });

    it('should set selected edge', () => {
      const { result } = renderHook(() => useStore());
      const edge = { id: 'edge_1', source: 'node_1', target: 'node_2' };

      act(() => {
        result.current.setSelectedEdge(edge);
      });

      expect(result.current.selectedEdge).toEqual(edge);
    });

    it('should manage multiple node selection', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedNodes(['node_1', 'node_2']);
      });

      expect(result.current.selectedNodes).toEqual(['node_1', 'node_2']);
    });

    it('should add to selected nodes', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedNodes(['node_1']);
      });

      act(() => {
        result.current.addToSelectedNodes('node_2');
      });

      expect(result.current.selectedNodes).toContain('node_1');
      expect(result.current.selectedNodes).toContain('node_2');
    });

    it('should remove from selected nodes', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedNodes(['node_1', 'node_2']);
      });

      act(() => {
        result.current.removeFromSelectedNodes('node_1');
      });

      expect(result.current.selectedNodes).not.toContain('node_1');
      expect(result.current.selectedNodes).toContain('node_2');
    });

    it('should clear selection', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedNodes(['node_1', 'node_2']);
        result.current.setSelectedEdges(['edge_1']);
        result.current.setSelectedNode({ id: 'node_1', position: { x: 0, y: 0 }, data: {} });
        result.current.setSelectedEdge({ id: 'edge_1', source: 'node_1', target: 'node_2' });
      });

      act(() => {
        result.current.clearSelection();
      });

      expect(result.current.selectedNodes).toEqual([]);
      expect(result.current.selectedEdges).toEqual([]);
      expect(result.current.selectedNode).toBeNull();
      expect(result.current.selectedEdge).toBeNull();
    });

    it('should atomically select a node and clear all other selection', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };
      const edge = { id: 'edge_1', source: 'a', target: 'b' };

      // Set up prior selection
      act(() => {
        result.current.setSelectedEdge(edge);
        result.current.setSelectedEdges(['edge_1']);
        result.current.setSelectedNodes(['other_node']);
      });

      act(() => {
        result.current.selectNode(node);
      });

      expect(result.current.selectedNode).toBe(node);
      expect(result.current.selectedEdge).toBeNull();
      expect(result.current.selectedNodes).toEqual(['node_1']);
      expect(result.current.selectedEdges).toEqual([]);
    });

    it('should atomically select an edge and clear all other selection', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };
      const edge = { id: 'edge_1', source: 'a', target: 'b' };

      // Set up prior selection
      act(() => {
        result.current.setSelectedNode(node);
        result.current.setSelectedNodes(['node_1']);
        result.current.setSelectedEdges(['other_edge']);
      });

      act(() => {
        result.current.selectEdge(edge);
      });

      expect(result.current.selectedEdge).toBe(edge);
      expect(result.current.selectedNode).toBeNull();
      expect(result.current.selectedEdges).toEqual(['edge_1']);
      expect(result.current.selectedNodes).toEqual([]);
    });

    it('should clear selected node when removing it', () => {
      const { result } = renderHook(() => useStore());
      const node = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };

      act(() => {
        result.current.setNodes([node]);
        result.current.setSelectedNode(node);
      });

      act(() => {
        result.current.removeNode('node_1');
      });

      expect(result.current.selectedNode).toBeNull();
    });

    it('should track selection source', () => {
      const { result } = renderHook(() => useStore());

      expect(result.current.lastSelectionSource).toBe('none');

      act(() => {
        result.current.setLastSelectionSource('canvas');
      });

      expect(result.current.lastSelectionSource).toBe('canvas');

      act(() => {
        result.current.setLastSelectionSource('replay');
      });

      expect(result.current.lastSelectionSource).toBe('replay');
    });
  });

  describe('components management', () => {
    it('should set components', () => {
      const { result } = renderHook(() => useStore());
      const components = [
        { label: 'Component 1', plugin: 'plugin_1' },
        { label: 'Component 2', plugin: 'plugin_2' },
      ];

      act(() => {
        result.current.setComponents(components);
      });

      expect(result.current.components).toEqual(components);
    });
  });

  describe('favorite components management', () => {
    it('should initialize with empty favorite components', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.favoriteComponents).toEqual({});
    });

    it('should set favorite components', () => {
      const { result } = renderHook(() => useStore());
      const favorites = {
        1: ['test_base:test_custom', 'content_entity:update'],
        4: ['action_message_action', 'test_token_set_value'],
        5: ['test_scalar', 'test_count'],
      };

      act(() => {
        result.current.setFavoriteComponents(favorites);
      });

      expect(result.current.favoriteComponents).toEqual(favorites);
    });

    it('should overwrite existing favorite components', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setFavoriteComponents({ 1: ['plugin_a'] });
      });

      act(() => {
        result.current.setFavoriteComponents({ 4: ['plugin_b'] });
      });

      expect(result.current.favoriteComponents).toEqual({ 4: ['plugin_b'] });
    });
  });

  describe('model data management', () => {
    it('should set model data', () => {
      const { result } = renderHook(() => useStore());
      const modelData = {
        id: 'model_1',
        version: '1.0',
        metadata: {
          label: 'Test Model',
          description: 'A test model',
        },
      };

      act(() => {
        result.current.setModelData(modelData);
      });

      expect(result.current.modelData).toEqual(modelData);
    });

    it('should update model data with function', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setModelData({ id: 'model_1', metadata: { label: 'Initial' } });
      });

      act(() => {
        result.current.setModelData(prev => ({
          ...prev,
          metadata: { ...prev?.metadata, label: 'Updated' },
        }));
      });

      expect(result.current.modelData?.metadata?.label).toBe('Updated');
    });
  });

  describe('panel state management', () => {
    it('should set panel width', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setPanelWidth(400);
      });

      expect(result.current.panelWidth).toBe(400);
    });

    it('should set panel resizing state', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setPanelResizing(true);
      });

      expect(result.current.panelIsResizing).toBe(true);
    });

    it('should toggle component panel collapse', () => {
      const { result } = renderHook(() => useStore());
      const initialState = result.current.componentPanelCollapsed;

      act(() => {
        result.current.toggleComponentPanelCollapse();
      });

      expect(result.current.componentPanelCollapsed).toBe(!initialState);
    });

    it('should toggle property panel collapse', () => {
      const { result } = renderHook(() => useStore());
      const initialState = result.current.propertyPanelCollapsed;

      act(() => {
        result.current.togglePropertyPanelCollapse();
      });

      expect(result.current.propertyPanelCollapsed).toBe(!initialState);
    });
  });

  describe('config modal state', () => {
    it('should open config modal with data', () => {
      const { result } = renderHook(() => useStore());
      const modalData = { nodeId: 'node_1', type: 'element' };

      act(() => {
        result.current.openConfigModal(modalData);
      });

      expect(result.current.configModalOpen).toBe(true);
      expect(result.current.configModalData).toEqual(modalData);
    });

    it('should close config modal', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.openConfigModal({ nodeId: 'node_1' });
      });

      act(() => {
        result.current.closeConfigModal();
      });

      expect(result.current.configModalOpen).toBe(false);
      expect(result.current.configModalData).toBeNull();
    });
  });

  describe('viewport target state', () => {
    it('should set viewport target', () => {
      const { result } = renderHook(() => useStore());
      const target = { type: 'center' as const, nodeId: 'node_1' };

      act(() => {
        result.current.setViewportTarget(target);
      });

      expect(result.current.viewportTarget).toEqual(target);
    });

    it('should clear viewport target', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setViewportTarget({ type: 'center', nodeId: 'node_1' });
      });

      act(() => {
        result.current.setViewportTarget(null);
      });

      expect(result.current.viewportTarget).toBeNull();
    });
  });

  describe('edge selection management', () => {
    it('should add to selected edges', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedEdges(['edge_1']);
      });

      act(() => {
        result.current.addToSelectedEdges('edge_2');
      });

      expect(result.current.selectedEdges).toContain('edge_1');
      expect(result.current.selectedEdges).toContain('edge_2');
    });

    it('should remove from selected edges', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setSelectedEdges(['edge_1', 'edge_2']);
      });

      act(() => {
        result.current.removeFromSelectedEdges('edge_1');
      });

      expect(result.current.selectedEdges).not.toContain('edge_1');
      expect(result.current.selectedEdges).toContain('edge_2');
    });
  });

  describe('component panel management', () => {
    it('should set component panel width', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setComponentPanelWidth(400);
      });

      expect(result.current.componentPanelWidth).toBe(400);
    });

    it('should clamp component panel width to minimum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setComponentPanelWidth(50); // below minimum
      });

      expect(result.current.componentPanelWidth).toBeGreaterThanOrEqual(180);
    });

    it('should clamp component panel width to maximum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setComponentPanelWidth(1000); // above maximum
      });

      expect(result.current.componentPanelWidth).toBeLessThanOrEqual(600);
    });

    it('should set component panel resizing state', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setComponentPanelResizing(true);
      });

      expect(result.current.componentPanelIsResizing).toBe(true);
    });
  });

  describe('replay panel management', () => {
    it('should set replay panel width', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setReplayPanelWidth(500);
      });

      expect(result.current.replayPanelWidth).toBe(500);
    });

    it('should clamp replay panel width to minimum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setReplayPanelWidth(50); // below minimum
      });

      expect(result.current.replayPanelWidth).toBeGreaterThanOrEqual(200);
    });

    it('should set replay panel resizing state', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setReplayPanelResizing(true);
      });

      expect(result.current.replayPanelIsResizing).toBe(true);
    });

    it('should toggle replay panel collapse', () => {
      const { result } = renderHook(() => useStore());
      const initialState = result.current.replayPanelCollapsed;

      act(() => {
        result.current.toggleReplayPanelCollapse();
      });

      expect(result.current.replayPanelCollapsed).toBe(!initialState);
    });
  });

  describe('applyNodeChanges and applyEdgeChanges', () => {
    it('should apply node position changes', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setNodes([
          { id: 'node_1', position: { x: 0, y: 0 }, data: {} },
        ]);
      });

      act(() => {
        result.current.applyNodeChanges([
          { id: 'node_1', type: 'position', position: { x: 100, y: 100 } },
        ]);
      });

      expect(result.current.nodes[0].position).toEqual({ x: 100, y: 100 });
    });

    it('should apply edge selection changes', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setEdges([
          { id: 'edge_1', source: 'node_1', target: 'node_2' },
        ]);
      });

      act(() => {
        result.current.applyEdgeChanges([
          { id: 'edge_1', type: 'select', selected: true },
        ]);
      });

      expect(result.current.edges[0].selected).toBe(true);
    });
  });

  describe('selection preservation on removal', () => {
    it('should preserve selectedNode when removing a different node', () => {
      const { result } = renderHook(() => useStore());
      const node1 = { id: 'node_1', position: { x: 0, y: 0 }, data: {} };
      const node2 = { id: 'node_2', position: { x: 100, y: 100 }, data: {} };

      act(() => {
        result.current.setNodes([node1, node2]);
        result.current.setSelectedNode(node1);
        result.current.setSelectedNodes(['node_1']);
      });

      act(() => {
        result.current.removeNode('node_2');
      });

      // selectedNode should still be node1
      expect(result.current.selectedNode).toEqual(node1);
      expect(result.current.selectedNodes).toContain('node_1');
    });

    it('should preserve selectedEdge when removing a different edge', () => {
      const { result } = renderHook(() => useStore());
      const edge1 = { id: 'edge_1', source: 'node_1', target: 'node_2' };
      const edge2 = { id: 'edge_2', source: 'node_2', target: 'node_3' };

      act(() => {
        result.current.setEdges([edge1, edge2]);
        result.current.setSelectedEdge(edge1);
        result.current.setSelectedEdges(['edge_1']);
      });

      act(() => {
        result.current.removeEdge('edge_2');
      });

      // selectedEdge should still be edge1
      expect(result.current.selectedEdge).toEqual(edge1);
      expect(result.current.selectedEdges).toContain('edge_1');
    });

    it('should clear selectedEdge when removing the selected edge', () => {
      const { result } = renderHook(() => useStore());
      const edge = { id: 'edge_1', source: 'node_1', target: 'node_2' };

      act(() => {
        result.current.setEdges([edge]);
        result.current.setSelectedEdge(edge);
        result.current.setSelectedEdges(['edge_1']);
      });

      act(() => {
        result.current.removeEdge('edge_1');
      });

      expect(result.current.selectedEdge).toBeNull();
      expect(result.current.selectedEdges).not.toContain('edge_1');
    });
  });

  describe('panel width clamping', () => {
    it('should clamp property panel width to minimum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setPanelWidth(50); // Below minimum
      });

      expect(result.current.panelWidth).toBeGreaterThanOrEqual(200);
    });

    it('should clamp property panel width to maximum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setPanelWidth(2000); // Above maximum
      });

      expect(result.current.panelWidth).toBeLessThanOrEqual(800);
    });

    it('should clamp replay panel width to maximum', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setReplayPanelWidth(2000); // Above maximum
      });

      expect(result.current.replayPanelWidth).toBeLessThanOrEqual(800);
    });
  });

  describe('setEdges with function', () => {
    it('should update edges using a function', () => {
      const { result } = renderHook(() => useStore());
      const initialEdge = { id: 'edge_1', source: 'node_1', target: 'node_2' };

      act(() => {
        result.current.setEdges([initialEdge]);
      });

      act(() => {
        result.current.setEdges(prev => [
          ...prev,
          { id: 'edge_2', source: 'node_2', target: 'node_3' },
        ]);
      });

      expect(result.current.edges).toHaveLength(2);
      expect(result.current.edges[1].id).toBe('edge_2');
    });
  });

  describe('context config management', () => {
    it('should initialize with empty context config', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.contextConfig).toEqual({});
    });

    it('should set context config', () => {
      const { result } = renderHook(() => useStore());
      const config = { event: 'entity:insert', type: 'node' };

      act(() => {
        result.current.setContextConfig(config);
      });

      expect(result.current.contextConfig).toEqual(config);
    });

    it('should overwrite existing context config', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setContextConfig({ key1: 'value1' });
      });

      act(() => {
        result.current.setContextConfig({ key2: 'value2' });
      });

      expect(result.current.contextConfig).toEqual({ key2: 'value2' });
    });

    it('should allow clearing context config with empty object', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setContextConfig({ event: 'entity:insert' });
      });

      act(() => {
        result.current.setContextConfig({});
      });

      expect(result.current.contextConfig).toEqual({});
    });
  });

  describe('visibleStartNodeIds management', () => {
    it('should initialize visibleStartNodeIds as null', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.visibleStartNodeIds).toBeNull();
    });

    it('should set visibleStartNodeIds to an array of IDs', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setVisibleStartNodeIds(['node_1', 'node_2']);
      });

      expect(result.current.visibleStartNodeIds).toEqual(['node_1', 'node_2']);
    });

    it('should set visibleStartNodeIds back to null', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setVisibleStartNodeIds(['node_1']);
      });

      act(() => {
        result.current.setVisibleStartNodeIds(null);
      });

      expect(result.current.visibleStartNodeIds).toBeNull();
    });

    it('should overwrite existing visibleStartNodeIds', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setVisibleStartNodeIds(['a']);
      });

      act(() => {
        result.current.setVisibleStartNodeIds(['b', 'c']);
      });

      expect(result.current.visibleStartNodeIds).toEqual(['b', 'c']);
    });
  });

  describe('token dragging state', () => {
    it('should initialize isTokenDragging as false', () => {
      const { result } = renderHook(() => useStore());
      expect(result.current.isTokenDragging).toBe(false);
    });

    it('should set isTokenDragging to true', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setTokenDragging(true);
      });

      expect(result.current.isTokenDragging).toBe(true);
    });

    it('should set isTokenDragging back to false', () => {
      const { result } = renderHook(() => useStore());

      act(() => {
        result.current.setTokenDragging(true);
      });

      act(() => {
        result.current.setTokenDragging(false);
      });

      expect(result.current.isTokenDragging).toBe(false);
    });
  });

  describe('localStorage error handling', () => {
    it('should handle localStorage errors gracefully', () => {
      // This tests the loadPanelWidth error handling
      const originalGetItem = localStorageMock.getItem;

      // Mock getItem to throw for panel width key
      localStorageMock.getItem.mockImplementation((key: string) => {
        if (key === 'workflow-modeler-property-panel-width') {
          throw new Error('localStorage error');
        }
        return null;
      });

      // Re-import to trigger loadPanelWidth
      jest.resetModules();

      // The store should still initialize with default values
      // even if localStorage throws
      localStorageMock.getItem = originalGetItem;
    });

    it('should handle invalid panel width in localStorage', () => {
      localStorageMock.getItem.mockReturnValue('invalid-number');

      const { result } = renderHook(() => useStore());

      // Should use default width since stored value is invalid
      expect(result.current.panelWidth).toBeGreaterThanOrEqual(200);
    });

    it('should handle out-of-range panel width in localStorage', () => {
      // Store a value outside valid range
      localStorageMock.getItem.mockReturnValue('50'); // Below minimum

      // The loadPanelWidth function should return default if outside range
      const { result } = renderHook(() => useStore());

      expect(result.current.panelWidth).toBeGreaterThanOrEqual(200);
    });
  });
});
