"use client"

import type React from "react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { useState, useRef, useEffect } from "react"

// Define our spacing scale in rem units
const spacingScale = [
  { name: "0.25rem", value: "0.25rem", tailwind: "1", px: "4px", description: "Tight spacing" },
  { name: "0.5rem", value: "0.5rem", tailwind: "2", px: "8px", description: "Small spacing" },
  { name: "0.75rem", value: "0.75rem", tailwind: "3", px: "12px", description: "Compact spacing" },
  { name: "1rem", value: "1rem", tailwind: "4", px: "16px", description: "Base spacing" },
  { name: "1.25rem", value: "1.25rem", tailwind: "5", px: "20px", description: "Comfortable spacing" },
  { name: "1.5rem", value: "1.5rem", tailwind: "6", px: "24px", description: "Relaxed spacing" },
  { name: "2rem", value: "2rem", tailwind: "8", px: "32px", description: "Section spacing" },
  { name: "2.5rem", value: "2.5rem", tailwind: "10", px: "40px", description: "Large spacing" },
  { name: "3rem", value: "3rem", tailwind: "12", px: "48px", description: "Extra large spacing" },
  { name: "4rem", value: "4rem", tailwind: "16", px: "64px", description: "Maximum spacing" },
]

// Spacing Notation Component
function SpacingNotation({
  value,
  direction = "all",
  label,
  color = "primary",
}: {
  value: string
  direction?: "top" | "bottom" | "left" | "right" | "horizontal" | "vertical" | "all"
  label?: string
  color?: "primary" | "secondary" | "accent" | "muted"
}) {
  const colorClasses = {
    primary: "border-primary bg-primary/10 text-primary",
    secondary: "border-orange-500 bg-orange-500/10 text-orange-600",
    accent: "border-green-500 bg-green-500/10 text-green-600",
    muted: "border-muted-foreground bg-muted text-muted-foreground",
  }

  const directionSymbols = {
    top: "↑",
    bottom: "↓",
    left: "←",
    right: "→",
    horizontal: "↔",
    vertical: "↕",
    all: "⊞",
  }

  return (
    <div
      className={`inline-flex items-center gap-1 px-2 py-1 rounded-md border text-xs font-mono ${colorClasses[color]}`}
    >
      <span className="font-semibold">{directionSymbols[direction]}</span>
      <span>{value}</span>
      {label && <span className="opacity-75">({label})</span>}
    </div>
  )
}

