---
import type { SectionKey } from '@/types/data';

import Typography from './typography.astro';

export interface Props {
  section: SectionKey;
  title?: string;
  className?: string;
}

const { section, title, className } = Astro.props;
---

<div
  data-type="section"
  id={section}
  class:list={['flex flex-col gap-6 rounded-2xl bg-white p-8 shadow-md dark:bg-gray-800', className]}
>
  {
    title && (
      <Typography variant="section-title" id={`${section}-heading`}>
        {title}
      </Typography>
    )
  }
  <slot />
</div>

<script>
  import hashState from '@/utils/hash-state';
  import throttle from '@/utils/throttle';

  const sections = [...document.querySelectorAll('[data-type="section"]')];

  const isInUpperView = (section: Element) => section.getBoundingClientRect().bottom >= window.innerHeight / 3;

  const updateHash = () => {
    const currentSection = sections.find(isInUpperView);

    if (currentSection) {
      hashState.updateHash(currentSection.id);
    }
  };

  document.addEventListener('scroll', throttle(updateHash, 200));
</script>
