/*!
 * 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
 */
/**
 * use_cases_rewrite.js - Die-aware link rewriting for use-cases pages (Shibuya theme)
 *
 * This script provides the handler function for :func: role links in use-cases pages.
 * Unlike how-to-use pages (which use doxygengroup with die-specific group IDs),
 * use-cases pages use :func: role which the Python post-processing has rewritten
 * from generic _CPPv anchors to die-specific group IDs.
 *
 * Problem:
 * Links have been rewritten to 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:
 * - href pointing to default die's group ID
 * - data-cpp-id with the original _CPPv identifier
 * - data-all-group-ids with comma-separated list of all die variants
 * - onclick="return handleUseCaseLinkClick(event, this);"
 *
 * 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('[use_cases_rewrite] Could not access sphinx-tabs die preference from sessionStorage:', e);
    }
    return null;
}

/**
 * Extract die name from a Doxygen group ID.
 * Group IDs follow pattern: STM32<die>_group__... (e.g., STM32C562xx_group__FLASH__...)
 *
 * @param {string} groupId - The Doxygen group 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__/i);
    return match ? match[1] : null;
}

/**
 * Find the group ID for the preferred die from data-all-group-ids attribute.
 *
 * @param {HTMLElement} link - The link element with data-all-group-ids attribute
 * @param {string} preferredDie - Target die name (e.g., "STM32C5A3xx")
 * @returns {string|null} Group ID for the preferred die, or null if not found
 */
function findGroupIdForDie(link, preferredDie) {
    const allGroupIds = link.getAttribute('data-all-group-ids');
    if (!allGroupIds) {
        return null;
    }

    const groupIdList = allGroupIds.split(',');
    for (const groupId of groupIdList) {
        const die = extractDieFromGroupId(groupId);
        if (die === preferredDie) {
            return groupId;
        }
    }

    return null;
}

/**
 * Handle click on :func: role links with die-aware rewriting.
 * This function is called from onclick attributes added by Python post-processing.
 *
 * Logic:
 * - Same page navigation: Allow normal navigation (use-cases 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 handleUseCaseLinkClick(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 (links have been rewritten by Python post-processing)
    if (!/^STM32[A-Z0-9]+xx_group__/i.test(anchor)) {
        console.debug('[use_cases_rewrite] Link is not a group ID:', anchor);
        return true; // Not a group 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 - use-cases pages don't have tabs, so just navigate normally
        // (the current page has no die variants to rewrite for)
        // this is unexpected as :func: links point to API pages
        console.warn('[use_cases_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).
    // This ensures die-subset functions (e.g. SAES-only) show the popup even on first click.
    const preferredDie = getPreferredDieFromStorage() ?? link.getAttribute('data-default-die');

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

    // Find the group ID for the preferred die from data-all-group-ids
    const rewrittenAnchor = findGroupIdForDie(link, preferredDie);
    if (!rewrittenAnchor) {
        // Function not available for preferred die - show popup and don't navigate
        event.preventDefault();
        const functionName = link.textContent.trim();
        console.warn('[use_cases_rewrite] No group ID found for preferred die:', {
            preferredDie: preferredDie,
            function: functionName,
            availableGroupIds: link.getAttribute('data-all-group-ids')
        });

        alert(`Note: This function may not be available for ${preferredDie}.\n\nThe function "${functionName}" was not found for your selected die variant.`);
        return false; // Don't navigate
    }

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

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

    // Navigate to the rewritten URL
    window.location.href = fullNewUrl;

    return false;
}
