<script lang="ts">
  import { useNavigate, useParams } from "svelte-navigator";
  import BrowseAdd from "../components/BrowseAdd.svelte";
  import BrowseColumn from "../components/BrowseColumn.svelte";
  import { updateTitle } from "../util/title";
  const navigate = useNavigate();
  const params = useParams();

  let root: HTMLDivElement;
  let identities: string[] = [];
  $: addresses = $params.addresses.split(",");

  function add(address: string) {
    let _addresses = addresses.concat();
    _addresses.push(address);
    navigate(`/browse/${_addresses.join(",")}`);
  }

  function close(idx: number) {
    let _addresses = addresses.concat();
    _addresses.splice(idx, 1);
    if (_addresses.length) {
      navigate(`/browse/${_addresses.join(",")}`);
    } else {
      navigate("/");
    }
  }

  $: scrollToVisible(addresses.length - 1);

  function scrollToVisible(idx: string | number) {
    const target = root?.querySelector(`[data-index='${idx}']`)
      ?.firstElementChild as HTMLElement;

    if (target) {
      root?.scrollTo({
        left: target.offsetLeft,
        behavior: "smooth",
      });
    }
  }

  function onIdentified(index: number, ev: CustomEvent<string[]>) {
    for (let i = 0; i < addresses.length; i++) {
      if (!identities[i]) {
        identities[i] = "?";
      }
      identities[index] = ev.detail.join("/");
    }
    identities = identities;
  }

  let detailMode = false;
  function onDetailChanged(index: number, ev: CustomEvent<boolean>) {
    if (ev.detail) {
      scrollToVisible(index);
    }
    detailMode = addresses.length === 1 && ev.detail;
  }

  $: updateTitle("Browse", identities.join(" / "));
</script>

<div class="browser" bind:this={root}>
  {#each addresses as address, index}
    <div class="column" data-index={index}>
      <BrowseColumn
        {address}
        {index}
        only={addresses.length === 1}
        on:close={() => close(index)}
        on:resolved={(ev) => onIdentified(index, ev)}
        on:detail={(ev) => onDetailChanged(index, ev)}
      />
    </div>
  {/each}
  {#if !detailMode}
    {#key addresses}
      <div class="column" data-index="add">
        <BrowseAdd
          on:input={(ev) => add(ev.detail.c)}
          on:editable={() => scrollToVisible("add")}
        />
      </div>
    {/key}
  {/if}
</div>

<style lang="scss">
  .browser {
    height: 100%;
    padding: 1rem;

    display: flex;
    overflow-x: auto;
    gap: 1rem;
  }

  .column {
    display: contents;
  }
</style>
