"use client";

import { useEffect, useMemo, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { cn } from "@/lib/utils";

function initials(email: string): string {
  const local = email.split("@")[0] || email;
  return local.slice(0, 2).toUpperCase();
}

/**
 * Shows who is currently viewing this project's page, via Supabase Realtime
 * Presence (in-memory; no DB tables involved). Each connected client tracks
 * its email; we dedupe and render an avatar per unique viewer.
 */
export function PresenceViewers({
  projectId,
  currentUserEmail,
  showLabel = true,
}: {
  projectId: string;
  currentUserEmail: string | null;
  showLabel?: boolean;
}) {
  const supabase = useMemo(() => createClient(), []);
  const [emails, setEmails] = useState<string[]>([]);

  useEffect(() => {
    const me = currentUserEmail ?? "unknown";
    const channel = supabase.channel(`presence:project:${projectId}`, {
      config: { presence: { key: me } },
    });

    channel
      .on("presence", { event: "sync" }, () => {
        const state = channel.presenceState<{ email: string }>();
        const set = new Set<string>();
        for (const entries of Object.values(state)) {
          for (const p of entries) if (p.email) set.add(p.email);
        }
        setEmails([...set].sort());
      })
      .subscribe(async (status) => {
        if (status === "SUBSCRIBED") {
          await channel.track({ email: me });
        }
      });

    return () => {
      supabase.removeChannel(channel);
    };
  }, [supabase, projectId, currentUserEmail]);

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

  return (
    <div className="flex items-center gap-2">
      {showLabel && (
        <span className="hidden text-xs text-muted-foreground sm:inline">
          Viewing now
        </span>
      )}
      <div className="flex -space-x-1.5">
        {emails.map((email) => (
          <span
            key={email}
            title={email === currentUserEmail ? `${email} (you)` : email}
            className={cn(
              "inline-flex size-6 items-center justify-center rounded-full border-2 border-background text-[10px] font-semibold",
              email === currentUserEmail
                ? "bg-primary text-primary-foreground"
                : "bg-muted text-muted-foreground",
            )}
          >
            {initials(email)}
          </span>
        ))}
      </div>
    </div>
  );
}
