import { createClient } from "@liveblocks/client";
import { createRoomContext, createLiveblocksContext } from "@liveblocks/react";

// Create the Liveblocks client
const client = createClient({
  publicApiKey: process.env.NEXT_PUBLIC_LIVEBLOCKS_PUBLIC_KEY || "",
  throttle: 100,
});

// Presence represents the user's current state
export type Presence = {
  cursor: { x: number; y: number } | null;
  name: string;
  color: string;
  activeFieldId: string | null;
};

// Storage represents the shared document state
// Using JsonObject for Liveblocks compatibility
export type Storage = {
  canvasData: { [key: string]: string | number | boolean | null | undefined };
};

// User meta information
export type UserMeta = {
  id: string;
  info: {
    name: string;
    color: string;
    avatar?: string;
  };
};

// Room event types
export type RoomEvent = {
  type: "FIELD_FOCUS" | "FIELD_BLUR" | "ELEMENT_MOVE";
  fieldId?: string;
  elementId?: string;
  userId?: string;
};

// Thread metadata (for comments if needed)
export type ThreadMetadata = {
  fieldId?: string;
  x?: number;
  y?: number;
};

// Create room context with typed state
export const {
  suspense: {
    RoomProvider,
    useRoom,
    useMyPresence,
    useUpdateMyPresence,
    useOthers,
    useOthersMapped,
    useSelf,
    useStorage,
    useMutation,
    useStatus,
    useBroadcastEvent,
    useEventListener,
  },
} = createRoomContext<Presence, Storage, UserMeta, RoomEvent>(client);

// Create Liveblocks context for account-level features
export const {
  suspense: { LiveblocksProvider },
} = createLiveblocksContext(client);

// Generate a random color for new users
export function getRandomColor(): string {
  const colors = [
    "#E57373", "#F06292", "#BA68C8", "#9575CD",
    "#7986CB", "#64B5F6", "#4FC3F7", "#4DD0E1",
    "#4DB6AC", "#81C784", "#AED581", "#DCE775",
    "#FFD54F", "#FFB74D", "#FF8A65", "#A1887F",
  ];
  return colors[Math.floor(Math.random() * colors.length)];
}

// Generate a random user name
export function getRandomName(): string {
  const adjectives = ["Curious", "Creative", "Innovative", "Bold", "Thoughtful", "Visionary"];
  const nouns = ["Designer", "Thinker", "Explorer", "Pioneer", "Creator", "Maker"];
  const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
  const noun = nouns[Math.floor(Math.random() * nouns.length)];
  return `${adj} ${noun}`;
}
