"use client"

import type React from "react"

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

type Template = "ocean" | "sunset" | "forest" | "midnight"

interface TemplateContextType {
  template: Template
  setTemplate: (template: Template) => void
}

const TemplateContext = createContext<TemplateContextType | undefined>(undefined)

export function TemplateProvider({ children }: { children: React.ReactNode }) {
  const [template, setTemplateState] = useState<Template>("ocean")

  useEffect(() => {
    // Load saved template from localStorage
    const saved = localStorage.getItem("app-template") as Template
    if (saved && ["ocean", "sunset", "forest", "midnight"].includes(saved)) {
      setTemplateState(saved)
      document.documentElement.setAttribute("data-template", saved)
    }
  }, [])

  const setTemplate = (newTemplate: Template) => {
    setTemplateState(newTemplate)
    localStorage.setItem("app-template", newTemplate)
    document.documentElement.setAttribute("data-template", newTemplate)
  }

  return <TemplateContext.Provider value={{ template, setTemplate }}>{children}</TemplateContext.Provider>
}

export function useTemplate() {
  const context = useContext(TemplateContext)
  if (context === undefined) {
    throw new Error("useTemplate must be used within a TemplateProvider")
  }
  return context
}
