{% extends 'layouts/base.html' %}
{% load static i18n itens_extras %}

{% block extrastyle %}
<link rel="stylesheet" href="{% static 'css/notifications.css' %}">
<link rel="stylesheet" href="{% static 'css/notification-modal.css' %}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<style>
  /* Animações suaves de entrada */
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .notifications-section {
    animation: fadeInUp 0.6s ease-out;
  }
  
  .notifications-section:nth-child(2) {
    animation-delay: 0.2s;
    animation-fill-mode: both;
  }
  
  .stat-card {
    animation: fadeInUp 0.5s ease-out;
  }
  
  .stat-card:nth-child(1) { animation-delay: 0.1s; animation-fill-mode: both; }
  .stat-card:nth-child(2) { animation-delay: 0.2s; animation-fill-mode: both; }
  .stat-card:nth-child(3) { animation-delay: 0.3s; animation-fill-mode: both; }
  
  /* Scrollbar personalizado */
  .modal-container::-webkit-scrollbar {
    width: 8px;
  }
  
  .modal-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
  }
  
  .modal-container::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 10px;
  }
  
  .modal-container::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  }
</style>
{% endblock %}

{% block content %}
<div class="notifications-page">
  <!-- Header Section -->
  <div class="page-header">
    <div class="header-content">
      <div class="header-icon">
        <i class="fas fa-bell"></i>
      </div>
      <div class="header-text">
        <h1>{% trans "Notificações" %}</h1>
        <p>{% trans "Gerencie suas notificações privadas e públicas" %}</p>
      </div>
    </div>
  </div>

  <!-- Breadcrumb -->
  <div class="breadcrumb-container">
    <nav class="breadcrumb-nav">
      <a href="{% url 'dashboard' %}" class="breadcrumb-link">
        <i class="fas fa-home"></i>
        <span>{% trans "Dashboard" %}</span>
      </a>
      <span class="breadcrumb-separator">/</span>
      <span class="breadcrumb-current">{% trans "Notificações" %}</span>
    </nav>
  </div>

  <!-- Statistics Section -->
  <div class="statistics-section">
    <div class="stat-card">
      <div class="stat-icon">
        <i class="fas fa-bell"></i>
      </div>
      <div class="stat-info">
        <div class="stat-value">{{ total_notifications|default:0 }}</div>
        <div class="stat-label">{% trans "Total" %}</div>
      </div>
    </div>
    <div class="stat-card">
      <div class="stat-icon unread">
        <i class="fas fa-bell-slash"></i>
      </div>
      <div class="stat-info">
        <div class="stat-value">{{ unread_count|default:0 }}</div>
        <div class="stat-label">{% trans "Não Lidas" %}</div>
      </div>
    </div>
    <div class="stat-card">
      <div class="stat-icon rewards">
        <i class="fas fa-gift"></i>
      </div>
      <div class="stat-info">
        <div class="stat-value">{{ notifications_with_rewards|default:0 }}</div>
        <div class="stat-label">{% trans "Com Prêmios" %}</div>
      </div>
    </div>
  </div>

  <!-- Actions Section -->
  <div class="actions-section">
    <div class="actions-container">
      <button id="mark-all-as-read" class="action-btn primary">
        <i class="fas fa-check-double"></i>
        <span>{% trans "Marcar todas como lidas" %}</span>
      </button>
      <button id="delete-all-read" class="action-btn danger">
        <i class="fas fa-trash"></i>
        <span>{% trans "Excluir lidas" %}</span>
      </button>
    </div>
  </div>

  <!-- Notifications Content -->
  <div class="notifications-content">
    <!-- Private Notifications -->
    <div class="notifications-section">
      <div class="section-header">
        <div class="section-icon private">
          <i class="fas fa-user-shield"></i>
        </div>
        <div class="section-info">
          <h2>{% trans "Notificações Privadas" %}</h2>
          <p>{% trans "Suas notificações pessoais" %}</p>
        </div>
      </div>

      <div class="notifications-list">
        {% if private_notifications %}
          {% for notification in private_notifications %}
          <div class="notification-card {% if not notification.viewed %}unread{% else %}read{% endif %}" 
               data-notification-id="{{ notification.id }}">
            <div class="notification-icon">
              <i class="fas fa-bell"></i>
            </div>
            <div class="notification-content">
              <div class="notification-header">
                <h3 class="notification-title">{{ notification.get_notification_type_display }}</h3>
                <div class="notification-meta">
                  <span class="notification-date">{{ notification.created_at|date:"d/m/Y H:i" }}</span>
                  {% if not notification.viewed %}
                  <span class="notification-badge">{% trans "Nova" %}</span>
                  {% endif %}
                </div>
              </div>
              <p class="notification-message">{{ notification.message|truncatewords:20 }}</p>
              {% if notification.rewards.exists %}
                <div class="notification-rewards-preview">
                  {% for reward in notification.rewards.all %}
                    {% if reward.fichas_amount and reward.fichas_amount > 0 %}
                      <div class="reward-item-preview" title="{{ reward.fichas_amount }} Fichas" style="background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%); border-radius: 8px; padding: 0.5rem;">
                        <i class="bi bi-coin text-white" style="font-size: 1.2rem;"></i>
                        <span class="reward-amount">{{ reward.fichas_amount }}</span>
                      </div>
                    {% else %}
                      <div class="reward-item-preview" title="{{ reward.item_name }} +{{ reward.item_enchant }} x{{ reward.item_amount }}">
                        <img src="{% item_image_url reward.item_id %}" 
                             alt="{{ reward.item_name }}" 
                             class="reward-item-icon-small">
                        {% if reward.item_amount > 1 %}
                          <span class="reward-amount">x{{ reward.item_amount }}</span>
                        {% endif %}
                      </div>
                    {% endif %}
                  {% endfor %}
                  {% if not notification.rewards_claimed %}
                    <span class="badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; font-size: 0.8rem; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);">
                      <i class="fas fa-gift me-1"></i>Prêmios Disponíveis
                    </span>
                  {% else %}
                    <span class="badge" style="background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); color: white; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; font-size: 0.8rem;">
                      <i class="fas fa-check-circle me-1"></i>Prêmios Reclamados
                    </span>
                  {% endif %}
                </div>
              {% endif %}
            </div>
            <div class="notification-actions">
              <button class="view-btn" onclick="viewNotification({{ notification.id }})">
                <i class="fas fa-eye"></i>
              </button>
            </div>
          </div>
          {% endfor %}
          
          <!-- Paginação Notificações Privadas -->
          {% if private_notifications.has_other_pages %}
          <div class="mt-4">
            {% with page_param='private_page' current_page=private_current_page total_pages=private_total_pages has_previous=private_has_previous has_next=private_has_next previous_page_number=private_previous_page_number next_page_number=private_next_page_number page_range=private_page_range show_first=private_show_first show_last=private_show_last show_first_ellipsis=private_show_first_ellipsis show_last_ellipsis=private_show_last_ellipsis query_params=request.GET.urlencode %}
              {% include 'includes/pagination_custom.html' %}
            {% endwith %}
          </div>
          {% endif %}
        {% else %}
          <div class="empty-state">
            <div class="empty-icon">
              <i class="fas fa-inbox"></i>
            </div>
            <h3>{% trans "Nenhuma notificação privada" %}</h3>
            <p>{% trans "Você não tem notificações privadas no momento" %}</p>
          </div>
        {% endif %}
      </div>
    </div>

    <!-- Public Notifications -->
    <div class="notifications-section">
      <div class="section-header">
        <div class="section-icon public">
          <i class="fas fa-broadcast-tower"></i>
        </div>
        <div class="section-info">
          <h2>{% trans "Notificações Públicas" %}</h2>
          <p>{% trans "Notificações gerais do sistema" %}</p>
        </div>
      </div>

      <div class="notifications-list">
        {% if public_notifications %}
          {% for notification in public_notifications %}
          <div class="notification-card {% if not notification.viewed %}unread{% else %}read{% endif %}" 
               data-notification-id="{{ notification.id }}">
            <div class="notification-icon public">
              <i class="fas fa-broadcast-tower"></i>
            </div>
            <div class="notification-content">
              <div class="notification-header">
                <h3 class="notification-title">{{ notification.get_notification_type_display }}</h3>
                <div class="notification-meta">
                  <span class="notification-date">{{ notification.created_at|date:"d/m/Y H:i" }}</span>
                  {% if not notification.viewed %}
                  <span class="notification-badge">{% trans "Nova" %}</span>
                  {% endif %}
                </div>
              </div>
              <p class="notification-message">{{ notification.message|truncatewords:20 }}</p>
              {% if notification.rewards.exists %}
                <div class="notification-rewards-preview">
                  {% for reward in notification.rewards.all %}
                    {% if reward.fichas_amount and reward.fichas_amount > 0 %}
                      <div class="reward-item-preview" title="{{ reward.fichas_amount }} Fichas" style="background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%); border-radius: 8px; padding: 0.5rem;">
                        <i class="bi bi-coin text-white" style="font-size: 1.2rem;"></i>
                        <span class="reward-amount">{{ reward.fichas_amount }}</span>
                      </div>
                    {% else %}
                      <div class="reward-item-preview" title="{{ reward.item_name }} +{{ reward.item_enchant }} x{{ reward.item_amount }}">
                        <img src="{% item_image_url reward.item_id %}" 
                             alt="{{ reward.item_name }}" 
                             class="reward-item-icon-small">
                        {% if reward.item_amount > 1 %}
                          <span class="reward-amount">x{{ reward.item_amount }}</span>
                        {% endif %}
                      </div>
                    {% endif %}
                  {% endfor %}
                  {% if not notification.rewards_claimed %}
                    <span class="badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; font-size: 0.8rem; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);">
                      <i class="fas fa-gift me-1"></i>Prêmios Disponíveis
                    </span>
                  {% else %}
                    <span class="badge" style="background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); color: white; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; font-size: 0.8rem;">
                      <i class="fas fa-check-circle me-1"></i>Prêmios Reclamados
                    </span>
                  {% endif %}
                </div>
              {% endif %}
            </div>
            <div class="notification-actions">
              <button class="view-btn" onclick="viewNotification({{ notification.id }})">
                <i class="fas fa-eye"></i>
              </button>
            </div>
          </div>
          {% endfor %}
          
          <!-- Paginação Notificações Públicas -->
          {% if public_notifications.has_other_pages %}
          <div class="mt-4">
            {% with page_param='public_page' current_page=public_current_page total_pages=public_total_pages has_previous=public_has_previous has_next=public_has_next previous_page_number=public_previous_page_number next_page_number=public_next_page_number page_range=public_page_range show_first=public_show_first show_last=public_show_last show_first_ellipsis=public_show_first_ellipsis show_last_ellipsis=public_show_last_ellipsis query_params=request.GET.urlencode %}
              {% include 'includes/pagination_custom.html' %}
            {% endwith %}
          </div>
          {% endif %}
        {% else %}
          <div class="empty-state">
            <div class="empty-icon">
              <i class="fas fa-broadcast-tower"></i>
            </div>
            <h3>{% trans "Nenhuma notificação pública" %}</h3>
            <p>{% trans "Não há notificações públicas no momento" %}</p>
          </div>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Return Button -->
  <div class="return-section">
    <a href="{% url 'dashboard' %}" class="return-btn">
      <i class="fas fa-arrow-left"></i>
      <span>{% trans "Voltar ao Dashboard" %}</span>
    </a>
  </div>
