/**
 * Adds the class "pmb-page-ref" onto all hyperlinks to posts/things that are actually in the current project,
 * and a span named "pmb-footnote", with the value of the hyperlink to all the links to external content.
 * @param external_link_policy string can be 'footnote', 'leave', 'remove'
 * @param internal_link_policy string can be 'parens' "(see page 12)", 'footnote' "[1]...See page 12", 'leave'
 * (leaves hyperlink to the page), 'remove' (removes the hyperlink altogether)
 * @param internal_footnote_text string
 * @param external_footnote_text string\
 * @global string pmb_pro.site_url
 */
function pmb_replace_internal_links_with_page_refs_and_footnotes(external_link_policy, internal_link_policy, external_footnote_text, internal_footnote_text)
{
    if(typeof(internal_footnote_text) === 'undefined' || internal_footnote_text === null){
        internal_footnote_text = 'See page %s';
    }
    var position_of_s = internal_footnote_text.search('%s');
    var pre_internal_footnote = internal_footnote_text.substr(0,position_of_s );
    var post_internal_footnote = internal_footnote_text.substr(position_of_s + 2);

    if(typeof(external_footnote_text) === 'undefined' || internal_footnote_text === null){
        external_footnote_text = 'See %s';
    }
    var position_of_s = external_footnote_text.search('%s');
    var pre_external_footnote = external_footnote_text.substr(0,position_of_s );
    var post_external_footnote = external_footnote_text.substr(position_of_s + 2);

    // epub-generator.js's pmb_replace_internal_links_with_epub_file_links has similar logic
    _pmb_for_each_hyperlink(
        // internal hyperlinks
        function(a, id_url, id_selector){
            switch(internal_link_policy){
                case 'parens':
                    a.addClass('pmb-page-ref');
                    a.attr('href',id_url);
                    break;
                case 'footnote':
                    // only add the footnote if the link isn't just the URL spelled out.
                    href = _pmb_get_href_from_a(a)
                    if( href !== a.html().trim()) {
                        a.attr('href',id_url);
                        a.after('<span class="pmb-footnote">' + pre_internal_footnote  + '<a class="pmb-page-num" href="' + id_url + '"></a>' + post_internal_footnote + '</span>');
                    }
                    break;
                case 'leave':
                    a.attr('href',id_url);
                    break;
                case 'remove':
                    a.contents().unwrap();
                    break;
                // otherwise, leave alone
            }
        },
        // external hyperlinks
        function(a){
            var href = _pmb_get_href_from_a(a);
            switch(external_link_policy){
                case 'footnote':
                    // only add the footnote if the link isn't just the URL spelled out.
                    var link_text = a.html().trim();
                    var matches = [href, href.replace('https://',''), href.replace('http://',''), href.replace('//',''), href.replace('mailto:','')];
                    if(matches.indexOf(link_text) === -1){
                        a.after('<span class="pmb-footnote">' + pre_external_footnote  + href + post_external_footnote + '</span>');
                        a.attr('href',href);
                    }
                    break;
                case 'remove':
                    a.contents().unwrap();
                    break;
                case 'leave':
                    a.attr('href', href);
            }
        }
    );
}

/**
 * Creates a table of contents from the content generated by the shortcode pmb_toc
 * @constructor
 * @param callback item_renderer_callback if provided, used to render each item in the TOC. Passed in arguments: title_text, href_id, depth, height, matter_class (all strings)
 */
