<script lang="ts">
  import Card from '$lib/ui/layout/Card.svelte';
  import Button from '$lib/ui/atoms/Button.svelte';
  import { copyToClipboard } from '$lib/utils/copy';
  import { success as toastSuccess, error as toastError } from '$lib/stores/toasts';
  import { createEventDispatcher } from 'svelte';

  export let title: string;
  export let description: string = '';
  export let url: string | null = null;
  export let rotating: boolean = false;

  const dispatch = createEventDispatcher<{ rotate: void }>();

  async function handleCopy() {
    if (!url) return;
    const ok = await copyToClipboard(url);
    if (ok) toastSuccess('Enlace de calendario copiado');
    else toastError('No se pudo copiar el enlace');
  }

  function handleRotate() {
    dispatch('rotate');
  }
</script>

<Card>
  <div class="head">
    <div class="titles">
      <div class="title">{title}</div>
      {#if description}<div class="desc">{description}</div>{/if}
      {#if url}
        <div class="url">{url}</div>
      {:else}
        <div class="hint">Por seguridad, la URL no se muestra. Pulsa “Rotar” para generar una nueva.</div>
      {/if}
    </div>
    <div class="actions">
      <Button variant="secondary" size="sm" on:click={handleCopy} disabled={!url} aria-disabled={!url} title={!url ? 'URL no disponible' : undefined}>Copiar</Button>
      <Button variant="danger" size="sm" on:click={handleRotate} disabled={rotating} aria-disabled={rotating} aria-busy={rotating} title={rotating ? 'Actualizando…' : undefined}>
        {rotating ? 'Rotando…' : 'Rotar'}
      </Button>
    </div>
  </div>
</Card>

<style>
  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: var(--space-3);
  }
  .titles {
    min-width: 0;
  }
  .title {
    font-weight: 600;
  }
  .desc {
    color: var(--color-text-muted);
    margin-top: 2px;
    font-size: 0.95rem;
  }
  .url {
    margin-top: 6px;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    font-size: 12px;
    color: var(--color-text-muted);
    word-break: break-all;
  }
  .actions {
    display: inline-flex;
    gap: 8px;
    flex-shrink: 0;
  }
  .hint {
    margin-top: 6px;
    color: var(--color-text-muted);
    font-size: 12px;
  }
</style>
