<script lang="ts">
  import { timefmt } from '../../../helpers.js';
  import Nav from '../Nav.svelte';
  import Tabs from '../Tabs.svelte';
  import type { PageData } from './$types';
  import { goto } from '$app/navigation';
  export let data: PageData;
  let includeClosed = false;
</script>

<svelte:head>
  <title>{data.owner}/{data.repo} - Discussions</title>
</svelte:head>
<div class="p-3">
  <Nav user={data.owner} repo={data.repo} link={true} />
  <Tabs user={data.owner} repo={data.repo} active="discussion" />
  <div class="pt-5 flex flex-col">
    <div class="flex w-full items-center justify-end gap-3">
      <div>
        <input
          type="checkbox"
          class="toggle toggle-sm toggle-primary"
          id="includeClosed"
          bind:checked={includeClosed}
          name="closed"
          on:change={() => {
            console.log('changed', includeClosed);
            if (includeClosed) goto(`?closed=true`);
            else goto(`?`);
          }} />
        <label class="label" for="includeClosed"> Include closed </label>
      </div>
      {#if data.login}
        <div class="flex justify-end">
          <a class="btn btn-primary btn-sm" href="/{data.owner}/{data.repo}/discussion/new"
            >Start a new discussion</a>
        </div>
      {/if}
    </div>

    {#if data.discussions.length}
      <ul class="list mt-3">
        {#each data.discussions as d}
          <li class="list-row">
            <div class="items-center justify-between">
              <div>
                <div class="flex items-center">
                  <h2>
                    <a href="/{data.owner}/{data.repo}/discussion/{d.num}">#{d.num} {d.title}</a>
                  </h2>
                </div>
                <div class="justify-between items-center">
                  {#if d.closed}
                    <div class="col col-auto">
                      Closed {timefmt(d.closed)}
                    </div>
                  {:else}
                    <div class="col col-auto">
                      Opened by <a class="mx-1" href="/{d.author}">{d.author}</a>
                      {timefmt(d.opened)}
                    </div>
                  {/if}
                </div>
              </div>
              {#if d.changes}
                <div class="rounded shadow-sm me-3 text-success">
                  {#if d.changes == 1}
                    1 change
                  {:else}
                    {d.changes} changes
                  {/if}
                </div>
              {/if}
            </div>
          </li>
        {/each}
      </ul>
    {/if}
  </div>
</div>