<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Degree Analysis: {{degree_name}}</title>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --success-color: #4CAF50;
            --warning-color: #FF9800;
            --light-bg: #f8f9fa;
            --border-color: #dee2e6;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.5;
            color: #333;
            background-color: var(--light-bg);
            padding: 1.5rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 2rem;
        }

        h1 {
            color: var(--primary-color);
            border-bottom: 3px solid var(--secondary-color);
            padding-bottom: 0.5rem;
            margin-bottom: 1.5rem;
        }

        h2 {
            color: var(--primary-color);
            margin-top: 2rem;
            margin-bottom: 1rem;
            border-left: 4px solid var(--secondary-color);
            padding-left: 0.75rem;
        }

        h3 {
            color: var(--primary-color);
            margin-bottom: 0.5rem;
        }

        /* Header metadata */
        .metadata {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
            padding: 1rem;
            background: var(--light-bg);
            border-radius: 6px;
        }

        .metadata-item {
            display: flex;
            flex-direction: column;
        }

        .metadata-item .label {
            font-size: 0.75rem;
            color: #666;
            text-transform: uppercase;
        }

        .metadata-item .value {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
        }

        /* ── Collapsible report sections ─────────────────────────────────────
           Each major h2 lives inside <details class="report-section" open>
           with the heading rendered via <summary>. The native disclosure
           triangle is hidden in favour of a CSS rotating chevron, so the
           summary still looks like a regular section header. */
        details.report-section {
            margin: 0 0 1.5rem 0;
        }
        details.report-section > summary {
            cursor: pointer;
            user-select: none;
            list-style: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.25rem 0;
        }
        /* Hide the default <summary> disclosure marker on every engine. */
        details.report-section > summary::-webkit-details-marker {
            display: none;
        }
        details.report-section > summary::marker {
            display: none;
            content: "";
        }
        details.report-section > summary::before {
            content: "▸";
            display: inline-block;
            color: var(--secondary-color);
            font-size: 0.9em;
            transition: transform 0.15s ease-out;
        }
        details.report-section[open] > summary::before {
            transform: rotate(90deg);
        }
        details.report-section > summary > h2 {
            display: inline;
            margin: 0;
            border-bottom: none;
            padding-bottom: 0;
        }
        details.report-section > summary:hover > h2 {
            color: var(--secondary-color);
        }
        details.report-section > summary:focus-visible {
            outline: 2px solid var(--secondary-color);
            outline-offset: 4px;
            border-radius: 4px;
        }
        /* Print: drop the chevron + click affordance so the headings look
           like regular h2s. Forcing closed sections open in print requires
           JS (the browser's UA stylesheet hides non-summary children when
           [open] is absent); see the beforeprint handler in <script>. */
        @media print {
            details.report-section > summary::before {
                display: none;
            }
            details.report-section > summary {
                cursor: default;
            }
        }

        /* Statistics cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: var(--light-bg);
            border-radius: 6px;
            padding: 1rem;
            text-align: center;
            border: 1px solid var(--border-color);
        }

        .stat-card .label {
            font-size: 0.75rem;
            color: #666;
            text-transform: uppercase;
        }

        .stat-card .value {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .stat-card .detail {
            font-size: 0.8rem;
            color: #888;
        }

        /* Box plots */
        .box-plots-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }

        .box-plot-container {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 1rem;
        }

        .box-plot-container h3 {
            text-align: center;
            margin-bottom: 1rem;
        }

        .box-plot-container svg {
            display: block;
            margin: 0 auto;
            max-width: 100%;
            height: auto;
        }

        .box-plot-legend {
            display: flex;
            justify-content: center;
            gap: 1.5rem;
            margin-top: 0.5rem;
            font-size: 0.8rem;
            color: #666;
        }

        .legend-box {
            display: inline-block;
            width: 16px;
            height: 12px;
            background: #e3f2fd;
            border: 2px solid #1976d2;
            vertical-align: middle;
            margin-right: 4px;
        }

        .legend-median {
            display: inline-block;
            width: 16px;
            height: 3px;
            background: #d32f2f;
            vertical-align: middle;
            margin-right: 4px;
        }

        .legend-mean {
            display: inline-block;
            width: 10px;
            height: 10px;
            background: #4caf50;
            transform: rotate(45deg);
            vertical-align: middle;
            margin-right: 4px;
        }

        /* Course stats table */
        .metrics-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 2rem;
            font-size: 0.9rem;
        }

        .metrics-table th,
        .metrics-table td {
            padding: 0.5rem;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .metrics-table th {
            background: var(--primary-color);
            color: white;
            font-weight: 600;
        }

        .metrics-table th.sortable {
            cursor: pointer;
            user-select: none;
            position: relative;
            padding-right: 1.5rem;
        }

        .metrics-table th.sortable:hover {
            background: #3d5a73;
        }

        .metrics-table th.sortable::after {
            content: '⇅';
            position: absolute;
            right: 0.5rem;
            opacity: 0.5;
            font-size: 0.7rem;
        }

        .metrics-table th.sortable.asc::after {
            content: '↑';
            opacity: 1;
        }

        .metrics-table th.sortable.desc::after {
            content: '↓';
            opacity: 1;
        }

        .metrics-table tr.sub-header th {
            background: #455a64;
            font-size: 0.75rem;
            font-weight: normal;
        }

        .metrics-table tbody tr:hover {
            background: var(--light-bg);
        }

        .metrics-table tbody tr.major-course {
            background: #e3f2fd;
        }

        .metrics-table tbody tr.major-course:hover {
            background: #bbdefb;
        }

        .metrics-table td small {
            color: #666;
        }

        /* Course stats legend */
        .course-stats-legend {
            display: flex;
            gap: 1.5rem;
            margin-bottom: 0.75rem;
            font-size: 0.85rem;
            color: #666;
        }

        .course-stats-legend .legend-item {
            display: flex;
            align-items: center;
            gap: 0.4rem;
        }

        .course-stats-legend .legend-color-box {
            width: 16px;
            height: 16px;
            border-radius: 3px;
            border: 1px solid var(--border-color);
        }

        .course-stats-legend .legend-color-box.major {
            background: #e3f2fd;
        }

        .course-stats-legend .legend-color-box.non-major {
            background: white;
        }

        /* Selected plans */
        /* Per-plan panel body — stats flow left-to-right; term schedule
           is a grid of color-coded term cards. */
        .tab-panel .plan-overview {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            margin-bottom: 1.25rem;
        }
        .tab-panel .plan-overview .stat-card {
            flex: 1 1 140px;
            min-width: 120px;
        }

        .tab-panel .critical-path {
            background: linear-gradient(90deg, var(--light-bg), white);
            padding: 0.75rem;
            border-radius: 6px;
            font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
            font-size: 0.85rem;
            margin-bottom: 1.25rem;
        }

        .tab-panel .term-schedule h4 {
            margin: 1rem 0 0.5rem;
            color: var(--primary-color);
            font-size: 1rem;
        }

        .tab-panel .term-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 0.75rem;
            margin-bottom: 1.5rem;
        }

        .tab-panel .term-card {
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .tab-panel .term-card-header {
            background: var(--primary-color);
            color: #fff;
            padding: 0.4rem 0.75rem;
            font-weight: 600;
            font-size: 0.85rem;
            display: flex;
            justify-content: space-between;
            align-items: baseline;
        }
        .tab-panel .term-card-header .term-credits {
            font-weight: 400;
            opacity: 0.9;
            font-size: 0.78rem;
        }

        .tab-panel .term-courses {
            list-style: none;
            margin: 0;
            padding: 0.5rem 0.5rem 0.6rem;
            display: flex;
            flex-direction: column;
            gap: 0.3rem;
        }

        .tab-panel .term-course {
            display: grid;
            grid-template-columns: minmax(0, auto) 1fr auto;
            align-items: baseline;
            gap: 0.5rem;
            padding: 0.3rem 0.5rem;
            background: #fff;
            border-radius: 4px;
            border-left: 3px solid #b0b8c1; /* default — non-major / supporting */
            font-size: 0.82rem;
        }
        .tab-panel .term-course--major {
            border-left-color: var(--secondary-color);
            background: #eef5fb;
        }
        .tab-panel .term-course .course-id {
            font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
            font-size: 0.78rem;
            font-weight: 600;
            color: var(--primary-color);
        }
        .tab-panel .term-course .course-name {
            color: #555;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .tab-panel .term-course .course-credits {
            color: #777;
            font-size: 0.75rem;
            font-variant-numeric: tabular-nums;
        }
        .tab-panel .term-courses-legend {
            display: flex;
            gap: 1rem;
            font-size: 0.75rem;
            color: #666;
            margin: 0.25rem 0 0.75rem;
        }
        .tab-panel .term-courses-legend .legend-swatch {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 2px;
            margin-right: 0.3rem;
            vertical-align: middle;
        }
        .tab-panel .term-courses-legend .legend-swatch--major {
            background: var(--secondary-color);
        }
        .tab-panel .term-courses-legend .legend-swatch--other {
            background: #b0b8c1;
        }

        /* Curriculum graphs are rendered by VanillaJsRenderer with scoped .nu-graph CSS */

        /* Print styles */
        @media print {
            body {
                background: white;
                padding: 0;
            }
            .container {
                box-shadow: none;
                padding: 0;
            }
            .box-plot-container {
                break-inside: avoid;
            }
            .tab-panel {
                break-inside: avoid;
            }
            .term-card {
                break-inside: avoid;
            }
        }

        /* ── Tabbed plans section ─────────────────────────────────────────── */
        /* Scoped under .nu-plan-tabs to avoid colliding with the .nu-graph
           scope used by the curriculum graph fragments themselves. */
        .nu-plan-tabs {
            margin: 1.5rem 0;
        }
        .nu-plan-tabs .tab-strip {
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
            border-bottom: 2px solid #ddd;
            margin-bottom: 1rem;
        }
        .nu-plan-tabs .tab-btn {
            background: #f6f6f6;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 4px 4px 0 0;
            padding: 0.5rem 1rem;
            cursor: pointer;
            font-size: 0.9rem;
            color: #555;
            font-family: inherit;
            transition: background-color 0.15s, color 0.15s;
        }
        .nu-plan-tabs .tab-btn:hover:not(.tab-btn--active) {
            background: #eaeaea;
        }
        .nu-plan-tabs .tab-btn--active {
            background: #fff;
            color: #2c3e50;
            font-weight: 600;
            margin-bottom: -2px;
            border-bottom: 2px solid #fff;
        }
        .nu-plan-tabs .tab-btn:focus-visible {
            outline: 2px solid #3498db;
            outline-offset: 2px;
        }
        .nu-plan-tabs .tab-panel {
            display: none;
        }
        .nu-plan-tabs .tab-panel--active {
            display: block;
        }
        .nu-plan-tabs .plan-tabs-empty {
            color: #666;
            font-style: italic;
        }
        /* Print: collapse tabs into a flat list so every panel makes the page. */
        @media print {
            .nu-plan-tabs .tab-strip {
                display: none;
            }
            .nu-plan-tabs .tab-panel {
                display: block !important;
                page-break-inside: avoid;
                margin-bottom: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Degree Analysis: {{degree_name}}</h1>

        <div class="metadata">
            <div class="metadata-item">
                <span class="label">Institution</span>
                <span class="value">{{institution}}</span>
            </div>
            <div class="metadata-item">
                <span class="label">Degree Type</span>
                <span class="value">{{degree_type}}</span>
            </div>
            <div class="metadata-item">
                <span class="label">Degree ID</span>
                <span class="value">{{degree_id}}</span>
            </div>
            <div class="metadata-item">
                <span class="label">CIP Code</span>
                <span class="value">{{cip_code}}</span>
            </div>
            <div class="metadata-item">
                <span class="label">System Type</span>
                <span class="value">{{system_type}}</span>
            </div>
            <div class="metadata-item">
                <span class="label">Total Plans Analyzed</span>
                <span class="value">{{total_plans}}</span>
            </div>
        </div>

        <details class="report-section" open>
            <summary><h2>Degree Statistics</h2></summary>
            <div class="stats-grid">
                {{stats_section}}
            </div>
        </details>

        <details class="report-section" open>
            <summary><h2>Metric Distributions</h2></summary>
            <div class="box-plots-grid">
                {{box_plots}}
            </div>
        </details>

        <details class="report-section" open>
            <summary><h2>Per-Course Statistics</h2></summary>
            <div class="course-stats-legend">
                <span class="legend-item"><span class="legend-color-box major"></span> Major courses (sorted first by complexity)</span>
                <span class="legend-item"><span class="legend-color-box non-major"></span> Non-major courses (electives, gen-eds, supporting)</span>
            </div>
            {{course_stats_table}}
        </details>

        <details class="report-section" open>
            <summary><h2>Plans</h2></summary>
            {{plan_tabs_section}}
        </details>

        <footer style="margin-top: 2rem; text-align: center; font-size: 0.8rem; color: #666;">
            Generated by NuAnalytics Degree Analyzer
        </footer>
    </div>

    <script>
        // Major subject codes for highlighting and sorting
        const majorSubjects = {{major_subjects_json}};

        // Check if a course ID belongs to a major subject
        function isMajorCourse(courseId) {
            if (!majorSubjects || majorSubjects.length === 0) return false;
            for (const subj of majorSubjects) {
                if (courseId.startsWith(subj)) return true;
            }
            return false;
        }

        // Parse the metric value from "Med / Min / Max" format
        function parseMetricValue(text) {
            const parts = text.split('/').map(s => parseFloat(s.trim()));
            return parts[0] || 0; // Return median (first value)
        }

        // Sort table functionality
        document.addEventListener('DOMContentLoaded', function() {
            const table = document.getElementById('course-stats-table');
            if (!table) return;

            const headers = table.querySelectorAll('th.sortable');
            const tbody = table.querySelector('tbody');

            headers.forEach((header, colIdx) => {
                header.addEventListener('click', () => {
                    const rows = Array.from(tbody.querySelectorAll('tr'));
                    const isAsc = header.classList.contains('asc');

                    // Clear other sort indicators
                    headers.forEach(h => h.classList.remove('asc', 'desc'));

                    // Toggle sort direction
                    header.classList.add(isAsc ? 'desc' : 'asc');
                    const dir = isAsc ? -1 : 1;

                    rows.sort((a, b) => {
                        const aCell = a.cells[colIdx];
                        const bCell = b.cells[colIdx];
                        if (!aCell || !bCell) return 0;

                        let aVal, bVal;

                        // Column 0 is course ID (text sort with major priority)
                        if (colIdx === 0) {
                            const aId = aCell.querySelector('strong')?.textContent || aCell.textContent;
                            const bId = bCell.querySelector('strong')?.textContent || bCell.textContent;
                            const aMajor = isMajorCourse(aId);
                            const bMajor = isMajorCourse(bId);

                            // Major courses always first when sorting ascending
                            if (aMajor !== bMajor) {
                                return (aMajor ? -1 : 1) * dir;
                            }
                            return aId.localeCompare(bId) * dir;
                        }

                        // Column 1 is Plans count (numeric)
                        if (colIdx === 1) {
                            aVal = parseInt(aCell.textContent) || 0;
                            bVal = parseInt(bCell.textContent) || 0;
                        } else {
                            // Columns 2-5 are "Med / Min / Max" format, sort by median
                            aVal = parseMetricValue(aCell.textContent);
                            bVal = parseMetricValue(bCell.textContent);
                        }

                        return (aVal - bVal) * dir;
                    });

                    // Re-append sorted rows
                    rows.forEach(row => tbody.appendChild(row));
                });
            });

            // Initial sort: major courses first by complexity descending
            const complexityHeader = headers[2]; // Complexity column
            if (complexityHeader) {
                complexityHeader.click(); // Ascending first
                complexityHeader.click(); // Then descending
            }

        });

        // ── Print: force every collapsible section open ───────────────────
        // The browser's UA stylesheet hides non-summary children when
        // <details> lacks the [open] attribute, so a user who collapses a
        // section before printing would otherwise miss it in the output.
        // Save+restore the original state around beforeprint/afterprint.
        (function () {
            const sections = document.querySelectorAll('details.report-section');
            let savedState = null;
            window.addEventListener('beforeprint', function () {
                savedState = Array.from(sections).map(function (d) { return d.open; });
                sections.forEach(function (d) { d.open = true; });
            });
            window.addEventListener('afterprint', function () {
                if (!savedState) return;
                sections.forEach(function (d, i) { d.open = savedState[i]; });
                savedState = null;
            });
        }());

        // ── Plan tab switcher ──────────────────────────────────────────────
        // The graph fragments are rendered eagerly into hidden panels. The
        // shared nuGraphs library handles initial layout on DOMContentLoaded;
        // we trigger nuGraphs.drawAll() again on tab switch so a previously
        // hidden panel's SVG (which the library sized to 0) gets re-laid-out
        // at the freshly-revealed container width.
        document.addEventListener('DOMContentLoaded', function () {
            const tabsRoot = document.querySelector('.nu-plan-tabs');
            if (!tabsRoot) return;
            const buttons = tabsRoot.querySelectorAll('.tab-btn');
            const panels = tabsRoot.querySelectorAll('.tab-panel');
            buttons.forEach(function (btn) {
                btn.addEventListener('click', function () {
                    const target = btn.getAttribute('data-tab-target');
                    buttons.forEach(function (b) {
                        const active = b === btn;
                        b.classList.toggle('tab-btn--active', active);
                        b.setAttribute('aria-selected', active ? 'true' : 'false');
                    });
                    panels.forEach(function (p) {
                        const active = p.getAttribute('data-tab-id') === target;
                        p.classList.toggle('tab-panel--active', active);
                    });
                    if (window.nuGraphs && typeof window.nuGraphs.drawAll === 'function') {
                        window.nuGraphs.drawAll();
                    }
                });
            });
        });
        // Graph JS is embedded inline within each plan's HTML block by VanillaJsRenderer.
    </script>
</body>
</html>
