<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../core/location.php';
require_once '../../services/crm/CustomerTerritoryService.php';

require_login();
require_permission('module.customers');

$page_title = 'Territorio de clientes';

$filters = array(
    'q' => isset($_GET['q']) ? trim((string)$_GET['q']) : '',
    'customer_segment' => isset($_GET['customer_segment']) ? trim((string)$_GET['customer_segment']) : '',
    'quote_status' => isset($_GET['quote_status']) ? trim((string)$_GET['quote_status']) : '',
);

$territory = new CustomerTerritoryService();
$options = $territory->getFilterOptions();
$customers = $territory->getCustomers($filters);
$summary = $territory->buildSummary($customers);
$mapPoints = $territory->buildMapPoints($customers);
$geocodeRate = $summary['total'] > 0 ? (int)round(($summary['geocoded'] / $summary['total']) * 100) : 0;

$territoryCountries = array();
$territoryRegions = array();

foreach ($customers as $customer) {
    $country = trim((string)($customer['country'] ?? ''));
    $region = trim((string)($customer['region'] ?? ''));
    $countryLabel = $country !== '' ? $country : 'Sin país registrado';
    $regionLabel = $region !== '' ? $region : 'Sin región registrada';
    $regionCompositeLabel = $country !== '' ? $regionLabel . ' · ' . $country : $regionLabel;

    if (!isset($territoryCountries[$countryLabel])) {
        $territoryCountries[$countryLabel] = array(
            'customers' => 0,
            'geocoded' => 0,
            'sales_last_12m' => 0,
            'total_net_sales' => 0,
            'weighted_pipeline_value' => 0,
            'open_pipeline_value' => 0,
            'open_opportunities' => 0,
            'at_risk_customers' => 0,
        );
    }

    if (!isset($territoryRegions[$regionCompositeLabel])) {
        $territoryRegions[$regionCompositeLabel] = array(
            'customers' => 0,
            'geocoded' => 0,
            'sales_last_12m' => 0,
            'total_net_sales' => 0,
            'weighted_pipeline_value' => 0,
            'open_pipeline_value' => 0,
            'open_opportunities' => 0,
            'at_risk_customers' => 0,
        );
    }

    $hasCoordinates = $customer['latitude'] !== null && $customer['longitude'] !== null && is_numeric($customer['latitude']) && is_numeric($customer['longitude']);
    $sales12m = (float)($customer['sales_last_12m'] ?? $customer['total_net_sales'] ?? 0);
    $totalSales = (float)($customer['total_net_sales'] ?? 0);
    $weightedPipeline = (float)($customer['weighted_pipeline_value'] ?? 0);
    $openPipeline = (float)($customer['open_pipeline_value'] ?? 0);
    $openOps = (int)($customer['open_opportunities'] ?? 0);
    $status = trim((string)($customer['customer_status'] ?? ''));
    $isAtRisk = in_array($status, array('en_riesgo', 'dormido', 'perdido'), true);

    foreach (array($countryLabel, $regionCompositeLabel) as $idx => $key) {
        if ($idx === 0) {
            $territoryCountries[$key]['customers']++;
            if ($hasCoordinates) $territoryCountries[$key]['geocoded']++;
            $territoryCountries[$key]['sales_last_12m'] += $sales12m;
            $territoryCountries[$key]['total_net_sales'] += $totalSales;
            $territoryCountries[$key]['weighted_pipeline_value'] += $weightedPipeline;
            $territoryCountries[$key]['open_pipeline_value'] += $openPipeline;
            $territoryCountries[$key]['open_opportunities'] += $openOps;
            if ($isAtRisk) $territoryCountries[$key]['at_risk_customers']++;
        } else {
            $territoryRegions[$key]['customers']++;
            if ($hasCoordinates) $territoryRegions[$key]['geocoded']++;
            $territoryRegions[$key]['sales_last_12m'] += $sales12m;
            $territoryRegions[$key]['total_net_sales'] += $totalSales;
            $territoryRegions[$key]['weighted_pipeline_value'] += $weightedPipeline;
            $territoryRegions[$key]['open_pipeline_value'] += $openPipeline;
            $territoryRegions[$key]['open_opportunities'] += $openOps;
            if ($isAtRisk) $territoryRegions[$key]['at_risk_customers']++;
        }
    }
}

uasort($territoryCountries, function ($a, $b) {
    return ($b['sales_last_12m'] <=> $a['sales_last_12m']) ?: ($b['weighted_pipeline_value'] <=> $a['weighted_pipeline_value']) ?: ($b['customers'] <=> $a['customers']);
});

