"use strict";
(function($){

  function getModalRoot() {
    return $('#mymodalfzr');
  }

  function getCreatorKey($root){
    return ($root.data('creator') || 'default').toString();
  }

  function isSkippable(el) {
    const $el = $(el);
    const name = $el.attr('name');
    if (!name) return true;
    const type = ($el.attr('type') || '').toLowerCase();
    if (type === 'button' || type === 'submit') return true;
    if (name.indexOf('_wpnonce') !== -1) return true;
    return false;
  }

  function collectDefaults($root) {
    const payload = {};

    $root.find('input, select, textarea').each(function(){
      if (isSkippable(this)) return;

      const $el  = $(this);
      const name = $el.attr('name');
      const tag  = this.tagName.toLowerCase();
      const type = ($el.attr('type') || '').toLowerCase();

      if (type === 'radio') {
        if ($el.is(':checked')) payload[name] = $el.val();
        return;
      }

      if (type === 'checkbox') {
        if (name.slice(-2) === '[]') {
          if (!Array.isArray(payload[name])) payload[name] = [];
          if ($el.is(':checked')) payload[name].push($el.val() === 'on' ? '1' : $el.val());
        } else {
          payload[name] = $el.is(':checked') ? '1' : '0';
        }
        return;
      }

      if (tag === 'select' && $el.prop('multiple')) {
        payload[name] = $el.val() || [];
        return;
      }

      payload[name] = $el.val();
    });

    return payload;
  }

  function applyDefaults($root, payload) {
    if (!payload) return;

    Object.keys(payload).forEach(function(name){

      const escName =
        (window.CSS && CSS.escape)
          ? CSS.escape(name)
          : name.replace(/"/g,'\\"');

      const $fields = $root.find('[name="' + escName + '"]');
      if (!$fields.length) return;

      const value = payload[name];

      $fields.each(function(){

        const $el = $(this);
        const tag = this.tagName.toLowerCase();
        const type = ($el.attr('type') || '').toLowerCase();

        if (type === 'radio') {
          $el.prop('checked', $el.val() == value);
          return;
        }

        if (type === 'checkbox') {

          if (name.slice(-2) === '[]') {
            const arr = Array.isArray(value) ? value : [];
            const v = ($el.val()==='on') ? '1' : $el.val();
            $el.prop('checked', arr.map(String).includes(String(v)));
          }
          else {
            $el.prop('checked',
              String(value)==='1' ||
              String(value).toLowerCase()==='true'
            );
          }

          return;
        }

        if (tag === 'select' && $el.prop('multiple')) {
          $el.val(Array.isArray(value)?value:[]).trigger('change');
          return;
        }

        $el.val(value).trigger('change');

      });
    });
  }

  function ensureDefaultsBar($root) {

    if ($root.find('.aiomatic-defaults-bar').length) return;

    const $bar = $(`
<div class="aiomatic-defaults-bar">

    <div class="aiomatic-defaults-label">
        
        <span class="aiomatic-default-state"></span>
    </div>

    <div class="aiomatic-defaults-actions">
        <button type="button"
            class="button aimogen-green aiomatic-save" id="aiomatic-save">
            Use as Default Template
        </button>

        <button type="button"
            class="button aimogen-darkred aiomatic-reset" id="aiomatic-reset">
            Reset Template
        </button>
    </div>

</div>
`);

    $root.find('.codemodalfzr-header').after($bar);
  }

  function setStatus($root, msg){

        const $badge = $root.find('.aiomatic-default-state');

        if(!msg){
            $badge.text('').removeClass('active');
            return;
        }

        $badge.text(msg).addClass('active');

        setTimeout(()=>{
            $badge.text('').removeClass('active');
        },2000);
    }

  function ajaxGetDefaults(key){
    return $.post(AiomaticRuleDefaults.ajax_url,{
      action:'aiomatic_get_rule_defaults',
      nonce:AiomaticRuleDefaults.nonce,
      creator_key:key
    });
  }

  function ajaxSaveDefaults(payload,key){
    return $.post(AiomaticRuleDefaults.ajax_url,{
      action:'aiomatic_save_rule_defaults',
      nonce:AiomaticRuleDefaults.nonce,
      creator_key:key,
      payload:JSON.stringify(payload)
    });
  }

  function ajaxResetDefaults(key){
    return $.post(AiomaticRuleDefaults.ajax_url,{
      action:'aiomatic_reset_rule_defaults',
      nonce:AiomaticRuleDefaults.nonce,
      creator_key:key
    });
  }

  $(document).on('click','#mybtnfzr',function(){

    const $root = getModalRoot();
    ensureDefaultsBar($root);

    const creatorKey = getCreatorKey($root);

    ajaxGetDefaults(creatorKey).done(function(resp){

        if(resp?.success && resp.data.payload){
            applyDefaults($root,resp.data.payload);
            setStatus($root,'Loaded ✓');
        }
        else{
            setStatus($root,null); 
        }

    });
    });

  $(document).on('click','#aiomatic-save',function(){

    const $root = getModalRoot();
    const key = getCreatorKey($root);

    ajaxSaveDefaults(
      collectDefaults($root),
      key
    ).done(()=>setStatus($root,'Updated ✓'));
  });

  $(document).on('click','#aiomatic-reset',function(){

    const $root = getModalRoot();
    const key = getCreatorKey($root);

    ajaxResetDefaults(key)
      .done(()=>setStatus($root,'Cleared'));
  });

})(jQuery);