'use client';

//import { useState } from "react";
import { SpotifyAuth, Scopes } from 'react-spotify-auth';
import 'react-spotify-auth/dist/index.css';
import {
  useEffect,
  useState,
  useRef,
  useMemo,
  useCallback,
  SetStateAction,
  ChangeEvent,
} from 'react';
import Script from 'next/script';
import * as Ably from 'ably';
import {
  SignedIn,
  SignedOut,
  SignInButton,
  SignUpButton,
  useAuth,
  UserButton,
  useUser,
} from '@clerk/nextjs';
import { create } from 'zustand';
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
import { GSP_NO_RETURNED_VALUE } from 'next/dist/lib/constants';

const padWithZero = (num: number) => {
  if (num < 10) {
    return `0${num}`;
  }
  return num;
};
const formatTime = (secs: number) => {
  return `${Math.floor(secs / 60)}:${padWithZero(Math.floor(secs % 60))}`;
};

class PlayerStore {
  queueItems: any[] = [];
  lastCurrentState: any = null;
  isSkipping: boolean = false;
  selectedChannel: string = 'camoffice';
  constructor() {
    makeAutoObservable(this);
  }

  setQueueItems(queueItems: any[]) {
    this.queueItems = queueItems;
  }
  setLastCurrentState(lastState: any) {
    this.lastCurrentState = lastState;
  }
  setIsSkipping(isSkipping: boolean) {
    this.isSkipping = isSkipping;
  }
  setSelectedChannel(channel: string) {
    this.selectedChannel = channel;
  }
}

const playerStore = new PlayerStore();

const useSpotifyPlayer = (accessToken: any) => {
  const [player, setPlayer] = useState(null);
  const [deviceId, setDeviceId] = useState(null);
  const [isReady, setIsReady] = useState(false);
  const [currentTrack, setCurrentTrack] = useState(null);
  const [isPaused, setIsPaused] = useState(true);
  const [isAuthError, setIsAuthError] = useState(false);

  // Handle SDK Ready
  useEffect(() => {
    // Wait for Spotify SDK to be ready
    (window as any).onSpotifyWebPlaybackSDKReady = () => {
      // Create the player
      const spotifyPlayer = new (window as any).Spotify.Player({
        name: 'Vibe App Player',
        getOAuthToken: (cb: any) => {
          cb(accessToken);
        },
        volume: 0.5,
      });

      // Set up event listeners
      spotifyPlayer.addListener(
        'ready',
        ({ device_id }: { device_id: any }) => {
          console.log('Player ready with device ID', device_id);
          setDeviceId(device_id);
          setIsReady(true);
        }
      );

      spotifyPlayer.addListener(
        'not_ready',
        ({ device_id }: { device_id: any }) => {
          console.log('Device ID is not ready', device_id);
          setIsReady(false);
        }
      );

      spotifyPlayer.addListener('player_state_changed', (state: any) => {
        console.log('state change', state);

        if (!state) return;

        const currentTrackData = state.track_window.current_track;
        setCurrentTrack(currentTrackData);
        setIsPaused(state.paused);

        if (
          state &&
          state.paused &&
          state.restrictions &&
          state.restrictions.disallow_resuming_reasons
        ) {
          console.log(
            'Pause reasons:',
            state.restrictions.disallow_resuming_reasons
          );
        }
      });

      // Error listeners
      spotifyPlayer.addListener(
        'initialization_error',
        ({ message }: { message: any }) => {
          console.error('Initialization error:', message);
        }
      );

      spotifyPlayer.addListener(
        'authentication_error',
        ({ message }: { message: any }) => {
          setIsAuthError(true);
          console.error('Authentication error:', message);
        }
      );

      spotifyPlayer.addListener(
        'account_error',
        ({ message }: { message: any }) => {
          console.error('Account error:', message);
        }
      );

      spotifyPlayer.addListener(
        'playback_error',
        ({ message }: { message: any }) => {
          console.error('Playback error:', message);
        }
      );

      // Connect the player
      spotifyPlayer.connect();
      setPlayer(spotifyPlayer);
    };

    // If the SDK is already loaded, trigger the ready function manually
    if ((window as any).Spotify) {
      (window as any).onSpotifyWebPlaybackSDKReady();
    }

    // Cleanup function to disconnect player
    return () => {
      if (player) {
        (player as any).disconnect();
      }
    };
  }, [accessToken]);

  // Function to activate the player
  const activatePlayer = async () => {
    if (!deviceId) return;

    try {
      const data = await fetch('https://api.spotify.com/v1/me/player', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({
          device_ids: [deviceId],
          play: true,
        }),
      });
      console.log('activetaed player', data);
      //setIsSpotifyActivated(true);
    } catch (error) {
      console.error('Error activating player:', error);
    }
  };

  return {
    player,
    deviceId,
    isReady,
    isAuthError,
    currentTrack,
    isPaused,
    activatePlayer,
  };
};

