{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tic-tac-toe-game",
  "title": "Tic Tac Toe Game",
  "description": "A playable Tic Tac Toe board with a built-in AI opponent, animated piece placement, a drawn winning-line reveal, score tracking, and a confetti burst on a win.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/tic-tac-toe-game/tic-tac-toe-game.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\ntype Cell = \"EMPTY\" | \"CIRCLE\" | \"CROSS\";\nexport type TicTacToeDifficulty = \"easy\" | \"medium\" | \"hard\";\nexport type TicTacToeTrigger = \"manual\" | \"delay\" | \"scroll\";\nexport type TicTacToeWidgetPosition = \"bottom-right\" | \"bottom-left\";\n\nconst LINES = [\n  [0, 1, 2],\n  [3, 4, 5],\n  [6, 7, 8],\n  [0, 3, 6],\n  [1, 4, 7],\n  [2, 5, 8],\n  [0, 4, 8],\n  [2, 4, 6],\n];\n\nconst LINE_COORDS: Record<string, { x1: number; y1: number; x2: number; y2: number }> = {\n  \"0,1,2\": { x1: 15, y1: 55, x2: 315, y2: 55 },\n  \"3,4,5\": { x1: 15, y1: 165, x2: 315, y2: 165 },\n  \"6,7,8\": { x1: 15, y1: 275, x2: 315, y2: 275 },\n  \"0,3,6\": { x1: 55, y1: 15, x2: 55, y2: 315 },\n  \"1,4,7\": { x1: 165, y1: 15, x2: 165, y2: 315 },\n  \"2,5,8\": { x1: 275, y1: 15, x2: 275, y2: 315 },\n  \"0,4,8\": { x1: 20, y1: 20, x2: 310, y2: 310 },\n  \"2,4,6\": { x1: 310, y1: 20, x2: 20, y2: 310 },\n};\n\nfunction checkWinner(board: Cell[]): { winner: Cell | \"tie\" | null; line: number[] | null } {\n  for (const line of LINES) {\n    const [a, b, c] = line;\n    if (board[a] !== \"EMPTY\" && board[a] === board[b] && board[a] === board[c]) {\n      return { winner: board[a], line };\n    }\n  }\n  if (board.every((p) => p !== \"EMPTY\")) return { winner: \"tie\", line: null };\n  return { winner: null, line: null };\n}\n\n// Perfect play for the \"hard\" AI: scores a position by playing every line out (+1 Cross wins,\n// -1 Circle wins, 0 tie). The board has at most 9 cells, so the full search stays instant.\nfunction minimax(board: Cell[], turn: Cell): number {\n  const { winner } = checkWinner(board);\n  if (winner === \"CROSS\") return 1;\n  if (winner === \"CIRCLE\") return -1;\n  if (winner === \"tie\") return 0;\n  let best = turn === \"CROSS\" ? -Infinity : Infinity;\n  board.forEach((v, i) => {\n    if (v !== \"EMPTY\") return;\n    const next = [...board];\n    next[i] = turn;\n    const score = minimax(next, turn === \"CROSS\" ? \"CIRCLE\" : \"CROSS\");\n    best = turn === \"CROSS\" ? Math.max(best, score) : Math.min(best, score);\n  });\n  return best;\n}\n\n// The \"hard\" AI never loses: it picks (at random, for variety) among the moves with the best minimax score.\nfunction bestHardMove(board: Cell[]): number {\n  let bestScore = -Infinity;\n  let bestMoves: number[] = [];\n  board.forEach((v, i) => {\n    if (v !== \"EMPTY\") return;\n    const next = [...board];\n    next[i] = \"CROSS\";\n    const score = minimax(next, \"CIRCLE\");\n    if (score > bestScore) {\n      bestScore = score;\n      bestMoves = [i];\n    } else if (score === bestScore) bestMoves.push(i);\n  });\n  return bestMoves[Math.floor(Math.random() * bestMoves.length)];\n}\n\nfunction Square({ value, onClick, circleColor, crossColor, squareColor, disabled }: { value: Cell; onClick: () => void; circleColor: string; crossColor: string; squareColor: string; disabled: boolean }) {\n  return (\n    <motion.div\n      className=\"flex cursor-pointer items-center justify-center rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.06)]\"\n      style={{ backgroundColor: squareColor }}\n      onClick={onClick}\n      whileHover={!disabled && value === \"EMPTY\" ? { scale: 1.04, backgroundColor: \"#f8f8f8\" } : {}}\n      whileTap={!disabled && value === \"EMPTY\" ? { scale: 0.96 } : {}}\n    >\n      <AnimatePresence>\n        {value === \"CIRCLE\" && (\n          <motion.svg key=\"circle\" width=\"80\" height=\"80\" viewBox=\"-50 -50 100 100\" initial={{ scale: 0, opacity: 0, rotate: -90 }} animate={{ scale: 1, opacity: 1, rotate: 0 }} exit={{ scale: 0, opacity: 0 }} transition={{ type: \"spring\", stiffness: 260, damping: 20 }}>\n            <circle cx=\"0\" cy=\"0\" r=\"36\" fill=\"none\" stroke={circleColor} strokeWidth=\"12\" strokeLinecap=\"round\" />\n          </motion.svg>\n        )}\n        {value === \"CROSS\" && (\n          <motion.svg key=\"cross\" width=\"80\" height=\"80\" viewBox=\"-50 -50 100 100\" initial={{ scale: 0, opacity: 0, rotate: 90 }} animate={{ scale: 1, opacity: 1, rotate: 0 }} exit={{ scale: 0, opacity: 0 }} transition={{ type: \"spring\", stiffness: 260, damping: 20 }}>\n            <line x1=\"-32\" y1=\"-32\" x2=\"32\" y2=\"32\" stroke={crossColor} strokeWidth=\"12\" strokeLinecap=\"round\" />\n            <line x1=\"-32\" y1=\"32\" x2=\"32\" y2=\"-32\" stroke={crossColor} strokeWidth=\"12\" strokeLinecap=\"round\" />\n          </motion.svg>\n        )}\n      </AnimatePresence>\n    </motion.div>\n  );\n}\n\nfunction Confetti({ colors }: { colors: string[] }) {\n  const particles = React.useMemo(\n    () =>\n      Array.from({ length: 60 }).map((_, i) => ({\n        id: i,\n        x: Math.random() * 100,\n        delay: Math.random() * 0.6,\n        duration: 1.8 + Math.random() * 1.4,\n        color: colors[Math.floor(Math.random() * colors.length)],\n        size: 6 + Math.random() * 10,\n        rotate: Math.random() * 360,\n      })),\n    [colors],\n  );\n\n  return (\n    <div className=\"pointer-events-none absolute inset-0 z-50 overflow-hidden\">\n      {particles.map((p) => (\n        <motion.div\n          key={p.id}\n          className=\"absolute rounded-[2px]\"\n          style={{ left: `${p.x}%`, top: -20, width: p.size, height: p.size * 0.6, backgroundColor: p.color }}\n          initial={{ y: 0, opacity: 1, rotate: 0 }}\n          animate={{ y: 700, opacity: [1, 1, 0], rotate: p.rotate + 720, x: (Math.random() - 0.5) * 200 }}\n          transition={{ duration: p.duration, delay: p.delay, ease: \"easeOut\" }}\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction WidgetGlyph() {\n  return (\n    <span className=\"text-[13px] font-extrabold tracking-wider text-white\" aria-hidden=\"true\">\n      ✕○\n    </span>\n  );\n}\n\nexport interface TicTacToeGameProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  circleColor?: string;\n  crossColor?: string;\n  boardColor?: string;\n  squareColor?: string;\n  enableAI?: boolean;\n  aiDifficulty?: TicTacToeDifficulty;\n  asPopup?: boolean;\n  trigger?: TicTacToeTrigger;\n  delaySeconds?: number;\n  widgetPosition?: TicTacToeWidgetPosition;\n  widgetIcon?: string;\n  title?: string;\n}\n\nexport function TicTacToeGame({\n  circleColor = \"#FF665C\",\n  crossColor = \"#EC0B8E\",\n  boardColor = \"#e0e0e0\",\n  squareColor = \"#ffffff\",\n  enableAI = true,\n  aiDifficulty = \"medium\",\n  asPopup = false,\n  trigger = \"manual\",\n  delaySeconds = 4,\n  widgetPosition = \"bottom-right\",\n  widgetIcon,\n  title = \"Tic Tac Toe\",\n  className,\n  style,\n  ...props\n}: TicTacToeGameProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const popupCardRef = React.useRef<HTMLDivElement>(null);\n  const widgetTriggerRef = React.useRef<HTMLButtonElement>(null);\n  const delayTimerRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const wasPopupOpenRef = React.useRef(false);\n\n  const [positions, setPositions] = React.useState<Cell[]>(Array(9).fill(\"EMPTY\"));\n  const [player, setPlayer] = React.useState<Cell>(\"CIRCLE\");\n  const [winner, setWinner] = React.useState<Cell | \"tie\" | null>(null);\n  const [winningLine, setWinningLine] = React.useState<number[] | null>(null);\n  const [scores, setScores] = React.useState({ circle: 0, cross: 0, ties: 0 });\n  const [showConfetti, setShowConfetti] = React.useState(false);\n  const [isAiThinking, setIsAiThinking] = React.useState(false);\n  const [popupOpen, setPopupOpen] = React.useState(!asPopup);\n  const [scrollTriggered, setScrollTriggered] = React.useState(false);\n  const [prevAsPopup, setPrevAsPopup] = React.useState(asPopup);\n\n  if (asPopup !== prevAsPopup) {\n    setPrevAsPopup(asPopup);\n    setPopupOpen(!asPopup);\n  }\n\n  const widgetOnRight = widgetPosition !== \"bottom-left\";\n\n  const getAiMove = (board: Cell[]) => {\n    const empty = board.map((v, i) => (v === \"EMPTY\" ? i : null)).filter((v): v is number => v !== null);\n    for (const i of empty) {\n      const test = [...board];\n      test[i] = \"CROSS\";\n      if (checkWinner(test).winner === \"CROSS\") return i;\n    }\n    if (aiDifficulty === \"hard\") return bestHardMove(board);\n    for (const i of empty) {\n      const test = [...board];\n      test[i] = \"CIRCLE\";\n      if (checkWinner(test).winner === \"CIRCLE\") return i;\n    }\n    if (board[4] === \"EMPTY\") return 4;\n    const corners = [0, 2, 6, 8].filter((i) => board[i] === \"EMPTY\");\n    if (corners.length && aiDifficulty !== \"easy\") return corners[Math.floor(Math.random() * corners.length)];\n    return empty[Math.floor(Math.random() * empty.length)];\n  };\n\n  const handleWin = (result: { winner: Cell | \"tie\" | null; line: number[] | null }) => {\n    setWinner(result.winner);\n    setWinningLine(result.line);\n    setShowConfetti(true);\n    setScores((prev) => {\n      if (result.winner === \"CIRCLE\") return { ...prev, circle: prev.circle + 1 };\n      if (result.winner === \"CROSS\") return { ...prev, cross: prev.cross + 1 };\n      return { ...prev, ties: prev.ties + 1 };\n    });\n    setTimeout(() => setShowConfetti(false), 3500);\n  };\n\n  const takeTurn = (pos: number) => {\n    if (positions[pos] !== \"EMPTY\" || winner || isAiThinking) return;\n    const newPositions = [...positions];\n    newPositions[pos] = player;\n    setPositions(newPositions);\n\n    const result = checkWinner(newPositions);\n    if (result.winner) {\n      handleWin(result);\n      return;\n    }\n\n    const nextPlayer: Cell = player === \"CIRCLE\" ? \"CROSS\" : \"CIRCLE\";\n    setPlayer(nextPlayer);\n\n    if (enableAI && nextPlayer === \"CROSS\") {\n      setIsAiThinking(true);\n      setTimeout(() => {\n        const aiPos = getAiMove(newPositions);\n        if (aiPos !== undefined) {\n          const aiBoard = [...newPositions];\n          aiBoard[aiPos] = \"CROSS\";\n          setPositions(aiBoard);\n          const aiResult = checkWinner(aiBoard);\n          if (aiResult.winner) handleWin(aiResult);\n          else setPlayer(\"CIRCLE\");\n        }\n        setIsAiThinking(false);\n      }, 450);\n    }\n  };\n\n  const reset = () => {\n    setPositions(Array(9).fill(\"EMPTY\"));\n    setPlayer(\"CIRCLE\");\n    setWinner(null);\n    setWinningLine(null);\n    setShowConfetti(false);\n    setIsAiThinking(false);\n  };\n\n  React.useEffect(() => () => clearTimeout(delayTimerRef.current), []);\n\n  React.useEffect(() => {\n    if (!asPopup || trigger !== \"delay\") return;\n    clearTimeout(delayTimerRef.current);\n    delayTimerRef.current = setTimeout(() => setPopupOpen(true), delaySeconds * 1000);\n    return () => clearTimeout(delayTimerRef.current);\n  }, [asPopup, trigger, delaySeconds]);\n\n  React.useEffect(() => {\n    if (!asPopup || trigger !== \"scroll\" || !rootRef.current) return;\n    const el = rootRef.current;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting && !scrollTriggered) {\n          setScrollTriggered(true);\n          setPopupOpen(true);\n        }\n      },\n      { threshold: 0.4 },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [asPopup, trigger, scrollTriggered]);\n\n  React.useEffect(() => {\n    if (!asPopup) return;\n    if (popupOpen) popupCardRef.current?.focus();\n    else if (wasPopupOpenRef.current) widgetTriggerRef.current?.focus();\n    wasPopupOpenRef.current = popupOpen;\n  }, [asPopup, popupOpen]);\n\n  const lineCoords = winningLine ? LINE_COORDS[winningLine.join(\",\")] : null;\n\n  const gameCard = (\n    <div\n      className=\"relative box-border flex w-full flex-col items-center justify-center overflow-hidden rounded-[24px] p-5\"\n      style={{ background: \"linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%)\", fontFamily: \"'Montserrat', system-ui, sans-serif\" }}\n    >\n      <div className=\"mb-3 flex items-center gap-7\">\n        <div className=\"flex flex-col items-center gap-0.5\" style={{ color: circleColor }}>\n          <span className=\"text-[13px] opacity-70\">CIRCLE</span>\n          <span className=\"text-[28px] font-black\">{scores.circle}</span>\n        </div>\n        <div className=\"flex flex-col items-center gap-0.5\">\n          <span className=\"text-[13px] opacity-50\">TIE</span>\n          <span className=\"text-xl font-bold\">{scores.ties}</span>\n        </div>\n        <div className=\"flex flex-col items-center gap-0.5\" style={{ color: crossColor }}>\n          <span className=\"text-[13px] opacity-70\">CROSS</span>\n          <span className=\"text-[28px] font-black\">{scores.cross}</span>\n        </div>\n      </div>\n\n      <div className=\"mb-4.5 h-6 text-base font-semibold text-[#333]\">\n        {winner ? (\n          <motion.span initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}>\n            {winner === \"tie\" ? \"It's a tie!\" : winner === \"CIRCLE\" ? \"Circle wins!\" : \"Cross wins!\"}\n          </motion.span>\n        ) : isAiThinking ? (\n          <span className=\"opacity-60\">AI is thinking...</span>\n        ) : (\n          <span>\n            Turn: <span className=\"font-black\" style={{ color: player === \"CIRCLE\" ? circleColor : crossColor }}>{player === \"CIRCLE\" ? \"Circle\" : \"Cross\"}</span>\n          </span>\n        )}\n      </div>\n\n      <div className=\"relative grid grid-cols-3 grid-rows-3 gap-2.5 rounded-[16px] p-2.5\" style={{ backgroundColor: boardColor, width: 330, height: 330 }}>\n        {positions.map((value, i) => (\n          <Square key={i} value={value} onClick={() => takeTurn(i)} circleColor={circleColor} crossColor={crossColor} squareColor={squareColor} disabled={!!winner || isAiThinking} />\n        ))}\n\n        <AnimatePresence>\n          {lineCoords && (\n            <motion.svg className=\"pointer-events-none absolute inset-0 z-10 h-full w-full\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.55, ease: \"easeOut\" }}>\n              <motion.line x1={lineCoords.x1} y1={lineCoords.y1} x2={lineCoords.x2} y2={lineCoords.y2} stroke={winner === \"CIRCLE\" ? circleColor : crossColor} strokeWidth=\"8\" strokeLinecap=\"round\" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.55 }} />\n            </motion.svg>\n          )}\n        </AnimatePresence>\n      </div>\n\n      <motion.button className=\"mt-5.5 cursor-pointer rounded-full border-none bg-[#111] px-8 py-3 text-[15px] font-bold text-white\" style={{ letterSpacing: \"0.5px\" }} onClick={reset} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} aria-label=\"Start a new tic tac toe game\">\n        New Game\n      </motion.button>\n\n      <AnimatePresence>{showConfetti && <Confetti colors={[circleColor, crossColor, \"#FFD700\", \"#00E5FF\"]} />}</AnimatePresence>\n    </div>\n  );\n\n  if (!asPopup) {\n    return (\n      <div ref={rootRef} className={cn(\"w-full\", className)} style={style} {...props}>\n        {gameCard}\n      </div>\n    );\n  }\n\n  return (\n    <div ref={rootRef} className={cn(\"relative w-full\", className)} style={style} {...props}>\n      <div className={cn(\"flex\", widgetOnRight ? \"justify-end\" : \"justify-start\")}>\n        <motion.button\n          ref={widgetTriggerRef}\n          type=\"button\"\n          onClick={() => setPopupOpen(true)}\n          whileHover={{ scale: 1.04 }}\n          whileTap={{ scale: 0.97 }}\n          aria-label={`Open ${title}`}\n          aria-haspopup=\"dialog\"\n          aria-expanded={popupOpen}\n          className=\"flex items-center gap-3 rounded-full border border-[rgba(23,26,33,0.08)] bg-white py-1.5 pr-5 pl-1.5 shadow-[0_8px_30px_rgba(0,0,0,0.12)]\"\n          style={{ fontFamily: \"'Montserrat', system-ui, sans-serif\" }}\n        >\n          <span className=\"flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#121212]\">\n            {widgetIcon ? (\n              // eslint-disable-next-line @next/next/no-img-element\n              <img src={widgetIcon} alt=\"\" className=\"h-6 w-6 rounded-full object-cover\" />\n            ) : (\n              <WidgetGlyph />\n            )}\n          </span>\n          <span className=\"flex flex-col gap-0.5 text-left\">\n            <span className=\"text-[9px] font-bold tracking-[0.1em] whitespace-nowrap text-[rgba(23,26,33,0.4)] uppercase\">Mini Game</span>\n            <span className=\"text-[13px] font-bold tracking-[0.02em] whitespace-nowrap text-[#171a21]\">{title}</span>\n          </span>\n        </motion.button>\n      </div>\n\n      <AnimatePresence>\n        {popupOpen && (\n          <motion.div\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0 }}\n            onClick={(e) => {\n              if (e.target === e.currentTarget) setPopupOpen(false);\n            }}\n            className=\"fixed inset-0 z-[9999] flex items-center justify-center p-5\"\n            style={{ background: \"rgba(0,0,0,0.45)\" }}\n          >\n            <motion.div\n              ref={popupCardRef}\n              initial={{ opacity: 0, scale: 0.94, y: 16 }}\n              animate={{ opacity: 1, scale: 1, y: 0 }}\n              exit={{ opacity: 0, scale: 0.96 }}\n              transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}\n              role=\"dialog\"\n              aria-modal=\"true\"\n              aria-label={title}\n              tabIndex={-1}\n              onKeyDown={(e) => {\n                if (e.key === \"Escape\") setPopupOpen(false);\n              }}\n              className=\"relative w-full max-w-[420px] overflow-auto rounded-[24px] bg-white shadow-[0_20px_50px_rgba(0,0,0,0.18)]\"\n              style={{ maxHeight: \"90vh\" }}\n            >\n              {gameCard}\n              <button\n                type=\"button\"\n                onClick={() => setPopupOpen(false)}\n                aria-label=\"Close game\"\n                className=\"absolute top-2.5 right-2.5 z-[100] flex h-8 w-8 items-center justify-center rounded-full border border-[rgba(23,26,33,0.1)] bg-white text-[17px] text-[#111]\"\n              >\n                ×\n              </button>\n            </motion.div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}