document.addEventListener('DOMContentLoaded', function () {
  const openAiModalButton = document.querySelector('.js-open-ai-selection-modal');

  function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    const results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  }

  const sessionId = getUrlParameter('sessionId');
  const page = getUrlParameter('page');

  if (page === 'starter-templates' && sessionId.trim() !== '') {
    generateTemplate(sessionId);
  } else if (openAiModalButton) {
    openAiModalButton.addEventListener('click', function (event) {
      event.preventDefault();
      typeGenerateModal();
    });
  }

  function generateTemplate(sessionId) {
    loadingModal(
      Brizy_Admin_Data.l10n.aiGenerateTemplateTitle,
      Brizy_Admin_Data.l10n.aiGenerateTemplateDesc,
    );

    const ajaxData = {
      action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.getTemplate,
      hash: Brizy_Admin_Data.aiNonce,
      sessionId: sessionId
    };

    fetch(Brizy_Admin_Data.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(ajaxData)
    })
      .then(response => response.json())
      .then(response => {
        if (response && response.success) {

          const content = getContentType();

          switch (content) {
            case 'delete':
              importContent(response.data, 'delete');
              break;
            case 'keep':
              importContent(response.data, 'keep');
              break;
            default:
              errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
              break;
          }
        } else {
          errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
        }
      })
      .catch(() => {
        errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
      });
  }

  function importContent(responseData, contentType) {
    loadingModal(
      Brizy_Admin_Data.l10n.aiBannerImportTitle,
      Brizy_Admin_Data.l10n.aiBannerImportDesc,
    );

    let actionName;
    switch (contentType) {
      case 'delete':
        actionName = Brizy_Admin_Data.aiActions.importDelete;
        break;
      case 'keep':
        actionName = Brizy_Admin_Data.aiActions.importKeep;
        break;
      default:
        errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
        return;
    }

    const ajaxData = {
      action: Brizy_Admin_Data.prefix + actionName,
      hash: Brizy_Admin_Data.aiNonce,
      body: JSON.stringify(responseData)
    };

    fetch(Brizy_Admin_Data.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(ajaxData)
    })
      .then(response => response.json())
      .then(response => {
        if (response && response.success) {
          if (response.data && response.data.editPageUrl) {
            const editPageUrl = response.data.editPageUrl;

            successModal(
              Brizy_Admin_Data.l10n.aiBannerSuccessTitle,
              Brizy_Admin_Data.l10n.aiBannerSuccessDesc,
              null,
              editPageUrl,
            );
          } else {
            errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
          }
        } else {
          errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
        }
      })
      .catch(() => {
        errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
      });
  }

  function successModal(titleText, descriptionText, buttonText, editUrl) {
    const modalElement = document.querySelector('.brz-demo-modal');
    const modalContentContainer = document.querySelector('.brz-demo-modal-content');
    const successTemplate = document.getElementById('brz-demo-modal-content-success');

    if (!modalElement || !modalContentContainer || !successTemplate) {
      return;
    }

    modalContentContainer.innerHTML = successTemplate.innerHTML;
    modalElement.classList.add('brz-demo-show-modal');

    const modalTitle = modalContentContainer.querySelector('.brz-demo-modal-content-h3');
    const editButton = modalContentContainer.querySelector('.js-demo-data-edit-homepage');
    const modalDescription = modalContentContainer.querySelector('.brz-demo-modal-content-p');

    if (titleText) {
      if (modalTitle) {
        modalTitle.textContent = titleText;
      }
    }

    if (descriptionText) {
      if (modalDescription) {
        modalDescription.textContent = descriptionText;
      }
    }

    if (buttonText) {
      if (editButton) {
        editButton.textContent = buttonText;
      }
    }

    if (editUrl) {
      if (editButton) {
        editButton.setAttribute('href', editUrl);
      }
    }
  }

  function typeGenerateModal() {
    const modalElement = document.querySelector('.brz-demo-modal');
    const modalContentContainer = document.querySelector('.brz-demo-modal-content');
    const installTemplate = document.getElementById('brz-demo-modal-content-install');

    if (!modalElement || !modalContentContainer || !installTemplate) {
      return;
    }

    modalContentContainer.innerHTML = installTemplate.innerHTML;
    modalElement.classList.add('brz-demo-show-modal');

    function handleContentAction(contentType) {
      return function (event) {
        event.preventDefault();
        event.stopPropagation();

        const buttonElement = event.currentTarget;

        if (buttonElement) {
          buttonElement.disabled = true;
        }

        loadingModal(
          Brizy_Admin_Data.l10n.aiCreatingSessionTitle,
          Brizy_Admin_Data.l10n.aiCreatingSessionDesc,
        );

        const ajaxData = {
          action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.createSession,
          hash: Brizy_Admin_Data.aiNonce,
          contentType: contentType
        };

        fetch(Brizy_Admin_Data.url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams(ajaxData)
        })
          .then(response => response.json())
          .then(response => {
            if (response && response.success) {
              if (response.data && response.data.aiUrl) {
                saveContentType(contentType);

                const aiUrl = response.data.aiUrl + '/wp-admin/admin.php?page=starter-templates';

                window.location.href = aiUrl;
              } else {
                errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
              }
            } else {
              errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
            }
          })
          .catch(() => {
            errorModal(Brizy_Admin_Data.l10n.aiBannerErrorDesc);
          })
          .finally(() => {
            if (buttonElement) {
              buttonElement.disabled = false;
            }
          });
      };
    }

    const deleteBtn = modalContentContainer.querySelector('.js-demo-install[data-rm-content="1"]');
    const keepBtn = modalContentContainer.querySelector('.js-demo-install[data-rm-content="0"]');

    if (deleteBtn) {
      deleteBtn.addEventListener('click', handleContentAction('delete'));
      deleteBtn.textContent = Brizy_Admin_Data.l10n.aiContinueButton;
    }

    if (keepBtn) {
      keepBtn.addEventListener('click', handleContentAction('keep'));
      keepBtn.textContent = Brizy_Admin_Data.l10n.aiContinueButton;
    }
  }

  function saveContentType(type) {
    localStorage.setItem('content', type);
  }

  function getContentType() {
    return localStorage.getItem('content');
  }

  function loadingModal(titleText, descriptionText) {
    const modalElement = document.querySelector('.brz-demo-modal');
    const modalContentContainer = document.querySelector('.brz-demo-modal-content');
    const loadingTemplate = document.getElementById('brz-demo-modal-content-installing');

    if (!modalElement || !modalContentContainer || !loadingTemplate) {
      return;
    }

    modalContentContainer.innerHTML = loadingTemplate.innerHTML;
    modalElement.classList.add('brz-demo-show-modal');

    const modalTitle = modalContentContainer.querySelector('.brz-demo-modal-content-h3');
    const modalDescription = modalContentContainer.querySelector('.brz-demo-modal-content-p');

    if (titleText) {
      if (modalTitle) {
        modalTitle.textContent = titleText;
      }
    }

    if (descriptionText) {
      if (modalDescription) {
        modalDescription.textContent = descriptionText;
      }
    }
  }

  function errorModal(descriptionText) {
    const modalElement = document.querySelector('.brz-demo-modal');
    const errorContentContainer = document.querySelector('.brz-demo-modal-content');
    const errorTemplate = document.getElementById('brz-demo-modal-content-error');

    if (!modalElement || !errorContentContainer || !errorTemplate) {
      return;
    }

    errorContentContainer.innerHTML = errorTemplate.innerHTML;
    modalElement.classList.add('brz-demo-show-modal');

    const modalDescription = errorContentContainer.querySelector('.brz-demo-modal-content-p');

    if (descriptionText) {
      if (modalDescription) {
        modalDescription.textContent = descriptionText;
      }
    }
  }



  const currentUrl = window.location.href;
  const postEditPattern = /\/wp-admin\/post\.php\?post=\d+/;
  const isPostEditPage = postEditPattern.test(currentUrl);
  if (isPostEditPage && sessionId && sessionId.trim() !== '') {
    const postIdMatch = currentUrl.match(/[?&]post=(\d+)/);
    if (postIdMatch && postIdMatch[1]) {
      startImport(sessionId, postIdMatch[1]);
    }
  }

  window.BrizyAiGetPostId = function (buttonElement) {
    const button = buttonElement;

    const url = window.location.href;
    const postIdMatch = url.match(/[?&]post=(\d+)/);

    if (postIdMatch && postIdMatch[1] && button) {
      const postId = postIdMatch[1];
      const iconContainer = button.querySelector('.brz-ai-button-icon');

      getPostForPage(iconContainer, button, postId);
    } else {
      showPostTitleRequiredNotice();
    }
  };

  function getPostForPage(iconContainer, buttonElement, currentPostId) {
    if (!iconContainer || !buttonElement || !currentPostId) {
      return;
    }

    showLoaderIcon(iconContainer, buttonElement);

    const slugAjaxData = {
      action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.getPost,
      hash: Brizy_Admin_Data.aiNonce,
      postId: currentPostId
    };

    fetch(Brizy_Admin_Data.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(slugAjaxData)
    })
      .then(slugResponse => slugResponse.json())
      .then(slugResponse => {
        if (slugResponse && slugResponse.success && slugResponse.data) {
          const slug = slugResponse.data.slug;

          createSessionForPage(iconContainer, buttonElement, currentPostId, slug);
        } else {
          showErrorIcon(iconContainer, buttonElement);
        }
      })
      .catch(() => {
        showErrorIcon(iconContainer, buttonElement);
      });
  }

  function showPostTitleRequiredNotice() {
    const message = (Brizy_Admin_Data.aiPostTitleRequired || 'Please add the post title before continuing.');
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.dispatch('core/notices')) {
      wp.data.dispatch('core/notices').createNotice('error', message, { isDismissible: true });
    } else {
      const notice = document.createElement('div');
      notice.className = 'notice notice-error is-dismissible';
      const p = document.createElement('p');
      p.textContent = message;
      notice.appendChild(p);
      const target = document.getElementById('wpbody-content') || document.querySelector('.wrap') || document.body;
      if (target && target.firstChild) {
        target.insertBefore(notice, target.firstChild);
      } else if (target) {
        target.appendChild(notice);
      }
    }
  }

  function createSessionForPage(iconContainer, button, postId, slug) {
    if (!iconContainer || !button || !postId || !slug) {
      return;
    }

    const contentType = 'keep';

    const ajaxData = {
      action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.createSession,
      hash: Brizy_Admin_Data.aiNonce,
      contentType: contentType,
      page: slug
    };

    fetch(Brizy_Admin_Data.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(ajaxData)
    })
      .then(response => response.json())
      .then(response => {
        if (response && response.success) {
          if (response.data && response.data.aiUrl) {
            saveContentType(contentType);

            const aiUrlObj = new URL(response.data.aiUrl);
            const baseCallbackUrl = aiUrlObj.searchParams.get('callbackUrl');

            if (baseCallbackUrl) {
              const postEditUrl = baseCallbackUrl + '/wp-admin/post.php?post=' + postId + '&action=edit';
              aiUrlObj.searchParams.set('callbackUrl', postEditUrl);
            }

            window.location.href = aiUrlObj.toString();
          } else {
            showErrorIcon(iconContainer, button);
          }
        } else {
          showErrorIcon(iconContainer, button);
        }
      })
      .catch(() => {
        showErrorIcon(iconContainer, button);
      });
  }

  function showErrorIcon(iconContainer, buttonElement) {
    if (!iconContainer) {
      return;
    }

    iconContainer.innerHTML =
      '<svg width="12px" height="12px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="display: block;">' +
      '<path d="M18 6L6 18M6 6l12 12" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
      '</svg>';

    if (buttonElement && buttonElement.tagName === 'A') {
      buttonElement.style.pointerEvents = '';
      buttonElement.style.opacity = '';
    }
  }

  function showLoaderIcon(iconContainer, buttonElement) {
    if (!iconContainer) {
      return;
    }

    if (!document.getElementById('brz-loader-style')) {
      const style = document.createElement('style');
      style.id = 'brz-loader-style';
      style.textContent = '@keyframes brz-loader-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }';
      document.head.appendChild(style);
    }

    iconContainer.innerHTML =
      '<svg width="12px" height="12px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="display: block; animation: brz-loader-spin 0.8s linear infinite; transform-origin: 50% 50%;">' +
      '<circle cx="12" cy="12" r="10" stroke="#FFFFFF" stroke-width="2" fill="none" stroke-dasharray="31.416" stroke-dashoffset="23.562" stroke-linecap="round" opacity="0.9"/>' +
      '</svg>';

    if (buttonElement && buttonElement.tagName === 'A') {
      buttonElement.style.pointerEvents = 'none';
      buttonElement.style.opacity = '0.6';
    }
  }

  function startImport(sessionId, postId) {
    executeImport(sessionId, postId);

    setInterval(function () {
      var aiButton = document.querySelector('.brz-ai-button');

      if (aiButton) {
        var iconContainer = aiButton.querySelector('.brz-ai-button-icon');
        if (iconContainer && !iconContainer.dataset.brzLoading) {
          iconContainer.dataset.brzLoading = '1';
          showLoaderIcon(iconContainer, aiButton);
        }
      }
    }, 200);
  }

  function executeImport(sessionId, postId) {
    const contentType = getContentType() || 'keep';

    const getTemplateData = {
      action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.getTemplate,
      hash: Brizy_Admin_Data.aiNonce,
      sessionId: sessionId
    };

    fetch(Brizy_Admin_Data.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(getTemplateData)
    })
      .then(response => response.json())
      .then(response => {
        if (response && response.success && response.data) {
          const importData = {
            action: Brizy_Admin_Data.prefix + Brizy_Admin_Data.aiActions.aiImportPage,
            hash: Brizy_Admin_Data.aiNonce,
            postId: postId,
            contentType: contentType,
            body: JSON.stringify(response.data)
          };

          return fetch(Brizy_Admin_Data.url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(importData)
          });
        } else {
          return Promise.reject('Failed to get template data');
        }
      })
      .then(response => response.json())
      .then(response => {
        if (response && response.success) {
          if (response.data && response.data.editPageUrl) {
            window.location.href = response.data.editPageUrl;
          } else {
            window.location.reload();
          }
        } else {
          var btn = document.querySelector('.brz-ai-button');
          if (btn) {
            showErrorIcon(btn.querySelector('.brz-ai-button-icon'), btn);
          }
        }
      })
      .catch(function () {
        var btn = document.querySelector('.brz-ai-button');
        if (btn) {
          showErrorIcon(btn.querySelector('.brz-ai-button-icon'), btn);
        }
      });
  }

});