</div>

<!-- Notification Modal -->
<div class="modal fade pdl-notification-modal" id="notificationModal" tabindex="-1" aria-labelledby="notificationModalLabel" aria-hidden="true">
  <div class="modal-dialog pdl-notification-modal__dialog" role="document">
    <div class="modal-content pdl-notification-modal__content">
      <div class="modal-header pdl-notification-modal__header">
        <div class="pdl-notification-modal__title" id="notificationModalLabel">{% trans "Detalhes da Notificação" %}</div>
        <button type="button" class="btn-close pdl-notification-modal__close" aria-label="{% trans 'Fechar' %}">
          <i class="bi bi-x-lg" aria-hidden="true"></i>
        </button>
      </div>
      <div class="modal-body pdl-notification-modal__body">
        <!-- Os detalhes da notificação serão carregados aqui -->
      </div>
      <div class="modal-footer pdl-notification-modal__footer">
        <button type="button" id="claim-rewards-btn" class="pdl-notification-modal__claim-btn" style="display: inline-flex !important; order: 1;" disabled>
          <i class="bi bi-gift-fill"></i> {% trans "Reclamar Prêmios" %}
        </button>
        <div id="notification-link-container" class="pdl-notification-modal__link-container" style="order: 2;">
          <a id="notification-link" href="#" class="pdl-notification-modal__link-btn" target="_blank">
            <i class="bi bi-box-arrow-up-right" aria-hidden="true"></i> {% trans "Acessar" %}
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
let currentNotificationId = null;

