// ElevenLabs widget tool bridge.
    // Goal: keep conversation alive by navigating inside SPA (no full reload).
    (function () {
      function normalizeDestination(destination) {
        var raw = typeof destination === 'string' ? destination.trim() : '';
        if (!raw) return null;

        if (/^https?:\/\//i.test(raw)) return raw;

        var key = raw.toLowerCase();
        var known = {
          'home': '/',
          'services': '/services',
          'about': '/about',
          'contact': '/contact',
          'book-consultation': '/book-consultation',
          'book': '/book-consultation',
          'case-studies': '/case-studies',
          'portfolio': '/portfolio',
          'blog': '/blog',
          'checkout': '/checkout',
          'register': '/register',
          'login': '/login',
          'web-development': '/services/web-development',
          'software-development': '/services/software-development',
          'marketing-growth': '/services/marketing-growth',
          'ai-automation': '/services/ai-automation',
          'it-infrastructure': '/services/it-infrastructure',
          'consulting': '/services/consulting',
          'data-analytics': '/services/data-analytics',
          'digital-operations-platform': '/services/digital-operations-platform'
        };
        if (known[key]) raw = known[key];

        var serviceSlugs = {
          'content-strategy': true,
          'conversion-rate-optimization': true,
          'programmatic-advertising': true,
          'international-seo': true,
          'marketing-analytics': true,
          'data-visualization-bi': true,
          'customer-intelligence': true,
          'web-app-measurement': true,
          'ai-chatbots': true,
          'process-automation': true,
          'ai-predictive-intelligence': true,
          'ai-voice-assistants': true,
          'sovran-assistant': true,
          'ai-integration-services': true,
          'machine-learning-models': true,
          'cloud-architecture-devops': true,
          'network-architecture': true,
          'managed-it-support': true,
          'disaster-recovery': true,
          'infrastructure-monitoring': true,
          'server-optimization': true,
          'remote-helpdesk': true,
          'patch-management': true,
          'endpoint-automation': true,
          'digital-transformation': true,
          'cto-as-a-service': true,
          'training-workshops': true,
          'martech-consulting': true,
          'data-strategy-governance': true,
          'growth-consulting': true,
          'custom-web-applications': true,
          'e-commerce-solutions': true,
          'pos-system': true,
          'ux-ui-design': true,
          'custom-software-apis': true,
          'seo-optimization': true,
          'paid-advertising-ppc': true
        };
        if (!known[key] && serviceSlugs[key]) {
          raw = '/services/' + key;
        }

        if (raw.charAt(0) !== '/') raw = '/' + raw;

        var isDe = window.location.pathname === '/de' || window.location.pathname.indexOf('/de/') === 0;
        var isAppDestination = window.__sovranIsAppPath
          ? window.__sovranIsAppPath(raw)
          : (raw === '/login' || raw === '/register');
        if (isDe && raw.indexOf('/de') !== 0 && !isAppDestination) {
          raw = raw === '/' ? '/de' : '/de' + raw;
        }
        return raw;
      }

      function navigateWithinSpa(target) {
        try {
          var next = new URL(target, window.location.origin);
          if (next.origin !== window.location.origin) return false;

          var nextPath = next.pathname + next.search + next.hash;
          var currentPath = window.location.pathname + window.location.search + window.location.hash;
          if (nextPath === currentPath) return true;

          window.history.pushState({}, '', nextPath);
          if (typeof window.PopStateEvent === 'function') {
            window.dispatchEvent(new PopStateEvent('popstate'));
          } else {
            var popstateEvent = document.createEvent('Event');
            popstateEvent.initEvent('popstate', true, true);
            window.dispatchEvent(popstateEvent);
          }
          return true;
        } catch (e) {
          return false;
        }
      }

      function bindTools(widget) {
        if (!widget || widget.__sovranBound) return;
        widget.__sovranBound = true;
        widget.setAttribute('disable-banner', '');

        var widgetDe = {
          'Need help?': 'Brauchen Sie Hilfe?',
          'Start a call': 'Anruf starten',
          'Message': 'Nachricht',
          'Send': 'Senden',
          'New call': 'Neuer Anruf',
          'End': 'Beenden',
          'End chat': 'Chat beenden',
          'Mute microphone': 'Mikrofon stummschalten',
          'Switch to text mode': 'Zum Textmodus wechseln',
          'Switch to voice mode': 'Zum Sprachmodus wechseln',
          'Switched to text mode': 'Zum Textmodus gewechselt',
          'Switched to voice mode': 'Zum Sprachmodus gewechselt',
          'Change language': 'Sprache ändern',
          'Collapse': 'Einklappen',
          'Expand': 'Ausklappen',
          'Copied!': 'Kopiert!',
          'Accept': 'Akzeptieren',
          'Cancel': 'Abbrechen',
          'End this chat?': 'Diesen Chat beenden?',
          'End this call?': 'Diesen Anruf beenden?',
          'End call': 'Anruf beenden',
          'Listening': 'Hört zu',
          'Talk to interrupt': 'Sprechen zum Unterbrechen',
          'Connecting': 'Verbinden ...',
          'Reconnecting...': 'Verbindung wird wiederhergestellt ...',
          'Chatting with AI Agent': 'Chat mit dem KI-Agenten',
          'Waiting for an available agent': 'Warte auf einen verfügbaren Mitarbeiter',
          'Send a message...': 'Nachricht senden ...',
          'Start a new conversation': 'Neues Gespräch starten',
          'You ended the conversation': 'Sie haben das Gespräch beendet',
          'The agent ended the conversation': 'Der Agent hat das Gespräch beendet',
          'An error occurred': 'Ein Fehler ist aufgetreten',
          'How was this conversation?': 'Wie war dieses Gespräch?',
          'Tell us more': 'Erzählen Sie uns mehr',
          'Thank you for your feedback!': 'Danke für Ihr Feedback!',
          'Submit': 'Absenden',
          'Go back': 'Zurück',
          'Copy': 'Kopieren',
          'Download': 'Herunterladen',
          'Agent is typing ...': 'Der Agent tippt ...',
          'Text message input': 'Texteingabe'
        };

        function translateWidget() {
          var root = widget.shadowRoot;
          if (!root) return;
          var lang = (document.documentElement.lang || '').toLowerCase();
          var path = window.location.pathname;
          var german = lang.indexOf('de') === 0 || path === '/de' || path.indexOf('/de/') === 0;
          if (!german) return;

          var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
          var node;
          while ((node = walker.nextNode())) {
            var raw = node.nodeValue;
            var key = raw.trim();
            if (widgetDe[key]) {
              var lead = raw.match(/^\s*/)[0];
              var trail = raw.match(/\s*$/)[0];
              node.nodeValue = lead + widgetDe[key] + trail;
            }
          }

          var attrs = ['placeholder', 'aria-label', 'title'];
          var els = root.querySelectorAll('[placeholder],[aria-label],[title]');
          for (var i = 0; i < els.length; i++) {
            for (var a = 0; a < attrs.length; a++) {
              var value = els[i].getAttribute(attrs[a]);
              if (value && widgetDe[value.trim()]) {
                els[i].setAttribute(attrs[a], widgetDe[value.trim()]);
              }
            }
          }
        }

        function forceHidePoweredBy() {
          var root = widget.shadowRoot;
          if (!root) return;

          if (!root.getElementById('sovran-hide-elevenlabs-powered')) {
            var style = document.createElement('style');
            style.id = 'sovran-hide-elevenlabs-powered';
            style.textContent = [
              'a[href*="elevenlabs.io/agents"]{display:none !important;}',
              'a[href*="elevenlabs.io/agents"] + *{display:none !important;}'
            ].join('');
            root.appendChild(style);
          }

          var links = root.querySelectorAll('a[href*="elevenlabs.io/agents"]');
          for (var i = 0; i < links.length; i++) {
            var parent = links[i].closest('p');
            if (parent && parent.parentNode) {
              parent.parentNode.removeChild(parent);
            } else if (links[i].parentNode) {
              links[i].parentNode.removeChild(links[i]);
            }
          }
        }

        function attachShadowObserver() {
          var root = widget.shadowRoot;
          if (!root || widget.__sovranShadowObserverBound) return;
          widget.__sovranShadowObserverBound = true;
          var shadowObserver = new MutationObserver(function () {
            forceHidePoweredBy();
            translateWidget();
          });
          shadowObserver.observe(root, { childList: true, subtree: true });
          var langObserver = new MutationObserver(translateWidget);
          langObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
        }

        forceHidePoweredBy();
        translateWidget();
        attachShadowObserver();
        setTimeout(function () { forceHidePoweredBy(); translateWidget(); }, 300);
        setTimeout(function () { forceHidePoweredBy(); translateWidget(); }, 1000);
        setTimeout(function () { forceHidePoweredBy(); translateWidget(); }, 2000);

        var rootWaiter = new MutationObserver(function () {
          forceHidePoweredBy();
          translateWidget();
        });
        rootWaiter.observe(widget, { childList: true, subtree: true });
        var retryCount = 0;
        var retryTimer = setInterval(function () {
          retryCount += 1;
          forceHidePoweredBy();
          translateWidget();
          attachShadowObserver();
          if (retryCount >= 20) clearInterval(retryTimer);
        }, 1000);

        widget.addEventListener('elevenlabs-convai:call', function (event) {
          if (!event || !event.detail || !event.detail.config) return;
          var existingTools = event.detail.config.clientTools || {};
          function navigateTool(args) {
            var destination = args && (args.destination || args.path || args.url);
            var target = normalizeDestination(destination);
            if (!target) return 'Invalid destination';

            if (!navigateWithinSpa(target)) {
              window.location.href = target;
            }
            return 'Successfully navigated to ' + target;
          }
          event.detail.config.clientTools = Object.assign({}, existingTools, {
            navigate_to_page: navigateTool,
            navigateToPage: navigateTool
          });
        });
      }

      function init() {
        var widget = document.querySelector('elevenlabs-convai');
        if (widget) bindTools(widget);
      }

      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
      } else {
        init();
      }
      setTimeout(init, 400);
      setTimeout(init, 1200);
    })();