// Google bağlantısı sağlık adımları PHP tarafından PW Connect ve WordPress'te
// kayıtlı gerçek duruma göre oluşturulur. Tarayıcı tarafında temsili ilerleme
// animasyonu kullanılmaz.

(function(){
  document.addEventListener('DOMContentLoaded',function(){
    var flow=document.querySelector('.ptms-health-flow-card[data-stage="merchant_preparing"]');
    if(!flow || typeof PTMS_ADMIN==='undefined' || !PTMS_ADMIN.connectionCheckNonce) return;

    var storageKey='ptmsMerchantAutoCheckStarted';
    var started=parseInt(sessionStorage.getItem(storageKey)||'0',10);
    var now=Date.now();
    if(!started || started>now){started=now;sessionStorage.setItem(storageKey,String(started));}
    var maxDuration=10*60*1000;
    var interval=30*1000;
    var summary=flow.querySelector('.ptms-flow-summary strong');
    var merchantStep=flow.querySelector('[data-step="merchant-api"] .ptms-flow-status');
    var i18n=PTMS_ADMIN.i18n||{};
    function text(key,fallback){return i18n[key]||fallback;}
    function format(template,value){return String(template).replace('%d',String(value));}

    function stop(message){
      sessionStorage.removeItem(storageKey);
      if(summary && message) summary.textContent=message;
    }
    function schedule(){
      var elapsed=Date.now()-started;
      if(elapsed>=maxDuration){
        stop(text('automaticCheckFinished','Automatic checking has finished; use the manual check if necessary'));
        if(merchantStep) merchantStep.textContent=text('manualCheckAvailable','You can check manually');
        return;
      }
      var seconds=Math.ceil(interval/1000);
      if(summary) summary.textContent=format(text('automaticCheckCountdown','Google is connected; an automatic check will run in %d seconds'),seconds);
      setTimeout(check,interval);
    }
    function check(){
      if(summary) summary.textContent=text('checkingMerchantApi','Merchant API status is being checked automatically');
      if(merchantStep) merchantStep.textContent=text('checking','Checking');
      var body=new URLSearchParams({action:'ptms_check_google_connection_status',nonce:PTMS_ADMIN.connectionCheckNonce});
      fetch(PTMS_ADMIN.ajaxUrl,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},body:body.toString()})
        .then(function(response){return response.json();})
        .then(function(response){
          if(!response || !response.success){
            stop(text('automaticCheckFailed','Automatic checking could not be completed; use the manual check button'));
            if(merchantStep) merchantStep.textContent=text('manualCheckRequired','Manual check required');
            return;
          }
          var status=(response.data||{}).status||'unknown';
          if(status==='ready' || status==='connected'){
            sessionStorage.removeItem(storageKey);
            window.location.reload();
            return;
          }
          if(status==='preparing'){
            if(merchantStep) merchantStep.textContent=text('googlePreparationContinues','Google preparation is still in progress');
            schedule();
            return;
          }
          if(status==='reconnect_required'){
            stop(text('googleReconnectionRequired','Google connection must be re-established'));
            if(merchantStep) merchantStep.textContent=text('googleReconnectionRequired','Google connection must be re-established');
            return;
          }
          stop(text('connectionNotFound','No completed Google connection was found'));
          if(merchantStep) merchantStep.textContent=text('googleConnectionRequired','Google connection required');
        })
        .catch(function(){
          stop(text('automaticCheckFailed','Automatic checking could not be completed; use the manual check button'));
          if(merchantStep) merchantStep.textContent=text('manualCheckRequired','Manual check required');
        });
    }
    schedule();
  });
})();


