<?php
// --- 1. DATU BĀZES SAVIENOJUMS UN DATU AGREGĀCIJA ---
// VERSIJA 11: Atjaunota pazudusī funkcija _get_most_common_symbol

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Ceļš uz datubāzi 'nace' apakšmapē
$db_file = __DIR__ . '/nace/katalogs.sqlite';
$pdo = null;
$nodes = [];
$counts = [];
$data_for_js = [];

// === SĀKUMS: ATJAUNOTĀ FUNKCIJA ===
function _get_most_common_symbol($symbols) {
    if (empty($symbols)) {
        return 'n';
    }
    $filtered = array_filter($symbols, function($s) { return $s !== 'n'; });
    if (empty($filtered)) {
        return 'n';
    }
    $counts = array_count_values($filtered);
    arsort($counts);
    return key($counts);
}
// === BEIGAS: ATJAUNOTĀ FUNKCIJA ===

try {
    if (!file_exists($db_file)) {
        die("Kļūda: Datubāzes fails netika atrasts: $db_file. Lūdzu, palaidiet atjaunināto `prepare_db.py` skriptu.");
    }
    
    $pdo = new PDO('sqlite:' . $db_file);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $stmt_nodes = $pdo->query("SELECT code, name, parent_code, level, health_string FROM nace ORDER BY code");
    $nodes_data = $stmt_nodes->fetchAll();
    
    if (empty($nodes_data)) {
        die("Kļūda: nace tabula ('nace') datubāzē ir tukša.");
    }
    
    foreach ($nodes_data as $row) {
        if ($row['code'] === 'UNDEFINED') continue;
        $nodes[$row['code']] = [
            'code' => $row['code'],
            'name' => $row['name'],
            'parent_code' => $row['parent_code'] ?: null,
            'level' => $row['level'] ?: 9,
            'description' => $row['name'],
            'health_string' => $row['health_string'] ?: 'nnnnnnnnnn',
            'children' => [],
            'company_count' => 0, 'total_turnover' => 0, 'total_employees' => 0,
            'total_profit' => 0, 'total_net_payroll' => 0, 'total_employees_for_salary' => 0
        ];
    }

    $stmt_counts = $pdo->query("
        SELECT 
            nace_code_np, 
            COUNT(*) as count, SUM(turnover) as total_turnover, SUM(employees) as total_employees,
            SUM(profit) as total_profit, SUM(avg_net_salary * employees) as total_net_payroll,
            SUM(CASE WHEN avg_net_salary IS NOT NULL THEN employees ELSE 0 END) as total_employees_for_salary
        FROM companies 
        WHERE employees > 0 OR turnover > 0 OR profit != 0
        GROUP BY nace_code_np
    ");
    while ($row = $stmt_counts->fetch()) {
        $counts[$row['nace_code_np']] = $row;
    }
    
    $stmt_undefined_counts = $pdo->query("
        SELECT 
            COUNT(*) as count, SUM(turnover) as total_turnover, SUM(employees) as total_employees,
            SUM(profit) as total_profit, SUM(avg_net_salary * employees) as total_net_payroll,
            SUM(CASE WHEN avg_net_salary IS NOT NULL THEN employees ELSE 0 END) as total_employees_for_salary,
            (SELECT health_string FROM nace WHERE code = 'UNDEFINED' LIMIT 1) as health_string
        FROM companies 
        WHERE nace_code_np = 'UNDEFINED' AND (employees > 0 OR turnover > 0 OR profit != 0)
    ");
    
    $undefined_data = $stmt_undefined_counts->fetch();
    if ($undefined_data) {
        $counts['UNDEFINED'] = $undefined_data;
    } else {
        $counts['UNDEFINED'] = [
            'count' => 0, 'total_turnover' => 0, 'total_employees' => 0,
            'total_profit' => 0, 'total_net_payroll' => 0, 'total_employees_for_salary' => 0,
            'health_string' => 'nnnnnnnnnn'
        ];
    }

    $tree = [];
    foreach ($nodes as $code => &$node) {
        $parent_code = $node['parent_code'];
        if ($parent_code && isset($nodes[$parent_code])) {
            $nodes[$parent_code]['children'][] = &$node;
        } elseif (!$parent_code) {
            $tree[] = &$node;
        }
    }
    unset($node);

    $counted_nodes = [];
    $calculate_counts = function(&$node) use (&$calculate_counts, $counts, &$counted_nodes) {
        if (isset($counted_nodes[$node['code']])) return $node;
        
        $code_np = str_replace('.', '', $node['code']);
        $direct_data = $counts[$code_np] ?? [
            'count' => 0, 'total_turnover' => 0, 'total_employees' => 0,
            'total_profit' => 0, 'total_net_payroll' => 0, 'total_employees_for_salary' => 0
        ];
        
        $node['company_count'] = $direct_data['count'];
        $node['total_turnover'] = $direct_data['total_turnover'];
        $node['total_employees'] = $direct_data['total_employees'];
        $node['total_profit'] = $direct_data['total_profit'];
        $node['total_net_payroll'] = $direct_data['total_net_payroll'];
        $node['total_employees_for_salary'] = $direct_data['total_employees_for_salary'];

        if (!empty($node['children'])) {
            $child_health_strings = [];
            foreach ($node['children'] as &$child_node) {
                $child_data = $calculate_counts($child_node);
                $node['company_count'] += $child_data['company_count'];
                $node['total_turnover'] += $child_data['total_turnover'];
                $node['total_employees'] += $child_data['total_employees'];
                $node['total_profit'] += $child_data['total_profit'];
                $node['total_net_payroll'] += $child_data['total_net_payroll'];
                $node['total_employees_for_salary'] += $child_data['total_employees_for_salary'];
                $child_health_strings[] = $child_data['health_string'];
            }
            if (!empty($child_health_strings)) {
                $aggregated_health_string = "";
                for ($i = 0; $i < 10; $i++) {
                    $symbols_at_pos = [];
                    foreach ($child_health_strings as $hs) {
                        if (isset($hs[$i])) $symbols_at_pos[] = $hs[$i];
                    }
                    $aggregated_health_string .= _get_most_common_symbol($symbols_at_pos);
                }
                $node['health_string'] = $aggregated_health_string;
            }
        }
        $counted_nodes[$node['code']] = true;
        return $node;
    };

    foreach ($tree as &$root_node) {
        $calculate_counts($root_node);
    }
    unset($root_node);

    foreach ($nodes as $code => $node) {
        $avg_net_salary_category = 0;
        if ($node['total_employees_for_salary'] > 0) {
            $avg_net_salary_category = $node['total_net_payroll'] / $node['total_employees_for_salary'];
        }
        $data_for_js[] = [
            'Kods' => $node['code'], 'Nosaukums' => $node['name'], 'Vecāka kods' => $node['parent_code'],
            'Līmenis' => $node['level'], 'Apraksts' => $node['description'], 'VeselibasVirkne' => $node['health_string'],
            'UznemumuSkaits' => $node['company_count'], 'KopApgrozijums' => $node['total_turnover'],
            'KopDarbinieki' => $node['total_employees'], 'KopPela' => $node['total_profit'], 'VidejaNetoAlga' => $avg_net_salary_category
        ];
    }
    
    $ud_data = $counts['UNDEFINED'] ?? [];
    $ud_avg_salary = 0;
    
    $ud_total_employees_for_salary = $ud_data['total_employees_for_salary'] ?? 0;
    $ud_total_net_payroll = $ud_data['total_net_payroll'] ?? 0;
    
    if ($ud_total_employees_for_salary > 0) {
        $ud_avg_salary = $ud_total_net_payroll / $ud_total_employees_for_salary;
    }
    
    $data_for_js[] = [
        'Kods' => 'UNDEFINED', 'Nosaukums' => 'Uzņēmumi, kuriem nav norādīts nace kods vai tas nav atrasts reģistros.',
        'Vecāka kods' => null, 'Līmenis' => 1, 'Apraksts' => 'Uzņēmumi, kuriem nav norādīts nace kods vai tas nav atrasts reģistros.',
        'VeselibasVirkne' => $ud_data['health_string'] ?? 'nnnnnnnnnn', 
        'UznemumuSkaits' => $ud_data['count'] ?? 0,
        'KopApgrozijums' => $ud_data['total_turnover'] ?? 0, 
        'KopDarbinieki' => $ud_data['total_employees'] ?? 0,
        'KopPela' => $ud_data['total_profit'] ?? 0, 
        'VidejaNetoAlga' => $ud_avg_salary
    ];

} catch (Exception $e) {
    die("Kļūda datu sagatavošanā: " . $e->getMessage());
}

?>
<!DOCTYPE html>
<html lang="lv">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Latvijas Nozaru Pārskats</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script type="text/javascript" src="https://www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js" charset="UTF-8"></script>
    <script type="text/javascript" charset="UTF-8">
    document.addEventListener('DOMContentLoaded', function () {
    cookieconsent.run({"notice_banner_type":"headline","consent_type":"express","palette":"light","language":"lv","page_load_consent_levels":["strictly-necessary","functionality","tracking","targeting"],"notice_banner_reject_button_hide":false,"preferences_center_close_button_hide":false,"page_refresh_confirmation_buttons":false,"website_name":"saraksts.lv"});
    });
    </script>
    <noscript>Free cookie consent management tool by <a href="https://www.termsfeed.com/">TermsFeed Generator</a></noscript>

    <script type="text/plain" data-cookie-consent="tracking" async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxx"></script>
    <script type="text/plain" data-cookie-consent="tracking">
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-xxxxxxxxx');
    </script>
    
    <style>
      /* === SĀKUMS: PIEVIENOTIE HEADER STILI === */
      :root {
          --color-surface: #ffffff;
          --color-border: #e5e7eb;
          --color-logo: #6366f1;
          --color-primary: #4f46e5;
          --color-primary-hover: #4338ca;
          /* Šīs ir mainīgās vērtības no _variables.css, kas nepieciešamas tikai galvenei */
      }

      .main-header {
          background-color: var(--color-surface);
          border-bottom: 1px solid var(--color-border);
          padding: 5px 20px;
          width: 100%;
          box-sizing: border-box;
          height: 35px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          /* Apvienoti stili no _layout.css un nozare.php, lai saglabātu fiksēto pozīciju */
          position: fixed; 
          top: 0; 
          z-index: 1000;
          max-width: 1881px; 
          left: 50%; 
          transform: translateX(-50%);
      }

      .header-container { 
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 100%;
          width: 100%;
          max-width: 1320px; 
          margin: 0 auto;
      }

      .logo a {
          display: flex;
          align-items: center;
          text-decoration: none;
          color: var(--color-logo);
      }

      .logo-icon {
          font-size: 1.1rem;
          margin-right: 8px;
      }

      .logo-text {
          font-size: 1rem; 
          font-weight: 700;
          letter-spacing: -0.5px;
      }

      .main-nav ul {
          margin: 0;
          padding: 0;
          list-style: none;
          display: flex;
          align-items: center;
          gap: 22px; 
      }

      .main-nav a {
          text-decoration: none;
          color: inherit;
      }

      .nav-button {
          background: var(--color-primary); 
          color: white;
          font-family: inherit;
          padding: 0.27em 0.58em;
          font-weight: 900;
          font-size: 14px;
          border: 1px solid var(--color-primary-hover);
          border-radius: 0.32em;
          box-shadow: 0.05em 0.05em var(--color-primary-hover);
          cursor: pointer;
          transition: transform 0.1s ease, box-shadow 0.1s ease;
      }

      .nav-button:hover {
          transform: translate(-0.02em, -0.02em);
          box-shadow: 0.07em 0.07em var(--color-primary-hover);
      }

      .nav-button:active {
          transform: translate(0.02em, 0.02em);
          box-shadow: 0.02em 0.02em var(--color-primary-hover);
      }
      /* === BEIGAS: PIEVIENOTIE HEADER STILI === */
    
      * { box-sizing: border-box; }
      
      html {
          background-color: #f0f0f0; 
      }

      body { 
          margin: 0 auto; 
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; 
          padding-top: 35px; /* <-- LABOTS NO 75px uz 35px, lai atbilstu .main-header augstumam */
          background-color: #f9f9f9; 
          color: #333; 
          max-width: 1881px; 
          min-width: 320px; 
      }
      
      /* === SĀKUMS: IZŅEMTS KONFLIKTĒJOŠAIS STILS === */
      /* Oriģinālais 'header' stils tika izņemts, jo tagad tiek izmantots '.main-header' */
      /* === BEIGAS: IZŅEMTS KONFLIKTĒJOŠAIS STILS === */

      main { padding: 20px; }
      
      /* Virsraksts, kas tagad ir iekš main */
      main h1 {
          margin-top: 0; /* Noņemam lieku atstarpi augšpusē */
      }
      
      #breadcrumbs { margin-bottom: 20px; font-size: 16px; color: #555; padding: 10px; background-color: #fff; border: 1px solid #ddd; border-radius: 8px; }
      #breadcrumbs a { color: #007bff; text-decoration: none; } #breadcrumbs a:hover { text-decoration: underline; }
      #breadcrumbs span.current-page { color: #333; font-weight: bold; }
      #breadcrumbs .separator { margin: 0 8px; color: #888; }
      
      .gallery { 
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(390px, 1fr));
          gap: 20px;
          margin-bottom: 20px;
      }
      
      .industry-card { 
          background-color: #fff; 
          border: 1px solid #ddd; 
          border-radius: 8px; 
          box-shadow: 0 4px 8px rgba(0,0,0,0.08); 
          transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out; 
          display: flex; 
          min-width: 320px; 
      }

      .industry-card:hover { transform: translateY(-5px); box-shadow: 0 8px 16px rgba(0,0,0,0.2); }
      .main-card-content { width: 340px; border-right: 1px solid #eee; cursor: pointer; }
      .industry-header { position: relative; height: 200px; }
      .industry-header img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px 0 0 0; }
      .description { position: absolute; bottom: 0; left: 0; right: 0; background-color: rgba(0, 0, 0, 0.5); color: white; padding: 10px; margin: 0; font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; max-height: 3.2em; }
      .card-badge { position: absolute; top: 10px; right: 10px; background-color: #e53e3e; color: white; border-radius: 50%; padding: 4px 8px; font-size: 14px; font-weight: bold; z-index: 10; border: 2px solid white; box-shadow: 0 0 5px rgba(0,0,0,0.5); min-width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; }
      .card-body { display: flex; align-items: center; justify-content: space-between; margin-top: 15px; border-top: 1px solid #eee; padding: 15px; }
      
      .industry-data { 
          width: auto; 
          display: grid;
          grid-template-columns: auto 1fr; 
          column-gap: 8px;
          row-gap: 10px;
          align-items: center;
      }
      .data-item-label {
          font-size: 14px;
          font-weight: 500; 
          color: #007bff; /* ZILĀ KRĀSA */
          text-align: right;
          white-space: nowrap;
      }
      .data-item-value {
          font-size: 14px;
          font-weight: 600; 
          color: #007bff; /* ZILĀ KRĀSA */
          text-align: left;
      }

      .financial-indicators-side { flex-shrink: 0; margin-left: 15px; cursor: help; }
      .neon-grid-container { width: 60px; height: 60px; border-radius: 8px; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); gap: 4px; padding: 5px; transition: box-shadow 0.3s ease-in-out, background-color 0.3s ease-in-out, filter 0.2s ease-in-out; box-sizing: border-box; border: 1px solid #ddd; background-color: rgba(0,0,0,0.02); }
      .financial-indicators-side:hover .neon-grid-container, .company-table .neon-grid-container:hover { filter: brightness(150%); }
      .neon-grid-container.frame-g { background-color: rgba(76, 175, 80, 0.1); border-color: #4CAF50; box-shadow: 0 0 8px #4CAF50, 0 0 12px #4CAF50, inset 0 0 5px rgba(76, 175, 80, 0.5); }
      .neon-grid-container.frame-o { background-color: rgba(255, 152, 0, 0.1); border-color: #FF9800; box-shadow: 0 0 8px #FF9800, 0 0 12px #FF9800, inset 0 0 5px rgba(255, 152, 0, 0.5); }
      .neon-grid-container.frame-r { background-color: rgba(244, 67, 54, 0.1); border-color: #F44336; box-shadow: 0 0 8px #F44336, 0 0 12px #F44336, inset 0 0 5px rgba(244, 67, 54, 0.5); }
      .neon-grid-container.frame-b { background-color: rgba(33, 150, 243, 0.1); border-color: #2196F3; box-shadow: 0 0 8px #2196F3, 0 0 12px #2196F3, inset 0 0 5px rgba(33, 150, 243, 0.5); }
      .led-wrapper { display: flex; align-items: center; justify-content: center; }
      .led { width: 12px; height: 12px; border-radius: 50%; background-color: #ddd; transition: background-color 0.3s, box-shadow 0.3s; }
      .led.g { background-color: #4CAF50; box-shadow: 0 0 5px #4CAF50; } .led.o { background-color: #FF9800; box-shadow: 0 0 5px #FF9800; }
      .led.r { background-color: #F44336; box-shadow: 0 0 5px #F44336; } .led.b { background-color: #2196F3; box-shadow: 0 0 5px #2196F3; }
      .subcategory-preview-pane { width: 70px; display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 10px 0; background-color: #fcfcfc; border-radius: 0 8px 8px 0; }
      .sub-preview-item { position: relative; }
      .sub-preview-img { width: 50px; height: 50px; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; background-color: #f0f0f0; }
      .sub-preview-badge { position: absolute; top: -5px; right: -5px; background-color: #e53e3e; color: white; border-radius: 50%; font-size: 10px; font-weight: bold; padding: 2px 4px; z-index: 10; border: 1px solid white; min-width: 18px; height: 18px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; }
      .sub-preview-more { font-size: 14px; color: #888; font-weight: bold; padding-top: 5px; }
      #company-display { background-color: #fff; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); width: 100%; overflow: hidden; }
      #company-display h2 { margin-top: 0; color: #2d3748; padding: 20px 20px 0 20px; }
      
      .table-responsive-wrapper { overflow-x: auto; }
      
      .company-table { 
          width: 100%; 
          border-collapse: collapse; 
      }
      
      .company-table th, .company-table td { 
          border-bottom: 1px solid #e2e8f0; 
          padding: 12px 20px; 
          text-align: left; 
          white-space: nowrap; 
          vertical-align: middle;
      }
      
      /* Pirmā kolonna (Nosaukums) */
      .company-table th:first-child,
      .company-table td:first-child {
          width: 450px; 
          white-space: normal;
          vertical-align: top;
      }
      
      /* Otrā kolonna (Lokācija) */
      .company-table th:nth-child(2),
      .company-table td:nth-child(2) {
          width: 200px;
          white-space: normal; 
      }

      .company-name-block {
          display: flex;
          flex-direction: column;
          gap: 2px;
      }
      .company-name {
          font-weight: 600;
          font-size: 15px;
          color: #2d3748;
      }
      .company-regcode {
          font-size: 13px;
          color: #555;
      }
      .company-regcode a {
          color: #007bff;
          text-decoration: none;
      }
      .company-regcode a:hover {
          text-decoration: underline;
      }

      .company-table th { background-color: #f7fafc; font-weight: 600; }
      .company-table tr:last-child td { border-bottom: none; }
      
      .company-table td:nth-child(3), 
      .company-table td:nth-child(5),
      .company-table td:nth-child(6) { 
          text-align: right; 
      }
      
      .company-table td:nth-child(4), 
      .company-table td:nth-child(7) { 
          text-align: center; 
      }

      .no-data { color: #718096; padding: 20px; }
      .company-table th.sortable { cursor: pointer; position: relative; padding-right: 25px; }
      .company-table th.sortable .sort-arrows { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column; opacity: 0.3; }
      .company-table th.sortable .arrow-up { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #2d3748; margin-bottom: 2px; }
      .company-table th.sortable .arrow-down { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #2d3748; }
      .company-table th.sortable.sorted-asc .sort-arrows, .company-table th.sortable.sorted-desc .sort-arrows { opacity: 1; }
      .company-table th.sortable.sorted-asc .arrow-up { opacity: 1; } .company-table th.sortable.sorted-asc .arrow-down { opacity: 0.3; }
      .company-table th.sortable.sorted-desc .arrow-down { opacity: 1; } .company-table th.sortable.sorted-desc .arrow-up { opacity: 0.3; }
      .company-table .neon-grid-container { width: 30px; height: 30px; gap: 2px; padding: 3px; margin: 0 auto; cursor: help; }
      .company-table .led { width: 6px; height: 6px; }
      
      .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); z-index: 2000; display: none; align-items: center; justify-content: center; }
      .modal-content { background-color: #fff; padding: 20px 30px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); position: relative; max-width: 90%; width: 680px; }
      .modal-close { position: absolute; top: 10px; right: 15px; font-size: 28px; font-weight: bold; color: #aaa; cursor: pointer; }
      .modal-close:hover { color: #333; }
      .modal-header h2 { margin-top: 0; color: #333; }
      .explanation-container { display: flex; align-items: flex-start; gap: 30px; margin-top: 10px; }
      .explanation-grid-wrapper { text-align: center; }
      #explanation-grid-dynamic { width: 120px; height: 120px; gap: 8px; padding: 10px; }
      #explanation-grid-dynamic .led { width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 14px; text-shadow: 0 0 2px rgba(0,0,0,0.5); }
      .label-frame { margin-top: 10px; font-size: 14px; color: #555; font-weight: bold; }
      .explanation-text { display: flex; flex-direction: column; flex: 1; }
      .color-legend { list-style: none; padding-left: 0; margin: 10px 0 0 0; text-align: left;}
      .color-legend li { margin-bottom: 5px; font-size: 14px; }
      .explanation-list { list-style-type: none; padding-left: 0; margin-left: 0; column-count: 2; column-gap: 20px; }
      .explanation-list li { margin-bottom: 6px; font-size: 13px; font-weight: 500;}
      .explanation-list li b { font-weight: bold; }
      .explanation-list li.color-b { color: #2196F3; }
      .explanation-list li.color-g { color: #4CAF50; }
      .explanation-list li.color-o { color: #FF9800; }
      .explanation-list li.color-r { color: #F44336; }
      .explanation-list li.color-n { color: #333; }
      .led-sample { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 8px; vertical-align: middle; border: 1px solid #ccc; }


      @media (max-width: 767px) {
          
          .company-table thead {
              display: none;
          }

          .company-table, 
          .company-table tbody, 
          .company-table tr, 
          .company-table td {
              display: block;
              width: 100% !important; 
          }

          .company-table tr {
              margin-bottom: 15px;
              border: 1px solid #ddd;
              border-radius: 8px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.05);
              overflow: hidden; 
          }

          .company-table td {
              border-bottom: 1px solid #eee; 
              padding-left: 50%; 
              position: relative;
              text-align: right !important; 
              white-space: normal; 
              min-height: 40px; 
              display: flex;
              align-items: center;
              justify-content: flex-end; 
          }

          .company-table tr:last-child td:last-child {
              border-bottom: none; 
          }

          .company-table td:before {
              content: attr(data-label); 
              position: absolute;
              left: 15px;
              width: calc(50% - 30px); 
              font-weight: bold;
              text-align: left;
              white-space: normal;
              color: #333;
              font-size: 13px;
          }

          .company-table td:first-child {
              padding-left: 15px; 
              text-align: left !important;
              background-color: #f9f9f9; 
              vertical-align: middle;
          }
          .company-table td:first-child:before {
              display: none; 
          }
          
          .company-table td[data-label="Lokācija"] {
               vertical-align: middle;
          }
          .company-table td[data-label="Lokācija"]:before {
               align-self: center;
          }

          .company-table td[data-label="Stāvoklis"] {
              justify-content: center; 
          }
          .company-table td[data-label="Stāvoklis"]:before {
              align-self: center; 
          }
          .company-table .neon-grid-container {
              margin: 0; 
          }

          .explanation-list {
              column-count: 1;
          }
      }
    </style>
</head>
<body>
    <?php include $_SERVER['DOCUMENT_ROOT'] . '/header.php'; ?>
  
    <main>
    <h1>Nozaru Pārskats</h1>
    
    <nav id="breadcrumbs" aria-label="breadcrumb"></nav>
    <div class="gallery"></div>
    <div id="company-display" class="company-list" style="display: none;"></div>
  </main>
  
  <div id="grid-explanation-modal" class="modal-overlay">
      <div class="modal-content">
          <span class="modal-close">&times;</span>
          <div class="modal-header"><h2>Finanšu veselības režģa skaidrojums</h2></div>
          <div class="modal-body">
              <div class="explanation-container">
                  <div class="explanation-grid-wrapper">
                      <div id="explanation-grid-dynamic" class="neon-grid-container"></div>
                      <div class="label-frame">&uarr; 10 </div>
                      <ul class="color-legend">
                          <li><span class="led-sample" style="background-color: #2196F3;"></span><b>Zils:</b> Pārmērīgi</li>
                          <li><span class="led-sample" style="background-color: #4CAF50;"></span><b>Zaļš:</b> Labi</li>
                          <li><span class="led-sample" style="background-color: #FF9800;"></span><b>Oranžs:</b> Vidēji</li>
                          <li><span class="led-sample" style="background-color: #F44336;"></span><b>Sarkans:</b> Slikti</li>
                          <li><span class="led-sample" style="background-color: #ddd;"></span><b>Pelēks:</b> Nav datu</li>
                      </ul>
                  </div>
                  <div class="explanation-text">
                      <ol class="explanation-list"></ol>
                  </div>
              </div>
          </div>
      </div>
  </div>

  <div style="text-align: center; padding: 20px;">
      <a href="#" id="open_preferences_center">Mainīt sīkdatņu iestatījumus</a>
  </div>
  <script>
    
    // PHP kods augšpusē tagad kļūdas gadījumā atgriezīs 'null' vai datus
    const naceData = <?php echo json_encode($data_for_js, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE); ?>;
    
    // Droša 'if' pārbaude, kas neizraisīs kļūdu, ja 'naceData' ir 'null'
    if (!naceData || !Array.isArray(naceData) || naceData.length === 0) {
        
         // Pārbaudām, vai pamatstruktūra joprojām pastāv, pirms mēģinām to pārrakstīt
         if (document.body) {
            document.body.innerHTML = "<h1>Kļūda: Nevarēja ielādēt datus no PHP.</h1><p>Iespējamais iemesls: PHP kļūda servera pusē (piem., nevar nolasīt .sqlite failu) vai datubāze ir tukša. Lūdzu, pārbaudiet 'View Page Source' (Skatīt lapas pirmkodu), lai redzētu PHP kļūdas paziņojumu.</p>";
         }
         
         // Pārtraucam tālāku skripta izpildi, lai tas nemēģinātu atrast elementus, kas vairs neeksistē
         throw new Error("Datu ielāde no PHP neizdevās. Skripts tiek apturēts.");
    }

    // Ja skripts nonāk līdz šejienei, tas nozīmē, ka 'naceData' ir veiksmīgi ielādēti
    // un pārējais kods var droši darboties.

    const gallery = document.querySelector('.gallery');
    const companyDisplay = document.getElementById('company-display');
    const breadcrumbsContainer = document.getElementById('breadcrumbs'); 
    let currentCategory = null;
    let currentCompaniesData = [];
    let currentSortKey = 'employees';
    let currentSortDir = 'desc';

    const symbolToClass = { 'r': 'r', 'o': 'o', 'g': 'g', 'b': 'b', 'n': '' };

    function generateNeonGridHtml(healthString, isExplanation = false) {
        if (!healthString || healthString.length !== 10) healthString = 'nnnnnnnnnn';
        
        let ledSymbols = healthString.slice(0, 9).split('');
        let frameSymbol = healthString.slice(9, 10);

        if (isExplanation) {
             ledSymbols = ledSymbols.map((symbol, index) => {
                const indicatorNum = index + 1;
                if (indicatorNum > 2 && symbol === 'b') {
                    return 'g';
                }
                return symbol;
            });
            if (frameSymbol === 'b') {
                frameSymbol = 'g';
            }
        }

        const frameClassLetter = symbolToClass[frameSymbol] || '';
        const frameClass = frameClassLetter ? `frame-${frameClassLetter}` : '';
        
        let ledsHtml = '';
        ledSymbols.forEach((symbol, index) => {
            const ledClass = symbolToClass[symbol] || '';
            const number = isExplanation ? `${index + 1}` : '';
            ledsHtml += `<div class="led-wrapper"><div class="led ${ledClass}">${number}</div></div>`;
        });

        if (isExplanation) {
            return { html: ledsHtml, frameClass: frameClass };
        }
        
        const originalFrameClassLetter = symbolToClass[healthString.slice(9, 10)] || '';
        const originalFrameClass = originalFrameClassLetter ? `frame-${originalFrameClassLetter}` : '';
        return `<div class="neon-grid-container ${originalFrameClass}" data-health-string="${healthString}">${ledsHtml}</div>`;
    }
    
    const modal = document.getElementById('grid-explanation-modal');
    // Pievienojam pārbaudi, vai 'modal' eksistē, pirms meklējam tā bērnus
    const closeModalBtn = modal ? modal.querySelector('.modal-close') : null;
    const explanationGrid = modal ? document.getElementById('explanation-grid-dynamic') : null;

    function openModal(healthString) {
        // Pārbaudām, vai 'explanationGrid' tika atrasts
        if (!explanationGrid) return; 
        
        if (!healthString || healthString.length !== 10) healthString = 'nnnnnnnnnn';
        const { html, frameClass } = generateNeonGridHtml(healthString, true);
        explanationGrid.innerHTML = html;
        explanationGrid.className = 'neon-grid-container ' + frameClass;
        
        const explanationList = modal.querySelector('.explanation-list');
        if (!explanationList) return; 
        explanationList.innerHTML = '';
        
        const explanations = {
            1: { title: "1. Likviditāte (CR)", blue: "Līdzekļi stāv neizmantoti uzņēmuma attīstībai", green: "Uzņēmums spēj segt savas īstermiņa saistības", orange: "Uzņēmumam var rasties problēmas segt saistības", red: "Uzņēmums nespēj segt savas īstermiņa saistības", grey: "Nav datu" },
            2: { title: "2. Likviditāte (QR)", blue: "Līdzekļi stāv neizmantoti uzņēmuma attīstībai", green: "Uzņēmums spēj segt saistības bez krājumu pārdošanas", orange: "Uzņēmumam var rasties problēmas segt saistības", red: "Uzņēmums nespēj segt savas īstermiņa saistības", grey: "Nav datu" },
            3: { title: "3. Rentabilitāte (NPM)", green: "Augsta peļņas marža, efektīva izmaksu kontrole", orange: "Vidēja peļņas marža, jāuzlabo efektivitāte", red: "Zema peļņas marža vai zaudējumi", grey: "Nav datu" },
            4: { title: "4. Efektivitāte (ROA)", green: "Efektīva aktīvu izmantošana peļņas gūšanai", orange: "Vidēja aktīvu atdeve, iespējami uzlabojumi", red: "Neefektīva aktīvu izmantošana, zema peļņa", grey: "Nav datu" },
            5: { title: "5. Efektivitāte (ROE)", green: "Laba kapitāla atdeve, efektīva peļņas reinvestēšana", orange: "Vidēja kapitāla atdeve, jāuzlabo rentabilitāte", red: "Zema kapitāla atdeve, risks investoriem", grey: "Nav datu" },
            6: { title: "6. Efektivitāte (AT)", green: "Efektīva aktīvu izmantošana apgrozījuma radīšanai", orange: "Vidēja aktīvu izmantošana, iespējama neefektivitāte", red: "Zems apgrozījums no aktīviem, nepietiekama pārdošana", grey: "Nav datu" },
            7: { title: "7. Maksātspēja (D/E)", green: "Zems saistību līmenis, stabils uzņēmums", orange: "Mērens saistību līmenis, pieņemams risks", red: "Augsts saistību līmenis, augsts risks", grey: "Nav datu" },
            8: { title: "8. Maksātspēja (ROCE)", green: "Efektīva kapitāla izmantošana peļņas gūšanai", orange: "Vidēja kapitāla atdeve, iespējami uzlabojumi", red: "Neefektīva kapitāla izmantošana, zema peļņa", grey: "Nav datu" },
            9: { title: "9. Maksātspēja (IC)", green: "Uzņēmums stabili sedz procentu maksājumus", orange: "Nelielas grūtības segt procentu maksājumus", red: "Uzņēmums nespēj segt procentu maksājumus", grey: "Nav datu" },
            10: { title: "10. Kopējais risks (Altman Z)", green: "Stabils uzņēmums, zems bankrota risks", orange: "Uzņēmums 'pelēkajā zonā', iespējamas problēmas", red: "Augsts bankrota risks", grey: "Nav datu" }
        };
        
        const symbolToColorKey = { 'r': 'red', 'o': 'orange', 'g': 'green', 'b': 'blue', 'n': 'grey', '': 'grey' };
        const symbolToCssClass = { 'b': 'color-b', 'g': 'color-g', 'o': 'color-o', 'r': 'color-r', 'n': 'color-n' };

        const ledSymbols = healthString.slice(0, 9).split('');
        const frameSymbol = healthString.slice(9, 10);

        ledSymbols.forEach((symbol, index) => {
            const indicatorNum = index + 1;
            const originalSymbol = symbol; 
            let currentSymbol = symbol;

            if (indicatorNum > 2 && currentSymbol === 'b') {
                currentSymbol = 'g';
            }
            
            const data = explanations[indicatorNum];
            const colorKey = symbolToColorKey[currentSymbol] || 'grey';
            const description = data[colorKey] || data['grey']; 
            
            const cssClass = symbolToCssClass[originalSymbol] || 'color-n';
            explanationList.innerHTML += `<li class="${cssClass}"><b>${data.title}</b><br>${description}</li>`;
        });

        const originalFrameSymbol = frameSymbol; 
        let currentFrameSymbol = frameSymbol;
        if (currentFrameSymbol === 'b') {
            currentFrameSymbol = 'g';
        }

        const data10 = explanations[10];
        const colorKey10 = symbolToColorKey[currentFrameSymbol] || 'grey';
        const description10 = data10[colorKey10] || data10['grey'];
        
        const cssClass10 = symbolToCssClass[originalFrameSymbol] || 'color-n';
        explanationList.innerHTML += `<li class="${cssClass10}"><b>${data10.title}</b><br>${description10}</li>`;
        
        modal.style.display = 'flex';
    }
    
    function closeModal() { 
        if(modal) modal.style.display = 'none'; 
    }

    if (modal) {
        document.body.addEventListener('click', function(event) {
            const grid = event.target.closest('.neon-grid-container');
            if (grid && grid.dataset.healthString) {
                openModal(grid.dataset.healthString);
            }
        });

        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', closeModal);
        }
        modal.addEventListener('click', function(event) { if (event.target === modal) closeModal(); });
        window.addEventListener('keydown', function(event) { if (event.key === 'Escape' && modal.style.display === 'flex') closeModal(); });
    }
    
    function sortData() {
        currentCompaniesData.sort((a, b) => {
            const valA = a[currentSortKey]; const valB = b[currentSortKey];
            const aIsData = valA !== null && typeof valA !== 'undefined'; const bIsData = valB !== null && typeof valB !== 'undefined';
            if (!aIsData && !bIsData) return 0; if (!aIsData) return 1; if (!bIsData) return -1;
            let compare = 0; 
            const th = companyDisplay ? companyDisplay.querySelector(`th[data-sort-key="${currentSortKey}"]`) : null;
            const sortType = th ? th.dataset.sortType : 'string';
            if (sortType === 'number') { compare = (valA || 0) - (valB || 0); } else { compare = (valA || '').toString().localeCompare((valB || '').toString(), 'lv'); }
            return currentSortDir === 'asc' ? compare : -compare;
        });
    }

    function renderTableBody() {
        let tbodyHtml = '';
        const formatNumber = (val) => (val !== null && typeof val !== 'undefined') ? new Intl.NumberFormat('lv-LV', {maximumFractionDigits: 0}).format(val) : 'Nav datu';
        const formatInt = (val) => (val !== null && typeof val !== 'undefined') ? new Intl.NumberFormat('lv-LV').format(val) : 'Nav datu';
        const formatNetSalary = (val) => (val !== null && typeof val !== 'undefined' && val > 0) ? new Intl.NumberFormat('lv-LV', {maximumFractionDigits: 0}).format(val) : 'Nav datu';
        
        currentCompaniesData.forEach(c => {
            tbodyHtml += `
                <tr>
                    <td data-label="Nosaukums">
                        <div class="company-name-block">
                            <div class="company-name">${c.name || '-'}</div>
                            <div class="company-regcode"><a href="https://saraksts.lv/${c.regcode}" target="_blank">${c.regcode || '-'}</a></div>
                        </div>
                    </td>
                    <td data-label="Lokācija">${c.location || '-'}</td>
                    <td data-label="Apgrozījums (EUR)">${formatNumber(c.turnover)}</td>
                    <td data-label="Darbinieki">${formatInt(c.employees)}</td>
                    <td data-label="Peļņa (EUR)">${formatNumber(c.profit)}</td>
                    <td data-label="Vid. Neto Alga (EUR)">${formatNetSalary(c.avg_net_salary)}</td>
                    <td data-label="Stāvoklis">${generateNeonGridHtml(c.financial_health_string || 'nnnnnnnnnn')}</td>
                </tr>`;
        });

        const tbody = companyDisplay ? companyDisplay.querySelector('tbody') : null;
        if (tbody) tbody.innerHTML = tbodyHtml;
    }

    function updateSortIcons() {
        if (!companyDisplay) return;
        companyDisplay.querySelectorAll('th.sortable').forEach(th => {
            th.classList.remove('sorted-asc', 'sorted-desc');
            if (th.dataset.sortKey === currentSortKey) { th.classList.add(currentSortDir === 'asc' ? 'sorted-asc' : 'sorted-desc'); }
        });
    }

    function addSortEventListeners() {
        if (!companyDisplay) return;
        companyDisplay.querySelectorAll('th.sortable').forEach(th => {
            th.addEventListener('click', () => {
                const newSortKey = th.dataset.sortKey;
                if (currentSortKey === newSortKey) { currentSortDir = currentSortDir === 'asc' ? 'desc' : 'asc'; } else { 
                    currentSortKey = newSortKey; 
                    currentSortDir = (newSortKey === 'name' || newSortKey === 'regcode' || newSortKey === 'location') ? 'asc' : 'desc'; 
                }
                sortData(); renderTableBody(); updateSortIcons();
            });
        });
    }

    function trackPageView(kods, nosaukums) {
        if (typeof gtag !== 'function') return; 
        
        const ga_id = 'G-xxxxxxxxx';
        let path = window.location.pathname;
        let title = 'Nozaru Pārskats - Sākums';
        
        if (kods && nosaukums) { 
            if (naceData && Array.isArray(naceData)) {
                const subCategories = naceData.filter(cat => cat['Vecāka kods'] === kods);
                if (kods === 'UNDEFINED' || subCategories.length === 0) {
                    path = `${window.location.pathname}#${kods}`;
                    title = `${kods} - ${nosaukums} (Uzņēmumi)`;
                } else {
                    path = `${window.location.pathname}#${kods}`;
                    title = `${kods} - ${nosaukums} (Nozare)`;
                }
            }
        }
        
        gtag('config', ga_id, {
            'page_path': path,
            'page_title': title
        });
    }

    function navigateTo(kods, pushHistory = true) {
        if (!naceData || !Array.isArray(naceData) || !gallery || !companyDisplay || !breadcrumbsContainer) {
            console.error("navigateTo tika izsaukta, bet trūkst datu vai HTML elementu.");
            return;
        }

        if (!kods) {
            currentCategory = null;
            const mainCategories = naceData.filter(cat => cat.Līmenis === 1);
            renderCards(mainCategories);
            renderBreadcrumbs(null);
            gallery.style.display = 'grid'; 
            companyDisplay.style.display = 'none';
            
            if (pushHistory) {
                history.pushState({ kods: null }, '', window.location.pathname); 
            }
            trackPageView(null, null); 
            return;
        }

        const category = naceData.find(c => c.Kods === kods);
        if (!category) {
            navigateTo(null, pushHistory); 
            return;
        }

        const subCategories = naceData.filter(cat => cat['Vecāka kods'] === category.Kods);
        
        if (category.Kods === 'UNDEFINED' || subCategories.length === 0) {
            currentCategory = category.Kods;
            renderBreadcrumbs(category.Kods);
            gallery.style.display = 'none'; 
            loadCompanyTable(category.Kods, category.Nosaukums);
        } else {
            currentCategory = category.Kods;
            renderCards(subCategories);
            renderBreadcrumbs(category.Kods);
            gallery.style.display = 'grid'; 
            
            if (category.Līmenis >= 2) {
                companyDisplay.style.display = 'block'; 
                loadCompanyTable(category.Kods, category.Nosaukums);
            } else {
                companyDisplay.style.display = 'none';
            }
        }
        
        if (pushHistory) {
            history.pushState({ kods: kods }, '', '#' + kods);
        }
        trackPageView(kods, category.Nosaukums);
    }

    function loadCompanyTable(kods, nosaukums) {
        if (!companyDisplay) return;
        
        const displayName = (kods === 'UNDEFINED') ? nosaukums : `${kods} - ${nosaukums}`;
        companyDisplay.innerHTML = `<h2>${displayName} (Uzņēmumi)</h2><p class="no-data">Ielādē datus...</p>`; 
        companyDisplay.style.display = 'block'; 
        
        // Ceļš uz API 'nace' apakšmapē
        fetch(`nace/get_companies.php?kods=${encodeURIComponent(kods)}`).then(response => { if (!response.ok) { return response.text().then(text => { throw new Error(text); }); } return response.json(); }).then(companies => {
            currentCompaniesData = companies; currentSortKey = 'employees'; currentSortDir = 'desc';
            let tableHtml = `<h2>${displayName} (Uzņēmumi)</h2>`;
            if (companies && companies.length > 0) {
                
                tableHtml += `
                <div class="table-responsive-wrapper">
                    <table class="company-table">
                        <thead>
                            <tr>
                                <th class="sortable" data-sort-key="name" data-sort-type="string">Nosaukums <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th class="sortable" data-sort-key="location" data-sort-type="string">Lokācija <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th class="sortable" data-sort-key="turnover" data-sort-type="number">Apgrozījums (EUR) <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th class="sortable sorted-desc" data-sort-key="employees" data-sort-type="number">Darbinieki <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th class="sortable" data-sort-key="profit" data-sort-type="number">Peļņa (EUR) <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th class="sortable" data-sort-key="avg_net_salary" data-sort-type="number">Vid. Neto Alga (EUR) <span class="sort-arrows"><span class="arrow-up"></span><span class="arrow-down"></span></span></th>
                                <th>Stāvoklis</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>`;

            } else { tableHtml += '<p class="no-data">Šajā kategorijā nav atrasts neviens aktīvs uzņēmums.</p>'; }
            companyDisplay.innerHTML = tableHtml;
            if (companies && companies.length > 0) { sortData(); renderTableBody(); addSortEventListeners(); }
        }).catch(error => { console.error("Kļūda, ielādējot uzņēmumu datus:", error); companyDisplay.innerHTML = `<h2>Kļūda</h2><p class="no-data">Nevarēja ielādēt datus no servera.</p>`; });
    }
    
    function renderBreadcrumbs(kods) {
        if (!breadcrumbsContainer) return;
        breadcrumbsContainer.innerHTML = ''; 
        
        if (!naceData || !Array.isArray(naceData)) return;

        let path = []; let currentKods = kods;
        while (currentKods) { const cat = naceData.find(c => c.Kods === currentKods); if (cat) { path.unshift(cat); currentKods = cat['Vecāka kods']; } else { currentKods = null; } }
        
        const homeLink = document.createElement('a'); homeLink.href = '#'; homeLink.textContent = 'Sākums';
        homeLink.addEventListener('click', (e) => { e.preventDefault(); navigateTo(null, true); }); 
        breadcrumbsContainer.appendChild(homeLink);

        path.forEach(cat => {
            const separator = document.createElement('span'); separator.className = 'separator'; separator.textContent = '>'; breadcrumbsContainer.appendChild(separator);
            const categoryName = cat.Nosaukums || ''; const categoryCode = cat.Kods || ''; const displayText = (categoryCode === 'UNDEFINED') ? categoryName : `${categoryCode} - ${categoryName}`;
            
            if (cat.Kods === kods) { 
                const currentText = document.createElement('span'); currentText.className = 'current-page'; currentText.textContent = displayText; breadcrumbsContainer.appendChild(currentText); 
            } else {
                const parentLink = document.createElement('a'); parentLink.href = '#' + cat.Kods; parentLink.textContent = displayText; parentLink.dataset.kods = cat.Kods;
                parentLink.addEventListener('click', (e) => { e.preventDefault(); navigateTo(e.currentTarget.dataset.kods, true); }); 
                breadcrumbsContainer.appendChild(parentLink);
            }
        });
    }

    function renderCards(categories) {
      if (!gallery) return;
      gallery.innerHTML = ''; gallery.style.display = 'grid'; 
      categories.sort((a, b) => (a.Kods || '').localeCompare(b.Kods || ''));
      const numFormatter = (val) => new Intl.NumberFormat('lv-LV', {maximumFractionDigits: 0}).format(val || 0);
      categories.forEach(cat => {
        // Attēlu ceļi ar .toLowerCase() un .webp
        const imageUrl = (cat.Kods === 'UNDEFINED') ? `nace/nace-foto/x.webp` : `nace/nace-foto/${cat.Kods.toLowerCase()}.webp`;
        const { UznemumuSkaits, KopApgrozijums, KopDarbinieki, KopPela, VidejaNetoAlga, Apraksts, Nosaukums, VeselibasVirkne } = cat;
        const description = Apraksts || Nosaukums;
        let subHtml = '';
        if (cat.Līmenis < 4 && cat.Kods !== 'UNDEFINED') { 
            if (naceData && Array.isArray(naceData)) {
                const subCategories = naceData.filter(subCat => subCat['Vecāka kods'] === cat.Kods);
                subCategories.sort((a, b) => (a.Kods || '').localeCompare(b.Kods || '')); subHtml = '<div class="subcategory-preview-pane">'; 
                if (subCategories.length > 0) {
                    const previewLimit = 6; 
                    subCategories.slice(0, previewLimit).forEach(subCat => {
                        const subImageUrl = `nace/nace-foto/${subCat.Kods.toLowerCase()}.webp`; 
                        const subCount = subCat.UznemumuSkaits;
                        subHtml += '<div class="sub-preview-item">'; if (subCount > 0) { subHtml += `<div class="sub-preview-badge">${subCount}</div>`; }
                        // Rezerves attēls 'a.webp'
                        subHtml += `<img src="${subImageUrl}" class="sub-preview-img" title="${subCat.Nosaukums || ''} (${subCat.Kods})" onerror="this.onerror=null;this.src='nace/nace-foto/a.webp';">`; 
                        subHtml += '</div>';
                    });
                    if (subCategories.length > previewLimit) { subHtml += `<div class="sub-preview-more">+${subCategories.length - previewLimit}</div>`; }
                }
                subHtml += '</div>';
            }
        }
        const card = document.createElement('div'); card.className = 'industry-card';
        
        card.innerHTML = `
          <div class="main-card-content" data-kods="${cat.Kods}">
              <div class="industry-header">${UznemumuSkaits > 0 ? `<div class="card-badge">${UznemumuSkaits}</div>` : ''}
                  <img src="${imageUrl}" 
     				onerror="this.onerror=null;this.src='nace/nace-foto/a.webp';"
     				alt="Nozares ${cat.Kods} attēls: ${description}" 
     				title="${description}"> 
				  <p class="description" title="${description}">${description}</p>
              </div>
              <div class="card-body">
                  <div class="industry-data">
                      
                      <span class="data-item-label" title="Kopējais apgrozījums">Apgrozījums:</span>
                      <span class="data-item-value">€ ${numFormatter(KopApgrozijums)}</span>

                      <span class="data-item-label" title="Kopējais darbinieku skaits">Darbinieki:</span>
                      <span class="data-item-value">${numFormatter(KopDarbinieki)}</span>

                      <span class="data-item-label" title="Kopējā peļņa">Peļņa:</span>
                      <span class="data-item-value">€ ${numFormatter(KopPela)}</span>

                      <span class="data-item-label" title="Vidējā neto alga">Vid. alga:</span>
                      <span class="data-item-value">€ ${numFormatter(VidejaNetoAlga)}</span>

                  </div>
                  <div class="financial-indicators-side" title="Skaidrojums">${generateNeonGridHtml(VeselibasVirkne)}</div>
              </div>
          </div>
          ${subHtml}`;

        gallery.appendChild(card);
      });
      gallery.querySelectorAll('.main-card-content').forEach(el => el.addEventListener('click', (e) => {
          if (naceData && Array.isArray(naceData)) {
              handleCardClick(naceData.find(c => c.Kods === e.currentTarget.dataset.kods))
          }
      }));
    }
    
    function handleCardClick(category) {
        if(category) {
            navigateTo(category.Kods, true); 
        }
    }
    
    document.addEventListener('DOMContentLoaded', () => {
        if (naceData && Array.isArray(naceData) && naceData.length > 0) {
            const kods = window.location.hash.substring(1); 
            navigateTo(kods, false); 
        }
    });

    window.addEventListener('popstate', (event) => {
        if (naceData && Array.isArray(naceData) && naceData.length > 0) {
            const kods = event.state ? event.state.kods : window.location.hash.substring(1);
            navigateTo(kods, false); 
        }
    });

  </script>
  </body>
</html>