"use client"

import { createContext, useContext, useState, useEffect, ReactNode } from "react"
import { usePathname } from "next/navigation"
import { VERTICALS, Vertical, VerticalSlug } from "@/config/verticals"

interface VerticalContextType {
    current: Vertical | null
    setCurrent: (slug: VerticalSlug | null) => void
    all: readonly Vertical[]
}

const VerticalContext = createContext<VerticalContextType | null>(null)

export function VerticalProvider({ children }: { children: ReactNode }) {
    const pathname = usePathname()

    // Detect vertical from URL path
    const getVerticalFromPath = (): Vertical | null => {
        const segments = pathname.split("/").filter(Boolean)
        const firstSegment = segments[0]
        const found = VERTICALS.find(v => v.slug === firstSegment)
        return found || null
    }

    const [current, setCurrentState] = useState<Vertical | null>(getVerticalFromPath)

    // Update current when path changes
    useEffect(() => {
        setCurrentState(getVerticalFromPath())
    }, [pathname])

    const setCurrent = (slug: VerticalSlug | null) => {
        if (slug === null) {
            setCurrentState(null)
            if (typeof window !== "undefined") {
                localStorage.removeItem("preferred-vertical")
            }
            return
        }

        const found = VERTICALS.find(v => v.slug === slug)
        if (found) {
            setCurrentState(found)
            // Store preference
            if (typeof window !== "undefined") {
                localStorage.setItem("preferred-vertical", slug)
            }
        }
    }

    // Load preference on mount
    useEffect(() => {
        if (typeof window !== "undefined") {
            const stored = localStorage.getItem("preferred-vertical") as VerticalSlug | null
            if (stored && VERTICALS.find(v => v.slug === stored)) {
                // Only set if not already in a vertical-specific route
                const segments = pathname.split("/").filter(Boolean)
                const isVerticalRoute = VERTICALS.some(v => v.slug === segments[0])
                if (!isVerticalRoute) {
                    setCurrent(stored)
                }
            }
        }
    }, [])

    return (
        <VerticalContext.Provider value={{ current, setCurrent, all: VERTICALS }}>
            {children}
        </VerticalContext.Provider>
    )
}

export function useVertical() {
    const context = useContext(VerticalContext)
    if (!context) {
        throw new Error("useVertical must be used within a VerticalProvider")
    }
    return context
}

// Helper to build vertical-aware paths
export function useVerticalPath() {
    const { current } = useVertical()

    return (path: string) => {
        // If path already starts with a vertical, return as-is
        const segments = path.split("/").filter(Boolean)
        if (VERTICALS.some(v => v.slug === segments[0])) {
            return path
        }

        // If no vertical selected, return path as-is
        if (!current) {
            return path.startsWith("/") ? path : `/${path}`
        }

        // Prepend current vertical
        return `/${current.slug}${path.startsWith("/") ? path : `/${path}`}`
    }
}
