'use client';

import dynamic from 'next/dynamic';
import { useEffect, useState } from 'react';
import { getAnnotatorAssets } from '@/app/actions/getAnnotatorAssets';
import { submitAnnotations } from '@/app/actions/submitAnnotations';

const Annotator = dynamic(() => import('@/components/annotator-local/Annotator').then(mod => mod.Annotator), { ssr: false });

export default function AnnotatorClientWrapper() {
  const [assets, setAssets] = useState<string[]>([]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Toggle key from Annotator.tsx is Shift+A
      if (e.shiftKey && e.key === "A") {
        setAssets((prev) => {
          if (prev.length === 0) {
            getAnnotatorAssets().then(fetchedAssets => {
              if (Array.isArray(fetchedAssets)) {
                setAssets(fetchedAssets);
              }
            }).catch(err => console.error('[AnnotatorClientWrapper] Fetch failed:', err));
          }
          return prev;
        });
      }
    };
    
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  const handleSubmit = async (annotations: any[]) => {
    const result = await submitAnnotations(annotations);
    if (!result.success) {
      throw new Error(result.error);
    }
  };

  return <Annotator assets={assets} onSubmit={handleSubmit} />;
}
