"use client";

import { useMemo } from "react";
import { Editor } from "@reacteditor/core";
import createTailwindCdnPlugin from "@reacteditor/plugin-tailwind-cdn";
import type { UserConfig } from "@/config/types";

export type EditorShellProps = {
  config: UserConfig;
  data: any;
  routeKey?: string;
};

export function EditorShell({ config, data, routeKey }: EditorShellProps) {
  const plugins = useMemo(() => [createTailwindCdnPlugin()], []);

  const handlePublish = async (nextData: any, route?: any) => {
    const resolved = route ?? (routeKey ? { key: routeKey } : undefined);
    console.log({
      type: "PUBLISH",
      data: { data: nextData, route: JSON.stringify(resolved) },
    });
    if (typeof window !== "undefined" && window.parent !== window) {
      window.parent.postMessage(
        { type: "PUBLISH", data: { data: nextData, route: resolved } },
        "*",
      );
    }
    await new Promise((resolve) => setTimeout(resolve, 1000));
  };

  return (
    <div className="h-screen w-screen">
      <Editor
        config={config as any}
        data={data}
        plugins={plugins}
        iframe={{ enabled: true }}
        ui={{ leftSideBarVisible: false }}
        onPublish={handlePublish}
      />
    </div>
  );
}
