/**
 * WorkspaceKeepAlive
 *
 * Renders the WorkspacePage permanently at the MainLayout level so it
 * survives route changes.  Visibility is toggled via CSS `display`
 * instead of mount / unmount, preserving messages, SSE connections,
 * files, and all other workspace state.
 */

import React, { useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { WorkspacePage } from './WorkspacePage';

const _WORKSPACE_ROUTE_RE = /\/mandates\/([^/]+)\/workspace\/([^/]+)/;

interface WorkspaceKeepAliveProps {
  isVisible: boolean;
}

export const WorkspaceKeepAlive: React.FC<WorkspaceKeepAliveProps> = ({ isVisible }) => {
  const location = useLocation();
  const cachedInstanceIdRef = useRef<string>('');

  const match = location.pathname.match(_WORKSPACE_ROUTE_RE);
  if (match?.[2]) {
    cachedInstanceIdRef.current = match[2];
  }

  const instanceId = cachedInstanceIdRef.current;
  if (!instanceId) return null;

  return (
    <div
      style={{
        display: isVisible ? 'flex' : 'none',
        flexDirection: 'column',
        position: 'absolute',
        top: 'var(--mobile-topbar-height, 0px)',
        left: 0,
        right: 0,
        bottom: 0,
        overflow: 'hidden',
      }}
    >
      <WorkspacePage persistentInstanceId={instanceId} />
    </div>
  );
};
