<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 12000;">
  <div class="toast border-0 shadow" [class.show]="toastOpen" [class.text-bg-success]="toastType === 'success'" [class.text-bg-danger]="toastType === 'danger'">
    <div class="toast-header border-bottom-0">
      <strong class="me-auto">LineGestão</strong>
      <button type="button" class="btn-close" (click)="hideToast()"></button>
    </div>
    <div class="toast-body bg-white rounded-bottom text-dark fw-bold">{{ toastMessage }}</div>
  </div>
</div>

<section class="vigencia-page">
  <span class="page-blob blob-1"></span>
  <span class="page-blob blob-2"></span>
  <span class="page-blob blob-3"></span>

  <div class="container-geral-responsive">
    <div class="geral-card">

      <div class="geral-header">
        <div class="header-row-top">
          <div class="title-badge"><i class="bi bi-calendar2-week"></i> VIGÊNCIA</div>
          <div class="header-title">
            <h5 class="title">GESTÃO DE VIGÊNCIA</h5>
            <small class="subtitle">Controle de contratos e fidelização</small>
          </div>
          <div class="header-actions d-flex gap-2 justify-content-end">
            <button *ngIf="isSysAdmin" class="btn btn-brand btn-sm" (click)="openCreate()">
              <i class="bi bi-plus-circle me-1"></i> Nova Vigência
            </button>
          </div>
        </div>

        <div class="mureg-kpis mt-4 animate-fade-in" *ngIf="viewMode === 'groups'">
          <div class="kpi">
            <span class="lbl">Total Clientes</span>
            <span class="val">{{ kpiTotalClientes }}</span>
          </div>
          <div class="kpi">
            <span class="lbl">Total Linhas</span>
            <span class="val">{{ kpiTotalLinhas }}</span>
          </div>
          <div class="kpi">
            <span class="lbl text-danger">Total Vencidos</span>
            <span class="val text-danger">{{ kpiTotalVencidos }}</span>
          </div>
        </div>

        <div class="controls mt-3 mb-2 d-flex flex-wrap gap-3 align-items-center justify-content-between">
          <div class="input-group input-group-sm search-group">
            <span class="input-group-text">
              <i class="bi" [class.bi-search]="!loading" [class.bi-hourglass-split]="loading"></i>
            </span>
            <input
              type="search"
              class="form-control"
              placeholder="Pesquisar..."
              inputmode="search"
              enterkeyhint="search"
              autocomplete="off"
              [(ngModel)]="search"
              (ngModelChange)="onSearchChange()">
            <button
              class="btn btn-outline-secondary btn-clear"
              type="button"
              *ngIf="search"
              (click)="clearFilters()">
              <i class="bi bi-x-lg"></i>
            </button>
          </div>

          <div class="page-size d-flex align-items-center gap-2">
             <span class="text-muted small fw-bold text-uppercase" style="font-size: 0.75rem;">Itens por pág:</span>
             <app-select class="select-glass" size="sm" [options]="pageSizeOptions" [(ngModel)]="pageSize" (ngModelChange)="fetch(1)" [disabled]="loading" style="width: 80px;"></app-select>
          </div>
        </div>
      </div>

      <div class="geral-body">
        <div class="groups-container">
          
          <div class="text-center p-5" *ngIf="loading">
             <div class="spinner-border text-brand" role="status"></div>
          </div>

          <div class="empty-state text-center p-5" *ngIf="!loading && groups.length === 0">
             Nenhum dado encontrado.
          </div>

          <div *ngFor="let g of groups" class="client-group-card mb-3" [class.expanded]="expandedGroup === g.cliente">
             
             <div class="group-header" (click)="toggleGroup(g)">
                <div class="group-info">
                   <h6 class="group-title mb-0">{{ g.cliente }}</h6>
                   <div class="group-badges mt-1">
                      <span class="badge-pill total">{{ g.linhas }} Registros</span>
                      <span class="badge-pill danger" *ngIf="g.vencidos > 0">{{ g.vencidos }} Vencidos</span>
                      <span class="badge-pill ok" *ngIf="g.linhas - g.vencidos > 0">{{ g.linhas - g.vencidos }} Ativos</span>
                   </div>
                </div>
                <div class="group-toggle-icon"><i class="bi bi-chevron-down"></i></div>
             </div>

             <div class="group-body" *ngIf="expandedGroup === g.cliente">
                
                <div class="group-body-top d-flex justify-content-between align-items-center px-4 py-2 border-bottom bg-white">
                    <small class="text-muted fw-bold">Linhas do Cliente</small>
                    <span class="chip-muted">Total: {{ g.total | currency:'BRL' }}</span>
                </div>

                <div class="text-center p-4" *ngIf="expandedLoading">
                   <div class="spinner-border spinner-border-sm text-brand"></div>
                </div>

                <div class="table-wrap inner-table-wrap" *ngIf="!expandedLoading">
                   <table class="table table-modern align-middle text-center mb-0">
                      <thead>
                        <tr>
                           <th>ITEM</th>
                           <th>LINHA</th>
                           <th>CONTA</th>
                           <th>USUÁRIO</th>
                           <th class="plano-col">PLANO</th>
                           <th>EFETIVAÇÃO</th>
                           <th>VENCIMENTO</th>
                           <th class="text-end">TOTAL</th>
                           <th class="actions-col">AÇÕES</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr *ngFor="let row of groupRows" class="table-row-item">
                           <td class="text-muted fw-bold">{{ row.item }}</td>
                           <td class="fw-black text-blue">{{ row.linha }}</td>
                           <td class="text-dark small">{{ row.conta || '-' }}</td>
                           <td class="text-muted small">{{ row.usuario || '-' }}</td>
                           <td class="text-muted small td-clip plano-col" [title]="row.planoContrato">{{ row.planoContrato || '-' }}</td>
                           
                           <td class="text-muted small fw-bold">
                              {{ row.dtEfetivacaoServico ? (row.dtEfetivacaoServico | date:'dd/MM/yyyy') : '-' }}
                           </td>

                           <td class="fw-bold" [class.text-danger]="isVencido(row.dtTerminoFidelizacao)">
                              {{ row.dtTerminoFidelizacao ? (row.dtTerminoFidelizacao | date:'dd/MM/yyyy') : '-' }}
                           </td>

                           <td class="text-end fw-black text-dark">
                              {{ (row.total || 0) | currency:'BRL' }}
                           </td>

                           <td class="actions-col">
                              <div class="action-group justify-content-center">
                                 <span class="renew-chip" *ngIf="row.autoRenewYears">{{ getRenewalBadge(row) }}</span>
                                 <button
                                   *ngIf="isAVencer(row.dtTerminoFidelizacao)"
                                   class="btn btn-primary btn-xs"
                                   (click)="scheduleAutoRenew(row)"
                                   title="Renovar por mais 2 anos">
                                   Renovar +2 anos
                                 </button>
                                 <button class="btn-icon primary" (click)="openDetails(row)" title="Ver Detalhes"><i class="bi bi-eye"></i></button>
                                 <button *ngIf="isSysAdmin" class="btn-icon primary" (click)="openEdit(row)" title="Editar"><i class="bi bi-pencil-square"></i></button>
                                 <button *ngIf="isSysAdmin" class="btn-icon danger" (click)="openDelete(row)" title="Excluir"><i class="bi bi-trash"></i></button>
                              </div>
                           </td>
                        </tr>
                        <tr *ngIf="groupRows.length === 0">
                           <td colspan="9" class="text-center py-4 text-muted fw-bold">Nenhuma linha encontrada.</td>
                        </tr>
                      </tbody>
                   </table>
                </div>
             </div>
          </div>
        </div>
      </div>

      <div class="geral-footer">
        <div class="small text-muted fw-bold">Mostrando {{ (page - 1) * pageSize + 1 }}–{{ (page * pageSize) > total ? total : (page * pageSize) }} de {{ total }} Clientes</div>
        <nav>
           <ul class="pagination pagination-sm mb-0 pagination-modern">
              <li class="page-item" [class.disabled]="page <= 1"><button class="page-link" (click)="fetch(page - 1)">Anterior</button></li>
              <li class="page-item active"><button class="page-link">{{ page }}</button></li>
              <li class="page-item" [class.disabled]="page >= totalPages"><button class="page-link" (click)="fetch(page + 1)">Próxima</button></li>
           </ul>
        </nav>
      </div>

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

