---
import type { SectionConfig } from '@/types/shared';
import Typography from './typography.astro';

export interface Props extends SectionConfig {
  className?: string;
  hideTitle?: boolean;
}

const { title, slug, hideTitle, className, visible } = Astro.props;
---

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

<script>
  import hashState from '@/web/utils/hash-state';
  import throttle from '@/web/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>
