"use client"; import { useCallback, useEffect, useState } from "react"; import { UpgradeProLink } from "./UpgradeProLink"; type Playlist = { id: string; title: string; itemCount: number; }; type Props = { value: string; onChange: (playlistId: string) => void; enabled: boolean; }; export function PlaylistSelect({ value, onChange, enabled }: Props) { const [playlists, setPlaylists] = useState([]); const [loading, setLoading] = useState(false); const [creating, setCreating] = useState(false); const [error, setError] = useState(null); const [showCreate, setShowCreate] = useState(false); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [privacy, setPrivacy] = useState<"public" | "unlisted" | "private">("private"); const loadPlaylists = useCallback(async () => { setLoading(true); setError(null); try { const res = await fetch("/api/youtube/playlists"); const data = await res.json(); if (!res.ok) throw new Error(data.error || "Failed to load playlists"); setPlaylists(data.playlists ?? []); } catch (err) { setError(err instanceof Error ? err.message : "Failed to load playlists"); } finally { setLoading(false); } }, []); useEffect(() => { if (!enabled) return; void loadPlaylists(); }, [enabled, loadPlaylists]); async function handleCreate() { if (!title.trim()) { setError("Playlist title is required"); return; } setCreating(true); setError(null); try { const res = await fetch("/api/youtube/playlists", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: title.trim(), description: description.trim() || undefined, privacy, }), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || "Failed to create playlist"); const playlist = data.playlist as Playlist; setPlaylists((prev) => [playlist, ...prev]); onChange(playlist.id); setShowCreate(false); setTitle(""); setDescription(""); setPrivacy("private"); } catch (err) { setError(err instanceof Error ? err.message : "Failed to create playlist"); } finally { setCreating(false); } } if (!enabled) { return (

Add uploaded videos to a YouTube playlist with{" "} .

); } return (
{showCreate && (
setTitle(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void handleCreate(); } }} className="input-field w-full" placeholder="My Songs2YT uploads" />
setDescription(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void handleCreate(); } }} className="input-field w-full" />
)} {loading &&

Loading playlists…

} {error &&

{error}

} {!loading && !error && playlists.length === 0 && !showCreate && (

No playlists yet. Create one above. If playlist access was just added, sign out and sign in again to grant the new Google permission.

)}
); }