(function() {
  function isElementorEditor() {
    return window.elementor !== undefined ||
      window.parent.elementor !== undefined ||
      document.body.classList.contains('elementor-editor-active') ||
      window.location.href.includes('elementor-preview');
  }

  function getDocumentContext() {
    if (window.self !== window.top) return document;
    const previewIframe = document.querySelector('iframe[name="elementor-preview"]');
    if (previewIframe && previewIframe.contentDocument) return previewIframe.contentDocument;
    return document;
  }

  window.applySilicaBorder = function(forceUpdate = false) {
    const doc = getDocumentContext();
    
    const allElementsWithBorder = doc.querySelectorAll("*");
    Array.from(allElementsWithBorder).forEach((element) => {
      if (element._silicaBorderApplied && !element.classList.contains("silicaGlass-yes")) {
        if (element._silicaBorderCleanup) {
          element._silicaBorderCleanup();
        }
        element._silicaBorderApplied = false;
      }
    });

    doc.querySelectorAll('.silicaGlass-yes').forEach(element => {
      if (element._silicaBorderApplied && !forceUpdate) return;
      
      try {
        element._silicaBorderApplied = true;
        
        let borderOverlay = element.querySelector('.silica-border-overlay');
        if (!borderOverlay) {
          borderOverlay = document.createElement('div');
          borderOverlay.className = 'silica-border-overlay';
          
          Object.assign(borderOverlay.style, {
            content: '""',
            position: 'absolute',
            inset: '0',
            top: '0',
            left: '0',
            right: '0',
            bottom: '0',
            zIndex: '1',
            borderRadius: 'inherit',
            padding: '2px',
            WebkitMask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
            mask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
            WebkitMaskComposite: 'xor',
            maskComposite: 'exclude',
            pointerEvents: 'none'
          });
          
          element.insertBefore(borderOverlay, element.firstChild);
        }

        const updateBorderGradient = () => {
          const rect = element.getBoundingClientRect();
          const width = rect.width;
          const height = rect.height;
          
          const userAngle = -45;
          const intensity = 0.3;
          
          let adjustedAngle;
          if (width > 0 && height > 0) {
            const userAngleRad = (userAngle * Math.PI) / 180;
            const aspectRatio = height / width;
            const adjustedAngleRad = Math.atan(Math.tan(userAngleRad) * aspectRatio);
            adjustedAngle = (adjustedAngleRad * 180) / Math.PI;
          } else {
            adjustedAngle = userAngle;
          }
          
          const calculatedAngle = adjustedAngle + 180;
          borderOverlay.style.background = `linear-gradient(${calculatedAngle}deg, rgba(255, 255, 255, ${intensity}) 0%, transparent 50%, rgba(255, 255, 255, ${intensity}) 100%)`;
        };

        element._silicaBorderCleanup = () => {
          if (element._resizeObserver) {
            element._resizeObserver.disconnect();
            element._resizeObserver = null;
          }
          if (borderOverlay && borderOverlay.parentNode) {
            borderOverlay.parentNode.removeChild(borderOverlay);
          }
          element._silicaBorderApplied = false;
        };

        updateBorderGradient();

        if (window.ResizeObserver) {
          if (element._resizeObserver) {
            element._resizeObserver.disconnect();
          }
          element._resizeObserver = new ResizeObserver(() => {
            updateBorderGradient();
          });
          element._resizeObserver.observe(element);
        }

      } catch (error) {
        console.error('Silica border effect error:', error);
      }
    });
  };

  const silicaObserver = new MutationObserver(function(mutations) {
    let shouldReapply = false;
    mutations.forEach(function(mutation) {
      if (mutation.type === "attributes" && mutation.attributeName === "class") {
        shouldReapply = true;
      }
      if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
        shouldReapply = true;
      }
    });
    if (shouldReapply) {
      setTimeout(() => {
        if (typeof window.applySilicaBorder === 'function') {
          window.applySilicaBorder();
        }
      }, 50);
    }
  });

  window.applySilicaBorder();

  silicaObserver.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['class']
  });

  jQuery(function($){
    function runSilicaBorder(){
      if (typeof window.applySilicaBorder === 'function') {
        window.applySilicaBorder();
      }
    }
    
    runSilicaBorder();
    
    if (window.elementorFrontend && window.elementorFrontend.hooks) {
      window.elementorFrontend.hooks.addAction('frontend/element_ready/global', runSilicaBorder);
    }
    if (window.elementorFrontend) {
      window.elementorFrontend.on('element:after:render', runSilicaBorder);
      window.elementorFrontend.on('preview:loaded', runSilicaBorder);
    }
    
    if (isElementorEditor()) {
      setInterval(() => {
        if (typeof window.applySilicaBorder === 'function') {
          window.applySilicaBorder();
        }
      }, 100);
      
      if (window.elementor) {
        window.elementor.on('panel:init', runSilicaBorder);
      }
    }
  });
})();
