'use client';

/**
 * PanelCoordinator — ensures only one overlay (Sidebar or Right Panel)
 * is open at a time on mobile/tablet viewports (< 1024px).
 *
 * Watches both stores and closes one when the other opens on mobile.
 * Renders nothing — purely a side-effect component.
 *
 * Requirements: 11.4
 */

import { useEffect, useRef } from 'react';
import { useSidebarStore } from '@/lib/stores/sidebar-store';
import { useRightPanelStore } from '@/lib/stores/right-panel-store';

export default function PanelCoordinator() {
  const sidebarOpen = useSidebarStore((s) => s.isMobileOpen);
  const closeSidebar = useSidebarStore((s) => s.closeMobile);
  const panelOpen = useRightPanelStore((s) => s.isOpen);
  const closePanel = useRightPanelStore((s) => s.close);

  // Track previous values to detect which one just opened
  const prevSidebarOpen = useRef(sidebarOpen);
  const prevPanelOpen = useRef(panelOpen);

  useEffect(() => {
    // Only coordinate on mobile/tablet (< 1024px)
    const isSmallViewport = window.innerWidth < 1024;
    if (!isSmallViewport) {
      prevSidebarOpen.current = sidebarOpen;
      prevPanelOpen.current = panelOpen;
      return;
    }

    // Sidebar just opened — close right panel
    if (sidebarOpen && !prevSidebarOpen.current && panelOpen) {
      closePanel();
    }

    // Right panel just opened — close sidebar
    if (panelOpen && !prevPanelOpen.current && sidebarOpen) {
      closeSidebar();
    }

    prevSidebarOpen.current = sidebarOpen;
    prevPanelOpen.current = panelOpen;
  }, [sidebarOpen, panelOpen, closePanel, closeSidebar]);

  return null;
}
