<div class="gc-container">

  <!-- ═══════════════════════════════ HEADER ═══════════════════════════════ -->
  <header class="gc-header">
    <div class="gc-header__left">
      <button class="gc-header__menu-btn" title="Menú principal">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </button>

      <div class="gc-header__logo">
        <span class="gc-header__logo-text">Agenda de Salas</span>
      </div>

      <button class="gc-header__btn gc-header__btn--rounded" (click)="goToToday()" title="Volver al día de hoy">Hoy</button>

      <div class="gc-header__nav">
        <button class="gc-header__nav-btn" (click)="prevDay()" title="Día anterior">‹</button>
        <button class="gc-header__nav-btn" (click)="nextDay()" title="Día siguiente">›</button>
      </div>

      <h2 class="gc-header__title">{{ monthLabel() | titlecase }}</h2>
    </div>

    <div class="gc-header__right">
      <div class="gc-header__search-container">
        <svg class="gc-header__search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"></circle>
          <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
        </svg>
        <input type="text" placeholder="Buscar recursos..." (input)="onSearch($event)" class="gc-header__search-input" />
      </div>

      <button class="gc-header__icon-btn" title="Asistencia"><span class="material-icons">help_outline</span></button>
      <button class="gc-header__icon-btn" title="Configuración"><span class="material-icons">settings</span></button>

      <div class="gc-header__view-select">
        <button class="gc-header__view-trigger">
          <span>Día</span>
          <span class="gc-header__view-arrow">▼</span>
        </button>
      </div>

      <button class="gc-header__icon-btn" title="Apps"><span class="material-icons">apps</span></button>
      <div class="gc-header__user-avatar">JO</div>
    </div>
  </header>

  <!-- ═══════════════════════════════ LOADING BAR ═══════════════════════════════ -->
  @if (reservasService.isLoading()) {
  <div class="gc-loading-bar">
    <div class="gc-loading-bar__inner"></div>
  </div>
  }

  <!-- ═══════════════════════════════ MAIN LAYOUT BODY ═══════════════════════════════ -->
  <div class="gc-body">

    <!-- ── SIDEBAR IZQUIERDO ── -->
    <aside class="gc-left-sidebar">

      <div class="gc-sidebar-create">
        <button class="gc-btn-create" (click)="navigateToNuevo()">
          <span class="gc-btn-create__text">+ Reservar</span>
        </button>
      </div>

      <!-- Fecha activa -->
      <div class="gc-date-display">
        <span class="gc-date-display__label">{{ activeDateLabel() | titlecase }}</span>
      </div>

      <!-- Mini calendar dinámico -->
      <div class="gc-mini-calendar">
        <div class="gc-mini-calendar__header">
          <span class="gc-mini-calendar__title">{{ monthLabel() | titlecase }}</span>
          <div class="gc-mini-calendar__nav">
            <button class="gc-mini-calendar__nav-btn" (click)="prevDay()">‹</button>
            <button class="gc-mini-calendar__nav-btn" (click)="nextDay()">›</button>
          </div>
        </div>

        <div class="gc-mini-calendar__days-header">
          <span>D</span><span>L</span><span>M</span><span>M</span><span>J</span><span>V</span><span>S</span>
        </div>

        <div class="gc-mini-calendar__days-grid">
          @for (d of miniCalendarDays(); track d.date.toISOString()) {
          <span class="gc-mini-calendar__day"
            [ngClass]="{
              'gc-mini-calendar__day--inactive': !d.currentMonth,
              'gc-mini-calendar__day--active': d.active
            }"
            (click)="selectMiniCalendarDay(d.date)"
            style="cursor: pointer;">
            {{ d.day }}
          </span>
          }
        </div>
      </div>

      <!-- Acordeón categorías -->
      <div class="gc-accordion">
        <div class="gc-accordion__header">
          <span class="gc-accordion__title">Mis Espacios</span>
          <span class="material-icons gc-accordion__chevron">keyboard_arrow_up</span>
        </div>
        <div class="gc-accordion__content">
          <label class="gc-checkbox-item">
            <input type="checkbox" [checked]="isCategorySelected('Sala Reuniones')" (change)="toggleCategory('Sala Reuniones')" class="gc-checkbox-item__input gc-checkbox-item__input--blue" />
            <span class="gc-checkbox-item__label">Sala Reuniones</span>
          </label>
          <label class="gc-checkbox-item">
            <input type="checkbox" [checked]="isCategorySelected('Oficina Flexible')" (change)="toggleCategory('Oficina Flexible')" class="gc-checkbox-item__input gc-checkbox-item__input--green" />
            <span class="gc-checkbox-item__label">Oficina Flexible</span>
          </label>
          <label class="gc-checkbox-item">
            <input type="checkbox" [checked]="isCategorySelected('Zona Relax')" (change)="toggleCategory('Zona Relax')" class="gc-checkbox-item__input gc-checkbox-item__input--yellow" />
            <span class="gc-checkbox-item__label">Zona Relax</span>
          </label>
          <label class="gc-checkbox-item">
            <input type="checkbox" [checked]="isCategorySelected('Evento')" (change)="toggleCategory('Evento')" class="gc-checkbox-item__input gc-checkbox-item__input--purple" />
            <span class="gc-checkbox-item__label">Eventos</span>
          </label>
        </div>
      </div>

      <!-- Reservas del día -->
      <div class="gc-accordion gc-accordion--reservas">
        <div class="gc-accordion__header">
          <span class="gc-accordion__title">Reservas del día</span>
          <span class="material-icons gc-accordion__chevron">keyboard_arrow_up</span>
        </div>
        <div class="gc-accordion__content gc-accordion__content--scroll">
          @if (reservasService.reservas().length === 0 && !reservasService.isLoading()) {
          <p class="gc-empty-reservas">Sin reservas para este día.</p>
          }
          @for (r of reservasService.reservas(); track r.id) {
          <div class="gc-activity-item">
            <div class="gc-activity-dot" [style.background]="r.resourceName.includes('Sala') ? '#4285f4' : r.resourceName.includes('Auditorio') ? '#8b5cf6' : '#16a34a'"></div>
            <div class="gc-activity-item__body">
              <span class="gc-activity-item__title"><strong>{{ r.resourceName }}</strong></span>
              <span class="gc-activity-item__desc">{{ r.startTime }} – {{ r.endTime }}</span>
              <span class="gc-activity-item__time">{{ r.author }}</span>
            </div>
          </div>
          }
        </div>
      </div>

    </aside>

    <!-- ── CENTRAL CALENDAR VIEW ── -->
    <main class="gc-main-calendar">

      <!-- Error global -->
      @if (reservasService.error()) {
      <div class="gc-error-banner">
        <span class="material-icons">error_outline</span>
        {{ reservasService.error() }}
      </div>
      }

      <!-- Columnas de recursos (header) -->
      <div class="gc-grid-header">
        <div class="gc-grid-header__corner">
          <span class="gc-corner-gmt">GMT-04</span>
        </div>
        <div class="gc-grid-header__columns">
          @for (res of filteredResources(); track res.id; let idx = $index) {
          <div class="gc-col-header" [class.gc-col-header--active]="idx === 0">
            <span class="gc-col-header__day">{{ res.type }}</span>
            <div class="gc-col-header__day-circle" [class.gc-col-header__day-circle--active]="idx === 0">
              <span class="gc-col-header__day-num">{{ res.icon }}</span>
            </div>
            <strong class="gc-col-header__name">{{ res.name }}</strong>
          </div>
          }
        </div>
      </div>

      <!-- Grid de slots -->
      <div class="gc-grid-scroll-area">
        <div class="gc-grid-body">

          <!-- Columna de horas -->
          <div class="gc-hours-column">
            @for (time of timeSlots; track time) {
            <div class="gc-hour-cell">
              <span class="gc-hour-label">{{ time }}</span>
            </div>
            }
          </div>

          <!-- Columnas por recurso -->
          <div class="gc-columns-grid" [style.grid-template-columns]="'repeat(' + filteredResources().length + ', 1fr)'">

            <div class="gc-current-time-line" style="top: 52%;" title="Hora actual aproximada">
              <div class="gc-current-time-line__circle"></div>
            </div>

            @for (res of filteredResources(); track res.id; let colIdx = $index) {
            <div class="gc-resource-column">

              @for (time of timeSlots; track time) {
              <div class="gc-grid-slot-cell">

                @if (isSlotOccupied(res.name, time)) {
                <!-- Slot ocupado -->
                <div class="gc-event gc-event--busy gc-event--color-{{ colIdx % 4 }}" [title]="getReservaForSlot(res.name, time)?.author || 'Reservado'">
                  <div class="gc-event__title">{{ getReservaForSlot(res.name, time)?.author || 'Reservado' }}</div>
                  <div class="gc-event__time">{{ time }} – {{ getEndTime(time) }}</div>
                </div>
                } @else {
                <!-- Slot disponible -->
                <div class="gc-slot-click-zone" (click)="onSlotClick(res, time)" title="Clic para reservar"></div>
                }

                <!-- Popup de confirmación -->
                @if (selectedSlot()?.resource?.id === res.id && selectedSlot()?.time === time) {
                <div class="gc-popup-card" (click)="$event.stopPropagation()">
                  <div class="gc-popup-card__header">
                    <span class="material-icons gc-popup-card__drag">drag_handle</span>
                    <button class="gc-popup-card__close-btn" (click)="closePopup()" title="Cerrar">✕</button>
                  </div>

                  <div class="gc-popup-card__body">
                    <h4 class="gc-popup-card__title">{{ res.name }}</h4>

                    <div class="gc-popup-card__row">
                      <span class="material-icons gc-popup-card__icon">schedule</span>
                      <div class="gc-popup-card__details">
                        <span>{{ activeDateLabel() | titlecase }}</span>
                        <span class="gc-popup-card__time">{{ time }} – {{ getEndTime(time) }}</span>
                      </div>
                    </div>

                    <div class="gc-popup-card__row">
                      <span class="material-icons gc-popup-card__icon">room</span>
                      <span>Capacidad: {{ res.capacity }} personas</span>
                    </div>

                    <div class="gc-popup-card__row">
                      <span class="material-icons gc-popup-card__icon">info_outline</span>
                      <span class="gc-popup-card__tag">{{ res.type }}</span>
                    </div>

                    <!-- Feedback -->
                    @if (confirmError()) {
                    <div class="gc-popup-error">
                      <span class="material-icons" style="font-size:14px">error</span>
                      {{ confirmError() }}
                    </div>
                    }
                    @if (confirmSuccess()) {
                    <div class="gc-popup-success">
                      <span class="material-icons" style="font-size:14px">check_circle</span>
                      ¡Reserva guardada en Supabase!
                    </div>
                    }
                  </div>

                  <div class="gc-popup-card__actions">
                    <button (click)="navigateToNuevo()" class="gc-popup-btn-secondary">Más opciones</button>
                    <button (click)="confirmReserva()" class="gc-popup-btn-primary" [disabled]="confirmLoading()">
                      @if (confirmLoading()) { Guardando... } @else { Guardar }
                    </button>
                  </div>
                </div>
                }

              </div>
              }

            </div>
            }

          </div>
        </div>
      </div>

      @if (filteredResources().length === 0) {
      <div class="gc-empty-state">
        <span class="material-icons gc-empty-state__icon">calendar_today</span>
        <p>No hay recursos seleccionados. Marque las categorías en el panel izquierdo.</p>
      </div>
      }

    </main>

    <!-- ── SIDEBAR DERECHO ── -->
    <aside class="gc-right-sidebar">
      <div class="gc-right-sidebar__icons">
        <button class="gc-right-sidebar__btn gc-right-sidebar__btn--tasks" title="Mis Reservas">
          <span class="material-icons" style="font-size:20px;color:#4285f4">event_available</span>
        </button>
        <div class="gc-right-sidebar__divider"></div>
        <button class="gc-right-sidebar__btn gc-right-sidebar__btn--plus" title="Nueva reserva" (click)="navigateToNuevo()">
          <span class="material-icons">add</span>
        </button>
      </div>
      <button class="gc-right-sidebar__btn gc-right-sidebar__btn--chevron" title="Ocultar panel lateral">
        <span class="material-icons">chevron_right</span>
      </button>
    </aside>

  </div>
</div>