import { useEffect, useRef } from 'react';
import { Allotment } from 'allotment';
import 'allotment/dist/style.css';
import type { WorkspaceDefinition } from '@/types/workbench';
import { MainAgentPane } from '@/features/terminal/MainAgentPane';
import { XTermPane } from '@/features/terminal/XTermPane';

interface PaneGridProps {
  workspace: WorkspaceDefinition;
}

export function PaneGrid({ workspace }: PaneGridProps) {
  const hostRef = useRef<HTMLDivElement>(null);
  const panes = workspace.layout.panes;

  useEffect(() => {
    const host = hostRef.current;
    if (!host) return;
    const notify = () => window.dispatchEvent(new Event('resize'));
    const observer = new ResizeObserver(() => {
      window.requestAnimationFrame(notify);
    });
    observer.observe(host);
    window.setTimeout(notify, 50);
    window.setTimeout(notify, 300);
    return () => observer.disconnect();
  }, [workspace.id, workspace.rootPath, panes.length]);

  const renderPane = (pane: (typeof panes)[0]) =>
    pane.role === 'mainAgent' ? (
      <MainAgentPane pane={pane} workspace={workspace} />
    ) : (
      <XTermPane pane={pane} workspace={workspace} />
    );

  if (panes.length === 1) {
    return <div ref={hostRef} className="pane-grid-host">{renderPane(panes[0])}</div>;
  }

  return (
    <div ref={hostRef} className="pane-grid-host">
    <Allotment
      vertical={workspace.layout.direction === 'vertical'}
      className="pane-grid"
    >
      {panes.map((pane) => (
        <Allotment.Pane
          key={pane.id}
          preferredSize={`${Math.round(pane.sizeWeight * 100)}%`}
          minSize={180}
        >
          {renderPane(pane)}
        </Allotment.Pane>
      ))}
    </Allotment>
    </div>
  );
}
