<?php
session_start();

// ── Verificar si ya pasó Google Auth ──
$googleAuth  = !empty($_SESSION['google_auth']);
$googleName  = $_SESSION['google_name'] ?? '';
$googleEmail = $_SESSION['google_email'] ?? '';

$error = $_GET['error'] ?? '';
$errorEmail = $_GET['email'] ?? '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mi Seguro CRM</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --sb: #1a1f2e;
    --sb-hover: rgba(255,255,255,0.07);
    --sb-active: rgba(255,255,255,0.10);
    --accent: #3b82f6;
    --page: #f4f5f7;
    --card: #ffffff;
    --stroke: #e5e7eb;
    --stroke-strong: #d1d5db;
    --ink: #111827;
    --muted: #374151;
    --faint: #9ca3af;
  }

  body {
    font-family: 'Inter', sans-serif;
    background: var(--page);
    color: var(--ink);
    height: 100vh;
    display: flex;
    overflow: hidden;
  }

  /* ══════════════════════════════════════
     PANTALLA GOOGLE AUTH
  ══════════════════════════════════════ */
  #googleScreen {
    position: fixed; inset: 0;
    background: #0f1623;
    display: <?= $googleAuth ? 'none' : 'flex' ?>;
    align-items: center; justify-content: center;
    z-index: 9999; padding: 1rem;
  }
  .bg-c1 { position:absolute;width:400px;height:400px;border-radius:50%;background:#1a3a5c;opacity:.3;top:-100px;right:-100px;pointer-events:none; }
  .bg-c2 { position:absolute;width:250px;height:250px;border-radius:50%;background:#0c2a4a;opacity:.4;bottom:-70px;left:-50px;pointer-events:none; }

  .google-card {
    background: #fff; border-radius: 18px;
    padding: 2.5rem 2rem 2rem;
    width: 100%; max-width: 380px;
    position: relative; z-index: 1;
    text-align: center;
  }

  .g-brand {
    display: flex; align-items: center; justify-content: center; gap: 10px;
    margin-bottom: 1.75rem;
  }
  .g-brand-icon {
    width: 38px; height: 38px; background: #1a5fa8;
    border-radius: 9px; display: flex; align-items: center; justify-content: center;
  }
  .g-brand-name { font-size: 19px; font-weight: 700; color: #0f1623; letter-spacing: -0.3px; }
  .g-brand-name span { color: #1a5fa8; }

  .g-title { font-size: 15px; font-weight: 600; color: #0f1623; margin-bottom: 6px; }
  .g-sub { font-size: 13px; color: #9ca3af; margin-bottom: 1.75rem; line-height: 1.5; }

  .g-error {
    background: #fef2f2; border: 1px solid #fca5a5;
    border-radius: 8px; padding: 10px 14px;
    font-size: 13px; color: #dc2626;
    margin-bottom: 1.25rem; text-align: left;
    display: flex; align-items: flex-start; gap: 8px;
  }

  .btn-google {
    display: flex; align-items: center; justify-content: center; gap: 10px;
    width: 100%; height: 46px;
    background: #fff; color: #374151;
    border: 1.5px solid #d1d5db; border-radius: 9px;
    font-size: 14px; font-weight: 600; font-family: 'Inter', sans-serif;
    cursor: pointer; text-decoration: none;
    transition: background 0.15s, border-color 0.15s, box-shadow 0.15s;
  }
  .btn-google:hover {
    background: #f9fafb; border-color: #9ca3af;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  }

  .g-notice {
    margin-top: 1.25rem; font-size: 12px; color: #9ca3af; line-height: 1.5;
  }
  .g-notice strong { color: #6b7280; }

  /* ══════════════════════════════════════
     LOGIN VISUAL (segunda capa)
  ══════════════════════════════════════ */
  #loginScreen {
    position: fixed; inset: 0;
    background: #0f1623;
    display: <?= $googleAuth ? 'flex' : 'none' ?>;
    align-items: center; justify-content: center;
    z-index: 9998; padding: 1rem;
  }

  .login-card {
    background: #fff; border-radius: 18px;
    padding: 2.5rem 2rem 2rem;
    width: 100%; max-width: 380px;
    position: relative; z-index: 1;
  }

  .login-brand {
    display: flex; align-items: center; justify-content: center; gap: 10px;
    margin-bottom: 1.75rem;
  }
  .login-brand-icon {
    width: 38px; height: 38px; background: #1a5fa8;
    border-radius: 9px; display: flex; align-items: center; justify-content: center;
  }
  .login-brand-name { font-size: 19px; font-weight: 700; color: #0f1623; letter-spacing: -0.3px; }
  .login-brand-name span { color: #1a5fa8; }

  .google-badge {
    display: flex; align-items: center; gap: 8px;
    background: #f0fdf4; border: 1px solid #bbf7d0;
    border-radius: 8px; padding: 8px 12px;
    font-size: 12px; color: #15803d;
    margin-bottom: 1.25rem;
  }

  .login-heading { font-size: 15px; font-weight: 600; color: #0f1623; margin-bottom: 4px; }
  .login-sub { font-size: 13px; color: #9ca3af; margin-bottom: 1.5rem; }

  .login-error {
    display: none; background: #fef2f2; border: 1px solid #fca5a5;
    border-radius: 8px; padding: 9px 13px;
    font-size: 13px; color: #dc2626; margin-bottom: 1rem;
    align-items: center; gap: 8px;
  }
  .login-error.show { display: flex; }

  .login-field { margin-bottom: 1rem; }
  .login-field label {
    display: block; font-size: 11px; font-weight: 600; color: #374151;
    text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px;
  }
  .login-input-wrap { position: relative; }
  .login-input-wrap .field-icon {
    position: absolute; left: 11px; top: 50%; transform: translateY(-50%);
    color: #9ca3af; pointer-events: none;
  }
  .login-input-wrap input {
    width: 100%; height: 42px; border: 1px solid #d1d5db; border-radius: 8px;
    padding: 0 36px 0 36px; font-size: 13.5px; font-family: 'Inter', sans-serif;
    color: #111827; background: #f9fafb; outline: none;
    transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
  }
  .login-input-wrap input:focus {
    border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.12); background: #fff;
  }
  .eye-toggle {
    position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
    background: none; border: none; cursor: pointer; color: #9ca3af;
    padding: 4px; display: flex; align-items: center; transition: color 0.15s;
  }
  .eye-toggle:hover { color: #374151; }

  .login-btn {
    width: 100%; height: 44px; background: #1a5fa8; color: #fff;
    border: none; border-radius: 9px; font-size: 14px; font-weight: 600;
    font-family: 'Inter', sans-serif; cursor: pointer; margin-top: 1.25rem;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: background 0.15s, transform 0.1s;
  }
  .login-btn:hover { background: #155090; }
  .login-btn:active { transform: scale(0.98); }
  .login-btn:disabled { opacity: 0.7; cursor: not-allowed; }

  .logout-google {
    display: block; text-align: center; margin-top: 1rem;
    font-size: 12px; color: #9ca3af; cursor: pointer; text-decoration: none;
  }
  .logout-google:hover { color: #dc2626; }

  .login-version { text-align: center; font-size: 11px; color: #d1d5db; margin-top: 1.25rem; }

  @keyframes spin { to { transform: rotate(360deg); } }
  .spin { animation: spin 0.75s linear infinite; display: inline-block; }

  /* ══════════════════════════════════════
     CRM APP
  ══════════════════════════════════════ */
  #crmApp {
    display: none; width: 100%; height: 100vh; overflow: hidden;
  }
  #crmApp.visible { display: flex; }

  aside {
    width: 212px; flex-shrink: 0; background: var(--sb);
    display: flex; flex-direction: column; user-select: none;
  }
  .sb-logo {
    height: 52px; display: flex; align-items: center; padding: 0 10px; margin-top: 8px;
    border-bottom: 1px solid rgba(255,255,255,0.06);
    font-size: 15px; font-weight: 700; color: #fff; letter-spacing: -0.3px;
  }
  .sb-logo span { color: var(--accent); }
  nav {
    flex: 1; padding: 12px 10px; overflow-y: auto;
    display: flex; flex-direction: column; gap: 2px;
  }
  nav a {
    display: flex; align-items: center; gap: 10px; padding: 7px 10px;
    border-radius: 6px; font-size: 13px; color: rgba(255,255,255,0.35);
    text-decoration: none; transition: background 0.1s, color 0.1s; position: relative;
  }
  nav a:hover { background: var(--sb-hover); color: rgba(255,255,255,0.65); }
  nav a.active { background: var(--sb-active); color: #fff; font-weight: 600; }
  nav a.active::before {
    content: ''; position: absolute; left: 0; width: 3px; height: 16px;
    border-radius: 0 3px 3px 0; background: var(--accent);
  }
  nav a svg { flex-shrink: 0; }
  nav a span { flex: 1; }
  .badge-wrap { display: flex; gap: 2px; }
  .badge {
    display: flex; align-items: center; justify-content: center;
    min-width: 16px; height: 16px; padding: 0 4px; border-radius: 999px;
    font-size: 9px; font-weight: 700; color: #fff; line-height: 1;
  }
  .badge-red { background: #ef4444; }
  .badge-orange { background: #f97316; }
  .badge-yellow { background: #eab308; }
  .sb-user { padding: 12px 10px; border-top: 1px solid rgba(255,255,255,0.06); }
  .sb-user-inner { display: flex; align-items: center; gap: 10px; padding: 6px 10px; border-radius: 6px; }
  .avatar {
    width: 24px; height: 24px; border-radius: 50%;
    background: rgba(59,130,246,0.7);
    display: flex; align-items: center; justify-content: center;
    font-size: 10px; font-weight: 600; color: #fff; flex-shrink: 0;
  }
  .sb-user-info { flex: 1; min-width: 0; }
  .sb-user-name { font-size: 12px; font-weight: 500; color: rgba(255,255,255,0.7); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .sb-user-role { font-size: 11px; color: rgba(255,255,255,0.25); }
  .logout-btn {
    background: none; border: none; cursor: pointer;
    color: rgba(255,255,255,0.2); padding: 0; margin-left: auto; transition: color 0.15s;
  }
  .logout-btn:hover { color: rgba(255,255,255,0.5); }
  main { flex: 1; overflow: auto; min-width: 0; display: flex; flex-direction: column; }
  .page-header {
    border-bottom: 1px solid var(--stroke); background: rgba(255,255,255,0.5);
    backdrop-filter: blur(4px); padding: 20px 24px;
  }
  .page-header-inner { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
  .page-title { font-size: 26px; font-weight: 700; color: var(--ink); letter-spacing: -0.5px; line-height: 1; }
  .page-sub { margin-top: 4px; font-size: 12px; color: var(--faint); }
  .header-actions { display: flex; align-items: center; gap: 12px; }
  .count-label { font-size: 12px; color: var(--faint); font-variant-numeric: tabular-nums; font-family: monospace; }
  .btn-primary {
    display: flex; align-items: center; gap: 6px; height: 32px; padding: 0 12px;
    background: var(--accent); color: #fff; border: none; border-radius: 7px;
    font-size: 12.5px; font-weight: 600; cursor: pointer; transition: background 0.15s;
  }
  .btn-primary:hover { background: #2563eb; }
  .filters-bar { background: var(--page); border-bottom: 1px solid var(--stroke); padding: 10px 16px; display: flex; flex-direction: column; gap: 8px; }
  .filter-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  .filter-divider { width: 1px; height: 16px; background: var(--stroke-strong); margin: 0 4px; }
  .btn-filter {
    height: 28px; padding: 0 12px; border-radius: 5px; font-size: 11.5px; font-weight: 600;
    border: 1px solid var(--stroke); background: transparent; color: var(--muted);
    cursor: pointer; transition: all 0.1s; white-space: nowrap;
  }
  .btn-filter:hover { color: var(--ink); border-color: var(--stroke-strong); }
  .btn-filter.active { background: var(--sb); color: #fff; border-color: var(--sb); }
  .select-wrap { position: relative; }
  .filter-select {
    height: 28px; padding: 0 28px 0 12px; border-radius: 5px; font-size: 11.5px; font-weight: 600;
    border: 1px solid var(--stroke); background: transparent; color: var(--muted);
    cursor: pointer; appearance: none; transition: all 0.1s;
  }
  .filter-select:hover { color: var(--ink); border-color: var(--stroke-strong); }
  .select-arrow { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: var(--faint); }
  .search-wrap { position: relative; width: 320px; }
  .search-icon { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--faint); }
  .search-input {
    width: 100%; height: 28px; padding: 0 12px 0 32px; border-radius: 999px;
    border: 1px solid rgba(229,231,235,0.8); background: transparent; color: var(--muted);
    font-size: 12px; outline: none; transition: border-color 0.15s;
  }
  .search-input::placeholder { color: var(--faint); }
  .search-input:focus { border-color: var(--accent); }
  .btn-icon {
    display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 12px;
    border-radius: 5px; font-size: 11.5px; font-weight: 600; border: 1px solid var(--stroke);
    background: transparent; color: var(--muted); cursor: pointer; transition: all 0.1s;
  }
  .btn-icon:hover { color: var(--ink); border-color: var(--stroke-strong); }
  .btn-icon.ml-auto { margin-left: auto; }
  .table-wrap { flex: 1; overflow: auto; padding: 16px; }
  .table-card { background: var(--card); border-radius: 10px; border: 1px solid var(--stroke); box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden; }
  table { width: 100%; border-collapse: collapse; }
  thead tr { background: rgba(244,245,247,0.6); border-bottom: 1px solid var(--stroke); }
  th { text-align: left; padding: 10px 12px; font-size: 11px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
  th button { display: inline-flex; align-items: center; gap: 2px; background: none; border: none; cursor: pointer; font-size: 11px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; transition: color 0.1s; }
  th button:hover { color: var(--ink); }
  tbody tr { cursor: pointer; transition: background 0.1s; border-bottom: 1px solid rgba(229,231,235,0.6); }
  tbody tr:last-child { border-bottom: none; }
  tbody tr:hover { background: rgba(244,245,247,0.5); }
  td { padding: 10px 12px; }
  .id-cell { font-family: monospace; font-size: 11px; color: var(--faint); }
  .cell-text { font-size: 12px; color: var(--muted); }
  .mono { font-family: monospace; }
  .plate { font-family: monospace; color: var(--faint); }
  .status-badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 999px; font-size: 10px; font-weight: 600; }
  .status-active { background: #f0fdf4; color: #15803d; }
  .status-inactive { background: #fef2f2; color: #dc2626; }
  .status-pendiente { background: #fefce8; color: #a16207; }
  .action-cell { text-align: right; }
  .action-btns { display: inline-flex; align-items: center; gap: 6px; }
  .action-btns button { color: var(--muted); transition: color 0.15s; background: none; border: none; cursor: pointer; padding: 0; }
  .action-btns button:hover { color: var(--accent); }
  .pagination { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 16px; border-top: 1px solid var(--stroke); }
  .page-info { font-size: 11px; color: var(--faint); font-family: monospace; white-space: nowrap; }
  .page-controls { display: flex; align-items: center; gap: 4px; }
  .page-btn { display: flex; align-items: center; justify-content: center; height: 28px; width: 28px; border-radius: 6px; border: 1px solid var(--stroke); background: none; color: var(--muted); cursor: pointer; transition: all 0.1s; }
  .page-btn:hover:not(:disabled) { color: var(--ink); border-color: var(--stroke-strong); }
  .page-btn:disabled { opacity: 0.3; cursor: not-allowed; }
  .page-input-wrap { display: flex; align-items: center; gap: 6px; padding: 0 8px; }
  .page-input { height: 28px; width: 48px; padding: 0 6px; border-radius: 6px; border: 1px solid var(--stroke); background: var(--card); text-align: center; font-size: 12px; font-family: monospace; color: var(--ink); outline: none; transition: border-color 0.15s; -webkit-appearance: textfield; appearance: textfield; }
  .page-input::-webkit-inner-spin-button, .page-input::-webkit-outer-spin-button { -webkit-appearance: none; }
  .page-input:focus { border-color: var(--accent); }
  .page-of { font-size: 11px; color: var(--faint); font-family: monospace; white-space: nowrap; }
</style>
</head>
<body>

<!-- ═══════════════ PASO 1: GOOGLE AUTH ═══════════════ -->
<div id="googleScreen">
  <div class="bg-c1"></div>
  <div class="bg-c2"></div>
  <div class="google-card">

    <div class="g-brand">
      <div class="g-brand-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>
      </div>
      <span class="g-brand-name">Mi<span>Seguro</span>.uno</span>
    </div>

    <?php if ($error === 'unauthorized'): ?>
    <div class="g-error">
      <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
      <div>
        La cuenta <strong><?= htmlspecialchars($errorEmail) ?></strong> no tiene acceso a este sistema.
      </div>
    </div>
    <?php elseif ($error === 'cancelled'): ?>
    <div class="g-error">
      <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
      <div>Cancelaste el acceso con Google. Intentá de nuevo.</div>
    </div>
    <?php endif; ?>

    <p class="g-title">Acceso restringido</p>
    <p class="g-sub">Este sistema requiere verificar tu identidad con Google antes de continuar.</p>

    <a class="btn-google" href="/auth.php?action=login">
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 48 48">
        <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
        <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
        <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
        <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.36-8.16 2.36-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
        <path fill="none" d="M0 0h48v48H0z"/>
      </svg>
      Continuar con Google
    </a>

    <p class="g-notice">Solo la cuenta autorizada de <strong>MiSeguro</strong> puede acceder.</p>
  </div>
</div>

<!-- ═══════════════ PASO 2: LOGIN CRM ═══════════════ -->
<div id="loginScreen">
  <div class="bg-c1"></div>
  <div class="bg-c2"></div>
  <div class="login-card">

    <div class="login-brand">
      <div class="login-brand-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>
      </div>
      <span class="login-brand-name">Mi<span>Seguro</span>.uno</span>
    </div>

    <?php if ($googleAuth): ?>
    <div class="google-badge">
      <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      Google verificado: <strong><?= htmlspecialchars($googleEmail) ?></strong>
    </div>
    <?php endif; ?>

    <p class="login-heading">Ingresá tus credenciales</p>
    <p class="login-sub">Segunda verificación del sistema</p>

    <div class="login-error" id="loginError">
      <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
      <span id="loginErrorText">Usuario o contraseña incorrectos.</span>
    </div>

    <div class="login-field">
      <label for="loginUser">Usuario</label>
      <div class="login-input-wrap">
        <svg class="field-icon" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        <input type="text" id="loginUser" placeholder="usuario" autocomplete="username" />
      </div>
    </div>

    <div class="login-field">
      <label for="loginPass">Contraseña</label>
      <div class="login-input-wrap">
        <svg class="field-icon" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
        <input type="password" id="loginPass" placeholder="••••••••" autocomplete="current-password" />
        <button class="eye-toggle" id="eyeBtn" type="button">
          <svg id="eyeIcon" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
        </button>
      </div>
    </div>

    <button class="login-btn" id="loginBtn" onclick="doLogin()">
      <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" x2="3" y1="12" y2="12"/></svg>
      Ingresar al CRM
    </button>

    <a class="logout-google" href="/auth.php?action=logout">Cerrar sesión de Google y salir</a>
    <p class="login-version">MiSeguro CRM · v2.4</p>
  </div>
</div>

<!-- ═══════════════ CRM APP ═══════════════ -->
<div id="crmApp">
<aside>
  <div class="sb-logo">Mi<span>Seguro</span>.uno</div>
  <nav>
    <a href="#dashboard"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><line x1="18" x2="18" y1="20" y2="10"/><line x1="12" x2="12" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="14"/></svg><span>Dashboard</span></a>
    <a href="#leads"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg><span>Leads</span></a>
    <a href="#clientes"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg><span>Clientes</span></a>
    <a href="#polizas" class="active"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg><span>Pólizas</span></a>
    <a href="#siniestros"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg><span>Siniestros</span></a>
    <a href="#vehiculos"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2"/><circle cx="7" cy="17" r="2"/><path d="M9 17h6"/><circle cx="17" cy="17" r="2"/></svg><span>Vehículos</span></a>
    <a href="#mensajeria"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg><span>Mensajería</span></a>
    <a href="#conversaciones"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg><span>Conversaciones</span></a>
    <a href="#ath"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg><span>ATH</span><div class="badge-wrap"><span class="badge badge-red">3</span><span class="badge badge-orange">2</span><span class="badge badge-yellow">6</span></div></a>
  </nav>
  <div class="sb-user">
    <div class="sb-user-inner">
      <div class="avatar" id="sidebarAvatar">DA</div>
      <div class="sb-user-info">
        <div class="sb-user-name" id="sidebarName">Dante Agustín Ferrara</div>
        <div class="sb-user-role" id="sidebarRole">dante</div>
      </div>
      <button class="logout-btn" title="Cerrar sesión" onclick="doLogout()">
        <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/></svg>
      </button>
    </div>
  </div>
</aside>

<main>
  <div class="page-header">
    <div class="page-header-inner">
      <div>
        <h1 class="page-title">Pólizas</h1>
        <p class="page-sub">Cartera de pólizas vigentes y dadas de baja</p>
      </div>
      <div class="header-actions">
        <span class="count-label" id="totalCount">9.800 pólizas</span>
        <button class="btn-primary" onclick="alert('Nueva Póliza')">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
          Nueva Póliza
        </button>
      </div>
    </div>
  </div>
  <div class="filters-bar">
    <div class="filter-row">
      <div style="display:flex;gap:4px;">
        <button class="btn-filter active" onclick="setStatus(this,'')">Todas</button>
        <button class="btn-filter" onclick="setStatus(this,'Activa')">Activa</button>
        <button class="btn-filter" onclick="setStatus(this,'Inactiva')">Inactiva</button>
        <button class="btn-filter" onclick="setStatus(this,'Pendiente')">Pendiente</button>
      </div>
      <div class="filter-divider"></div>
      <div class="select-wrap">
        <select class="filter-select" id="ramoFilter" onchange="applyFilters()">
          <option value="">Todos los ramos</option>
          <option>Automotor</option><option>Motovehículo</option><option>Hogar</option>
          <option>Integral Consorcio</option><option>Integral Comercio</option>
          <option>Bicicleta</option><option>AP</option><option>RC Profesional</option><option>Caución Alquiler</option>
        </select>
        <svg class="select-arrow" xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
      </div>
      <div class="select-wrap">
        <select class="filter-select" id="ciaFilter" onchange="applyFilters()">
          <option value="">Todas las cías</option>
          <option>Federación Patronal</option><option>Provincia Seguros</option><option>Experta</option>
          <option>ATM</option><option>CAS</option><option>Mercantil Andina</option><option>Rivadavia</option>
          <option>Finisterre</option><option>La Equidad</option><option>La Holando</option>
          <option>San Cristóbal</option><option>Galicia Seguros</option><option>La Nueva</option>
          <option>San Patricio</option><option>ATMBON</option><option>SMG</option><option>Metropol</option><option>RUS</option>
        </select>
        <svg class="select-arrow" xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
      </div>
      <div class="filter-divider"></div>
      <div style="display:flex;gap:4px;">
        <button class="btn-filter" onclick="setCob(this,'Todo Riesgo')">Todo Riesgo</button>
        <button class="btn-filter" onclick="setCob(this,'Terceros Full')">3ros Full</button>
        <button class="btn-filter" onclick="setCob(this,'Terceros Completo')">3ros Completo</button>
        <button class="btn-filter" onclick="setCob(this,'Terceros Básico')">3ros Básico</button>
        <button class="btn-filter" onclick="setCob(this,'RC')">RC</button>
      </div>
    </div>
    <div class="filter-row">
      <div class="search-wrap">
        <svg class="search-icon" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
        <input id="searchInput" class="search-input" placeholder="Nombre, apellido, DNI, teléfono, email o patente..." oninput="applyFilters()">
      </div>
      <div style="display:flex;gap:4px;">
        <button class="btn-filter" onclick="setUso(this,'particular')">Particular</button>
        <button class="btn-filter" onclick="setUso(this,'apps')">Apps</button>
        <button class="btn-filter" onclick="setUso(this,'comercial')">Comercial</button>
      </div>
      <div class="filter-divider"></div>
      <button class="btn-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
        Reemplazos sin verificar
      </button>
      <button class="btn-icon ml-auto">
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>
        Exportar
      </button>
    </div>
  </div>
  <div class="table-wrap">
    <div class="table-card">
      <table>
        <thead>
          <tr>
            <th style="width:64px"><button>ID</button></th>
            <th><button>Cliente</button></th>
            <th style="width:112px">Teléfono</th>
            <th style="width:112px">Ramo</th>
            <th style="width:128px"><button>Compañía</button></th>
            <th style="width:112px">Cobertura</th>
            <th style="width:96px">Uso</th>
            <th><button>Bien Asegurado</button></th>
            <th style="width:80px"><button>Estado</button></th>
            <th style="width:64px"></th>
          </tr>
        </thead>
        <tbody id="tableBody"></tbody>
      </table>
      <div class="pagination">
        <span class="page-info" id="pageInfo">1 – 25 de 0</span>
        <div class="page-controls">
          <button class="page-btn" id="btnFirst" onclick="goPage(1)"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m11 17-5-5 5-5"/><path d="m18 17-5-5 5-5"/></svg></button>
          <button class="page-btn" id="btnPrev" onclick="goPage(currentPage-1)"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg></button>
          <div class="page-input-wrap">
            <input type="number" class="page-input" id="pageInput" value="1" min="1" onchange="goPage(parseInt(this.value))">
            <span class="page-of" id="pageOf">de 1</span>
          </div>
          <button class="page-btn" id="btnNext" onclick="goPage(currentPage+1)"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg></button>
          <button class="page-btn" id="btnLast" onclick="goPage(totalPages)"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 17 5-5-5-5"/><path d="m13 17 5-5-5-5"/></svg></button>
        </div>
      </div>
    </div>
  </div>
</main>
</div>

<script>
const GOOGLE_AUTH = <?= $googleAuth ? 'true' : 'false' ?>;

const USUARIOS = [
  { user: 'dante',  pass: 'dante123',  nombre: 'Dante Agustín Ferrara', iniciales: 'DA' },
  { user: 'admin',  pass: 'admin2024', nombre: 'Administrador',          iniciales: 'AD' },
];

// Si ya pasó Google, mostrar login CRM
if (GOOGLE_AUTH) {
  document.getElementById('loginScreen').style.display = 'flex';
}

// Ojo toggle
document.getElementById('eyeBtn').addEventListener('click', function() {
  const inp = document.getElementById('loginPass');
  inp.type = inp.type === 'password' ? 'text' : 'password';
});

document.getElementById('loginPass').addEventListener('keydown', e => { if(e.key==='Enter') doLogin(); });
document.getElementById('loginUser').addEventListener('keydown', e => { if(e.key==='Enter') document.getElementById('loginPass').focus(); });

function doLogin() {
  const user = document.getElementById('loginUser').value.trim().toLowerCase();
  const pass = document.getElementById('loginPass').value;
  const errorEl = document.getElementById('loginError');
  const errorTxt = document.getElementById('loginErrorText');
  const btn = document.getElementById('loginBtn');

  errorEl.classList.remove('show');

  if (!user || !pass) {
    errorTxt.textContent = 'Completá usuario y contraseña.';
    errorEl.classList.add('show');
    return;
  }

  btn.disabled = true;
  btn.innerHTML = '<span class="spin"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg></span> Verificando...';

  setTimeout(function() {
    const match = USUARIOS.find(u => u.user === user && u.pass === pass);
    if (match) {
      document.getElementById('sidebarName').textContent = match.nombre;
      document.getElementById('sidebarRole').textContent = match.user;
      document.getElementById('sidebarAvatar').textContent = match.iniciales;
      document.getElementById('loginScreen').style.display = 'none';
      document.getElementById('crmApp').classList.add('visible');
    } else {
      errorTxt.textContent = 'Usuario o contraseña incorrectos.';
      errorEl.classList.add('show');
      btn.disabled = false;
      btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" x2="3" y1="12" y2="12"/></svg> Ingresar al CRM';
    }
  }, 700);
}

function doLogout() {
  if (confirm('¿Cerrar sesión?')) {
    window.location.href = '/auth.php?action=logout';
  }
}

// CRM filters
let allData = [], filtered = [], currentPage = 1, totalPages = 1;
const PAGE_SIZE = 25;
let activeStatus = '', activeCob = '', activeUso = '';

function applyFilters() {
  const q = document.getElementById('searchInput').value.toLowerCase();
  const ramo = document.getElementById('ramoFilter').value;
  const cia  = document.getElementById('ciaFilter').value;
  filtered = allData.filter(r =>
    (!activeStatus || r.estado === activeStatus) &&
    (!ramo   || r.ramo === ramo) &&
    (!cia    || r.cia === cia) &&
    (!activeCob || r.cobertura === activeCob) &&
    (!activeUso || r.uso.toLowerCase() === activeUso) &&
    (!q || Object.values(r).join(' ').toLowerCase().includes(q))
  );
  currentPage = 1;
  renderTable();
}

function setStatus(btn, val) {
  activeStatus = val;
  document.querySelectorAll('.btn-filter').forEach(b => {
    if(['Todas','Activa','Inactiva','Pendiente'].includes(b.textContent.trim())) b.classList.remove('active');
  });
  btn.classList.add('active');
  applyFilters();
}

function setCob(btn, val) {
  if (activeCob === val) { activeCob = ''; btn.classList.remove('active'); }
  else {
    activeCob = val;
    document.querySelectorAll('.btn-filter').forEach(b => {
      if(['Todo Riesgo','3ros Full','3ros Completo','3ros Básico','RC'].includes(b.textContent.trim())) b.classList.remove('active');
    });
    btn.classList.add('active');
  }
  applyFilters();
}

function setUso(btn, val) {
  if (activeUso === val) { activeUso = ''; btn.classList.remove('active'); }
  else {
    activeUso = val;
    document.querySelectorAll('.btn-filter').forEach(b => {
      if(['Particular','Apps','Comercial'].includes(b.textContent.trim())) b.classList.remove('active');
    });
    btn.classList.add('active');
  }
  applyFilters();
}

function goPage(n) {
  if (n < 1 || n > totalPages) return;
  currentPage = n;
  renderTable();
}

function renderTable() {
  totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  currentPage = Math.min(currentPage, totalPages);
  const start = (currentPage - 1) * PAGE_SIZE;
  const rows  = filtered.slice(start, start + PAGE_SIZE);
  document.getElementById('pageInfo').textContent = filtered.length ? `${start+1} – ${Math.min(start+PAGE_SIZE, filtered.length)} de ${filtered.length}` : '0 resultados';
  document.getElementById('pageOf').textContent = `de ${totalPages}`;
  document.getElementById('pageInput').value = currentPage;
  document.getElementById('btnFirst').disabled = currentPage === 1;
  document.getElementById('btnPrev').disabled  = currentPage === 1;
  document.getElementById('btnNext').disabled  = currentPage === totalPages;
  document.getElementById('btnLast').disabled  = currentPage === totalPages;
  const tbody = document.getElementById('tableBody');
  tbody.innerHTML = rows.length ? rows.map(r => `
    <tr>
      <td class="id-cell">#${r.id}</td>
      <td><div style="font-size:12.5px;font-weight:500;color:var(--ink)">${r.cliente}</div><div style="font-size:11px;color:var(--faint)">${r.dni}</div></td>
      <td class="cell-text mono">${r.tel}</td>
      <td class="cell-text">${r.ramo}</td>
      <td class="cell-text">${r.cia}</td>
      <td class="cell-text">${r.cobertura}</td>
      <td class="cell-text">${r.uso}</td>
      <td class="cell-text plate">${r.bien}</td>
      <td><span class="status-badge status-${r.estado.toLowerCase()}">${r.estado}</span></td>
      <td class="action-cell"><div class="action-btns"><button title="Editar"><svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg></button></div></td>
    </tr>`).join('') :
    '<tr><td colspan="10" style="text-align:center;padding:32px;color:var(--faint);font-size:13px">Sin resultados</td></tr>';
}

applyFilters();
</script>
</body>
</html>
