'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { Spinner } from '@phosphor-icons/react';
import { MDXRemote } from 'next-mdx-remote';
import { cn } from '@/lib/utils';
// Import base MDX components (using relative path for Vercel compatibility)
import { Note, Warning as WarningCallout, Info, Tip, Check, Error as ErrorCallout, Callout } from '../../docs/mdx/index';
// Custom styled components for changelog content
const changelogMdxComponents = {
    h2: ({ children, ...props })=>/*#__PURE__*/ _jsx("h2", {
            className: "text-lg font-semibold text-foreground mt-6 mb-3",
            ...props,
            children: children
        }),
    h3: ({ children, ...props })=>/*#__PURE__*/ _jsx("h3", {
            className: "text-base font-medium text-foreground mt-4 mb-2",
            ...props,
            children: children
        }),
    p: ({ children, ...props })=>/*#__PURE__*/ _jsx("p", {
            className: "text-muted-foreground mb-4",
            ...props,
            children: children
        }),
    ul: ({ children, ...props })=>/*#__PURE__*/ _jsx("ul", {
            className: "space-y-2 text-muted-foreground mb-4",
            ...props,
            children: children
        }),
    li: ({ children, ...props })=>/*#__PURE__*/ _jsxs("li", {
            className: "flex items-start gap-2",
            ...props,
            children: [
                /*#__PURE__*/ _jsx("span", {
                    className: "mt-2 h-1.5 w-1.5 rounded-full bg-foreground shrink-0"
                }),
                /*#__PURE__*/ _jsx("span", {
                    children: children
                })
            ]
        }),
    strong: ({ children, ...props })=>/*#__PURE__*/ _jsx("strong", {
            className: "font-semibold text-foreground",
            ...props,
            children: children
        }),
    // Keep callout components
    Note,
    Warning: WarningCallout,
    Info,
    Tip,
    Check,
    Error: ErrorCallout,
    Callout
};
// Format date to be more readable
function formatDate(dateString) {
    try {
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    } catch  {
        return dateString;
    }
}
// Extract version from slug (e.g., "changelog/v1.2.0" -> "v1.2.0")
function getVersionFromSlug(slug) {
    return slug.replace(/^changelog\//, '');
}
// Single release entry component
function ReleaseEntry({ release, content, isLatest, isLast }) {
    // Use version extracted from slug for the ID (without changelog/ prefix)
    const versionId = getVersionFromSlug(release.slug);
    return /*#__PURE__*/ _jsxs("article", {
        id: `release-${versionId}`,
        className: "docs-changelog-entry relative scroll-mt-24 pl-8",
        children: [
            !isLast && /*#__PURE__*/ _jsx("div", {
                className: "absolute left-[3px] top-3 bottom-0 w-[2px] bg-border"
            }),
            /*#__PURE__*/ _jsx("div", {
                className: cn("absolute left-0 top-[6px] w-[8px] h-[8px] rounded-full border-2 z-10", isLatest ? "bg-primary border-primary" : "bg-background border-muted-foreground/40")
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: "pb-10",
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: "flex flex-wrap items-center gap-3 mb-4",
                        children: [
                            /*#__PURE__*/ _jsxs("span", {
                                className: cn("docs-changelog-version inline-flex items-center px-3 py-1 text-sm font-semibold rounded-full", isLatest ? "bg-primary/10 text-primary border border-primary/20" : "bg-muted text-foreground border border-border"),
                                children: [
                                    release.version,
                                    isLatest && /*#__PURE__*/ _jsx("span", {
                                        className: "ml-2 text-xs font-normal opacity-75",
                                        children: "Latest"
                                    })
                                ]
                            }),
                            /*#__PURE__*/ _jsx("time", {
                                className: "docs-changelog-date text-sm text-muted-foreground",
                                children: formatDate(release.date)
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsx("h2", {
                        className: "docs-changelog-title text-xl font-semibold text-foreground mb-4",
                        children: release.title
                    }),
                    content ? /*#__PURE__*/ _jsx("div", {
                        className: "docs-changelog-content prose prose-sm dark:prose-invert max-w-none",
                        children: /*#__PURE__*/ _jsx(MDXRemote, {
                            ...content.mdxSource,
                            components: changelogMdxComponents
                        })
                    }) : /*#__PURE__*/ _jsxs("div", {
                        className: "flex items-center gap-2 text-muted-foreground py-4",
                        children: [
                            /*#__PURE__*/ _jsx(Spinner, {
                                className: "h-4 w-4 animate-spin"
                            }),
                            /*#__PURE__*/ _jsx("span", {
                                className: "text-sm",
                                children: "Loading..."
                            })
                        ]
                    })
                ]
            })
        ]
    });
}
export function ChangelogPage({ releases, tabName = 'Changelog' }) {
    const [releaseContents, setReleaseContents] = useState(new Map());
    const [loadingAll, setLoadingAll] = useState(true);
    const [error, setError] = useState(null);
    const [activeVersion, setActiveVersion] = useState(releases[0]?.version || null);
    // Load all releases on mount
    useEffect(()=>{
        async function fetchAllReleases() {
            if (releases.length === 0) {
                setLoadingAll(false);
                return;
            }
            setLoadingAll(true);
            setError(null);
            const contents = new Map();
            // Fetch all releases in parallel
            const fetchPromises = releases.map(async (release)=>{
                try {
                    const response = await fetch(`/api/docs?slug=${encodeURIComponent(release.slug)}`);
                    if (response.ok) {
                        const data = await response.json();
                        contents.set(release.version, data);
                    }
                } catch (err) {
                    console.error(`Error loading release ${release.version}:`, err);
                }
            });
            await Promise.all(fetchPromises);
            setReleaseContents(contents);
            setLoadingAll(false);
        }
        fetchAllReleases();
    }, [
        releases
    ]);
    // Track active version based on scroll position
    useEffect(()=>{
        const observer = new IntersectionObserver((entries)=>{
            for (const entry of entries){
                if (entry.isIntersecting) {
                    const version = entry.target.getAttribute('data-version');
                    if (version) {
                        setActiveVersion(version);
                    }
                }
            }
        }, {
            rootMargin: '-100px 0px -70% 0px',
            threshold: 0
        });
        // Observe all release entries
        releases.forEach((release)=>{
            const versionId = getVersionFromSlug(release.slug);
            const element = document.getElementById(`release-${versionId}`);
            if (element) {
                element.setAttribute('data-version', release.version);
                observer.observe(element);
            }
        });
        return ()=>observer.disconnect();
    }, [
        releases,
        releaseContents
    ]);
    const scrollToRelease = (slug)=>{
        const versionId = getVersionFromSlug(slug);
        const element = document.getElementById(`release-${versionId}`);
        if (element) {
            element.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    };
    if (releases.length === 0) {
        return /*#__PURE__*/ _jsx("div", {
            className: "flex-1 flex items-center justify-center py-12",
            children: /*#__PURE__*/ _jsx("p", {
                className: "text-muted-foreground",
                children: "No changelog releases found."
            })
        });
    }
    return /*#__PURE__*/ _jsxs("div", {
        className: "docs-changelog flex flex-1 h-full overflow-hidden",
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "docs-changelog-main flex-1 overflow-y-auto",
                children: /*#__PURE__*/ _jsxs("div", {
                    className: "max-w-3xl mx-auto px-6 py-8 lg:px-8",
                    children: [
                        /*#__PURE__*/ _jsxs("header", {
                            className: "docs-changelog-header mb-10",
                            children: [
                                /*#__PURE__*/ _jsx("h1", {
                                    className: "docs-content-title text-3xl font-bold text-foreground mb-2",
                                    children: tabName
                                }),
                                /*#__PURE__*/ _jsx("p", {
                                    className: "text-muted-foreground",
                                    children: "All notable changes and updates to this project."
                                })
                            ]
                        }),
                        loadingAll && releaseContents.size === 0 && /*#__PURE__*/ _jsx("div", {
                            className: "docs-loading flex items-center justify-center py-12",
                            children: /*#__PURE__*/ _jsx(Spinner, {
                                className: "h-6 w-6 animate-spin text-muted-foreground"
                            })
                        }),
                        error && /*#__PURE__*/ _jsx("div", {
                            className: "docs-error text-center py-12",
                            children: /*#__PURE__*/ _jsx("p", {
                                className: "text-destructive",
                                children: error
                            })
                        }),
                        /*#__PURE__*/ _jsx("div", {
                            className: "docs-changelog-releases relative",
                            children: releases.map((release, index)=>/*#__PURE__*/ _jsx(ReleaseEntry, {
                                    release: release,
                                    content: releaseContents.get(release.version) || null,
                                    isLatest: index === 0,
                                    isLast: index === releases.length - 1
                                }, release.version))
                        })
                    ]
                })
            }),
            releases.length > 1 && /*#__PURE__*/ _jsx("aside", {
                className: "docs-changelog-sidebar hidden lg:flex lg:flex-col w-48 h-full border-l border-border bg-muted/20 overflow-y-auto shrink-0",
                children: /*#__PURE__*/ _jsxs("div", {
                    className: "p-4 sticky top-0",
                    children: [
                        /*#__PURE__*/ _jsx("h3", {
                            className: "docs-changelog-sidebar-title text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3",
                            children: "Releases"
                        }),
                        /*#__PURE__*/ _jsx("nav", {
                            className: "docs-changelog-nav space-y-1",
                            children: releases.map((release, index)=>/*#__PURE__*/ _jsx("button", {
                                    onClick: ()=>scrollToRelease(release.slug),
                                    className: cn('docs-changelog-nav-item block w-full text-left px-3 py-2 text-sm rounded-md transition-all duration-200', activeVersion === release.version ? 'docs-changelog-nav-item-active bg-primary/10 text-primary font-medium' : 'text-muted-foreground hover:text-foreground hover:bg-muted'),
                                    children: /*#__PURE__*/ _jsxs("span", {
                                        className: "flex items-center gap-2",
                                        children: [
                                            release.version,
                                            index === 0 && /*#__PURE__*/ _jsx("span", {
                                                className: "text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary",
                                                children: "Latest"
                                            })
                                        ]
                                    })
                                }, release.version))
                        })
                    ]
                })
            })
        ]
    });
}
