"use client"
import { Button } from "@/components/ui/buttons/Button";
import { CustomCard } from "@/components/ui/cards";
import { MainLogo } from "@/components/ui/Logos";
import { H5, S } from "@/components/ui/typography";
import { useTranslations } from "next-intl";
import React, { useEffect, useState } from "react";

interface HeadingData {
    text: string;
    id: string;
    level: number;
}

const BlogSidebar = ({ content }: { content: string }) => {
    const [headings, setHeadings] = useState<HeadingData[]>([]);
    const [activeId, setActiveId] = useState<string | null>(null);

    useEffect(() => {
        const tempHeadings: HeadingData[] = [];
        try {
            const parser = new DOMParser();
            const doc = parser.parseFromString(content, "text/html");

            // Select all heading levels you want to include
            const headingElements = Array.from(
                doc.querySelectorAll("h1, h2")
            ) as HTMLElement[];

            headingElements.forEach((element) => {
                const text = element.textContent?.trim() || '';
                const id = element.id ||
                    text.replace(/[^\w\s-]/g, '')
                        .replace(/\s+/g, '-')
                        .toLowerCase();

                // If element didn't have an ID, set it
                if (!element.id) {
                    element.id = id;
                }

                tempHeadings.push({
                    text,
                    id,
                    level: parseInt(element.tagName.substring(1), 10)
                });
            });

            setHeadings(tempHeadings);
        } catch (error) {
            console.error("Error parsing headings:", error);
            setHeadings([]);
        }
    }, [content]);

    // Add intersection observer for active heading highlight
    useEffect(() => {
        if (headings.length === 0) return;

        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
                        setActiveId(entry.target.id);
                    }
                });
            },
            {
                rootMargin: '0px 0px -50% 0px',
                threshold: [0, 0.5, 1]
            }
        );

        headings.forEach(({ id }) => {
            const element = document.getElementById(id);
            if (element) {
                observer.observe(element);
            }
        });

        return () => {
            headings.forEach(({ id }) => {
                const element = document.getElementById(id);
                if (element) {
                    observer.unobserve(element);
                }
            });
        };
    }, [headings]);

    // Smooth scroll with offset for fixed headers
    const handleClick = (e: React.MouseEvent, id: string) => {
        e.preventDefault();
        const element = document.getElementById(id);
        if (element) {
            const offset = 100; // Adjust based on your header height
            const top = element.getBoundingClientRect().top + window.pageYOffset - offset;
            window.scrollTo({ top, behavior: 'smooth' });
        }
    };
    const t = useTranslations()
    return (
        <div className="top-20 max-h-[calc(100vh-5rem)]   border-gray-200 sticky lg:w-[400px]">
            <div className="border-l px-4">
                <h3 className="text-xl font-bold mb-4 text-gray-800  ">{t("Content")}</h3>
                <ul className="space-y-2 mb-6">
                    {headings.map((heading, index) => (
                        <li
                            key={index}
                            className={`ml-${(heading.level - 2) * 4} ${activeId === heading.id ? 'text-primary font-medium' : 'text-gray-600'
                                }`}
                        >
                            <a
                                href={`#${heading.id}`}
                                onClick={(e) => handleClick(e, heading.id)}
                                className="hover:underline text-sm transition-colors duration-300 max-xl:text-[10px]"
                            >
                                {heading.text}
                            </a>
                        </li>
                    ))}
                </ul>
            </div>

            {/* CTA Box */}
            <CustomCard className="border-none shadow-lg shadow-black/15 flex flex-col gap-4 rounded-md p-6 mt-10 mb-5">
                <MainLogo />
                <div className="flex flex-col gap-1">
                    <H5>{t("Start your journey now")}</H5>
                    <S className="text-gray-500 !font-normal">{t("In few clicks start your journey with dadycar now")}</S>
                </div>
                <Button>{t("Get my demo")}</Button>
            </CustomCard>
        </div>
    );
};

export default BlogSidebar;