"use client";

import React from "react";
import { cn } from "@/lib/utils";
import { TrialOption } from "@/components/ui/TrialOption";
import type { TrialOptionProps } from "@/components/ui/TrialOption";

export type TrialOptionsItem = (Omit<TrialOptionProps, "children"> & { id: string });

export interface TrialOptionsGridProps extends React.ComponentProps<"div"> {
  items: TrialOptionsItem[];
  /** Fallback click handler if item doesn't provide onClick */
  onItemClick?: (id: string) => void;
  /** Extra class applied to each option wrapper */
  itemClassName?: string;
}

/**
 * TrialOptionsGrid — lays out TrialOption components in two columns with 12px gap.
 * - 1 item → full width
 * - 2 items → two columns
 * - Odd count (>=3) → last item spans full width
 * - Even count → pairs in two columns
 */
export function TrialOptionsGrid({
  className,
  items,
  onItemClick,
  itemClassName,
  ...props
}: TrialOptionsGridProps) {
  const count = items.length;

  return (
    <div
      {...props}
      className={cn(
        // 2-column grid, 12px gap
        "grid grid-cols-2 gap-3 w-full",
        className
      )}
    >
      {items.map((item, index) => {
        const isLast = index === count - 1;
        const shouldSpanFull =
          count === 1 || (count % 2 !== 0 && isLast);

        return (
          <div
            key={item.id}
            className={cn(shouldSpanFull ? "col-span-2" : "col-span-1", itemClassName)}
            style={shouldSpanFull ? { gridColumn: "1 / -1" } : undefined}
          >
            <TrialOption
              {...item}
              onClick={(e) => {
                item.onClick?.(e);
                if (!item.onClick && onItemClick) onItemClick(item.id);
              }}
              className={cn("w-full", item.className)}
            />
          </div>
        );
      })}
    </div>
  );
}
