"use client";
import * as React from 'react';
import { useSensors, useSensor, PointerSensor, DndContext, closestCorners, DragOverlay } from '@dnd-kit/core';
import { arrayMove, useSortable, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { cva } from 'class-variance-authority';
import { Search, User, Calendar, MoreHorizontal, Edit3, X, Plus } from 'lucide-react';
import { cn } from '@hanzo/ui/lib/utils';
import { Badge } from '@hanzo/ui/primitives/badge';
import { Button } from '@hanzo/ui/primitives/button';
import { Card, CardHeader } from '@hanzo/ui/primitives/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@hanzo/ui/primitives/dialog';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@hanzo/ui/primitives/dropdown-menu';
import { Input } from '@hanzo/ui/primitives/input';
import { Label } from '@hanzo/ui/primitives/label';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@hanzo/ui/primitives/select';
import { Textarea } from '@hanzo/ui/primitives/textarea';
import { jsxs, jsx } from 'react/jsx-runtime';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var priorityVariants = cva(
  "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-semibold",
  {
    variants: {
      priority: {
        low: "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/20 dark:text-blue-400",
        medium: "border-yellow-200 bg-yellow-50 text-yellow-700 dark:border-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400",
        high: "border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-800 dark:bg-orange-900/20 dark:text-orange-400",
        urgent: "border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400"
      }
    },
    defaultVariants: {
      priority: "low"
    }
  }
);
function SortableCard({
  card,
  onEdit,
  onDelete
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: card.id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition
  };
  return /* @__PURE__ */ jsx(
    "div",
    {
      ref: setNodeRef,
      style,
      ...attributes,
      ...listeners,
      className: cn(
        "cursor-grab active:cursor-grabbing",
        isDragging && "opacity-50"
      ),
      children: /* @__PURE__ */ jsx(KanbanCardComponent, { card, onEdit, onDelete })
    }
  );
}
__name(SortableCard, "SortableCard");
function KanbanCardComponent({
  card,
  onEdit,
  onDelete
}) {
  return /* @__PURE__ */ jsx(Card, { className: "mb-3 group hover:shadow-md transition-shadow", children: /* @__PURE__ */ jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsx("div", { className: "flex items-start justify-between", children: /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
    /* @__PURE__ */ jsx("h4", { className: "font-medium text-sm leading-tight mb-2 break-words", children: card.title }),
    card.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground line-clamp-2 mb-2", children: card.description }),
    card.labels && card.labels.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1 mb-2", children: card.labels.map((label) => /* @__PURE__ */ jsx(
      Badge,
      {
        variant: "outline",
        className: "text-xs h-5",
        style: {
          backgroundColor: `${label.color}20`,
          borderColor: label.color,
          color: label.color
        },
        children: label.name
      },
      label.id
    )) }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        card.priority && /* @__PURE__ */ jsx(
          "span",
          {
            className: cn(
              priorityVariants({ priority: card.priority })
            ),
            children: card.priority
          }
        ),
        card.assignee && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 text-muted-foreground", children: [
          /* @__PURE__ */ jsx(User, { className: "h-3 w-3" }),
          /* @__PURE__ */ jsx("span", { children: card.assignee })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
        card.dueDate && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 text-muted-foreground", children: [
          /* @__PURE__ */ jsx(Calendar, { className: "h-3 w-3" }),
          /* @__PURE__ */ jsx("span", { children: new Date(card.dueDate).toLocaleDateString() })
        ] }),
        /* @__PURE__ */ jsxs(DropdownMenu, { children: [
          /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "icon",
              className: "h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",
              children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3 w-3" })
            }
          ) }),
          /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
            /* @__PURE__ */ jsxs(DropdownMenuItem, { onClick: () => onEdit(card), children: [
              /* @__PURE__ */ jsx(Edit3, { className: "h-4 w-4 mr-2" }),
              "Edit"
            ] }),
            /* @__PURE__ */ jsxs(
              DropdownMenuItem,
              {
                onClick: () => onDelete(card.id),
                className: "text-destructive",
                children: [
                  /* @__PURE__ */ jsx(X, { className: "h-4 w-4 mr-2" }),
                  "Delete"
                ]
              }
            )
          ] })
        ] })
      ] })
    ] })
  ] }) }) }) });
}
__name(KanbanCardComponent, "KanbanCardComponent");
function KanbanColumnComponent({
  column,
  onAddCard,
  onEditCard,
  onDeleteCard
}) {
  const { setNodeRef } = useSortable({ id: column.id });
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      className: "bg-muted/50 rounded-lg p-4 min-w-[280px] max-w-[280px] flex flex-col",
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm", children: column.title }),
            /* @__PURE__ */ jsxs(Badge, { variant: "secondary", className: "text-xs", children: [
              column.cards.length,
              column.limit && `/${column.limit}`
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "icon",
              className: "h-8 w-8",
              onClick: () => onAddCard(column.id),
              children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" })
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          SortableContext,
          {
            items: column.cards.map((card) => card.id),
            strategy: verticalListSortingStrategy,
            children: /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-[200px]", children: column.cards.map((card) => /* @__PURE__ */ jsx(
              SortableCard,
              {
                card,
                onEdit: onEditCard,
                onDelete: onDeleteCard
              },
              card.id
            )) })
          }
        )
      ]
    }
  );
}
__name(KanbanColumnComponent, "KanbanColumnComponent");
function CardFormDialog({
  open,
  onOpenChange,
  card,
  onSave,
  labels
}) {
  const [formData, setFormData] = React.useState({
    title: card?.title || "",
    description: card?.description || "",
    priority: card?.priority || "low",
    assignee: card?.assignee || "",
    dueDate: card?.dueDate || "",
    labels: card?.labels?.map((l) => l.id) || []
  });
  const handleSubmit = /* @__PURE__ */ __name((e) => {
    e.preventDefault();
    if (!formData.title.trim()) return;
    onSave({
      ...card,
      ...formData,
      labels: labels.filter((l) => formData.labels.includes(l.id)),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    });
    onOpenChange(false);
  }, "handleSubmit");
  React.useEffect(() => {
    if (card) {
      setFormData({
        title: card.title,
        description: card.description || "",
        priority: card.priority || "low",
        assignee: card.assignee || "",
        dueDate: card.dueDate || "",
        labels: card.labels?.map((l) => l.id) || []
      });
    } else {
      setFormData({
        title: "",
        description: "",
        priority: "low",
        assignee: "",
        dueDate: "",
        labels: []
      });
    }
  }, [card]);
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-md", children: [
    /* @__PURE__ */ jsxs(DialogHeader, { children: [
      /* @__PURE__ */ jsx(DialogTitle, { children: card ? "Edit Card" : "Create Card" }),
      /* @__PURE__ */ jsx(DialogDescription, { children: card ? "Update the card details below." : "Create a new card for your kanban board." })
    ] }),
    /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "title", children: "Title *" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "title",
            value: formData.title,
            onChange: (e) => setFormData((prev) => ({ ...prev, title: e.target.value })),
            placeholder: "Enter card title...",
            required: true
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "description", children: "Description" }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            id: "description",
            value: formData.description,
            onChange: (e) => setFormData((prev) => ({
              ...prev,
              description: e.target.value
            })),
            placeholder: "Enter card description...",
            rows: 3
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "priority", children: "Priority" }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: formData.priority,
              onValueChange: (value) => setFormData((prev) => ({ ...prev, priority: value })),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsxs(SelectContent, { children: [
                  /* @__PURE__ */ jsx(SelectItem, { value: "low", children: "Low" }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "medium", children: "Medium" }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "high", children: "High" }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "urgent", children: "Urgent" })
                ] })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "assignee", children: "Assignee" }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "assignee",
              value: formData.assignee,
              onChange: (e) => setFormData((prev) => ({ ...prev, assignee: e.target.value })),
              placeholder: "Assign to..."
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "dueDate", children: "Due Date" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "dueDate",
            type: "date",
            value: formData.dueDate,
            onChange: (e) => setFormData((prev) => ({ ...prev, dueDate: e.target.value }))
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            onClick: () => onOpenChange(false),
            children: "Cancel"
          }
        ),
        /* @__PURE__ */ jsxs(Button, { type: "submit", children: [
          card ? "Update" : "Create",
          " Card"
        ] })
      ] })
    ] })
  ] }) });
}
__name(CardFormDialog, "CardFormDialog");
function KanbanBoard({
  board,
  onUpdateBoard,
  className
}) {
  const [activeCard, setActiveCard] = React.useState(null);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [cardFormOpen, setCardFormOpen] = React.useState(false);
  const [editingCard, setEditingCard] = React.useState(
    void 0
  );
  const [activeColumnId, setActiveColumnId] = React.useState("");
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8
      }
    })
  );
  const filteredBoard = React.useMemo(() => {
    if (!searchQuery.trim()) return board;
    const filtered = {
      ...board,
      columns: board.columns.map((column) => ({
        ...column,
        cards: column.cards.filter(
          (card) => card.title.toLowerCase().includes(searchQuery.toLowerCase()) || card.description?.toLowerCase().includes(searchQuery.toLowerCase()) || card.labels?.some(
            (label) => label.name.toLowerCase().includes(searchQuery.toLowerCase())
          )
        )
      }))
    };
    return filtered;
  }, [board, searchQuery]);
  const handleDragStart = /* @__PURE__ */ __name((event) => {
    const { active } = event;
    const card = board.columns.flatMap((col) => col.cards).find((card2) => card2.id === active.id);
    setActiveCard(card || null);
  }, "handleDragStart");
  const handleDragOver = /* @__PURE__ */ __name((event) => {
    const { active, over } = event;
    if (!over) return;
    const activeId = active.id;
    const overId = over.id;
    const activeContainer = findContainer(activeId);
    const overContainer = findContainer(overId);
    if (!activeContainer || !overContainer || activeContainer === overContainer) {
      return;
    }
    const updatedBoard = { ...board };
    const activeColumnIndex = updatedBoard.columns.findIndex(
      (col) => col.id === activeContainer
    );
    const overColumnIndex = updatedBoard.columns.findIndex(
      (col) => col.id === overContainer
    );
    const activeColumn = updatedBoard.columns[activeColumnIndex];
    const overColumn = updatedBoard.columns[overColumnIndex];
    const activeCardIndex = activeColumn.cards.findIndex(
      (card) => card.id === activeId
    );
    const [movedCard] = activeColumn.cards.splice(activeCardIndex, 1);
    if (overColumn.limit && overColumn.cards.length >= overColumn.limit) {
      return;
    }
    overColumn.cards.push(movedCard);
    onUpdateBoard(updatedBoard);
  }, "handleDragOver");
  const handleDragEnd = /* @__PURE__ */ __name((event) => {
    const { active, over } = event;
    setActiveCard(null);
    if (!over) return;
    const activeId = active.id;
    const overId = over.id;
    const activeContainer = findContainer(activeId);
    const overContainer = findContainer(overId);
    if (!activeContainer || !overContainer) return;
    const activeColumnIndex = board.columns.findIndex(
      (col) => col.id === activeContainer
    );
    const activeColumn = board.columns[activeColumnIndex];
    if (activeContainer === overContainer) {
      const oldIndex = activeColumn.cards.findIndex(
        (card) => card.id === activeId
      );
      const newIndex = activeColumn.cards.findIndex(
        (card) => card.id === overId
      );
      if (oldIndex !== newIndex) {
        const updatedBoard = { ...board };
        updatedBoard.columns[activeColumnIndex].cards = arrayMove(
          activeColumn.cards,
          oldIndex,
          newIndex
        );
        onUpdateBoard(updatedBoard);
      }
    }
  }, "handleDragEnd");
  const findContainer = /* @__PURE__ */ __name((id) => {
    if (board.columns.some((col) => col.id === id)) {
      return id;
    }
    return board.columns.find((col) => col.cards.some((card) => card.id === id))?.id;
  }, "findContainer");
  const handleAddCard = /* @__PURE__ */ __name((columnId) => {
    setActiveColumnId(columnId);
    setEditingCard(void 0);
    setCardFormOpen(true);
  }, "handleAddCard");
  const handleEditCard = /* @__PURE__ */ __name((card) => {
    setEditingCard(card);
    setActiveColumnId("");
    setCardFormOpen(true);
  }, "handleEditCard");
  const handleSaveCard = /* @__PURE__ */ __name((cardData) => {
    const updatedBoard = { ...board };
    if (editingCard) {
      const columnIndex = updatedBoard.columns.findIndex(
        (col) => col.cards.some((card) => card.id === editingCard.id)
      );
      if (columnIndex !== -1) {
        const cardIndex = updatedBoard.columns[columnIndex].cards.findIndex(
          (card) => card.id === editingCard.id
        );
        if (cardIndex !== -1) {
          updatedBoard.columns[columnIndex].cards[cardIndex] = {
            ...editingCard,
            ...cardData
          };
        }
      }
    } else {
      const columnIndex = updatedBoard.columns.findIndex(
        (col) => col.id === activeColumnId
      );
      if (columnIndex !== -1) {
        const newCard = {
          id: `card-${Date.now()}`,
          title: cardData.title,
          description: cardData.description,
          labels: cardData.labels,
          priority: cardData.priority,
          assignee: cardData.assignee,
          dueDate: cardData.dueDate,
          createdAt: (/* @__PURE__ */ new Date()).toISOString(),
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        };
        updatedBoard.columns[columnIndex].cards.push(newCard);
      }
    }
    onUpdateBoard(updatedBoard);
  }, "handleSaveCard");
  const handleDeleteCard = /* @__PURE__ */ __name((cardId) => {
    const updatedBoard = { ...board };
    const columnIndex = updatedBoard.columns.findIndex(
      (col) => col.cards.some((card) => card.id === cardId)
    );
    if (columnIndex !== -1) {
      updatedBoard.columns[columnIndex].cards = updatedBoard.columns[columnIndex].cards.filter((card) => card.id !== cardId);
      onUpdateBoard(updatedBoard);
    }
  }, "handleDeleteCard");
  return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col h-full", className), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-4 border-b", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold", children: board.title }),
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            placeholder: "Search cards...",
            value: searchQuery,
            onChange: (e) => setSearchQuery(e.target.value),
            className: "pl-9 w-64"
          }
        )
      ] }) })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-x-auto", children: /* @__PURE__ */ jsx("div", { className: "h-full p-4", children: /* @__PURE__ */ jsxs(
      DndContext,
      {
        sensors,
        collisionDetection: closestCorners,
        onDragStart: handleDragStart,
        onDragOver: handleDragOver,
        onDragEnd: handleDragEnd,
        children: [
          /* @__PURE__ */ jsx("div", { className: "flex gap-6 h-full pb-4", children: filteredBoard.columns.map((column) => /* @__PURE__ */ jsx(
            KanbanColumnComponent,
            {
              column,
              onAddCard: handleAddCard,
              onEditCard: handleEditCard,
              onDeleteCard: handleDeleteCard
            },
            column.id
          )) }),
          /* @__PURE__ */ jsx(DragOverlay, { children: activeCard ? /* @__PURE__ */ jsx(
            KanbanCardComponent,
            {
              card: activeCard,
              onEdit: () => {
              },
              onDelete: () => {
              }
            }
          ) : null })
        ]
      }
    ) }) }),
    /* @__PURE__ */ jsx(
      CardFormDialog,
      {
        open: cardFormOpen,
        onOpenChange: setCardFormOpen,
        card: editingCard,
        onSave: handleSaveCard,
        labels: board.labels
      }
    )
  ] });
}
__name(KanbanBoard, "KanbanBoard");
var kanban_default = KanbanBoard;

export { kanban_default as KanbanBoard };
