/* Global state */
window.__lastVerifiedFile = null;

/* DEV toggle for reCAPTCHA */
(function(){
  function readFlagFromURL(){
    try{
      var q = location.search || ''; var h = location.hash || '';
      var m = (q.match(/[?&]recaptcha=(on|off)/i) || h.match(/recaptcha=(on|off)/i));
      return m ? m[1].toLowerCase() : null;
    }catch(e){ return null; }
  }
  function getLS(){ try{ return localStorage.getItem('recaptcha_off'); }catch(e){ return null; } }
  function setLS(v){ try{ if(v){ localStorage.setItem('recaptcha_off','1'); } else { localStorage.removeItem('recaptcha_off'); } }catch(e){} }
  var urlFlag = readFlagFromURL();
  if(urlFlag === 'off'){ setLS(true); }
  if(urlFlag === 'on'){ setLS(false); }
  var off = !!getLS();
  window.DEV_MODE = off;
  window.recaptchaOff = function(v){
    setLS(!!v);
    try{ console.log('recaptcha_off =', !!v, '(reload to apply)'); }catch(e){}
  };
  window.recaptchaMode = function(){ return { off: off, hint: 'use recaptchaOff(true/false) and reload' }; };
})();

function toAbsolute(p){
  try{
    if(!p) return p;
    if(/^https?:\/\//i.test(p)) return p;
    if(p.startsWith('/')) return p;
    const base = (document.querySelector('base') && document.querySelector('base').href) ||
                 (location.pathname.replace(/\/[^\/]*$/, '/'));
    return base + p.replace(/^\.\//,'').replace(/^\//,'');
  }catch(e){ return p; }
}

function isIOSLike(){
  try{
    const ua = navigator.userAgent || "";
    const iOS = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    return !!iOS;
  }catch(e){ return false; }
}

function isSafariLike(){
  try{
    const ua = navigator.userAgent || "";
    return /Safari\//.test(ua) && !/Chrome|CriOS|FxiOS|EdgiOS|OPiOS/.test(ua);
  }catch(e){ return false; }
}

function isAndroid(){
  try{
    return /Android/i.test(navigator.userAgent || "");
  }catch(e){ return false; }
}

function isMobile(){
  try{
    const ua = navigator.userAgent || "";
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua) || 
           (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||
           window.innerWidth <= 768;
  }catch(e){ return false; }
}



// Build PDF viewer URL - always use pdf.php for consistency
function viewerSrcForPlatform(pdfPathOrUrl){
  try{
    // Handle blob/data URLs
    if(/^blob:|^data:/i.test(pdfPathOrUrl)){ 
      return pdfPathOrUrl; 
    }
    
    // Use pdf.php for all file-based PDFs
    return 'pdf.php?f=' + encodeURIComponent(pdfPathOrUrl);
  }catch(_e){
    return 'pdf.php?f=' + encodeURIComponent(pdfPathOrUrl);
  }
}

(function injectBasicStyles(){
  const css = `
/* Global fix for all interactive elements - prevents red rectangle on mobile */
* {
  -webkit-tap-highlight-color: transparent !important;
}
button, a, input, select, textarea, [role="button"] {
  -webkit-tap-highlight-color: transparent !important;
  -webkit-touch-callout: none;
}
#result{margin-top:12px}
.doc-available-line{text-align:right;color:#00B594;font-weight:800;margin:0 0 8px}
.preview-box{background:#E6F2FF;border:1px solid #DBE7FF;border-radius:10px;padding:24px;text-align:center}
.preview-box p{margin:0 0 12px;color:#3b3f52}
.pdf-badge{display:inline-block;font-weight:700;padding:12px 18px;border-radius:6px;border:1px solid #C8D3D5;background:#F7F9FC;color:#5B636F;margin-bottom:14px}
.open-btn{
  display:inline-block;
  padding:16px 32px;
  border-radius:6px;
  border:1px solid #081430;
  cursor:pointer;
  font-size:16px;
  background:#F7F9FC;
  color:#081430;
  font-weight:700;
  -webkit-appearance:none;
  -moz-appearance:none;
  appearance:none;
  touch-action:manipulation;
  -webkit-tap-highlight-color:transparent !important;
  -webkit-touch-callout:none;
  -webkit-user-select:none;
  user-select:none;
  outline:none !important;
  text-decoration:none;
  transition:all 0.2s ease;
  min-height:48px;
  width:auto;
  max-width:100%;
  box-shadow:none;
}
.open-btn:hover,.open-btn:active{
  filter:brightness(0.97);
  transform:scale(0.98);
  outline:none !important;
  box-shadow:none !important;
}
.open-btn:focus{
  outline:none !important;
  box-shadow:0 0 0 3px rgba(0,181,148,0.3);
}
.open-btn:focus:not(:focus-visible){
  outline:none;
  box-shadow:none;
}
.err{
  background:#fff;
  color:#b00020;
  border:1px solid #f2c3c8;
  padding:14px 16px;
  border-radius:8px;
  margin-top:12px;
  text-align:center;
  font-family:'Tajawal',system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
  font-weight:600;
  font-size:15px;
  line-height:1.6;
  min-height:48px;
  display:flex;
  align-items:center;
  justify-content:center;
  word-break:break-word;
}
.err:empty{
  display:none !important;
  visibility:hidden !important;
  height:0 !important;
  min-height:0 !important;
  padding:0 !important;
  margin:0 !important;
  border:none !important;
}

/* PDF Modal - Universal mobile support */
.pdf-modal{
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  width:100vw;
  height:100vh;
  height:100%;
  background:rgba(8,20,48,0.96);
  z-index:99999;
  display:flex;
  flex-direction:column;
  overflow:hidden;
  -webkit-overflow-scrolling:touch;
}

.pdf-wrap{
  position:relative;
  width:100%;
  height:100%;
  display:flex;
  flex-direction:column;
  background:#2a2a2a;
}

.pdf-header{
  background:#2C176C;
  color:#fff;
  padding:14px 16px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  flex-shrink:0;
  z-index:100000;
  box-shadow:0 2px 8px rgba(0,0,0,0.3);
}

.pdf-title{
  font-size:16px;
  font-weight:700;
  margin:0;
}

.pdf-close{
  background:#fff;
  color:#2C176C;
  border:0;
  border-radius:6px;
  padding:10px 20px;
  cursor:pointer;
  font-weight:700;
  font-size:15px;
  box-shadow:0 2px 4px rgba(0,0,0,0.2);
  transition:all 0.2s;
  -webkit-appearance:none;
  -moz-appearance:none;
  appearance:none;
  touch-action:manipulation;
  -webkit-tap-highlight-color:transparent !important;
  -webkit-touch-callout:none;
  outline:none !important;
  min-height:44px;
}

.pdf-close:hover, .pdf-close:active{
  background:#f5f5f5;
  transform:scale(0.98);
  outline:none !important;
  box-shadow:0 2px 4px rgba(0,0,0,0.2) !important;
}

.pdf-close:focus{
  outline:none !important;
  box-shadow:0 0 0 3px rgba(44,23,108,0.3);
}

.pdf-close:focus:not(:focus-visible){
  outline:none;
  box-shadow:0 2px 4px rgba(0,0,0,0.2);
}

.pdf-content{
  flex:1;
  position:relative;
  background:#525659;
  overflow:auto;
  -webkit-overflow-scrolling:touch;
  width:100%;
  height:100%;
}

.pdf-embed, .pdf-iframe{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  min-height:100%;
  border:0;
  background:#fff;
}

/* iOS Safari specific fixes */
@supports (-webkit-touch-callout: none) {
  .pdf-modal{
    position:fixed;
    top:0;
    left:0;
    width:100vw;
    height:100vh;
    height:-webkit-fill-available;
  }
  
  .pdf-content{
    overflow:auto;
    -webkit-overflow-scrolling:touch;
    height:-webkit-fill-available;
  }
  
  .pdf-embed, .pdf-iframe{
    position:relative;
    height:100vh;
    height:-webkit-fill-available;
    min-height:100vh;
    min-height:-webkit-fill-available;
  }
}

/* Android browser fixes */
@media screen and (max-width: 768px) {
  .pdf-modal{
    position:fixed;
  }
  
  .pdf-content{
    overflow:auto;
    -webkit-overflow-scrolling:touch;
  }
  
  .pdf-embed, .pdf-iframe{
    min-height:calc(100vh - 60px);
  }
}

/* Landscape orientation */
@media (orientation: landscape) and (max-height: 500px) {
  .pdf-header{
    padding:10px 12px;
  }
  
  .pdf-title{
    font-size:14px;
  }
  
  .pdf-close{
    padding:8px 16px;
    font-size:14px;
  }
}
`;
  const style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);
})();

function showError(msg){
  const res = document.getElementById('result');
  if(!res) return;
  
  // Ensure we have a message to display
  const displayMsg = (msg && typeof msg === 'string' && msg.trim()) 
    ? msg.trim() 
    : 'حدث خطأ. يرجى المحاولة مرة أخرى.';
  
  res.innerHTML = `<div class="err">${displayMsg}</div>`;
  
  // Ensure the card container gets the has-result class to hide the form
  var verifyCard = document.querySelector('.verify');
  if(verifyCard){
    verifyCard.classList.add('has-result');
  }
}

function renderSuggestions(res, json){
  try{
    if(!res) return;
    if(json && json.searched && json.searched.path){
      const p = document.createElement('p');
      p.style.cssText='font-size:12px;color:#6e6b7b;margin-top:8px';
      p.textContent = 'المسار الذي تم البحث عنه: ' + json.searched.path;
      res.appendChild(p);
    }
  }catch(_e){}
}

// FIXED: Universal PDF modal that works on ALL mobile browsers
function openPdfModal(src){
  try{
    if(!src || typeof src!=='string'){
      var res = document.getElementById('result');
      if(res){ 
        res.innerHTML='<div class="err">مسار الملف غير صالح.</div>'; 
        var verifyCard = document.querySelector('.verify');
        if(verifyCard) verifyCard.classList.add('has-result');
      }
      return;
    }
  }catch(_e){}
  
  // For mobile: Use dedicated viewer page (most reliable)
  if (isMobile()) {
    const viewerUrl = 'pdf-viewer.html?f=' + encodeURIComponent(src);
    window.open(viewerUrl, '_blank');
    return;
  }
  
  // Desktop: Use modal
  const url = viewerSrcForPlatform(src);
  const modal = document.createElement('div');
  modal.className = 'pdf-modal';
  
  // Desktop browsers: Use object with iframe fallback
  modal.innerHTML = `
    <div class="pdf-wrap">
      <div class="pdf-header">
        <h2 class="pdf-title">عرض المستند</h2>
        <button class="pdf-close" aria-label="إغلاق">إغلاق ✕</button>
      </div>
      <div class="pdf-content">
        <object class="pdf-embed" 
                data="${url}" 
                type="application/pdf"
                width="100%"
                height="100%">
          <iframe class="pdf-iframe" 
                  src="${url}"></iframe>
        </object>
      </div>
    </div>`;
  
  document.body.appendChild(modal);
  
  // Prevent body scroll
  document.body.style.overflow = 'hidden';
  document.body.style.position = 'fixed';
  document.body.style.width = '100%';
  
  const closeBtn = modal.querySelector('.pdf-close');
  const closeModal = function(){
    try{
      document.body.style.overflow = '';
      document.body.style.position = '';
      document.body.style.width = '';
      modal.remove();
    }catch(_e){}
  };
  
  if(closeBtn){
    closeBtn.addEventListener('click', closeModal);
  }
  
  // Close on backdrop click
  modal.addEventListener('click', function(e){
    if(e.target === modal){
      closeModal();
    }
  });
  
  // ESC key to close
  const escHandler = function(e){
    if(e.key === 'Escape' || e.keyCode === 27){
      closeModal();
      document.removeEventListener('keydown', escHandler);
    }
  };
  document.addEventListener('keydown', escHandler);
}

document.addEventListener('DOMContentLoaded', function(){
  var form = document.getElementById('verificationForm');
  if(!form) return;
  if(form.__boundSubmit) return;
  form.__boundSubmit = true;

  form.addEventListener('submit', async function(e){
    if(!ensureRecaptchaToken()){
      e.preventDefault();
      var resMsg = document.getElementById('result');
      if(resMsg){ 
        resMsg.innerHTML='<div class="err">يرجى إكمال التحقق أنا لست روبوت</div>'; 
        var verifyCard = document.querySelector('.verify');
        if(verifyCard) verifyCard.classList.add('has-result');
      }
      return;
    }
    e.preventDefault();

    const docType   = document.getElementById('docType').value.trim();
    const docNumber = document.getElementById('docNumber').value.trim();

    const token = (function(){
      var t = document.getElementById('gRecaptchaToken');
      if(t && t.value) return t.value;
      if(typeof grecaptcha!=='undefined' && grecaptcha){
        try{
          if (window.__recaptchaId != null) return grecaptcha.getResponse(window.__recaptchaId) || '';
          return grecaptcha.getResponse() || '';
        }catch(_e){}
      }
      return '';
    })();

    const formData = new URLSearchParams({ 
      docType, 
      docNumber, 
      'g-recaptcha-response': token 
    });
    
    const headers = { 
      'Content-Type': 'application/x-www-form-urlencoded' 
    };
    
    if (typeof DEV_MODE!=='undefined' && DEV_MODE) {
      headers['X-Bypass-Recaptcha'] = '1';
    }

    let json;
    try {
      const r = await fetch('verify.php', { 
        method:'POST', 
        headers, 
        body: formData.toString() 
      });
      
      const text = await r.text();
      
      try {
        json = JSON.parse(text);
      } catch(parseErr) {
        const msg = (text || '').slice(0, 400).trim() || 'تعذر الاتصال بالخادم';
        showError(msg);
        return;
      }
    } catch (netErr) {
      showError('تعذر الاتصال بالخادم');
      return;
    }

    const res = document.getElementById('result');
    if(!json || !json.ok){
      showError((json && json.msg) || 'البيانات لا تطابق قاعدة البيانات');
      return;
    }

    const headerText = json.label || (docType && docNumber ? (docType + '_' + docNumber + ' المستندات المتاحة') : 'المستندات المتاحة');
    window.__lastVerifiedFile = (json && json.fileExists) ? json.file : null;

    res.innerHTML = '<div class="preview-box"><div class="doc-available-line">'+headerText+'</div><div class="pdf-badge">PDF</div><br/><a href="pdf.php?f=' + encodeURIComponent(json.file) + '" class="open-btn" target="_blank" download="كشف الحساب-1.pdf">عرض المستند</a></div>';
    
    // Ensure the card container gets the has-result class to hide the form
    var verifyCard = document.querySelector('.verify');
    if(verifyCard){
      verifyCard.classList.add('has-result');
    }

    if(!json.fileExists){
      showError('لم يتم العثور على ملف مطابق. تأكد من الاسم داخل htdocs/uploads/');
      renderSuggestions(res, json);
      return;
    }
  });
});

/* Google reCAPTCHA helpers */
function onRecaptchaOK(token){
  try{
    var t = document.getElementById('gRecaptchaToken');
    if(t) t.value = token || (typeof grecaptcha!=='undefined'?grecaptcha.getResponse():'' );
    var btn = document.getElementById('check');
    if(btn) btn.disabled = false;
  }catch(e){}
}

function onRecaptchaExpired(){
  try{
    var t = document.getElementById('gRecaptchaToken');
    if(t) t.value = '';
    var btn = document.getElementById('check');
    if(btn) btn.disabled = true;
  }catch(e){}
}

function ensureRecaptchaToken(){
  var token = '';
  var hidden = document.getElementById('gRecaptchaToken');
  if(hidden && hidden.value) token = hidden.value;
  if(!token && typeof grecaptcha!=='undefined' && grecaptcha){
    try{
      if (window.__recaptchaId != null) token = grecaptcha.getResponse(window.__recaptchaId) || '';
      else token = grecaptcha.getResponse() || '';
    }catch(e){ token = ''; }
  }
  if (token) return true;
  if (typeof DEV_MODE!=='undefined' && DEV_MODE) return true;
  return false;
}

function resetRecaptchaAfter(){
  try{
    document.addEventListener('submit', function(){
      try{
        if(typeof grecaptcha!=='undefined' && grecaptcha){
          if (window.__recaptchaId != null) grecaptcha.reset(window.__recaptchaId);
          else grecaptcha.reset();
        }
      }catch(_e){}
    }, true);
  }catch(_e){}
}

resetRecaptchaAfter();