function PmbToc(item_renderer_callback){
    this.item_renderer_callback = item_renderer_callback || null;
    /**
     * Search for PMB titles in the selector at the specified depth, and return them
     * @param jquery_obj
     * @param depth_to_look_for
     */
    this.find_articles_of_depth = function(selection, depth){
        return jQuery(selection ).find( ' .pmb-depth-' + depth);
    }

    this.create_toc_for_depth = function(selection, depth){
        var articles = this.find_articles_of_depth(selection, depth);
        var _this = this;
        articles.each(function(index,element){
            // find its title
            var selection = jQuery(element);
            var title_element = jQuery(element).find('.pmb-title');
            var id = selection.attr('id');
            // if it's a PMB-core section, like title page or TOC, don't show it.
            if(id.indexOf('/pmb-') !== -1){
                return;
            }
            var depth = parseInt(selection.attr('data-depth'));
            var height = parseInt(selection.attr('data-height'));
            if(selection.hasClass('pmb-front_matter_article')){
                var matter_class = 'pmb-toc-front';
            } else if(selection.hasClass('pmb-back_matter_article')){
                var matter_class = 'pmb-toc-back';
            } else {
                var matter_class = 'pmb-toc-main';
            }
            var title_text = title_element.html();
            if(title_text){
                if(_this.item_renderer_callback){
                    var html = _this.item_renderer_callback(title_text, id, depth, height, matter_class, selection);
                } else {
                    var html = '<li class="pmb-toc-item pmb-toc-depth-' + depth + ' pmb-toc-height-' + height + ' '  + matter_class + '"><a href="#' + id + '">' + title_text + '</a></li>';
                }
                jQuery('#pmb-toc-list').append(html);
            }
            // find its children
            _this.create_toc_for_depth(selection.siblings('div'),depth + 1);
        });
    }
    this.create_toc_for_depth('.pmb-print-page', 0);
}

/**
 * To be used by Design Developers as an optional item_renderer_callback for the Pmbtoc function.
 *
 * @example
 * // Use render_toc_with_thumbnails like this:
 * new Pmbtoc(render_toc_with_thumbnails);
 *
 * // The above will render the Pmbtoc item like this: 
 * <li class="pmb-toc-item pmb-toc-depth-0 pmb-toc-height-0 pmb-toc-main">
 *   <div class="pmb-toc-thumb" style="background-image: url('https://www.example.com/wp-content/uploads/2026/03/my_featured_image.jpg');"></div>
 *   <a href="#my-post-title" class="pmb-toc-link">My Post Title</a>
 * </li>
 * @param {string} title_text The title of the article.
 * @param {string} id The id of the article. 
 * @param {number} depth The depth of the item, 0 = h1 etc. 
 * @param {number} height The data height of the article.
 * @param {string} matter_class The class of the type of matter of the article
 * @param {HTMLElement} selection The article. 
 * @returns {string} The OuterHTML of the <li /> TOC list item. 
 */
function render_toc_with_thumbnails(title_text, id, depth, height, matter_class, selection) {
    // Create the TOC list item.
    const toc_list_item = jQuery("<li />", {
        class: `pmb-toc-item pmb-toc-depth-${depth} pmb-toc-height-${height} ${matter_class}`,
    });

    // Create the article link to display in the TOC.
    const toc_link = jQuery("<a />", {
        href: `#${id}`,
        class: "pmb-toc-link",
        text: title_text,
    });

    // Get the Featured Image Source.
    const featured_image_source = selection
        .find(".pmb-featured-image")
        .attr("src");

    const first_image_source = selection.find("figure img").attr("src");

    // Attach the featured image if it exists.
    if (featured_image_source) {
        // Create the thumbnail for the TOC item using the featured image.
        const toc_thumbnail = jQuery("<div />", {
            class: "pmb-toc-thumb",
        }).css({
            "background-image": `url('${featured_image_source}')`, // image URL
        });

        // Attach the thumbnail to the list item.
        toc_list_item.append(toc_thumbnail);
    } else if (first_image_source) {
        // Create the thumbnail for the TOC item using the first image in the article.
        const toc_thumbnail = jQuery("<div />", {
            class: "pmb-toc-thumb",
        }).css({
            "background-image": `url('${first_image_source}')`, // image URL
        });

        // Attach the thumbnail to the list item.
        toc_list_item.append(toc_thumbnail);
    } else {
        // Create a spacer so that the Article Title is horizontally in line with others. 
        const toc_spacer = jQuery("<div />", {
            class: "pmb-toc-spacer",
        });

        // Attach the spacer to the list item.
        toc_list_item.append(toc_spacer);
    }

    toc_list_item.append(toc_link);
    
    // Return the list item as an HTML string.
    return toc_list_item.prop("outerHTML");
}

/**
 * Whatever content we need to fix in a way that only applies to PDFs
 */
function pmb_pdf_plugin_fixups(){
    // On any Elementor rows, use the CSS columns and count the number of column DIVs
    jQuery('.elementor-row, .elementor-container').each(function(){
        var jqe_row = jQuery(this);
        var columns = jqe_row.children('.elementor-column').length;
        if(columns){
            jqe_row.css('columns', columns.toString());
        }
    });
}