'use client';

import React, { useState, useEffect } from 'react';
import { useRecordMode } from './RecordModeContext';
import { FeedbackOverlay } from '@mintel/next-feedback';
import { RecordModeOverlay } from './RecordModeOverlay';
import { PickingHelper } from './PickingHelper';

interface ToolCoordinatorProps {
  isEmbedded?: boolean;
  feedbackEnabled?: boolean;
}

export function ToolCoordinator({
  isEmbedded: isEmbeddedProp,
  feedbackEnabled = false,
}: ToolCoordinatorProps) {
  const { isActive, setIsActive, isFeedbackActive, setIsFeedbackActive, isEnabled } =
    useRecordMode();
  const [isEmbedded, setIsEmbedded] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const embedded =
      isEmbeddedProp ||
      window.location.search.includes('embedded=true') ||
      window.name === 'record-mode-iframe' ||
      window.self !== window.top;
    setIsEmbedded(embedded);
  }, [isEmbeddedProp]);

  if (!mounted) return null;

  // Nothing enabled → render nothing
  if (!feedbackEnabled && !isEnabled) return null;

  // Iframe → only PickingHelper
  if (isEmbedded) return <PickingHelper />;

  // Record Mode active and enabled
  if (isActive && isEnabled) return <RecordModeOverlay />;

  // Feedback active and enabled
  if (isFeedbackActive && feedbackEnabled) {
    return (
      <FeedbackOverlay
        isActive={isFeedbackActive}
        onActiveChange={(active) => setIsFeedbackActive(active)}
      />
    );
  }

  // Baseline: toggle buttons
  return (
    <div className="feedback-ui-ignore">
      {feedbackEnabled && (
        <FeedbackOverlay
          isActive={false}
          onActiveChange={(active) => setIsFeedbackActive(active)}
        />
      )}
      {isEnabled && <RecordModeOverlay />}
    </div>
  );
}
