(function ($) {
  'use strict';

  $(document).ready(function () {
    initWelcomeBanner();
    initSettingsTabs();
    initTemplateDrawer();
    initConnectionForm();
    initTemplateConnectionModal();
    initTemplateFilters();
    initBackgroundSync();
    initSystemDiagnostics();
    initCardPreviews();
  });

  // ── Welcome Banner ──────────────────────────────────────────────
  function initWelcomeBanner() {
    $('.hundredp-welcome-dismiss').on('click', function () {
      var $banner = $(this).closest('.hundredp-welcome-banner');
      $banner.slideUp(200, function () {
        $banner.remove();
        // Keep dismissed state in local storage for simplicity
        localStorage.setItem('100p_welcome_dismissed', '1');
      });
    });

    if (localStorage.getItem('100p_welcome_dismissed') === '1') {
      $('.hundredp-welcome-banner').remove();
    }
  }

  // ── Settings Tabs ───────────────────────────────────────────────
  function initSettingsTabs() {
    var $tabs = $('.hundredp-tab-nav a');
    if (!$tabs.length) return;

    $tabs.on('click', function (e) {
      e.preventDefault();
      var target = $(this).attr('href');

      $tabs.removeClass('active');
      $(this).addClass('active');

      $('.hundredp-tab-content section').hide();
      $(target).show();

      // Update location hash without jumping
      history.pushState(null, null, target);
    });

    // Handle initial hash routing
    var hash = window.location.hash;
    if (hash && $('.hundredp-tab-content section' + hash).length) {
      $('.hundredp-tab-nav a[href="' + hash + '"]').trigger('click');
    } else {
      $tabs.first().trigger('click');
    }
  }

  // ── Template Preview Drawer ─────────────────────────────────────
  function initTemplateDrawer() {
    var $drawer = $('.hundredp-drawer');
    if (!$drawer.length) return;

    // Open drawer
    $(document).on('click', '.hundredp-btn-preview', function (e) {
      e.preventDefault();
      var templateId = $(this).data('id');
      var templateName = $(this).data('name');
      var source = $(this).data('source');

      $('.hundredp-drawer-title').text(templateName);
      $drawer.addClass('is-open');

      // Clear previous canvas
      var $previewContainer = $('.hundredp-drawer-preview');
      $previewContainer.html('<div class="ph-bold ph-spinner spinner" style="font-size: 24px; animation: hundredp-spin 1s linear infinite;"></div>');

      // Fetch template JSON data and render preview
      $.ajax({
        url: hundredPrintsAdmin.restUrl + 'template/' + templateId,
        method: 'GET',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
        },
        success: function (template) {
          $previewContainer.empty();
          
          var $variablesContainer = $('#hundredp-drawer-variables');
          $variablesContainer.empty();

          var headers = [];
          if (template.sample_data && template.sample_data.headers && template.sample_data.headers.length) {
            headers = template.sample_data.headers;
          } else if (template.variables && template.variables.length) {
            headers = template.variables;
          }

          if (headers.length > 0) {
            var varHtml = '<h5 style="margin: 0 0 8px 0; font-size: 13px; font-weight: 600; color: var(--hundredp-fg);">Dynamic Values</h5>';
            varHtml += '<p style="margin: 0; font-family: monospace; font-size: 12px; color: var(--hundredp-muted); line-height: 1.6;">';
            var formattedVars = headers.map(function(h) { return '{{' + h + '}}'; });
            varHtml += formattedVars.join(' , ');
            varHtml += '</p>';
            $variablesContainer.html(varHtml);
          }

          if (window.WordPressSDK && window.WordPressSDK.preview) {
            // Render the preview with sample rows if available
            var samplePayload = {};
            if (template.sample_data && template.sample_data.rows && template.sample_data.rows.length) {
              samplePayload = template.sample_data.rows[0];
            } else if (headers.length > 0) {
              // Construct blank payload
              headers.forEach(function (h) {
                samplePayload[h] = '[' + h + ']';
              });
            }

            try {
              window.WordPressSDK.preview({
                template: template.template_data || template,
                payload: samplePayload,
                container: $previewContainer[0],
                scale: 0.5
              });
            } catch (err) {
              $previewContainer.html('<p style="color:var(--hundredp-danger); font-size:13px;">Preview rendering failed.</p>');
              console.error(err);
            }
          } else {
            $previewContainer.html('<p style="color:var(--hundredp-muted); font-size:13px;">WordPress SDK not loaded.</p>');
          }
        },
        error: function () {
          $previewContainer.html('<p style="color:var(--hundredp-danger); font-size:13px;">Could not load template metadata.</p>');
        }
      });
    });

    // Close drawer
    $('.hundredp-drawer-close, .hundredp-drawer-overlay').on('click', function () {
      $drawer.removeClass('is-open');
    });

    $(document).on('keyup', function (e) {
      if (e.key === 'Escape') {
        $drawer.removeClass('is-open');
      }
    });
  }

  // ── Connections Connect / Disconnect ────────────────────────────
  function initConnectionForm() {
    var $form = $('#hundredp-connect-form');

    if ($form.length) {
      $form.on('submit', function (e) {
        e.preventDefault();
        var key = $('#hundredp-api-key').val();
        var $btn = $form.find('button[type="submit"]');

        $btn.prop('disabled', true).text('Verifying Connection...');

        $.ajax({
          url: hundredPrintsAdmin.restUrl + 'connect',
          method: 'POST',
          beforeSend: function (xhr) {
            xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
          },
          data: JSON.stringify({ api_key: key }),
          contentType: 'application/json',
          success: function (response) {
            showNotification('success', 'Connected successfully! Syncing templates...');
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          },
          error: function (xhr) {
            $btn.prop('disabled', false).text('Connect Account');
            var err = xhr.responseJSON ? xhr.responseJSON.message : 'Invalid API Secret Key.';
            showNotification('error', err);
          }
        });
      });
    }

    // Disconnect Button
    $(document).on('click', '.hundredp-btn-disconnect', function (e) {
      e.preventDefault();
      if (!confirm('Are you sure you want to disconnect your 100Prints account? This will clear all synced cloud templates.')) {
        return;
      }

      var $btn = $(this);
      $btn.prop('disabled', true).text('Disconnecting...');

      $.ajax({
        url: hundredPrintsAdmin.restUrl + 'disconnect',
        method: 'POST',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
        },
        success: function () {
          showNotification('success', 'Disconnected successfully.');
          setTimeout(function () {
            window.location.href = 'admin.php?page=100prints';
          }, 1000);
        },
        error: function () {
          $btn.prop('disabled', false).text('Disconnect Account');
          showNotification('error', 'Failed to disconnect account.');
        }
      });
    });

    // Sync Templates Button
    $(document).on('click', '.hundredp-btn-sync', function (e) {
      e.preventDefault();
      var $btn = $(this);
      var originalText = $btn.text();
      $btn.prop('disabled', true).text('Syncing templates...');

      $.ajax({
        url: hundredPrintsAdmin.restUrl + 'sync-templates',
        method: 'POST',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
        },
        success: function (response) {
          showNotification('success', 'Successfully synced ' + response.count + ' templates!');
          setTimeout(function () {
            window.location.reload();
          }, 1000);
        },
        error: function (xhr) {
          $btn.prop('disabled', false).text(originalText);
          var err = xhr.responseJSON ? xhr.responseJSON.message : 'Synchronization failed.';
          showNotification('error', err);
        }
      });
    });
  }

  // ── Template Page Connection Modal ────────────────────────────────
  function initTemplateConnectionModal() {
    var $modalOverlay = $('#hundredp-connect-modal');
    if (!$modalOverlay.length) return;

    // Open Modal
    $('#hundredp-btn-open-connect-modal').on('click', function (e) {
      e.preventDefault();
      $modalOverlay.addClass('is-open');
    });

    // Close Modal
    $('.hundredp-modal-close').on('click', function () {
      $modalOverlay.removeClass('is-open');
    });

    $(document).on('keyup', function (e) {
      if (e.key === 'Escape' && $modalOverlay.hasClass('is-open')) {
        $modalOverlay.removeClass('is-open');
      }
    });

    // Handle Form Submit
    var $form = $('#hundredp-modal-connect-form');
    $form.on('submit', function (e) {
      e.preventDefault();
      var key = $('#hundredp-modal-api-key').val();
      var $btn = $form.find('button[type="submit"]');

      $btn.prop('disabled', true).text('Verifying...');

      $.ajax({
        url: hundredPrintsAdmin.restUrl + 'connect',
        method: 'POST',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
        },
        data: JSON.stringify({ api_key: key }),
        contentType: 'application/json',
        success: function (response) {
          // Immediately sync templates on success
          $.ajax({
            url: hundredPrintsAdmin.restUrl + 'sync-templates',
            method: 'POST',
            beforeSend: function (xhr) {
              xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
            },
            success: function (syncResponse) {
              $('#hundredp-modal-step-connect').hide();
              $('#hundredp-modal-step-success').show();

              if (response.workspace) {
                $('#hundredp-modal-ws-name').text(response.workspace.workspace_name || '-');
                $('#hundredp-modal-ws-plan').text(response.workspace.plan_tier || 'Free');
                $('#hundredp-modal-ws-count').text(syncResponse.count || '0');
              }
            },
            error: function () {
              $btn.prop('disabled', false).text('Connect');
              showNotification('error', 'Connected but failed to sync templates.');
            }
          });
        },
        error: function (xhr) {
          $btn.prop('disabled', false).text('Connect');
          var err = xhr.responseJSON ? xhr.responseJSON.message : 'Invalid API Secret Key.';
          showNotification('error', err);
        }
      });
    });

    // Continue Button
    $('#hundredp-modal-continue').on('click', function () {
      $modalOverlay.removeClass('is-open');
      window.location.reload();
    });
  }

  // ── Template Grid Search & Category Filters ───────────────────────
  function initTemplateFilters() {
    var $searchInput = $('#hundredp-template-search');
    var $categoryFilter = $('#hundredp-category-filter');
    var $cards = $('#hundredp-cloud-grid .hundredp-template-card');

    if (!$searchInput.length && !$categoryFilter.length) return;

    function filterTemplates() {
      var query = ($searchInput.val() || '').toLowerCase().trim();
      var category = ($categoryFilter.val() || '').toLowerCase().trim();

      $cards.each(function () {
        var $card = $(this);
        var name = $card.find('h4').text().toLowerCase();

        // Find category: matches text of first .hundredp-var-chip without icon
        var cardCategory = '';
        $card.find('.hundredp-var-chip').each(function () {
          var $chip = $(this);
          if ($chip.find('i').length === 0) {
            cardCategory = $chip.text().toLowerCase().trim();
            return false; // break loop
          }
        });

        var matchesQuery = !query || name.indexOf(query) !== -1;
        var matchesCategory = !category || cardCategory === category;

        if (matchesQuery && matchesCategory) {
          $card.show();
        } else {
          $card.hide();
        }
      });
    }

    $searchInput.on('input', filterTemplates);
    $categoryFilter.on('change', filterTemplates);
  }

  // ── Background API Sync ──────────────────────────────────────────
  function initBackgroundSync() {
    // Only perform background sync if connected and viewing templates library
    var $workspaceHeader = $('.hundredp-workspace-header-card');
    if (!$workspaceHeader.length) return;

    // Do background sync without blocking
    $.ajax({
      url: hundredPrintsAdmin.restUrl + 'sync-templates',
      method: 'POST',
      beforeSend: function (xhr) {
        xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
      },
      success: function (response) {
        // Compare template count in DOM with synced count
        var currentCount = parseInt($('.hundredp-badge-cloud').text()) || 0;
        if (response.count !== undefined && response.count !== currentCount) {
          // Templates count has changed. Refresh the page to show latest
          window.location.reload();
        }
      },
      error: function (err) {
        console.warn('100Prints: Background sync failed', err);
      }
    });
  }

  // ── System Diagnostics ──────────────────────────────────────────
  function initSystemDiagnostics() {
    var $copyBtn = $('.hundredp-btn-copy-diagnostics');
    if (!$copyBtn.length) return;

    $copyBtn.on('click', function (e) {
      e.preventDefault();
      var dumpText = $('.hundredp-diagnostic-dump').text();

      navigator.clipboard.writeText(dumpText).then(function () {
        var originalText = $copyBtn.text();
        $copyBtn.text('Copied System Info!');
        setTimeout(function () {
          $copyBtn.text(originalText);
        }, 1500);
      }).catch(function (err) {
        alert('Could not copy system diagnostics: ' + err);
      });
    });
  }

  // ── Show Toast Notification Helper ──────────────────────────────
  function showNotification(type, message) {
    // Remove existing notifications first
    $('.hundredp-notice').remove();

    var icon = 'ph-info';
    var cssClass = 'hundredp-notice--info';
    if (type === 'success') {
      icon = 'ph-check-circle';
      cssClass = 'hundredp-notice--success';
    } else if (type === 'error') {
      icon = 'ph-x-circle';
      cssClass = 'hundredp-notice--error';
    } else if (type === 'warning') {
      icon = 'ph-warning';
      cssClass = 'hundredp-notice--warning';
    }

    var html = '<div class="hundredp-notice ' + cssClass + '" role="alert">' +
      '<i class="ph-bold ' + icon + '"></i>' +
      '<span>' + message + '</span>' +
      '<button class="hundredp-notice__close" aria-label="Dismiss"><i class="ph-bold ph-x"></i></button>' +
      '</div>';

    $('.hundredp-page-header').after(html);

    // Bind close click
    $('.hundredp-notice__close').on('click', function () {
      $(this).closest('.hundredp-notice').slideUp(150, function () {
        $(this).remove();
      });
    });
  }

  // ── Card Preview Rendering ───────────────────────────────────────
  function initCardPreviews() {
    var $thumbnails = $('.hundredp-template-thumbnail[data-id]');
    if (!$thumbnails.length) return;

    $thumbnails.each(function () {
      var $thumbnail = $(this);
      var templateId = $thumbnail.data('id');

      // Make API call to fetch template data
      $.ajax({
        url: hundredPrintsAdmin.restUrl + 'template/' + templateId,
        method: 'GET',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('X-WP-Nonce', hundredPrintsAdmin.nonce);
        },
        success: function (template) {
          $thumbnail.empty();

          if (window.WordPressSDK && window.WordPressSDK.preview) {
            // Render template preview on the card
            var samplePayload = {};
            if (template.sample_data && template.sample_data.rows && template.sample_data.rows.length) {
              samplePayload = template.sample_data.rows[0];
            } else if (template.sample_data && template.sample_data.headers) {
              template.sample_data.headers.forEach(function (h) {
                samplePayload[h] = '[' + h + ']';
              });
            }

            var tW = template.dimensions ? template.dimensions.width : 856;
            if (template.template_data && template.template_data.dimensions) {
              tW = template.template_data.dimensions.width || tW;
            }
            var tH = template.dimensions ? template.dimensions.height : 540;
            if (template.template_data && template.template_data.dimensions) {
              tH = template.template_data.dimensions.height || tH;
            }

            var cardW = $thumbnail.width();
            var cardH = $thumbnail.height();
            var padding = 8;
            var scale = Math.min((cardW - padding * 2) / tW, (cardH - padding * 2) / tH);
            var scaledW = Math.round(tW * scale);
            var scaledH = Math.round(tH * scale);
            var bg = template.template_data ? (template.template_data.backgroundColor || '#ffffff') : (template.backgroundColor || '#ffffff');

            var $clip = $('<div style="width:' + scaledW + 'px; height:' + scaledH + 'px; position:relative; overflow:hidden; flex-shrink:0; background-color:' + bg + '; box-shadow:0 2px 12px 0 rgba(0,0,0,0.08), 0 0 0 1px rgba(0,0,0,0.03); border-radius:4px;"></div>');
            var $inner = $('<div style="width:' + tW + 'px; height:' + tH + 'px; position:absolute; top:0; left:0; transform:scale(' + scale + '); transform-origin:top left; background-color:' + bg + '; overflow:hidden; image-rendering:high-quality; -webkit-font-smoothing:antialiased;"></div>');

            $clip.append($inner);
            $thumbnail.append($clip);

            try {
              window.WordPressSDK.preview({
                template: template.template_data || template,
                payload: samplePayload,
                container: $inner[0],
                scale: 1
              });
            } catch (err) {
              console.error(err);
              $thumbnail.html('<i class="ph-bold ph-image" style="font-size: 32px; color: #CBD5E1;"></i>');
            }
          } else {
            $thumbnail.html('<i class="ph-bold ph-image" style="font-size: 32px; color: #CBD5E1;"></i>');
          }
        },
        error: function () {
          $thumbnail.html('<i class="ph-bold ph-image" style="font-size: 32px; color: #CBD5E1;"></i>');
        }
      });
    });
  }

})(jQuery);