// SpotifyPlayer component
const SpotifyPlayer = ({ accessToken }: { accessToken: any }) => {
  if (!accessToken) return <div>Please provide an access token</div>;

  //if (!isReady) return <div>Loading Spotify Player...</div>;

  return 'Spotify Loaded';

  // return (
  //   <div className="spotify-player p-4 bg-gray-900 text-white rounded-lg">
  //     <div className="flex justify-between items-center mb-4">
  //       <h2 className="text-xl font-bold">Vibe Player</h2>
  //       <button
  //         onClick={activatePlayer}
  //         className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600"
  //       >
  //         Set as Active Device
  //       </button>
  //     </div>

  //     {currentTrack && (
  //       <div className="flex items-center mb-4">
  //         {(currentTrack as any).album.images[0]?.url && (
  //           <img
  //             src={(currentTrack as any).album.images[0].url}
  //             alt="Album art"
  //             className="w-16 h-16 mr-4 rounded"
  //           />
  //         )}
  //         <div>
  //           <div className="font-semibold">{(currentTrack as any).name}</div>
  //           <div className="text-gray-400">
  //             {(currentTrack as any).artists.map((a) => a.name).join(", ")}
  //           </div>
  //         </div>
  //       </div>
  //     )}

  //     <div className="flex justify-center space-x-4">
  //       <button
  //         onClick={() => (player as any).previousTrack()}
  //         className="p-2 bg-gray-800 rounded-full hover:bg-gray-700"
  //       >
  //         ⏮️
  //       </button>
  //       <button
  //         onClick={() => (player as any).togglePlay()}
  //         className="p-2 bg-gray-800 rounded-full hover:bg-gray-700"
  //       >
  //         {isPaused ? "▶️" : "⏸️"}
  //       </button>
  //       <button
  //         onClick={() => (player as any).nextTrack()}
  //         className="p-2 bg-gray-800 rounded-full hover:bg-gray-700"
  //       >
  //         ⏭️
  //       </button>
  //     </div>
  //   </div>
  // );
};

// Update the ActiveUser type
type ActiveUser = {
  clientId: string;
  data: {
    email: string;
    isHost: boolean;
    imageUrl?: string;
  };
};

export function formatClipPrompt(prompt: string, maxLength = 40) {
  return prompt
    .replace(/\[.*?\]/g, '')
    .trim()
    .split('\n')[0]
    .slice(0, maxLength);
}

/**
 * Chooses between title, prompt, or a fallback
 */
export function formatClipTitle(
  title: string | null | undefined,
  prompt: string | null | undefined,
  fallback = 'Untitled'
) {
  return title || formatClipPrompt(prompt ?? '') || fallback;
}

export const getClipTitle = (clip: any) =>
  formatClipTitle(clip?.title, clip?.metadata?.prompt, 'Untitled');

