"use client";

import type { DocumentStats, PageOptionsState } from "@/types/page-options";
import type { Json } from "@/types/supabase";
import type { ReferenceTarget } from "@/types/search";
import type { EditorHostKind } from "@/components/editor/editor-host-config";
import type { LeptosTiptapRuntimePageOptions } from "@/lib/documents/page-option-semantics";

export interface DocumentEditorHostProps {
  documentId: string;
  workspaceId: string;
  initialContent: unknown;
  title?: string | null;
  hostKind?: EditorHostKind;
  initialRevision?: number | null;
  initialConflictDetectionKey?: string | null;
  pageOptions: PageOptionsState;
  readOnly?: boolean;
  onStatsChange?: (stats: DocumentStats) => void;
  onSnapshot?: (payload: { blocks: Json; stats: DocumentStats }) => void;
  onCloseToc?: () => void;
  onPersistedMetaChange?: (payload: {
    revision: number | null;
    conflictDetectionKey: string | null;
  }) => void;
  onHostEvent?: (event: EditorHostEvent) => void;
  onRequestFallback?: (payload: EditorHostFallbackRequest) => void;
}

export type BlockNoteEditorProps = DocumentEditorHostProps;

export type EditorHostFallbackReason =
  | "runtime_load_failed"
  | "host_init_failed"
  | "command_failed"
  | "save_failed"
  | "explicit_fallback";

export type EditorHostFallbackRequest = {
  reason: EditorHostFallbackReason;
  error?: string | null;
  at: string;
};

export type EditorHostEvent =
  | {
      kind: "status_changed";
      status: string;
      at: string;
      message?: string | null;
    }
  | {
      kind: "runtime_load_failed" | "host_init_failed" | "command_failed" | "save_failed";
      at: string;
      message: string;
    }
  | {
      kind: "fallback_triggered";
      at: string;
      reason: EditorHostFallbackReason;
      message?: string | null;
    };

export type LeptosTiptapHostBridgeState = {
  ready: boolean;
  runtimeName: string;
  runtimeVersion: string;
  runtimeUrl: string;
  documentId: string;
  workspaceId: string;
  status: string;
  lastChangeAt?: string | null;
  lastSaveRequestAt?: string | null;
  lastError?: string | null;
};

export type LeptosTiptapHostBridgeEventDetail = {
  documentId: string;
  workspaceId: string;
  runtimeUrl: string;
  status?: string;
  payload?: unknown;
  snapshot?: { blocks: Json; stats?: DocumentStats };
  references?: ReferenceTarget[];
  revision?: number | null;
  conflictDetectionKey?: string | null;
  error?: string | null;
  at?: string;
};

export type { LeptosTiptapRuntimePageOptions };
