"use client"

import type React from "react"
import { ComponentContainer } from "@/components/ui/component-container"
import { SectionHeading } from "@/components/ui/section-heading"
import { useState, useRef, useEffect } from "react"
import { createPortal } from "react-dom"

// Functional Context Menu Component with Portal Rendering
function ContextMenuDemo() {
  const [isOpen, setIsOpen] = useState(false)
  const [position, setPosition] = useState({ x: 0, y: 0 })
  const [mounted, setMounted] = useState(false)
  const triggerRef = useRef<HTMLDivElement>(null)
  const menuRef = useRef<HTMLDivElement>(null)

  // Handle SSR
  useEffect(() => {
    setMounted(true)
    return () => setMounted(false)
  }, [])

  const handleContextMenu = (e: React.MouseEvent) => {
    e.preventDefault()

    // Calculate position relative to the viewport
    const x = e.clientX
    const y = e.clientY

    // Adjust position to ensure menu stays within viewport
    const menuWidth = 220
    const menuHeight = 300 // Approximate height

    const adjustedX = Math.min(x, window.innerWidth - menuWidth - 10)
    const adjustedY = Math.min(y, window.innerHeight - menuHeight - 10)

    setPosition({ x: adjustedX, y: adjustedY })
    setIsOpen(true)
  }

  const handleClickOutside = (e: MouseEvent) => {
    if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
      setIsOpen(false)
    }
  }

  useEffect(() => {
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside)
      document.addEventListener("contextmenu", handleClickOutside)
    } else {
      document.removeEventListener("mousedown", handleClickOutside)
      document.removeEventListener("contextmenu", handleClickOutside)
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
      document.removeEventListener("contextmenu", handleClickOutside)
    }
  }, [isOpen])

  // Menu component to be rendered in portal
  const ContextMenuPortal = () => {
    if (!mounted || !isOpen) return null

    return createPortal(
      <div
        ref={menuRef}
        className="fixed min-w-[220px] bg-popover text-popover-foreground rounded-md border shadow-md p-1 z-[9999] animate-in fade-in-0 zoom-in-95 duration-100"
        style={{
          left: `${position.x}px`,
          top: `${position.y}px`,
        }}
      >
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center justify-between">
          Back
          <span className="text-xs text-muted-foreground ml-auto">⌘[</span>
        </div>
        <div className="px-2 py-1.5 text-sm text-muted-foreground cursor-not-allowed rounded-sm flex items-center justify-between">
          Forward
          <span className="text-xs text-muted-foreground ml-auto">⌘]</span>
        </div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center justify-between">
          Reload
          <span className="text-xs text-muted-foreground ml-auto">⌘R</span>
        </div>

        <div className="h-px my-1 bg-border" />

        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center justify-between">
          Save Page As...
          <span className="text-xs text-muted-foreground ml-auto">⌘S</span>
        </div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm">
          Create Shortcut...
        </div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm">
          Name Window...
        </div>

        <div className="h-px my-1 bg-border" />

        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center">
          <span className="mr-2">✓</span> Show Bookmarks Bar
          <span className="text-xs text-muted-foreground ml-auto">⌘⇧B</span>
        </div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center">
          <span className="mr-2 opacity-0">✓</span> Show Full URLs
        </div>

        <div className="h-px my-1 bg-border" />

        <div className="px-2 py-1.5 text-sm font-semibold">People</div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center">
          <span className="mr-2">●</span> Pedro Duarte
        </div>
        <div className="px-2 py-1.5 text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-sm flex items-center">
          <span className="mr-2 opacity-0">●</span> Colm Tuite
        </div>
      </div>,
      document.body,
    )
  }

  return (
    <div className="relative">
      <div
        ref={triggerRef}
        onContextMenu={handleContextMenu}
        className="flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm cursor-context-menu"
      >
        Right click here
      </div>
      <ContextMenuPortal />
    </div>
  )
}

export function ContextMenuSection() {
  return (
    <div className="space-y-8">
      <SectionHeading
        title="Context Menu"
        description="A context menu displayed at the pointer's position on right click."
      />

      <ComponentContainer
        title="Basic Context Menu"
        description="A simple context menu with items and shortcuts. Right-click on the dashed area to see it in action."
        code={`import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
  ContextMenuSeparator,
  ContextMenuShortcut,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuCheckboxItem,
  ContextMenuRadioGroup,
  ContextMenuRadioItem,
} from "@/components/ui/context-menu"

export function ContextMenuDemo() {
  return (
    <ContextMenu>
      <ContextMenuTrigger className="flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm">
        Right click here
      </ContextMenuTrigger>
      <ContextMenuContent className="w-64">
        <ContextMenuItem inset>
          Back
          <ContextMenuShortcut>⌘[</ContextMenuShortcut>
        </ContextMenuItem>
        <ContextMenuItem inset disabled>
          Forward
          <ContextMenuShortcut>⌘]</ContextMenuShortcut>
        </ContextMenuItem>
        <ContextMenuItem inset>
          Reload
          <ContextMenuShortcut>⌘R</ContextMenuShortcut>
        </ContextMenuItem>
        <ContextMenuSub>
          <ContextMenuSubTrigger inset>More Tools</ContextMenuSubTrigger>
          <ContextMenuSubContent className="w-48">
            <ContextMenuItem>
              Save Page As...
              <ContextMenuShortcut>⌘S</ContextMenuShortcut>
            </ContextMenuItem>
            <ContextMenuItem>Create Shortcut...</ContextMenuItem>
            <ContextMenuItem>Name Window...</ContextMenuItem>
            <ContextMenuSeparator />
            <ContextMenuItem>Developer Tools</ContextMenuItem>
          </ContextMenuSubContent>
        </ContextMenuSub>
        <ContextMenuSeparator />
        <ContextMenuCheckboxItem checked>
          Show Bookmarks Bar
          <ContextMenuShortcut>⌘⇧B</ContextMenuShortcut>
        </ContextMenuCheckboxItem>
        <ContextMenuCheckboxItem>Show Full URLs</ContextMenuCheckboxItem>
        <ContextMenuSeparator />
        <ContextMenuRadioGroup value="pedro">
          <ContextMenuLabel inset>People</ContextMenuLabel>
          <ContextMenuSeparator />
          <ContextMenuRadioItem value="pedro">
            Pedro Duarte
          </ContextMenuRadioItem>
          <ContextMenuRadioItem value="colm">
            Colm Tuite
          </ContextMenuRadioItem>
        </ContextMenuRadioGroup>
      </ContextMenuContent>
    </ContextMenu>
  )
}`}
      >
        <div className="flex items-center justify-center p-6">
          <ContextMenuDemo />
        </div>
      </ComponentContainer>
    </div>
  )
}
