<script>
  import { onMount } from 'svelte';
  import { push } from 'svelte-spa-router';
  import { auth } from '../lib/stores/auth.js';
  import { navContext } from '../lib/stores/navContext.js';
  import { fetchPublishedDecksByOwner, copyDeckToUser, getMyDeckRating, submitDeckRating } from '../lib/api/decks.js';
  import RatingModal from '../lib/RatingModal.svelte';

  onMount(() => navContext.set('community'));

  export let params = {};

  let decks = [];
  let ownerName = '';
  let loading = true;
  let error = null;
  let addingDeckId = null;
  let useError = null;
  let ratingDeck = null;
  let ratingInitial = { rating: 0, comment: '' };

  $: userId = $auth.user?.id;

  let prevOwnerId = null;
  $: ownerId = params?.id;
  $: if (ownerId && ownerId !== prevOwnerId) {
    prevOwnerId = ownerId;
    load();
  }

  function formatRating(n) {
    return Number(n).toFixed(1);
  }

  function goPreview(deckId) {
    push(`/decks/${deckId}/preview`);
  }

  async function openRatingModal(deck, e) {
    e?.stopPropagation();
    if (!userId) {
      useError = 'Sign in to rate this deck.';
      return;
    }
    if (deck.owner_id === userId) return; // cannot rate own deck
    useError = null;
    ratingDeck = { id: deck.id, title: deck.title };
    try {
      const data = await getMyDeckRating(deck.id, userId);
      ratingInitial = { rating: data?.rating ?? 0, comment: data?.comment ?? '' };
    } catch (_) {
      ratingInitial = { rating: 0, comment: '' };
    }
  }

  function closeRatingModal() {
    ratingDeck = null;
  }

  async function handleRatingSubmit(payload) {
    if (!ratingDeck || !userId) return;
    try {
      await submitDeckRating(ratingDeck.id, userId, payload);
      await load();
    } catch (e) {
      useError = e?.message ?? 'Failed to save rating';
    }
  }

  async function handleUse(deckId) {
    useError = null;
    if (!userId) {
      useError = 'Sign in to add this deck to My decks.';
      return;
    }
    if (addingDeckId) return;
    addingDeckId = deckId;
    try {
      await copyDeckToUser(deckId, userId);
      await load();
    } catch (e) {
      useError = e?.message ?? 'Failed to add deck';
    } finally {
      addingDeckId = null;
    }
  }

  function goCommunity(e) {
    if (e) e.preventDefault();
    push('/community');
  }

  async function load() {
    if (!ownerId) return;
    loading = true;
    error = null;
    try {
      const result = await fetchPublishedDecksByOwner(ownerId, userId ?? undefined);
      decks = result.decks ?? [];
      ownerName = result.owner_display_name ?? result.owner_email ?? 'User';
    } catch (e) {
      error = e?.message ?? 'Failed to load decks';
      decks = [];
      ownerName = '';
    } finally {
      loading = false;
    }
  }
</script>