(function(){
  var i18n=(typeof PTMS_ADMIN!=='undefined'&&PTMS_ADMIN.i18n)||{};
  function text(key,fallback){return i18n[key]||fallback;}
  function updateSync(){
    var box=document.querySelector('.ptms-sync-live');
    if(!box || typeof PTMS_ADMIN==='undefined') return;
    var body=new URLSearchParams({action:'ptms_sync_status',nonce:PTMS_ADMIN.syncNonce});
    fetch(PTMS_ADMIN.ajaxUrl,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},body:body.toString()})
      .then(function(r){return r.json();}).then(function(r){
        if(!r || !r.success) return;
        var d=r.data||{};
        var status=box.querySelector('.ptms-sync-status');
        if(status){status.textContent=d.label||text('ready','Ready');status.className='ptms-sync-status is-'+(d.status||'ready');}
        var bar=box.querySelector('.ptms-progress span'); if(bar) bar.style.width=(d.percent||0)+'%';
        var labels=d.metric_labels||{}, values=d.metric_values||{};
        var map={
          '[data-sync-description]':d.description||'',
          '[data-sync-progress-help]':d.progress_help||'',
          '[data-sync-label-first]':labels.first||text('total','Total'),
          '[data-sync-label-second]':labels.second||text('successful','Successful'),
          '[data-sync-label-third]':labels.third||text('failed','Failed'),
          '[data-sync-label-fourth]':labels.fourth||text('pendingQueue','Pending queue'),
          '[data-sync-value-first]':values.first!=null?values.first:d.total,
          '[data-sync-value-second]':values.second!=null?values.second:d.done,
          '[data-sync-value-third]':values.third!=null?values.third:d.failed,
          '[data-sync-value-fourth]':values.fourth!=null?values.fourth:d.remaining,
          '[data-sync-percent]':'%'+d.percent,
          '[data-sync-progress]':d.processed+' / '+d.total,
          '[data-sync-eta]':d.eta_label||'—',
          '[data-failed-queue]':d.failed_queue||0,
          '[data-worker-state]':d.worker_active?text('working','Working'):text('waiting','Waiting')
        };
        Object.keys(map).forEach(function(sel){var el=box.querySelector(sel);if(el)el.textContent=map[sel];});
        var activity=document.querySelector('.ptms-bulk-activity');
        if(activity){
          var activityTitle=activity.querySelector('[data-live-title]');
          var activityDone=activity.querySelector('[data-live-processed]');
          var activityTotal=activity.querySelector('[data-live-total]');
          var activityMessage=activity.querySelector('[data-live-message]');
          if(activityDone) activityDone.textContent=d.processed||0;
          if(activityTotal) activityTotal.textContent=d.total||0;
          if(activityMessage){
            activityMessage.textContent=d.status==='running'
              ? text('liveRefreshHelp','The status refreshes automatically every few seconds. You do not need to keep this page open.')
              : (d.status==='completed' ? text('initialSyncCompletedResults','The initial synchronization is complete. Updated results are being prepared.') : (d.description||''));
          }
          if(d.status!=='running'){
            activity.classList.add('is-finished');
            if(activityTitle) activityTitle.textContent=d.status==='completed'?text('initialSyncCompleted','Initial synchronization completed'):text('syncStatusUpdated','Synchronization status updated');
            var spinner=activity.querySelector('.ptms-activity-spinner');
            if(spinner) spinner.classList.add('is-finished');
            if(d.status==='completed' && !sessionStorage.getItem('ptmsSyncCompletionReloaded')){
              sessionStorage.setItem('ptmsSyncCompletionReloaded','1');
              setTimeout(function(){window.location.reload();},2500);
            }
          }
        }
        var logList=document.querySelector('[data-live-log-list]');
        if(logList && Array.isArray(d.activity_logs)){
          while(logList.firstChild) logList.removeChild(logList.firstChild);
          if(d.activity_logs.length){
            var heading=document.createElement('div');
            heading.className='ptms-console-log-heading';
            var headingTitle=document.createElement('strong'); headingTitle.textContent=text('bulkOperationLog','Bulk operation log');
            var headingMeta=document.createElement('small'); headingMeta.textContent=text('updatingAutomatically','Updating automatically');
            heading.appendChild(headingTitle); heading.appendChild(headingMeta); logList.appendChild(heading);
          }
          d.activity_logs.forEach(function(log){
            var row=document.createElement('div'); row.className='ptms-console-log-row is-'+(log.level||'info');
            var time=document.createElement('time');
            var stamp=parseInt(log.time||0,10); time.textContent=stamp?new Date(stamp*1000).toLocaleTimeString((typeof PTMS_ADMIN!=='undefined'&&PTMS_ADMIN.locale)||undefined,{hour:'2-digit',minute:'2-digit',second:'2-digit'}):'—';
            var mark=document.createElement('span');
            var content=document.createElement('div');
            var title=document.createElement('strong'); title.textContent=log.message||text('operationLog','Operation log'); content.appendChild(title);
            if(log.detail){var detail=document.createElement('small');detail.textContent=log.detail;content.appendChild(detail);}
            row.appendChild(time); row.appendChild(mark); row.appendChild(content); logList.appendChild(row);
          });
        }
        box.setAttribute('data-status',d.status||'ready'); if(d.status==='running') setTimeout(updateSync,4000);
      }).catch(function(){});
  }
  document.addEventListener('DOMContentLoaded',function(){
    var box=document.querySelector('.ptms-sync-live');
    if(box && box.getAttribute('data-status')==='running'){
      sessionStorage.removeItem('ptmsSyncCompletionReloaded');
      setTimeout(updateSync,1200);
      setTimeout(function(){window.location.reload();},10000);
    }
  });
})();

(function(){
  document.addEventListener('DOMContentLoaded',function(){
    var links=document.querySelectorAll('[data-ptms-lightbox]');
    if(!links.length) return;
    var overlay=document.createElement('div');
    overlay.className='ptms-lightbox';
    overlay.hidden=true;
    var i18n=(typeof PTMS_ADMIN!=='undefined'&&PTMS_ADMIN.i18n)||{};
    var screenshot=i18n.merchantScreenshot||'Merchant Center screenshot';
    var closeLabel=i18n.close||'Close';
    overlay.innerHTML='<div class="ptms-lightbox-inner" role="dialog" aria-modal="true" aria-label="'+screenshot+'"><button type="button" class="ptms-lightbox-close" aria-label="'+closeLabel+'">×</button><img alt=""></div>';
    document.body.appendChild(overlay);
    var image=overlay.querySelector('img');
    var close=overlay.querySelector('.ptms-lightbox-close');
    function hide(){overlay.hidden=true;image.removeAttribute('src');document.body.style.overflow='';}
    links.forEach(function(link){
      link.addEventListener('click',function(e){e.preventDefault();image.src=link.getAttribute('href');image.alt=(link.querySelector('img')||{}).alt||screenshot;overlay.hidden=false;document.body.style.overflow='hidden';close.focus();});
    });
    close.addEventListener('click',hide);
    overlay.addEventListener('click',function(e){if(e.target===overlay) hide();});
    document.addEventListener('keydown',function(e){if(e.key==='Escape'&&!overlay.hidden) hide();});
  });
})();
