"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEditContext, useEditContextRef } from "../client/editContext";
import { useEffect, useState, useCallback, useRef } from "react";
import { Star, Pencil, Check, X, GripVertical, FolderTree, Ban, } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import * as favouritesService from "../services/favouritesService";
import { toast } from "sonner";
import { getAbsoluteIconUrl } from "../utils";
import { localStorageService } from "../services/localStorageService";
import { Input } from "../../components/ui/input";
import { Button } from "../../components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { HomeListBadge, HomeListIcon, homeListContainerClass, homeListRowClass, } from "../ui/HomeListRow";
import { cn } from "../../lib/utils";
export function Favorites({ variant = "sidebar" } = {}) {
    const editContext = useEditContext();
    const editContextRef = useEditContextRef();
    const [favorites, setFavorites] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editingId, setEditingId] = useState(null);
    const [editName, setEditName] = useState("");
    const editInputRef = useRef(null);
    const [draggedIndex, setDraggedIndex] = useState(null);
    const [dragOverIndex, setDragOverIndex] = useState(null);
    const [showPaths, setShowPaths] = useState(() => {
        const saved = localStorageService.getString("favorites.showPaths");
        return saved !== null ? saved === "true" : false;
    });
    if (!editContext)
        return null;
    // Persist showPaths to localStorage when it changes
    useEffect(() => {
        localStorageService.setString("favorites.showPaths", String(showPaths));
    }, [showPaths]);
    const currentItemId = editContext.currentItemDescriptor?.id;
    const currentLanguage = editContext.currentItemDescriptor?.language;
    // Load all favorites with item details
    // Use ref to access itemsRepository to avoid re-running when repository reference changes
    const loadFavorites = useCallback(async () => {
        setLoading(true);
        try {
            const result = await favouritesService.getAllFavorites();
            if (result.type === "success" && result.data) {
                // Sort favorites by priority descending (highest priority first)
                const sortedFavorites = result.data.sort((a, b) => b.priority - a.priority);
                // Load item details for each favorite
                const favoritesWithDetails = [];
                for (const favorite of sortedFavorites) {
                    let item = null;
                    try {
                        const loadedItem = await editContextRef.current?.itemsRepository.getItem({
                            id: favorite.itemId,
                            language: favorite.language,
                            version: 0,
                        });
                        item = loadedItem ?? null;
                    }
                    catch {
                        // Silently ignore item loading errors
                    }
                    favoritesWithDetails.push({ favorite, item });
                }
                setFavorites(favoritesWithDetails);
            }
        }
        catch {
            // Silently ignore loading errors
        }
        finally {
            setLoading(false);
        }
    }, [editContextRef]);
    // Reload when the shared favorites list changes, for example from the titlebar star.
    useEffect(() => {
        loadFavorites();
    }, [loadFavorites, editContext.favorites]);
    // Navigate to favorite item
    const navigateToFavorite = useCallback((favorite) => {
        editContext
            ?.loadItem({
            id: favorite.itemId,
            language: favorite.language,
            version: 0,
        })
            .then(() => {
            editContext.switchWorkspace("editor");
        });
    }, [editContext]);
    // Remove a favorite
    const removeFavorite = useCallback(async (favorite, event) => {
        event.stopPropagation();
        try {
            const result = await favouritesService.toggleFavorite({
                itemId: favorite.itemId,
                language: favorite.language,
                priority: favorite.priority,
            });
            if (result.type === "success" && result.data) {
                toast.success("Removed from favorites");
                loadFavorites();
            }
            else {
                toast.error("Failed to remove favorite");
            }
        }
        catch {
            toast.error("Failed to remove favorite");
        }
    }, [loadFavorites]);
    // Start editing a favorite name
    const startEditing = useCallback((favorite, item, event) => {
        event.stopPropagation();
        setEditName(favorite.name || item?.name || "");
        setEditingId(`${favorite.itemId}-${favorite.language}`);
        requestAnimationFrame(() => {
            editInputRef.current?.focus();
            editInputRef.current?.select();
        });
    }, []);
    // Cancel editing
    const cancelEditing = useCallback(() => {
        setEditingId(null);
        setEditName("");
    }, []);
    // Save edited name
    const saveEditedName = useCallback(async (favorite) => {
        try {
            const result = await favouritesService.updateFavoriteName({
                itemId: favorite.itemId,
                language: favorite.language,
                name: editName.trim() || "",
            });
            if (result.type === "success" && result.data) {
                toast.success("Favorite name updated");
                setEditingId(null);
                setEditName("");
                loadFavorites();
            }
            else {
                toast.error("Failed to update favorite name");
            }
        }
        catch {
            toast.error("Failed to update favorite name");
        }
    }, [editName, loadFavorites]);
    // Handle key press in edit input
    const handleEditKeyDown = useCallback((event, favorite) => {
        if (event.key === "Enter") {
            saveEditedName(favorite);
        }
        else if (event.key === "Escape") {
            cancelEditing();
        }
    }, [saveEditedName, cancelEditing]);
    // Drag and drop handlers for reordering
    const handleDragStart = useCallback((index) => {
        setDraggedIndex(index);
    }, []);
    const handleDragOver = useCallback((e, index) => {
        e.preventDefault();
        setDragOverIndex(index);
    }, []);
    const handleDragEnd = useCallback(() => {
        setDraggedIndex(null);
        setDragOverIndex(null);
    }, []);
    const handleDrop = useCallback(async (e, dropIndex) => {
        e.preventDefault();
        if (draggedIndex === null || draggedIndex === dropIndex) {
            handleDragEnd();
            return;
        }
        // Reorder favorites locally first for immediate UI feedback
        const newFavorites = [...favorites];
        const [draggedItem] = newFavorites.splice(draggedIndex, 1);
        if (!draggedItem) {
            handleDragEnd();
            return;
        }
        newFavorites.splice(dropIndex, 0, draggedItem);
        setFavorites(newFavorites);
        // Note: Backend reordering would require a new API endpoint
        // For now, this is just visual reordering within the session
        handleDragEnd();
    }, [draggedIndex, favorites, handleDragEnd]);
    if (variant === "home") {
        return (_jsx("div", { className: "h-full overflow-auto", children: loading ? (_jsx("div", { className: "text-neutral-grey-50 p-12 text-center text-sm", children: "Loading favorites..." })) : favorites.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center p-12 text-center", children: [_jsx(Star, { className: "text-neutral-grey-50 mb-2 h-8 w-8", strokeWidth: 1.5 }), _jsx("div", { className: "text-neutral-grey-50 text-sm font-medium", children: "No favorites yet" }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 text-xs", children: "Click the star icon to add favorites" })] })) : (_jsx("div", { className: homeListContainerClass, children: favorites.slice(0, 12).map(({ favorite, item }) => {
                    const itemKey = `${favorite.itemId}-${favorite.language}`;
                    const displayName = favorite.name || item?.name || favorite.itemId;
                    const isCurrentItem = favorite.itemId === currentItemId &&
                        favorite.language === currentLanguage;
                    const isDeleted = !item;
                    return (_jsxs("button", { className: cn(homeListRowClass, isDeleted && "cursor-default opacity-60 hover:bg-white", isCurrentItem && !isDeleted && "bg-neutral-grey-5"), onClick: () => !isDeleted && navigateToFavorite(favorite), "data-testid": `favorite-item-${favorite.itemId}`, title: isDeleted ? "This item no longer exists" : item?.path, children: [_jsx(HomeListIcon, { className: cn(isCurrentItem &&
                                    !isDeleted &&
                                    "bg-highlight-10 text-highlight-100"), children: isDeleted ? (_jsx(Ban, { className: "h-4 w-4", strokeWidth: 1.5 })) : item?.icon ? (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: "h-5 w-5 object-contain" })) : (_jsx(Star, { className: "h-4 w-4", strokeWidth: 1.5 })) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: cn("text-neutral-grey-100 truncate text-sm font-medium", isDeleted && "text-neutral-grey-50"), children: displayName }), _jsx("div", { className: cn("text-neutral-grey-50 mt-0.5 truncate text-xs", isDeleted && "text-neutral-grey-50"), children: isDeleted
                                            ? "Item no longer exists"
                                            : item?.path || favorite.language })] }), _jsx(HomeListBadge, { className: cn(isDeleted
                                    ? "bg-neutral-grey-5 text-neutral-grey-50"
                                    : "bg-neutral-grey-5 text-neutral-grey-100"), children: isDeleted ? "Missing" : favorite.language })] }, itemKey));
                }) })) }));
    }
    return (_jsxs("div", { className: "absolute inset-0 flex flex-col", children: [_jsx(SimpleToolbar, { children: _jsx(SimpleIconButton, { selected: showPaths, onClick: () => setShowPaths(!showPaths), icon: _jsx(FolderTree, { className: "h-4 w-4", strokeWidth: 1 }), label: "Show paths", "data-testid": "favorites-show-paths-button" }) }), _jsx("div", { className: "flex flex-1 flex-col overflow-x-hidden overflow-y-auto text-sm", children: loading ? (_jsx("div", { className: "text-neutral-grey-50 p-4 text-center text-xs", children: "Loading favorites..." })) : favorites.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center p-6 text-center", children: [_jsx(Star, { className: "text-neutral-grey-50 mb-2 h-8 w-8", strokeWidth: 1 }), _jsx("div", { className: "text-neutral-grey-50 text-xs font-medium", children: "No favorites yet" }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 text-[11px]", children: "Click the star icon to add favorites" })] })) : (_jsx("div", { className: "py-1", children: favorites.map(({ favorite, item }, index) => {
                        const itemKey = `${favorite.itemId}-${favorite.language}`;
                        const isEditing = editingId === itemKey;
                        const displayName = favorite.name || item?.name || favorite.itemId;
                        const isCurrentItem = favorite.itemId === currentItemId &&
                            favorite.language === currentLanguage;
                        const keyboardShortcut = index < 9 ? `Ctrl+Alt+${index + 1}` : null;
                        const isDragging = draggedIndex === index;
                        const isDragOver = dragOverIndex === index;
                        const isDeleted = !item;
                        if (isEditing) {
                            return (_jsxs("div", { className: "badge-pad bg-neutral-grey-5 flex items-center gap-1.5", onMouseDown: (e) => e.preventDefault(), children: [item?.icon && (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: "h-3.5 w-3.5 shrink-0" })), _jsx(Input, { ref: editInputRef, value: editName, onChange: (e) => setEditName(e.target.value), onKeyDown: (e) => handleEditKeyDown(e, favorite), autoFocus: true, className: "h-6 flex-1 text-xs", placeholder: "Enter custom name..." }), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => saveEditedName(favorite), className: "h-5 w-5 p-0", children: _jsx(Check, { className: "h-3 w-3" }) }), _jsx(Button, { variant: "ghost", size: "sm", onClick: cancelEditing, className: "h-5 w-5 p-0", children: _jsx(X, { className: "h-3 w-3" }) })] }, itemKey));
                        }
                        return (_jsxs("div", { className: cn("group badge-pad flex gap-1.5 transition-colors", showPaths ? "items-start" : "items-center", isDeleted
                                ? "cursor-default opacity-60"
                                : "hover:bg-neutral-grey-5 cursor-pointer", isCurrentItem &&
                                !isDeleted &&
                                "bg-feedback-blue-light hover:bg-feedback-blue-light", isDragging && "opacity-50", isDragOver && "border-feedback-blue border-t-2"), onClick: () => !isDeleted && navigateToFavorite(favorite), draggable: !isDeleted, onDragStart: () => !isDeleted && handleDragStart(index), onDragOver: (e) => handleDragOver(e, index), onDragEnd: handleDragEnd, onDrop: (e) => handleDrop(e, index), "data-testid": `favorite-item-${favorite.itemId}`, title: isDeleted ? "This item no longer exists" : undefined, children: [_jsx("div", { className: cn("text-neutral-grey-50 transition-opacity", isDeleted
                                        ? "opacity-30"
                                        : "cursor-grab opacity-0 group-hover:opacity-100", showPaths && "mt-0.5"), children: _jsx(GripVertical, { className: "h-3 w-3" }) }), isDeleted ? (_jsx(Ban, { className: cn("text-neutral-grey-50 h-3.5 w-3.5 shrink-0", showPaths && "mt-0.5"), strokeWidth: 1 })) : item?.icon ? (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: cn("h-3.5 w-3.5 shrink-0", showPaths && "mt-0.5") })) : (_jsx(Star, { className: cn("h-3.5 w-3.5 shrink-0", showPaths && "mt-0.5", isCurrentItem
                                        ? "fill-feedback-blue text-feedback-blue"
                                        : "text-neutral-grey-50"), strokeWidth: 1 })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { className: cn("truncate text-xs", isDeleted
                                                ? "text-neutral-grey-50"
                                                : isCurrentItem
                                                    ? "text-feedback-blue font-medium"
                                                    : "text-neutral-grey-100"), children: displayName }), showPaths && (_jsx("span", { className: cn("truncate text-[10px]", isDeleted
                                                ? "text-neutral-grey-50"
                                                : "text-neutral-grey-50"), children: isDeleted
                                                ? "Item no longer exists"
                                                : item?.path || favorite.language }))] }), keyboardShortcut && !isDeleted && (_jsx("kbd", { className: cn("bg-neutral-grey-5 text-neutral-grey-50 pointer-events-none hidden shrink-0 rounded border px-1 font-mono text-[8px] select-none group-hover:inline", showPaths && "mt-0.5"), children: index + 1 })), _jsxs("div", { className: cn("flex shrink-0 items-center opacity-0 transition-opacity group-hover:opacity-100", showPaths && "mt-0.5"), children: [!isDeleted && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => startEditing(favorite, item, e), className: "h-5 w-5 p-0", children: _jsx(Pencil, { className: "h-2.5 w-2.5" }) }) }), _jsx(TooltipContent, { children: "Edit name" })] })), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => removeFavorite(favorite, e), className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 h-5 w-5 p-0", children: _jsx(DeleteIcon, { size: "xs" }) }) }), _jsx(TooltipContent, { children: "Remove from favorites" })] })] })] }, itemKey));
                    }) })) })] }));
}
//# sourceMappingURL=Favorites.js.map