<div class="page">
  <header class="page-header">
    <button type="button" class="btn btn-back" onclick={goCommunity}>← Community</button>
    <h1 class="page-title">Decks by {ownerName}</h1>
  </header>

  {#if loading}
    <p class="muted">Loading…</p>
  {:else if error}
    <p class="error">{error}</p>
  {:else if decks.length === 0}
    <p class="muted">No published decks by this user.</p>
  {:else}
    {#if useError}
      <p class="use-error">{useError}</p>
    {/if}
    <ul class="deck-grid">
      {#each decks as deck (deck.id)}
        <li class="deck-card">
          <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
          <div class="deck-card-inner" role="button" tabindex="0" onclick={() => goPreview(deck.id)} onkeydown={(e) => e.key === 'Enter' && goPreview(deck.id)}>
            <h3 class="deck-title">{deck.title}</h3>
            {#if deck.description}
              <p class="deck-description">{deck.description}</p>
            {/if}
            <div class="deck-meta">
              <span class="deck-count">{deck.question_count ?? 0} questions</span>
            </div>
            {#if userId && deck.owner_id !== userId}
              <button
                type="button"
                class="deck-rating clickable"
                aria-label="Rating: {deck.average_rating ?? 0} out of 5 stars"
                onclick={(e) => openRatingModal(deck, e)}
                onkeydown={(e) => e.key === 'Enter' && openRatingModal(deck, e)}
              >
                <span class="stars">{['★', '★', '★', '★', '★'].map((_, i) => (i < Math.round(deck.average_rating ?? 0) ? '★' : '☆')).join('')}</span>
                <span class="rating-text">{formatRating(deck.average_rating ?? 0)}</span>
                {#if (deck.rating_count ?? 0) > 0}
                  <span class="rating-count">({deck.rating_count})</span>
                {/if}
              </button>
            {:else}
              <div class="deck-rating" aria-label="Rating: {deck.average_rating ?? 0} out of 5 stars">
                <span class="stars">{['★', '★', '★', '★', '★'].map((_, i) => (i < Math.round(deck.average_rating ?? 0) ? '★' : '☆')).join('')}</span>
                <span class="rating-text">{formatRating(deck.average_rating ?? 0)}</span>
                {#if (deck.rating_count ?? 0) > 0}
                  <span class="rating-count">({deck.rating_count})</span>
                {/if}
              </div>
            {/if}
            <div class="deck-card-actions">
              {#if !deck.user_has_this}
                <button type="button" class="btn btn-small btn-primary" onclick={(e) => { e.stopPropagation(); handleUse(deck.id); }} disabled={addingDeckId === deck.id}>
                  {addingDeckId === deck.id ? 'Adding…' : 'Add'}
                </button>
              {:else}
                <span class="already-have">In My decks</span>
              {/if}
            </div>
          </div>
        </li>
      {/each}
    </ul>
  {/if}

  <RatingModal
    deck={ratingDeck}
    initialRating={ratingInitial.rating}
    initialComment={ratingInitial.comment}
    onSubmit={handleRatingSubmit}
    onClose={closeRatingModal}
  />
</div>

<style>
  .page {
    padding: 1.5rem;
    max-width: 1200px;
    margin: 0 auto;
  }

  .page-header {
    margin-bottom: 1.5rem;
  }

  .btn-back {
    padding: 0.4rem 0.75rem;
    font-size: 0.9rem;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: transparent;
    color: var(--text-muted, #a0a0a0);
    cursor: pointer;
    margin-bottom: 0.75rem;
  }

  .btn-back:hover {
    color: var(--text-primary, #f0f0f0);
    border-color: var(--border-hover, #444);
  }

  .page-title {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--text-primary, #f0f0f0);
  }

  .muted,
  .error {
    margin: 0;
  }

  .error {
    color: #ef4444;
  }

  .muted {
    color: var(--text-muted, #a0a0a0);
  }

  .use-error {
    margin: 0 0 1rem 0;
    font-size: 0.9rem;
    color: #ef4444;
  }

  .deck-grid {
    list-style: none;
    margin: 0;
    padding: 0;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1.25rem;
  }

  .deck-card {
    margin: 0;
  }

  .deck-card-inner {
    position: relative;
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 160px;
    padding: 1.25rem;
    background: var(--card-bg, #1a1a1a);
    border: 1px solid var(--border, #333);
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    transition: border-color 0.15s, box-shadow 0.15s, transform 0.2s ease;
    cursor: pointer;
  }

  .deck-card-inner:hover {
    border-color: var(--border-hover, #444);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
    transform: translateY(-2px);
  }

  .deck-title {
    margin: 0 0 0.25rem 0;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-primary, #f0f0f0);
  }

  .deck-description {
    margin: 0 0 0.5rem 0;
    font-size: 0.9rem;
    color: var(--text-muted, #a0a0a0);
    line-height: 1.4;
    flex: 1;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .deck-meta {
    font-size: 0.85rem;
    color: var(--text-muted, #a0a0a0);
    margin-bottom: 0.25rem;
  }

  .deck-rating {
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 0.35rem;
    font-size: 0.9rem;
    color: var(--text-muted, #a0a0a0);
    margin-bottom: 0.25rem;
    border: none;
    background: transparent;
    padding: 0;
    font: inherit;
    text-align: left;
  }

  button.deck-rating {
    cursor: pointer;
  }

  .deck-rating.clickable {
    cursor: pointer;
  }

  .deck-rating.clickable:hover {
    color: #eab308;
  }

  .deck-rating .stars {
    color: #eab308;
    letter-spacing: 0.05em;
  }

  .deck-rating .rating-count {
    font-size: 0.8rem;
    color: var(--text-muted, #888);
  }

  .deck-card-actions {
    position: relative;
    z-index: 1;
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.75rem;
    margin-bottom: 0.5rem;
  }

  .deck-card-actions .btn {
    padding: 0.35rem 0.75rem;
    font-size: 0.85rem;
    font-weight: 500;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
    color: var(--text-primary, #f0f0f0);
    cursor: pointer;
  }

  .deck-card-actions .btn:hover {
    background: var(--hover-bg, #2a2a2a);
  }

  .deck-card-actions .btn-primary {
    background: var(--accent, #3b82f6);
    border-color: var(--accent, #3b82f6);
  }

  .deck-card-actions .btn-primary:hover {
    background: #2563eb;
  }

  .already-have {
    font-size: 0.85rem;
    color: #22c55e;
    font-style: italic;
  }
</style>
