<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Component List - Finite State Report</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>

    {% include '_design_system.html' %}

    <style>
        /* Report-specific overrides */
        .license-link {
            color: #007bff;
            text-decoration: none;
            font-size: 0.85em;
        }
        .license-link:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            {% if logo_path %}
            <div class="logo-container">
                <img src="{{ logo_path }}" alt="Company Logo" class="company-logo">
            </div>
            {% else %}
            <div class="logo-container">
                <img src="https://finitestate.io/hs-fs/hubfs/FS-Logo-Final-01.png?width=256&height=50&name=FS-Logo-Final-01.png"
                     alt="Finite State Logo" class="company-logo">
            </div>
            {% endif %}
            <h1>Component List</h1>
            <p class="subtitle">Software Component Inventory &amp; License Analysis</p>
        </div>

        <!-- Metadata -->
        <div class="metadata">
            <strong>Report:</strong> Component List |
            <strong>Generated:</strong> {{ generated_at | default('N/A') }}
            {% if metadata and metadata.start_date %} | <strong>Period:</strong> {{ metadata.start_date }} to {{ metadata.end_date }}{% endif %}
            {% if folder_path %} | <strong>Folder:</strong> {{ folder_path }}{% endif %}
            {% if project_filter %} | <strong>Project:</strong> {{ project_filter }}{% endif %}
            {% if metadata %} | <strong>Components:</strong> {{ metadata.transformed_count | default('N/A') }}{% endif %}
        </div>

        <!-- Filter Information -->
        {% if folder_path or project_filter %}
        <div class="chart-container">
            <h3>Applied Filter</h3>
            {% if folder_path %}<p><strong>Folder:</strong> {{ folder_path }}</p>{% endif %}
            {% if project_filter %}<p><strong>Project Filter:</strong> {{ project_filter }}</p>{% endif %}
            <p>Showing components for the specified scope only.</p>
        </div>
        {% endif %}

        {% if transform_result and transform_result.component_summary %}
        {% set summary = transform_result.component_summary %}

        <!-- KPI Cards -->
        <div class="kpi-row">
            <div class="kpi-card">
                <div class="kpi-title">Total Components</div>
                <div class="kpi-value">{{ summary.total_components }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-title">Unique Licenses</div>
                <div class="kpi-value">{{ summary.unique_licenses }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-title">No License</div>
                <div class="kpi-value" {% if summary.no_license_count > 0 %}style="color: #ef6c00;"{% endif %}>{{ summary.no_license_count }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-title">Policy Violations</div>
                <div class="kpi-value" {% if summary.violation_count > 0 %}style="color: #c62828;"{% endif %}>{{ summary.violation_count }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-title">Copyleft Components</div>
                <div class="kpi-value" {% if summary.copyleft_strong + summary.copyleft_weak > 0 %}style="color: #ef6c00;"{% endif %}>{{ summary.copyleft_strong + summary.copyleft_weak }}</div>
            </div>
        </div>

        <!-- Charts Row 1: License Distribution + Policy Status -->
        <div class="two-col">
            <div class="chart-container">
                <h2 class="chart-title">License Distribution</h2>
                <p class="chart-description">Top licenses by component count</p>
                <div class="chart-wrapper-tall">
                    <canvas id="licenseDistChart"></canvas>
                </div>
            </div>
            <div class="chart-container">
                <h2 class="chart-title">Policy Status</h2>
                <p class="chart-description">License policy compliance breakdown</p>
                <div class="chart-wrapper-tall">
                    <canvas id="policyChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Charts Row 2: Copyleft Classification + Source Type -->
        <div class="two-col">
            <div class="chart-container">
                <h2 class="chart-title">Copyleft Classification</h2>
                <p class="chart-description">License copyleft obligation breakdown</p>
                <div class="chart-wrapper-tall">
                    <canvas id="copyleftChart"></canvas>
                </div>
            </div>
            <div class="chart-container">
                <h2 class="chart-title">Source Type</h2>
                <p class="chart-description">How components were discovered</p>
                <div class="chart-wrapper-tall">
                    <canvas id="sourceChart"></canvas>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Data Table -->
        <div class="table-container">
            <h2>Component Inventory</h2>
            <p>Comprehensive software component inventory with license details</p>

            {% if data %}
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Component</th>
                        <th>Version</th>
                        <th>Type</th>
                        <th>Source</th>
                        <th>Declared License</th>
                        <th>Concluded License</th>
                        <th>Copyleft</th>
                        <th>Policy</th>
                        {% if folder_path %}<th>Folder</th>{% endif %}
                        <th>Project</th>
                        <th>Project Version</th>
                        <th>BOM Reference</th>
                        <th>Findings</th>
                        <th>Status</th>
                        <th>License URL</th>
                        <th>Release Date</th>
                    </tr>
                </thead>
                <tbody>
                    {% set current_project = namespace(value=None) %}
                    {% for row in data %}
                        {% if row['Project Name'] != current_project.value %}
                            {% set current_project.value = row['Project Name'] %}
                            <tr class="project-group-row">
                                <td colspan="{% if folder_path %}16{% else %}15{% endif %}">{{ row['Project Name'] }}</td>
                            </tr>
                        {% endif %}
                        <tr class="{% if loop.index > 100 %}hidden-row{% endif %}">
                            <td><strong>{{ row['Component'] }}</strong></td>
                            <td>{{ row['Version'] }}</td>
                            <td>
                                <span class="status-badge type-{{ row.get('Type', '') | lower | replace(' ', '-') | default('default') }}">
                                    {{ row['Type'] }}
                                </span>
                            </td>
                            <td>{{ row.get('Source', '') }}</td>
                            <td class="truncate" title="{{ row.get('Declared License', '') }}">
                                {{ row.get('Declared License', '') }}
                            </td>
                            <td class="truncate" title="{{ row.get('Concluded License', '') }}">
                                {% if row.get('Concluded License') %}
                                    <span class="status-badge status-CONFIRMED">{{ row['Concluded License'] }}</span>
                                {% endif %}
                            </td>
                            <td>
                                {% set copyleft = row.get('Copyleft Status', '') %}
                                {% if copyleft %}
                                    <span class="status-badge copyleft-{{ copyleft }}">
                                        {% if copyleft == 'STRONG_COPYLEFT' %}Strong
                                        {% elif copyleft == 'WEAK_COPYLEFT' %}Weak
                                        {% elif copyleft == 'PERMISSIVE' %}Permissive
                                        {% else %}{{ copyleft }}{% endif %}
                                    </span>
                                {% else %}
                                    <span style="color: #9e9e9e;">-</span>
                                {% endif %}
                            </td>
                            <td>
                                {% set policy = row.get('Policy Status', '') %}
                                {% if policy %}
                                    <span class="status-badge policy-{{ policy }}">{{ policy }}</span>
                                {% else %}
                                    <span style="color: #9e9e9e;">-</span>
                                {% endif %}
                            </td>
                            {% if folder_path %}<td>{{ row.get('Folder', '') }}</td>{% endif %}
                            <td>{{ row['Project Name'] }}</td>
                            <td>{{ row['Project Version'] }}</td>
                            <td class="truncate" title="{{ row.get('BOM Reference', '') }}">
                                <code style="font-size: 0.8em;">{{ row.get('BOM Reference', '') }}</code>
                            </td>
                            <td class="num">
                                {% if row.get('Findings', 0) > 0 %}
                                    <span class="severity-badge {% if row.get('Findings', 0) >= 10 %}severity-CRITICAL{% elif row.get('Findings', 0) >= 5 %}severity-HIGH{% else %}severity-MEDIUM{% endif %}">
                                        {{ row['Findings'] }}
                                    </span>
                                {% else %}
                                    <span style="color: #4caf50;">0</span>
                                {% endif %}
                            </td>
                            <td>
                                {% set cstatus = row.get('Component Status', 'N/A') %}
                                {% if cstatus and cstatus != 'N/A' %}
                                    <span class="status-badge status-{{ cstatus }}">{{ cstatus }}</span>
                                {% else %}
                                    <span style="color: #9e9e9e;">-</span>
                                {% endif %}
                            </td>
                            <td>
                                {% set lurl = row.get('License URL', '') %}
                                {% if lurl %}
                                    <a href="{{ lurl }}" target="_blank" class="license-link" title="{{ lurl }}">Link</a>
                                {% else %}
                                    <span style="color: #9e9e9e;">-</span>
                                {% endif %}
                            </td>
                            <td>{{ row.get('Release Date', '') if row.get('Release Date', '') else '-' }}</td>
                        </tr>
                    {% endfor %}
                    {% if data|length > 100 %}
                    <tr class="show-more-row">
                        <td colspan="{% if folder_path %}16{% else %}15{% endif %}">
                            <button class="show-more-btn" onclick="toggleAllRows()">
                                Show {{ data|length - 100 }} more rows...
                            </button>
                        </td>
                    </tr>
                    {% endif %}
                </tbody>
            </table>
            {% else %}
            <div class="empty-state">
                <p><strong>No components found</strong></p>
                <p>No software components match the current criteria.</p>
            </div>
            {% endif %}
        </div>

        <div class="footer">
            <p>Generated by <span class="finite-state-logo">Finite State</span> Reporting Kit</p>
        </div>
    </div>

    <script>
    // Toggle hidden rows
    function toggleAllRows() {
        const rows = document.querySelectorAll('.hidden-row');
        const btn = document.querySelector('.show-more-row');
        rows.forEach(r => r.classList.remove('hidden-row'));
        if (btn) btn.style.display = 'none';
    }

    document.addEventListener('DOMContentLoaded', function() {
        const POLICY_COLORS = {
            'PERMITTED': '#28a745',
            'WARNING': '#ffc107',
            'VIOLATION': '#dc3545'
        };

        const COPYLEFT_COLORS = {
            'Permissive': '#28a745',
            'Weak Copyleft': '#fd7e14',
            'Strong Copyleft': '#dc3545',
            'Unknown': '#6c757d'
        };

        // =============================================
        // 1. License Distribution (Horizontal Bar)
        // =============================================
        {% if transform_result and transform_result.component_summary and transform_result.component_summary.license_distribution is defined %}
        (function() {
            const ctx = document.getElementById('licenseDistChart');
            if (!ctx) return;
            {% set ld = transform_result.component_summary.license_distribution %}
            {% if ld is defined and ld|length > 0 %}
            const labels = [{% for row in ld %}{{ row.License | tojson }}{% if not loop.last %}, {% endif %}{% endfor %}];
            const values = [{% for row in ld %}{{ row.Count }}{% if not loop.last %}, {% endif %}{% endfor %}];

            new Chart(ctx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: '#4e79a7',
                        borderWidth: 0
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        datalabels: {
                            anchor: 'end',
                            align: 'right',
                            font: { weight: 'bold', size: 11 },
                            color: '#333',
                            formatter: function(v) { return v > 0 ? v : ''; }
                        }
                    },
                    scales: {
                        x: { title: { display: true, text: 'Component Count' }, grid: { color: 'rgba(0,0,0,0.06)' } },
                        y: { ticks: { font: { size: 11 } }, grid: { display: false } }
                    }
                },
                plugins: [ChartDataLabels]
            });
            {% endif %}
        })();
        {% endif %}

        // =============================================
        // 2. Policy Status (Doughnut)
        // =============================================
        {% if transform_result and transform_result.component_summary %}
        (function() {
            const ctx = document.getElementById('policyChart');
            if (!ctx) return;
            {% set s = transform_result.component_summary %}
            const labels = ['PERMITTED', 'WARNING', 'VIOLATION'];
            const values = [{{ s.permitted_count }}, {{ s.warning_count }}, {{ s.violation_count }}];
            const colors = [POLICY_COLORS.PERMITTED, POLICY_COLORS.WARNING, POLICY_COLORS.VIOLATION];

            // Only show if there's data
            if (values.reduce((a, b) => a + b, 0) === 0) return;

            new Chart(ctx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: colors,
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'right' },
                        datalabels: {
                            color: '#fff',
                            font: { weight: 'bold', size: 14 },
                            formatter: function(value, ctx) {
                                if (value === 0) return '';
                                const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
                                const pct = ((value / total) * 100).toFixed(1);
                                return value + '\n(' + pct + '%)';
                            }
                        }
                    }
                },
                plugins: [ChartDataLabels]
            });
        })();
        {% endif %}

        // =============================================
        // 3. Copyleft Classification (Doughnut)
        // =============================================
        {% if transform_result and transform_result.component_summary %}
        (function() {
            const ctx = document.getElementById('copyleftChart');
            if (!ctx) return;
            {% set s = transform_result.component_summary %}
            const labels = ['Permissive', 'Weak Copyleft', 'Strong Copyleft', 'Unknown'];
            const values = [{{ s.copyleft_permissive }}, {{ s.copyleft_weak }}, {{ s.copyleft_strong }}, {{ s.copyleft_unknown }}];
            const colors = [COPYLEFT_COLORS['Permissive'], COPYLEFT_COLORS['Weak Copyleft'], COPYLEFT_COLORS['Strong Copyleft'], COPYLEFT_COLORS['Unknown']];

            // Filter out zero values
            const filtered = labels.reduce((acc, label, i) => {
                if (values[i] > 0) {
                    acc.labels.push(label);
                    acc.values.push(values[i]);
                    acc.colors.push(colors[i]);
                }
                return acc;
            }, { labels: [], values: [], colors: [] });

            if (filtered.values.length === 0) return;

            new Chart(ctx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: filtered.labels,
                    datasets: [{
                        data: filtered.values,
                        backgroundColor: filtered.colors,
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'right' },
                        datalabels: {
                            color: '#fff',
                            font: { weight: 'bold', size: 14 },
                            formatter: function(value, ctx) {
                                if (value === 0) return '';
                                const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
                                const pct = ((value / total) * 100).toFixed(1);
                                return value + '\n(' + pct + '%)';
                            }
                        }
                    }
                },
                plugins: [ChartDataLabels]
            });
        })();
        {% endif %}

        // =============================================
        // 4. Source Type Breakdown (Bar)
        // =============================================
        {% if transform_result and transform_result.component_summary and transform_result.component_summary.source_distribution is defined %}
        (function() {
            const ctx = document.getElementById('sourceChart');
            if (!ctx) return;
            {% set sd = transform_result.component_summary.source_distribution %}
            {% if sd is defined and sd|length > 0 %}
            const labels = [{% for row in sd %}{{ row.Source | tojson }}{% if not loop.last %}, {% endif %}{% endfor %}];
            const values = [{% for row in sd %}{{ row.Count }}{% if not loop.last %}, {% endif %}{% endfor %}];

            const palette = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f', '#edc948', '#b07aa1'];

            new Chart(ctx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: labels.map((_, i) => palette[i % palette.length]),
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        datalabels: {
                            anchor: 'end',
                            align: 'top',
                            font: { weight: 'bold', size: 11 },
                            color: '#333',
                            formatter: function(v) { return v > 0 ? v : ''; }
                        }
                    },
                    scales: {
                        y: { title: { display: true, text: 'Component Count' }, grid: { color: 'rgba(0,0,0,0.06)' } },
                        x: { grid: { display: false } }
                    }
                },
                plugins: [ChartDataLabels]
            });
            {% endif %}
        })();
        {% endif %}
    });
    </script>
</body>
</html>
