/**
 * Anjaneyulu.in — UI Utilities v2.0
 * Shimmer | Toast | Welcome Popup | Scroll Reveal
 */

/* ========================
   TOAST NOTIFICATION
   ======================== */
(function () {
  let toastContainer = null;

  function getContainer() {
    if (!toastContainer) {
      toastContainer = document.createElement('div');
      toastContainer.id = 'toast-container';
      document.body.appendChild(toastContainer);
    }
    return toastContainer;
  }

  const ICONS = {
    success: 'fa-circle-check',
    error: 'fa-circle-xmark',
    info: 'fa-circle-info',
    warning: 'fa-triangle-exclamation'
  };

  window.showToast = function (message, type = 'info', duration = 4000) {
    const container = getContainer();
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
      <i class="fas ${ICONS[type] || ICONS.info} toast-icon"></i>
      <span>${message}</span>
      <button class="toast-close" onclick="this.parentElement.remove()">
        <i class="fas fa-times"></i>
      </button>`;
    container.appendChild(toast);
    setTimeout(() => {
      toast.classList.add('toast-out');
      setTimeout(() => toast.remove(), 320);
    }, duration);
    return toast;
  };
})();

/* ========================
   SHIMMER HELPERS
   ======================== */
window.showShimmerCards = function (containerId, count = 3) {
  const el = document.getElementById(containerId);
  if (!el) return;
  const html = Array.from({ length: count }, () => `
    <div class="shimmer-card">
      <div class="shimmer-block shimmer-img"></div>
      <div class="shimmer-block shimmer-badge"></div>
      <div class="shimmer-block shimmer-title"></div>
      <div class="shimmer-block shimmer-text wide"></div>
      <div class="shimmer-block shimmer-text medium"></div>
      <div class="shimmer-block shimmer-text short" style="margin-top:1rem;height:2.5rem;border-radius:0.75rem;"></div>
    </div>`).join('');
  el.innerHTML = `<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:1.25rem;">${html}</div>`;
};

window.hideShimmerAndShow = function (containerId, renderFn, delay = 600) {
  setTimeout(() => {
    const el = document.getElementById(containerId);
    if (!el) return;
    el.style.opacity = '0';
    renderFn();
    requestAnimationFrame(() => {
      el.style.transition = 'opacity 0.4s ease';
      el.style.opacity = '1';
    });
  }, delay);
};

/* ========================
   WELCOME POPUP
   ======================== */
window.showWelcomePopup = function () {
  const key = 'anj_welcome_v2';
  if (localStorage.getItem(key)) return;
  localStorage.setItem(key, '1');

  const overlay = document.createElement('div');
  overlay.id = 'welcome-popup-overlay';
  overlay.innerHTML = `
    <div id="welcome-popup">
      <button class="popup-close" id="popupClose"><i class="fas fa-times"></i></button>
      <div class="popup-icon">🎉</div>
      <div class="popup-title">Welcome to Anjaneyulu.in!</div>
      <div class="popup-desc">
        Your trusted partner for <strong>Loans, Finance, Legal, Tech & Property</strong> services since 2015.
        Serving 10,000+ happy clients across Hyderabad.
      </div>
      <div class="popup-badge">
        <span style="background:#e6f0fa;color:#001f4d;">✓ Trusted Since 2015</span>
        <span style="background:#fdf8ea;color:#d4a017;">✓ 100% Secure</span>
        <span style="background:#e6f0fa;color:#001f4d;">✓ Expert Team</span>
      </div>
      <div class="popup-cta">
        <button class="popup-btn-primary" id="popupExploreCta">
          <i class="fas fa-arrow-right" style="margin-right:0.4rem;"></i> Explore Our Services
        </button>
        <button class="popup-btn-secondary" id="popupDismiss">Maybe Later</button>
      </div>
    </div>`;
  document.body.appendChild(overlay);

  const close = () => overlay.remove();
  document.getElementById('popupClose').addEventListener('click', close);
  document.getElementById('popupDismiss').addEventListener('click', close);
  document.getElementById('popupExploreCta').addEventListener('click', () => {
    close();
    const svc = document.getElementById('services');
    if (svc) svc.scrollIntoView({ behavior: 'smooth' });
    else window.location.href = 'index.html#services';
  });
  overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
};

/* ========================
   SCROLL REVEAL
   ======================== */
window.initScrollReveal = function () {
  const targets = document.querySelectorAll('.reveal, .reveal-left, .reveal-right');
  if (!targets.length) return;
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('revealed');
        observer.unobserve(entry.target);
      }
    });
  }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
  targets.forEach(el => observer.observe(el));
};

/* ========================
   COUNTER ANIMATION
   ======================== */
window.animateCounters = function () {
  document.querySelectorAll('[data-count]').forEach(el => {
    const target = parseFloat(el.dataset.count);
    const suffix = el.dataset.suffix || '';
    const prefix = el.dataset.prefix || '';
    const decimals = el.dataset.decimals ? parseInt(el.dataset.decimals) : 0;
    const duration = 1800;
    const step = target / (duration / 16);
    let current = 0;
    const timer = setInterval(() => {
      current = Math.min(current + step, target);
      el.textContent = prefix + current.toFixed(decimals) + suffix;
      if (current >= target) clearInterval(timer);
    }, 16);
  });
};

/* ========================
   PAGE CONTENT SHIMMER
   ======================== */
window.pageContentReveal = function (selectorOrFn, delay = 700) {
  if (typeof selectorOrFn === 'string') {
    const els = document.querySelectorAll(selectorOrFn);
    els.forEach(el => el.classList.add('content-hidden'));
    setTimeout(() => {
      els.forEach(el => el.classList.add('content-visible'));
    }, delay);
  } else if (typeof selectorOrFn === 'function') {
    setTimeout(selectorOrFn, delay);
  }
};

/* ========================
   APPLY SITE SETTINGS
   ======================== */
window.applySiteSettings = function () {
  const savedSettings = JSON.parse(localStorage.getItem('siteSettings') || '{}');
  if (Object.keys(savedSettings).length === 0) return;

  document.querySelectorAll('[data-setting]').forEach(el => {
    const key = el.dataset.setting;
    if (savedSettings[key]) {
      if (el.tagName === 'A') {
        if (key === 'phone') el.href = `tel:${savedSettings[key].replace(/[^0-9+]/g, '')}`;
        if (key === 'whatsapp') el.href = `https://wa.me/${savedSettings[key].replace(/[^0-9]/g, '')}`;
        if (key === 'email') el.href = `mailto:${savedSettings[key]}`;
      }
      el.textContent = savedSettings[key];
    }
  });
};

/* ========================
   AUTO-INIT ON DOM READY
   ======================== */
document.addEventListener('DOMContentLoaded', () => {
  // Inject toast container
  if (!document.getElementById('toast-container')) {
    const c = document.createElement('div');
    c.id = 'toast-container';
    document.body.appendChild(c);
  }

  // Apply dynamic settings
  applySiteSettings();

  // Init scroll reveal
  initScrollReveal();

  // Animate counters when visible
  const counterEls = document.querySelectorAll('[data-count]');
  if (counterEls.length) {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { animateCounters(); obs.disconnect(); }
      });
    }, { threshold: 0.3 });
    counterEls.forEach(el => obs.observe(el));
  }
});
