/**
 * GraphicalEditorKeepAlive
 *
 * Keeps the GraphicalEditorPage mounted across route changes so the canvas
 * state, SSE connections, and editor context survive navigation to ANY page
 * (other features, admin, settings, etc.).
 * Visibility is toggled via CSS `display` instead of mount / unmount.
 * Cached mandateId/instanceId are passed as props so the page does not
 * depend on URL params (which disappear on non-feature routes).
 */

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

const _GE_EDITOR_ROUTE_RE = /\/mandates\/([^/]+)\/graphicalEditor\/([^/]+)\/editor/;

interface GraphicalEditorKeepAliveProps {
  isVisible: boolean;
}

export const GraphicalEditorKeepAlive: React.FC<GraphicalEditorKeepAliveProps> = ({ isVisible }) => {
  const location = useLocation();
  const cachedMandateIdRef = useRef<string>('');
  const cachedInstanceIdRef = useRef<string>('');
  const hasEverMountedRef = useRef(false);

  const match = location.pathname.match(_GE_EDITOR_ROUTE_RE);
  if (match?.[1] && match?.[2]) {
    cachedMandateIdRef.current = match[1];
    cachedInstanceIdRef.current = match[2];
    hasEverMountedRef.current = true;
  }

  if (!hasEverMountedRef.current) 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',
      }}
    >
      <GraphicalEditorPage
        persistentInstanceId={cachedInstanceIdRef.current}
        persistentMandateId={cachedMandateIdRef.current}
      />
    </div>
  );
};

export default GraphicalEditorKeepAlive;
