/**
 * RandomGroup Pro - Admin Panel Script
 * Supports: Ad configuration, Domain URL management, Export/Import
 */

(function () {
  const form = document.getElementById('adminConfigForm');
  const resetBtn = document.getElementById('resetConfigBtn');
  const exportBtn = document.getElementById('exportConfigBtn');
  const importInput = document.getElementById('importConfigInput');
  const statusBox = document.getElementById('adminStatus');
  const updateAllUrlsBtn = document.getElementById('updateAllUrlsBtn');
  const urlUpdateStatus = document.getElementById('urlUpdateStatus');

  // Domain configuration elements
  const domainUrlInput = document.getElementById('domainUrlInput');
  const siteNameInput = document.getElementById('siteNameInput');

  const STORAGE_KEY_DOMAIN = 'rgp_domain_config_v1';

  function getConfig() {
    if (!window.RGPAdManager) return null;
    return window.RGPAdManager.readConfig();
  }

  function getDomainConfig() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY_DOMAIN);
      if (!raw) return { domainUrl: 'https://randomgrouppro.com', siteName: 'RandomGroup Pro' };
      return JSON.parse(raw);
    } catch (e) {
      return { domainUrl: 'https://randomgrouppro.com', siteName: 'RandomGroup Pro' };
    }
  }

  function setStatus(message, type = 'info') {
    if (!statusBox) return;
    statusBox.textContent = message;
    statusBox.className = `admin-status ${type}`;
  }

  function setUrlStatus(message, type = 'info') {
    if (!urlUpdateStatus) return;
    urlUpdateStatus.textContent = message;
    urlUpdateStatus.className = `admin-status ${type}`;
  }

  function fillForm(config) {
    if (!form || !config) return;

    // Basic settings
    form.enabled.checked = !!config.enabled;
    form.provider.value = config.provider || 'adsense';
    form.clientId.value = config.clientId || '';
    form.adsterraScriptUrl.value = config.adsterraScriptUrl || '';
    form.customAdScript.value = config.customAdScript || '';

    // Slots
    form.slotHeader.value = config.slots?.header || '';
    form.slotHero.value = config.slots?.hero || '';
    form.slotContentTop.value = config.slots?.contentTop || '';
    form.slotContentBottom.value = config.slots?.contentBottom || '';
    form.slotSidebar.value = config.slots?.sidebar || '';
    form.slotFooter.value = config.slots?.footer || '';

    // Verification
    form.googleSiteVerification.value = config.verification?.googleSiteVerification || '';
    form.adsenseAccount.value = config.verification?.adsenseAccount || '';
    form.bingVerification.value = config.verification?.bingVerification || '';
    form.yandexVerification.value = config.verification?.yandexVerification || '';
    form.customHeadTags.value = config.customHeadTags || '';

    // Domain config
    const domainConfig = getDomainConfig();
    if (domainUrlInput) domainUrlInput.value = domainConfig.domainUrl || 'https://randomgrouppro.com';
    if (siteNameInput) siteNameInput.value = domainConfig.siteName || 'RandomGroup Pro';
  }

  function collectForm() {
    return {
      enabled: form.enabled.checked,
      provider: form.provider.value,
      clientId: form.clientId.value.trim(),
      adsterraScriptUrl: form.adsterraScriptUrl.value.trim(),
      customAdScript: form.customAdScript.value,
      slots: {
        header: form.slotHeader.value.trim(),
        hero: form.slotHero.value.trim(),
        contentTop: form.slotContentTop.value.trim(),
        contentBottom: form.slotContentBottom.value.trim(),
        sidebar: form.slotSidebar.value.trim(),
        footer: form.slotFooter.value.trim()
      },
      verification: {
        googleSiteVerification: form.googleSiteVerification.value.trim(),
        adsenseAccount: form.adsenseAccount.value.trim(),
        bingVerification: form.bingVerification.value.trim(),
        yandexVerification: form.yandexVerification.value.trim()
      },
      customHeadTags: form.customHeadTags.value
    };
  }

  function saveConfig(config) {
    localStorage.setItem(window.RGPAdManager.storageKey, JSON.stringify(config));
    setStatus('Konfigurasi berhasil disimpan.', 'success');
  }

  function saveDomainConfig(domainConfig) {
    localStorage.setItem(STORAGE_KEY_DOMAIN, JSON.stringify(domainConfig));
    // Also save to ad config for easy access
    const adConfig = getConfig() || {};
    adConfig.domainUrl = domainConfig.domainUrl;
    adConfig.siteName = domainConfig.siteName;
    localStorage.setItem(window.RGPAdManager.storageKey, JSON.stringify(adConfig));
  }

  // Generate all HTML pages with updated URLs
  function generateAllPagesWithNewUrls(domainUrl) {
    const pages = [
      { file: 'index.html', title: 'Random Group Generator Premium' },
      { file: 'generator.html', title: 'Generator' },
      { file: 'howto.html', title: 'Cara Penggunaan' },
      { file: 'about.html', title: 'Tentang Kami' },
      { file: 'copyright.html', title: 'Hak Cipta' },
      { file: 'tools.html', title: 'Tools' },
      { file: 'all-tools.html', title: 'Semua Tools' },
      { file: 'tool-picker.html', title: 'Random Name Picker' },
      { file: 'tool-pairs.html', title: 'Random Pair Generator' },
      { file: 'tool-spinner.html', title: 'Wheel Spinner' },
      { file: 'tool-list-shuffler.html', title: 'List Shuffler' },
      { file: 'tool-bracket.html', title: 'Tournament Bracket' },
      { file: 'tool-number.html', title: 'Random Number' },
      { file: 'tool-color.html', title: 'Random Color' },
      { file: 'tool-password.html', title: 'Password Generator' },
      { file: 'tool-duplicate-remover.html', title: 'Duplicate Remover' },
      { file: 'tool-seat-generator.html', title: 'Seat Generator' },
      { file: 'tool-team-balancer.html', title: 'Team Balancer' },
      { file: 'tool-suite.html', title: 'Tool Suite' },
      { file: 'tool-leader.html', title: 'Random Leader' },
      { file: 'admin.html', title: 'Admin Panel' }
    ];

    // Show instructions for manual update
    const instructions = `
PENTING: Untuk memperbarui URL di semua halaman, Anda perlu mengedit setiap file HTML secara manual.

Berikut list halaman yang perlu diperbarui:
${pages.map(p => `- ${p.file}: Canonical URL -> ${domainUrl}/${p.file}`).join('\n')}

Caranya:
1. Buka setiap file HTML
2. Cari tag <link rel="canonical" href="...">
3. Ubah URL-nya ke ${domainUrl}/[nama-file]
4. Simpan file

Atau Anda bisa menggunakan tools bulk replace di editor favorit Anda.
    `;

    return instructions;
  }

  function bindEvents() {
    if (!form) return;

    form.addEventListener('submit', (e) => {
      e.preventDefault();
      const config = collectForm();
      saveConfig(config);
      setStatus('Konfigurasi iklan berhasil disimpan.', 'success');
    });

    resetBtn?.addEventListener('click', () => {
      localStorage.removeItem(window.RGPAdManager.storageKey);
      fillForm(window.RGPAdManager.defaultConfig);
      setStatus('Konfigurasi direset ke default.', 'warning');
    });

    exportBtn?.addEventListener('click', () => {
      const config = collectForm();
      // Include domain config in export
      const domainConfig = getDomainConfig();
      const exportData = {
        ...config,
        domainConfig: domainConfig,
        exportedAt: new Date().toISOString()
      };

      const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'rgp-admin-config.json';
      a.click();
      URL.revokeObjectURL(url);
      setStatus('Konfigurasi berhasil diexport.', 'info');
    });

    importInput?.addEventListener('change', async (e) => {
      const file = e.target.files?.[0];
      if (!file) return;

      try {
        const text = await file.text();
        const imported = JSON.parse(text);

        // Extract domain config if present
        if (imported.domainConfig) {
          saveDomainConfig(imported.domainConfig);
        }

        // Remove domainConfig from imported data before saving to ad config
        delete imported.domainConfig;
        delete imported.exportedAt;

        localStorage.setItem(window.RGPAdManager.storageKey, JSON.stringify(imported));
        fillForm(getConfig());
        setStatus('Konfigurasi berhasil diimport.', 'success');
      } catch (err) {
        setStatus('Gagal import konfigurasi. Format JSON tidak valid.', 'error');
      }
    });

    // Domain URL update button
    updateAllUrlsBtn?.addEventListener('click', () => {
      const domainUrl = domainUrlInput?.value?.trim();
      const siteName = siteNameInput?.value?.trim();

      if (!domainUrl) {
        setUrlStatus('Mohon masukkan URL domain terlebih dahulu.', 'error');
        return;
      }

      // Validate URL format
      try {
        new URL(domainUrl);
      } catch (e) {
        setUrlStatus('Format URL tidak valid. Contoh: https://randomgrouppro.com', 'error');
        return;
      }

      // Save domain config
      const domainConfig = { domainUrl, siteName: siteName || 'RandomGroup Pro' };
      saveDomainConfig(domainConfig);

      // Generate instructions for manual update
      const instructions = generateAllPagesWithNewUrls(domainUrl);

      setUrlStatus('Konfigurasi domain disimpan!', 'success');

      // Show alert with instructions
      alert('Konfigurasi domain berhasil disimpan!\n\n' + instructions);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    if (!window.RGPAdManager) return;
    fillForm(getConfig());
    bindEvents();
  });
})();
