// SOCIOS CRM: logo y branding cargados desde initial-data del backend.
(function () {
  'use strict';
  let branding = null;

  function validUrl(value) {
    try {
      const u = new URL(String(value || '').trim());
      return u.protocol === 'https:' || u.protocol === 'http:';
    } catch (_) { return false; }
  }

  function applyBranding() {
    if (!branding) return;
    const logo = branding.logo_url;
    const brandName = String(branding.brand_name || '').trim();

    if (validUrl(logo)) {
      document.querySelectorAll('img').forEach(img => {
        const src = img.getAttribute('src') || '';
        const alt = (img.getAttribute('alt') || '').toLowerCase();
        if (src.includes('label/icons/plugin/icon.png') || alt === 'logo' || alt.startsWith('logo ')) {
          if (img.dataset.sociosDynamicLogo !== logo) {
            img.dataset.sociosDynamicLogo = logo;
            img.src = logo;
          }
        }
      });
    }

    if (brandName) {
      document.querySelectorAll('[data-socios-brand-name]').forEach(el => {
        el.textContent = brandName;
      });
    }
    document.documentElement.style.setProperty('--socios-brand-logo', validUrl(logo) ? `url("${logo}")` : 'none');
  }

  function load() {
    chrome.runtime.sendMessage({ message: 'get_socios_dynamic_config', force: true }, response => {
      if (chrome.runtime.lastError || !response?.success) {
        console.warn('[SOCIOS] No se pudo cargar branding dinámico:', chrome.runtime.lastError?.message || response?.error);
        return;
      }
      branding = response.data?.branding || null;
      applyBranding();
      const observer = new MutationObserver(applyBranding);
      observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });
    });
  }

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