"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useEffect } from "react";
import { AlertCircle, Clock, Cloud, Globe, Bot, CircleDot, GitBranch, MessageSquare, User, Users, } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "../../components/ui/tooltip";
import { cn } from "../../lib/utils";
import { useEditContext } from "../client/editContext";
import { useGutterContextSafe } from "./GutterContext";
/**
 * Map from backend icon name to Lucide icon component.
 */
const iconMap = {
    "alert-circle": AlertCircle,
    clock: Clock,
    cloud: Cloud,
    globe: Globe,
    bot: Bot,
    "git-branch": GitBranch,
    "message-square": MessageSquare,
    user: User,
    users: Users,
};
function getIconComponent(iconName) {
    return iconMap[iconName] || CircleDot;
}
/**
 * Severity to color class mapping.
 */
const severityColors = {
    error: "text-red-500",
    warning: "text-amber-500",
    info: "text-blue-500",
    success: "text-green-500",
    neutral: "text-muted-foreground",
};
/** Width of each gutter column in pixels */
const GUTTER_COLUMN_WIDTH = 18;
/** Indentation per tree level in pixels */
const TREE_INDENT_PX = 24;
/**
 * Renders the gutter column area for a single node.
 * Uses absolute positioning to keep gutters in a fixed column on the left.
 */
export function GutterColumns({ itemId, itemLanguage, depth = 0, className, }) {
    const gutterContext = useGutterContextSafe();
    // Extract stable function reference to avoid re-running effect
    const registerVisibleNode = gutterContext?.registerVisibleNode;
    // Always register this node as visible (even if no gutters shown yet)
    // This allows us to fetch provider metadata
    useEffect(() => {
        if (registerVisibleNode && itemId) {
            registerVisibleNode(itemId);
        }
    }, [registerVisibleNode, itemId]);
    // Extract values with stable fallbacks BEFORE any hooks to ensure
    // hooks are always called in the same order (React rules of hooks)
    const visibleGutters = gutterContext?.visibleGutters ?? [];
    const providers = gutterContext?.providers ?? [];
    const getIndicator = gutterContext?.getIndicator;
    const showBadges = gutterContext?.showBadges ?? false;
    // Get providers in priority order, filtered by visible gutters
    // This hook MUST be called before any conditional returns
    const visibleProviders = useMemo(() => {
        return providers
            .filter((p) => visibleGutters.includes(p.id))
            .sort((a, b) => a.priority - b.priority);
    }, [providers, visibleGutters]);
    // If no gutter context, don't render anything
    if (!gutterContext) {
        return null;
    }
    // If no visible gutters, don't render (but we already registered the node above)
    if (visibleGutters.length === 0) {
        return null;
    }
    // Calculate the width needed for gutter columns
    const gutterWidth = visibleGutters.length * GUTTER_COLUMN_WIDTH;
    // Calculate the tree padding (same formula as MainContentTreeInner)
    const treePadding = visibleGutters.length * GUTTER_COLUMN_WIDTH + 8;
    // Calculate absolute left position relative to the node row
    // Need to offset by tree padding + depth indentation to reach position 0
    const leftPosition = -(treePadding + depth * TREE_INDENT_PX);
    // If no visible providers yet, render placeholder columns
    if (visibleProviders.length === 0) {
        return (_jsx("div", { className: cn("absolute top-0 bottom-0 flex items-center gap-0.5 border-r border-gray-200 pr-1", className), style: { left: leftPosition, width: gutterWidth }, children: visibleGutters.map((id) => (_jsx("div", { className: "h-4 w-4 flex-shrink-0" }, id))) }));
    }
    return (_jsx("div", { className: cn("absolute top-0 bottom-0 flex items-center gap-0.5 border-r border-gray-200 pr-1", className), style: { left: leftPosition, width: gutterWidth }, children: visibleProviders.map((provider) => (_jsx(GutterCell, { provider: provider, itemId: itemId, itemLanguage: itemLanguage, indicator: getIndicator?.(itemId, provider.id), showBadges: showBadges }, provider.id))) }));
}
/**
 * Severity to badge background color mapping.
 */
const severityBadgeColors = {
    error: "bg-red-500",
    warning: "bg-amber-500",
    info: "bg-blue-500",
    success: "bg-green-500",
    neutral: "bg-gray-400",
};
/**
 * Badge component for displaying counts on icons.
 */
function IndicatorBadge({ count, severity, }) {
    // Format count: show "9+" for numbers > 9
    const displayCount = count > 9 ? "9+" : count.toString();
    const bgColor = severityBadgeColors[severity] || "bg-gray-400";
    return (_jsx("span", { className: cn("absolute -top-1 -right-1 flex h-3 min-w-3 items-center justify-center rounded-full px-0.5 text-[8px] leading-none font-bold text-white", bgColor), children: displayCount }));
}
/**
 * A single cell in the gutter, showing one indicator.
 */
function GutterCell({ provider, itemId, itemLanguage, indicator, showBadges, }) {
    const editContext = useEditContext();
    // If no indicator data, render empty placeholder
    if (!indicator || !indicator.severity) {
        return _jsx("div", { className: "h-4 w-4 flex-shrink-0" });
    }
    const iconName = indicator.customIcon || provider.icon;
    const IconComponent = getIconComponent(iconName);
    const colorClass = severityColors[indicator.severity] || "text-muted-foreground";
    const showBadge = showBadges && indicator.count !== undefined && indicator.count > 0;
    const actionContext = {
        provider,
        indicator,
        itemId,
        itemLanguage,
    };
    const action = editContext?.configuration?.editor?.contentTree?.indicatorActions?.[provider.id];
    const isClickable = !!editContext &&
        !!action &&
        (action.isEnabled ? action.isEnabled(editContext, actionContext) : true);
    const ariaLabel = typeof action?.ariaLabel === "function"
        ? action.ariaLabel(actionContext)
        : action?.ariaLabel || `Open ${provider.label}`;
    const iconContent = (_jsxs(_Fragment, { children: [_jsx(IconComponent, { className: cn("h-3.5 w-3.5", colorClass) }), showBadge && (_jsx(IndicatorBadge, { count: indicator.count, severity: indicator.severity }))] }));
    const icon = isClickable ? (_jsx("button", { type: "button", className: "relative flex h-4 w-4 flex-shrink-0 cursor-pointer items-center justify-center rounded-sm", "data-testid": `tree-indicator-icon-${provider.id}`, "aria-label": ariaLabel, onMouseDown: (event) => event.stopPropagation(), onClick: (event) => {
            event.stopPropagation();
            if (!editContext || !action)
                return;
            void action.onClick(editContext, actionContext);
        }, children: iconContent })) : (_jsx("div", { className: "relative flex h-4 w-4 flex-shrink-0 items-center justify-center", "data-testid": `tree-indicator-icon-${provider.id}`, children: iconContent }));
    // If no tooltip, just render the icon
    if (!indicator.tooltip) {
        return icon;
    }
    // With tooltip
    return (_jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: icon }), _jsx(TooltipContent, { side: "right", className: "max-w-xs", children: _jsx("p", { className: "text-xs", "data-testid": `tree-indicator-tooltip-${provider.id}`, children: indicator.tooltip }) })] }) }));
}
export default GutterColumns;
//# sourceMappingURL=GutterColumns.js.map