<script lang="ts">
  import { Link, useLocation, useNavigate } from "svelte-navigator";
  import { useMatch } from "svelte-navigator";
  import { addEmitter } from "../AddModal.svelte";
  import Icon from "../utils/Icon.svelte";
  import Input from "../utils/Input.svelte";
  import { jobsEmitter } from "./Jobs.svelte";
  const navigate = useNavigate();
  const location = useLocation();

  const searchMatch = useMatch("/search/:query");

  let searchQuery = $searchMatch?.params.query
    ? decodeURIComponent($searchMatch?.params.query)
    : "";
  $: if (!$location.pathname.includes("search")) searchQuery = "";
  function onInput(event: CustomEvent<string>) {
    searchQuery = event.detail;

    if (searchQuery.length > 0) {
      navigate(`/search/${encodeURIComponent(searchQuery)}`, {
        replace: $location.pathname.includes("search"),
      });
    } else {
      navigate("/");
    }
  }

  let fileInput: HTMLInputElement;
  function onFileChange() {
    if (fileInput.files.length > 0) {
      addEmitter.emit("files", Array.from(fileInput.files));
    }
  }

  async function rescan() {
    await fetch("api/refresh", { method: "POST" });
    jobsEmitter.emit("reload");
  }
</script>

<div class="header">
  <h1>
    <Link to="/">
      <img class="logo" src="/assets/upend.svg" alt="UpEnd logo" />
      UpEnd
    </Link>
  </h1>
  <div class="input">
    <Input
      placeholder="Search or add..."
      value={searchQuery}
      on:input={onInput}
    >
      <Icon name="search" slot="prefix" />
    </Input>
  </div>
  <button class="button" on:click={() => fileInput.click()}>
    <Icon name="plus-circle" />
    <input
      type="file"
      multiple
      bind:this={fileInput}
      on:change={onFileChange}
    />
  </button>
  <button class="button" on:click={() => rescan()} title="Rescan vault">
    <Icon name="refresh" />
  </button>
</div>

<style lang="scss">
  .header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0 0.5rem;
    height: 3.5rem;
    border-bottom: 1px solid var(--foreground);

    background: var(--background);

    h1 {
      font-size: 16pt;
      font-weight: normal;
      margin: 0;

      :global(a) {
        display: flex;
        align-items: center;

        color: var(--foreground-lightest);
        text-decoration: none;
        font-weight: normal;
      }

      img {
        margin-right: 0.5em;
      }
    }

    .logo {
      display: inline-block;
      height: 1.5em;
    }

    .input {
      flex-grow: 1;
    }

    .button {
      border: 1px solid var(--foreground);
      border-radius: 4px;
      background: var(--background-lighter);
      color: var(--foreground);
      padding: 0.25em 1em;
      line-height: 1;
      display: block;
      cursor: pointer;

      input {
        display: none;
      }
    }
  }
</style>
