/*!
 * Copyright (c) 2024-2026 STMicroelectronics.
 * All rights reserved.
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 * SPDX-License-Identifier: SLA0044
 */
/**
 * how_to_use_rewrite.js - Die-aware link rewriting for how-to-use pages (Shibuya theme)
 *
 * This script provides the handler function for doxygengroup directive links in how-to-use pages.
 * Unlike use-cases pages (which use :func: role with _CPPv anchors), how-to-use pages
 * use doxygengroup which generates direct die-specific group IDs.
 *
 * Problem:
 * Links always point to breathe_default_project die (e.g., #STM32C562xx_group__...),
 * but user may have selected a different die in sphinx-tabs on other pages.
 *
 * Solution:
 * The Python post-processing (html.py) adds onclick="return handleDoxygroupLinkClick(event, this);"
 * to each doxygengroup link. This function:
 * 1. Extracts die name from target anchor (e.g., "STM32C562xx" from "#STM32C562xx_group__...")
 * 2. Gets user's preferred die from sessionStorage (set by sphinx-tabs when they select a tab)
 * 3. Checks if link navigates to same page (unexpected) or different page (normal case)
 * 4. For different page: if dies match or no preference, navigates normally
 * 5. For different page: if dies don't match, rewrites anchor to use preferred die before navigating
 *
 * Note: The user's die preference is stored in sessionStorage by sphinx-tabs extension
 * when they click on any sphinx-tabs button across the documentation.
 *
 * Note: If the rewritten anchor doesn't exist on the target page, the page will load
 * but the anchor won't scroll. We may detect this after page load (not implemented).
 *
 * Added by STMicroelectronics.
 */

/**
 * Get the user's preferred die from sphinx-tabs sessionStorage.
 * Sphinx-tabs stores the last selected tab's name attribute in sessionStorage.
 * The name attribute is base64-encoded die name (e.g., "U1RNMzJDNTYyeHg=" for "STM32C562xx").
 *
 * @returns {string|null} Preferred die name (e.g., "STM32C562xx") or null if not set
 */
function getPreferredDieFromStorage() {
    try {
        // sphinx-tabs stores the name attribute (base64-encoded die name)
        const encodedDie = sessionStorage.getItem('sphinx-tabs-last-selected');
        if (encodedDie) {
            // Decode base64 to get die name
            const decodedDie = atob(encodedDie);
            // Validate die name format: STM32<series><variant>xx
            const diePattern = /^STM32[A-Z0-9]+xx$/i;
            if (diePattern.test(decodedDie)) {
                return decodedDie;
            }
        }
    } catch (e) {
        // sessionStorage might not be available (privacy mode, etc.) or base64 decode failed
        console.warn('Could not access sphinx-tabs die preference from sessionStorage:', e);
    }
    return null;
}

/**
 * Extract die name from a Doxygen group ID or type ID.
 * Group IDs follow pattern: STM32<die>_group__... (e.g., STM32C562xx_group__FLASH__...)
 * Type IDs follow pattern: STM32<die>_struct/union/typedef... (e.g., STM32C562xx_structhal__uart__config__t)
 *
 * @param {string} groupId - The Doxygen group ID or type ID
 * @returns {string|null} Die name (e.g., "STM32C562xx") or null if pattern doesn't match
 */
function extractDieFromGroupId(groupId) {
    const match = groupId.match(/^(STM32[A-Z0-9]+xx)_(group__|struct|union|typedef)/i);
    return match ? match[1] : null;
}

/**
 * Rewrite a group/type anchor to use a different die.
 *
 * @param {string} originalAnchor - Original anchor (e.g., "STM32C562xx_group__FLASH__..." or "STM32C562xx_structhal__uart__config__t")
 * @param {string} newDie - Target die name (e.g., "STM32C5A3xx")
 * @returns {string} Rewritten anchor with new die
 */
function rewriteAnchorForDie(originalAnchor, newDie) {
    // Replace the die prefix in the group/type ID
    // Pattern: STM32<die>_(group__|struct|union|typedef)<suffix>
    return originalAnchor.replace(/^STM32[A-Z0-9]+xx_(group__|struct|union|typedef)/i, newDie + '_$1');
}

/**
 * Handle click on doxygengroup links with die-aware rewriting.
 * This function is called from onclick attributes added by Python post-processing.
 *
 * Logic:
 * - Same page navigation: Allow normal navigation (how-to-use pages don't have tabs)
 * - Different page navigation: Rewrite anchor to match user's preferred die if needed
 *
 * @param {Event} event - The click event
 * @param {HTMLElement} link - The link element that was clicked
 * @returns {boolean} False to prevent default navigation if we're handling it, true otherwise
 */
function handleDoxygroupLinkClick(event, link) {
    const href = link.getAttribute('href');

    if (!href || !href.includes('#')) {
        return true; // Let browser handle normally
    }

    const parts = href.split('#');
    const targetFile = parts[0];
    const anchor = parts[1];

    // Check if it's a group ID or type ID (struct/union/typedef)
    // Pattern matches: STM32<die>_(group__|struct|union|typedef)
    if (!/^STM32[A-Z0-9]+xx_(group__|struct|union|typedef)/i.test(anchor)) {
        console.debug('[how_to_use_rewrite] Link is not a doxygengroup or type ID:', anchor);
        return true; // Not a group/type ID, let browser handle
    }

    // Build full URL to check if we're navigating to same page or different page
    const fullUrl = new URL(href, window.location.href).href;
    const targetUrl = new URL(fullUrl);
    const currentUrl = new URL(window.location.href);

    if (targetUrl.pathname === currentUrl.pathname) {
        // Same page - how-to-use pages don't have tabs, so just navigate normally
        // (the current page has no die variants to rewrite for)
        // this is unexpected as doxygroup links point to API pages
        console.warn('[how_to_use_rewrite] Navigating to same page, no rewrite needed.');
        return true;
    }

    // Different page - check if we need to rewrite before navigating
    const originalDie = extractDieFromGroupId(anchor);
    // Fall back to data-default-die when no tab has been selected yet (fresh session).
    const preferredDie = getPreferredDieFromStorage() ?? link.getAttribute('data-default-die');

    if (!preferredDie || !originalDie || preferredDie === originalDie) {
        // No preference or dies match - navigate to original URL
        console.debug('[how_to_use_rewrite] No rewrite needed, navigating normally.');
        return true;
    }

    // Rewrite anchor for preferred die before navigation
    event.preventDefault();
    const rewrittenAnchor = rewriteAnchorForDie(anchor, preferredDie);
    const newHref = targetFile + '#' + rewrittenAnchor;
    const fullNewUrl = new URL(newHref, window.location.href).href;

    console.debug('[how_to_use_rewrite] Rewriting link:', {
        original: href,
        rewritten: newHref,
        originalDie: originalDie,
        targetDie: preferredDie
    });

    // Navigate to the rewritten URL
    // Note: If the function doesn't exist for the target die, the page will load
    // but the anchor won't scroll. We may detect this after page load.
    window.location.href = fullNewUrl;

    return false;
}
