const API = 'http://127.0.0.1:8000/api';
const UP = new URLSearchParams(location.search);
const id = UP.get('id') || UP.get('view');

if(!id) {
  window.location.href = 'explore.html';
}

// Ensure Visitor UUID for unique views
function getVisitorId() {
  let vid = localStorage.getItem('sv_visitor');
  if(!vid) {
    vid = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15);
    localStorage.setItem('sv_visitor', vid);
  }
  return vid;
}

const FALLBACK_IMGS = [
  'https://th.bing.com/th/id/OIP.yYhBFU7SPBhbzd0blCB8lwHaJQ?w=188&h=235&c=7&r=0&o=7&pid=1.7&rm=3',
  'https://th.bing.com/th/id/OIP.tzwbuHA1xWUByq1l5hDElgHaJ4?w=188&h=251&c=7&r=0&o=7&pid=1.7&rm=3'
];

async function loadAd() {
  try {
    const res = await fetch(`${API}/public/listings/${id}`);
    if(!res.ok) throw new Error('Not found');
    const l = await res.json();

    document.getElementById('loader').style.display = 'none';
    document.getElementById('mainWrap').style.display = 'block';

    document.title = `${l.title} in ${l.city} â€” Swagvio`;

    // Breadcrumb
    document.getElementById('bc').innerHTML = `<a href="index.html">Home</a> / <a href="explore.html?city=${encodeURIComponent(l.city)}">${l.city}</a> / <a href="explore.html?cat=${l.category}">${(l.category||'').replace('_', ' ')}</a> / <span>${l.title}</span>`;

    // Title & Meta
    document.getElementById('fTitle').textContent = l.title;
    
    let metaHTML = `<span>Published on ${new Date(l.created_at).toLocaleDateString('en-IN')}</span>`;
    if(l.boost_bid > 0 || l.is_boosted) metaHTML += `<span class="badge-f b-feat"><i class="fa-solid fa-star"></i> PREMIUM</span>`;
    if(l.user && l.user.is_verified) metaHTML += `<span class="badge-f b-ver"><i class="fa-solid fa-check"></i> VERIFIED</span>`;
    metaHTML += `<span style="margin-left:auto;"><i class="fa-solid fa-eye" style="color:var(--text-4);"></i> ${l.views_count+1} views</span>`;
    document.getElementById('fMeta').innerHTML = metaHTML;

    // Contact
    if(l.whatsapp) {
      document.getElementById('waBtn').style.display = 'flex';
      let w = l.whatsapp.replace(/[^0-9]/g, '');
      if(w.length === 10) w = '91'+w;
      document.getElementById('waBtn').href = `https://wa.me/${w}?text=Hi, I saw your ad "${encodeURIComponent(l.title)}" on Swagvio. Are you available?`;
    }
    if(l.phone) {
      document.getElementById('phBtn').style.display = 'flex';
      document.getElementById('phBtn').href = `tel:${l.phone}`;
    }

    // Specifications
    document.getElementById('fCat').textContent = (l.category||'').replace('_',' ');
    document.getElementById('fCity').textContent = l.city;
    if(l.age) document.getElementById('fAge').textContent = l.age + ' Years'; else document.getElementById('liAge').style.display='none';
    if(l.price_per_hour) document.getElementById('fPrice').textContent = 'â‚¹' + l.price_per_hour; else document.getElementById('liPrice').style.display='none';
    if(l.availability) document.getElementById('fAvail').textContent = l.availability.replace('_','/').toUpperCase(); else document.getElementById('liAvail').style.display='none';
    
    document.getElementById('fDesc').textContent = l.description || 'No description provided by the user.';

    // Tags rendering
    if(l.tags && Array.isArray(l.tags) && l.tags.length > 0) {
      let tHTML = '';
      l.tags.forEach(sec => {
        if(!sec || !sec.tags || !Array.isArray(sec.tags) || sec.tags.length === 0) return;
        
        let icon = 'fa-regular fa-hashtag';
        let lowerCol = (sec.column || '').toLowerCase();
        if(lowerCol.includes('service')) icon = 'fa-regular fa-heart';
        if(lowerCol.includes('attention')) icon = 'fa-regular fa-user';
        if(lowerCol.includes('place')) icon = 'fa-regular fa-map';
        
        let pillsHTML = sec.tags.map(t => `<span class="ad-tag-pill">${t}</span>`).join('');
        
        tHTML += `
        <div class="desc-box" style="margin-top:0; margin-bottom:24px;">
          <h3 class="box-h3" style="font-size:18px; color:#0f172a; border-bottom:none; margin-bottom:0;"><i class="${icon}" style="color:#0f172a;"></i> ${sec.column || 'Details'}</h3>
          <div class="ad-tag-list">${pillsHTML}</div>
        </div>`;
      });
      document.getElementById('dynamicTagsCont').innerHTML = tHTML;
    }

    // Images
    const slides = [];
    if(l.images && l.images.length > 0) {
      l.images.forEach(img => {
        slides.push(`http://127.0.0.1:8000/storage/${img.path}`);
      });
    } else if(l.primary_image) {
      slides.push(`http://127.0.0.1:8000/storage/${l.primary_image.path}`);
    } else {
      slides.push(FALLBACK_IMGS[id % 2]);
    }

    const gMain = document.getElementById('gMain');
    const gThumbs = document.getElementById('gThumbs');
    slides.forEach(src => {
      gMain.insertAdjacentHTML('beforeend', `<div class="swiper-slide"><img src="${src}" onerror="this.onerror=null;this.src='${FALLBACK_IMGS[0]}'"></div>`);
      gThumbs.insertAdjacentHTML('beforeend', `<div class="swiper-slide"><img src="${src}" onerror="this.onerror=null;this.src='${FALLBACK_IMGS[0]}'"></div>`);
    });

    // Init swiper
    const swiperThumbs = new Swiper('.swiper-thumbs', {
      spaceBetween: 10, slidesPerView: 'auto', freeMode: true, watchSlidesProgress: true,
    });
    const swiperMain = new Swiper('.swiper-main', {
      spaceBetween: 10,
      navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
      thumbs: { swiper: swiperThumbs }
    });

    // Fire view tracking POST
    recordView();

  } catch(e) {
    console.error(e);
    document.getElementById('loader').innerHTML = `<div style="color:#e11d48;font-size:48px;margin-bottom:16px;"><i class="fa-solid fa-circle-exclamation"></i></div><h3 style="font-family:'Plus Jakarta Sans'">Listing Not Found</h3><p style="color:var(--text-3);margin-bottom:20px;">The ad you are looking for may have been removed or deactivated.</p><a href="explore.html" style="color:var(--pink);font-weight:700;">Back to Explore</a>`;
  }
}

