<script lang="ts">
  import { getLinkType } from '$lib/models/socials';
  import { editorStore } from '$lib/stores/editor';
  import SocialLink from './SocialLink.svelte';
  import SocialText from './SocialText.svelte';
  import { SocialLink as SocialLinkType } from '$lib/models/socials';
  import { browser } from '$app/environment';

  export let socials: BioSiteSocials | undefined = undefined;
  export let storelessSocials: boolean = false;

  $: socialLinks = (
    [
      ...(socials?.links ?? [])
        .map((x) => {
          const remove = $editorStore.edits.edits.deleteSocialLinks.map((x) => x.id).findIndex((y) => y === x.id);
          if (remove !== -1) return null;

          return x;
        })
        .filter((x) => x),
      ...$editorStore.edits.edits.createSocialLinks
        .filter(() => !storelessSocials)
        .map((x) => ({ ...x, type: Object.values(SocialLinkType)[x.type] } as BioSiteSocialLink)),
    ].filter((x) => x) as BioSiteSocialLink[]
  )
    .map((x) => {
      const index = $editorStore.edits.edits.indexSocialLinks.findIndex((y) => x.id == y.socialId);
      if (index === -1) return x;
      return { ...x, index: $editorStore.edits.edits.indexSocialLinks[index].index ?? -1 };
    })
    .sort((a, b) => a.index - b.index);

  $: socialTexts = (
    [
      ...(socials?.texts ?? [])
        .map((x) => {
          const remove = $editorStore.edits.edits.deleteSocialTexts.map((x) => x.id).findIndex((y) => y === x.id);
          if (remove !== -1) return null;

          return x;
        })
        .filter((x) => x),
      ...$editorStore.edits.edits.createSocialTexts.filter(() => !storelessSocials),
    ].filter((x) => x) as BioSiteSocialText[]
  )
    .map((x) => {
      const index = $editorStore.edits.edits.indexSocialTexts.findIndex((y) => x.id == y.socialId);
      if (index === -1) return x;
      return { ...x, index: $editorStore.edits.edits.indexSocialTexts[index].index ?? -1 };
    })
    .sort((a, b) => a.index - b.index);
</script>

{#key socials}
  {#if socials}
    {#key socialLinks}
      {#if socialLinks.length > 0}
        <div class="flex flex-wrap gap-1.5" class:edit={$editorStore.editMode}>
          {#each socialLinks as link}
            <SocialLink
              site={getLinkType(link.type)}
              social={link}
              hoverInvert={socials.invert}
              minimal={socials.minimal} />
          {/each}
        </div>
      {/if}
    {/key}
    {#if browser}
      {#key socialTexts}
        {#if socialTexts.length > 0}
          <div class="flex flex-col gap-1.5" class:edit={$editorStore.editMode}>
            {#each socialTexts as text}
              <SocialText social={text} />
            {/each}
          </div>
        {/if}
      {/key}
    {/if}
  {/if}
{/key}

<style lang="postcss">
  div {
    @apply select-none;
  }

  div.edit {
    @apply pointer-events-none;
  }
</style>
