import { createApp } from "vue";
import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n";
import { addressMessages } from "./i18n";
import App from "./App.vue";

const i18n = _createI18n(addressMessages);

const addAddressInput = (inputs) => {
  console.log(inputs);
  inputs.forEach((el) => {
    let addressId = el.value,
      uniqid = el.dataset.inputAddress,
      container = el.parentNode.querySelector(
        'div[data-input-address-container="' + uniqid + '"]',
      ),
      isEdit = addressId !== "",
      addressIdInt = addressId !== "" ? parseInt(addressId) : null;
    if (container === null) {
      throw Error("no container");
    }
    /* exported app */
    const app = createApp({
      template: `<app v-bind:addAddress="this.addAddress" @address-created="associateToInput"></app>`,
      data() {
        return {
          addAddress: {
            context: {
              // for legacy ? can be remove ?
              target: {
                name: "input-address",
                id: addressIdInt,
              },
              edit: isEdit,
              addressId: addressIdInt,
              defaults: window.addaddress,
            },
            options: {
              /// Options override default.
              /// null value take default component value defined in AddAddress data()
              button: {
                text: {
                  create: el.dataset.buttonTextCreate || null,
                  edit: el.dataset.buttonTextUpdate || null,
                },
                size: null,
                displayText: true,
              },

              /// Modal title text if create or edit address (trans chain, see i18n)
              title: {
                create: null,
                edit: null,
              },

              /// Display panes in Modal for step123
              openPanesInModal: true,

              /// Display actions buttons of panes in a sticky-form-button navbar
              stickyActions: false,
              showMessageWhenNoAddress: true,

              /// Use Date fields
              useDate: {
                validFrom: el.dataset.useValidFrom === "1" || false, //boolean, default: false
                validTo: el.dataset.useValidTo === "1" || false, //boolean, default: false
              },

              /// Don't display show renderbox Address: showPane display only a button
              onlyButton: false,
            },
          },
        };
      },
      methods: {
        associateToInput(payload) {
          el.value = payload.addressId;
        },
      },
    })
      .use(i18n)
      .component("app", App)
      .mount(container);
  });
};

document.addEventListener("DOMContentLoaded", (_e) =>
  addAddressInput(
    document.querySelectorAll('input[type="hidden"][data-input-address]'),
  ),
);

window.addEventListener("collection-add-entry", (e) =>
  addAddressInput(
    e.detail.entry.querySelectorAll('input[type="hidden"][data-input-address]'),
  ),
);
