<script lang="ts">
  import FeedCard from '$lib/ui/data/FeedCard.svelte';
  import EmptyState from '$lib/ui/feedback/EmptyState.svelte';
  import { success, error } from '$lib/stores/toasts';
  import { onMount } from 'svelte';

  export let data: {
    personal: { url: string | null };
    aggregate: { url: string | null };
    groups: Array<{ groupId: string; groupName: string | null; url: string | null }>;
  };

  let personalUrl: string | null = data.personal?.url ?? null;
  let aggregateUrl: string | null = data.aggregate?.url ?? null;
  let groups = data.groups?.map(g => ({ ...g })) || [];

  let rotating: Record<string, boolean> = {};

  async function rotate(type: 'personal' | 'aggregate' | 'group', groupId?: string) {
    try {
      if (type === 'group' && groupId) rotating[groupId] = true;
      if (type === 'personal') rotating['personal'] = true;
      if (type === 'aggregate') rotating['aggregate'] = true;
      rotating = { ...rotating };

      const res = await fetch('/api/integrations/feeds/rotate', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ type, groupId: groupId ?? null })
      });
      if (!res.ok) {
        error('No se puedo actualizar');
        return;
      }
      const body = await res.json();
      if (type === 'personal') {
        personalUrl = body.url || null;
      } else if (type === 'aggregate') {
        aggregateUrl = body.url || null;
      } else if (type === 'group' && groupId) {
        const idx = groups.findIndex(g => g.groupId === groupId);
        if (idx >= 0) {
          groups[idx] = { ...groups[idx], url: body.url || null };
          groups = [...groups];
        }
      }
      success('Feed de calendario actualizado');
    } catch (e) {
      error('No se puedo actualizar');
    } finally {
      if (type === 'group' && groupId) rotating[groupId] = false;
      if (type === 'personal') rotating['personal'] = false;
      if (type === 'aggregate') rotating['aggregate'] = false;
      rotating = { ...rotating };
    }
  }
</script>

<svelte:head>
  <title>Integraciones</title>
  <meta name="robots" content="noindex,nofollow" />
</svelte:head>

<section style="max-width: 920px; margin: 1.5rem auto; padding: 0 1rem;">
  <h1 style="font-size: 1.4rem; font-weight: 600; margin-bottom: .75rem;">Integraciones</h1>

  <h2 style="font-size: 1.1rem; font-weight: 600; margin: .5rem 0;">Feed personal</h2>
  <FeedCard
    title="Mis tareas (con fecha)"
    description="Suscríbete a este feed en tu calendario para ver tus tareas con fecha de vencimiento."
    url={personalUrl}
    rotating={!!rotating['personal']}
    on:rotate={() => rotate('personal')}
  />

  <h2 style="font-size: 1.1rem; font-weight: 600; margin: 1rem 0 .5rem;">Feed multigrupo</h2>
  <FeedCard
    title="Mis grupos (sin responsable)"
    description="Tareas sin responsable agregadas de tus grupos permitidos."
    url={aggregateUrl}
    rotating={!!rotating['aggregate']}
    on:rotate={() => rotate('aggregate')}
  />

  <h2 style="font-size: 1.1rem; font-weight: 600; margin: 1rem 0 .5rem;">Feeds por grupo (sin responsable)</h2>
  {#if groups.length === 0}
    <EmptyState>No hay grupos disponibles todavía. Cuando los haya, verás aquí sus feeds ICS.</EmptyState>
  {:else}
    <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: var(--space-3);">
      {#each groups as g (g.groupId)}
        <FeedCard
          title={g.groupName || g.groupId}
          description="Tareas sin responsable"
          url={g.url}
          rotating={!!rotating[g.groupId]}
          on:rotate={() => rotate('group', g.groupId)}
        />
      {/each}
    </div>
  {/if}
</section>