// Hit backend to count view
function recordView() {
  fetch(`${API}/public/listings/${id}/view`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-Visitor-Id': getVisitorId()
    }
  }).catch(e => console.log('View count error', e));
}

// Interactions (Favorite, Share, Report)
function initInteractions(listingId) {
  const strId = String(listingId);
  const btnFav = document.getElementById('btnFav');
  const favText = document.getElementById('favText');
  const favIcon = btnFav.querySelector('i');
  
  let favs = JSON.parse(localStorage.getItem('sv_favs') || '[]');
  
  if(favs.includes(strId)) {
    favIcon.className = 'fa-solid fa-heart';
    favIcon.style.color = '#e11d48';
    favText.textContent = 'Favorited';
  }

  btnFav.addEventListener('click', () => {
    let currentFavs = JSON.parse(localStorage.getItem('sv_favs') || '[]');
    if(currentFavs.includes(strId)) {
      currentFavs = currentFavs.filter(fid => fid !== strId);
      favIcon.className = 'fa-regular fa-heart';
      favIcon.style.color = '';
      favText.textContent = 'Save to Favorites';
    } else {
      currentFavs.push(strId);
      favIcon.className = 'fa-solid fa-heart';
      favIcon.style.color = '#e11d48';
      favText.textContent = 'Favorited';
    }
    localStorage.setItem('sv_favs', JSON.stringify(currentFavs));
  });

  document.getElementById('btnShare').addEventListener('click', async () => {
    const shareData = {
      title: document.title,
      text: 'Check out this ad on Swagvio!',
      url: window.location.href
    };
    if (navigator.share) {
      try {
        await navigator.share(shareData);
      } catch(e) { console.log('Share dismissed'); }
    } else {
      navigator.clipboard.writeText(window.location.href);
      alert('Link copied to clipboard!');
    }
  });

  const repModal = document.getElementById('reportModal');
  document.getElementById('btnReport').addEventListener('click', () => {
    repModal.style.display = 'flex';
  });
  document.getElementById('closeReport').addEventListener('click', () => {
    repModal.style.display = 'none';
  });
  
  document.getElementById('reportForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    btn.textContent = 'Submitting...';
    btn.disabled = true;
    
    try {
      const res = await fetch(`${API}/public/listings/${listingId}/report`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          reason: document.getElementById('repReason').value,
          details: document.getElementById('repDetails').value
        })
      });
      if(res.ok) {
        alert('Thank you! Your report has been submitted to moderations.');
        repModal.style.display = 'none';
        document.getElementById('reportForm').reset();
      } else {
        alert('Failed to submit report. Please try again.');
      }
    } catch(err) {
      console.error(err);
      alert('Error submitting report.');
    } finally {
      btn.textContent = 'Submit Report';
      btn.disabled = false;
    }
  });
}

loadAd().then(() => {
  if (id) {
    initInteractions(id);
  }
});
</script>
</body>
</html>