uasort($territoryRegions, function ($a, $b) {
    return ($b['sales_last_12m'] <=> $a['sales_last_12m']) ?: ($b['weighted_pipeline_value'] <=> $a['weighted_pipeline_value']) ?: ($b['customers'] <=> $a['customers']);
});


$browserKey = defined('GOOGLE_MAPS_BROWSER_KEY') ? trim((string)GOOGLE_MAPS_BROWSER_KEY) : '';
$mapId = defined('GOOGLE_MAPS_MAP_ID') ? trim((string)GOOGLE_MAPS_MAP_ID) : '';
$hasActiveFilters = implode('', $filters) !== '';


function territory_country_code($country)
{
    $country = trim((string)$country);
    if ($country === '') {
        return '';
    }

    $normalized = function_exists('mb_strtolower') ? mb_strtolower($country, 'UTF-8') : strtolower($country);
    $normalized = strtr($normalized, array(
        'á' => 'a', 'é' => 'e', 'í' => 'i', 'ó' => 'o', 'ú' => 'u', 'ü' => 'u', 'ñ' => 'n',
        'Á' => 'a', 'É' => 'e', 'Í' => 'i', 'Ó' => 'o', 'Ú' => 'u', 'Ü' => 'u', 'Ñ' => 'n',
    ));

    $codes = array(
        'chile' => 'CHL',
        'argentina' => 'ARG',
        'peru' => 'PER',
        'uruguay' => 'URY',
        'brasil' => 'BRA',
        'brazil' => 'BRA',
        'colombia' => 'COL',
        'ecuador' => 'ECU',
        'mexico' => 'MEX',
        'mejico' => 'MEX',
        'paraguay' => 'PRY',
        'bolivia' => 'BOL',
        'estados unidos' => 'USA',
        'eeuu' => 'USA',
        'usa' => 'USA',
        'united states' => 'USA',
        'espana' => 'ESP',
        'spain' => 'ESP',
        'venezuela' => 'VEN',
        'otro' => 'OTR',
    );

    if (isset($codes[$normalized])) {
        return $codes[$normalized];
    }

    $letters = preg_replace('/[^a-z]/', '', $normalized);
    return strtoupper(substr($letters, 0, 3));
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';

?>

<main class="app-main" id="customers-territory-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">
        <div class="page-header territory-page-header">
            <div class="page-header-content">
                <span class="label">Comercial</span>
                <h1>Territorio de clientes</h1>
                <p class="text-secondary">Mapa BI para priorizar valor comercial, pipeline, riesgo y cobertura territorial.</p>
            </div>
        
            <div class="cluster actions-cluster territory-header-actions">
                <a class="btn btn-outline territory-back-btn" href="/modules/customers/index.php" title="Volver a clientes" aria-label="Volver a clientes">
                    <i data-lucide="chevron-left"></i>
                    <span class="territory-back-label">Clientes</span>
                </a>
            </div>
        </div>


        <section class="territory-kpi-grid mb-4" aria-label="Resumen territorial">
            <article class="kpi-card">
                <div class="kpi-label">Clientes filtrados</div>
                <div class="kpi-main"><div class="kpi-value"><?php echo (int)$summary['total']; ?></div></div>
                <p class="kpi-context"><?php echo number_format($geocodeRate, 0, ',', '.'); ?>% geolocalizado · <?php echo (int)$summary['no_coordinates']; ?> sin coordenadas</p>
            </article>
            <article class="kpi-card">
                <div class="kpi-label">Ventas 12M</div>
                <div class="kpi-main"><div class="kpi-value"><?php echo clp((float)($summary['sales_last_12m'] ?? 0)); ?></div></div>
                <p class="kpi-context">Venta neta atribuida a clientes filtrados</p>
            </article>
            <article class="kpi-card">
                <div class="kpi-label">Pipeline ponderado</div>
                <div class="kpi-main"><div class="kpi-value"><?php echo clp((float)($summary['weighted_pipeline_value'] ?? 0)); ?></div></div>
                <p class="kpi-context"><?php echo (int)$summary['open_opportunities']; ?> oportunidades abiertas · <?php echo clp((float)($summary['open_pipeline_value'] ?? 0)); ?> bruto</p>
            </article>
            <article class="kpi-card">
                <div class="kpi-label">Clientes en riesgo</div>
                <div class="kpi-main"><div class="kpi-value"><?php echo (int)($summary['at_risk_customers'] ?? 0); ?></div></div>
                <p class="kpi-context">En riesgo, dormidos o perdidos</p>
            </article>
        </section>

        <section class="card mb-4 territory-filters-card">
            <div class="card-body">
                <form method="GET" class="territory-filters <?php echo $hasActiveFilters ? 'has-clear' : 'no-clear'; ?>" style="margin: 0;">
                    <div class="form-field territory-filter-search">
                        <input class="input" type="text" name="q" value="<?php echo safe_text($filters['q']); ?>" placeholder="Buscar cliente, RUT, ciudad o país..." autocomplete="off">
                    </div>

                    <div class="form-field">
                        <select class="select" name="customer_segment" onchange="this.form.submit()">
                            <option value="">Perfil comercial: todos</option>
                            <?php foreach ($options['segments'] as $segmentValue => $segmentLabel): ?>
                                <option value="<?php echo safe_text($segmentValue); ?>" <?php echo $filters['customer_segment'] === $segmentValue ? 'selected' : ''; ?>><?php echo safe_text($segmentLabel); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-field">
                        <select class="select" name="quote_status" onchange="this.form.submit()">
                            <option value="">Estado cotización: todos</option>
                            <?php foreach ($options['quote_statuses'] as $status): ?>
                                <option value="<?php echo safe_text($status); ?>" <?php echo $filters['quote_status'] === $status ? 'selected' : ''; ?>><?php echo safe_text($status); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <button class="btn btn-primary territory-filter-submit" type="submit">Filtrar</button>
                    <?php if ($hasActiveFilters): ?>
                        <a class="btn btn-outline territory-filter-clear" href="/modules/customers/territory.php">Limpiar</a>
                    <?php endif; ?>
                </form>
            </div>
        </section>

        <section class="grid grid-2 territory-main-grid">
            <article class="card territory-map-card" id="territoryMap" data-customer-territory-map data-google-key="<?php echo safe_text($browserKey); ?>" data-map-id="<?php echo safe_text($mapId); ?>">
                <div class="card-header territory-map-card-header">
                    <div>
                        <span class="label">Mapa BI</span>
                        <h3 data-map-title>Valor comercial</h3>
                        <p class="text-secondary text-sm territory-map-subtitle">Tamaño, color y modo cambian según la lectura comercial seleccionada.</p>
                    </div>
                    <div class="territory-map-header-tools">
                        <span class="badge"><?php echo count($mapPoints); ?> puntos · <?php echo number_format($geocodeRate, 0, ',', '.'); ?>% geo</span>
                        <div class="territory-map-mode-switch" role="group" aria-label="Vista del mapa territorial">
                            <button class="btn btn-sm btn-primary" type="button" data-territory-map-mode="value">Valor</button>
                            <button class="btn btn-sm btn-outline" type="button" data-territory-map-mode="pipeline">Pipeline</button>
                            <button class="btn btn-sm btn-outline" type="button" data-territory-map-mode="risk">Riesgo</button>
                            <button class="btn btn-sm btn-outline" type="button" data-territory-map-mode="coverage">Cobertura</button>
                            <button class="btn btn-sm btn-outline" type="button" data-territory-map-mode="detail">Detalle</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="territory-map-canvas territory-bi-map-canvas" data-map-canvas>
                        <?php if ($browserKey === ''): ?>
                            <div class="territory-map-placeholder">
                                <i data-lucide="map"></i>
                                <strong>Mapa BI pendiente</strong>
                                <span>Define <code>GOOGLE_MAPS_BROWSER_KEY</code> / <code>ICYLAB_GOOGLE_MAPS_BROWSER_KEY</code> en <code>core/private_config.php</code> para habilitar el mapa estratégico.</span>
                            </div>
                        <?php endif; ?>
                    </div>
                    <p class="customer-location-note" data-map-message>
                        <?php echo $browserKey === '' ? 'Listado territorial activo. El mapa se habilita al configurar la key frontend.' : 'Cargando mapa BI territorial...'; ?>
                    </p>
                </div>
            </article>

            <article class="card territory-breakdown-card" id="territorySegmentation">
                <div class="card-header territory-breakdown-header">
                    <div>
                        <span class="label">Segmentación</span>
                        <h3>Distribución territorial</h3>
                    </div>
                    <span class="badge territory-mobile-summary"><?php echo (int)$summary['geocoded']; ?>/<?php echo (int)$summary['total']; ?> geo</span>
                </div>
                <div class="card-body territory-breakdown-grid territory-bi-breakdown-grid">
                    <div class="territory-breakdown-block">
                        <h4 class="territory-subtitle">Países por valor</h4>
                        <div class="territory-metric-list territory-chip-list">
                            <?php foreach (array_slice($territoryCountries, 0, 8, true) as $country => $data): ?>
                                <div class="metric-row territory-metric-card territory-chip-card territory-bi-chip-card">
                                    <span>
                                        <strong><?php echo safe_text($country); ?></strong>
                                        <small><?php echo (int)$data['customers']; ?> clientes · <?php echo (int)$data['geocoded']; ?> geo</small>
                                    </span>
                                    <strong class="metric-value"><?php echo clp((float)$data['sales_last_12m']); ?></strong>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($territoryCountries)): ?>
                                <p class="text-secondary text-sm">Sin países registrados.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="territory-breakdown-block">
                        <h4 class="territory-subtitle">Regiones prioritarias</h4>
                        <div class="territory-metric-list territory-chip-list">
                            <?php foreach (array_slice($territoryRegions, 0, 10, true) as $region => $data): ?>
                                <div class="metric-row territory-metric-card territory-chip-card territory-bi-chip-card">
                                    <span>
                                        <strong><?php echo safe_text($region); ?></strong>
                                        <small><?php echo (int)$data['customers']; ?> clientes · <?php echo (int)$data['open_opportunities']; ?> ops · <?php echo (int)$data['at_risk_customers']; ?> riesgo</small>
                                    </span>
                                    <strong class="metric-value"><?php echo clp((float)$data['sales_last_12m']); ?></strong>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($territoryRegions)): ?>
                                <p class="text-secondary text-sm">Sin regiones registradas.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </article>
        </section>

        <section class="card mt-4 territory-table-card card-table-container" id="territoryTable">
            <div class="card-header">
                <div>
                    <span class="label">Clientes</span>
                    <h3>Detalle territorial</h3>
                </div>
                <span class="text-secondary text-sm"><?php echo count($customers); ?> registros</span>
            </div>
            <div class="table-wrap table-container-scroll territory-table-scroll">
                <table class="table table-compact territory-table">
                    <colgroup>
                        <col class="territory-col-client">
                        <col class="territory-col-country">
                        <col class="territory-col-region">
                        <col class="territory-col-city">
                        <col class="territory-col-geo">
                        <col class="territory-col-opportunities">
                        <col class="territory-col-action">
                    </colgroup>
                    <thead>
                        <tr>
                            <th class="territory-head-client">Cliente</th>
                            <th class="territory-head-country">País</th>
                            <th class="territory-head-region">Región</th>
                            <th class="territory-head-city">Ciudad / Comuna</th>
                            <th class="territory-head-geo">Geo</th>
                            <th class="territory-head-opportunities text-center">Ops.</th>
                            <th class="territory-head-action text-right">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($customers as $customer): ?>
                            <?php
                                $displayName = trim((string)($customer['commercial_name'] ?? '')) ?: trim((string)($customer['customer_name'] ?? 'Cliente'));
                                $hasCoordinates = $customer['latitude'] !== null && $customer['longitude'] !== null && is_numeric($customer['latitude']) && is_numeric($customer['longitude']);
                                $mapsQuery = $hasCoordinates
                                    ? $customer['latitude'] . ',' . $customer['longitude']
                                    : trim(($customer['address'] ?? '') . ' ' . ($customer['district'] ?? '') . ' ' . ($customer['city'] ?? '') . ' ' . ($customer['region'] ?? '') . ' ' . ($customer['country'] ?? ''));
                                $cityDistrictRaw = trim(($customer['city'] ?? '') . ' / ' . ($customer['district'] ?? ''), ' /');
                                $cityDistrict = safe_text($cityDistrictRaw);
                                $countryName = trim((string)($customer['country'] ?? ''));
                                $countryCode = territory_country_code($countryName);
                                $geoLabel = $hasCoordinates ? 'Con coordenadas' : safe_text($customer['geocode_status'] ?? 'pending');
                                $locationSummary = trim(implode(' · ', array_filter(array(
                                    trim((string)($customer['region'] ?? '')),
                                    trim((string)$cityDistrictRaw)
                                ))));
                            ?>
                            <tr>
                                <td class="territory-cell-client" data-label="Cliente">
                                    <a class="territory-customer-link" href="/modules/customers/view.php?id=<?php echo (int)$customer['id']; ?>" title="<?php echo safe_text($displayName); ?>">
                                        <strong><?php echo safe_text($displayName); ?></strong>
                                        <?php if (!empty($customer['legal_name']) && trim((string)$customer['legal_name']) !== $displayName): ?>
                                            <small title="<?php echo safe_text($customer['legal_name']); ?>"><?php echo safe_text($customer['legal_name']); ?></small>
                                        <?php endif; ?>
                                        <?php if ($locationSummary !== ''): ?>
                                            <small class="territory-mobile-location" title="<?php echo safe_text($locationSummary); ?>"><?php echo safe_text($locationSummary); ?></small>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td class="territory-cell-country" title="<?php echo safe_text($customer['country'] ?? ''); ?>">
                                    <?php
                                        $countryName = trim((string)($customer['country'] ?? ''));
                                        $countryKey = function_exists('mb_strtolower') ? mb_strtolower($countryName, 'UTF-8') : strtolower($countryName);
                                
                                        $countryCodes = array(
                                            'chile' => 'CHL',
                                            'argentina' => 'ARG',
                                            'perú' => 'PER',
                                            'peru' => 'PER',
                                            'uruguay' => 'URY',
                                            'brasil' => 'BRA',
                                            'brazil' => 'BRA',
                                            'colombia' => 'COL',
                                            'ecuador' => 'ECU',
                                            'méxico' => 'MEX',
                                            'mexico' => 'MEX',
                                            'paraguay' => 'PRY',
                                            'bolivia' => 'BOL',
                                            'venezuela' => 'VEN',
                                            'estados unidos' => 'USA',
                                            'usa' => 'USA',
                                            'united states' => 'USA',
                                            'españa' => 'ESP',
                                            'espana' => 'ESP',
                                            'spain' => 'ESP',
                                            'otro' => 'OTR',
                                        );
                                
                                        $countryCode = isset($countryCodes[$countryKey]) ? $countryCodes[$countryKey] : strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $countryName), 0, 3));
                                    ?>
                                    <span class="territory-country-full"><?php echo safe_text($countryName); ?></span>
                                    <span class="territory-country-code"><?php echo safe_text($countryCode); ?></span>
                                </td>
                                <td class="territory-cell-region" data-label="Región" title="<?php echo safe_text($customer['region'] ?? ''); ?>"><?php echo safe_text($customer['region'] ?? ''); ?></td>
                                <td class="territory-cell-city" data-label="Ciudad / Comuna" title="<?php echo $cityDistrict; ?>"><?php echo $cityDistrict; ?></td>
                                <td class="territory-cell-geo" data-label="Geo">
                                    <?php if ($hasCoordinates): ?>
                                        <span class="badge badge-success territory-geo-badge"><?php echo $geoLabel; ?></span>
                                    <?php else: ?>
                                        <span class="badge territory-geo-badge"><?php echo $geoLabel; ?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="territory-cell-opportunities text-center" data-label="Ops."><?php echo (int)($customer['open_opportunities'] ?? 0); ?></td>
                                <td class="territory-cell-action text-right" data-label="Acción">
                                    <div class="territory-row-actions">
                                        <?php if ($mapsQuery !== ''): ?>
                                            <a class="btn btn-sm btn-outline territory-icon-btn" href="https://www.google.com/maps/search/?api=1&amp;query=<?php echo urlencode($mapsQuery); ?>" target="_blank" rel="noopener" data-no-spa="true" title="Abrir en Maps">
                                                <i data-lucide="map-pin"></i>
                                                <span class="territory-action-label">Maps</span>
                                            </a>
                                        <?php endif; ?>
                                        <a class="btn btn-sm btn-outline territory-icon-btn" href="/modules/customers/view.php?id=<?php echo (int)$customer['id']; ?>" title="Abrir ficha">
                                            <i data-lucide="chevron-right"></i>
                                            <span class="territory-action-label">Ficha</span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($customers)): ?>
                            <tr><td colspan="7" class="text-center text-secondary py-8">No hay clientes para los filtros seleccionados.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>


    <style>
        /* =========================================================
           Territory BI - desktop/mobile layout hard fix
           Objetivo: evitar colapso de tarjetas, mantener mapa legible
           y hacer que segmentación use todo el alto disponible.
        ========================================================= */

        #customers-territory-main,
        #customers-territory-main .content,
        #customers-territory-main .territory-main-grid,
        #customers-territory-main .territory-map-card,
        #customers-territory-main .territory-breakdown-card,
        #customers-territory-main .territory-table-card,
        #customers-territory-main .territory-map-card *,
        #customers-territory-main .territory-breakdown-card * {
            box-sizing: border-box;
            min-width: 0;
        }

        #customers-territory-main {
            --territory-bi-card-height: 720px;
            --territory-bi-map-mobile-height: 430px;
        }

        #customers-territory-main .territory-main-grid {
            align-items: start !important;
            display: grid !important;
            gap: var(--space-5, 1.25rem) !important;
            grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) !important;
            max-width: 100% !important;
            overflow: visible !important;
        }

        #customers-territory-main .territory-map-card,
        #customers-territory-main .territory-breakdown-card {
            align-self: start !important;
            display: flex !important;
            flex-direction: column !important;
            height: var(--territory-bi-card-height) !important;
            max-height: var(--territory-bi-card-height) !important;
            min-height: var(--territory-bi-card-height) !important;
            overflow: hidden !important;
            width: 100% !important;
        }

        #customers-territory-main .territory-map-card-header,
        #customers-territory-main .territory-breakdown-header {
            flex: 0 0 auto !important;
            min-height: 0 !important;
        }

        #customers-territory-main .territory-map-card-header {
            align-items: flex-start !important;
            gap: 1rem !important;
        }

        #customers-territory-main .territory-map-subtitle {
            margin: 0.2rem 0 0 !important;
        }

        #customers-territory-main .territory-map-header-tools {
            align-items: flex-end !important;
            display: flex !important;
            flex-direction: column !important;
            gap: 0.55rem !important;
            min-width: 260px !important;
        }

        #customers-territory-main .territory-map-mode-switch {
            display: flex !important;
            flex-wrap: wrap !important;
            gap: 0.35rem !important;
            justify-content: flex-end !important;
        }

        #customers-territory-main .territory-map-card > .card-body,
        #customers-territory-main .territory-breakdown-card > .card-body {
            flex: 1 1 auto !important;
            height: auto !important;
            min-height: 0 !important;
            overflow: hidden !important;
        }

        #customers-territory-main .territory-map-card > .card-body {
            display: flex !important;
            flex-direction: column !important;
        }

        #customers-territory-main .territory-breakdown-card > .card-body {
            display: grid !important;
        }

        #customers-territory-main .territory-bi-map-canvas,
        #customers-territory-main .territory-map-placeholder {
            flex: 1 1 auto !important;
            height: 100% !important;
            max-height: none !important;
            min-height: 0 !important;
            position: relative !important;
            touch-action: auto !important;
            width: 100% !important;
        }

        #customers-territory-main .customer-location-note {
            flex: 0 0 auto !important;
            margin: 0.65rem 0 0 !important;
        }

        #customers-territory-main .territory-bi-breakdown-grid {
            align-items: stretch !important;
            display: grid !important;
            gap: 0.85rem !important;
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            height: 100% !important;
            max-height: 100% !important;
            max-width: 100% !important;
            min-height: 0 !important;
            overflow: hidden !important;
            padding: var(--space-5, 1.25rem) !important;
        }

        #customers-territory-main .territory-breakdown-block {
            display: flex !important;
            flex-direction: column !important;
            height: 100% !important;
            max-height: 100% !important;
            max-width: 100% !important;
            min-height: 0 !important;
            overflow: hidden !important;
        }

        #customers-territory-main .territory-subtitle {
            flex: 0 0 auto !important;
            margin: 0 0 0.7rem !important;
        }

        #customers-territory-main .territory-chip-list,
        #customers-territory-main .territory-metric-list {
            display: flex !important;
            flex: 1 1 auto !important;
            flex-direction: column !important;
            flex-wrap: nowrap !important;
            gap: 0.5rem !important;
            height: auto !important;
            max-height: none !important;
            max-width: 100% !important;
            min-height: 0 !important;
            min-width: 0 !important;
            overflow-x: hidden !important;
            overflow-y: auto !important;
            padding: 0 0.35rem 0 0 !important;
            -webkit-overflow-scrolling: touch !important;
            overscroll-behavior: contain !important;
        }

        #customers-territory-main .territory-bi-chip-card {
            align-items: center;
            box-sizing: border-box;
            display: grid !important;
            gap: 0.48rem;
            grid-template-columns: minmax(0, 1fr) auto;
            max-width: 100%;
            min-width: 0;
            padding: 0.56rem 0.62rem;
            width: 100%;
        }

        #customers-territory-main .territory-bi-chip-card > span {
            display: grid;
            gap: 0.14rem;
            max-width: 100%;
            min-width: 0;
            overflow: hidden;
        }

        #customers-territory-main .territory-bi-chip-card > span > strong,
        #customers-territory-main .territory-bi-chip-card small {
            display: block;
            line-height: 1.2;
            max-width: 100%;
            min-width: 0;
            overflow-wrap: anywhere;
            white-space: normal;
        }

        #customers-territory-main .territory-bi-chip-card small {
            color: var(--text-secondary, #64748b) !important;
            font-size: 0.7rem !important;
            font-weight: 500 !important;
        }

        #customers-territory-main .territory-bi-chip-card .metric-value {
            font-size: 0.76rem !important;
            justify-self: end !important;
            line-height: 1.12 !important;
            max-width: 7.8rem !important;
            overflow: hidden !important;
            text-align: right !important;
            text-overflow: ellipsis !important;
            white-space: nowrap !important;
        }

        #customers-territory-main .territory-map-legend {
            backdrop-filter: blur(14px);
            background: rgba(10, 15, 23, 0.9);
            border: 1px solid rgba(148, 163, 184, 0.22);
            border-radius: 14px;
            bottom: 12px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.34);
            color: #f8fafc;
            display: block;
            left: 12px;
            max-width: min(420px, calc(100% - 24px));
            overflow: hidden;
            padding: 0;
            position: absolute;
            z-index: 5;
        }

        #customers-territory-main .territory-map-legend[data-expanded="false"] {
            max-width: min(315px, calc(100% - 24px));
        }

        #customers-territory-main .territory-map-legend-toggle {
            align-items: center;
            background: transparent;
            border: 0;
            color: inherit;
            cursor: pointer;
            display: flex;
            gap: 0.6rem;
            justify-content: space-between;
            min-height: 44px;
            padding: 0.58rem 0.68rem;
            text-align: left;
            width: 100%;
        }

        #customers-territory-main .territory-map-legend-toggle-main {
            display: grid;
            gap: 0.05rem;
            min-width: 0;
        }

        #customers-territory-main .territory-map-legend-toggle-main strong {
            font-size: 0.78rem;
            font-weight: 800;
            letter-spacing: 0.01em;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        #customers-territory-main .territory-map-legend-toggle-main small,
        #customers-territory-main .territory-map-legend-toggle-value {
            color: rgba(226, 232, 240, 0.78);
            font-size: 0.68rem;
            line-height: 1.2;
        }

        #customers-territory-main .territory-map-legend-toggle-value {
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 999px;
            flex: 0 0 auto;
            padding: 0.24rem 0.45rem;
            white-space: nowrap;
        }

        #customers-territory-main .territory-map-legend-toggle-icon {
            align-items: center;
            background: rgba(255, 255, 255, 0.12);
            border-radius: 999px;
            display: inline-flex;
            flex: 0 0 auto;
            font-style: normal;
            font-weight: 800;
            height: 24px;
            justify-content: center;
            line-height: 1;
            width: 24px;
        }

        #customers-territory-main .territory-map-legend-body {
            border-top: 1px solid rgba(148, 163, 184, 0.18);
            display: grid;
            gap: 0.45rem;
            padding: 0.66rem 0.76rem 0.76rem;
        }

        #customers-territory-main .territory-map-legend[data-expanded="false"] .territory-map-legend-body {
            display: none;
        }

        #customers-territory-main .territory-map-legend-desc {
            color: rgba(226, 232, 240, 0.82);
            font-size: 0.72rem;
            line-height: 1.3;
        }

        #customers-territory-main .territory-map-legend-scale,
        #customers-territory-main .territory-map-color-keys,
        #customers-territory-main .territory-map-legend-clients {
            align-items: center;
            display: flex;
            flex-wrap: wrap;
            gap: 0.45rem;
        }

        #customers-territory-main .territory-map-legend-scale span,
        #customers-territory-main .territory-map-color-key,
        #customers-territory-main .territory-map-legend-client {
            color: rgba(241, 245, 249, 0.88);
            font-size: 0.7rem;
        }

        #customers-territory-main .territory-map-legend-dot,
        #customers-territory-main .territory-map-legend-swatch,
        #customers-territory-main .territory-map-color-key i {
            border-radius: 999px;
            display: inline-block;
        }

        #customers-territory-main .territory-map-legend-dot {
            background: rgba(255, 255, 255, 0.55);
            border: 1px solid rgba(255, 255, 255, 0.85);
        }

        #customers-territory-main .territory-map-legend-dot-small { height: 12px; width: 12px; }
        #customers-territory-main .territory-map-legend-dot-large { height: 30px; width: 30px; }
        #customers-territory-main .territory-map-legend-swatch,
        #customers-territory-main .territory-map-color-key i { height: 10px; width: 10px; }

        #customers-territory-main .territory-map-color-key,
        #customers-territory-main .territory-map-legend-client {
            align-items: center;
            display: inline-flex;
            gap: 0.3rem;
        }

        #customers-territory-main .territory-map-legend-client {
            max-width: 190px;
            min-width: 0;
        }

        #customers-territory-main .territory-map-legend-client span {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        #customers-territory-main .territory-map-legend-client strong {
            color: #ffffff;
            font-weight: 800;
            white-space: nowrap;
        }

        #customers-territory-main .territory-info-window {
            color: #111827;
            display: grid;
            gap: 0.22rem;
            min-width: 240px;
        }

        #customers-territory-main .territory-info-window strong {
            font-size: 0.92rem;
        }

        #customers-territory-main .territory-info-window small,
        #customers-territory-main .territory-info-window span {
            display: block;
            font-size: 0.76rem;
        }

        @media (max-width: 1180px) {
            #customers-territory-main .territory-main-grid {
                grid-template-columns: minmax(0, 1fr) !important;
            }

            #customers-territory-main .territory-map-card,
            #customers-territory-main .territory-breakdown-card {
                height: auto !important;
                max-height: none !important;
                min-height: 0 !important;
            }

            #customers-territory-main .territory-bi-map-canvas,
            #customers-territory-main .territory-map-placeholder {
                height: var(--territory-bi-map-mobile-height) !important;
                min-height: var(--territory-bi-map-mobile-height) !important;
            }

            #customers-territory-main .territory-bi-breakdown-grid {
                height: auto !important;
                max-height: none !important;
                overflow: visible !important;
            }

            #customers-territory-main .territory-chip-list,
            #customers-territory-main .territory-metric-list {
                max-height: 430px !important;
            }
        }

        @media (max-width: 760px) {
            #customers-territory-main .territory-map-card,
            #customers-territory-main .territory-breakdown-card,
            #customers-territory-main .territory-table-card {
                max-width: 100% !important;
                width: 100% !important;
            }

            #customers-territory-main .territory-map-card-header {
                align-items: stretch !important;
            }

            #customers-territory-main .territory-map-header-tools {
                align-items: stretch !important;
                min-width: 0 !important;
                width: 100% !important;
            }

            #customers-territory-main .territory-map-mode-switch {
                display: grid !important;
                grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
                justify-content: stretch !important;
                width: 100% !important;
            }

            #customers-territory-main .territory-map-mode-switch .btn {
                justify-content: center !important;
                width: 100% !important;
            }

            #customers-territory-main .territory-bi-map-canvas,
            #customers-territory-main .territory-map-placeholder {
                height: 430px !important;
                min-height: 430px !important;
            }

            #customers-territory-main .territory-map-legend {
                bottom: 8px;
                left: 8px;
                max-width: calc(100% - 16px);
            }

            #customers-territory-main .territory-map-legend[data-expanded="false"] {
                max-width: min(300px, calc(100% - 16px));
            }

            #customers-territory-main .territory-map-legend-toggle {
                min-height: 42px;
                padding: 0.5rem 0.58rem;
            }

            #customers-territory-main .territory-map-legend-toggle-value,
            #customers-territory-main .territory-map-legend-clients {
                display: none;
            }

            #customers-territory-main .territory-map-legend-body {
                padding: 0.58rem 0.64rem 0.66rem;
            }

            #customers-territory-main .territory-bi-breakdown-grid {
                grid-template-columns: minmax(0, 1fr) !important;
                gap: 0.62rem !important;
                padding: 1rem !important;
            }

            #customers-territory-main .territory-chip-list,
            #customers-territory-main .territory-metric-list {
                max-height: none !important;
                overflow: visible !important;
                padding-right: 0 !important;
            }

            #customers-territory-main .territory-bi-chip-card {
                align-items: center !important;
                display: grid !important;
                gap: 0.45rem !important;
                grid-template-columns: minmax(0, 1fr) auto !important;
                min-height: 66px !important;
                padding: 0.58rem 0.72rem !important;
                width: 100% !important;
            }
            
            #customers-territory-main .territory-bi-chip-card > span {
                display: grid !important;
                gap: 0.12rem !important;
                min-width: 0 !important;
                overflow: hidden !important;
            }
            
            #customers-territory-main .territory-bi-chip-card > span > strong {
                display: block !important;
                font-size: 0.86rem !important;
                line-height: 1.16 !important;
                max-width: 100% !important;
                overflow-wrap: anywhere !important;
                white-space: normal !important;
            }
            
            #customers-territory-main .territory-bi-chip-card small {
                display: block !important;
                font-size: 0.7rem !important;
                line-height: 1.15 !important;
                max-width: 100% !important;
                overflow-wrap: anywhere !important;
                white-space: normal !important;
            }
            
            #customers-territory-main .territory-bi-chip-card .metric-value {
                align-self: center !important;
                font-size: 0.76rem !important;
                justify-self: end !important;
                line-height: 1.1 !important;
                max-width: 6.8rem !important;
                min-width: max-content !important;
                overflow: hidden !important;
                text-align: right !important;
                text-overflow: ellipsis !important;
                white-space: nowrap !important;
            }
        }
    </style>

    <script id="customerTerritoryPoints" type="application/json"><?php echo json_encode($mapPoints, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?></script>
    <script src="/assets/js/customer-territory-map.js?v=p18_bi_hard_layout_fix"></script>
</main>

<?php require_once '../../layouts/footer.php'; ?>