<div class="lg-backdrop" *ngIf="detailsOpen || editOpen || deleteOpen || createOpen" (click)="closeDetails(); closeEdit(); cancelDelete(); closeCreate()"></div>

<div class="lg-modal" *ngIf="detailsOpen">
  <div class="lg-modal-card modal-lg" (click)="$event.stopPropagation()">
    <div class="modal-header">
      <div class="modal-title">
        <span class="icon-bg primary-soft"><i class="bi bi-card-list"></i></span>
        Detalhes da Vigência
      </div>
      <button class="btn-icon" (click)="closeDetails()"><i class="bi bi-x-lg"></i></button>
    </div>

    <div class="modal-body bg-light-gray">
      <div class="details-dashboard">
        <div class="detail-box">
          <div class="box-header justify-content-center">
            <span><i class="bi bi-card-text me-2"></i> Informações da Linha</span>
          </div>
          <div class="box-body">
            <div class="info-grid">
              <div class="info-item span-2">
                <span class="lbl">Cliente</span>
                <span class="val">{{ selectedRow?.cliente || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="lbl">Linha</span>
                <span class="val fw-black text-blue">{{ selectedRow?.linha || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="lbl">Conta</span>
                <span class="val">{{ selectedRow?.conta || '-' }}</span>
              </div>
              <div class="info-item span-2">
                <span class="lbl">Usuário</span>
                <span class="val">{{ selectedRow?.usuario || '-' }}</span>
              </div>
              <div class="info-item span-2">
                <span class="lbl">Plano</span>
                <span class="val">{{ selectedRow?.planoContrato || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="lbl">Efetivação</span>
                <span class="val">{{ selectedRow?.dtEfetivacaoServico ? (selectedRow?.dtEfetivacaoServico | date:'dd/MM/yyyy') : '-' }}</span>
              </div>
              <div class="info-item">
                <span class="lbl">Término</span>
                <span class="val" [class.text-danger]="isVencido(selectedRow?.dtTerminoFidelizacao)">
                  {{ selectedRow?.dtTerminoFidelizacao ? (selectedRow?.dtTerminoFidelizacao | date:'dd/MM/yyyy') : '-' }}
                </span>
              </div>
              <div class="info-item">
                <span class="lbl">Situação</span>
                <span class="status-pill" [class.is-danger]="isVencido(selectedRow?.dtTerminoFidelizacao)">
                  {{ isVencido(selectedRow?.dtTerminoFidelizacao) ? 'Vencido' : 'Ativo' }}
                </span>
              </div>
              <div class="info-item">
                <span class="lbl">Renovação</span>
                <span class="val">
                  {{ selectedRow?.autoRenewYears ? ('Auto +' + selectedRow?.autoRenewYears + ' ano(s)') : 'Não programada' }}
                </span>
              </div>
              <div class="info-item">
                <span class="lbl">Valor Total</span>
                <span class="val text-brand">{{ (selectedRow?.total || 0) | currency:'BRL' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="modal-footer p-3 text-end border-top">
      <button class="btn btn-glass btn-sm" (click)="closeDetails()">Fechar</button>
    </div>
  </div>
</div>

<!-- CREATE MODAL -->
<div class="lg-modal" *ngIf="createOpen">
  <div class="lg-modal-card modal-xl create-modal" (click)="$event.stopPropagation()">
    <div class="modal-header">
      <div class="modal-title">
        <span class="icon-bg primary-soft"><i class="bi bi-plus-circle"></i></span>
        Nova Vigência
      </div>
      <button class="btn-icon" (click)="closeCreate()"><i class="bi bi-x-lg"></i></button>
    </div>

    <div class="modal-body bg-light-gray">
      <div class="edit-sections">
        <details open class="detail-box">
          <summary class="box-header">
            <span><i class="bi bi-link-45deg me-2"></i> Vínculo com GERAL</span>
            <i class="bi bi-chevron-down ms-auto transition-icon"></i>
          </summary>
          <div class="box-body">
            <div class="form-grid">
              <div class="form-field span-2">
                <label>Cliente (GERAL)</label>
                <app-select
                  class="form-select"
                  size="sm"
                  [options]="clientsFromGeral"
                  [(ngModel)]="createModel.selectedClient"
                  (ngModelChange)="onCreateClientChange()"
                  [disabled]="createClientsLoading"
                ></app-select>
              </div>
              <div class="form-field span-2">
                <label>Linha (GERAL)</label>
                <app-select
                  class="form-select"
                  size="sm"
                  [options]="lineOptionsCreate"
                  labelKey="label"
                  valueKey="id"
                  [(ngModel)]="createModel.mobileLineId"
                  (ngModelChange)="onCreateLineChange()"
                  [disabled]="createLinesLoading || !createModel.selectedClient"
                ></app-select>
              </div>
            </div>
          </div>
        </details>

        <details open class="detail-box">
          <summary class="box-header">
            <span><i class="bi bi-person-badge me-2"></i> Identificação</span>
            <i class="bi bi-chevron-down ms-auto transition-icon"></i>
          </summary>
          <div class="box-body">
            <div class="form-grid">
              <div class="form-field"><label>Cliente</label><input class="form-control form-control-sm" [(ngModel)]="createModel.cliente" /></div>
              <div class="form-field field-line"><label>Linha</label><input class="form-control form-control-sm" inputmode="numeric" [(ngModel)]="createModel.linha" /></div>
              <div class="form-field"><label>Conta</label><input class="form-control form-control-sm" [(ngModel)]="createModel.conta" /></div>
              <div class="form-field"><label>Usuário</label><input class="form-control form-control-sm" [(ngModel)]="createModel.usuario" /></div>
              <div class="form-field span-2">
                <label>Plano</label>
                <app-select
                  *ngIf="planOptions.length > 0"
                  class="form-select"
                  size="sm"
                  [options]="planOptions"
                  [(ngModel)]="createModel.planoContrato"
                  (ngModelChange)="onCreatePlanChange()"
                ></app-select>
                <input
                  *ngIf="planOptions.length === 0"
                  class="form-control form-control-sm"
                  [(ngModel)]="createModel.planoContrato"
                  (ngModelChange)="onCreatePlanChange()"
                />
              </div>
              <div class="form-field field-item field-auto">
                <label>Item (Automático)</label>
                <input class="form-control form-control-sm bg-light" type="number" [(ngModel)]="createModel.item" readonly title="Gerado automaticamente pelo sistema" />
                <small class="field-hint">Gerado automaticamente pelo sistema</small>
              </div>
            </div>
          </div>
        </details>

        <details open class="detail-box">
          <summary class="box-header">
            <span><i class="bi bi-calendar-event me-2"></i> Vigência e Valor</span>
            <i class="bi bi-chevron-down ms-auto transition-icon"></i>
          </summary>
          <div class="box-body">
            <div class="form-grid">
              <div class="form-field"><label>Efetivação</label><input class="form-control form-control-sm" type="date" [(ngModel)]="createEfetivacao" /></div>
              <div class="form-field"><label>Término</label><input class="form-control form-control-sm" type="date" [(ngModel)]="createTermino" /></div>
              <div class="form-field span-2"><label>Total</label><input class="form-control form-control-sm" type="number" [(ngModel)]="createModel.total" /></div>
            </div>
          </div>
        </details>
      </div>
    </div>

    <div class="modal-footer p-3 text-end border-top">
      <button class="btn btn-glass btn-sm me-2" (click)="closeCreate()">Cancelar</button>
      <button class="btn btn-brand btn-sm" [disabled]="createSaving" (click)="saveCreate()">
        {{ createSaving ? 'Salvando...' : 'Salvar' }}
      </button>
    </div>
  </div>
</div>

<!-- EDIT MODAL -->
<div class="lg-modal" *ngIf="editOpen">
  <div class="lg-modal-card modal-xl" (click)="$event.stopPropagation()">
    <div class="modal-header">
      <div class="modal-title">
        <span class="icon-bg primary-soft"><i class="bi bi-pencil-square"></i></span>
        Editar Vigência
      </div>
      <button class="btn-icon" (click)="closeEdit()"><i class="bi bi-x-lg"></i></button>
    </div>

    <div class="modal-body bg-light-gray" *ngIf="editModel">
      <div class="edit-sections">
        <details open class="detail-box">
          <summary class="box-header">
            <span><i class="bi bi-person-badge me-2"></i> Identificação</span>
            <i class="bi bi-chevron-down ms-auto transition-icon"></i>
          </summary>
          <div class="box-body">
            <div class="form-grid">
              <div class="form-field"><label>Cliente</label><input class="form-control form-control-sm" [(ngModel)]="editModel.cliente" /></div>
              <div class="form-field field-line"><label>Linha</label><input class="form-control form-control-sm" inputmode="numeric" [(ngModel)]="editModel.linha" /></div>
              <div class="form-field"><label>Conta</label><input class="form-control form-control-sm" [(ngModel)]="editModel.conta" /></div>
              <div class="form-field"><label>Usuário</label><input class="form-control form-control-sm" [(ngModel)]="editModel.usuario" /></div>
              <div class="form-field span-2"><label>Plano</label><input class="form-control form-control-sm" [(ngModel)]="editModel.planoContrato" (ngModelChange)="onEditPlanChange()" /></div>
            </div>
          </div>
        </details>

        <details open class="detail-box">
          <summary class="box-header">
            <span><i class="bi bi-calendar-event me-2"></i> Vigência e Valor</span>
            <i class="bi bi-chevron-down ms-auto transition-icon"></i>
          </summary>
          <div class="box-body">
            <div class="form-grid">
              <div class="form-field"><label>Efetivação</label><input class="form-control form-control-sm" type="date" [(ngModel)]="editEfetivacao" /></div>
              <div class="form-field"><label>Término</label><input class="form-control form-control-sm" type="date" [(ngModel)]="editTermino" /></div>
              <div class="form-field span-2"><label>Total</label><input class="form-control form-control-sm" type="number" [(ngModel)]="editModel.total" /></div>
            </div>
          </div>
        </details>
      </div>
    </div>

    <div class="modal-footer p-3 text-end border-top">
      <button class="btn btn-glass btn-sm me-2" (click)="closeEdit()">Cancelar</button>
      <button class="btn btn-primary btn-sm" [disabled]="editSaving" (click)="saveEdit()">
        {{ editSaving ? 'Salvando...' : 'Salvar' }}
      </button>
    </div>
  </div>
</div>

<!-- DELETE MODAL -->
<div class="lg-modal" *ngIf="deleteOpen">
  <div class="lg-modal-card modal-lg" (click)="$event.stopPropagation()">
    <div class="modal-header">
      <div class="modal-title">
        <span class="icon-bg danger-soft"><i class="bi bi-trash"></i></span>
        Remover Vigência
      </div>
      <button class="btn-icon" (click)="cancelDelete()"><i class="bi bi-x-lg"></i></button>
    </div>
    <div class="modal-body bg-light-gray">
      <div class="confirm-delete">
        <div class="confirm-icon"><i class="bi bi-trash"></i></div>
        <p class="mb-0">Confirma remover o registro <strong>{{ deleteTarget?.linha }}</strong>?</p>
      </div>
    </div>
    <div class="modal-footer p-3 text-end border-top">
      <button class="btn btn-glass btn-sm me-2" (click)="cancelDelete()">Cancelar</button>
      <button class="btn btn-danger btn-sm" (click)="confirmDelete()">Excluir</button>
    </div>
  </div>
</div>