// Interactive Annotated Component with precise positioning
function InteractiveAnnotatedComponent({
  children,
  spacingAreas = [],
  title,
}: {
  children: React.ReactNode
  spacingAreas?: Array<{
    type: "padding" | "margin" | "gap"
    value: string
    direction?: "top" | "bottom" | "left" | "right" | "horizontal" | "vertical" | "all"
    selector: string // CSS selector to target the specific element
    spacingType: "padding" | "margin" | "gap"
    label?: string
    description?: string
  }>
  title: string
}) {
  const [hoveredArea, setHoveredArea] = useState<number | null>(null)
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 })
  const [overlayPositions, setOverlayPositions] = useState<
    Array<{ top: number; left: number; width: number; height: number }>
  >([])
  const containerRef = useRef<HTMLDivElement>(null)

  // Calculate overlay positions based on actual DOM elements
  useEffect(() => {
    if (!containerRef.current) return

    const positions = spacingAreas.map((area) => {
      const element = containerRef.current?.querySelector(area.selector) as HTMLElement
      if (!element) return { top: 0, left: 0, width: 0, height: 0 }

      const containerRect = containerRef.current!.getBoundingClientRect()
      const elementRect = element.getBoundingClientRect()

      // Get computed styles to calculate actual spacing
      const computedStyle = window.getComputedStyle(element)

      let overlayRect = {
        top: elementRect.top - containerRect.top,
        left: elementRect.left - containerRect.left,
        width: elementRect.width,
        height: elementRect.height,
      }

      // Adjust overlay based on spacing type
      if (area.spacingType === "padding") {
        // For padding, highlight the inner content area
        const paddingTop = Number.parseFloat(computedStyle.paddingTop)
        const paddingLeft = Number.parseFloat(computedStyle.paddingLeft)
        const paddingRight = Number.parseFloat(computedStyle.paddingRight)
        const paddingBottom = Number.parseFloat(computedStyle.paddingBottom)

        overlayRect = {
          top: overlayRect.top + paddingTop,
          left: overlayRect.left + paddingLeft,
          width: overlayRect.width - paddingLeft - paddingRight,
          height: overlayRect.height - paddingTop - paddingBottom,
        }
      } else if (area.spacingType === "margin") {
        // For margin, highlight the margin area around the element
        const marginTop = Number.parseFloat(computedStyle.marginTop)
        const marginLeft = Number.parseFloat(computedStyle.marginLeft)
        const marginRight = Number.parseFloat(computedStyle.marginRight)
        const marginBottom = Number.parseFloat(computedStyle.marginBottom)

        overlayRect = {
          top: overlayRect.top - marginTop,
          left: overlayRect.left - marginLeft,
          width: overlayRect.width + marginLeft + marginRight,
          height: overlayRect.height + marginTop + marginBottom,
        }
      }

      return overlayRect
    })

    setOverlayPositions(positions)
  }, [spacingAreas])

  const handleMouseMove = (e: React.MouseEvent) => {
    const rect = e.currentTarget.getBoundingClientRect()
    setMousePosition({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    })
  }

  const getAreaColor = (type: "padding" | "margin" | "gap") => {
    switch (type) {
      case "padding":
        return "bg-primary/30 border-primary border-2"
      case "margin":
        return "bg-orange-500/30 border-orange-500 border-2"
      case "gap":
        return "bg-green-500/30 border-green-500 border-2"
    }
  }

  const getNotationColor = (type: "padding" | "margin" | "gap") => {
    switch (type) {
      case "padding":
        return "primary" as const
      case "margin":
        return "secondary" as const
      case "gap":
        return "accent" as const
    }
  }

  return (
    <div className="space-y-4">
      <h5 className="text-sm font-medium text-foreground">{title}</h5>
      <div
        ref={containerRef}
        className="relative inline-block"
        onMouseMove={handleMouseMove}
        onMouseLeave={() => setHoveredArea(null)}
      >
        {/* Component */}
        <div className="relative z-10">{children}</div>

        {/* Interactive spacing overlays */}
        {overlayPositions.map((position, index) => (
          <div
            key={index}
            className={`absolute border-dashed transition-all duration-200 cursor-help pointer-events-auto ${
              hoveredArea === index
                ? `${getAreaColor(spacingAreas[index].type)} opacity-100 z-20`
                : "border-transparent hover:border-muted-foreground/50 opacity-0 hover:opacity-70"
            }`}
            style={{
              top: `${position.top}px`,
              left: `${position.left}px`,
              width: `${position.width}px`,
              height: `${position.height}px`,
            }}
            onMouseEnter={() => setHoveredArea(index)}
            onMouseLeave={() => setHoveredArea(null)}
          />
        ))}

        {/* Tooltip */}
        {hoveredArea !== null && (
          <div
            className="absolute z-30 pointer-events-none"
            style={{
              left: mousePosition.x + 10,
              top: mousePosition.y - 10,
              transform: mousePosition.x > 200 ? "translateX(-100%)" : "none",
            }}
          >
            <div className="bg-background border border-border rounded-lg shadow-lg p-3 max-w-xs">
              <div className="flex items-center gap-2 mb-1">
                <SpacingNotation
                  value={spacingAreas[hoveredArea].value}
                  direction={spacingAreas[hoveredArea].direction}
                  label={spacingAreas[hoveredArea].label}
                  color={getNotationColor(spacingAreas[hoveredArea].type)}
                />
              </div>
              <div className="text-xs text-muted-foreground capitalize">
                {spacingAreas[hoveredArea].type}
                {spacingAreas[hoveredArea].description && ` • ${spacingAreas[hoveredArea].description}`}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export function SpacingSection() {
  const [selectedExample, setSelectedExample] = useState("button")

  return (
    <section id="spacing" className="scroll-mt-16">
      <h2 className="text-3xl font-semibold tracking-tight mb-4 text-foreground">Spacing</h2>

      <p className="text-muted-foreground text-sm mb-8 max-w-2xl">
        Our spacing system uses a consistent scale based on rem units. Hover over components below to explore their
        spacing interactively.
      </p>

      <div className="space-y-12">
        {/* Notation System Legend */}
        <div className="p-6 rounded-lg border bg-muted/30">
          <h3 className="text-lg font-medium text-foreground mb-4">Interactive Spacing Notation</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div className="space-y-3">
              <h4 className="text-sm font-medium text-foreground">Types</h4>
              <div className="space-y-2">
                <div className="flex items-center gap-3">
                  <div className="w-4 h-4 bg-primary/30 border-2 border-primary rounded"></div>
                  <SpacingNotation value="1rem" color="primary" />
                  <span className="text-xs text-muted-foreground">Padding</span>
                </div>
                <div className="flex items-center gap-3">
                  <div className="w-4 h-4 bg-orange-500/30 border-2 border-orange-500 rounded"></div>
                  <SpacingNotation value="1rem" color="secondary" />
                  <span className="text-xs text-muted-foreground">Margin</span>
                </div>
                <div className="flex items-center gap-3">
                  <div className="w-4 h-4 bg-green-500/30 border-2 border-green-500 rounded"></div>
                  <SpacingNotation value="1rem" color="accent" />
                  <span className="text-xs text-muted-foreground">Gap</span>
                </div>
              </div>
            </div>

            <div className="space-y-3">
              <h4 className="text-sm font-medium text-foreground">Directions</h4>
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="top" color="muted" />
                  <span className="text-muted-foreground">Top</span>
                </div>
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="bottom" color="muted" />
                  <span className="text-muted-foreground">Bottom</span>
                </div>
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="left" color="muted" />
                  <span className="text-muted-foreground">Left</span>
                </div>
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="right" color="muted" />
                  <span className="text-muted-foreground">Right</span>
                </div>
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="horizontal" color="muted" />
                  <span className="text-muted-foreground">Horizontal</span>
                </div>
                <div className="flex items-center gap-2">
                  <SpacingNotation value="1rem" direction="vertical" color="muted" />
                  <span className="text-muted-foreground">Vertical</span>
                </div>
              </div>
            </div>

            <div className="space-y-3">
              <h4 className="text-sm font-medium text-foreground">How to Use</h4>
              <div className="text-xs text-muted-foreground space-y-1">
                <div>• Hover over components to see spacing</div>
                <div>• Colored overlays show spacing areas</div>
                <div>• Tooltips display exact values</div>
                <div>• Direction arrows indicate application</div>
              </div>
            </div>
          </div>
        </div>

        {/* Spacing Scale */}
        <div className="space-y-6">
          <h3 className="text-lg font-medium text-foreground">Spacing Scale</h3>

          <div className="space-y-3">
            {spacingScale.map((spacing, index) => (
              <div key={spacing.name} className="flex items-center gap-6 py-2">
                {/* Value and Tailwind class */}
                <div className="flex items-center gap-4 w-48">
                  <div className="text-sm font-mono text-foreground w-16">{spacing.name}</div>
                  <div className="text-xs text-muted-foreground font-mono bg-muted px-2 py-1 rounded">
                    {spacing.tailwind}
                  </div>
                  <div className="text-xs text-muted-foreground">({spacing.px})</div>
                </div>

                {/* Visual representation */}
                <div className="flex items-center gap-3 flex-1">
                  <div className="h-6 bg-primary/20 border-l-2 border-primary" style={{ width: spacing.value }} />
                  <div className="text-xs text-muted-foreground">{spacing.description}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Interactive Component Examples */}
        <div className="space-y-6">
          <div className="flex items-center gap-4">
            <h3 className="text-lg font-medium text-foreground">Interactive Examples</h3>
            <div className="flex gap-2">
              {["button", "card", "form"].map((example) => (
                <Button
                  key={example}
                  variant={selectedExample === example ? "default" : "outline"}
                  size="sm"
                  onClick={() => setSelectedExample(example)}
                  className="capitalize"
                >
                  {example}
                </Button>
              ))}
            </div>
          </div>

          <div className="text-sm text-muted-foreground mb-4">
            Hover over the components below to explore their spacing interactively.
          </div>

          <div className="p-8 bg-muted/30 rounded-lg min-h-[400px] flex items-center justify-center">
            {selectedExample === "button" && (
              <div className="space-y-12">
                <InteractiveAnnotatedComponent
                  title="Small Button"
                  spacingAreas={[
                    {
                      type: "padding",
                      value: "0.75rem",
                      direction: "horizontal",
                      selector: "button",
                      spacingType: "padding",
                      description: "px-3 py-1.5 - Internal button spacing",
                    },
                  ]}
                >
                  <Button size="sm">Small Button</Button>
                </InteractiveAnnotatedComponent>

                <InteractiveAnnotatedComponent
                  title="Default Button"
                  spacingAreas={[
                    {
                      type: "padding",
                      value: "1rem",
                      direction: "horizontal",
                      selector: "button",
                      spacingType: "padding",
                      description: "px-4 py-2 - Internal button spacing",
                    },
                  ]}
                >
                  <Button>Default Button</Button>
                </InteractiveAnnotatedComponent>

                <InteractiveAnnotatedComponent
                  title="Large Button"
                  spacingAreas={[
                    {
                      type: "padding",
                      value: "2rem",
                      direction: "horizontal",
                      selector: "button",
                      spacingType: "padding",
                      description: "px-8 py-3 - Internal button spacing",
                    },
                  ]}
                >
                  <Button size="lg">Large Button</Button>
                </InteractiveAnnotatedComponent>
              </div>
            )}

            {selectedExample === "card" && (
              <InteractiveAnnotatedComponent
                title="Card Structure"
                spacingAreas={[
                  {
                    type: "padding",
                    value: "1.5rem",
                    direction: "all",
                    selector: "[data-card-header]",
                    spacingType: "padding",
                    label: "header",
                    description: "p-6 - Header padding",
                  },
                  {
                    type: "padding",
                    value: "1.5rem",
                    direction: "all",
                    selector: "[data-card-content]",
                    spacingType: "padding",
                    label: "content",
                    description: "p-6 - Content padding",
                  },
                  {
                    type: "padding",
                    value: "1.5rem",
                    direction: "all",
                    selector: "[data-card-footer]",
                    spacingType: "padding",
                    label: "footer",
                    description: "p-6 - Footer padding",
                  },
                ]}
              >
                <Card className="w-80">
                  <CardHeader data-card-header>
                    <CardTitle>Card Title</CardTitle>
                  </CardHeader>
                  <CardContent data-card-content>
                    <p className="text-sm text-muted-foreground">
                      Card content with consistent internal spacing for optimal readability and visual hierarchy.
                    </p>
                  </CardContent>
                  <CardFooter data-card-footer>
                    <Button>Action</Button>
                  </CardFooter>
                </Card>
              </InteractiveAnnotatedComponent>
            )}

            {selectedExample === "form" && (
              <InteractiveAnnotatedComponent
                title="Form Layout"
                spacingAreas={[
                  {
                    type: "gap",
                    value: "1rem",
                    direction: "vertical",
                    selector: "[data-form-container]",
                    spacingType: "gap",
                    description: "space-y-4 - Gap between form elements",
                  },
                  {
                    type: "margin",
                    value: "0.25rem",
                    direction: "top",
                    selector: "[data-form-input]:first-of-type",
                    spacingType: "margin",
                    description: "mt-1 - Label to input spacing",
                  },
                  {
                    type: "margin",
                    value: "0.25rem",
                    direction: "top",
                    selector: "[data-form-input]:last-of-type",
                    spacingType: "margin",
                    description: "mt-1 - Label to input spacing",
                  },
                ]}
              >
                <div className="space-y-4 w-64" data-form-container>
                  <div>
                    <Label htmlFor="name" className="text-sm">
                      Name
                    </Label>
                    <Input id="name" placeholder="Enter name" className="mt-1" data-form-input />
                  </div>
                  <div>
                    <Label htmlFor="email" className="text-sm">
                      Email
                    </Label>
                    <Input id="email" type="email" placeholder="Enter email" className="mt-1" data-form-input />
                  </div>
                  <Button className="w-full">Submit</Button>
                </div>
              </InteractiveAnnotatedComponent>
            )}
          </div>
        </div>

        {/* Additional Interactive Examples */}
        <div className="space-y-6">
          <h3 className="text-lg font-medium text-foreground">Component Spacing Patterns</h3>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <InteractiveAnnotatedComponent
              title="Badge Groups"
              spacingAreas={[
                {
                  type: "gap",
                  value: "0.5rem",
                  direction: "all",
                  selector: "[data-badge-container]",
                  spacingType: "gap",
                  description: "gap-2 - Gap between badges in flex layout",
                },
              ]}
            >
              <div className="p-6 bg-background border rounded-lg">
                <div className="flex flex-wrap gap-2" data-badge-container>
                  <Badge variant="outline">Design</Badge>
                  <Badge variant="secondary">Development</Badge>
                  <Badge>Featured</Badge>
                  <Badge variant="destructive">Urgent</Badge>
                </div>
              </div>
            </InteractiveAnnotatedComponent>

            <InteractiveAnnotatedComponent
              title="Button Groups"
              spacingAreas={[
                {
                  type: "gap",
                  value: "0.75rem",
                  direction: "horizontal",
                  selector: "[data-button-container]",
                  spacingType: "gap",
                  description: "gap-3 - Gap between buttons in flex layout",
                },
              ]}
            >
              <div className="p-6 bg-background border rounded-lg">
                <div className="flex gap-3" data-button-container>
                  <Button variant="outline" size="sm">
                    Cancel
                  </Button>
                  <Button size="sm">Save</Button>
                </div>
              </div>
            </InteractiveAnnotatedComponent>
          </div>
        </div>

        {/* Usage Guidelines */}
        <div className="p-6 rounded-lg border bg-muted/30">
          <h4 className="text-sm font-medium mb-4 text-foreground">Spacing Guidelines</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm">
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Component padding</div>
                  <div className="text-muted-foreground text-xs">Use 1rem (16px) for default internal spacing</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Related elements</div>
                  <div className="text-muted-foreground text-xs">Use 1rem (16px) gap between related items</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Section spacing</div>
                  <div className="text-muted-foreground text-xs">Use 2rem (32px) between distinct sections</div>
                </div>
              </div>
            </div>
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Interactive exploration</div>
                  <div className="text-muted-foreground text-xs">
                    Hover over components to understand their spacing structure
                  </div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Consistency</div>
                  <div className="text-muted-foreground text-xs">
                    Maintain consistent spacing within component types
                  </div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0" />
                <div>
                  <div className="font-medium">Responsive scaling</div>
                  <div className="text-muted-foreground text-xs">Consider reducing spacing on smaller screens</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
