"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"

type DesignContextType = {
  borderRadius: number
  setBorderRadius: (value: number) => void
  font: string
  setFont: (value: string) => void
}

// Update the fonts array to include all requested fonts
const fonts = [
  { name: "Inter", value: "Inter, sans-serif" },
  { name: "Satoshi", value: "Satoshi, sans-serif" },
  { name: "DM Sans", value: "DM Sans, sans-serif" },
  { name: "Manrope", value: "Manrope, sans-serif" },
  // Add new Google Fonts
  { name: "Public Sans", value: "Public Sans, sans-serif" },
  { name: "IBM Plex Sans", value: "IBM Plex Sans, sans-serif" },
  { name: "Recursive", value: "Recursive, sans-serif" },
  { name: "Fraunces", value: "Fraunces, serif" },
  { name: "Lexend", value: "Lexend, sans-serif" },
  // Monospace fonts
  { name: "Fira Code", value: "Fira Code, monospace" },
  { name: "JetBrains Mono", value: "JetBrains Mono, monospace" },
  { name: "IBM Plex Mono", value: "IBM Plex Mono, monospace" },
  { name: "Source Code Pro", value: "Source Code Pro, monospace" },
  { name: "Space Mono", value: "Space Mono, monospace" },
  { name: "Roboto Mono", value: "Roboto Mono, monospace" },
  { name: "Ubuntu Mono", value: "Ubuntu Mono, monospace" },
  { name: "Inconsolata", value: "Inconsolata, monospace" },
  // Existing fonts
  { name: "Arial", value: "Arial, sans-serif" },
  { name: "Helvetica", value: "Helvetica, sans-serif" },
  { name: "Source Sans Pro", value: "Source Sans Pro, sans-serif" },
  { name: "Space Grotesk", value: "Space Grotesk, sans-serif" },
  { name: "Rubik", value: "Rubik, sans-serif" },
  { name: "Work Sans", value: "Work Sans, sans-serif" },
  { name: "Object Sans", value: "Object Sans, sans-serif" },
  { name: "Libre Baskerville", value: "Libre Baskerville, serif" },
  { name: "Roboto", value: "Roboto, sans-serif" },
  { name: "Poppins", value: "Poppins, sans-serif" },
  { name: "Montserrat", value: "Montserrat, sans-serif" },
  { name: "Open Sans", value: "Open Sans, sans-serif" },
  { name: "Lato", value: "Lato, sans-serif" },
  { name: "Nunito", value: "Nunito, sans-serif" },
  { name: "Raleway", value: "Raleway, sans-serif" },
  { name: "SF Pro", value: "SF Pro, -apple-system, BlinkMacSystemFont, sans-serif" },
  { name: "Segoe UI", value: "Segoe UI, Tahoma, Geneva, Verdana, sans-serif" },
  { name: "System UI", value: "system-ui, -apple-system, BlinkMacSystemFont, sans-serif" },
  { name: "Playfair Display", value: "Playfair Display, serif" },
  { name: "Merriweather", value: "Merriweather, serif" },
]

const DesignContext = createContext<DesignContextType | undefined>(undefined)

export function DesignProvider({ children }: { children: ReactNode }) {
  const [borderRadius, setBorderRadius] = useState<number>(12) // Default 12px (0.8rem)
  const [font, setFont] = useState<string>(fonts[0].value)

  useEffect(() => {
    // Only run on client-side
    if (typeof window === "undefined") return

    const root = document.documentElement

    // Update border radius for style guide components only
    root.style.setProperty("--radius", `${borderRadius / 16}rem`)

    // Add a more pronounced radius for cards to properly encapsulate inner components
    // Increased from +4px to +8px for a more noticeable difference
    root.style.setProperty("--card-radius", `${(borderRadius + 8) / 16}rem`)

    // Update font - Apply font only to style guide components, not the entire body
    root.style.setProperty("--selected-font", font)

    console.log("Font changed to:", font) // Debug log
    console.log("Border radius set to:", borderRadius, "Card radius set to:", borderRadius + 8) // Debug log

    // Use requestAnimationFrame to batch DOM updates and avoid layout thrashing
    requestAnimationFrame(() => {
      // Apply font to the root document for global inheritance
      document.documentElement.style.setProperty("--selected-font", font)

      // Apply to body for fallback
      document.body.style.fontFamily = font

      // Apply to main content and all its children
      const mainContentElement = document.querySelector(".main-content")
      if (mainContentElement) {
        console.log("Applying font to main-content:", font)
        ;(mainContentElement as HTMLElement).style.fontFamily = font
      }

      // Apply to all major content containers
      const contentSelectors = [
        ".style-guide-section",
        ".app-ui",
        ".style-guide-banner-content",
        ".block-content",
        ".block-section",
        "[data-block]",
        ".page-content",
        "main",
        "article",
        "section",
      ]

      contentSelectors.forEach((selector) => {
        document.querySelectorAll(selector).forEach((element) => {
          ;(element as HTMLElement).style.fontFamily = font
        })
      })

      // Apply to all text elements globally (except those with fixed-font class)
      const textSelectors = [
        "p",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "span",
        "div",
        "button",
        "input",
        "textarea",
        "select",
        "label",
        "a",
        "li",
        "td",
        "th",
        "caption",
        "figcaption",
      ]

      textSelectors.forEach((selector) => {
        document.querySelectorAll(selector).forEach((element) => {
          // Skip elements with fixed-font class or that are inside fixed-font containers
          if (
            !(element as HTMLElement).classList.contains("fixed-font") &&
            !(element as HTMLElement).closest(".fixed-font")
          ) {
            ;(element as HTMLElement).style.fontFamily = font
          }
        })
      })

      // Force update for any dynamically loaded content
      const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              const element = node as HTMLElement
              if (!element.classList.contains("fixed-font") && !element.closest(".fixed-font")) {
                element.style.fontFamily = font

                // Apply to children as well
                element.querySelectorAll(textSelectors.join(", ")).forEach((child) => {
                  if (!(child as HTMLElement).classList.contains("fixed-font")) {
                    ;(child as HTMLElement).style.fontFamily = font
                  }
                })
              }
            }
          })
        })
      })

      // Observe the entire document for changes
      observer.observe(document.body, {
        childList: true,
        subtree: true,
      })

      // Clean up observer after 5 seconds to avoid memory leaks
      setTimeout(() => observer.disconnect(), 5000)
    })
  }, [borderRadius, font])

  return (
    <DesignContext.Provider
      value={{
        borderRadius,
        setBorderRadius,
        font,
        setFont,
      }}
    >
      {children}
    </DesignContext.Provider>
  )
}

export function useDesign() {
  const context = useContext(DesignContext)
  if (context === undefined) {
    throw new Error("useDesign must be used within a DesignProvider")
  }
  return context
}

export const availableFonts = fonts

export const useDesignContext = useDesign