const App = observer(({ isStreamer }: { isStreamer?: boolean }) => {
  const [token, setToken] = useState<any>(0);
  //const [queueItems, setQueueItems] = useState<any>([]);
  // const [lastCurrentState, setLastCurrentState] = useState<any>(null);
  const audioRef = useRef<any>(null);
  const [url, setUrl] = useState('');
  const [initPlaying, setInitPlaying] = useState(false);
  const [randomPos, setRandomPos] = useState<string>('bg-[right_bottom_0rem]');
  const [randomSize, setRandomSize] = useState<string>('bg-[auto_1000px]');
  const checkIntervalRef = useRef<any>(null);
  const {
    player,
    deviceId,
    isReady,
    isAuthError,
    currentTrack,
    isPaused,
    activatePlayer,
  } = useSpotifyPlayer(token);

  const auth = useAuth();
  const { isSignedIn, user, isLoaded } = useUser();
  const ablyClient = useMemo(() => {
    return new Ably.Realtime({
      authUrl: 'api/ably-auth',
      clientId: auth.userId || null,
    } as Ably.ClientOptions);
  }, [auth.userId]);

  const isValidSpotifyUri = (spotifyUri: string) => {
    if (spotifyUri.includes('open.spotify.com')) {
      const parts = spotifyUri.split('/');
      const id = parts[parts.length - 1].split('?')[0]; // Remove query params if any
      const type = parts[parts.length - 2]; // track, album, playlist, etc.
      return type === 'track';
    }
    return false;
  };

  const lookupSpotifyURL = useCallback(
    async (url: string) => {
      if (isValidSpotifyUri(url)) {
        const parts = url.split('/');
        const id = parts[parts.length - 1].split('?')[0];
        const data = await fetch(`https://api.spotify.com/v1/tracks/${id}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        });
        if (!data.ok) {
          setToken(null);
          return;
        }
        const dataJSON = await data.json();
        if (!!dataJSON.error) {
          setToken(null);
          return;
        }
        return dataJSON;
      }
      return null;
    },
    [token]
  );

  const lookupSunoURL = useCallback(
    async (url: string) => {
      const parts = url.split('/');
      const id = parts[parts.length - 1].split('?')[0];
      const data = await fetch(`/api/suno/?clip_id=${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          //Authorization: `Bearer ${token}`,
        },
      });
      const dataJSON = await data.json();
      return dataJSON;
    },
    [token]
  );

  const playItem = async (item: Ably.InboundMessage, offset: number) => {
    if (!item) {
      return;
    }
    if (!!item.data.spotifyData) {
      // item is Spotify track, play with Spotify player
      playSpotifyURL(item.data?.spotifyData.uri);
    } else if (!!item.data.sunoData) {
      // item is Suno track
      if (audioRef.current) {
        audioRef.current.src = item.data.sunoData.audio_url;
        audioRef.current.currentTime = offset;
        audioRef.current.play();
        if (playerStore.isSkipping) {
          playerStore.setIsSkipping(false);
        }
      }
    }
    await channel.publish('currentState', {
      queueId: item.data.queueId,
      offset: 0,
    });
  };

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.addEventListener('ended', () => {
        console.log('ended event!');
        if (initPlaying) {
          console.log('skip 2 next');
          //skipToNextTrack();
        }
      });
      audioRef.current.addEventListener('pause', () => {
        console.log('pause event!');
      });
      audioRef.current.addEventListener('timeupdate', () => {
        console.log('pause event!', audioRef.current.duration);
        console.log(audioRef.current.currentTime);
        if (audioRef.current.duration - audioRef.current.currentTime < 0.5) {
          if (!playerStore.isSkipping) {
            playerStore.setIsSkipping(true);
            skipToNextTrack();
          }
        }
      });
    }
  }, [audioRef.current]);

  const playSpotifyURL = useCallback(
    async (transformUri: string, offset?: number) => {
      // Add retry logic for player activation
      const maxRetries = 3;
      let retryCount = 0;

      const attemptPlayback = async () => {
        if (!player || !deviceId) {
          if (retryCount < maxRetries) {
            retryCount++;
            console.log(`Retrying player activation (attempt ${retryCount})`);
            await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1s between retries
            await activatePlayer();
            return attemptPlayback();
          }
          console.error('Failed to initialize Spotify player after retries');
          return;
        }

        try {
          await activatePlayer();

          // Wait a moment for device activation
          await new Promise(resolve => setTimeout(resolve, 1000));

          const data = await fetch(
            `https://api.spotify.com/v1/me/player/play?device_id=${deviceId}`,
            {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`,
              },
              body: JSON.stringify({
                uris: [transformUri],
              }),
            }
          );

          if (!data.ok) {
            throw new Error(`Failed to start playback: ${data.status}`);
          }

          if (offset && player) {
            await new Promise(resolve => setTimeout(resolve, 500)); // Wait for track to load
            await (player as any).seek(offset * 1000);
          }

          if (isPaused && player) {
            await (player as any).resume();
          }

          if (playerStore.isSkipping) {
            playerStore.setIsSkipping(false);
          }
        } catch (error) {
          console.error('Playback error:', error);
          if (retryCount < maxRetries) {
            retryCount++;
            console.log(`Retrying after error (attempt ${retryCount})`);
            await new Promise(resolve => setTimeout(resolve, 1000));
            return attemptPlayback();
          }
        }
      };

      await attemptPlayback();
    },
    [deviceId, token, player, isPaused, activatePlayer]
  );

  const resolveUrl = async (url: string, channel: any) => {
    const queueId = crypto.randomUUID();
    const dataToPublish: any = {
      queueId,
      email: user?.primaryEmailAddress?.emailAddress,
    };

    if (url.includes('open.spotify.com/track/')) {
      const data = await lookupSpotifyURL(url);
      if (data) {
        dataToPublish.spotifyData = data;
      }
    } else if (
      url.includes('b.suno.fm/song/') ||
      url.includes('suno.com/song/')
    ) {
      //const data = await lookupSunoURL(url);
      const parts = url.split('/');
      const id = parts[parts.length - 1].split('?')[0];

      const suno_api_url = url.includes('suno.com/song/')
        ? 'https://studio-api.prod.suno.com'
        : 'https://studio-api.staging.suno.com';
      const data = await fetch(`${suno_api_url}/api/clip/${id}`);
      const dataJSON = await data.json();

      if (data) {
        dataToPublish.sunoData = { ...dataJSON, url: url };
      }
    }
    if (!!dataToPublish.spotifyData || !!dataToPublish.sunoData) {
      await channel.publish('newSongQueue', dataToPublish);
    }
  };

  useEffect(() => {
    const tk = localStorage.getItem('spotifyAuthToken');
    if (tk && !isStreamer) {
      setToken(tk);
    }
    const k = setInterval(() => {
      // setRandomPos(
      //   [
      //     "bg-[right_bottom_0rem]",
      //     "bg-[left_bottom_3rem]",
      //     "bg-[left_top_0rem]",
      //     "bg-[left_top_2rem]",
      //   ][Math.floor(Math.random() * 4)]
      // );
      // setRandomSize(
      //   [
      //     "bg-[auto_1000px]",
      //     "bg-[auto_800px]",
      //     "bg-[auto_1200px]",
      //     "bg-[auto_900px]",
      //   ][Math.floor(Math.random() * 4)]
      // );
    }, 5000);
    return () => {
      clearInterval(k);
    };
  }, []);

  // useEffect(() => {
  //   if (isStreamer && isReady && token && player && !initPlaying) {
  //     setInitPlaying(true);
  //   }
  // }, [isReady, token, player, initPlaying, isStreamer]);

  const channel = useMemo(() => {
    const keys: { [key: string]: string } = {
      camoffice: 'data',
      songfooding: 'songfood',
      headphones: 'headphones',
      schtud: 'schtud',
      nyc: 'nyc',
      la: 'la',
    };
    return ablyClient.channels.get(
      `officeRadio:${keys[playerStore.selectedChannel] || 'data'}`
    );
  }, [ablyClient, playerStore.selectedChannel]);

  const skipToFirstTrack = useCallback(() => {
    const itemToPlay = playerStore.queueItems[0];
    playItem(itemToPlay, 0);
    setInitPlaying(true);
  }, [playerStore.queueItems]);

  const skipToNextTrack = useCallback(() => {
    console.log('skipping to next!@');
    player && (player as any).pause();
    audioRef.current && audioRef.current.pause();
    if (playerStore.queueItems.length <= 1) {
      playerStore.setQueueItems([]);
      return;
    }
    const itemToPlay = playerStore.queueItems[1];
    console.log('skipping to next track!', itemToPlay);
    playerStore.setQueueItems(playerStore.queueItems.slice(1));
    playItem(itemToPlay, 0);
  }, [playerStore.queueItems, player]);

  useEffect(() => {
    if (!isPaused && player && isStreamer) {
      clearInterval(checkIntervalRef.current);
      checkIntervalRef.current = setInterval(async () => {
        if (!playerStore.queueItems?.[0]?.data?.spotifyData) {
          return;
        }
        const state = await (player as any).getCurrentState();
        const { position, duration, paused } = state;
        console.log('state', state);
        console.log('remaining in song', duration - position);
        if (duration - position < 1000 && !playerStore.isSkipping && !paused) {
          console.log('skipping to next');
          skipToNextTrack();
        }
      }, 1000);
    }
  }, [isPaused, player, playerStore.queueItems, isStreamer]);

  const isValidItem = (item: any) => {
    return (
      item.name === 'newSongQueue' &&
      !!item.data.queueId &&
      !!item.data.email &&
      (!!item.data.spotifyData || !!item.data.sunoData) &&
      !item.data.spotifyData?.error
    );
  };

  const addToQueueItems = useCallback(
    (message: Ably.InboundMessage) => {
      console.log(playerStore.queueItems);
      playerStore.setQueueItems([...playerStore.queueItems, message]);
      if (playerStore.queueItems.length === 1) {
        skipToFirstTrack();
      }
    },
    [playerStore.queueItems]
  );

  const [likedSongs, setLikedSongs] = useState<Map<string, Set<string>>>(
    new Map()
  );

  const processMessage = useCallback(
    (message: Ably.InboundMessage) => {
      console.log(message);
      console.log(playerStore.queueItems);
      if (
        message.name === 'newSongQueue' &&
        playerStore.queueItems.find(
          (item: Ably.InboundMessage) =>
            item.data.queueId === message.data.queueId
        )
      ) {
        console.log('already queued!');
        return;
      }
      if (isValidItem(message)) {
        console.log('add to queue items');
        addToQueueItems(message);
      } else if (message.name === 'currentState') {
        console.log(message);
        playerStore.setLastCurrentState(message);
        const queueTsOfCurrent = playerStore.queueItems.find(
          (item: Ably.InboundMessage) =>
            item.data.queueId === message?.data.queueId
        )?.timestamp;

        const validMessages = playerStore.queueItems.filter(
          (item: Ably.InboundMessage) =>
            isValidItem(item) && item.timestamp >= (queueTsOfCurrent || 0)
        );

        console.log('setting queue items', validMessages);
        playerStore.setQueueItems(validMessages);
      } else if (message.name === 'songLike') {
        // Handle like/unlike messages
        const { queueId, userEmail, isLiked } = message.data;
        setLikedSongs(prev => {
          const newMap = new Map(prev);
          if (!newMap.has(queueId)) {
            newMap.set(queueId, new Set());
          }
          const userSet = newMap.get(queueId)!;
          if (isLiked) {
            userSet.add(userEmail);
          } else {
            userSet.delete(userEmail);
          }
          if (userSet.size === 0) {
            newMap.delete(queueId);
          }
          return newMap;
        });
      }
    },
    [playerStore.queueItems, playerStore.lastCurrentState]
  );

  const [activeUsers, setActiveUsers] = useState<ActiveUser[]>([]);

  useEffect(() => {
    const getData = async () => {
      const messagesPage = await channel.history({ limit: 1000 });
      const lastCurrentStateUpdate = messagesPage.items.find(
        (item: Ably.InboundMessage) => item.name === 'currentState'
      );
      const queueTsOfCurrent = messagesPage.items.find(
        (item: Ably.InboundMessage) =>
          item.name === 'newSongQueue' &&
          item.data.queueId === lastCurrentStateUpdate?.data.queueId
      )?.timestamp;

      console.log(messagesPage.items);

      const validMessages = messagesPage.items
        .filter(
          (item: Ably.InboundMessage) =>
            isValidItem(item) && item.timestamp >= (queueTsOfCurrent || 0)
        )
        .toReversed();

      playerStore.setQueueItems(validMessages);
      playerStore.setLastCurrentState(lastCurrentStateUpdate);

      // Subscribe to presence events
      channel.presence.subscribe('enter', member => {
        setActiveUsers(prev => [...prev, member]);
      });

      channel.presence.subscribe('leave', member => {
        setActiveUsers(prev =>
          prev.filter(user => user.clientId !== member.clientId)
        );
      });

      // Get current presence set
      const members = await channel.presence.get();
      setActiveUsers(members as unknown as ActiveUser[]);

      channel.subscribe(processMessage);
      channel.presence.enter({
        isHost: isStreamer,
        email: user?.emailAddresses[0].emailAddress,
        imageUrl: user?.imageUrl,
      });
    };
    if (channel) {
      getData();
    }

    // Cleanup subscriptions
    return () => {
      if (channel && channel.state === 'attached') {
        channel.presence.unsubscribe();
        channel.presence.leave();
      }
    };
  }, [channel]);

  useEffect(() => {
    if (isReady && playerStore.queueItems && isStreamer && !initPlaying) {
      if (playerStore.lastCurrentState) {
        const nowTs = Date.now();
        const nowOffset =
          playerStore.lastCurrentState.data.offset +
          (nowTs - playerStore.lastCurrentState.timestamp);
        if (isStreamer) {
          playItem(playerStore.queueItems[0], nowOffset);
          setInitPlaying(true);
        }
      } else {
        if (isStreamer) {
          playItem(playerStore.queueItems[0], 0);
          setInitPlaying(true);
        }
      }
    }
  }, [isReady]);

  useEffect(() => {
    if (isAuthError) {
      setToken(null);
    }
  }, [isAuthError]);

  //   useEffect(() => {
  //     console.log(currentTrack, isPaused, player, isReady, deviceId);
  //     if (currentTrack && isPaused && player && isReady && deviceId) {
  //       console.log("toggling play");
  //       (player as any).togglePlay();
  //     }
  //   }, [currentTrack, isPaused, player]);

  const numUsers = [
    ...new Map(
      activeUsers.filter(u => u.data.email).map(user => [user.data.email, user])
    ).values(),
  ].length;

  const handleSkip = useCallback(() => {
    console.log('skipping to next!@');
    player && (player as any).pause();
    audioRef.current && audioRef.current.pause();
    if (playerStore.queueItems.length <= 1) {
      playerStore.setQueueItems([]);
      return;
    }
    const itemToPlay = playerStore.queueItems[1];
    console.log('skipping to next track!', itemToPlay);
    playerStore.setQueueItems(playerStore.queueItems.slice(1));
    playItem(itemToPlay, 0);
  }, [playerStore.queueItems, player]);

  const handleLike = useCallback(
    (queueId: string) => {
      const userEmail = user?.emailAddresses[0]?.emailAddress;
      if (!userEmail) return;

      const currentLikes = likedSongs.get(queueId) || new Set();
      const isCurrentlyLiked = currentLikes.has(userEmail);
      const newIsLiked = !isCurrentlyLiked;

      // Publish like/unlike event to channel
      channel.publish('songLike', {
        queueId,
        userEmail,
        isLiked: newIsLiked,
      });

      // Update local state immediately for responsive UI
      setLikedSongs(prev => {
        const newMap = new Map(prev);
        if (!newMap.has(queueId)) {
          newMap.set(queueId, new Set());
        }
        const userSet = newMap.get(queueId)!;
        if (newIsLiked) {
          userSet.add(userEmail);
        } else {
          userSet.delete(userEmail);
        }
        if (userSet.size === 0) {
          newMap.delete(queueId);
        }
        return newMap;
      });
    },
    [likedSongs, user?.emailAddresses, channel]
  );

  return (
    <div className="w-full p-8 px-20 h-screen bg-slate-800 flex flex-row gap-4 overflow-y-auto relative font-sans">
      <div
        className={`hidden fixed top-0 left-0 ${randomSize} blur-[20px] h-[1000px] max-h-screen w-full z-[0] pointer-events-none transition-[background-image,background-position,background-size] duration-[2s] ease-in-out bg-[url('/Aura-07.png')] ${randomPos} [mask-image:radial-gradient(circle_at_top,rgba(0,0,0,0.6)_0%,rgba(0,0,0,0.3)_35%,rgba(0,0,0,0.0)_80%)]`}
      />
      <div className="flex flex-col sticky top-0">
        <div className="flex flex-row flex-end">
          <h1 className="text-[32px] bg-gradient-to-r from-[#39ff14] to-[#7DF9FF] text-transparent bg-clip-text font-serif font-medium">
            Songfood
          </h1>
          <div className="flex-1 flex flex-row-reverse">
            <select
              className="bg-slate-600 text-white h-[32px] rounded-lg mr-1 mt-2 px-2"
              value={playerStore.selectedChannel}
              onChange={(e: ChangeEvent) =>
                playerStore.setSelectedChannel((e.target as any).value)
              }
            >
              <option value="camoffice">CAM Office</option>
              <option value="songfooding">Songfooding</option>
              <option value="headphones">Headphones</option>
              <option value="schtud">Schtüd</option>
              <option value="nyc">NYC Office</option>
              <option value="la">LA Office</option>
            </select>
          </div>
        </div>
        <div className="rounded-[20px] bg-slate-300 border border-black w-[500px] p-8">
          {/* <button className="rounded-[20px]">Play Here</button>
        <button id="togglePlay">Play/Pause</button>
        <button id="nextTrack">Next</button>
        <button id="prevTrack">Previous</button>
        <div id="currentTrack"></div> */}
          <input
            type="text"
            value={url}
            className="w-full rounded-2xl bg-white h-[40px] p-4 mb-8"
            placeholder={'Paste Spotify or Suno (staging or prod) link'}
            onChange={(e: any) => {
              setUrl(e.target.value);
            }}
            onKeyDown={(e: any) => {
              if (e.key === 'Enter') {
                resolveUrl(url, channel);
                setUrl('');
              }
            }}
          />
          {!token ? (
            <SpotifyAuth
              redirectUri={
                isStreamer
                  ? 'https://songfood.suno.run/stream'
                  : 'https://songfood.suno.run'
                // isStreamer
                //   ? "http://localhost:3000/stream"
                //   : "http://localhost:3000"
              }
              clientID={process.env.NEXT_PUBLIC_SPOTIFY_KEY}
              scopes={[
                Scopes.userReadPrivate,
                Scopes.userReadEmail,
                Scopes.streaming,
              ]}
              onAccessToken={(token: any) => {
                // Use the token for API calls
                setToken(token);
                localStorage.setItem('spotifyAuthToken', token);
              }}
            />
          ) : null}

          {isStreamer ? (
            <>
              {!token ? (
                <div>Please provide an access token</div>
              ) : !isReady ? (
                <div>Spotify getting ready...</div>
              ) : (
                <>
                  <div>Spotify Ready: {isPaused ? 'PAUSED' : 'PLAYING'}</div>
                  <div>
                    {currentTrack &&
                      `${(currentTrack as any)?.name || ''} - ${(
                        currentTrack as any
                      ).artists
                        .map((a: any) => a.name)
                        .join(', ')}`}
                  </div>
                  <div className="flex flex-row gap-2 my-2">
                    <button
                      className="border border-black/50 bg-black/5 rounded-xl px-2 cursor-pointer hover:bg-black/10"
                      onClick={() => skipToFirstTrack()}
                    >
                      Play/Pause
                    </button>
                    <button
                      className="border border-black/50 bg-black/5 rounded-xl px-2 cursor-pointer hover:bg-black/10"
                      onClick={() => skipToNextTrack()}
                    >
                      Skip
                    </button>
                  </div>
                </>
              )}
            </>
          ) : null}

          {/* Add skip button for non-streamers */}
          {!isStreamer && (
            <div className="flex flex-row gap-2 my-2">
              <button
                className="border border-black/50 bg-black/5 rounded-xl px-2 cursor-pointer hover:bg-black/10"
                onClick={handleSkip}
              >
                Skip Current Song
              </button>
            </div>
          )}

          <SignedOut>
            <div className="flex flex-row gap-4">
              <SignInButton />
              <SignUpButton />
            </div>
          </SignedOut>
          <SignedIn>
            <div className="flex flex-row text-slate-700 items-center font-bold text-base gap-2">
              <UserButton /> {user?.emailAddresses?.[0]?.emailAddress}
            </div>
          </SignedIn>

          {/* Add Active Users Section */}
          <div className="mt-8 rounded-xl p-4 border border-black/20 bg-black/5">
            <h2 className="text-base font-bold text-slate-700 mb-4">
              {numUsers} {numUsers !== 1 ? 'Users' : 'User'} Online
            </h2>
            <div className="flex flex-wrap gap-2">
              {Array.from(
                new Map(
                  activeUsers
                    .filter(u => u.data.email)
                    .map(user => [user.data.email, user])
                ).values()
              ).map(user => (
                <div
                  key={user.clientId}
                  className="relative group"
                  title={user.data.email}
                >
                  {user.data.imageUrl ? (
                    <img
                      src={user.data.imageUrl}
                      className={`w-10 h-10 rounded-full ${
                        user.data.isHost ? 'ring-2 ring-green-500' : ''
                      }`}
                      alt={user.data.email}
                    />
                  ) : (
                    <div
                      className={`w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center text-lg font-medium ${
                        user.data.isHost ? 'ring-2 ring-green-500' : ''
                      }`}
                    >
                      {user.data.email[0].toUpperCase()}
                    </div>
                  )}
                  <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-black/75 text-white text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
                    {user.data.email}
                    {user.data.isHost && ' (Host)'}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
        {isStreamer ? (
          <>
            <Script src="https://sdk.scdn.co/spotify-player.js" />
            <audio ref={audioRef} />
          </>
        ) : null}
      </div>
      <div className="flex-1 flex flex-col gap-[5px] mt-12">
        {(playerStore.queueItems || []).map(
          (item: Ably.InboundMessage, index: number) => (
            <div
              key={index}
              className={`rounded-[20px] bg-white/20 backdrop-blur-[100px] p-8 flex flex-row gap-4 box-shadow-lg box-shadow-black relative ${
                index === 0 ? 'border-4 border-white' : ''
              }`}
            >
              <div className="rounded-lg w-[100px] h-[100px]">
                <img
                  className="w-full h-full object-fit rounded-lg shadow-2xl"
                  src={
                    item.data.spotifyData?.album?.images?.[0]?.url ||
                    item.data.sunoData?.image_url
                  }
                />
              </div>
              <div className="flex flex-col">
                <h1 className="font-bold text-[36px] text-white">
                  {item.data.spotifyData?.name ||
                    getClipTitle(item.data.sunoData)}
                </h1>
                <h3 className="text-white font-bold">
                  {(item.data.spotifyData?.artists || [])
                    .map((artist: any) => artist.name)
                    .join(', ') || item.data.sunoData?.handle}
                </h3>
                <h3 className="text-white">{item.data.email}</h3>
              </div>
              <div className="flex-1 flex flex-row-reverse text-white text-lg">
                <div className="flex flex-col items-end">
                  {formatTime(
                    (item.data.spotifyData?.duration_ms || 0) / 1000 ||
                      item.data.sunoData?.metadata.duration
                  )}
                  <div className="flex-1 flex flex-col-reverse items-end">
                    {!!item.data.spotifyData ? (
                      <div>
                        <img src="/spotify_white.png" width="30px" />
                      </div>
                    ) : (
                      <div>
                        <a href={item.data.sunoData?.url} target="_blank">
                          <img src="/Logo-1.svg" width="50px" />
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Heart button and liked avatars */}
              <div className="absolute bottom-[30px] right-18 flex flex-row items-center gap-2">
                {/* Liked avatars */}
                <div className="flex flex-row gap-1">
                  {(likedSongs.get(item.data.queueId) || new Set()).size >
                    0 && (
                    <div className="flex flex-row gap-1">
                      {Array.from(
                        likedSongs.get(item.data.queueId) || new Set()
                      )
                        .slice(0, 5) // Limit to 5 avatars to prevent overflow
                        .map(userEmail => {
                          const user = activeUsers.find(
                            u => u.data.email === userEmail
                          );
                          if (!user) return null;

                          return (
                            <div key={user.clientId} className="relative group">
                              {user.data.imageUrl ? (
                                <img
                                  src={user.data.imageUrl}
                                  className="w-6 h-6 rounded-full ring-1 ring-white/50"
                                  alt={user.data.email}
                                />
                              ) : (
                                <div className="w-6 h-6 rounded-full bg-gray-300 flex items-center justify-center text-xs font-medium ring-1 ring-white/50">
                                  {user.data.email[0].toUpperCase()}
                                </div>
                              )}
                              <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-1 px-2 py-1 bg-black/75 text-white text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
                                {user.data.email}
                              </div>
                            </div>
                          );
                        })}
                      {(likedSongs.get(item.data.queueId) || new Set()).size >
                        5 && (
                        <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-xs font-medium ring-1 ring-white/50">
                          +
                          {(likedSongs.get(item.data.queueId) || new Set())
                            .size - 5}
                        </div>
                      )}
                    </div>
                  )}
                </div>

                {/* Heart button */}
                <button
                  onClick={() => handleLike(item.data.queueId)}
                  className={`p-2 rounded-full transition-all duration-200 ${
                    (likedSongs.get(item.data.queueId) || new Set()).has(
                      user?.emailAddresses[0]?.emailAddress || ''
                    )
                      ? 'bg-red-500 text-white'
                      : 'bg-white/20 text-white hover:bg-white/30'
                  }`}
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill={
                      (likedSongs.get(item.data.queueId) || new Set()).has(
                        user?.emailAddresses[0]?.emailAddress || ''
                      )
                        ? 'currentColor'
                        : 'none'
                    }
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
                  </svg>
                </button>
              </div>
            </div>
          )
        )}
        <div className="pb-12"></div>
      </div>
    </div>
  );
});

export default App;