// Função auxiliar para mostrar modal manualmente
function showModalManually(modalElement) {
  // Remover qualquer backdrop existente primeiro
  const existingBackdrop = document.querySelector('.modal-backdrop');
  if (existingBackdrop) {
    existingBackdrop.remove();
  }
  
  // Remover classe fade inicialmente para garantir que apareça
  modalElement.classList.remove('fade');
  
  // Adicionar classes e estilos necessários
  modalElement.style.display = 'flex';
  modalElement.style.visibility = 'visible';
  modalElement.style.opacity = '1';
  modalElement.style.zIndex = '9999';
  modalElement.style.position = 'fixed';
  modalElement.style.top = '0';
  modalElement.style.left = '0';
  modalElement.style.width = '100%';
  modalElement.style.height = '100%';
  modalElement.style.overflow = 'auto';
  modalElement.style.alignItems = 'center';
  modalElement.style.justifyContent = 'center';
  modalElement.setAttribute('aria-hidden', 'false');
  modalElement.setAttribute('aria-modal', 'true');
  
  // Garantir que o dialog e content também estejam visíveis e centralizados
  const dialog = modalElement.querySelector('.modal-dialog');
  const content = modalElement.querySelector('.modal-content');
  if (dialog) {
    dialog.style.pointerEvents = 'auto';
    dialog.style.margin = 'auto';
    dialog.style.display = 'block';
  }
  if (content) {
    content.style.pointerEvents = 'auto';
  }
  
  // Adicionar classe show após um pequeno delay para animação
  setTimeout(function() {
    modalElement.classList.add('show');
  }, 10);
  
  // Adicionar classes ao body
  document.body.classList.add('modal-open');
  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  if (scrollbarWidth > 0) {
    document.body.style.paddingRight = scrollbarWidth + 'px';
  }
  document.body.style.overflow = 'hidden';
  
  // Criar backdrop
  const backdrop = document.createElement('div');
  backdrop.className = 'modal-backdrop fade show';
  backdrop.style.position = 'fixed';
  backdrop.style.top = '0';
  backdrop.style.left = '0';
  backdrop.style.width = '100%';
  backdrop.style.height = '100%';
  backdrop.style.zIndex = '9998';
  backdrop.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
  document.body.appendChild(backdrop);
  
  // Fechar ao clicar no backdrop
  backdrop.addEventListener('click', function() {
    hideModalManually(modalElement);
  });
  
  // Fechar com ESC
  const escHandler = function(e) {
    if (e.key === 'Escape' || e.keyCode === 27) {
      hideModalManually(modalElement);
      document.removeEventListener('keydown', escHandler);
    }
  };
  document.addEventListener('keydown', escHandler);
  
  // Focar no modal após um pequeno delay
  setTimeout(function() {
    modalElement.focus();
  }, 100);
}

