(() => {
  'use strict';

  const config = window.calioMarketingHud;
  const root = document.querySelector('[data-calio-marketing-hud]');

  if (!config || !root) {
    return;
  }

  const tabs = Array.from(root.querySelectorAll('[data-marketing-tab]'));
  const panels = Array.from(root.querySelectorAll('[data-marketing-panel]'));
  const exportButton = root.querySelector('[data-marketing-export]');
  const status = root.querySelector('[data-marketing-status]');
  let activeView = 'geography';

  const activate = (view) => {
    activeView = view;

    tabs.forEach((tab) => {
      const isActive = tab.dataset.marketingTab === view;
      tab.classList.toggle('is-active', isActive);
      tab.setAttribute('aria-selected', isActive ? 'true' : 'false');
    });

    panels.forEach((panel) => {
      const isActive = panel.dataset.marketingPanel === view;
      panel.classList.toggle('is-active', isActive);
      panel.hidden = !isActive;
    });
  };

  const csvCell = (value) => `"${String(value ?? '').replaceAll('"', '""')}"`;

  const exportCsv = () => {
    const panel = root.querySelector(`[data-marketing-panel="${activeView}"]`);
    const tables = panel ? Array.from(panel.querySelectorAll('[data-marketing-table]')) : [];
    const lines = [];

    tables.forEach((table) => {
      const type = table.dataset.marketingTable || activeView;
      const firstHeader = type === 'source' ? config.labels.source : config.labels.location;

      if (lines.length > 0) {
        lines.push('');
      }
      lines.push([firstHeader, config.labels.orders, config.labels.revenue].map(csvCell).join(','));

      table.querySelectorAll('.calio-marketing-hud__row').forEach((row) => {
        lines.push([
          row.dataset.name || '',
          row.dataset.orders || '0',
          row.dataset.revenue || '0',
        ].map(csvCell).join(','));
      });
    });

    if (lines.length === 0) {
      if (status) {
        status.textContent = config.labels.empty;
      }
      return;
    }

    const blob = new Blob([`\uFEFF${lines.join('\r\n')}`], {
      type: 'text/csv;charset=utf-8',
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    const label = activeView === 'traffic' ? config.labels.traffic : config.labels.geography;

    link.href = url;
    link.download = `${config.filePrefix}-${label.toLowerCase().replaceAll(' ', '-')}.csv`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);

    if (status) {
      status.textContent = '';
    }
  };

  tabs.forEach((tab) => {
    tab.addEventListener('click', () => activate(tab.dataset.marketingTab || 'geography'));
  });

  if (exportButton) {
    exportButton.addEventListener('click', exportCsv);
  }
})();
