"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCommentSidebar = generateCommentSidebar;
const Generator = __importStar(require("@postxl/generator"));
/**
 * Generator function that generates the Comment Sidebar Content component for admin pages.
 * This is a reusable component that fetches comments for a given model,
 * groups them by model entity, builds reply trees, and renders them using CommentList.
 */
function generateCommentSidebar({ context }) {
    const commentModel = context.models.get('Comment');
    const userModel = context.models.get('User');
    const imports = Generator.ImportGenerator
        //
        .from(context.admin.components.commentSidebar.location)
        .addImport({
        from: Generator.toPackageName('react'),
        items: [
            Generator.toFunctionName('useState'),
            Generator.toFunctionName('useMemo'),
            Generator.toFunctionName('useCallback'),
            Generator.toFunctionName('useEffect'),
        ],
    })
        .add(commentModel.itemsHook)
        .add(userModel.itemsHook)
        .addType(commentModel.types.id)
        .addType(userModel.types.id);
    const userLabelField = userModel.labelField.name;
    return `
${imports.generate()}
import { useAuth } from '@context-providers/auth-context-provider'
import { Avatar, AvatarFallback, AvatarImage, Button, CommentCreate, CommentList, Label, Switch } from '@postxl/ui-components'
import type { CommentItem, CommentGroup } from '@postxl/ui-components'

type ModelCommentContentProps = Readonly<{
  model: string
  filteredIds?: string[]
  labelMap?: Record<string, string>
  selectedEntityId?: string
  onCommentCountChange?: (count: number) => void
  singleCommentThread?: boolean
}>

export function ${context.admin.components.commentSidebar.name}({ model, filteredIds, labelMap, selectedEntityId, onCommentCountChange, singleCommentThread }: ModelCommentContentProps) {
  const { viewerData } = useAuth()
  const currentUserId = viewerData?.user?.id
  const [commentTarget, setCommentTarget] = useState<{ entityId: string; label: string } | null>(null)
  const [unresolvedOnly, setUnresolvedOnly] = useState(false)
  const {
    ${commentModel.itemsHook.filteredList.name}: comments,
    ${commentModel.itemsHook.create.name}: createComment,
    ${commentModel.itemsHook.updateField.name}: updateCommentField,
    ${commentModel.itemsHook.isLoaded.name}: commentsLoaded,
  } = ${commentModel.itemsHook.name}({
    filters: {
      model: { values: [model] },
      ...(filteredIds?.length ? { modelId: { values: filteredIds } } : {}),
      ...(unresolvedOnly ? { isResolved: [false] } : {}),
    },
    paginated: false,
  })

  const { ${userModel.itemsHook.map.name}: userMap } = ${userModel.itemsHook.name}()

  const groups = useMemo<CommentGroup[]>(() => {
    if (!comments?.length || !userMap) return []

    function toItem(c: (typeof comments)[number], groupComments: typeof comments): CommentItem {
      const user = userMap.get(c.userId)
      const replies = groupComments.filter(r => r.replyToCommentId === c.id).map(r => toItem(r, groupComments))
      return {
        id: c.id,
        userName: user?.${userLabelField} ?? String(c.userId),
        userAvatar: user?.profilePictureUrl ? (
          <Avatar className="size-full">
            <AvatarImage src={user.profilePictureUrl} />
            <AvatarFallback className="text-sm">{(user.${userLabelField} ?? '?').slice(0, 2).toUpperCase()}</AvatarFallback>
          </Avatar>
        ) : undefined,
        createdAt: c.createdAt ?? new Date(),
        comment: c.comment,
        isResolved: c.isResolved ?? undefined,
        replies: replies.length > 0 ? replies : undefined,
      }
    }

    const grouped = new Map<string, typeof comments>()
    for (const c of comments) {
      if (!grouped.has(c.modelId)) grouped.set(c.modelId, [])
      grouped.get(c.modelId)!.push(c)
    }

    return Array.from(grouped.entries())
      .map(([modelId, items]): CommentGroup => ({
        groupId: modelId,
        groupName: labelMap?.[modelId] ?? modelId,
        comments: items.filter(c => !c.replyToCommentId).map(c => toItem(c, items)),
      }))
      .filter(g => g.comments.length > 0)
      .sort((a, b) => a.groupName.localeCompare(b.groupName))
  }, [comments, userMap, labelMap])

  const commentCount = useMemo(() => groups.reduce((sum, g) => sum + g.comments.length, 0), [groups])

  useEffect(() => {
    onCommentCountChange?.(commentCount)
  }, [commentCount, onCommentCountChange])

  const handleResolve = useCallback((commentId: string, isResolve: boolean) => {
    void updateCommentField({ id: commentId as ${commentModel.types.id.name}, field: 'isResolved', value: isResolve || null })
  }, [updateCommentField])

  const handleReply = useCallback((parentId: string, text: string) => {
    if (!currentUserId) return
    const parentComment = comments?.find(c => c.id === parentId)
    if (!parentComment) return
    void createComment({
      userId: currentUserId as ${userModel.types.id.name},
      model,
      modelId: parentComment.modelId,
      comment: text,
      replyToCommentId: parentId as ${commentModel.types.id.name},
      isResolved: null,
    })
  }, [currentUserId, comments, createComment, model])

  const handleCreate = useCallback((text: string, groupId?: string) => {
    if (!currentUserId || !groupId) return
    void createComment({
      userId: currentUserId as ${userModel.types.id.name},
      model,
      modelId: groupId,
      comment: text,
      replyToCommentId: null,
      isResolved: null,
    })
  }, [currentUserId, createComment, model])

  const handleCreateForTarget = useCallback((text: string) => {
    if (!currentUserId || !commentTarget) return
    void createComment({
      userId: currentUserId as ${userModel.types.id.name},
      model,
      modelId: commentTarget.entityId,
      comment: text,
      replyToCommentId: null,
      isResolved: null,
    })
    setCommentTarget(null)
  }, [currentUserId, createComment, model, commentTarget])

  const selectedLabel = selectedEntityId ? labelMap?.[selectedEntityId] ?? selectedEntityId : undefined
  let commentListOnCreate: ((text: string) => void) | undefined
  if (currentUserId) {
    if (singleCommentThread && groups.length === 1) {
      commentListOnCreate = (text: string) => handleCreate(text, groups[0].groupId)
    } else {
      commentListOnCreate = handleCreate
    }
  }

  if (!commentsLoaded) {
    return (
      <div className="p-4">
        <p className="text-sm text-muted-foreground">Loading comments...</p>
      </div>
    )
  }

  return (
    <div className="p-2">
        {commentTarget ? (
          <div className="mb-3">
            <p className="text-xs text-muted-foreground mb-1">Commenting on {commentTarget.label}</p>
            <CommentCreate
              onSubmit={handleCreateForTarget}
              onCancel={() => setCommentTarget(null)}
            />
          </div>
        ) : (
          <>
            {currentUserId && selectedEntityId && (
              <div className="mb-3">
                <Button
                  variant="outline"
                  size="sm"
                  className="w-full truncate block"
                  onClick={() =>
                    setCommentTarget({ entityId: selectedEntityId, label: selectedLabel ?? selectedEntityId })
                  }
                >
                  Comment on {selectedLabel}
                </Button>
              </div>
            )}
          </>
        )}
        {(groups.length > 0 || unresolvedOnly) && (
          <div className="flex items-center gap-2 mb-3">
            <Switch id="unresolved-only" checked={unresolvedOnly} onCheckedChange={setUnresolvedOnly} />
            <Label htmlFor="unresolved-only" className="text-xs">Unresolved only</Label>
          </div>
        )}
        {groups.length === 0 && !commentTarget && (
          <p className="text-sm text-muted-foreground">
            {unresolvedOnly ? 'No unresolved comments' : selectedEntityId ? 'No comments' : 'Select a row to add a comment'}
          </p>
        )}
        {groups.length > 0 && (
          <CommentList
            comments={singleCommentThread && groups.length === 1 ? groups[0].comments : groups}
            onResolve={handleResolve}
            onReply={currentUserId ? handleReply : undefined}
            onCreate={commentListOnCreate}
          />
        )}
    </div>
  )
}
`;
}
//# sourceMappingURL=comment-sidebar.generator.js.map