<?php
/**
 * Template Name: Luminous Learning Portal Shell
 */
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?> class="light">
<head>
    <meta charset="<?php bloginfo('charset'); ?>"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>Luminous Learning Portal</title>
    
    <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
    <?php wp_head(); ?>

    <script id="tailwind-config">
        tailwind.config = {
            darkMode: "class",
            theme: {
                extend: {
                    "colors": {
                        "warm-orange": "#F9AD6D", "on-surface-variant": "#5a4136", "outline-variant": "#e2bfb0",
                        "on-secondary-container": "#007147", "on-primary-fixed": "#351000", "on-surface": "#191c1d",
                        "surface-container-highest": "#e1e3e4", "soft-lilac": "#F2F2FB", "on-tertiary-container": "#412457",
                        "on-error": "#ffffff", "tertiary": "#705287", "surface-container-lowest": "#ffffff",
                        "surface-container-high": "#e7e8e9", "on-primary-fixed-variant": "#7a3000", "error": "#ba1a1a",
                        "primary-fixed": "#ffdbcc", "on-tertiary": "#ffffff", "on-background": "#191c1d",
                        "inverse-surface": "#2e3132", "inverse-on-surface": "#f0f1f2", "surface-bright": "#f8f9fa",
                        "primary": "#a04100", "surface-container-low": "#f3f4f5", "on-secondary": "#ffffff",
                        "primary-fixed-dim": "#ffb693", "on-tertiary-fixed-variant": "#573a6e", "surface-variant": "#e1e3e4",
                        "background": "#f8f9fa", "alert-coral": "#EA7052", "surface-container": "#edeeef",
                        "secondary": "#006d43", "error-container": "#ffdad6", "tertiary-container": "#ae8cc6",
                        "surface": "#f8f9fa", "primary-container": "#ff6b00", "tertiary-fixed": "#f2daff",
                        "outline": "#8e7164", "on-primary-container": "#572000", "tertiary-fixed-dim": "#ddb9f6",
                        "on-error-container": "#93000a", "on-secondary-fixed-variant": "#005232", "on-secondary-fixed": "#002111",
                        "on-tertiary-fixed": "#290d3f", "secondary-container": "#75f8b3", "on-primary": "#ffffff",
                        "inverse-primary": "#ffb693", "surface-tint": "#a04100", "secondary-fixed-dim": "#59de9b",
                        "secondary-fixed": "#78fbb6", "surface-dim": "#d9dadb"
                    },
                    "borderRadius": { "DEFAULT": "0.25rem", "lg": "0.5rem", "xl": "0.75rem", "full": "9999px" },
                    "spacing": { "margin-desktop": "48px", "margin-mobile": "16px", "gutter": "24px", "base": "4px", "container-max-width": "1280px" },
                    "fontFamily": {
                        "headline-lg": ["Montserrat"], "display-lg": ["Montserrat"], "body-lg": ["Be Vietnam Pro"],
                        "label-sm": ["Be Vietnam Pro"], "label-lg": ["Be Vietnam Pro"], "body-md": ["Be Vietnam Pro"],
                        "headline-md": ["Montserrat"], "headline-lg-mobile": ["Montserrat"]
                    },
                    "fontSize": {
                        "headline-lg": ["32px", {"lineHeight": "40px", "fontWeight": "700"}],
                        "display-lg": ["48px", {"lineHeight": "56px", "letterSpacing": "-0.02em", "fontWeight": "700"}],
                        "body-lg": ["18px", {"lineHeight": "28px", "fontWeight": "400"}],
                        "label-sm": ["12px", {"lineHeight": "16px", "fontWeight": "500"}],
                        "label-lg": ["14px", {"lineHeight": "20px", "letterSpacing": "0.01em", "fontWeight": "600"}],
                        "body-md": ["16px", {"lineHeight": "24px", "fontWeight": "400"}],
                        "headline-md": ["24px", {"lineHeight": "32px", "fontWeight": "600"}],
                        "headline-lg-mobile": ["28px", {"lineHeight": "36px", "fontWeight": "700"}]
                    }
                },
            },
        }
    </script>
    <style>
        .material-symbols-outlined { font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24; }
        .class-card:hover .card-icon { transform: translateY(-4px) scale(1.1); }
        body { font-family: 'Be Vietnam Pro', sans-serif; background-color: #f8f9fa; }
        h1, h2, h3 { font-family: 'Montserrat', sans-serif; }
    </style>
</head>
<body class="text-on-background min-h-screen relative">

    <?php get_template_part('partials/topbar'); ?>
    
    <div class="flex pt-16 h-full min-h-screen">
        <?php get_template_part('partials/sidebar'); ?>
        
        <main id="portal-viewport-canvas" class="flex-1 lg:ml-64 p-6 md:p-margin-desktop bg-background pb-24 lg:pb-12 transition-all duration-200">
            </main>
    </div>

    <?php get_template_part('partials/mobile-nav'); ?>

    <div id="portal-overlay-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm transition-all duration-200 p-4">
    <div class="bg-white rounded-2xl w-full max-w-4xl shadow-2xl border border-outline-variant relative overflow-hidden transform transition-all duration-200" id="portal-modal-content">
        </div>
</div>

    <script>
        const wpAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";

        async function fetchViewMarkup(containerId, templateName) {
            try {
                const response = await fetch(`${wpAjaxUrl}?action=load_portal_view&view_name=${templateName}`);
                if (response.ok) {
                    document.getElementById(containerId).innerHTML = await response.text();
                    executeEmbeddedScripts(containerId);
                }
            } catch (err) {
                console.error("View resolution runtime exception:", err);
            }
        }
        
        // Map of sub-views to their parent sidebar nav ID
    const navParentMap = {
        'class-selection': 'nav-class-selection',
        'nursery-subject': 'nav-class-selection',
        'nursery-lesson': 'nav-class-selection',
        'subject-terms': 'nav-class-selection',      // Still highlights Curriculum
        'teacher-selection': 'nav-class-selection',  // Still highlights Curriculum
        'student-lesson-overview': 'nav-class-selection',
        'my-progress': 'nav-my-progress',
        'library': 'nav-library',
        'settings': 'nav-settings'
    };

        async function navigate(viewName, params = {}) {
    const viewport = document.getElementById('portal-viewport-canvas');
    viewport.style.opacity = '0.3';
    
    // 1. Build Query Parameters string dynamically from the params argument object
    const queryString = Object.keys(params)
        .map(key => `&${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('');

    // 2. Fetch view markup utilizing the global endpoint with the parameters appended
    try {
        const response = await fetch(`${wpAjaxUrl}?action=load_portal_view&view_name=${viewName}${queryString}`);
        if (response.ok) {
            document.getElementById('portal-viewport-canvas').innerHTML = await response.text();
            executeEmbeddedScripts('portal-viewport-canvas');
        } else {
            console.error("Failed to load view markup stream.");
        }
    } catch (err) {
        console.error("View resolution runtime exception:", err);
    }
    
    viewport.style.opacity = '1';
    
    // 3. Clear all sidebar active states
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('bg-primary-fixed', 'text-primary', 'font-bold', 'scale-[0.98]');
        item.classList.add('text-on-surface-variant', 'font-medium');
    });

    // 4. Find parent and apply active styling highlight indicators
    const parentId = navParentMap[viewName];
    const activeItem = document.getElementById(parentId);
    
    if (activeItem) {
        activeItem.classList.add('bg-primary-fixed', 'text-primary', 'font-bold', 'scale-[0.98]');
        activeItem.classList.remove('text-on-surface-variant', 'font-medium');
    }

    // 5. Update browser window tracking state hash safely
    window.location.hash = `/${viewName}`;
}

        // Inside page-portal-shell.php
async function openOverlay(overlayName, params = {}) {
    // Build query parameters safely
    const queryString = Object.keys(params)
        .map(key => `&${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('');

    await fetchViewMarkup('portal-modal-content', `${overlayName}${queryString}`);
    document.getElementById('portal-overlay-modal').classList.remove('hidden');
}

        function closeOverlay() {
            document.getElementById('portal-overlay-modal').classList.add('hidden');
            document.getElementById('portal-modal-content').innerHTML = '';
        }

        function executeEmbeddedScripts(containerId) {
            const scripts = document.getElementById(containerId).querySelectorAll("script");
            scripts.forEach(oldScript => {
                const newScript = document.createElement("script");
                Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
                newScript.appendChild(document.createTextNode(oldScript.innerHTML));
                oldScript.parentNode.replaceChild(newScript, oldScript);
            });
        }

        document.getElementById('portal-overlay-modal').addEventListener('click', function(e) {
            if (e.target === this) closeOverlay();
        });

        window.addEventListener('DOMContentLoaded', () => {
            // Automatically launch the dashboard on setup complete
            navigate('class-selection');
        });
    </script>
    <?php wp_footer(); ?>
</body>
</html>