import type { ReactNode, CSSProperties } from 'react'
import { clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'

function cn(...inputs: Parameters<typeof clsx>) {
  return twMerge(clsx(inputs))
}

/* ─── BentoGrid ─────────────────────────────────────────── */
export function BentoGrid({
  children,
  className,
}: {
  children: ReactNode
  className?: string
}) {
  return (
    <div
      className={cn(
        'grid grid-cols-1 md:grid-cols-3',
        className,
      )}
      style={{ gap: 1, background: 'var(--rule-thin)' }}
    >
      {children}
    </div>
  )
}

/* ─── BentoGridItem ──────────────────────────────────────── */
export interface BentoGridItemProps {
  title:       string
  description?: string
  header?:     ReactNode   /* visual block above content */
  icon?:       ReactNode
  tag?:        string
  tagColor?:   string      /* CSS color value */
  accentLine?: boolean     /* left/top colored accent rule */
  className?:  string
  style?:      CSSProperties
  onClick?:    () => void
}

export function BentoGridItem({
  title,
  description,
  header,
  icon,
  tag,
  tagColor = 'var(--red)',
  accentLine = false,
  className,
  style,
  onClick,
}: BentoGridItemProps) {
  return (
    <div
      onClick={onClick}
      className={cn(
        'group relative flex flex-col bg-[var(--paper)] p-8 transition-colors duration-200 hover:bg-[var(--paper-2)]',
        onClick && 'cursor-pointer',
        className,
      )}
      style={style}
    >
      {/* Accent bar */}
      {accentLine && (
        <div
          style={{
            position:  'absolute',
            top:       0,
            right:     0,
            left:      0,
            height:    3,
            background: tagColor,
          }}
        />
      )}

      {/* Optional visual header block */}
      {header && <div className="mb-4">{header}</div>}

      {/* Tag */}
      {tag && (
        <div
          style={{
            fontSize:      9,
            fontWeight:    700,
            letterSpacing: '2.5px',
            textTransform: 'uppercase',
            color:         tagColor,
            marginBottom:  10,
          }}
        >
          {tag}
        </div>
      )}

      {/* Icon + body */}
      <div className="flex flex-col flex-1 gap-2">
        {icon && <div className="mb-1">{icon}</div>}

        <h3
          style={{
            fontSize:      18,
            fontWeight:    700,
            letterSpacing: '-0.4px',
            lineHeight:    1.4,
            color:         'var(--ink)',
          }}
        >
          {title}
        </h3>

        {description && (
          <p
            style={{
              fontSize:   14,
              lineHeight: 1.8,
              color:      'var(--ink-3)',
              fontWeight: 400,
              marginTop:  6,
            }}
          >
            {description}
          </p>
        )}
      </div>
    </div>
  )
}
