<!DOCTYPE html>
<html lang="es" data-bs-theme="{{ $appConfig['tema'] === 'oscuro' ? 'dark' : 'light' }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>@yield('titulo', 'Inicio') | {{ $appConfig['empresa'] }}</title>
<link rel="icon" href="{{ asset($appConfig['favicon']) }}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.min.css" rel="stylesheet">
<style>
:root {
  --color-primario: {{ $appConfig['color_primario'] }};
  --color-secundario: {{ $appConfig['color_secundario'] }};
  --color-acento: {{ $appConfig['color_acento'] }};
}
body { font-family: 'Segoe UI', Tahoma, Arial, sans-serif; }
.navbar-brand img { height: 38px; }
.bg-primario { background: var(--color-primario) !important; }
.bg-secundario { background: var(--color-secundario) !important; }
.btn-primario { background: var(--color-primario); color: #fff; border-color: var(--color-primario); }
.btn-primario:hover { background: var(--color-secundario); color:#fff; border-color: var(--color-secundario); }
.btn-acento { background: var(--color-acento); color:#000; }
.text-primario { color: var(--color-primario) !important; }
.kpi-card { border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,.08); transition: transform .15s; }
.kpi-card:hover { transform: translateY(-2px); }
.table-sticky thead th { position: sticky; top: 0; z-index: 2; background: var(--bs-body-bg); }
@media (max-width:768px) { .navbar-brand span { display:none; } }
@if($appConfig['animaciones'])
.fade-in { animation: fadeIn .3s ease-out; }
@keyframes fadeIn { from { opacity:0; transform: translateY(8px); } to { opacity:1; transform: translateY(0); } }
@endif
.estado-badge { padding: .25rem .6rem; border-radius: 20px; color: #fff; font-size: .8rem; }
/* Tom Select — ajustes para integrarse con Bootstrap 5 */
.ts-control { min-height: calc(1.5em + .75rem + 2px); }
.ts-wrapper.form-select-sm .ts-control, .form-select-sm + .ts-control { min-height: 31px; font-size: .875rem; }
.ts-dropdown { z-index: 1080; }
.ts-wrapper.single .ts-control { background-image: none; }
.ts-dropdown .no-results, .ts-dropdown .create { padding: .5rem .75rem; }
.menu-pie-movil { display:none; }
@media (max-width:768px) {
  .menu-pie-movil { display:flex; position:fixed; bottom:0; left:0; right:0; background:var(--color-primario);
    justify-content: space-around; padding: .4rem 0; z-index: 1000; }
  .menu-pie-movil a { color:#fff; text-align:center; flex:1; font-size:.7rem; text-decoration:none; }
  .menu-pie-movil a i { display:block; font-size:1.2rem; }
  body { padding-bottom: 70px; }
}
</style>
@stack('estilos')
</head>
<body class="fade-in">

<nav class="navbar navbar-expand-lg navbar-dark bg-primario shadow-sm">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="{{ url('/') }}">
      <img src="{{ asset($appConfig['logo_largo']) }}" alt="logo" onerror="this.src='{{ asset('img/logo_cuadrado.png') }}'">
      <span class="ms-2 d-none d-md-inline fw-bold">{{ $appConfig['empresa'] }}</span>
    </a>
    <button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#nav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="nav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item"><a class="nav-link" href="{{ route('dashboard') }}"><i class="fa fa-gauge"></i> Dashboard</a></li>
        @can('planes.ver')
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown"><i class="fa fa-clipboard-list"></i> Planes</a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="{{ route('planes.index', ['clase'=>'preventivo']) }}">Preventivos</a></li>
              <li><a class="dropdown-item" href="{{ route('planes.index', ['clase'=>'correctivo']) }}">Correctivos</a></li>
            </ul>
          </li>
        @endcan
        @can('programacion.ver')
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown"><i class="fa fa-calendar-days"></i> Programación</a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="{{ route('programacion.index') }}"><i class="fa fa-calendar"></i> Por calendario</a></li>
              <li><a class="dropdown-item" href="{{ route('horometro.index') }}"><i class="fa fa-gauge-high"></i> Lecturas de horómetro</a></li>
              <li><a class="dropdown-item" href="{{ route('paros.index') }}"><i class="fa fa-circle-stop"></i> Paros de planta</a></li>
            </ul>
          </li>
        @endcan
        @can('ordenes.ver')
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown"><i class="fa fa-wrench"></i> Órdenes</a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="{{ route('ordenes.index', ['clase'=>'preventivo']) }}">Preventivas</a></li>
              <li><a class="dropdown-item" href="{{ route('ordenes.index', ['clase'=>'correctivo']) }}">Correctivas</a></li>
              <li><a class="dropdown-item" href="{{ route('movil.index') }}">Móvil (Mis órdenes)</a></li>
            </ul>
          </li>
        @endcan
        @can('catalogos.ver')
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown"><i class="fa fa-book"></i> Catálogos</a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="{{ route('areas.index') }}">Áreas</a></li>
              <li><a class="dropdown-item" href="{{ route('sistemas.index') }}">Sistemas</a></li>
              <li><a class="dropdown-item" href="{{ route('equipos.index') }}">Equipos</a></li>
              <li><a class="dropdown-item" href="{{ route('componentes.index') }}">Componentes</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="{{ route('tipos-mantenimiento.index') }}">Tipos de mantenimiento</a></li>
              <li><a class="dropdown-item" href="{{ route('frecuencias.index') }}">Frecuencias</a></li>
              <li><a class="dropdown-item" href="{{ route('unidades.index') }}">Unidades</a></li>
              <li><a class="dropdown-item" href="{{ route('estados-orden.index') }}">Estados</a></li>
              <li><a class="dropdown-item" href="{{ route('prioridades.index') }}">Prioridades</a></li>
            </ul>
          </li>
        @endcan
        @can('repuestos.ver')
          <li class="nav-item"><a class="nav-link" href="{{ route('repuestos.index') }}"><i class="fa fa-box"></i> Repuestos</a></li>
        @endcan
        @can('reportes.ver')
          <li class="nav-item"><a class="nav-link" href="{{ route('reportes.index') }}"><i class="fa fa-chart-line"></i> Reportes</a></li>
        @endcan
        @can('importar.excel')
          <li class="nav-item"><a class="nav-link" href="{{ route('importacion.index') }}"><i class="fa fa-file-excel"></i> Importar</a></li>
        @endcan
      </ul>
      <ul class="navbar-nav">
        @auth
        @can('usuarios.ver')
          <li class="nav-item"><a class="nav-link" href="{{ route('usuarios.index') }}"><i class="fa fa-users"></i> Usuarios</a></li>
        @endcan
        @can('configuracion.ver')
          <li class="nav-item"><a class="nav-link" href="{{ route('configuracion.index') }}"><i class="fa fa-gear"></i> Configuración</a></li>
        @endcan
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
            <i class="fa fa-user-circle"></i> {{ auth()->user()->nombres ?? auth()->user()->usuario }}
          </a>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="{{ route('perfil.edit') }}"><i class="fa fa-id-card"></i> Mi perfil</a></li>
            <li><hr class="dropdown-divider"></li>
            <li>
              <form method="POST" action="{{ route('logout') }}">@csrf
                <button class="dropdown-item"><i class="fa fa-right-from-bracket"></i> Cerrar sesión</button>
              </form>
            </li>
          </ul>
        </li>
        @endauth
      </ul>
    </div>
  </div>
</nav>

<main class="container-fluid py-3">
  @if(session('exito'))
    <div class="alert alert-success alert-dismissible fade show">{{ session('exito') }}<button class="btn-close" data-bs-dismiss="alert"></button></div>
  @endif
  @if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show">{{ session('error') }}<button class="btn-close" data-bs-dismiss="alert"></button></div>
  @endif
  @if($errors->any())
    <div class="alert alert-danger alert-dismissible fade show">
      <ul class="mb-0">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
      <button class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  @endif

  @yield('contenido')
</main>

<nav class="menu-pie-movil">
  <a href="{{ route('dashboard') }}"><i class="fa fa-gauge"></i>Inicio</a>
  <a href="{{ route('movil.index') }}"><i class="fa fa-list-check"></i>Mis OT</a>
  <a href="{{ route('ordenes.index') }}"><i class="fa fa-wrench"></i>Órdenes</a>
  <a href="{{ route('reportes.index') }}"><i class="fa fa-chart-line"></i>Reportes</a>
</nav>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>
<script>
window.csrfToken = document.querySelector('meta[name="csrf-token"]').content;

// Autocompletado en todos los <select>
document.addEventListener('DOMContentLoaded', () => {
  if (typeof TomSelect === 'undefined') return;

  const baseOpciones = {
    create: false,
    allowEmptyOption: true,
    maxOptions: 1000,
    plugins: ['clear_button'],
    placeholder: 'Buscar...',
    render: {
      no_results: () => '<div class="no-results text-muted small">No se encontraron resultados</div>',
      option: (data, esc) => `<div>${esc(data.text)}</div>`,
      item:   (data, esc) => `<div>${esc(data.text)}</div>`,
    },
  };

  const aplicar = (root = document, forzar = false) => {
    root.querySelectorAll('select:not([data-no-search]):not(.tomselected):not([multiple])').forEach(el => {
      if (el.tomselect) return;
      if (el.options.length < 4 && !el.hasAttribute('data-search')) return;
      // Saltar selects que están dentro de un collapse cerrado (se inicializan al abrirlo)
      if (!forzar && el.closest('.collapse:not(.show)')) return;
      try { new TomSelect(el, baseOpciones); }
      catch (e) { console.warn('TomSelect error en', el, e); }
    });
  };

  aplicar();
  document.addEventListener('shown.bs.collapse', e => aplicar(e.target, true));
});

@stack('scripts_inline')
</script>
@stack('scripts')
</body>
</html>
