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

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

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

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

  const headerConfig = matchesWithHeader.reduce((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,
        }
      }
    }
    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,
  };
}

export default useRouterConfig;
