<script lang="ts">
  import { onMount } from 'svelte';

  interface Idea {
    id: string;
    title: string;
    body: string;
    author: string;
    created_at: number;
    votes: string[];
    vote_count: number;
    my_vote: boolean;
    status?: string;
    admin_comment?: string | null;
  }

  let ideas: Idea[] = [];
  let loading = true;
  let myHandle = '';
  let isAdmin = false;

  let showForm = false;
  let newTitle = '';
  let newBody = '';
  let submitting = false;
  let formError = '';

  let editingId: string | null = null;
  let editTitle = '';
  let editBody = '';
  let editSaving = false;

  let editingCommentId: string | null = null;
  let commentDraft = '';
  let commentSaving = false;

  function startEditComment(idea: Idea) {
    editingCommentId = idea.id;
    commentDraft = idea.admin_comment ?? '';
  }

  function cancelEditComment() {
    editingCommentId = null;
    commentDraft = '';
  }

  async function saveComment(idea: Idea) {
    commentSaving = true;
    try {
      const r = await fetch(`/api/ideas/${idea.id}/comment`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ comment: commentDraft.trim() }),
      });
      if (r.ok) {
        idea.admin_comment = commentDraft.trim() || null;
        ideas = ideas;
        editingCommentId = null;
        commentDraft = '';
      }
    } finally {
      commentSaving = false;
    }
  }

  function startEdit(idea: Idea) {
    editingId = idea.id;
    editTitle = idea.title;
    editBody = idea.body;
  }

  function cancelEdit() {
    editingId = null;
  }

  async function saveEdit(idea: Idea) {
    if (!editTitle.trim()) return;
    editSaving = true;
    try {
      const r = await fetch(`/api/ideas/${idea.id}`, {
        method: 'PATCH',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: editTitle.trim(), body: editBody.trim() }),
      });
      if (r.ok) {
        idea.title = editTitle.trim();
        idea.body = editBody.trim();
        ideas = ideas;
        editingId = null;
      }
    } finally {
      editSaving = false;
    }
  }

  function relativeTime(ts: number): string {
    const diff = Math.floor(Date.now() / 1000) - ts;
    if (diff < 60)   return 'just now';
    if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
    const d = Math.floor(diff / 86400);
    return d === 1 ? '1 day ago' : `${d} days ago`;
  }

  async function load() {
    loading = true;
    try {
      const [ideasRes, meRes] = await Promise.all([
        fetch('/api/ideas', { credentials: 'include' }),
        fetch('/api/me', { credentials: 'include' }),
      ]);
      if (ideasRes.status === 401 || meRes.status === 401) {
        window.location.href = `/login/?next=${encodeURIComponent(window.location.pathname)}`;
        return;
      }
      if (ideasRes.ok) ideas = (await ideasRes.json()).ideas ?? [];
      if (meRes.ok) {
        const me = await meRes.json();
        myHandle = me.handle ?? '';
        isAdmin = !!me.is_admin;
      }
    } finally {
      loading = false;
    }
  }

  async function vote(idea: Idea) {
    const prev = { my_vote: idea.my_vote, vote_count: idea.vote_count };
    idea.my_vote = !idea.my_vote;
    idea.vote_count += idea.my_vote ? 1 : -1;
    ideas = ideas;
    try {
      const r = await fetch(`/api/ideas/${idea.id}/vote`, {
        method: 'POST',
        credentials: 'include',
      });
      if (r.ok) {
        const d = await r.json();
        idea.vote_count = d.votes;
        idea.my_vote = d.voted;
        ideas = [...ideas].sort((a, b) => b.vote_count - a.vote_count || b.created_at - a.created_at);
      } else {
        idea.my_vote = prev.my_vote;
        idea.vote_count = prev.vote_count;
        ideas = ideas;
      }
    } catch {
      idea.my_vote = prev.my_vote;
      idea.vote_count = prev.vote_count;
      ideas = ideas;
    }
  }

  async function submit() {
    formError = '';
    if (!newTitle.trim()) { formError = 'Title is required.'; return; }
    submitting = true;
    try {
      const r = await fetch('/api/ideas', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: newTitle.trim(), body: newBody.trim() }),
      });
      if (r.ok) {
        newTitle = '';
        newBody = '';
        showForm = false;
        await load();
      } else {
        const d = await r.json().catch(() => ({}));
        formError = d.detail ?? 'Could not submit idea.';
      }
    } catch {
      formError = 'Network error.';
    } finally {
      submitting = false;
    }
  }

  function statusOrder(s: string | undefined) {
    return s === 'awaiting' ? 0 : s === 'done' ? 2 : s === 'declined' ? 3 : 1;
  }

  async function reopenIdea(idea: Idea) {
    const r = await fetch(`/api/ideas/${idea.id}/reopen`, {
      method: 'POST',
      credentials: 'include',
    });
    if (r.ok) {
      idea.status = 'open';
      ideas = [...ideas].sort((a, b) =>
        statusOrder(a.status) - statusOrder(b.status) ||
        b.vote_count - a.vote_count ||
        b.created_at - a.created_at
      );
    }
  }

  async function declineIdea(idea: Idea) {
    const r = await fetch(`/api/ideas/${idea.id}/decline`, {
      method: 'POST',
      credentials: 'include',
    });
    if (r.ok) {
      const d = await r.json();
      idea.status = d.status;
      ideas = [...ideas].sort((a, b) =>
        statusOrder(a.status) - statusOrder(b.status) ||
        b.vote_count - a.vote_count ||
        b.created_at - a.created_at
      );
    }
  }

  async function toggleStatus(idea: Idea) {
    const r = await fetch(`/api/ideas/${idea.id}/status`, {
      method: 'POST',
      credentials: 'include',
    });
    if (r.ok) {
      const d = await r.json();
      idea.status = d.status;
      ideas = [...ideas].sort((a, b) =>
        statusOrder(a.status) - statusOrder(b.status) ||
        b.vote_count - a.vote_count ||
        b.created_at - a.created_at
      );
    }
  }

  $: awaitingIdeas  = ideas.filter(i => i.status === 'awaiting');
  $: otherIdeas     = ideas.filter(i => i.status !== 'awaiting' && i.status !== 'declined');
  $: declinedIdeas  = ideas.filter(i => i.status === 'declined');

  async function deleteIdea(idea: Idea) {
    if (!confirm(`Delete "${idea.title}"?`)) return;
    const r = await fetch(`/api/ideas/${idea.id}`, {
      method: 'DELETE',
      credentials: 'include',
    });
    if (r.ok) ideas = ideas.filter(i => i.id !== idea.id);
  }

  onMount(load);
