/**
 * Form Builder Bundle Entry Point for jlocal
 * 
 * This provides a clean API for using the FormBuilder component
 * in jlocal's Vue application context.
 */
import { createApp, h, ref } from "vue";
import { createPinia } from "pinia";
import FormBuilderComponent from "./FormBuilder.vue";
import { registerGlobalComponents } from "./globals.js";
import { useFormBuilderStore, ALL_FIELDTYPES, LAYOUT_FIELDS, NO_VALUE_TYPES, DEFAULT_PAGEFIELD_PROPERTIES } from "./store";
import * as utils from "./utils.js";

/**
 * Create and mount a FormBuilder instance
 * @param {Object} options - Configuration options
 * @param {HTMLElement|string} options.container - DOM element or selector to mount to
 * @param {Array} options.fields - Initial field definitions
 * @param {string} options.pagetype - The pagetype name
 * @param {boolean} [options.readOnly=false] - Whether the form is read-only
 * @param {boolean} [options.isCustomizeForm=false] - Whether this is customize form mode
 * @param {Function} [options.onSave] - Callback when save is triggered
 * @param {Function} [options.onDirtyChange] - Callback when dirty state changes
 * @returns {Object} FormBuilder instance with control methods
 */
export function createFormBuilder(options) {
  const {
    container,
    fields = [],
    pagetype = "",
    readOnly = false,
    isCustomizeForm = false,
    onSave,
    onDirtyChange,
  } = options;

  // Resolve container element
  const el = typeof container === "string" 
    ? document.querySelector(container) 
    : container;

  if (!el) {
    throw new Error("FormBuilder: Invalid container element");
  }

  // Create pinia instance
  const pinia = createPinia();

  // Track current fields
  const currentFields = ref([...fields]);

  // Create Vue app
  const app = createApp({
    setup() {
      return () => h(FormBuilderComponent, {
        fields: currentFields.value,
        pagetype,
        readOnly,
        isCustomizeForm,
        "onUpdate:fields": (newFields) => {
          currentFields.value = newFields;
        },
        onSave: () => {
          onSave?.(currentFields.value);
        },
        onDirtyChange: (isDirty) => {
          onDirtyChange?.(isDirty);
        },
        ref: "formBuilder",
      });
    },
  });

  app.use(pinia);
  registerGlobalComponents(app);

  // Mount the app
  const instance = app.mount(el);

  // Get store reference
  const store = useFormBuilderStore();

  // Return control API
  return {
    /**
     * Get the current field definitions
     * @returns {Array} Current fields
     */
    getFields() {
      return store.getUpdatedFields();
    },

    /**
     * Set new fields
     * @param {Array} newFields - New field definitions
     */
    setFields(newFields) {
      currentFields.value = [...newFields];
      store.initialize({ fields: newFields, pagetype });
    },

    /**
     * Validate the current form configuration
     * @returns {boolean} Whether validation passed
     */
    validate() {
      return store.validateFields();
    },

    /**
     * Check if there are unsaved changes
     * @returns {boolean} Dirty state
     */
    isDirty() {
      return store.dirty;
    },

    /**
     * Reset dirty state
     */
    resetDirty() {
      store.dirty = false;
    },

    /**
     * Set read-only mode
     * @param {boolean} value - Read-only state
     */
    setReadOnly(value) {
      store.read_only = value;
    },

    /**
     * Toggle preview mode
     */
    togglePreview() {
      store.preview = !store.preview;
      store.read_only = store.preview;
    },

    /**
     * Get the Pinia store instance
     * @returns {Object} Store instance
     */
    getStore() {
      return store;
    },

    /**
     * Unmount and cleanup
     */
    destroy() {
      app.unmount();
    },
  };
}

// Export components and utilities for direct usage
export { FormBuilderComponent as FormBuilder };
export { useFormBuilderStore };
export { registerGlobalComponents };
export { ALL_FIELDTYPES, LAYOUT_FIELDS, NO_VALUE_TYPES, DEFAULT_PAGEFIELD_PROPERTIES };
export { utils };

// Default export
export default {
  createFormBuilder,
  FormBuilder: FormBuilderComponent,
  useFormBuilderStore,
  registerGlobalComponents,
  ALL_FIELDTYPES,
  LAYOUT_FIELDS,
  NO_VALUE_TYPES,
  DEFAULT_PAGEFIELD_PROPERTIES,
  utils,
};
