
document.addEventListener('DOMContentLoaded', () => {
  /* =========================
       CONFIG
  ========================= */
  const rows              = document.querySelectorAll('tr.ai-item');
  const progressContainer = document.getElementById('progress-container');
  const progressBar       = document.getElementById('progress-bar');
  const progressText      = document.getElementById('progress-text');
  const currentGame       = document.getElementById('current-game');
  const nonce             = document.getElementById('nonce')?.value || '';
  const btnStart          = document.getElementById('btn-start');
  const btnPause          = document.getElementById('btn-pause');
  const btnStop           = document.getElementById('btn-stop');
  const baseUrlRow        = document.getElementById('base_url');
  const controlsWrapper   = document.querySelector('.import-controls-wrapper');
  const baseDomainInput   = document.getElementById('base_domain_url');
  const ImportNotifModal  = document.querySelector('#import-notification');
  const sourceSelect      = document.querySelector('select[name="auto_importer_settingss[source]"]');
  const baseUrlInput      = document.querySelector('input[name="auto_importer_settingss[base_url]"]');
  const pauseLabel        = btnPause?.querySelector('.label');
  const startLabel        = btnStart?.querySelector('.label');
  const STORAGE_KEY       = 'ai_post_imported_links';
  const btnSaveSettings   = document.querySelector('button.button-primary[type="submit"]');
  const btnResetSettings  = document.querySelector('input[name="auto_importer_reset_settings"]')?.closest('form')?.querySelector('button');
  const btnCloseNotif     = document.getElementById('import-notification-close');

  if (!baseDomainInput || !rows.length || !btnStart) return;

  let index       = 0;
  let isRunning   = false;
  let isPaused    = false;
  let isStopped   = false;
  let timeoutId   = null;
  let controller  = null;

  let importStats = {
    total:        0,
    success:      0,
    duplicate:    0,
    missingImage: 0,
    draft:        0,
    error:        0
  };

  let recentLogs = [];
  let importLogs = [];

  /* =========================
       UTILITIES
  ========================= */
  function cleanUrl(value) {
    return value.trim().replace(/\s+/g, '');
  }

  function getImportedLinks() {
    try {
      return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
    } catch {
      return [];
    }
  }

  function saveImportedLink(url) {
    const links = getImportedLinks();
    if (!links.includes(url)) {
      links.push(url);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(links));
    }
  }

  function isAlreadyImported(url) {
    return getImportedLinks().includes(url);
  }

  function markImportedRows() {
    const imported = new Set(getImportedLinks());
    rows.forEach(row => {
      if (imported.has(row.dataset.url)) {
        row.classList.add('imported');
        const badge = row.querySelector('.status-badge');
        badge.className = 'status-badge badge-success';
        badge.textContent = 'Already Imported';
        row.querySelector('.status-text').textContent = 'Already Imported';
      }
    });
  }

  markImportedRows();

  baseDomainInput.addEventListener('paste', (e) => {
    e.preventDefault();
    const pasted = (e.clipboardData || window.clipboardData).getData('text');
    baseDomainInput.value = cleanUrl(pasted);
  });

  baseDomainInput.addEventListener('input', () => {
    const cleaned = cleanUrl(baseDomainInput.value);
    if (baseDomainInput.value !== cleaned) {
      baseDomainInput.value = cleaned;
    }
  });

  function disableSettingsButtons() {
    if (btnSaveSettings) {
      btnSaveSettings.disabled = true;
      btnSaveSettings.classList.add('disabled');
    }
    if (btnResetSettings) {
      btnResetSettings.disabled = true;
      btnResetSettings.classList.add('disabled');
    }
  }

  function enableSettingsButtons() {
    if (btnSaveSettings) {
      btnSaveSettings.disabled = false;
      btnSaveSettings.classList.remove('disabled');
    }
    if (btnResetSettings) {
      btnResetSettings.disabled = false;
      btnResetSettings.classList.remove('disabled');
    }
  }

  function disableSettingsFields() {
    if (sourceSelect) sourceSelect.disabled = true;
    if (baseUrlInput) baseUrlInput.disabled = true;
  }

  function enableSettingsFields() {
    if (sourceSelect) sourceSelect.disabled = false;
    if (baseUrlInput) baseUrlInput.disabled = false;
    showCustomSourceNotice();
  }

  function addTooltip(el, text) {
    if (!el) return;
    el.classList.add('ai-tooltip');
    el.setAttribute('data-tooltip', text);
  }

  function removeTooltip(el) {
    if (!el) return;
    el.classList.remove('ai-tooltip');
    el.removeAttribute('data-tooltip');
  }

  function showToast(message, type = '') {
    const toast = document.createElement('div');
    toast.className = `ai-toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    requestAnimationFrame(() => toast.classList.add('show'));
    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 300);
    }, 3500);
  }

  function showImportNotification() {
    /* if (ImportNotifModal) ImportNotifModal.style.display = 'block';
    if (btnCloseNotif) btnCloseNotif.style.display = 'block'; */
  }

  function hideImportNotification() {
    /* if (ImportNotifModal) ImportNotifModal.style.display = 'none';
    if (btnCloseNotif) btnCloseNotif.style.display = 'none'; */
  }

  function updateImportProgressKeModal(current, total, currentTitle = '—', editLink = '') {
    if (total <= 0) return;
    const percent = Math.min(100, Math.round((current / total) * 100));
    document.getElementById('current-count').textContent = current;
    document.getElementById('total-count').textContent = total;
    document.getElementById('current-item-title').textContent = `Processing: ${currentTitle}`;
    document.getElementById('progress-fill').style.width = percent + '%';

    const linkSection = document.getElementById('edit-link-section');
    const editLinkEl = document.getElementById('edit-post-link');
    if (editLink && editLink !== '#') {
      editLinkEl.href = editLink;
      linkSection.style.display = 'block';
    } else {
      linkSection.style.display = 'none';
    }
  }

  function showProgress() {
    progressContainer?.classList.add('visible');
  }

  function hideProgress() {
    progressContainer?.classList.remove('visible');
  }

  function resetUI() {
    index = 0;
    isRunning = isPaused = isStopped = false;
    hideProgress();

    btnStart.disabled = false;
    btnStart.classList.remove('running');
    startLabel.textContent = 'Start Import';

    btnPause.disabled = true;
    btnStop.disabled = true;
    pauseLabel.textContent = 'Pause';

    rows.forEach(r => {
      r.classList.remove('processing', 'success', 'error', 'imported');
      const badge = r.querySelector('.status-badge');
      badge.className = 'status-badge badge-waiting';
      badge.textContent = 'Wait';
      r.querySelector('.status-text').textContent = 'Wait';

      const metaDiv = r.querySelector('.ai-row-meta');
      if (metaDiv) metaDiv.remove();
    });

    markImportedRows();
    enableSettingsFields();
  }

  function showImportCompleteMessage() {
    const table = document.getElementById('ai-import-table');
    const done = document.getElementById('ai-import-complete');

    if (table) {
      table.style.transition = 'opacity .4s ease';
      table.style.opacity = '0';
      setTimeout(() => table.style.display = 'none', 400);
    }

    if (done) {
      setTimeout(() => {
        done.style.display = 'block';
        done.style.opacity = '0';
        done.style.transition = 'opacity .4s ease';
        setTimeout(() => done.style.opacity = '1', 50);
      }, 450);
    }
  }

  function hideAllManualForms() {
    document.querySelectorAll('form#post_manual').forEach(f => f.style.display = 'none');
  }

  function showManualForm(row) {
    const url = row.dataset.url;
    if (isAlreadyImported(url)) return;
    const form = row.querySelector('form#post_manual');
    if (form) form.style.display = 'inline-block';
  }

  function showCustomSourceNotice() {
    const old = document.getElementById('ai-custom-notice');
    if (old) old.remove();

    if (!sourceSelect) return;

    const parentTd = sourceSelect.closest('td');
    if (!parentTd) return;

    if (sourceSelect.value === 'custom') {
      const notice = document.createElement('div');
      notice.id = 'ai-custom-notice';
      notice.className = 'notice notice-warning';
      notice.style.marginTop = '10px';
      notice.innerHTML = `<p>⚠️ <strong>Custom source selected.</strong><br>
        Please contact <a href="//exthem.es" target="_blank">exthem.es</a> for new source.</p>`;
      parentTd.appendChild(notice);

      if (baseUrlRow) baseUrlRow.style.display = 'none';
      if (controlsWrapper) controlsWrapper.style.display = 'none';
      if (btnStart) {
        btnStart.disabled = true;
        btnStart.title = 'Custom source requires admin configuration';
      }
    } else {
      if (baseUrlRow) baseUrlRow.style.display = '';
      if (controlsWrapper) controlsWrapper.style.display = '';
      if (btnStart) {
        btnStart.disabled = false;
        btnStart.title = '';
      }
    }
  }

  window.addEventListener('load', showCustomSourceNotice);
  sourceSelect?.addEventListener('change', showCustomSourceNotice);

  /* =========================
       LOGGING
  ========================= */
  function addRecentLog(title, status, extra = '', editLink = '') {
    const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    const logEntry = {
      time,
      title: title.length > 60 ? title.substring(0, 57) + '...' : title,
      status,
      extra,
      editLink: editLink || ''  // simpan editLink di object log
    };
    recentLogs.unshift(logEntry);
    if (recentLogs.length > 10) recentLogs.pop();
    renderRecentLogs();
  }

  function renderRecentLogs() {
    const list = document.getElementById('recent-activity-list');
    if (!list) return;
    list.innerHTML = '';

    recentLogs.forEach(l => {
      const li = document.createElement('li');
      li.style.marginBottom = '6px';

      // Status dengan warna
      const statusSpan = `<span class="status-${l.status.toLowerCase()}">${l.status}</span>`;

      // Tambahkan link Edit Post jika ada
      let editLinkHtml = '';
      if (l.editLink && l.editLink !== '#' && l.editLink.trim() !== '') {
        editLinkHtml = ` <a href="${l.editLink}" target="_blank" class="recent-edit-link" style="font-size:0.85em; margin-left:8px; color:#2271b1; text-decoration:none;">[Edit Post]</a>`;
      }

      li.innerHTML = `
        <span class="text-gray-500 text-xs">(${l.time})</span> 
        ${statusSpan}
        ${l.title}
        ${l.extra ? ` (${l.extra})` : ''}
        ${editLinkHtml}
      `;

      list.appendChild(li);
    });
  }

/* =========================
   FINAL RECENT LOG BY STATUS
   (AFTER IMPORT COMPLETE)
========================= */
function addRecentLogByStatusComplete() {
  const list = document.getElementById('recent-activity-list');
  if (!list) return;

  // Group log berdasarkan status
  const grouped = {
    Success: [],
    Error: [],
    Duplicate: [],
    Draft: []
  };

  recentLogs.forEach(log => {
    if (grouped[log.status]) {
      grouped[log.status].push(log);
    }
  });

  // Separator utama
  const separator = document.createElement('li');
  separator.style.margin = '10px 0';
  separator.style.borderTop = '2px solid #e5e7eb';
  separator.innerHTML = `<strong>Final Import Results</strong>`;
  list.appendChild(separator);

  Object.entries(grouped).forEach(([status, logs]) => {
    if (!logs.length) return;

    const header = document.createElement('li');
    header.style.marginTop = '8px';
    header.innerHTML = `<strong class="status-${status.toLowerCase()}">${status} (${logs.length})</strong>`;
    list.appendChild(header);

    logs.forEach(l => {
      const li = document.createElement('li');
      li.style.marginLeft = '12px';
      li.style.marginBottom = '4px';

      let editLinkHtml = '';
      if (l.editLink && l.editLink.trim() !== '') {
        editLinkHtml = `
          <a href="${l.editLink}" 
             target="_blank"
             style="margin-left:6px; font-size:0.85em; color:#2271b1; text-decoration:none;">
            [Edit]
          </a>`;
      }

      li.innerHTML = `
        <span class="text-gray-500 text-xs">(${l.time})</span>
        ${l.title}
        ${editLinkHtml}
      `;

      list.appendChild(li);
    });
  });

  // Auto scroll ke bawah
  list.scrollTop = list.scrollHeight;
}


  function addImportLog(message, type = 'info', edit_link = '') {
  const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  importLogs.unshift({ time, message, type, edit_link });
  if (importLogs.length > 20) importLogs.pop();
  renderImportLogs();
}


  function renderImportLogs() {
  const containers = {
    success: document.getElementById('import-log-success'),
    error: document.getElementById('import-log-error'),
    warning: document.getElementById('import-log-warning'),
    info: document.getElementById('import-log-info')
  };

  // Bersihkan semua list
  Object.values(containers).forEach(list => {
    if (list) list.innerHTML = '';
  });

  importLogs.forEach(log => {
    const li = document.createElement('li');
    li.style.marginBottom = '6px';

    let prefix = '', colorClass = '';
    const type = log.type.toLowerCase();
    switch (type) {
      case 'error':
        prefix = '✗';
        colorClass = 'text-red-600 font-medium';
        break;
      case 'warning':
        prefix = '⚠';
        colorClass = 'text-amber-600';
        break;
      case 'success':
        prefix = '✓';
        colorClass = 'text-green-600';
        break;
      default:
        prefix = 'ℹ';
        colorClass = 'text-blue-600';
    }

    // Build innerHTML log
    li.innerHTML = `<span class="text-gray-500 text-xs">(${log.time})</span> 
                    <span class="${colorClass}">${prefix}</span> 
                    ${log.message}`;

    // Jika ada edit_link, tambahkan tombol Edit
    if (log.edit_link) {
      const editAnchor = document.createElement('a');
      editAnchor.href = log.edit_link;
      editAnchor.target = '_blank';
      editAnchor.textContent = 'Edit';
      editAnchor.style.marginLeft = '8px';
      editAnchor.style.color = '#1e73be';
      editAnchor.style.textDecoration = 'underline';
      li.appendChild(editAnchor);
    }

    // Masukkan ke container sesuai tipe
    if (containers[type]) {
      containers[type].appendChild(li);
    } else {
      containers.info?.appendChild(li); // fallback ke info
    }
  });

  // Scroll otomatis ke bawah untuk tiap container
  Object.values(containers).forEach(list => {
    if (list) list.scrollTop = list.scrollHeight;
  });
}


  /* =========================
       PROCESS
  ========================= */
  function processNext() {
    if (isPaused || isStopped) return;

    if (index >= rows.length) {
      progressBar.style.width = '100%';
      progressText.textContent = `${rows.length} / ${rows.length}`;

      setTimeout(() => {
        hideProgress();
        showImportCompleteMessage();
        //showImportNotification();
      }, 1200);

      btnStart.disabled = false;
      btnPause.disabled = true;
      btnStop.disabled = true;
      startLabel.textContent = 'Start Import';
      pauseLabel.textContent = 'Pause';

      enableSettingsFields();
      enableSettingsButtons();
      controlsWrapper?.classList.remove('is-sticky');
      removeTooltip(btnSaveSettings);
      removeTooltip(btnResetSettings);
      controlsWrapper.style.display = 'none';

      isRunning = isPaused = isStopped = false;
	  
	  addRecentLogByStatusComplete();


      return;
    }

    const row = rows[index];
    const url = row.dataset.url;
    const title = row.querySelector('.ai-item-title')?.textContent.trim() || 'Item';
    const badge = row.querySelector('.status-badge');
    const text = row.querySelector('.status-text');

    row.classList.add('processing');
    badge.className = 'status-badge badge-processing';
    badge.textContent = 'Processing...';
    text.textContent = 'Processing...';

    currentGame.textContent = `Processing... ${title} (${index + 1}/${rows.length})`;
    //updateImportProgressKeModal(index, rows.length, title, '');

    controller = new AbortController();
	let editLink = '';
	
    fetch(ajaxurl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `action=auto_submit_post&wp_url=${encodeURIComponent(url)}&nonce=${nonce}`,
      signal: controller.signal
    })
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(res => {
        if (isStopped) return;

        row.classList.remove('processing');

        let logMessage = '';
        let logType = 'info';		
		
		 // Set editLink di scope ini
		let editLink = res.data?.edit_link || '';
	
        if (res.success) {
          row.classList.add('success', 'imported');
          saveImportedLink(url);

          badge.className = 'status-badge badge-success';
          badge.textContent = 'Success';
          text.textContent = 'Success';

          if (res.data?.edit_link) {
            let metaDiv = row.querySelector('.ai-row-meta');
            if (!metaDiv) {
              metaDiv = document.createElement('div');
              metaDiv.className = 'row-actions ai-row-meta';
              text.insertAdjacentElement('afterend', metaDiv);
            }
            metaDiv.innerHTML = `<a href="${res.data.edit_link}" target="_blank">Edit Post</a>`;
          }

          logMessage = `Success: ${title} imported/updated.`;
          logType = 'success';
          importStats.success++;
			// Panggil addRecentLog dengan edit_link (jika ada)
			/* addRecentLog(
			  title,
			  logType.charAt(0).toUpperCase() + logType.slice(1),
			  '',
			  res.data?.edit_link || ''
			);
			addImportLog(`Success: ${title} imported/updated.`, 'success', editLink); */
        } else {
          const serverMessage = res.data?.message || 'Unknown error';
          row.classList.add('error');
          badge.className = 'status-badge badge-error';
          badge.textContent = serverMessage;
          text.textContent = serverMessage;

          logType = 'error';
          logMessage = `Failed: ${title} → ${serverMessage}`;
          importStats.error++;
          showManualForm(row);
		  
		 /*  addRecentLog(title, logType.charAt(0).toUpperCase() + logType.slice(1), '', editLink);
		  addImportLog(logMessage, logType, editLink); */
		  
        }

				
		  

    // Panggil sekali saja
    addRecentLog(title, logType.charAt(0).toUpperCase() + logType.slice(1), '', editLink);
    addImportLog(logMessage, logType, editLink);
  
      })
      .catch(err => {
        if (isStopped) return;

        row.classList.remove('processing');
        row.classList.add('error');
        badge.className = 'status-badge badge-error';

        if (err.name === 'AbortError') {
          badge.textContent = 'Stopped';
          text.textContent = 'Stopped';
        } else {
          badge.textContent = 'Connection Error';
          text.textContent = 'Connection Error';
        }

        importStats.error++; 
		
    addRecentLog(title, 'Error', '', ''); // satu kali saja
    addImportLog(`Error processing ${title}: ${err.message}`, 'error', '');
	
		//addImportLog(`Error processing ${title}: ${err.message}`, 'error', editLink); // gunakan editLink yang sudah didefinisikan
        showManualForm(row);
      })
      .finally(() => {
        if (isStopped) return;

        index++;
        progressBar.style.width = Math.round((index / rows.length) * 100) + '%';
        progressText.textContent = `${index} / ${rows.length}`;

        timeoutId = setTimeout(processNext, 2200 + Math.random() * 2800);

        //updateImportProgressKeModal(index, rows.length, title, '');
        //showImportNotification();
      });
  }

  /* =========================
       BUTTON EVENTS
  ========================= */
  if (btnStart) {
    btnStart.onclick = () => {
      if (isRunning) return;

      hideAllManualForms();
      isRunning = true;
      btnStart.classList.add('running');
      startLabel.textContent = 'Running';

      btnPause.disabled = false;
      btnStop.disabled = false;

      disableSettingsFields();
      disableSettingsButtons();
      controlsWrapper?.classList.add('is-sticky');

      addTooltip(btnSaveSettings, 'Importer is running');
      addTooltip(btnResetSettings, 'Importer is running');

      showToast('🚀 Importer is running… Please wait', 'success');
      //showImportNotification();
      showProgress();

      processNext();
    };
  }

  if (btnPause) {
    btnPause.onclick = () => {
      isPaused = !isPaused;
      pauseLabel.textContent = isPaused ? 'Continue' : 'Pause';
      if (!isPaused) processNext();
    };
  }

  if (btnStop) {
    btnStop.onclick = () => {
      isStopped = true;
      isPaused = false;

    // Hentikan proses AJAX & timeout
    if (timeoutId) clearTimeout(timeoutId);
    if (controller) controller.abort();


       // Reset UI (tabel, status row, progress)
    resetUI();
	
	// Force enable tombol Save/Reset
    [btnSaveSettings, btnResetSettings].forEach(btn => {
      if (!btn) return;
      btn.disabled = false;             // hapus disabled
      btn.classList.remove('disabled'); // hapus class
      // paksa reflow
      btn.offsetHeight; 
    });

    // Reset controls wrapper
    if (controlsWrapper) {
      controlsWrapper.classList.remove('is-sticky');
      controlsWrapper.style.display = 'none';
    }
	
      removeTooltip(btnSaveSettings);
      removeTooltip(btnResetSettings);

      //hideImportNotification();
      showToast('⛔ Import stopped', 'warning');
    };
  }
  
});
 
 