<script lang="ts">
  import { browser } from '$app/environment';
  import { setSidebarContext, type SidebarContextValue, type SidebarProps } from './context.svelte.js';

  let {
    variant = 'sidebar',
    collapsible = 'offcanvas',
    side = 'left',
    open = $bindable(false),
    openMobile = $bindable(false),
    children,
  }: SidebarProps & {
    open?: boolean;
    openMobile?: boolean;
    children?: import('svelte').Snippet;
  } = $props();

  let isMobile = $state(false);

  if (browser) {
    const mq = window.matchMedia('(max-width: 767px)');
    isMobile = mq.matches;
    const handler = (e: MediaQueryListEvent) => (isMobile = e.matches);
    mq.addEventListener('change', handler);
  }

  const setOpen = (v: boolean) => (open = v);
  const setOpenMobile = (v: boolean) => (openMobile = v);
  const toggleSidebar = () => {
    if (isMobile) {
      setOpenMobile(!openMobile);
    } else {
      setOpen(!open);
    }
  };

  const ctx: SidebarContextValue = {
    get state() {
      return open ? 'expanded' : 'collapsed';
    },
    get open() {
      return open;
    },
    setOpen,
    get openMobile() {
      return openMobile;
    },
    setOpenMobile,
    get isMobile() {
      return isMobile;
    },
    variant,
    collapsible,
    side,
    toggleSidebar,
  };
  setSidebarContext(ctx);
</script>

{@render children?.()}