import './style.css';

const syncAdminCardState = (card) => {
  const active = card.querySelector('.calio-switch-input:checked');
  const stateTexts = Array.from(card.querySelectorAll('[data-state-text]'));
  const locked = card.dataset.locked === '1';
  const enabled = !locked && !!active;

  card.dataset.enabled = enabled ? '1' : '0';
  card.classList.toggle('is-locked', locked);

  stateTexts.forEach((stateText) => {
    stateText.textContent = locked ? 'Locked' : (enabled ? 'Active' : 'Disabled');
  });
};

Array.from(document.querySelectorAll('.calio-widget-card')).forEach((card) => {
  card.querySelectorAll('.calio-switch-input').forEach((input) => {
    input.addEventListener('change', () => {
      syncAdminCardState(card);
    });
  });

  syncAdminCardState(card);
});

Array.from(document.querySelectorAll('form')).forEach((form) => {
  const statusNode = form.querySelector('[data-form-status]');

  form.querySelectorAll('input, textarea, select').forEach((field) => {
    field.addEventListener('change', () => {
      form.classList.add('is-dirty');

      if (statusNode) {
        statusNode.textContent = 'Unsaved changes. Click Save to persist them.';
      }
    });

    field.addEventListener('input', () => {
      form.classList.add('is-dirty');

      if (statusNode) {
        statusNode.textContent = 'Unsaved changes. Click Save to persist them.';
      }
    });
  });

  form.addEventListener('submit', () => {
    if (statusNode) {
      statusNode.textContent = 'Saving changes...';
    }
  });
});

const getAjaxErrorMessage = (response, fallback) => {
  if (!response) {
    return fallback;
  }

  if (typeof response === 'string') {
    return response || fallback;
  }

  const data = response.data || response.error || response;
  if (typeof data === 'string') {
    return data || fallback;
  }

  return data?.message || data?.error?.message || data?.error || fallback;
};

Array.from(document.querySelectorAll('[data-calio-license-activation]')).forEach((form) => {
  const message = form.querySelector('[data-calio-license-message]');
  const submitButton = form.querySelector('button[type="submit"]');
  const licenseInput = form.querySelector('input[name="license_key"]');
  const defaultButtonText = submitButton?.textContent || 'Activate License';

  form.addEventListener('submit', async (event) => {
    event.preventDefault();

    if (!licenseInput || !licenseInput.value.trim()) {
      if (message) {
        message.textContent = 'Please enter a license key first.';
        message.dataset.state = 'error';
      }
      licenseInput?.focus();
      return;
    }

    if (submitButton) {
      submitButton.disabled = true;
      submitButton.textContent = 'Activating...';
    }

    if (message) {
      message.textContent = 'Activating license...';
      message.dataset.state = 'loading';
    }

    try {
      const result = await fetch(form.action || window.ajaxurl || 'admin-ajax.php', {
        method: 'POST',
        credentials: 'same-origin',
        body: new window.FormData(form),
      });
      const raw = await result.text();
      let response = raw;

      try {
        response = raw ? JSON.parse(raw) : {};
      } catch (parseError) {
        response = raw;
      }

      if (response?.success) {
        if (message) {
          message.textContent = 'License activated. Refreshing dashboard...';
          message.dataset.state = 'success';
        }

        const nextUrl = `${window.location.pathname}${window.location.search}#calio_addon_license_settings`;
        window.history.replaceState({ tabId: 'calio_addon_license_settings' }, '', nextUrl);
        window.location.reload();
        return;
      }

      if (message) {
        message.textContent = getAjaxErrorMessage(response, 'License activation failed. Please check the key and try again.');
        message.dataset.state = 'error';
      }
    } catch (error) {
      if (message) {
        message.textContent = 'License activation request failed. Please try again.';
        message.dataset.state = 'error';
      }
    } finally {
      if (submitButton) {
        submitButton.disabled = false;
        submitButton.textContent = defaultButtonText;
      }
    }
  });
});

