/**
 * Archive, as an overlay rather than a footer.
 *
 * It used to sit in the card's footer, which is where a reader's eye lands
 * after the title — so the most destructive control on the page was competing
 * with the content for attention, for the majority of viewers who cannot even
 * use it. It is now a sibling of the play button (never a descendant: a button
 * inside a button is invalid and Firefox drops the inner one) and only appears
 * once an admin has asked to manage.
 */
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { cn } from '@/components/ui';

export function ArchiveControl({
  id,
  title,
  className,
}: {
  id: string;
  title: string;
  className?: string;
}) {
  const queryClient = useQueryClient();
  const [confirming, setConfirming] = useState(false);

  const archive = useMutation({
    mutationFn: () => api<unknown>(`/api/learn/resources/${id}`, { method: 'DELETE' }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['learn'] });
      toast.success(`Archived “${title}”.`);
    },
    onError: (error: unknown) => {
      setConfirming(false);
      toast.error(error instanceof Error ? error.message : 'Could not archive that video.');
    },
  });

  return (
    <button
      type="button"
      onClick={() => {
        // Two taps, no dialog. A modal for an archive that a colleague can
        // restore is ceremony; one silent tap is a video gone from a shared
        // library because a thumb brushed the corner of a card.
        if (!confirming) {
          setConfirming(true);
          return;
        }
        archive.mutate();
      }}
      onBlur={() => setConfirming(false)}
      disabled={archive.isPending}
      aria-label={confirming ? `Confirm archiving ${title}` : `Archive ${title}`}
      className={cn(
        'tap inline-flex items-center gap-1.5 rounded-lg border border-border px-2.5 text-xs font-medium',
        'bg-surface/90 backdrop-blur-sm transition-colors duration-1 ease-enter disabled:opacity-50',
        confirming ? 'text-danger hover:bg-danger/10' : 'text-muted hover:bg-surface-2 hover:text-fg',
        className,
      )}
    >
      <Trash2 className="size-4 shrink-0" aria-hidden />
      {confirming ? 'Confirm' : 'Archive'}
    </button>
  );
}
