"use client"

import { Children, type ReactNode } from "react"
import { cn } from "@/lib/utils"

function MasonryStack({ children }: { children: ReactNode }) {
  return (
    <div className="flex min-w-0 flex-1 flex-col gap-4 lg:gap-5">{children}</div>
  )
}

export function AutomationTabMasonry({
  columns,
  children,
  className,
}: {
  columns: 1 | 2
  children: ReactNode
  className?: string
}) {
  const items = Children.toArray(children).filter(Boolean)

  if (columns === 1) {
    return (
      <div className={cn("flex w-full flex-col gap-4", className)}>{children}</div>
    )
  }

  const left = items.filter((_, index) => index % 2 === 0)
  const right = items.filter((_, index) => index % 2 === 1)

  return (
    <div className={cn("w-full", className)}>
      <div className="flex flex-col gap-4 lg:hidden">
        {items.map((child, index) => (
          <div key={index} className="min-w-0">
            {child}
          </div>
        ))}
      </div>

      <div className="hidden items-start gap-5 lg:flex">
        <MasonryStack>
          {left.map((child, index) => (
            <div key={index} className="min-w-0">
              {child}
            </div>
          ))}
        </MasonryStack>
        <MasonryStack>
          {right.map((child, index) => (
            <div key={index} className="min-w-0">
              {child}
            </div>
          ))}
        </MasonryStack>
      </div>
    </div>
  )
}
