---
import type { MarkdownHeading } from 'astro';
import type { HTMLAttributes } from 'astro/types';

interface Links extends MarkdownHeading, HTMLAttributes<'a'> {};

export interface Props extends HTMLAttributes<'ol'> {
    url?: string;
    headings?: Array<Links>;
    depth?: number;
    max?: number;
}

const {
    url=Astro.url.pathname,
    headings=[],
    depth=1,
    max=6,
    ...attrs
} = Astro.props

const equalDepth = headings.filter(h => h.depth === +depth);
---

<ol {...attrs} data-depth={depth}>
    { equalDepth.map((heading, i) => {
        const { slug, text, depth: _depth, ..._attrs} = heading
        const start = headings.indexOf(heading) + 1
        const end = headings.indexOf(equalDepth[i + 1])
        const subHeadings = headings.slice(start, end === -1 ? undefined : end)
        const _props = { 
            url, 
            headings: subHeadings, 
            depth: _depth + 1,
            max
        }
        return <li>
            <a {...{href: `${url}#${slug}`, ..._attrs}}>{text}</a>
            <Astro.self {..._props}/>
        </li>
    })}
</ol>