(function () {
  'use strict';

  function getConfig() {
    if (!window.WPSNSchemaHelper || typeof window.WPSNSchemaHelper !== 'object') {
      return null;
    }
    return window.WPSNSchemaHelper;
  }

  function setStatus(container, message, isError) {
    var el = container ? container.querySelector('.wpsn-schema-ai-status') : null;
    if (!el) {
      return;
    }
    el.textContent = message || '';
    el.style.color = isError ? '#b32d2e' : '';
  }

  function fillTargetFromSource(button) {
    var targetId = button.getAttribute('data-target') || '';
    var sourceId = button.getAttribute('data-source-id') || '';
    if (!targetId || !sourceId) {
      return;
    }

    var target = document.getElementById(targetId);
    var source = document.getElementById(sourceId);
    if (!target || !source) {
      return;
    }

    target.value = source.value || '';
    target.dispatchEvent(new Event('input', { bubbles: true }));
    target.dispatchEvent(new Event('change', { bubbles: true }));
    target.focus();
  }

  function handleAiClick(button) {
    var config = getConfig();
    var container = button.closest('.wpsn-schema-ai-controls');
    if (!config || !container) {
      return;
    }

    var postId = parseInt(container.getAttribute('data-post-id') || '0', 10);
    var targetId = container.getAttribute('data-target') || '';
    var presetSelect = container.querySelector('.wpsn-schema-ai-preset');
    var preset = presetSelect ? String(presetSelect.value || 'auto') : 'auto';
    var target = targetId ? document.getElementById(targetId) : null;

    if (!target) {
      setStatus(container, config.i18n && config.i18n.missingTarget ? config.i18n.missingTarget : 'Schema textarea was not found.', true);
      return;
    }

    button.disabled = true;
    setStatus(container, config.i18n && config.i18n.generating ? config.i18n.generating : 'Generating…', false);

    window.fetch(config.generateUrl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': config.nonce || ''
      },
      body: JSON.stringify({
        post_id: postId,
        preset_slug: preset
      })
    })
      .then(function (res) {
        return res.json().catch(function () {
          return {};
        }).then(function (data) {
          if (!res.ok) {
            var message = (data && data.message) || (config.i18n && config.i18n.requestFailed) || 'Request failed.';
            throw new Error(message);
          }
          return data;
        });
      })
      .then(function (data) {
        if (!data || typeof data.json_ld !== 'string' || !data.json_ld) {
          throw new Error((config.i18n && config.i18n.requestFailed) || 'Request failed.');
        }

        target.value = data.json_ld;
        target.dispatchEvent(new Event('input', { bubbles: true }));
        target.dispatchEvent(new Event('change', { bubbles: true }));
        target.focus();

        var message = (config.i18n && config.i18n.generated) || 'Draft inserted.';
        if (data.preset_slug && data.preset_slug !== 'auto') {
          message += ' ' + data.preset_slug + '.';
        }
        setStatus(container, message, false);
      })
      .catch(function (err) {
        setStatus(container, err && err.message ? err.message : ((config.i18n && config.i18n.requestFailed) || 'Request failed.'), true);
      })
      .finally(function () {
        button.disabled = false;
      });
  }

  document.addEventListener('click', function (event) {
    var insertButton = event.target.closest('.wpsn-schema-insert-template');
    if (insertButton) {
      event.preventDefault();
      fillTargetFromSource(insertButton);
      return;
    }

    var aiButton = event.target.closest('.wpsn-schema-ai-generate');
    if (aiButton) {
      event.preventDefault();
      handleAiClick(aiButton);
    }
  });
})();