// Função auxiliar para esconder modal manualmente
function hideModalManually(modalElement) {
  if (!modalElement) return;
  
  // Remover classe show primeiro para animação
  modalElement.classList.remove('show');
  
  // Remover backdrop
  const backdrop = document.querySelector('.modal-backdrop');
  if (backdrop) {
    backdrop.classList.remove('show');
    setTimeout(function() {
      if (backdrop && backdrop.parentNode) {
        backdrop.remove();
      }
    }, 150);
  }
  
  // Esconder modal após animação
  setTimeout(function() {
    if (!modalElement) return;
    modalElement.style.display = 'none';
    modalElement.style.visibility = 'hidden';
    modalElement.style.opacity = '0';
    modalElement.setAttribute('aria-hidden', 'true');
    modalElement.setAttribute('aria-modal', 'false');
    
    // Remover classes e estilos do body
    document.body.classList.remove('modal-open');
    document.body.style.overflow = '';
    document.body.style.paddingRight = '';
  }, 150);
}

function viewNotification(id) {
  currentNotificationId = id;
  const modal = document.getElementById('notificationModal');
  const modalBody = document.querySelector('#notificationModal .modal-body');
  const claimBtn = document.getElementById('claim-rewards-btn');
  
  if (!modal || !modalBody) return;
  
  // Mostrar loading
  modalBody.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">Carregando...</span></div></div>';
  
  // Busca dados da notificação via AJAX
  fetch(`/app/notification/detail/${id}/`)
    .then(response => {
      if (!response.ok) throw new Error('Network response was not ok');
      return response.json();
    })
    .then(data => {
      // Construir HTML das recompensas se houver
      let rewardsHTML = '';
      if (data.has_rewards && data.rewards && data.rewards.length > 0) {
        rewardsHTML = '<div class="pdl-notification-details__rewards"><div class="pdl-notification-details__rewards-title"><i class="bi bi-gift-fill"></i> Prêmios:</div><div class="pdl-notification-details__rewards-list">';
        data.rewards.forEach(reward => {
          if (reward.fichas_amount && reward.fichas_amount > 0) {
            rewardsHTML += `
              <div class="pdl-notification-reward-item" style="background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%); border-radius: 8px; padding: 12px; margin-bottom: 8px; display: flex; align-items: center; gap: 12px;">
                <div style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.2); border-radius: 8px; font-size: 20px;">
                  <i class="bi bi-coin" style="color: white;"></i>
                </div>
                <div style="color: white; font-weight: 600;">
                  ${reward.fichas_amount} Fichas
                </div>
              </div>
            `;
          } else if (reward.item_id) {
            const itemImageUrl = `/static/assets/img/l2/icons/5-${reward.item_id}.jpg`;
            rewardsHTML += `
              <div class="pdl-notification-reward-item" style="background: rgba(0,0,0,0.05); border-radius: 8px; padding: 12px; margin-bottom: 8px; display: flex; align-items: center; gap: 12px;">
                <img src="${itemImageUrl}" alt="${reward.item_name || ''}" style="width: 40px; height: 40px; border-radius: 6px;">
                <div style="flex: 1;">
                  <div style="font-weight: 600; color: #1f2937;">${reward.item_name || ''}</div>
                  <div style="font-size: 12px; color: #6b7280;">
                    ID: ${reward.item_id}
                    ${reward.item_enchant > 0 ? ` • +${reward.item_enchant}` : ''}
                    ${reward.item_amount > 1 ? ` • x${reward.item_amount}` : ''}
                  </div>
                </div>
              </div>
            `;
          }
        });
        rewardsHTML += '</div></div>';
      }

      modalBody.innerHTML = `
        <div class="pdl-notification-details">
          <div class="pdl-notification-details__type">
            <i class="bi bi-info-circle-fill"></i> ${data.type || ''}
          </div>
          <div class="pdl-notification-details__message">${data.message || ''}</div>
          ${rewardsHTML}
          <div class="pdl-notification-details__created-at">
            <i class="bi bi-clock"></i> {% trans "Criado em:" %} ${data.created_at || ''}
          </div>
        </div>
      `;

      // Gerenciar botão de reclamar prêmios
      if (claimBtn) {
        // Calcular se há prêmios não reclamados
        const hasUnclaimed = data.has_unclaimed_rewards === true || 
                             (data.has_rewards && data.rewards && data.rewards.length > 0 && data.rewards_claimed !== true);
        
        // Se os prêmios já foram reclamados, esconder o botão
        if (!hasUnclaimed && data.rewards_claimed === true) {
          claimBtn.style.setProperty('display', 'none', 'important');
        } else {
          // Mostrar o botão se houver prêmios não reclamados
          claimBtn.setAttribute('data-notification-id', id);
          claimBtn.style.setProperty('display', 'inline-flex', 'important');
          claimBtn.style.setProperty('visibility', 'visible', 'important');
          claimBtn.style.setProperty('opacity', '1', 'important');
          claimBtn.style.setProperty('width', 'auto', 'important');
          claimBtn.style.setProperty('height', 'auto', 'important');
          claimBtn.style.setProperty('min-width', '150px', 'important');
          claimBtn.style.setProperty('min-height', '40px', 'important');
          claimBtn.style.setProperty('position', 'relative', 'important');
          claimBtn.style.setProperty('z-index', '10', 'important');
          
          // Controlar apenas o estado disabled
          if (hasUnclaimed) {
            claimBtn.disabled = false;
            claimBtn.style.setProperty('cursor', 'pointer', 'important');
          } else {
            claimBtn.disabled = true;
            claimBtn.style.setProperty('cursor', 'not-allowed', 'important');
          }
        }
      }

      // Gerenciar link
      const linkContainer = document.getElementById('notification-link-container');
      const linkButton = document.getElementById('notification-link');

      if (linkContainer && linkButton) {
        if (data.link) {
          linkButton.href = data.link;
          linkContainer.classList.add('pdl-notification-modal__link-container--visible');
        } else {
          linkContainer.classList.remove('pdl-notification-modal__link-container--visible');
        }
      }

      // Mostrar modal
      showModalManually(modal);
    })
    .catch(error => {
      console.error('Erro ao carregar notificação:', error);
      modalBody.innerHTML = `<div class="pdl-notification-details__message" style="color: #ef4444;">{% trans "Erro ao carregar os detalhes da notificação." %}</div>`;
    });
}

