---
interface Props {
  initialLikes?: number;
  initialDislikes?: number;
  postId: string;
}

const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
---

<div class="post-reactions" data-post-id={postId}>
  <button 
    class="reaction-btn like-btn" 
    data-action="like" 
    aria-label="Нравится"
    type="button"
  >
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="reaction-icon">
      <path d="M7 10v12"></path>
      <path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"></path>
    </svg>
    <span class="reaction-count" data-count="likes">{initialLikes}</span>
  </button>

  <button 
    class="reaction-btn dislike-btn" 
    data-action="dislike" 
    aria-label="Не нравится"
    type="button"
  >
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="reaction-icon">
      <path d="M17 14V2"></path>
      <path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"></path>
    </svg>
    <span class="reaction-count" data-count="dislikes">{initialDislikes}</span>
  </button>
</div>

<style>
  .post-reactions {
    display: flex;
    gap: 0.5rem;
  }

  .reaction-btn {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.5rem 0.875rem;
    background: rgba(15, 23, 42, 0.75);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 2rem;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    font-size: 0.875rem;
    font-weight: 600;
    color: #ffffff;
    backdrop-filter: blur(10px);
  }

  .reaction-icon {
    width: 1rem;
    height: 1rem;
    transition: transform 0.2s ease;
  }

  .reaction-count {
    min-width: 1rem;
    text-align: center;
  }

  .like-btn:hover,
  .like-btn.active {
    background: #22c55e;
    border-color: #22c55e;
    transform: scale(1.05);
  }

  .dislike-btn:hover,
  .dislike-btn.active {
    background: #ef4444;
    border-color: #ef4444;
    transform: scale(1.05);
  }

  .reaction-btn:active {
    transform: scale(0.95);
  }

  .reaction-btn:hover .reaction-icon {
    transform: scale(1.2);
  }

  @media (max-width: 768px) {
    .reaction-btn {
      padding: 0.4rem 0.75rem;
      font-size: 0.8rem;
    }
    .post-reactions {
      align-items: flex-end;
    }
  }

  :global(.toast-link) {
    color: #60a5fa;
    text-decoration: underline;
    font-size: 0.875rem;
    margin-left: 0.5rem;
    flex-shrink: 0;
  }

  :global(.toast-link:hover) {
    color: #93c5fd;
  }
</style>

