/**
 * FLOWhatsapp — Theme-aware WCAG AAA brand name injector (fluxo.html / kanban.html)
 *
 * Extracted out of an inline <script> so it actually runs: the packaged manifest CSP is
 * "script-src 'self'" with no 'unsafe-inline' and these are static files (no server-rendered
 * per-request nonce is possible), so an inline block here is silently blocked by Chrome.
 *
 * Colour contract:
 *   Dark background  → "FLOW" = #a78bfa  (violet 400, ~8.8:1 on dark bg)   ✓ AAA
 *                      "Whatsapp" = #ffffff (~15:1 on dark bg)             ✓ AAA
 *   Light background → "FLOW" = #5b21b6  (violet 800, ~9.0:1 on #fff)     ✓ AAA
 *                      "Whatsapp" = #5b21b6  (same, full purple name)
 *
 * WCAG AAA large text (≥14pt bold) requires ≥ 4.5:1. WCAG AAA normal text requires ≥ 7:1.
 * All chosen colours exceed 7:1 on their respective backgrounds.
 */
(function () {
  'use strict';

  var LABEL_ID = 'wf-brand-name';

  /* ── Colour tokens ─────────────────────────────────────────────────────── */
  var DARK_FLOW  = '#a78bfa'; // violet-400 — AAA on dark bg
  var DARK_REST  = '#ffffff'; // white      — AAA on dark bg
  var LIGHT_FLOW = '#5b21b6'; // violet-800 — AAA on light bg
  var LIGHT_REST = '#5b21b6'; // same purple for full-name consistency

  /* ── Get app name (whitelabel-aware) ──────────────────────────────────── */
  function getAppName() {
    return (self.FLOWHATSAPP_LICENSE_CONFIG && self.FLOWHATSAPP_LICENSE_CONFIG.appName)
      ? String(self.FLOWHATSAPP_LICENSE_CONFIG.appName)
      : 'FLOWhatsapp';
  }

  /* ── Relative luminance (sRGB) per WCAG 2.x ──────────────────────────── */
  function srgbChannel(val) {
    var v = val / 255;
    return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
  }
  function relativeLuminance(r, g, b) {
    return 0.2126 * srgbChannel(r) + 0.7152 * srgbChannel(g) + 0.0722 * srgbChannel(b);
  }

  /* ── Detect background darkness of a DOM element ─────────────────────── */
  function bgIsDark(element) {
    var el = element;
    while (el && el !== document.documentElement) {
      var bg = window.getComputedStyle(el).backgroundColor;
      if (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') {
        var m = bg.match(/rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/);
        if (m) {
          var lum = relativeLuminance(+m[1], +m[2], +m[3]);
          // dark if luminance < 0.179 (roughly < #777)
          return lum < 0.179;
        }
      }
      el = el.parentElement;
    }
    // Fallback: OS preference
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  }

  /* ── Build or update the brand label ─────────────────────────────────── */
  function applyTheme(label, dark) {
    label.style.setProperty('--wf-brand-flow', dark ? DARK_FLOW : LIGHT_FLOW);
    label.style.setProperty('--wf-brand-rest', dark ? DARK_REST : LIGHT_REST);
  }

  function createLabel(appName) {
    var el = document.createElement('span');
    el.id = LABEL_ID;

    // Split "FLOWhatsapp" → "FLOW" + "Whatsapp" (case-insensitive match)
    var m = appName.match(/^(FLOW|Flow|flow)([\s\S]*)/);
    if (m) {
      var flow = document.createElement('span');
      flow.className = 'wf-bn-flow';
      flow.textContent = m[1];

      var rest = document.createElement('span');
      rest.className = 'wf-bn-rest';
      rest.textContent = m[2];

      el.appendChild(flow);
      el.appendChild(rest);
    } else {
      // Non-FLOW brand name: single span, theme will colour it
      var single = document.createElement('span');
      single.className = 'wf-bn-flow'; // use flow colour as brand accent
      single.textContent = appName;
      el.appendChild(single);
    }

    return el;
  }

  /* ── Inject brand label next to the logo icon ─────────────────────────── */
  function tryInject() {
    if (document.getElementById(LABEL_ID)) return true;

    var appName = getAppName();

    // Strategy A: small <img> (logo icon) in the top area
    var imgs = document.querySelectorAll('#root img');
    for (var i = 0; i < imgs.length; i++) {
      var img = imgs[i];
      var rect = img.getBoundingClientRect();
      if (rect.width > 0 && rect.width <= 60 && rect.height <= 60) {
        var parent = img.parentElement;
        if (!parent) continue;

        var label = createLabel(appName);
        label.style.marginLeft = '7px';

        var ps = window.getComputedStyle(parent);
        if (ps.display !== 'flex' && ps.display !== 'inline-flex') {
          parent.style.display = 'flex';
          parent.style.alignItems = 'center';
        }

        img.after(label);
        applyTheme(label, bgIsDark(parent));
        watchTheme(label, parent);
        return true;
      }
    }

    // Strategy B: small <svg> in the header area (top 80px)
    var svgs = document.querySelectorAll('#root svg');
    for (var j = 0; j < svgs.length; j++) {
      var svg = svgs[j];
      var svgRect = svg.getBoundingClientRect();
      if (svgRect.width > 0 && svgRect.width <= 50 && svgRect.height <= 50 && svgRect.top < 80) {
        var svgParent = svg.parentElement;
        if (!svgParent || document.getElementById(LABEL_ID)) continue;

        var svgLabel = createLabel(appName);
        svgLabel.style.marginLeft = '8px';

        var svgPs = window.getComputedStyle(svgParent);
        if (svgPs.display !== 'flex' && svgPs.display !== 'inline-flex') {
          svgParent.style.display = 'flex';
          svgParent.style.alignItems = 'center';
        }

        svg.after(svgLabel);
        applyTheme(svgLabel, bgIsDark(svgParent));
        watchTheme(svgLabel, svgParent);
        return true;
      }
    }

    return false;
  }

  /* ── Watch for theme changes (dark-mode toggle, WhatsApp theme switch) ── */
  function watchTheme(label, parentEl) {
    // OS-level dark mode changes
    var mq = window.matchMedia('(prefers-color-scheme: dark)');
    mq.addEventListener('change', function () {
      applyTheme(label, bgIsDark(parentEl));
    });

    // WhatsApp in-app theme switch: observe body class / data-* attrs
    var themeObs = new MutationObserver(function () {
      applyTheme(label, bgIsDark(parentEl));
    });
    themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] });
    themeObs.observe(document.body, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] });
  }

  /* ── Rebuild on whitelabel branding update ────────────────────────────── */
  window.addEventListener('flowhatsapp:branding-updated', function () {
    var existing = document.getElementById(LABEL_ID);
    if (existing) existing.remove();
    setTimeout(tryInject, 80);
  });

  /* ── Bootstrap ────────────────────────────────────────────────────────── */
  var domObserver = new MutationObserver(function (mutations, obs) {
    if (tryInject()) obs.disconnect();
  });

  function boot() {
    var root = document.getElementById('root');
    if (root) {
      domObserver.observe(root, { childList: true, subtree: true });
      // Staggered retries for slow React hydration
      setTimeout(tryInject, 250);
      setTimeout(tryInject, 700);
      setTimeout(tryInject, 1500);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
