/**
 * Early tenant SEO loader (runs from index.html before React).
 *
 * Source of truth for title / description / keywords:
 *   public/branding/tenant-{id}.json  →  "meta"
 *
 * Canonical host comes from public/branding/domain-registry.json.
 * React keeps the same tags in sync via src/components/TenantSeoHead.tsx.
 */
(async function applyTenantSeoFromBranding() {
  const brandingBase = '/branding';

  function normalizeHostname(hostname) {
    return String(hostname || '').toLowerCase().replace(/\.$/, '');
  }

  function lookupHost(registry, hostname) {
    const host = normalizeHostname(hostname);
    if (registry[host]) return registry[host];
    const alt = host.startsWith('www.') ? host.slice(4) : ('www.' + host);
    return registry[alt];
  }

  function canonicalOrigin(tenantId, registry) {
    const hosts = Object.keys(registry).filter(function (host) {
      return String(registry[host]) === String(tenantId);
    });
    if (!hosts.length) return window.location.origin.replace(/\/$/, '');
    const apex = hosts.find(function (h) { return !h.startsWith('www.'); }) || hosts[0];
    return 'https://' + apex;
  }

  function setMeta(attr, key, value) {
    if (!value) return;
    let el = document.querySelector('meta[' + attr + '="' + key + '"]');
    if (!el) {
      el = document.createElement('meta');
      el.setAttribute(attr, key);
      document.head.appendChild(el);
    }
    el.setAttribute('content', value);
  }

  function toAbsolute(url, origin) {
    if (!url) return origin + '/icon-192x192.png';
    if (/^https?:\/\//i.test(url)) return url;
    return origin + (url.charAt(0) === '/' ? url : '/' + url);
  }

  function collapseText(text) {
    return String(text || '').replace(/\s+/g, ' ').trim();
  }

  function keywordPack(config) {
    const type = (config.tenantType || (config.homepage && config.homepage.homepageLayout) || '');
    const packs = {
      accounts: 'finance courses, finance training, online finance courses, business courses, career training',
      college: 'college courses, online learning, student courses, LMS, career training',
      education: 'online courses, e-learning, education platform, career training',
      academics: 'academic courses, online education, student training',
      political: 'online learning, training platform, courses',
      techieshub: 'tech courses, programming courses, online IT training, career training'
    };
    return packs[type] || 'online courses, e-learning, career training';
  }

  function resolveSeo(config) {
    const name = config.tenantName || 'Edutech Platform';
    const meta = config.meta || {};
    const hero = config.homepage && config.homepage.heroSubtitle;
    return {
      title: collapseText(meta.title) || (name + ' | Online Courses & Career Training'),
      description: collapseText(meta.description) || collapseText(config.description) || collapseText(hero) || ('Learn with ' + name + ' through career-focused online courses and training.'),
      keywords: collapseText(meta.keywords) || (name + ', ' + name + ' courses, ' + keywordPack(config)),
      image: meta.image || config.favicon || config.logo
    };
  }

  function patchJsonLd(id, patch) {
    const script = document.getElementById(id);
    if (!script) return;
    try {
      const data = JSON.parse(script.textContent || '{}');
      script.textContent = JSON.stringify(Object.assign(data, patch));
    } catch (e) { /* ignore */ }
  }

  function applySeo(config, origin) {
    const seo = resolveSeo(config);
    const canonical = origin.replace(/\/$/, '') + '/';
    const image = toAbsolute(seo.image, origin.replace(/\/$/, ''));

    document.title = seo.title;
    setMeta('name', 'description', seo.description);
    setMeta('name', 'keywords', seo.keywords);
    setMeta('name', 'author', config.tenantName || 'Platform Team');
    setMeta('property', 'og:title', seo.title);
    setMeta('property', 'og:description', seo.description);
    setMeta('property', 'og:url', canonical);
    setMeta('property', 'og:image', image);
    setMeta('name', 'twitter:title', seo.title);
    setMeta('name', 'twitter:description', seo.description);
    setMeta('name', 'twitter:image', image);

    let canonicalLink = document.querySelector('link[rel="canonical"]');
    if (canonicalLink) {
      canonicalLink.setAttribute('href', canonical);
    } else {
      canonicalLink = document.createElement('link');
      canonicalLink.setAttribute('rel', 'canonical');
      canonicalLink.setAttribute('href', canonical);
      document.head.appendChild(canonicalLink);
    }

    patchJsonLd('ld-organization', {
      name: config.tenantName || seo.title,
      url: canonical,
      logo: image
    });
    patchJsonLd('ld-website', { name: seo.title, url: canonical });
  }

  let registry = {};
  try {
    const regRes = await fetch(brandingBase + '/domain-registry.json?v=' + Date.now(), {
      cache: 'no-store',
      headers: { 'Cache-Control': 'no-cache' }
    });
    if (regRes.ok) registry = await regRes.json();
  } catch (e) { /* preview hosts fall back to location.origin */ }

  const domainTenant = lookupHost(registry, window.location.hostname);
  const queryTenant = new URLSearchParams(window.location.search).get('tenant');
  const tenantId = domainTenant || queryTenant || 'default';

  try {
    const response = await fetch(brandingBase + '/tenant-' + tenantId + '.json?v=' + Date.now(), {
      cache: 'no-store',
      headers: { 'Cache-Control': 'no-cache' }
    });

    if (!response.ok) return;

    const config = await response.json();
    applySeo(config, canonicalOrigin(config.tenantId || tenantId, registry));

    if (config.favicon) {
      const favicon = document.getElementById('app-favicon') || document.querySelector('link[rel~="icon"]');
      if (favicon) favicon.setAttribute('href', config.favicon);
    }

    if (config.colors && config.colors.primary) {
      const themeColor = document.querySelector("meta[name='theme-color']");
      if (themeColor) themeColor.setAttribute('content', config.colors.primary);
    }
  } catch (error) {
    console.warn('Tenant branding load failed');
  }
})();
