<?php

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

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once __DIR__ . '/_customer_quick_fields.php';
require_once '../../services/crm/CrmService.php';
require_once '../../services/crm/PaymentStatusService.php';
require_once '../../services/crm/CustomerLifecycleService.php';

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

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

// Variable de control para auto-abrir modal de oportunidad recién creada
$openModalId = isset($_GET['open_modal']) ? (int) $_GET['open_modal'] : 0;

PaymentStatusService::processOverdueOpportunities(db());
$crm = new CrmService();

$customer = $crm->getCustomerById($id, true);

if (!$customer) {
    die('Cliente no encontrado.');
}

$isCustomerDeleted = !empty($customer['deleted_at']);
$lifecycle = new CustomerLifecycleService(db());
$customerHistoryCounts = $lifecycle->getHistoryCounts($id);

if (!$isCustomerDeleted && !empty($customer['customer_tax_id'])) {
    $crm->updateCustomerRestockFrequency($customer['id'], $customer['customer_tax_id']);
    // Refrescamos los datos de la variable para que la pantalla muestre el cálculo actualizado
    $customer = $crm->getCustomerById($id); 
}

$analytics = $crm->getCustomerAnalytics($customer['customer_tax_id']);
$factoSummary = $crm->getCustomerFactoSummary($customer['customer_tax_id']);
$opportunities = $crm->getCustomerOpportunities($id);
$openOpportunities = $crm->getCustomerOpenOpportunities($id);
$quotes = $crm->getCustomerQuotes($id, 30);
$pendingActions = $crm->getCustomerPendingActions($id);
$documents = $crm->getCustomerDocuments($id);
$activities = $crm->getCustomerActivities($id, 40);
$factoInvoices = $crm->getCustomerInvoicesFromFacto($customer['customer_tax_id'], 20);

// Variables para el Modal de Nueva Oportunidad
$assignableUsers = $crm->getAssignableUsers();
$currentUser = current_user();
$ownerValue = $currentUser['name'] ?? '';

$stages = ['nuevo' => 'Nuevo', 'contactado' => 'Contactado', 'cotizando' => 'Cotizando', 'negociacion' => 'Negociación', 'ganada' => 'Ganada', 'perdida' => 'Perdida', 'facturada' => 'Facturada'];
$paymentStatusOptions = ['no_facturado' => 'No facturado', 'por_cobrar' => 'Por cobrar', 'pagado' => 'Pagado', 'atrasado' => 'Atrasado', 'incobrable' => 'Incobrable'];
$sourceOptions = ['Instagram' => 'Instagram', 'Web' => 'Web', 'OpenLab' => 'OpenLab', 'Recomendación' => 'Recomendación', 'Email' => 'Email', 'Llamada' => 'Llamada', 'Distribuidor' => 'Distribuidor', 'Otro' => 'Otro'];
$competitorOptions = ['' => 'No identificado', 'Abstrax' => 'Abstrax', 'HopBurst' => 'HopBurst', 'Pellets' => 'Pellets', 'Proveedor tradicional' => 'Proveedor tradicional', 'Otro' => 'Otro'];
$nextActionOptions = ['' => 'Sin acción', 'Llamar' => 'Llamar', 'Enviar cotización' => 'Enviar cotización', 'Enviar muestra' => 'Enviar muestra', 'Agendar reunión' => 'Agendar reunión', 'Despachar' => 'Despachar', 'Hacer seguimiento' => 'Hacer seguimiento', 'Esperar respuesta' => 'Esperar respuesta'];

$quoteStatusClass = function ($status) {
    $status = strtolower(trim((string)$status));
    if (in_array($status, array('aceptada', 'pagada'), true)) return 'badge-success';
    if (in_array($status, array('enviada', 'facturada', 'esperando pago'), true)) return 'badge-warning';
    if (in_array($status, array('rechazada', 'anulada'), true)) return 'badge-error';
    return '';
};

$paymentStatusClass = function ($status) {
    $status = trim((string)$status);
    if ($status === 'pagado') return 'badge-success';
    if ($status === 'por_cobrar') return 'badge-warning';
    if (in_array($status, array('atrasado', 'incobrable'), true)) return 'badge-error';
    return '';
};

$factoDocTypeLabel = function ($code) {
    $code = trim((string)$code);
    $labels = array(
        '33' => 'Factura electrónica',
        '34' => 'Factura exenta',
        '39' => 'Boleta electrónica',
        '52' => 'Guía de despacho',
        '56' => 'Nota de débito',
        '61' => 'Nota de crédito'
    );
    return $labels[$code] ?? ('Tipo ' . ($code !== '' ? $code : 'S/I'));
};

$factoStatusLabel = function ($status) {
    $status = trim((string)$status);
    $labels = array(
        '0' => 'Borrador',
        '1' => 'Emitido',
        '2' => 'Anulado',
        '3' => 'Pagado'
    );
    return $labels[$status] ?? ($status !== '' ? $status : 'Sin estado');
};


$customerNameStr = !empty($customer['commercial_name']) ? $customer['commercial_name'] : $customer['customer_name'];
$customerHasCoordinates = !empty($customer['latitude']) && !empty($customer['longitude']) && is_numeric($customer['latitude']) && is_numeric($customer['longitude']);
$customerMapsQuery = $customerHasCoordinates
    ? trim((string)$customer['latitude']) . ',' . trim((string)$customer['longitude'])
    : trim(($customer['address'] ?? '') . ' ' . ($customer['district'] ?? '') . ' ' . ($customer['city'] ?? '') . ' ' . ($customer['region'] ?? '') . ' ' . ($customer['country'] ?? ''));

$page_title = 'Ficha Cliente';

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

