'use client';

import { useCallback, useEffect, useState } from 'react';
import { X, Bell } from 'lucide-react';
import {
  subscribeRealtime,
  type RealtimeNotification,
} from '@/lib/realtime';

interface ActiveToast extends RealtimeNotification {
  /** Local id — `id` from the server may collide across reconnects in dev. */
  localId: string;
}

const MAX_TOASTS = 3;
const AUTO_DISMISS_MS = 8_000;

/**
 * Global corner toaster. Listens for every `notification:new` event coming
 * through the realtime bus and stacks up to 3 cards in the bottom-right.
 * Older toasts are evicted FIFO; each toast also auto-dismisses after 8s.
 *
 * Mounted once in the root layout so toasts appear on every page. Renders
 * nothing (just an empty <div>) when there are no active toasts and the bus
 * isn't connected — meaning "no socket available" produces zero DOM noise.
 */
export function NotificationToaster() {
  const [toasts, setToasts] = useState<ActiveToast[]>([]);

  const dismiss = useCallback((localId: string) => {
    setToasts((prev) => prev.filter((t) => t.localId !== localId));
  }, []);

  useEffect(() => {
    const unsubscribe = subscribeRealtime((n) => {
      const localId = `${n.id}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      setToasts((prev) => {
        const next = [...prev, { ...n, localId }];
        // Keep only the most recent MAX_TOASTS.
        return next.slice(-MAX_TOASTS);
      });
      // Auto-dismiss.
      window.setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.localId !== localId));
      }, AUTO_DISMISS_MS);
    });
    return unsubscribe;
  }, []);

  if (toasts.length === 0) return null;

  return (
    <div
      className="pointer-events-none fixed bottom-4 right-4 z-[60] flex w-full max-w-sm flex-col gap-2"
      role="region"
      aria-label="Notifications"
      aria-live="polite"
    >
      {toasts.map((t) => (
        <div
          key={t.localId}
          className="pointer-events-auto flex items-start gap-3 rounded-lg border border-denseSurface-border bg-white p-3 shadow-lg ring-1 ring-black/5"
        >
          <span className="mt-0.5 inline-flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md bg-brand-50 text-brand-600">
            <Bell className="h-4 w-4" />
          </span>
          <div className="min-w-0 flex-1">
            <p className="truncate text-sm font-semibold text-ink-1">
              {t.title}
            </p>
            {t.body ? (
              <p className="mt-0.5 line-clamp-3 text-xs text-ink-2">{t.body}</p>
            ) : null}
          </div>
          <button
            type="button"
            onClick={() => dismiss(t.localId)}
            aria-label="Dismiss notification"
            className="-mr-1 -mt-1 inline-flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-ink-3 transition-colors hover:bg-denseSurface-bg hover:text-ink-1"
          >
            <X className="h-4 w-4" />
          </button>
        </div>
      ))}
    </div>
  );
}
