import { useMatches } from "@tanstack/react-router";
import { useMemo } from "react";
import { HeaderConfig } from "../types/header-config";

export const defaultHeaderConfig: HeaderConfig = {
  title: 'FLXN',
  withBackButton: false,
  collapsed: false,
}

const useRouterConfig = () => {
  const matches = useMatches();

  return useMemo(() => {
    const matchesWithHeader = matches.filter((match) =>
      match?.loaderData && 'header' in match.loaderData
    );

    const headerConfig = matchesWithHeader.reduce<HeaderConfig>((acc, match) => {
      const loaderData = match?.loaderData;
      if (loaderData && typeof loaderData === 'object' && 'header' in loaderData) {
        const header = loaderData.header;
        if (header && typeof header === 'object') {
          return {
            ...acc,
            ...(header as HeaderConfig),
          }
        }
      }
      return acc;
    }, defaultHeaderConfig);

    const current = matches[matches.length - 1]?.loaderData;

    return {
      header: headerConfig,
      refresh: current && typeof current === 'object' && 'refresh' in current ? current.refresh : [],
      withPadding: current && typeof current === 'object' && 'withPadding' in current ? current.withPadding : true,
      fullWidth: current && typeof current === 'object' && 'fullWidth' in current ? current.fullWidth : false,
    };
  }, [matches]);
}

export default useRouterConfig;