?>

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

    <section class="content">

        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Cliente 360 comercial</span>
                <h2>
                    <?php echo safe_text($customerNameStr); ?>
                </h2>
                <p class="text-secondary">
                    <?php echo safe_text($customer['legal_name'] ?? ''); ?>
                    <?php if (!empty($customer['customer_tax_id'])): ?>
                        · <?php echo safe_text(format_rut($customer['customer_tax_id'])); ?>
                    <?php endif; ?>
                    <?php if (!empty($customer['city'])): ?>
                        · <?php echo safe_text($customer['city']); ?>
                    <?php endif; ?>
                </p>
            </div>

            <div class="cluster actions-cluster">
                <a class="btn btn-outline icon-btn-mobile" href="/modules/customers/" title="Volver a clientes">
                    <i data-lucide="chevron-left"></i>
                    <span class="mobile-hidden">Volver</span>
                </a>
                
                <?php if ($isCustomerDeleted): ?>
                    <form action="/modules/customers/customer_restore.php" method="POST" data-no-spa="true" style="margin:0;">
                        <input type="hidden" name="id" value="<?php echo (int) $customer['id']; ?>">
                        <button type="submit" class="btn btn-primary icon-btn-mobile" title="Reactivar cliente">
                            <i data-lucide="rotate-ccw"></i>
                            <span class="mobile-hidden">Reactivar</span>
                        </button>
                    </form>
                <?php else: ?>
                    <button class="btn btn-outline icon-btn-mobile" onclick="openEditCustomerModal()" title="Editar Cliente">
                        <i data-lucide="edit-3"></i>
                        <span class="mobile-hidden">Editar</span>
                    </button>

                    <button class="btn btn-primary icon-btn-mobile" onclick="openOpportunityModal()" title="Nueva oportunidad">
                        <i data-lucide="plus"></i>
                        <span class="mobile-hidden">Nueva oportunidad</span>
                    </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($isCustomerDeleted): ?>
            <div class="card" style="border-color: rgba(255, 77, 79, 0.45); background: rgba(255, 77, 79, 0.08); margin-bottom: var(--space-5);">
                <div class="cluster" style="align-items: flex-start; justify-content: space-between; gap: var(--space-4);">
                    <div>
                        <span class="label" style="color: var(--color-error);">Cliente desactivado</span>
                        <h3 style="margin: 4px 0 6px;">Historial comercial protegido</h3>
                        <p class="text-secondary" style="margin: 0;">
                            Este cliente no aparece en buscadores operativos ni puede recibir nuevas oportunidades o cotizaciones hasta ser reactivado.
                        </p>
                        <p class="text-muted text-sm" style="margin: 8px 0 0;">
                            Desactivado: <?php echo safe_text(date('d-m-Y H:i', strtotime($customer['deleted_at']))); ?>
                            <?php if (!empty($customer['deleted_by'])): ?> · Por: <?php echo safe_text($customer['deleted_by']); ?><?php endif; ?>
                            <?php if (!empty($customer['deleted_reason'])): ?> · Motivo: <?php echo safe_text($customer['deleted_reason']); ?><?php endif; ?>
                        </p>
                    </div>
                    <div class="cluster" style="gap: var(--space-2); flex-wrap: wrap; justify-content: flex-end;">
                        <span class="badge">Oportunidades: <?php echo (int) $customerHistoryCounts['opportunities']; ?></span>
                        <span class="badge">Cotizaciones: <?php echo (int) $customerHistoryCounts['quotes']; ?></span>
                        <span class="badge">Documentos: <?php echo (int) $customerHistoryCounts['documents']; ?></span>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php
        $nextRestock = $customer['next_restock_date'] ?? null;
        $restockStatus = 'success';
        $restockText = 'Al día';
        $daysLeft = 0;
        
        if ($nextRestock) {
            $today = new DateTime();
            $today->setTime(0, 0, 0); 
            
            $targetDate = new DateTime($nextRestock);
            $targetDate->setTime(0, 0, 0); 
            
            $diff = $today->diff($targetDate);
            $daysLeft = (int)$diff->format('%R%a'); 
        
            if ($daysLeft < 0) {
                $restockStatus = 'error'; 
                $restockText = '¡Atrasado por ' . abs($daysLeft) . ' días!';
            } elseif ($daysLeft <= 7) {
                $restockStatus = 'warning';
                $restockText = 'Llamar pronto (' . $daysLeft . ' días)';
            } else {
                $restockStatus = 'success';
                $restockText = 'Próxima en ' . $daysLeft . ' días';
            }
        } else {
            $restockText = 'Sin fecha calculada';
            $restockStatus = 'text-muted';
        }

        // Lectura estratégica comercial: cálculos agregados sin nuevas consultas.
        $todayDate = new DateTimeImmutable('today');
        $openPipelineValue = 0.0;
        $weightedPipelineValue = 0.0;
        $receivablePipelineValue = 0.0;
        $overduePipelineValue = 0.0;
        $overduePipelineCount = 0;

        foreach ($openOpportunities as $op) {
            $expectedValue = (float)($op['expected_value'] ?? 0);
            $probability = max(0, min(100, (float)($op['probability'] ?? 0)));
            $paymentStatus = $op['payment_status'] ?? 'no_facturado';
            $dueDateRaw = $op['payment_due_date'] ?? '';

            $openPipelineValue += $expectedValue;
            $weightedPipelineValue += $expectedValue * ($probability / 100);

            if (in_array($paymentStatus, array('por_cobrar', 'atrasado', 'incobrable'), true)) {
                $receivablePipelineValue += $expectedValue;
            }

            $isPaymentOverdue = in_array($paymentStatus, array('atrasado', 'incobrable'), true);
            if (!$isPaymentOverdue && !empty($dueDateRaw) && !in_array($paymentStatus, array('pagado', 'no_facturado'), true)) {
                try {
                    $dueDate = new DateTimeImmutable($dueDateRaw);
                    $isPaymentOverdue = $dueDate < $todayDate;
                } catch (Exception $e) {
                    $isPaymentOverdue = false;
                }
            }

            if ($isPaymentOverdue) {
                $overduePipelineCount++;
                $overduePipelineValue += $expectedValue;
            }
        }

        $nextPendingAction = $pendingActions[0] ?? null;
        foreach ($pendingActions as $actionCandidate) {
            if (empty($actionCandidate['next_action_date'])) continue;
            if ($nextPendingAction === null || empty($nextPendingAction['next_action_date']) || strtotime($actionCandidate['next_action_date']) < strtotime($nextPendingAction['next_action_date'])) {
                $nextPendingAction = $actionCandidate;
            }
        }

        $nextActionIsOverdue = false;
        if ($nextPendingAction && !empty($nextPendingAction['next_action_date'])) {
            try {
                $nextActionDate = new DateTimeImmutable($nextPendingAction['next_action_date']);
                $nextActionIsOverdue = $nextActionDate < $todayDate;
            } catch (Exception $e) {
                $nextActionIsOverdue = false;
            }
        }

        $latestQuote = $quotes[0] ?? null;
        $latestFactoInvoice = $factoInvoices[0] ?? null;
        $activeQuoteCount = 0;
        foreach ($quotes as $quoteCandidate) {
            $quoteStatus = $quoteCandidate['status'] ?? 'Borrador';
            if (!in_array($quoteStatus, array('Rechazada', 'Anulada'), true)) {
                $activeQuoteCount++;
            }
        }

        $strategicRiskClass = 'badge-success';
        $strategicRiskLabel = 'Cuenta estable';
        $strategicRecommendation = 'Mantener seguimiento comercial y detectar oportunidad de recompra.';

        if ($isCustomerDeleted) {
            $strategicRiskClass = 'badge-error';
            $strategicRiskLabel = 'Cliente desactivado';
            $strategicRecommendation = 'No crear nuevas gestiones hasta reactivar el cliente.';
        } elseif ($overduePipelineCount > 0) {
            $strategicRiskClass = 'badge-error';
            $strategicRiskLabel = 'Cobranza en riesgo';
            $strategicRecommendation = 'Priorizar cobranza antes de abrir nueva venta.';
        } elseif ($nextRestock && $daysLeft < 0) {
            $strategicRiskClass = 'badge-error';
            $strategicRiskLabel = 'Reposición atrasada';
            $strategicRecommendation = 'Contactar hoy y recuperar ciclo de consumo.';
        } elseif ($nextActionIsOverdue) {
            $strategicRiskClass = 'badge-warning';
            $strategicRiskLabel = 'Acción vencida';
            $strategicRecommendation = 'Regularizar seguimiento pendiente y actualizar próxima acción.';
        } elseif ($nextRestock && $daysLeft <= 7) {
            $strategicRiskClass = 'badge-warning';
            $strategicRiskLabel = 'Reposición próxima';
            $strategicRecommendation = 'Activar contacto preventivo para evitar quiebre de recompra.';
        } elseif (count($openOpportunities) > 0) {
            $strategicRiskClass = 'badge-warning';
            $strategicRiskLabel = 'Venta activa';
            $strategicRecommendation = 'Acelerar oportunidad abierta y cerrar próximo hito comercial.';
        }

        $nextMovementTitle = 'Sin acción pendiente';
        $nextMovementContext = 'Crear oportunidad o programar seguimiento si corresponde.';
        if ($nextPendingAction) {
            $nextMovementTitle = trim(($nextPendingAction['next_action'] ?? 'Seguimiento') . ' · ' . ($nextPendingAction['next_action_date'] ?? 'Sin fecha'));
            $nextMovementContext = trim(($nextPendingAction['title'] ?? '') . (!empty($nextPendingAction['owner_name']) ? ' · ' . $nextPendingAction['owner_name'] : ''));
        } elseif ($nextRestock) {
            $nextMovementTitle = $restockText;
            $nextMovementContext = 'Reposición estimada: ' . date('d-m-Y', strtotime($nextRestock));
        }

        $latestQuoteLabel = $latestQuote
            ? (($latestQuote['quote_number'] ?? 'Cotización') . ' · ' . ($latestQuote['status'] ?? 'Borrador') . ' · ' . clp($latestQuote['total'] ?? 0))
            : 'Sin cotización reciente';
        $latestFactoLabel = $latestFactoInvoice
            ? (($latestFactoInvoice['document_number'] ?? 'Documento') . ' · ' . clp($latestFactoInvoice['total_amount'] ?? 0))
            : 'Sin documento tributario reciente';
        ?>
        <section class="grid grid-4 customer-strategic-kpis">
            <article class="kpi-card" style="border-left: 4px solid var(--color-<?php echo $restockStatus; ?>);">
                <div class="kpi-label">Reposición / próxima acción</div>
                <div class="kpi-main" style="width: 100%; min-width: 0; overflow: hidden;">
                    <div class="kpi-value kpi-auto-shrink" style="color: var(--color-<?php echo $restockStatus; ?>);">
                        <?php echo safe_text($nextPendingAction ? ($nextPendingAction['next_action'] ?? 'Seguimiento') : $restockText); ?>
                    </div>
                </div>
                <p class="kpi-context">
                    <?php echo safe_text($nextPendingAction ? ($nextPendingAction['next_action_date'] ?? 'Sin fecha') : ($nextRestock ? 'Fecha ideal: ' . date('d-m-Y', strtotime($nextRestock)) : 'Fija ciclo o próxima acción')); ?>
                </p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Venta 12M</div>
                <div class="kpi-main" style="width: 100%; min-width: 0; overflow: hidden;">
                    <div class="kpi-value kpi-auto-shrink"><?php echo $analytics ? clp($analytics['sales_last_12m']) : '$0'; ?></div>
                </div>
                <p class="kpi-context">Valor comercial reciente</p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Pipeline abierto</div>
                <div class="kpi-main" style="width: 100%; min-width: 0; overflow: hidden;">
                    <div class="kpi-value kpi-auto-shrink"><?php echo clp($openPipelineValue); ?></div>
                </div>
                <p class="kpi-context"><?php echo count($openOpportunities); ?> oportunidades · ponderado <?php echo clp($weightedPipelineValue); ?></p>
            </article>

            <article class="kpi-card">
                <div class="kpi-label">Riesgo comercial</div>
                <div class="kpi-main" style="width: 100%; min-width: 0; overflow: hidden;">
                    <div class="kpi-value kpi-auto-shrink"><?php echo safe_text($strategicRiskLabel); ?></div>
                </div>
                <p class="kpi-context">Última compra: <?php echo !empty($factoSummary['last_document_date']) ? safe_text($factoSummary['last_document_date']) : 'sin registro'; ?></p>
            </article>
        </section>

        <section class="card customer-commercial-brief">
            <div class="card-header">
                <div>
                    <span class="label">BI comercial</span>
                    <h3>Lectura estratégica</h3>
                </div>
                <span class="badge <?php echo safe_text($strategicRiskClass); ?>"><?php echo safe_text($strategicRiskLabel); ?></span>
            </div>
            <div class="card-body">
                <div class="customer-brief-grid">
                    <article class="customer-brief-panel customer-brief-priority">
                        <span class="label">Prioridad recomendada</span>
                        <h4><?php echo safe_text($strategicRecommendation); ?></h4>
                        <p class="text-secondary text-sm">Decisión basada en reposición, cobranza, acciones pendientes y pipeline abierto.</p>
                    </article>
                    <article class="customer-brief-panel">
                        <span class="label">Próximo movimiento</span>
                        <h4><?php echo safe_text($nextMovementTitle); ?></h4>
                        <p class="text-secondary text-sm"><?php echo safe_text($nextMovementContext ?: 'Sin detalle operativo.'); ?></p>
                    </article>
                    <article class="customer-brief-panel">
                        <span class="label">Dinero en juego</span>
                        <h4><?php echo clp($openPipelineValue); ?> abierto</h4>
                        <p class="text-secondary text-sm">Ponderado: <?php echo clp($weightedPipelineValue); ?> · Por cobrar/atrasado: <?php echo clp($receivablePipelineValue); ?></p>
                    </article>
                    <article class="customer-brief-panel">
                        <span class="label">Actividad documentada</span>
                        <h4><?php echo safe_text($latestQuoteLabel); ?></h4>
                        <p class="text-secondary text-sm"><?php echo safe_text($latestFactoLabel); ?> · <?php echo $activeQuoteCount; ?> cotizaciones activas recientes</p>
                    </article>
                </div>
            </div>
        </section>

        <div class="mt-6"></div>

        <section class="grid grid-2">

            <article class="card customer-data-card">
                <div class="card-header">
                    <div>
                        <span class="label">Cliente</span>
                        <h3>Datos comerciales y tributarios</h3>
                    </div>
                </div>

                <div class="card-body">

                    <div class="metric-row">
                        <span>Nombre comercial</span>
                        <strong class="metric-value"><?php echo safe_text($customer['commercial_name'] ?? ''); ?></strong>
                    </div>

                    <div class="metric-row">
                        <span>Razón social</span>
                        <strong class="metric-value"><?php echo safe_text($customer['legal_name'] ?? ''); ?></strong>
                    </div>

                    <div class="metric-row">
                        <span>RUT</span>
                        <strong class="metric-value"><?php echo safe_text(format_rut($customer['customer_tax_id'] ?? '')); ?></strong>
                    </div>

                    <div class="metric-row">
                        <span>Giro</span>
                        <strong class="metric-value"><?php echo safe_text($customer['business_activity'] ?? ''); ?></strong>
                    </div>

                    <div class="metric-row">
                        <span>Condición de pago</span>
                        <strong class="metric-value"><?php echo safe_text(icylab_payment_terms_label($customer['payment_terms'] ?? ($customer['facto_payment_term'] ?? 'contado'))); ?></strong>
                    </div>

                    <div class="metric-row">
                        <span>Contacto</span>
                        <strong class="metric-value"><?php echo safe_text($customer['contact_name'] ?? ''); ?></strong>
                    </div>

                    <div class="metric-row" style="align-items: center;">
                        <span>Email</span>
                        <div class="metric-actions-value">
                            <strong class="metric-value"><?php echo safe_text($customer['email'] ?? ''); ?></strong>
                            <?php if (!empty($customer['email'])): ?>
                                <a href="mailto:<?php echo safe_text($customer['email']); ?>" class="btn btn-sm btn-outline" style="padding: 0 8px; height: 28px;" title="Enviar Email"><i data-lucide="mail" style="width:14px;height:14px;"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="metric-row" style="align-items: center;">
                        <span>Teléfono</span>
                        <div class="metric-actions-value">
                            <strong class="metric-value"><?php echo safe_text($customer['phone'] ?? ''); ?></strong>
                            <?php 
                            if (!empty($customer['phone'])): 
                                $cleanPhone = preg_replace('/[^0-9]/', '', $customer['phone']);
                                $waNumber = (strpos($cleanPhone, '56') === 0) ? $cleanPhone : '56' . $cleanPhone;
                            ?>
                                <a href="https://wa.me/<?php echo $waNumber; ?>" target="_blank" class="btn btn-sm btn-outline" style="padding: 0 8px; height: 28px; color: #25D366; border-color: #25D366;" title="Enviar WhatsApp">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
                                        <path d="M13.601 2.326A7.854 7.854 0 0 0 7.994 0C3.627 0 .068 3.558.064 7.926c0 1.399.366 2.76 1.057 3.965L0 16l4.204-1.102a7.933 7.933 0 0 0 3.79.965h.004c4.368 0 7.926-3.558 7.93-7.93A7.898 7.898 0 0 0 13.6 2.326zM7.994 14.521a6.573 6.573 0 0 1-3.356-.92l-.24-.144-2.494.654.666-2.433-.156-.251a6.56 6.56 0 0 1-1.007-3.505c0-3.626 2.957-6.584 6.591-6.584a6.56 6.56 0 0 1 4.66 1.931 6.557 6.557 0 0 1 1.928 4.66c-.004 3.639-2.961 6.592-6.592 6.592zm3.615-4.934c-.197-.099-1.17-.578-1.353-.646-.182-.065-.315-.099-.445.099-.133.197-.513.646-.627.775-.114.133-.232.148-.43.05-.197-.1-.836-.308-1.592-.985-.59-.525-.985-1.175-1.103-1.372-.114-.198-.011-.304.088-.403.087-.088.197-.232.296-.346.1-.114.133-.198.198-.33.065-.134.034-.248-.015-.347-.05-.099-.445-1.076-.612-1.47-.16-.389-.323-.335-.445-.34-.114-.007-.247-.007-.38-.007a.729.729 0 0 0-.529.247c-.182.198-.691.677-.691 1.654 0 .977.71 1.916.81 2.049.098.133 1.394 2.132 3.383 2.992.47.205.84.326 1.129.418.475.152.904.129 1.246.08.38-.058 1.171-.48 1.338-.943.164-.464.164-.86.114-.943-.049-.084-.182-.133-.38-.232z"/>
                                    </svg>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="metric-row">
                        <span>Dirección</span>
                        <strong class="metric-value"><?php echo safe_text($customer['address'] ?? ''); ?></strong>
                        <?php if ($customerMapsQuery !== ''): ?>
                            <a class="customer-map-link" href="https://www.google.com/maps/search/?api=1&amp;query=<?php echo urlencode($customerMapsQuery); ?>" target="_blank" rel="noopener" data-no-spa="true">
                                <i data-lucide="map-pin"></i> <?php echo $customerHasCoordinates ? 'Ver en Maps' : 'Buscar en Maps'; ?>
                            </a>
                        <?php endif; ?>
                    </div>

                    <?php if ($customerMapsQuery !== ''): ?>
                        <div class="customer-location-compact">
                            <div>
                                <span class="label">Ubicación</span>
                                <strong><?php echo safe_text(trim(($customer['district'] ?? '') . ' · ' . ($customer['city'] ?? '') . ' · ' . ($customer['region'] ?? '') . ' · ' . ($customer['country'] ?? ''), ' ·')); ?></strong>
                                <p class="text-muted text-sm"><?php echo $customerHasCoordinates ? 'Coordenadas disponibles' : 'Sin coordenadas guardadas'; ?>. Mapa embebido omitido para priorizar lectura comercial.</p>
                            </div>
                            <a class="btn btn-sm btn-outline" href="https://www.google.com/maps/search/?api=1&amp;query=<?php echo urlencode($customerMapsQuery); ?>" target="_blank" rel="noopener" data-no-spa="true">
                                <i data-lucide="map-pin"></i><span>Maps</span>
                            </a>
                        </div>
                    <?php endif; ?>

                    <div class="metric-row">
                        <span>Ciudad / Distrito</span>
                        <strong class="metric-value">
                            <?php echo safe_text(trim(($customer['city'] ?? '') . ' / ' . ($customer['district'] ?? ''), ' /')); ?>
                        </strong>
                    </div>

                </div>
            </article>

            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">Acciones pendientes</span>
                        <h3>Próximos movimientos</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Oportunidad</th>
                                    <th>Acción</th>
                                    <th>Fecha</th>
                                    <th>Responsable</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($pendingActions as $action): ?>
                                    <tr>
                                        <td>
                                            <a href="#" onclick="window.openOppViewModal(event, <?php echo (int) $action['id']; ?>); return false;">
                                                <?php echo safe_text($action['title']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo safe_text($action['next_action']); ?></td>
                                        <td><?php echo safe_text($action['next_action_date']); ?></td>
                                        <td><?php echo safe_text($action['owner_name']); ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($pendingActions)): ?>
                                    <tr>
                                        <td colspan="4">Sin acciones pendientes registradas.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

        </section>

        <div class="mt-8"></div>

        <section class="grid grid-2">

            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">CRM</span>
                        <h3>Oportunidades abiertas</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Oportunidad</th>
                                    <th>Etapa</th>
                                    <th>Cobranza</th>
                                    <th>Valor</th>
                                    <th>Prob.</th>
                                    <th>Venc. pago</th>
                                    <th>Cierre</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($openOpportunities as $opportunity): ?>
                                    <tr>
                                        <td>
                                            <a href="#" onclick="window.openOppViewModal(event, <?php echo (int) $opportunity['id']; ?>); return false;">
                                                <?php echo safe_text($opportunity['title']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo safe_text($stages[$opportunity['stage']] ?? $opportunity['stage']); ?></td>
                                        <td>
                                            <?php $ps = $opportunity['payment_status'] ?? 'no_facturado'; ?>
                                            <span class="badge <?php echo safe_text($paymentStatusClass($ps)); ?>">
                                                <?php echo safe_text($paymentStatusOptions[$ps] ?? $ps); ?>
                                            </span>
                                        </td>
                                        <td><?php echo clp($opportunity['expected_value']); ?></td>
                                        <td><?php echo (int) $opportunity['probability']; ?>%</td>
                                        <td><?php echo !empty($opportunity['payment_due_date']) ? safe_text($opportunity['payment_due_date']) : '—'; ?></td>
                                        <td><?php echo safe_text($opportunity['expected_close_date']); ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($openOpportunities)): ?>
                                    <tr>
                                        <td colspan="7">Sin oportunidades abiertas.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">CRM</span>
                        <h3>Historial de oportunidades</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Oportunidad</th>
                                    <th>Etapa</th>
                                    <th>Cobranza</th>
                                    <th>Valor</th>
                                    <th>Actualizada</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($opportunities as $opportunity_hist): ?>
                                    <tr>
                                        <td>
                                            <a href="#" onclick="window.openOppViewModal(event, <?php echo (int) $opportunity_hist['id']; ?>); return false;">
                                                <?php echo safe_text($opportunity_hist['title']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo safe_text($stages[$opportunity_hist['stage']] ?? $opportunity_hist['stage']); ?></td>
                                        <td>
                                            <?php $psHist = $opportunity_hist['payment_status'] ?? 'no_facturado'; ?>
                                            <span class="badge <?php echo safe_text($paymentStatusClass($psHist)); ?>">
                                                <?php echo safe_text($paymentStatusOptions[$psHist] ?? $psHist); ?>
                                            </span>
                                        </td>
                                        <td><?php echo clp($opportunity_hist['expected_value']); ?></td>
                                        <td><?php echo safe_text($opportunity_hist['updated_at']); ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($opportunities)): ?>
                                    <tr>
                                        <td colspan="5">Sin oportunidades registradas.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

        </section>

        <div class="mt-8"></div>

        <section class="grid grid-2">

            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">CRM</span>
                        <h3>Cotizaciones asociadas</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Folio</th>
                                    <th>Estado</th>
                                    <th>Oportunidad</th>
                                    <th>Total</th>
                                    <th>PDF</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($quotes as $quoteRow): ?>
                                    <tr>
                                        <td><?php echo !empty($quoteRow['created_at']) ? safe_text(date('d-m-Y', strtotime($quoteRow['created_at']))) : '—'; ?></td>
                                        <td><?php echo safe_text($quoteRow['quote_number']); ?></td>
                                        <td>
                                            <span class="badge <?php echo safe_text($quoteStatusClass($quoteRow['status'] ?? 'Borrador')); ?>">
                                                <?php echo safe_text($quoteRow['status'] ?? 'Borrador'); ?>
                                            </span>
                                        </td>
                                        <td><?php echo safe_text($quoteRow['opportunity_title'] ?? 'Venta directa'); ?></td>
                                        <td><?php echo clp($quoteRow['total'] ?? 0); ?></td>
                                        <td>
                                            <a class="btn btn-sm btn-outline" href="/modules/crm/quote_view.php?id=<?php echo (int)$quoteRow['id']; ?>" target="_blank">
                                                Ver
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($quotes)): ?>
                                    <tr>
                                        <td colspan="6">Sin cotizaciones asociadas.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">FACTO</span>
                        <h3>Documentos tributarios</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Folio</th>
                                    <th>Tipo SII</th>
                                    <th>Estado</th>
                                    <th>Neto</th>
                                    <th>Total</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($factoInvoices as $doc): ?>
                                    <tr>
                                        <td><?php echo safe_text($doc['issue_date']); ?></td>
                                        <td><?php echo safe_text($doc['document_number']); ?></td>
                                        <td><?php echo safe_text($factoDocTypeLabel($doc['document_type_taxbureau'] ?? '')); ?></td>
                                        <td><span class="badge"><?php echo safe_text($factoStatusLabel($doc['document_status'] ?? '')); ?></span></td>
                                        <td><?php echo clp($doc['net_amount']); ?></td>
                                        <td><?php echo clp($doc['total_amount']); ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($factoInvoices)): ?>
                                    <tr>
                                        <td colspan="6">Sin documentos FACTO asociados por RUT.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <?php if (!empty($documents)): ?>
            <article class="card">
                <div class="card-header">
                    <div>
                        <span class="label">CRM</span>
                        <h3>Documentos cargados</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="table-wrap table-scroll-y">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Tipo</th>
                                    <th>Número</th>
                                    <th>Nombre</th>
                                    <th>Neto</th>
                                    <th>Archivo</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php foreach ($documents as $document): ?>
                                    <tr>
                                        <td><?php echo safe_text($document['document_date']); ?></td>
                                        <td><?php echo safe_text($document['document_type']); ?></td>
                                        <td><?php echo safe_text($document['document_number']); ?></td>
                                        <td><?php echo safe_text($document['document_name']); ?></td>
                                        <td><?php echo clp($document['net_amount']); ?></td>
                                        <td>
                                            <?php if (!empty($document['file_path'])): ?>
                                                <a class="btn btn-sm btn-outline" href="<?php echo safe_text($document['file_path']); ?>" target="_blank">
                                                    Ver PDF
                                                </a>
                                            <?php else: ?>
                                                —
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>

                            </tbody>
                        </table>
                    </div>
                </div>
            </article>
            <?php endif; ?>

        </section>

        <div class="mt-8"></div>

        <section class="card">
            <div class="card-header">
                <div>
                    <span class="label">Timeline</span>
                    <h3>Historial comercial del cliente</h3>
                </div>
            </div>

           <div class="card-body">
                <div class="crm-timeline-scroll">
                    <div class="crm-timeline">
                        <?php foreach ($activities as $activity): ?>
                            <div class="crm-timeline-item">
                                <span class="crm-timeline-dot <?php echo safe_text($activity['activity_type']); ?>"></span>
    
                                <div>
                                    <strong><?php echo safe_text($activity['title']); ?></strong>
    
                                    <?php if (!empty($activity['description'])): ?>
                                        <p class="text-secondary text-sm">
                                            <?php echo nl2br(safe_text($activity['description'])); ?>
                                        </p>
                                    <?php endif; ?>
    
                                    <span class="text-muted text-sm">
                                        <?php echo safe_text($activity['activity_date']); ?>
                                        <?php if (!empty($activity['owner_name'])): ?>
                                            · <?php echo safe_text($activity['owner_name']); ?>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        <?php endforeach; ?>
    
                        <?php if (empty($activities)): ?>
                            <p class="text-secondary">Sin actividades registradas para este cliente.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </section>

    </section>

    <div id="customerEditModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            <div class="product-modal-header">
                <div>
                    <h2 class="h3">Editar Cliente</h2>
                    <span class="text-secondary text-sm">Actualiza los datos comerciales</span>
                </div>
                <button type="button" class="icon-btn" onclick="window.closeEditCustomerModal()"><i data-lucide="x"></i></button>
            </div>
            
            <div class="product-modal-body">
                <form id="form-edit-customer" action="/modules/customers/customer_update.php" method="POST" data-no-spa="true" style="margin:0;">
                    <input type="hidden" name="id" value="<?php echo (int) $customer['id']; ?>">
                    <div class="form-grid form-grid-2">
                        <div class="form-field is-required">
                            <label class="label">Razón social / Cliente</label>
                            <input class="input" type="text" name="customer_name" required value="<?php echo safe_text($customer['customer_name'] ?? ''); ?>">
                        </div>
                        <div class="form-field">
                            <label class="label">Nombre comercial</label>
                            <input class="input" type="text" name="commercial_name" value="<?php echo safe_text($customer['commercial_name'] ?? ''); ?>">
                        </div>
                        <div class="form-field">
                            <label class="label">RUT</label>
                            <input class="input" type="text" id="editCustomerTaxId" name="customer_tax_id" value="<?php echo safe_text($customer['customer_tax_id'] ?? ''); ?>" maxlength="12">
                        </div>
                        <div class="form-field">
                            <label class="label">Contacto principal</label>
                            <input class="input" type="text" name="contact_name" value="<?php echo safe_text($customer['contact_name'] ?? ''); ?>">
                        </div>
                        <div class="form-field">
                            <label class="label">Email</label>
                            <input class="input" type="email" name="email" value="<?php echo safe_text($customer['email'] ?? ''); ?>">
                        </div>
                        <div class="form-field">
                            <label class="label">Teléfono</label>
                            <div style="display: flex; gap: 8px;">
                                <select id="edit_phone_prefix" class="input" style="width: 110px; flex-shrink: 0; padding: 0 4px; appearance: auto;">
                                    <option value="+56" selected>🇨🇱 +56</option>
                                    <option value="+54">🇦🇷 +54</option>
                                    <option value="+51">🇵🇪 +51</option>
                                    <option value="+52">🇲🇽 +52</option>
                                    <option value="+57">🇨🇴 +57</option>
                                    <option value="+34">🇪🇸 +34</option>
                                    <option value="+1">🇺🇸 +1</option>
                                </select>
                                <input class="input" type="text" id="edit_phone_number" placeholder="9 1234 5678" style="flex: 1;">
                                <input type="hidden" name="phone" id="edit_real_phone_input" value="<?php echo safe_text($customer['phone'] ?? ''); ?>">
                            </div>
                        </div>
                        <div class="form-field">
                            <label class="label">Condición de pago</label>
                            <?php icylab_render_payment_terms_select('payment_terms', $customer['payment_terms'] ?? ($customer['facto_payment_term'] ?? 'contado'), false); ?>
                        </div>
                        <div class="form-field">
                            <label class="label">Ciclo de Reposición (Días)</label>
                            <input class="input" type="number" name="restock_days" min="0" value="<?php echo (int)($customer['restock_days'] ?? 0); ?>">
                        </div>
                        <div class="form-field is-required">
                            <label class="label">País</label>
                            <?php icylab_render_country_select('country', $customer['country'] ?? 'Chile', true); ?>
                        </div>
                        <div class="form-field form-field-full location-autocomplete-wrap is-required">
                            <label class="label">Dirección / ubicación</label>
                            <input class="input" type="text" name="address" data-location-autocomplete="true" value="<?php echo safe_text($customer['address'] ?? ''); ?>" placeholder="Ej: Pasaje Lovera s/n, Valdivia" required>
                            <input type="hidden" name="latitude" value="<?php echo safe_text($customer['latitude'] ?? ''); ?>">
                            <input type="hidden" name="longitude" value="<?php echo safe_text($customer['longitude'] ?? ''); ?>">
                            <input type="hidden" name="geocode_status" value="<?php echo safe_text($customer['geocode_status'] ?? 'pending'); ?>">
                            <input type="hidden" name="geocode_source" value="<?php echo safe_text($customer['geocode_source'] ?? ''); ?>">
                            <input type="hidden" name="geocode_query" value="<?php echo safe_text($customer['geocode_query'] ?? ''); ?>">
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Comuna</label>
                            <input class="input" type="text" name="district" value="<?php echo safe_text($customer['district'] ?? ''); ?>" required>
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Ciudad</label>
                            <input class="input" type="text" name="city" value="<?php echo safe_text($customer['city'] ?? ''); ?>" required>
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Región</label>
                            <input class="input" type="text" name="region" value="<?php echo safe_text($customer['region'] ?? ''); ?>" required>
                        </div>
                    </div>
                </form>
            </div>

            <div class="product-modal-footer" style="justify-content: space-between; align-items: center;">
                <form class="modal-footer-actions-left" action="/modules/customers/customer_delete.php" method="POST" data-no-spa="true" onsubmit="return confirm('Este cliente será desactivado. El historial comercial se conservará. ¿Continuar?');" style="margin:0;">
                    <input type="hidden" name="id" value="<?php echo (int) $customer['id']; ?>">
                    <input type="hidden" name="reason" value="Desactivación manual desde ficha de cliente">
                    <button type="submit" class="btn btn-outline btn-delete-mobile" style="color: var(--color-error); border-color: var(--color-error);" title="Desactivar cliente">
                        <i data-lucide="archive-x"></i><span class="mobile-hidden">Desactivar</span>
                    </button>
                </form>
                
                <div class="modal-footer-actions-right">
                    <button type="button" class="btn btn-outline" onclick="window.closeEditCustomerModal()">Cancelar</button>
                    <button type="submit" form="form-edit-customer" class="btn btn-primary">
                        <i data-lucide="save"></i><span>Guardar&nbsp;<span class="mobile-hidden">Cambios</span></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="opportunityModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            <div class="product-modal-header">
                <div>
                    <h2 class="h3">Crear Nueva Oportunidad</h2>
                    <span class="text-secondary text-sm">Ingresa los datos para sumar al embudo</span>
                </div>
                <button type="button" class="icon-btn" onclick="window.closeOpportunityModal()"><i data-lucide="x"></i></button>
            </div>
            <div class="product-modal-body">
                <form id="form-create-opportunity" action="/modules/crm/opportunity_store.php" method="POST" data-no-spa="true" style="margin: 0;">
                    
                    <input type="hidden" name="customer_id" value="<?php echo (int) $customer['id']; ?>">
                    
                    <div class="form-grid form-grid-2 mb-4">
                        <div class="form-field">
                            <label class="label">Cliente</label>
                            <input class="input" type="text" value="<?php echo safe_text($customerNameStr); ?>" disabled style="background: var(--surface-2);">
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Título de la oportunidad</label>
                            <input class="input" type="text" name="title" required placeholder="Ej: Venta de Insumos Q3">
                        </div>
                    </div>

                    <div class="form-grid form-grid-4">
                        <div class="form-field is-required"><label class="label">Etapa inicial</label><select class="select" name="stage" required><?php foreach ($stages as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Estado de cobranza</label><select class="select" name="payment_status"><?php foreach ($paymentStatusOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Fecha vencimiento pago</label><input class="input" type="date" name="payment_due_date"></div>
                        <div class="form-field"><label class="label">Fecha de pago</label><input class="input" type="date" name="payment_paid_date"></div>
                        <div class="form-field"><label class="label">Responsable comercial</label><select class="select" name="owner_name"><option value="">Sin responsable</option><?php foreach ($assignableUsers as $user): ?><option value="<?php echo safe_text($user['name']); ?>" <?php echo $user['name'] === $ownerValue ? 'selected' : ''; ?>><?php echo safe_text($user['name']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field is-required"><label class="label">Origen</label><select class="select" name="source" required><option value="" disabled selected>Seleccionar origen</option><?php foreach ($sourceOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Competidor / Alternativa</label><select class="select" name="competitor"><?php foreach ($competitorOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Valor esperado ($)</label><input class="input" type="number" name="expected_value" min="0" step="1" placeholder="Ej: 500000"></div>
                        <div class="form-field"><label class="label">Probabilidad (%)</label><input class="input" type="number" name="probability" min="0" max="100" value="20"></div>
                        <div class="form-field is-required"><label class="label">Fecha est. de cierre</label><input class="input" type="date" name="expected_close_date" required></div>
                        <div class="form-field is-required"><label class="label">Próxima acción</label><select class="select" name="next_action" required><?php foreach ($nextActionOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field is-required"><label class="label">Fecha próxima acción</label><input class="input" type="date" name="next_action_date" required></div>
                        <div class="form-field form-field-full"><label class="label">Notas iniciales</label><textarea class="textarea" name="notes" placeholder="Escribe aquí..."></textarea></div>
                    </div>
                </form>
            </div>
            <div class="product-modal-footer" style="justify-content: flex-end;">
                <div class="modal-footer-actions-right">
                    <button type="button" class="btn btn-outline" onclick="window.closeOpportunityModal()"><i data-lucide="x"></i><span>Cancelar</span></button>
                    <button type="submit" form="form-create-opportunity" class="btn btn-primary" id="saveOpportunityBtn">
                        <i data-lucide="save"></i><span>Crear&nbsp;<span class="mobile-hidden">Oportunidad</span></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <style>
    /* ==========================================================================
       CLIENTE 360 COMERCIAL - lectura estratégica y UX móvil de ficha
       No modifica modales.
       ========================================================================== */
    #customer-view-main .customer-strategic-kpis {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: var(--space-4);
        margin-bottom: var(--space-5);
    }

    #customer-view-main .customer-commercial-brief {
        border-color: rgba(0, 255, 48, 0.18);
        background: linear-gradient(180deg, var(--surface-1), var(--surface-0));
    }

    #customer-view-main .customer-commercial-brief .card-header {
        align-items: center;
    }

    #customer-view-main .customer-brief-grid {
        display: grid;
        grid-template-columns: 1.15fr 1fr 1fr 1fr;
        gap: var(--space-3);
    }

    #customer-view-main .customer-brief-panel {
        min-width: 0;
        padding: var(--space-4);
        border: 1px solid var(--border-subtle);
        border-radius: var(--radius-xl);
        background: var(--surface-1);
        display: flex;
        flex-direction: column;
        gap: 6px;
    }

    #customer-view-main .customer-brief-panel h4 {
        margin: 0;
        font-size: 1rem;
        line-height: 1.22;
    }

    #customer-view-main .customer-brief-panel p {
        margin: 0;
        line-height: 1.35;
    }

    #customer-view-main .customer-brief-priority {
        border-color: rgba(0, 255, 48, 0.22);
        background: var(--color-primary-soft);
    }

    #customer-view-main .customer-location-compact {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: var(--space-3);
        margin: 10px 0 12px;
        padding: 12px;
        border: 1px solid var(--border-subtle);
        border-radius: var(--radius-lg);
        background: var(--surface-2);
    }

    #customer-view-main .customer-location-compact strong,
    #customer-view-main .customer-location-compact p {
        display: block;
        margin: 0;
    }

    #customer-view-main .customer-location-compact .btn {
        flex: 0 0 auto;
        height: 36px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
    }

    #customer-view-main .table-scroll-y {
        max-height: min(48dvh, 420px);
        overflow-y: auto;
        overflow-x: hidden;
        -webkit-overflow-scrolling: touch;
    }

    #customer-view-main .crm-timeline-scroll {
        max-height: min(58dvh, 560px);
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }

    #customer-view-main .customer-data-card .metric-row {
        display: grid;
        grid-template-columns: minmax(128px, 34%) minmax(0, 1fr);
        align-items: start;
        column-gap: 16px;
        row-gap: 6px;
    }

    #customer-view-main .customer-data-card .metric-row > span:first-child {
        min-width: 0;
        text-align: left;
        line-height: 1.35;
    }

    #customer-view-main .customer-data-card .metric-value {
        display: block;
        min-width: 0;
        max-width: 100%;
        text-align: right;
        line-height: 1.35;
        white-space: normal;
        overflow-wrap: anywhere;
        word-break: break-word;
        font-family: var(--font-sans, inherit);
        font-weight: 700;
        letter-spacing: 0;
    }

    #customer-view-main .customer-data-card .metric-actions-value {
        min-width: 0;
        max-width: 100%;
        justify-self: end;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 8px;
    }

    #customer-view-main .customer-data-card .metric-actions-value .metric-value {
        flex: 1 1 auto;
    }

    #customer-view-main .customer-data-card .metric-actions-value .btn {
        flex: 0 0 auto;
    }

    #customer-view-main .customer-data-card .customer-map-link {
        grid-column: 2 / 3;
        justify-self: end;
        margin-top: 4px;
        text-align: right;
    }

    @media (max-width: 1180px) {
        #customer-view-main .customer-strategic-kpis,
        #customer-view-main .customer-brief-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
    }

    @media (max-width: 760px) {
        #customer-view-main > .content,
        #customer-view-main .content {
            padding-left: 12px !important;
            padding-right: 12px !important;
        }

        #customer-view-main .customer-strategic-kpis {
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: 10px !important;
            margin-bottom: 12px !important;
        }

        #customer-view-main .customer-strategic-kpis .kpi-card {
            min-height: 98px !important;
            padding: 12px !important;
        }

        #customer-view-main .customer-commercial-brief .card-header {
            display: flex !important;
            flex-direction: row !important;
            align-items: flex-start !important;
            gap: 10px !important;
        }

        #customer-view-main .customer-commercial-brief .card-header .badge {
            flex: 0 0 auto;
            max-width: 44%;
            white-space: normal;
            text-align: center;
        }

        #customer-view-main .customer-brief-grid {
            grid-template-columns: 1fr !important;
            gap: 10px !important;
        }

        #customer-view-main .customer-brief-panel {
            padding: 12px !important;
        }

        #customer-view-main .content > .grid.grid-2 {
            grid-template-columns: 1fr !important;
            gap: 12px !important;
        }

        #customer-view-main .content > .mt-8,
        #customer-view-main .content > .mt-6 {
            margin-top: 12px !important;
        }

        #customer-view-main .card {
            border-radius: var(--radius-xl) !important;
            overflow: hidden;
        }

        #customer-view-main .card-header {
            padding: 14px !important;
        }

        #customer-view-main .card-body {
            padding: 14px !important;
        }

        #customer-view-main .customer-data-card .metric-row {
            grid-template-columns: minmax(104px, 30%) minmax(0, 1fr) !important;
            column-gap: 12px !important;
            row-gap: 6px !important;
        }

        #customer-view-main .customer-data-card .metric-value {
            font-size: 0.96rem !important;
            font-weight: 650 !important;
        }

        #customer-view-main .customer-data-card .metric-actions-value {
            gap: 6px !important;
        }

        #customer-view-main .customer-location-compact {
            align-items: stretch !important;
            flex-direction: column !important;
        }

        #customer-view-main .customer-location-compact .btn {
            width: 100% !important;
        }

        #customer-view-main .table-scroll-y {
            max-height: min(44dvh, 360px) !important;
            overflow-y: auto !important;
            overflow-x: auto !important;
        }

        #customer-view-main .table-scroll-y .table {
            min-width: 620px;
        }

        #customer-view-main .table-scroll-y .table th,
        #customer-view-main .table-scroll-y .table td {
            font-size: 0.78rem;
            padding: 9px 8px;
            vertical-align: middle;
        }

        #customer-view-main .crm-timeline-scroll {
            max-height: min(48dvh, 420px) !important;
        }
    }

    /* ==========================================================================
       MODALES Y COMPORTAMIENTO
       ========================================================================== */
    .product-modal-backdrop {
        position: fixed; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(4px);
        z-index: 1050; display: none; align-items: center; justify-content: center;
        opacity: 0; transition: opacity 0.2s ease;
    }
    .product-modal-backdrop.show { opacity: 1; }
    .product-modal-box {
        background: var(--surface-1); width: 980px; max-width: min(96vw, 980px); max-height: 90vh;
        border: 1px solid var(--border-default); border-radius: var(--radius-xl); 
        box-shadow: var(--shadow-lg); display: flex; flex-direction: column;
        transform: translateY(20px); transition: transform 0.2s ease;
    }
    .product-modal-backdrop.show .product-modal-box { transform: translateY(0); }
    .product-modal-header { padding: var(--space-5); border-bottom: 1px solid var(--border-subtle); display: flex; justify-content: space-between; }
    .product-modal-body { padding: var(--space-5); overflow-y: auto; flex: 1; }
    .product-modal-footer { padding: var(--space-4) var(--space-5); border-top: 1px solid var(--border-subtle); display: flex; background: var(--surface-0); border-radius: 0 0 var(--radius-xl) var(--radius-xl); }

    /* ==========================================================================
       COMPORTAMIENTO MÓVIL GENERAL (< 760px)
       ========================================================================== */
    @media (max-width: 760px) {
        .page-header {
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            justify-content: space-between !important;
            align-items: flex-start !important;
        }
        .page-header-content {
            flex: 1;
            min-width: 0; 
            padding-right: 12px;
        }
        .page-header-content h2 {
            font-size: 1.35rem !important;
            line-height: 1.2 !important;
            margin-bottom: 4px !important;
            word-break: break-word;
        }
        .actions-cluster {
            flex-shrink: 0; 
            display: flex !important;
            gap: 8px !important;
        }
        .mobile-hidden { display: none !important; }
        .icon-btn-mobile {
            padding: 0 !important; width: 44px; height: 44px;
            display: flex; align-items: center; justify-content: center;
        }
        .product-modal-footer {
            display: flex !important;
            flex-direction: row !important;
            justify-content: space-between !important;
            align-items: center !important;
            gap: 8px !important;
            padding: var(--space-3) var(--space-4) !important;
        }
        .btn-delete-mobile {
            padding: 0 !important;
            width: 42px !important;
            height: 42px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }
        .modal-footer-actions-right {
            display: flex !important;
            gap: 8px !important;
            justify-content: flex-end !important;
            flex: 1;
        }
        .modal-footer-actions-right .btn {
            padding: 0 var(--space-3) !important;
            height: 42px !important;
            font-size: 0.85rem !important;
            white-space: nowrap !important;
        }
    }


    /* =========================================================
       P23 - Ficha cliente: modales homologados a Cotizaciones final
       Aplica a editar cliente y crear oportunidad desde cliente.
       Header/footer fijos; body con scroll interno; footer estable.
       ========================================================= */
    #customer-view-main #customerEditModal.product-modal-backdrop,
    #customer-view-main #opportunityModal.product-modal-backdrop {
        position: fixed !important;
        inset: 0 !important;
        display: none;
        align-items: center !important;
        justify-content: center !important;
        padding: 24px !important;
        overflow: hidden !important;
        background: rgba(0, 0, 0, 0.68) !important;
        backdrop-filter: blur(5px) !important;
        z-index: 1050 !important;
        opacity: 0;
        transition: opacity 0.2s ease !important;
    }

    #customer-view-main #customerEditModal.product-modal-backdrop.show,
    #customer-view-main #opportunityModal.product-modal-backdrop.show {
        display: flex !important;
        opacity: 1 !important;
    }

    #customer-view-main #customerEditModal > .product-modal-box,
    #customer-view-main #opportunityModal > .product-modal-box {
        width: min(980px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        height: min(700px, calc(100dvh - 100px)) !important;
        min-height: min(700px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 100px) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        border-radius: var(--radius-xl) !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        box-shadow: var(--shadow-lg) !important;
    }

    #customer-view-main #customerEditModal .product-modal-header,
    #customer-view-main #opportunityModal .product-modal-header {
        flex: 0 0 auto !important;
        min-height: 78px !important;
        padding: 20px 24px !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: flex-start !important;
        justify-content: space-between !important;
        gap: 14px !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        background: var(--surface-1) !important;
    }

    #customer-view-main #customerEditModal .product-modal-body,
    #customer-view-main #opportunityModal .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        padding: 20px 24px !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior: contain !important;
    }

    #customer-view-main #customerEditModal .product-modal-footer,
    #customer-view-main #opportunityModal .product-modal-footer {
        flex: 0 0 auto !important;
        min-height: 76px !important;
        height: auto !important;
        max-height: none !important;
        padding: 14px 20px !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        background: var(--surface-0) !important;
        border-top: 1px solid var(--border-subtle) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
        overflow: visible !important;
    }

    #customer-view-main #customerEditModal .product-modal-footer:has(.modal-footer-actions-left:not(:empty)) {
        justify-content: space-between !important;
    }

    #customer-view-main #customerEditModal .modal-footer-actions-left {
        flex: 0 0 auto !important;
        min-width: 48px !important;
        margin-right: auto !important;
        display: flex !important;
        align-items: center !important;
        justify-content: flex-start !important;
        gap: 8px !important;
        overflow: visible !important;
    }

    #customer-view-main #customerEditModal .modal-footer-actions-right,
    #customer-view-main #opportunityModal .modal-footer-actions-right {
        flex: 0 1 auto !important;
        width: auto !important;
        min-width: 0 !important;
        margin-left: auto !important;
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        overflow: visible !important;
        flex-wrap: nowrap !important;
    }

    #customer-view-main #customerEditModal .product-modal-footer .btn,
    #customer-view-main #opportunityModal .product-modal-footer .btn {
        width: auto !important;
        min-width: 118px !important;
        max-width: none !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 18px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        flex: 0 0 auto !important;
        white-space: nowrap !important;
        text-align: center !important;
        overflow: visible !important;
        text-overflow: clip !important;
        border-radius: var(--radius-lg) !important;
    }

    #customer-view-main #customerEditModal .product-modal-footer .btn-primary,
    #customer-view-main #opportunityModal .product-modal-footer .btn-primary,
    #customer-view-main #opportunityModal #saveOpportunityBtn {
        min-width: 178px !important;
    }

    #customer-view-main #customerEditModal .product-modal-footer .btn span,
    #customer-view-main #opportunityModal .product-modal-footer .btn span {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        min-width: 0 !important;
        max-width: none !important;
        overflow: visible !important;
        text-overflow: clip !important;
        white-space: nowrap !important;
        text-align: center !important;
    }

    /* Desktop: botón destructivo con icono + texto */
    #customer-view-main #customerEditModal .btn-delete-mobile,
    #customer-view-main #customerEditModal .modal-footer-actions-left .btn {
        width: auto !important;
        min-width: 132px !important;
        max-width: none !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 18px !important;
        flex: 0 0 auto !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        color: var(--color-error) !important;
        border-color: rgba(255, 77, 79, 0.58) !important;
        background: rgba(255, 77, 79, 0.06) !important;
        white-space: nowrap !important;
    }
    
    #customer-view-main #customerEditModal .btn-delete-mobile span,
    #customer-view-main #customerEditModal .modal-footer-actions-left .btn span {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
    }

    #customer-view-main #customerEditModal .btn-delete-mobile svg,
    #customer-view-main #customerEditModal .modal-footer-actions-left .btn svg {
        color: var(--color-error) !important;
        stroke: var(--color-error) !important;
    }

    @media (max-width: 760px) {
        #customer-view-main #customerEditModal.product-modal-backdrop,
        #customer-view-main #opportunityModal.product-modal-backdrop {
            align-items: center !important;
            justify-content: center !important;
            padding: 12px !important;
        }

        #customer-view-main #customerEditModal > .product-modal-box,
        #customer-view-main #opportunityModal > .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }

        #customer-view-main #customerEditModal .product-modal-header,
        #customer-view-main #opportunityModal .product-modal-header {
            min-height: 64px !important;
            padding: 14px !important;
            align-items: flex-start !important;
            gap: 10px !important;
        }

        #customer-view-main #customerEditModal .product-modal-header .h3,
        #customer-view-main #customerEditModal .product-modal-header h2,
        #customer-view-main #opportunityModal .product-modal-header .h3,
        #customer-view-main #opportunityModal .product-modal-header h2 {
            font-size: 1.05rem !important;
            line-height: 1.14 !important;
            margin-bottom: 2px !important;
        }

        #customer-view-main #customerEditModal .product-modal-header .text-sm,
        #customer-view-main #opportunityModal .product-modal-header .text-sm {
            font-size: 0.78rem !important;
            line-height: 1.15 !important;
        }

        #customer-view-main #customerEditModal .product-modal-body,
        #customer-view-main #opportunityModal .product-modal-body {
            padding: 14px !important;
        }

        #customer-view-main #customerEditModal .product-modal-footer,
        #customer-view-main #opportunityModal .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
            overflow: visible !important;
        }

        #customer-view-main #customerEditModal .modal-footer-actions-left {
            min-width: 44px !important;
            gap: 8px !important;
        }

        #customer-view-main #customerEditModal .modal-footer-actions-right,
        #customer-view-main #opportunityModal .modal-footer-actions-right {
            gap: 10px !important;
            flex: 0 1 auto !important;
            min-width: 0 !important;
        }

        #customer-view-main #customerEditModal .product-modal-footer .btn,
        #customer-view-main #opportunityModal .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 106px !important;
            max-width: none !important;
            padding: 0 14px !important;
            font-size: 0.94rem !important;
            flex: 0 0 auto !important;
        }

        #customer-view-main #customerEditModal .product-modal-footer .btn-primary,
        #customer-view-main #opportunityModal .product-modal-footer .btn-primary,
        #customer-view-main #opportunityModal #saveOpportunityBtn {
            min-width: 124px !important;
        }

        #customer-view-main #customerEditModal .product-modal-footer .btn span,
        #customer-view-main #opportunityModal .product-modal-footer .btn span {
            display: inline-flex !important;
            overflow: visible !important;
            text-overflow: clip !important;
            max-width: none !important;
        }

        /* Mobile: botón destructivo sólo icono */
        #customer-view-main #customerEditModal .btn-delete-mobile,
        #customer-view-main #customerEditModal .modal-footer-actions-left .btn {
            width: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            height: 44px !important;
            min-height: 44px !important;
            padding: 0 !important;
            flex: 0 0 44px !important;
        }
        
        #customer-view-main #customerEditModal .btn-delete-mobile span,
        #customer-view-main #customerEditModal .modal-footer-actions-left .btn span {
            display: none !important;
        }
        
        #customer-view-main #customerEditModal .btn-delete-mobile svg,
        #customer-view-main #customerEditModal .modal-footer-actions-left .btn svg {
            margin: 0 !important;
            flex-shrink: 0 !important;
        }
    }


    </style>

    <script src="/assets/js/customer-location.js?v=p4_5_1"></script>
    <script>
    (function() {

        // =========================================================================
        // MANEJO DE ENVÍO MANUAL (CREAR OPORTUNIDAD)
        // =========================================================================
        const createOppForm = document.getElementById('form-create-opportunity');
        if (createOppForm && !createOppForm.dataset.customSubmitAttached) {
            createOppForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const btn = document.getElementById('saveOpportunityBtn');
                const originalHtml = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<i data-lucide="loader" class="spin-icon"></i><span class="mobile-hidden">Guardando...</span>';
                if (window.lucide) window.lucide.createIcons();

                fetch(this.action, {
                    method: 'POST',
                    body: new FormData(this),
                    redirect: 'follow'
                })
                .then(res => {
                    const url = new URL(res.url);
                    const oppId = url.searchParams.get('id');
                    // Si se creó con éxito, recargamos con el ID mágico
                    if (oppId) {
                        (window.ICY_SPA_GO ? window.ICY_SPA_GO(window.location.pathname + '?id=<?php echo $id; ?>&open_modal=' + oppId, { replace: true, force: true }) : (window.location.href = window.location.pathname + '?id=<?php echo $id; ?>&open_modal=' + oppId));
                    } else {
                        (window.ICY_SPA_RELOAD ? window.ICY_SPA_RELOAD({ force: true }) : window.location.reload());
                    }
                })
                .catch(err => {
                    console.error('Error al guardar:', err);
                    btn.disabled = false;
                    btn.innerHTML = originalHtml;
                    if (window.lucide) window.lucide.createIcons();
                });
            });
            createOppForm.dataset.customSubmitAttached = 'true';
        }

        // =========================================================================
        // AUTO-ABRIR MODAL SI VENIMOS DE CREAR
        // =========================================================================
        <?php if ($openModalId > 0): ?>
            // Limpiamos la URL visualmente para que no se quede pegado el ?open_modal
            window.history.replaceState({}, document.title, window.location.pathname + '?id=<?php echo $id; ?>');
            setTimeout(() => {
                if(typeof window.openOppViewModal === 'function') {
                    window.openOppViewModal(null, <?php echo $openModalId; ?>);
                }
            }, 400);
        <?php endif; ?>


        window.openOppViewModal = function(e, oppId) {
            if (e) e.preventDefault();
            
            var existing = document.getElementById('oppViewModalBackdrop');
            if (existing) existing.remove();

            var loader = document.createElement('div');
            loader.id = 'oppViewModalBackdrop';
            loader.className = 'product-modal-backdrop show';
            loader.style.display = 'flex';
            loader.style.zIndex = '1040';
            loader.innerHTML = '<div style="color:var(--text-primary); display:flex; flex-direction:column; align-items:center; gap:12px;"><i data-lucide="loader" class="spin-icon" style="width:32px;height:32px;"></i><span>Cargando oportunidad...</span></div>';
            document.body.appendChild(loader);
            if (window.lucide) window.lucide.createIcons();

            fetch('/modules/crm/opportunity.php?id=' + oppId + '&modal=1')
            .then(res => res.text())
            .then(html => {
                loader.outerHTML = html;
                var newModal = document.getElementById('oppViewModalBackdrop');
                if (newModal) {
                    var scripts = newModal.querySelectorAll('script');
                    scripts.forEach(s => {
                        var newS = document.createElement('script');
                        newS.innerHTML = s.innerHTML;
                        document.body.appendChild(newS);
                    });
                    if (window.lucide) window.lucide.createIcons();
                }
            })
            .catch(err => { 
                alert('Error al cargar la oportunidad'); 
                if (loader) loader.remove(); 
            });
        };

        window.openEditCustomerModal = function() {
            var editModal = document.getElementById('customerEditModal');
            if(editModal) {
                editModal.style.display = 'flex';
                setTimeout(() => editModal.classList.add('show'), 10);
            }
        };

        window.closeEditCustomerModal = function() {
            var editModal = document.getElementById('customerEditModal');
            if(editModal) {
                editModal.classList.remove('show');
                setTimeout(() => editModal.style.display = 'none', 200);
            }
        };
        
        window.openOpportunityModal = function() {
            var oppModal = document.getElementById('opportunityModal');
            if(oppModal) {
                document.getElementById('form-create-opportunity').reset();
                oppModal.style.display = 'flex';
                setTimeout(() => oppModal.classList.add('show'), 10);
            }
        };

        window.closeOpportunityModal = function() {
            var oppModal = document.getElementById('opportunityModal');
            if(oppModal) {
                oppModal.classList.remove('show');
                setTimeout(() => oppModal.style.display = 'none', 200);
            }
        };

        if (!window.__customerViewGlobalClicksAttached) {
            document.addEventListener('click', (e) => { 
                var editModal = document.getElementById('customerEditModal');
                var oppModal = document.getElementById('opportunityModal');
                
                if (editModal && e.target === editModal) window.closeEditCustomerModal(); 
                if (oppModal && e.target === oppModal) window.closeOpportunityModal(); 
            });
            window.__customerViewGlobalClicksAttached = true;
        }

        // ==========================================================================
        // AUTO-ESCALADO DE KPIS (Shrink to Fit)
        // ==========================================================================
        function resizeKPIs() {
            document.querySelectorAll('.kpi-auto-shrink').forEach(el => {
                el.style.fontSize = '1.8rem';
                let parentWidth = el.parentElement.clientWidth;
                let currentSize = 1.8; 
                
                while(el.scrollWidth > parentWidth && currentSize > 0.8) {
                    currentSize -= 0.1;
                    el.style.fontSize = currentSize + 'rem';
                }
            });
        }

        window.addEventListener('resize', resizeKPIs);
        setTimeout(resizeKPIs, 50); 
        
        // ==========================================================================
        // FORMATOS Y SELECTORES INTERNOS DE LOS FORMULARIOS
        // ==========================================================================
        var ePrefixSelect = document.getElementById('edit_phone_prefix');
        var eNumberInput = document.getElementById('edit_phone_number');
        var eRealPhone = document.getElementById('edit_real_phone_input');

        if (ePrefixSelect && eNumberInput && eRealPhone) {
            var savedPhone = eRealPhone.value.trim();
            if (savedPhone) {
                var foundPrefix = Array.from(ePrefixSelect.options).find(opt => savedPhone.startsWith(opt.value));
                if (foundPrefix) {
                    ePrefixSelect.value = foundPrefix.value;
                    eNumberInput.value = savedPhone.substring(foundPrefix.value.length).trim();
                } else {
                    eNumberInput.value = savedPhone;
                }
            }

            function updateEditPhone() {
                var num = eNumberInput.value.replace(/[^0-9\s-]/g, ''); 
                eNumberInput.value = num;
                if (num.replace(/[^0-9]/g, '').length > 0) {
                    eRealPhone.value = ePrefixSelect.value + ' ' + num;
                } else {
                    eRealPhone.value = '';
                }
            }
            ePrefixSelect.addEventListener('change', updateEditPhone);
            eNumberInput.addEventListener('input', updateEditPhone);
        }

        var rutEditInput = document.getElementById('editCustomerTaxId');
        if (rutEditInput) {
            rutEditInput.addEventListener('input', function (e) {
                if (window.ICY_CUSTOMER_LOCATION && window.ICY_CUSTOMER_LOCATION.countryCode(e.target.closest('form')) !== 'cl') return;
                var value = e.target.value.replace(/[^0-9kK]/g, '');
                if (!value) {
                    e.target.value = '';
                    return;
                }
                if (value.length === 1) {
                    e.target.value = value.toUpperCase();
                    return;
                }
                var body = value.slice(0, -1);
                var dv = value.slice(-1).toUpperCase();
                body = body.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
                e.target.value = body + '-' + dv;
            });
            
            rutEditInput.dispatchEvent(new Event('input'));
        }

        if (window.ICY_CUSTOMER_LOCATION) {
            window.ICY_CUSTOMER_LOCATION.init(document.querySelector('.app-main') || document);
        }

    })();
    </script>
</main>

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