</script>

<div class="max-w-2xl mx-auto px-4 py-8">
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-2xl font-bold text-white">Ideas</h1>
    <div class="flex items-center gap-2">
      <a
        href="/feedback/"
        class="px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        style="border: 1px solid var(--border-sub); color: var(--text-4)"
      >💬 Feedback</a>
      <button
        on:click={() => { showForm = !showForm; formError = ''; }}
        class="px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        style="background: var(--accent-dim); color: var(--accent); border: 1px solid var(--accent)"
      >
        {showForm ? 'Cancel' : '+ Submit an idea'}
      </button>
    </div>
  </div>

  {#if showForm}
    <div class="rounded-xl border p-4 mb-6" style="background: var(--bg-card); border-color: var(--border)">
      <input
        bind:value={newTitle}
        placeholder="Title (required)"
        maxlength="200"
        class="w-full rounded-lg px-3 py-2 text-sm mb-3"
        style="background: var(--bg-elevated); border: 1px solid var(--border-sub); color: var(--text-primary)"
      />
      <textarea
        bind:value={newBody}
        placeholder="More detail… (optional)"
        maxlength="2000"
        rows="3"
        class="w-full rounded-lg px-3 py-2 text-sm mb-3 resize-none"
        style="background: var(--bg-elevated); border: 1px solid var(--border-sub); color: var(--text-primary)"
      ></textarea>
      {#if formError}
        <p class="text-red-400 text-xs mb-2">{formError}</p>
      {/if}
      <button
        on:click={submit}
        disabled={submitting}
        class="px-4 py-2 rounded-lg text-sm font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-50"
        style="background: var(--accent)"
      >
        {submitting ? 'Submitting…' : 'Submit'}
      </button>
    </div>
  {/if}

  {#if loading}
    <p class="text-sm" style="color: var(--text-5)">Loading…</p>
  {:else if ideas.length === 0}
    <p class="text-sm" style="color: var(--text-5)">No ideas yet. Be the first!</p>
  {:else}
    {#if awaitingIdeas.length > 0}
      <div class="mb-2">
        <p class="text-xs font-semibold uppercase tracking-wide mb-2" style="color: #f59e0b">
          🕐 Waiting for your feedback
        </p>
        <ul class="space-y-3">
          {#each awaitingIdeas as idea (idea.id)}
            <li
              class="rounded-xl border px-4 py-3 flex gap-3"
              style="background: var(--bg-card); border-color: #f59e0b; border-width: 1.5px"
            >
              {@render ideaContent(idea)}
            </li>
          {/each}
        </ul>
      </div>
    {/if}

    {#if otherIdeas.length > 0}
      <ul class="space-y-3">
        {#each otherIdeas as idea (idea.id)}
          {@const done = idea.status === 'done'}
          <li
            class="rounded-xl border px-4 py-3 flex gap-3 transition-opacity"
            style="background: var(--bg-card); border-color: var(--border); opacity: {done ? '0.55' : '1'}"
          >
            {@render ideaContent(idea)}
          </li>
        {/each}
      </ul>
    {/if}

    {#if declinedIdeas.length > 0}
      <div class="mt-6">
        <p class="text-xs font-semibold uppercase tracking-wide mb-2" style="color: #71717a">
          ✗ Won't implement
        </p>
        <ul class="space-y-2">
          {#each declinedIdeas as idea (idea.id)}
            <li
              class="rounded-xl border px-4 py-3 flex gap-3"
              style="background: var(--bg-card); border-color: var(--border); opacity: 0.4"
            >
              {@render ideaContent(idea)}
            </li>
          {/each}
        </ul>
      </div>
    {/if}
  {/if}

  {#snippet ideaContent(idea: Idea)}
    {@const done     = idea.status === 'done'}
    {@const awaiting = idea.status === 'awaiting'}
    {@const declined = idea.status === 'declined'}
    <!-- Vote button -->
    <div class="flex flex-col items-center shrink-0 pt-0.5">
      <button
        on:click={() => vote(idea)}
        class="w-10 h-10 rounded-lg text-sm font-semibold flex flex-col items-center justify-center gap-0 leading-none transition-colors"
        style={idea.my_vote
          ? 'background: var(--accent-dim); border: 1px solid var(--accent); color: var(--accent)'
          : 'background: transparent; border: 1px solid var(--border-sub); color: var(--text-5)'}
        title={idea.my_vote ? 'Remove vote' : '+1 this idea'}
      >
        <span class="text-xs leading-none">▲</span>
        <span class="text-xs leading-none">{idea.vote_count}</span>
      </button>
    </div>

    <!-- Content -->
    <div class="flex-1 min-w-0">
      {#if editingId === idea.id}
        <input
          bind:value={editTitle}
          class="w-full rounded-lg px-3 py-1.5 text-sm mb-2"
          style="background: var(--bg-elevated); border: 1px solid var(--border-sub); color: var(--text-primary)"
        />
        <textarea
          bind:value={editBody}
          rows="2"
          class="w-full rounded-lg px-3 py-1.5 text-sm mb-2 resize-none"
          style="background: var(--bg-elevated); border: 1px solid var(--border-sub); color: var(--text-primary)"
        ></textarea>
        <div class="flex gap-2">
          <button
            on:click={() => saveEdit(idea)}
            disabled={editSaving || !editTitle.trim()}
            class="px-3 py-1 rounded-lg text-xs font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-50"
            style="background: var(--accent)"
          >{editSaving ? 'Saving…' : 'Save'}</button>
          <button
            on:click={cancelEdit}
            class="px-3 py-1 rounded-lg text-xs transition-colors"
            style="color: var(--text-5)"
          >Cancel</button>
        </div>
      {:else}
        <div class="flex items-start justify-between gap-2">
          <p class="font-medium text-sm" style="color: var(--text-primary)">
            {#if done}<span class="mr-1.5 text-green-500">✓</span>{:else if declined}<span class="mr-1.5" style="color:#71717a">✗</span>{/if}{idea.title}
          </p>
          <div class="flex items-center gap-1 shrink-0">
            {#if isAdmin}
              {#if declined}
                <button
                  on:click={() => declineIdea(idea)}
                  class="text-xs px-1.5 py-0.5 rounded transition-colors"
                  style="color: var(--text-5); border: 1px solid var(--border-sub)"
                  title="Reopen"
                >↩</button>
              {:else}
                {@const nextLabel = done ? 'reopen' : awaiting ? 'done' : 'awaiting'}
                {@const btnColor = done ? 'var(--text-5)' : awaiting ? 'var(--accent)' : '#f59e0b'}
                {@const borderColor = done ? 'var(--border-sub)' : awaiting ? 'var(--accent)' : '#f59e0b'}
                <button
                  on:click={() => toggleStatus(idea)}
                  class="text-xs px-1.5 py-0.5 rounded transition-colors"
                  style="color: {btnColor}; border: 1px solid {borderColor}"
                  title="Cycle status"
                >{nextLabel}</button>
                {#if awaiting}
                  <button
                    on:click={() => reopenIdea(idea)}
                    class="text-xs px-1.5 py-0.5 rounded transition-colors"
                    style="color: var(--text-5); border: 1px solid var(--border-sub)"
                    title="Back to todo"
                  >↩</button>
                {/if}
                <button
                  on:click={() => declineIdea(idea)}
                  class="text-xs px-1.5 py-0.5 rounded transition-colors"
                  style="color: #ef4444; border: 1px solid rgba(239,68,68,0.35)"
                  title="Won't implement"
                >✗</button>
              {/if}
            {/if}
            {#if isAdmin || idea.author === myHandle}
              <button
                on:click={() => startEdit(idea)}
                class="text-xs px-1.5 py-0.5 rounded transition-colors hover:text-white"
                style="color: var(--text-5)"
                title="Edit"
              >✎</button>
              <button
                on:click={() => deleteIdea(idea)}
                class="text-xs px-1.5 py-0.5 rounded transition-colors hover:text-red-400"
                style="color: var(--text-5)"
                title="Delete"
              >×</button>
            {/if}
          </div>
        </div>
        {#if idea.body}
          <p class="text-xs mt-1" style="color: var(--text-4)">{idea.body}</p>
        {/if}
        <p class="text-xs mt-1.5" style="color: var(--text-5)">
          @{idea.author} · {relativeTime(idea.created_at)}
        </p>
      {/if}

      {#if idea.admin_comment || (isAdmin && awaiting)}
        <div class="mt-3 rounded-lg px-3 py-2.5" style="background: var(--bg-elevated); border: 1px solid rgba(245,158,11,0.25)">
          {#if editingCommentId === idea.id}
            <textarea
              bind:value={commentDraft}
              rows="3"
              placeholder="Add an implementation note…"
              class="w-full rounded px-2 py-1.5 text-xs resize-none mb-2"
              style="background: var(--bg-card); border: 1px solid var(--border-sub); color: var(--text-primary)"
            ></textarea>
            <div class="flex gap-2">
              <button
                on:click={() => saveComment(idea)}
                disabled={commentSaving}
                class="px-3 py-1 rounded-lg text-xs font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-50"
                style="background: var(--accent)"
              >{commentSaving ? 'Saving…' : 'Save'}</button>
              <button
                on:click={cancelEditComment}
                class="px-3 py-1 rounded-lg text-xs transition-colors"
                style="color: var(--text-5)"
              >Cancel</button>
            </div>
          {:else}
            <div class="flex items-start justify-between gap-2">
              <div class="flex-1 min-w-0">
                {#if idea.admin_comment}
                  <p class="text-xs leading-relaxed" style="color: var(--text-4)">{idea.admin_comment}</p>
                {:else}
                  <p class="text-xs italic" style="color: var(--text-5)">Add an implementation note…</p>
                {/if}
              </div>
              {#if isAdmin}
                <button
                  on:click={() => startEditComment(idea)}
                  class="text-xs shrink-0 transition-colors hover:text-white"
                  style="color: var(--text-5)"
                  title="Edit note"
                >✎</button>
              {/if}
            </div>
          {/if}
        </div>
      {/if}
    </div>
  {/snippet}

  <div class="mt-10 pt-6 border-t text-sm" style="border-color: var(--border); color: var(--text-5)">
    <a href="/feedback/" style="color: var(--accent)" class="hover:underline">Found a bug? Have feedback to share? Click here.</a>
  </div>
</div>
