/**
 * Prism Line Numbers Plugin
 * Adds line numbers to code blocks
 */
(function() {
    if (typeof Prism === 'undefined') {
        return;
    }

    /**
     * Returns the number of lines in the code
     */
    function getLines(text) {
        if (!text) return 0;
        return text.split('\n').length;
    }

    /**
     * Resizes line numbers based on content
     */
    function resizeLineNumbers(element) {
        var codeElement = element.querySelector('code');
        var lineNumbersWrapper = element.querySelector('.line-numbers-rows');
        
        if (!codeElement || !lineNumbersWrapper) {
            return;
        }

        var lines = getLines(codeElement.textContent);
        var lineHeight = parseFloat(getComputedStyle(codeElement).lineHeight);
        
        // Clear existing spans
        lineNumbersWrapper.innerHTML = '';
        
        // Add new spans for each line
        for (var i = 0; i < lines; i++) {
            var span = document.createElement('span');
            lineNumbersWrapper.appendChild(span);
        }
    }

    // Hook into Prism's complete event
    Prism.hooks.add('complete', function(env) {
        var pre = env.element.parentNode;
        var clsReg = /\s*\bline-numbers\b\s*/;
        
        if (
            !pre || !/pre/i.test(pre.nodeName) ||
            !clsReg.test(pre.className)
        ) {
            return;
        }

        // Remove existing line numbers if any
        var existingLineNumbers = pre.querySelector('.line-numbers-rows');
        if (existingLineNumbers) {
            existingLineNumbers.remove();
        }

        var linesNum = getLines(env.code);
        var lineNumbersWrapper = document.createElement('span');
        lineNumbersWrapper.className = 'line-numbers-rows';
        lineNumbersWrapper.setAttribute('aria-hidden', 'true');

        for (var i = 0; i < linesNum; i++) {
            var span = document.createElement('span');
            lineNumbersWrapper.appendChild(span);
        }

        if (pre.hasAttribute('data-start')) {
            pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1);
        }

        env.element.appendChild(lineNumbersWrapper);
        resizeLineNumbers(pre);
        
        // Also add line-numbers class to pre if not present
        if (!clsReg.test(pre.className)) {
            pre.className += ' line-numbers';
        }
    });

    // Handle window resize
    var resizeTimeout;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            var elements = document.querySelectorAll('pre.line-numbers');
            Array.prototype.forEach.call(elements, resizeLineNumbers);
        }, 100);
    });

    // Export for manual use
    window.PrismLineNumbers = {
        resize: resizeLineNumbers,
        getLines: getLines
    };
})();