(() => {
  const logoSelector = [
    'header a.logo',
    'header a.ftb-logo',
    'header a.logo-container',
    'header a[href="index"]',
    'header a[href="index.html"]',
    'header a[href="/"]',
    'header a[href="https://toolbajar.com/"]'
  ].join(', ');

  function createLogo() {
    const image = document.createElement('img');
    image.src = '/image/logo.png';
    image.alt = 'ToolBajar';
    image.width = 40;
    image.height = 40;
    image.decoding = 'async';
    image.className = 'site-logo-badge loaded';
    return image;
  }

  function addLogo() {
    if (document.querySelector('.site-logo-badge')) return;

    const target = document.querySelector(logoSelector);
    if (target) {
      target.insertAdjacentElement('afterbegin', createLogo());
      return;
    }

    const link = document.createElement('a');
    link.href = '/';
    link.className = 'site-logo-fallback';
    link.setAttribute('aria-label', 'ToolBajar home');
    link.append(createLogo());
    const header = document.querySelector('header, #mainNav, nav');
    if (header) {
      header.insertAdjacentElement('afterbegin', link);
    } else {
      document.body.append(link);
    }
  }

  const style = document.createElement('style');
  style.textContent = `
    .site-logo-badge {
      width: 40px !important;
      height: 40px !important;
      min-width: 40px !important;
      aspect-ratio: 1 / 1;
      display: inline-block !important;
      object-fit: cover;
      box-sizing: border-box;
      padding: 3px;
      border-radius: 10px;
      background: linear-gradient(135deg, #BFACC8, #783F8E, #4F1271);
      box-shadow: 0 3px 10px rgba(79, 18, 113, .35);
      opacity: 1 !important;
      vertical-align: middle;
    }
    header a.logo, header a.ftb-logo, header a.logo-container,
    header a[href="index"], header a[href="index.html"] {
      gap: 8px;
    }
    .site-logo-fallback {
      position: absolute;
      top: 10px;
      left: 12px;
      z-index: 2001;
      line-height: 0;
    }
  `;
  document.head.append(style);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addLogo, { once: true });
  } else {
    addLogo();
  }
})();
