/**
 * CommcoachKeepAlive
 *
 * Keeps the CommCoach dossier/coaching page mounted across route changes.
 * Visibility is toggled via CSS so session state, messages, and input state
 * stay alive when the user leaves and later returns.
 */

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

const _COMMCOACH_ROUTE_RE = /\/mandates\/([^/]+)\/commcoach\/([^/]+)\/(?:coaching|dossier)/;

interface CommcoachKeepAliveProps {
  isVisible: boolean;
}

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

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

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

export default CommcoachKeepAlive;
