"use client"

import { useState } from "react"
import { Copy } from "lucide-react"

interface ColorSwatchProps {
  color: string
  name: string
  variable: string
  showCopy?: boolean
}

export function ColorSwatch({ color, name, variable, showCopy = true }: ColorSwatchProps) {
  const [copied, setCopied] = useState(false)

  // Function to determine if a color is light or dark
  const isLightColor = (hexColor: string) => {
    // Remove the hash if it exists
    const hex = hexColor.replace("#", "")

    // Convert hex to RGB
    const r = Number.parseInt(hex.substr(0, 2), 16)
    const g = Number.parseInt(hex.substr(2, 2), 16)
    const b = Number.parseInt(hex.substr(4, 2), 16)

    // Calculate brightness (perceived)
    const brightness = (r * 299 + g * 587 + b * 114) / 1000

    // Return true if the color is light, false if it's dark
    return brightness > 128
  }

  const copyToClipboard = () => {
    if (!showCopy) return

    navigator.clipboard.writeText(variable)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  // Determine text color based on background color
  const textColor = isLightColor(color) ? "text-gray-900" : "text-white"

  return (
    <div
      className={`relative rounded-md p-3 flex flex-col justify-between h-20 ${textColor} cursor-pointer group`}
      style={{ backgroundColor: color }}
      onClick={copyToClipboard}
    >
      <div className="flex justify-between items-start">
        <span className="font-medium">{name}</span>
        {showCopy && (
          <Copy
            className={`h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity ${textColor} drop-shadow-sm`}
          />
        )}
      </div>
      <div className="text-xs opacity-80">{variable}</div>

      {copied && (
        <div className="absolute inset-0 flex items-center justify-center rounded-md">
          <span className="bg-black/80 text-white text-xs px-2 py-1 rounded drop-shadow-lg">Copied!</span>
        </div>
      )}
    </div>
  )
}
