(function ($) {
  'use strict';

  function setStatus($el, msg, isError) {
    if (!$el || !$el.length) return;
    $el.removeClass('notice notice-error notice-success');
    if (isError) {
      $el.addClass('notice notice-error');
    }
    $el.text(msg || '');
    $el.show();
  }

  function hideStatus($el) {
    if ($el && $el.length) $el.hide();
  }

  function updateMode(type) {
    var t = (type || '').toString();
    var $postWrap = $('#wpsn-tt-post-wrap');
    var $termWrap = $('#wpsn-tt-term-wrap');
    var $taxWrap = $('#wpsn-tt-tax-wrap');
    var $authorWrap = $('#wpsn-tt-author-wrap');

    if (t === 'term') {
      $postWrap.hide();
      $authorWrap.hide();
      $termWrap.show();
      $taxWrap.show();
    } else if (t === 'author') {
      $postWrap.hide();
      $termWrap.hide();
      $taxWrap.hide();
      $authorWrap.show();
    } else if (t === 'home') {
      $postWrap.hide();
      $termWrap.hide();
      $taxWrap.hide();
      $authorWrap.hide();
    } else {
      // post
      $postWrap.show();
      $termWrap.hide();
      $taxWrap.hide();
      $authorWrap.hide();
    }
  }

  function formatTokenBreakdown(tokens) {
    var lines = [];
    if (!tokens || !tokens.length) {
      lines.push('(no tokens detected)');
      return lines.join("\n");
    }

    tokens.forEach(function (t) {
      var token = (t.token || '').toString();
      var value = (t.value || '').toString();
      var selected = (t.selected_branch || '').toString();
      lines.push(token + ' => ' + (value !== '' ? JSON.stringify(value) : '(empty)'));
      if (t.branches && t.branches.length) {
        lines.push('  branches:');
        t.branches.forEach(function (b) {
          var bx = (b.expr || '').toString();
          var bv = (b.value || '').toString();
          var mark = (selected && bx === selected) ? ' *' : '  ';
          lines.push('   -' + mark + ' ' + bx + ' => ' + (bv !== '' ? JSON.stringify(bv) : '(empty)'));
        });
      }
      lines.push('');
    });

    return lines.join("\n");
  }

  $(function () {
    var cfg = window.WPSNTemplateTokens || {};
    var ajaxEnabled = (typeof cfg.ajaxEnabled !== 'undefined') ? !!cfg.ajaxEnabled : true;
    var ajaxUrl = (ajaxEnabled && cfg.ajaxUrl) ? cfg.ajaxUrl : (ajaxEnabled ? (window.ajaxurl || '') : '');

    var $type = $('#wpsn-tt-type');
    var $btn = $('#wpsn-tt-run');
    var $form = $('#wpsn-tt-form');
    var $live = $('#wpsn-tt-live');
    var $tpl = $('#wpsn-tt-template');
    var $status = $('#wpsn-tt-status');
    var $outWrap = $('#wpsn-tt-output-wrap');
    var $out = $('#wpsn-tt-output');
    var $dbgWrap = $('#wpsn-tt-debug-wrap');
    var $dbg = $('#wpsn-tt-debug');

    if ($type.length) {
      updateMode($type.val());
      $type.on('change', function () {
        updateMode($type.val());
      });
    }

    function runAjaxRender() {
        var t = ($type.val() || 'post').toString();
        var template = ($tpl.val() || '').toString().trim();

        $outWrap.hide();
        $dbgWrap.hide();
        $out.text('');
        $dbg.text('');

        if (!template) {
          setStatus($status, (cfg.i18n && cfg.i18n.emptyTemplate) ? cfg.i18n.emptyTemplate : 'Please enter a template.', true);
          return;
        }

        var payload = {
          action: 'wpsn_template_test',
          nonce: cfg.nonce || '',
          object_type: t,
          template: template
        };

        if (t === 'post') {
          var postId = parseInt(($('#wpsn-tt-post-id').val() || '0').toString(), 10) || 0;
          if (!postId || postId < 1) {
            setStatus($status, (cfg.i18n && cfg.i18n.needPostId) ? cfg.i18n.needPostId : 'Please enter a valid Post ID.', true);
            return;
          }
          payload.object_id = postId;
        } else if (t === 'term') {
          var termId = parseInt(($('#wpsn-tt-term-id').val() || '0').toString(), 10) || 0;
          var tax = ($('#wpsn-tt-tax').val() || '').toString().trim();
          if (!termId || termId < 1) {
            setStatus($status, (cfg.i18n && cfg.i18n.needTermId) ? cfg.i18n.needTermId : 'Please enter a valid Term ID.', true);
            return;
          }
          if (!tax) {
            setStatus($status, (cfg.i18n && cfg.i18n.needTax) ? cfg.i18n.needTax : 'Please enter a taxonomy.', true);
            return;
          }
          payload.object_id = termId;
          payload.taxonomy = tax;
        } else if (t === 'author') {
          var authorId = parseInt(($('#wpsn-tt-author-id').val() || '0').toString(), 10) || 0;
          if (!authorId || authorId < 1) {
            setStatus($status, (cfg.i18n && cfg.i18n.needAuthorId) ? cfg.i18n.needAuthorId : 'Please enter a valid Author ID.', true);
            return;
          }
          payload.author_id = authorId;
        }

        setStatus($status, (cfg.i18n && cfg.i18n.rendering) ? cfg.i18n.rendering : 'Rendering…', false);

        $.post(ajaxUrl, payload, function (resp) {
          if (!resp) {
            setStatus($status, 'Empty response.', true);
            return;
          }

          if (resp.success) {
            hideStatus($status);

            var d = resp.data || {};
            var output = (d.output || '').toString();
            var tokens = d.tokens || [];

            $out.text(output !== '' ? output : '(empty)').show();
            $outWrap.show();

            $dbg.text(formatTokenBreakdown(tokens)).show();
            $dbgWrap.show();
          } else {
            var msg = (resp.data && resp.data.message) ? resp.data.message : 'Request failed.';
            setStatus($status, ((cfg.i18n && cfg.i18n.error) ? cfg.i18n.error : 'Error:') + ' ' + msg, true);
          }
        }, 'json').fail(function (xhr) {
          var msg = 'Request failed.';
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            msg = xhr.responseJSON.data.message;
          }
          setStatus($status, ((cfg.i18n && cfg.i18n.error) ? cfg.i18n.error : 'Error:') + ' ' + msg, true);
        });
    }

    // Default mode is non-AJAX (page reload). Only intercept when Live mode is enabled AND AJAX is enabled globally.
    if ($form.length) {
      $form.on('submit', function (e) {
        if (!ajaxEnabled || !ajaxUrl) {
          return; // force non-AJAX submit
        }
        if (!$live.length || !$live.prop('checked')) {
          return; // normal POST submit
        }
        e.preventDefault();
        runAjaxRender();
      });
    } else if ($btn.length) {
      // Back-compat: old markup without a form.
      $btn.on('click', function () {
        if (!ajaxEnabled || !ajaxUrl) {
          return;
        }
        runAjaxRender();
      });
    }
  });
})(jQuery);
