<script lang="ts">
  import type { InspectorItem } from './types';

  export let item: InspectorItem | null;
  let activeTab: 'discussion' | 'properties' | 'more' = 'discussion';
  let copyFeedback = '';
  let copyFailed = false;
  let currentItem: InspectorItem | null = null;

  $: if (item !== currentItem) {
    currentItem = item;
    copyFeedback = '';
    copyFailed = false;
  }

  async function copyLink() {
    const link = new URL(`?item=${encodeURIComponent(item?.title ?? '')}`, window.location.href).toString();
    if (!navigator.clipboard?.writeText) {
      copyFailed = true;
      copyFeedback = 'Clipboard access is unavailable.';
      return;
    }

    try {
      await navigator.clipboard.writeText(link);
      copyFailed = false;
      copyFeedback = 'Link copied to clipboard.';
    } catch {
      copyFailed = true;
      copyFeedback = 'Unable to copy link.';
    }
  }
</script>

<aside class="object-inspector" aria-label="Object inspector">
  <div class="inspector-tabs">
    <button type="button" aria-pressed={activeTab === 'discussion'} on:click={() => (activeTab = 'discussion')}>Discussion</button>
    <button type="button" aria-pressed={activeTab === 'properties'} on:click={() => (activeTab = 'properties')}>Properties</button>
    <button type="button" aria-pressed={activeTab === 'more'} on:click={() => (activeTab = 'more')}>More</button>
  </div>

  {#if item}
    <h2>{item.title}</h2>
    <p>{item.description}</p>
    {#if activeTab === 'discussion'}
      <p>No comments yet. Add project discussion here later.</p>
    {:else if activeTab === 'properties'}
      <dl>
        {#each item.properties as property}
          <div>
            <dt>{property.label}</dt>
            <dd>{property.value}</dd>
          </div>
        {/each}
      </dl>
    {:else}
      <button type="button" on:click={copyLink}>Copy link</button>
      {#if copyFeedback}
        <p class:copy-error={copyFailed} class="copy-feedback" role="status">{copyFeedback}</p>
      {/if}
      <button type="button" aria-label="Archive is unavailable in this preview" title="Archive is unavailable in this preview" disabled>Archive</button>
    {/if}
  {:else}
    <h2>Inspector</h2>
    <p>Select an item to inspect discussion, properties, and actions.</p>
  {/if}
</aside>
