/**
 * CommcoachKeepAlive
 *
 * Keeps the CommCoach session page mounted across route changes.
 * The voice session must persist when the user navigates to other tabs.
 * Only the "session" tab is kept alive; modules/dashboard can unmount freely.
 *
 * Persistence is scoped per `(mandateId, instanceId)` — switching to a
 * different mandate or instance unmounts the previous view.
 */

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

const _COMMCOACH_SESSION_ROUTE_RE = /\/mandates\/([^/]+)\/commcoach\/([^/]+)\/session/;

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_SESSION_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;
  const scopeKey = `${mandateId}:${instanceId}`;

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

export default CommcoachKeepAlive;