<script>
  import { pb } from '../../lib/pb';

  console.log('PostReactionButtons loaded');

  function showToast(message: string, type: string = 'info', duration: number = 3000, link?: { text: string; href: string }) {
    console.log('showToast called:', message, type);
    const container = document.querySelector('.toast-container');
    console.log('toast-container found:', container);
    if (!container) {
      console.error('Toast container not found!');
      return;
    }

    const toast = document.createElement('div');
    toast.className = `toast-item toast-${type}`;
    toast.innerHTML = `
      <div class="toast-icon">
        ${type === 'success' ? '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>' : ''}
        ${type === 'error' ? '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>' : ''}
        ${type === 'warning' ? '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 512 512"><path fill="currentColor" d="M240 176h32v176h-32zm0 208h32v32h-32z"/><path fill="currentColor" d="M274.014 16h-36.028L16 445.174V496h480v-50.826ZM464 464H48v-11.041L256 50.826l208 402.133Z"/></svg>' : ''}
        ${type === 'info' ? '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>' : ''}
      </div>
      <span class="toast-message">${message}</span>
      ${link ? `<a href="${link.href}" class="toast-link">${link.text}</a>` : ''}
      <button class="toast-close" aria-label="Закрыть">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
      </button>
    `;

    const closeBtn = toast.querySelector('.toast-close');
    closeBtn?.addEventListener('click', () => {
      toast.classList.remove('show');
      toast.classList.add('hide');
      setTimeout(() => toast.remove(), 300);
    });

    container.appendChild(toast);
    requestAnimationFrame(() => toast.classList.add('show'));

    if (duration > 0) {
      setTimeout(() => {
        toast.classList.remove('show');
        toast.classList.add('hide');
        setTimeout(() => toast.remove(), 300);
      }, duration);
    }
  }

  async function handleVote(postId: string, voteType: 'like' | 'dislike') {
    const container = document.querySelector(`[data-post-id="${postId}"]`);
    if (!container) return;

    const likeBtn = container.querySelector('.like-btn') as HTMLButtonElement;
    const dislikeBtn = container.querySelector('.dislike-btn') as HTMLButtonElement;
    const likesCount = container.querySelector('[data-count="likes"]');
    const dislikesCount = container.querySelector('[data-count="dislikes"]');

    if (!pb.authStore.isValid) {
      console.log('pb.authStore.isValid:', pb.authStore.isValid);
      console.log('pb.authStore.model:', pb.authStore.model);
      console.log('pb.authStore.token:', pb.authStore.token ? 'exists' : 'none');
      showToast('Войдите, чтобы голосовать', 'warning', 5000, { text: 'Войти', href: '/auth/sign-in' });
      return;
    }

    try {
      const formData = new FormData();
      formData.append('post_id', postId);
      formData.append('vote_type', voteType);

      const response = await fetch('/api/votes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ post_id: postId, vote_type: voteType }),
        credentials: 'include',
      });

      if (!response.ok) {
        const error = await response.json();
        console.error('Vote error response:', error);
        throw new Error(error.message || error.details || 'Ошибка голосования');
      }

      const result = await response.json();

      if (likesCount) likesCount.textContent = result.likes.toString();
      if (dislikesCount) dislikesCount.textContent = result.dislikes.toString();

      if (result.userVote === 'like') {
        likeBtn?.classList.add('active');
        dislikeBtn?.classList.remove('active');
      } else if (result.userVote === 'dislike') {
        dislikeBtn?.classList.add('active');
        likeBtn?.classList.remove('active');
      } else {
        likeBtn?.classList.remove('active');
        dislikeBtn?.classList.remove('active');
      }

      showToast('Ваш голос учтён', 'success', 2000);
    } catch (error) {
      console.error('Ошибка голосования:', error);
      showToast('Не удалось отправить голос. Попробуйте позже.', 'error', 3000);
    }
  }

  document.querySelectorAll('.post-reactions').forEach((container) => {
    const postId = (container as HTMLElement).dataset.postId;
    const likeBtn = container.querySelector('.like-btn');
    const dislikeBtn = container.querySelector('.dislike-btn');

    async function loadUserVote() {
      const likesCountEl = container.querySelector('[data-count="likes"]');
      const dislikesCountEl = container.querySelector('[data-count="dislikes"]');
      
      try {
        console.log('[Vote] Загрузка голосов для post:', postId);
        const response = await fetch(`/api/votes?post_id=${postId}`, {
          credentials: 'include',
        });
        console.log('[Vote] Ответ:', response.status);
        if (response.ok) {
          const result = await response.json();
          console.log('[Vote] Данные:', result);
          // Обновляем счетчики
          if (likesCountEl) likesCountEl.textContent = result.likes.toString();
          if (dislikesCountEl) dislikesCountEl.textContent = result.dislikes.toString();
          // Показываем голос пользователя
          if (pb.authStore.isValid) {
            if (result.userVote === 'like') {
              likeBtn?.classList.add('active');
            } else if (result.userVote === 'dislike') {
              dislikeBtn?.classList.add('active');
            }
          }
        }
      } catch (e) {
        console.error('Ошибка загрузки голоса:', e);
      }
    }

    // Вызываем при загрузке и при изменении авторизации
    loadUserVote();
    
    // Также при изменении авторизации
    window.addEventListener('storage', (e) => {
      if (e.key === 'pb_auth') {
        loadUserVote();
      }
    });

    likeBtn?.addEventListener('click', () => {
      if (postId) handleVote(postId, 'like');
    });

    dislikeBtn?.addEventListener('click', () => {
      if (postId) handleVote(postId, 'dislike');
    });
  });
</script>