document.addEventListener('click', (event) => {
  const confirmSubmit = event.target.closest?.('[data-calio-confirm-submit]');
  if (confirmSubmit) {
    event.preventDefault();

    const message = confirmSubmit.dataset.calioConfirmSubmit || '';
    if (message === '' || window.confirm(message)) {
      confirmSubmit.form?.submit();
    }

    return;
  }

  const trigger = event.target.closest?.('[data-calio-license-modal-trigger]');
  if (!trigger) {
    return;
  }

  event.preventDefault();

  window.setTimeout(() => {
    const modal = document.querySelector('.fs-modal-license-activation');

    if (modal) {
      modal.classList.add('active');
      document.body.classList.add('has-fs-modal');
      modal.querySelector('input.fs-license-key, input[type="text"], input[type="password"]')?.focus();
      return;
    }

    const fallback = trigger.dataset.calioLicenseFallback;
    if (fallback) {
      document.querySelector(fallback)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, 80);
});

const tabsRoot = document.getElementById('calio-tabs');
if (tabsRoot) {
  const tabs = Array.from(tabsRoot.querySelectorAll('.calio-tab-link'));
  const panels = Array.from(document.querySelectorAll('.calio-tab-panel'));
  const linkedAnchors = Array.from(document.querySelectorAll('a[href^="#calio_"]'));
  const updateUrl = (tabId) => {
    const nextUrl = `${window.location.pathname}${window.location.search}#${tabId}`;
    window.history.replaceState({ tabId }, '', nextUrl);
  };

  const activate = (tabId) => {
    tabs.forEach((tab) => {
      tab.classList.toggle('is-active', tab.dataset.tab === tabId);
    });

    panels.forEach((panel) => {
      panel.classList.toggle('is-active', panel.id === tabId);
    });
  };

  const resolveHash = () => {
    const hash = window.location.hash.replace('#', '');
    const found = tabs.find((tab) => tab.dataset.tab === hash);
    return found ? found.dataset.tab : 'calio_overview';
  };

  linkedAnchors.forEach((anchor) => {
    anchor.addEventListener('click', (event) => {
      event.preventDefault();
      const tabId = anchor.getAttribute('href')?.replace('#', '') || anchor.dataset.tab;
      if (!tabId) {
        return;
      }

      activate(tabId);
      updateUrl(tabId);
    });
  });

  activate(resolveHash());

  if (window.location.hash) {
    window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
  }

  window.addEventListener('popstate', () => {
    activate(resolveHash());
    window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
  });
}

const widgetGrid = document.getElementById('calio-widget-grid');
if (widgetGrid) {
  const cards = Array.from(widgetGrid.querySelectorAll('[data-widget-item]'));
  const overviewCards = Array.from(document.querySelectorAll('[data-overview-category]'));
  const quickActions = Array.from(document.querySelectorAll('[data-quick-action]'));
  const activeCountNodes = Array.from(document.querySelectorAll('[data-active-count]'));
  const disabledCountNodes = Array.from(document.querySelectorAll('[data-disabled-count]'));
  const totalCountNodes = Array.from(document.querySelectorAll('[data-total-count]'));
  const visibleCountNodes = Array.from(document.querySelectorAll('[data-visible-count]'));
  const summaryNodes = Array.from(document.querySelectorAll('[data-filter-summary]'));
  const searchNode = document.getElementById('calio-widget-search');
  const clearSearchBtn = document.getElementById('calio-clear-search');
  const enableAllBtn = document.getElementById('calio-enable-all');
  const disableAllBtn = document.getElementById('calio-disable-all');
  const emptyStateNode = document.getElementById('calio-widget-empty-state');
  const filterPills = Array.from(document.querySelectorAll('.calio-filter-pill'));

  let activeCategory = 'all';
  let activeState = 'all';
  let activeTier = 'all';

  const setNodeText = (nodes, value) => {
    nodes.forEach((node) => {
      node.textContent = value;
    });
  };

  const syncFilterPills = () => {
    filterPills.forEach((pill) => {
      if (pill.dataset.filterType === 'category') {
        pill.classList.toggle('is-active', pill.dataset.filterValue === activeCategory);
      }

      if (pill.dataset.filterType === 'state') {
        pill.classList.toggle('is-active', pill.dataset.filterValue === activeState);
      }

      if (pill.dataset.filterType === 'tier') {
        pill.classList.toggle('is-active', pill.dataset.filterValue === activeTier);
      }
    });
  };

  const updateCardState = (card) => syncAdminCardState(card);

  const updateCount = () => {
    const activeCount = cards.filter((card) => card.dataset.enabled === '1').length;
    const disabledCount = cards.length - activeCount;

    setNodeText(activeCountNodes, String(activeCount));
    setNodeText(disabledCountNodes, String(disabledCount));
    setNodeText(totalCountNodes, String(cards.length));
  };

  const updateOverview = () => {
    overviewCards.forEach((overviewCard) => {
      const category = overviewCard.dataset.overviewCategory || '';
      const categoryCards = cards.filter((card) => card.dataset.category === category);
      const activeCount = categoryCards.filter((card) => card.dataset.enabled === '1').length;
      const totalCount = categoryCards.length;
      const activeNode = overviewCard.querySelector('[data-category-active]');
      const totalNode = overviewCard.querySelector('[data-category-total]');

      if (activeNode) {
        activeNode.textContent = String(activeCount);
      }

      if (totalNode) {
        totalNode.textContent = String(totalCount);
      }

      overviewCard.classList.toggle('is-active', activeCategory === category);
      overviewCard.classList.toggle('is-dimmed', activeCategory !== 'all' && activeCategory !== category);
    });
  };

  const applyFilters = () => {
    const term = (searchNode?.value || '').trim().toLowerCase();
    let visibleCount = 0;

    cards.forEach((card) => {
      const title = card.dataset.title || '';
      const keywords = card.dataset.keywords || '';
      const category = card.dataset.category || '';
      const tier = card.dataset.tier || 'free';
      const enabled = card.dataset.enabled === '1';
      const searchMatch = term === '' || title.includes(term) || keywords.includes(term) || category.includes(term);
      const categoryMatch = activeCategory === 'all' || category === activeCategory;
      const stateMatch = activeState === 'all' || (activeState === 'active' && enabled) || (activeState === 'disabled' && !enabled);
      const tierMatch = activeTier === 'all' || tier === activeTier;
      const visible = searchMatch && categoryMatch && stateMatch && tierMatch;

      card.classList.toggle('is-hidden', !visible);
      if (visible) {
        visibleCount += 1;
      }
    });

    setNodeText(visibleCountNodes, String(visibleCount));

    if (emptyStateNode) {
      emptyStateNode.hidden = visibleCount !== 0;
    }

    const categoryLabel = activeCategory === 'all' ? 'all categories' : activeCategory;
    const tierLabel = activeTier === 'all' ? 'all tiers' : `${activeTier} tier`;
    const stateLabel = activeState === 'all' ? 'all states' : activeState;
    const searchLabel = term ? ` matching "${term}"` : '';
    setNodeText(summaryNodes, `Showing ${categoryLabel}, ${tierLabel}, ${stateLabel}${searchLabel}.`);

    updateOverview();
    syncFilterPills();
  };

  cards.forEach((card) => {
    card.querySelectorAll('.calio-switch-input').forEach((input) => {
      input.addEventListener('change', () => {
        updateCardState(card);
        updateCount();
        applyFilters();
      });
    });

    updateCardState(card);
  });

  updateCount();
  updateOverview();
  applyFilters();

  if (searchNode) {
    searchNode.addEventListener('input', applyFilters);
  }

  if (clearSearchBtn) {
    clearSearchBtn.addEventListener('click', () => {
      if (searchNode) {
        searchNode.value = '';
      }

      applyFilters();
    });
  }

  filterPills.forEach((pill) => {
    pill.addEventListener('click', () => {
      const filterType = pill.dataset.filterType;
      const filterValue = pill.dataset.filterValue || 'all';

      if (filterType === 'category') {
        activeCategory = filterValue;
      }

      if (filterType === 'state') {
        activeState = filterValue;
      }

      if (filterType === 'tier') {
        activeTier = filterValue;
      }

      applyFilters();
    });
  });

  overviewCards.forEach((overviewCard) => {
    overviewCard.addEventListener('click', () => {
      activeCategory = overviewCard.dataset.overviewCategory || 'all';
      applyFilters();
    });
  });

  quickActions.forEach((action) => {
    action.addEventListener('click', () => {
      const type = action.dataset.quickAction;

      if (type === 'show-active') {
        activeState = 'active';
      }

      if (type === 'show-disabled') {
        activeState = 'disabled';
      }

      if (type === 'clear-filters') {
        activeCategory = 'all';
        activeTier = 'all';
        activeState = 'all';
        if (searchNode) {
          searchNode.value = '';
        }
      }

      applyFilters();
    });
  });

  const setAll = (value) => {
    cards.forEach((card) => {
      if (card.dataset.locked === '1') {
        return;
      }

      const target = card.querySelector('.calio-switch-input');
      if (target) {
        target.checked = value === '1';
        updateCardState(card);
      }
    });

    updateCount();
    applyFilters();
  };

  if (enableAllBtn) {
    enableAllBtn.addEventListener('click', () => setAll('1'));
  }

  if (disableAllBtn) {
    disableAllBtn.addEventListener('click', () => setAll('0'));
  }
}

const markCalioElementorWidgets = () => {
  const badgeCard = (card) => {
    if (!(card instanceof HTMLElement) || card.classList.contains('calio-editor-widget-card')) {
      return;
    }

    card.classList.add('calio-editor-widget-card');

    if (!card.querySelector('.calio-editor-widget-badge')) {
      const badge = document.createElement('span');
      badge.className = 'calio-editor-widget-badge';
      badge.setAttribute('aria-hidden', 'true');
      badge.setAttribute('title', 'Calio');
      card.appendChild(badge);
    }
  };

  const candidates = Array.from(document.querySelectorAll(
    '[data-widget_type], [data-widget-type], [data-element_type="widget"]',
  ));

  candidates.forEach((node) => {
    const widgetType = (
      node.dataset.widget_type
      || node.dataset.widgetType
      || node.getAttribute('data-widget_type')
      || node.getAttribute('data-widget-type')
      || node.querySelector('[data-widget_type]')?.getAttribute('data-widget_type')
      || node.querySelector('[data-widget-type]')?.getAttribute('data-widget-type')
      || ''
    ).toLowerCase();

    if (!widgetType.startsWith('calio-')) {
      return;
    }

    const card = node.closest('.elementor-element-wrapper') || node;
    badgeCard(card);
  });

  const calioCategories = Array.from(document.querySelectorAll(
    '.elementor-panel-category, [id*="calio"], [class*="calio"]',
  ));

  calioCategories.forEach((category) => {
    if (!(category instanceof HTMLElement)) {
      return;
    }

    const title = (
      category.querySelector('.elementor-panel-category-title, .elementor-panel-heading-title')?.textContent
      || category.getAttribute('aria-label')
      || category.id
      || ''
    ).trim().toLowerCase();

    if (!title.includes('calio')) {
      return;
    }

    category.querySelectorAll('.elementor-element-wrapper, .elementor-element').forEach(badgeCard);
  });
};

if (document.body) {
  markCalioElementorWidgets();

  const calioPanelObserver = new MutationObserver(() => {
    window.requestAnimationFrame(markCalioElementorWidgets);
  });

  calioPanelObserver.observe(document.body, {
    childList: true,
    subtree: true,
  });
}
