---
import { type Hierarchy } from "../lib/hierarchy.ts";
import { makeHierarchy } from '../lib/hierarchy';
import { getCollection } from 'astro:content';

interface Props {
  prefix: string;
	hierarchy?: Hierarchy;
}

const { prefix, hierarchy: maybeHierarchy} = Astro.props;

const hierarchy = maybeHierarchy ?? makeHierarchy((await getCollection('notes')).map(note => [note.id, note.data.title]));


const pathname = Astro.url.pathname.replace(import.meta.env.BASE_URL, '/');

---
{
  Object.entries(hierarchy).map(([leader, node]) => {
    const notePath = `${prefix}/${leader}`;
    const isActive = pathname === notePath;
    const linkClasses = isActive ? "active" : "";

    if (node.children) {
        return (
        <details open={pathname.startsWith(notePath) && "true"}>
          <summary>
            { node.id
              ? <a href={notePath} class={linkClasses}>{node.title || leader}</a>
              : <span class="header-only">{node.title || leader}</span>
            }
          </summary>
          <div class="child-notes">
            { <Astro.self prefix={notePath} hierarchy={node.children} /> }
          </div>
        </details>
      );
    }

    return (
      <div>
        <a href={notePath} class={linkClasses}>
          {node.title || leader}
        </a>
      </div>
      );
  })
}

<style>
.active {
  font-weight: bold;
}

.child-notes {
  margin-left: 1em;
}

summary {
  .header-only {
    color: var(--color-gray)
  }

  &:hover {
    color: var(--color-gold);
  }
}

</style>
