import React from 'react';
import { Editor } from '@craftjs/core';
import { EditorShell } from './editor/EditorShell';
import { componentResolver } from './components/resolver';
import { WhpConfig } from './types';
import { EditorConfigProvider } from './state/EditorConfigContext';
import { SiteDesignProvider } from './state/SiteDesignContext';
import { PageProvider } from './state/PageContext';
import { SitesmithProvider, useSitesmithModal } from './state/SitesmithContext';
import { SitesmithModal } from './panels/sitesmith/SitesmithModal';

interface AppProps {
  whpConfig: WhpConfig | null;
}

const SitesmithModalMount: React.FC = () => {
  const { isOpen, target, close } = useSitesmithModal();
  if (!isOpen) return null;
  return <SitesmithModal target={target} onClose={close} />;
};

export const App: React.FC<AppProps> = ({ whpConfig }) => {
  return (
    <EditorConfigProvider config={whpConfig}>
      <SiteDesignProvider>
        <Editor resolver={componentResolver} enabled={true}>
          <PageProvider>
            <SitesmithProvider>
              <EditorShell />
              <SitesmithModalMount />
            </SitesmithProvider>
          </PageProvider>
        </Editor>
      </SiteDesignProvider>
    </EditorConfigProvider>
  );
};