function claimNotificationRewards(notificationId) {
  const id = notificationId || currentNotificationId;
  if (!id) return;
  
  const btn = document.getElementById('claim-rewards-btn');
  if (!btn || btn.disabled) return;
  
  const originalHTML = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '<i class="bi bi-hourglass-split"></i> {% trans "Reclamando..." %}';

  const csrfToken = getCookie('csrftoken');
  
  fetch(`/app/notification/claim-rewards/${id}/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
      'X-Requested-With': 'XMLHttpRequest'
    },
  })
    .then(response => {
      if (!response.ok) throw new Error('Network response was not ok');
      return response.json();
    })
    .then(data => {
      if (data.status === 'success') {
        // Recarregar os detalhes da notificação para atualizar o status
        fetch(`/app/notification/detail/${id}/`)
          .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
          })
          .then(notificationData => {
            const modalBody = document.querySelector('#notificationModal .modal-body');
            
            if (modalBody) {
              // Construir HTML das recompensas se houver
              let rewardsHTML = '';
              if (notificationData.has_rewards && notificationData.rewards && notificationData.rewards.length > 0) {
                rewardsHTML = '<div class="pdl-notification-details__rewards"><div class="pdl-notification-details__rewards-title"><i class="bi bi-gift-fill"></i> Prêmios:</div><div class="pdl-notification-details__rewards-list">';
                notificationData.rewards.forEach(reward => {
                  if (reward.fichas_amount && reward.fichas_amount > 0) {
                    rewardsHTML += `
                      <div class="pdl-notification-reward-item" style="background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%); border-radius: 8px; padding: 12px; margin-bottom: 8px; display: flex; align-items: center; gap: 12px;">
                        <div style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.2); border-radius: 8px; font-size: 20px;">
                          <i class="bi bi-coin" style="color: white;"></i>
                        </div>
                        <div style="color: white; font-weight: 600;">
                          ${reward.fichas_amount} Fichas
                        </div>
                      </div>
                    `;
                  } else if (reward.item_id) {
                    const itemImageUrl = `/static/assets/img/l2/icons/5-${reward.item_id}.jpg`;
                    rewardsHTML += `
                      <div class="pdl-notification-reward-item" style="background: rgba(0,0,0,0.05); border-radius: 8px; padding: 12px; margin-bottom: 8px; display: flex; align-items: center; gap: 12px;">
                        <img src="${itemImageUrl}" alt="${reward.item_name || ''}" style="width: 40px; height: 40px; border-radius: 6px;">
                        <div style="flex: 1;">
                          <div style="font-weight: 600; color: #1f2937;">${reward.item_name || ''}</div>
                          <div style="font-size: 12px; color: #6b7280;">
                            ID: ${reward.item_id}
                            ${reward.item_enchant > 0 ? ` • +${reward.item_enchant}` : ''}
                            ${reward.item_amount > 1 ? ` • x${reward.item_amount}` : ''}
                          </div>
                        </div>
                      </div>
                    `;
                  }
                });
                rewardsHTML += '</div></div>';
              }

              // Mostrar mensagem de sucesso
              const successMsg = document.createElement('div');
              successMsg.className = 'alert alert-success';
              successMsg.style.marginBottom = '16px';
              successMsg.innerHTML = `<i class="bi bi-check-circle-fill"></i> ${data.message || 'Prêmios reclamados com sucesso!'}`;
              
              modalBody.innerHTML = `
                <div class="pdl-notification-details">
                  <div class="pdl-notification-details__type">
                    <i class="bi bi-info-circle-fill"></i> ${notificationData.type || ''}
                  </div>
                  <div class="pdl-notification-details__message">${notificationData.message || ''}</div>
                  ${rewardsHTML}
                  <div class="pdl-notification-details__created-at">
                    <i class="bi bi-clock"></i> {% trans "Criado em:" %} ${notificationData.created_at || ''}
                  </div>
                </div>
              `;
              
              modalBody.insertBefore(successMsg, modalBody.firstChild);
            }

            // Atualizar estado do botão de reclamar baseado nos dados atualizados
            const claimBtn = document.getElementById('claim-rewards-btn');
            if (claimBtn) {
              const hasUnclaimed = notificationData.has_unclaimed_rewards === true || 
                                   (notificationData.has_rewards && notificationData.rewards && notificationData.rewards.length > 0 && notificationData.rewards_claimed !== true);
              
              // Se os prêmios já foram reclamados, esconder o botão
              if (!hasUnclaimed && notificationData.rewards_claimed === true) {
                claimBtn.style.setProperty('display', 'none', 'important');
              } else {
                // Mostrar o botão se houver prêmios não reclamados
                claimBtn.style.setProperty('display', 'inline-flex', 'important');
                claimBtn.style.setProperty('visibility', 'visible', 'important');
                claimBtn.style.setProperty('opacity', '1', 'important');
                claimBtn.setAttribute('data-notification-id', id);
                
                // Controlar apenas o estado disabled
                if (hasUnclaimed) {
                  claimBtn.disabled = false;
                  claimBtn.style.setProperty('cursor', 'pointer', 'important');
                } else {
                  claimBtn.disabled = true;
                  claimBtn.style.setProperty('cursor', 'not-allowed', 'important');
                }
              }
            }

            // Recarregar a página após um delay para atualizar a lista
            setTimeout(() => location.reload(), 2000);
          })
          .catch(error => {
            console.error('Erro ao recarregar detalhes:', error);
            setTimeout(() => location.reload(), 1000);
          });
      } else {
        alert(data.error || 'Erro ao reclamar prêmios.');
        if (btn) {
          btn.disabled = false;
          btn.innerHTML = originalHTML;
        }
      }
    })
    .catch(error => {
      console.error('Erro ao reclamar prêmios:', error);
      alert('Erro de conexão com o servidor.');
      if (btn) {
        btn.disabled = false;
        btn.innerHTML = originalHTML;
      }
    });
}

function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

function closeModal() {
  const modal = document.getElementById('notificationModal');
  if (modal) {
    hideModalManually(modal);
  }
}

// Inicializar event listeners quando o DOM estiver pronto
document.addEventListener('DOMContentLoaded', function() {
  const notificationModal = document.getElementById('notificationModal');
  
  // Adicionar event listener permanente ao botão de reclamar prêmios
  const claimRewardsBtn = document.getElementById('claim-rewards-btn');
  if (claimRewardsBtn) {
    claimRewardsBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      const notificationId = this.getAttribute('data-notification-id');
      if (notificationId) {
        claimNotificationRewards(notificationId);
      }
    });
  }
  
  if (notificationModal) {
    // Função para fechar o modal
    function closeModalHandler(e) {
      if (e) {
        e.preventDefault();
        e.stopPropagation();
      }
      hideModalManually(notificationModal);
    }
    
    // Adicionar listeners usando delegação de eventos no modal
    notificationModal.addEventListener('click', function(e) {
      const target = e.target;
      
      // Verificar se o clique foi em um botão de fechar
      const isCloseButton = target.classList.contains('pdl-notification-modal__close') ||
                            target.classList.contains('btn-close') ||
                            target.closest('.pdl-notification-modal__close') ||
                            target.closest('.btn-close') ||
                            (target.tagName === 'I' && target.closest('button[class*="close"]'));
      
      if (isCloseButton) {
        closeModalHandler(e);
        return false;
      }
      
      // Fechar ao clicar fora do modal (no backdrop)
      if (e.target === notificationModal) {
        closeModalHandler(e);
        return false;
      }
    });
    
    // Adicionar listeners diretos também para garantir
    setTimeout(function() {
      const closeBtnHeader = notificationModal.querySelector('.pdl-notification-modal__close, .btn-close');
      if (closeBtnHeader) {
        closeBtnHeader.onclick = function(e) {
          e.preventDefault();
          e.stopPropagation();
          closeModalHandler(e);
        };
      }
    }, 100);
  }
});

// Marcar todas como lidas
document.getElementById('mark-all-as-read').addEventListener('click', function() {
  if (confirm('{% trans "Tem certeza que deseja marcar todas as notificações como lidas?" %}')) {
    fetch('{% url "notification:mark_all_as_read" %}', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
      },
    })
    .then(response => response.json())
    .then(data => {
      if (data.status === 'ok') {
        location.reload();
      } else {
        alert('{% trans "Erro ao marcar notificações como lidas." %}');
      }
    })
    .catch(error => {
      console.error('Erro:', error);
      alert('{% trans "Erro ao marcar notificações como lidas." %}');
    });
  }
});

// Excluir notificações lidas
document.getElementById('delete-all-read').addEventListener('click', function() {
  if (confirm('{% trans "Tem certeza que deseja excluir todas as notificações lidas?" %}')) {
    // Deletar notificações privadas lidas
    const privateRead = document.querySelectorAll('.notification-card.read[data-notification-id]');
    const privateIds = Array.from(privateRead).map(el => el.getAttribute('data-notification-id'));
    
    if (privateIds.length > 0) {
      // Deletar via AJAX ou recarregar após confirmação
      fetch('{% url "notification:clear_all_notifications" %}', {
        method: 'POST',
        headers: {
          'X-CSRFToken': getCookie('csrftoken'),
          'Content-Type': 'application/json',
        },
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'ok') {
          location.reload();
        }
      })
      .catch(error => {
        console.error('Erro:', error);
        alert('{% trans "Erro ao excluir notificações." %}');
      });
    } else {
      alert('{% trans "Não há notificações lidas para excluir." %}');
    }
  }
});
</script>
{% endblock %}
