'use client';

import { type ReactNode, useEffect, useState } from 'react';

import dynamic from 'next/dynamic';

import type { ConnectionPerson } from '@/components/Interactive2DGraph';

const Interactive2DGraph = dynamic(() => import('@/components/Interactive2DGraph'), { ssr: false });

const ConnectionsSectionClient = ({
  creatorId,
  name,
  connections,
  heightClassName = 'h-[520px]',
  controlsSlot,
  overlaySlot,
}: {
  creatorId: string;
  name: string;
  connections: ConnectionPerson[];
  heightClassName?: string;
  controlsSlot?: ReactNode;
  overlaySlot?: ReactNode;
}) => {
  const [isOpen, setIsOpen] = useState(false);
  // const t = useTranslations("connectionsGraph");

  useEffect(() => {
    if (!isOpen) return;

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen]);

  return (
    <div className="w-full">
      {isOpen && (
        <div className="fixed inset-0 z-[999] bg-black/70" onClick={() => setIsOpen(false)} />
      )}

      <div
        className={[
          'bg-slate-100',
          isOpen
            ? 'fixed inset-0 z-[1000] h-[100svh] w-[100vw]'
            : `relative w-full rounded-lg border border-slate-200 ${heightClassName}`,
        ].join(' ')}
      >
        <Interactive2DGraph
          creatorId={creatorId}
          creatorName={name}
          connections={connections}
          className="h-full w-full"
          showControls
          fullscreenMode={isOpen}
          onRequestFullscreen={() => setIsOpen(!isOpen)}
          controlsSlot={controlsSlot}
        />
        {overlaySlot ? (
          <div className="pointer-events-none absolute right-4 top-16 z-[9] flex justify-end sm:top-20">
            <div className="pointer-events-auto">{overlaySlot}</div>
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default ConnectionsSectionClient;
