import React, { createContext, useContext } from 'react';
import type { SectionContextProps, SectionLevel } from './types';

const SectionContext = createContext<SectionContextProps | undefined>(undefined);

const defaultProps: SectionContextProps = {
    expandable: false,
    level: 'top',
};

export const useSectionContext = (): SectionContextProps =>
    useContext(SectionContext) ?? defaultProps;

export const getLevel = (parentLevel?: SectionLevel): SectionLevel => {
    if (parentLevel === 'top') return 'sub';
    if (parentLevel === 'sub') return 'nested';
    if (parentLevel === 'nested') {
        console.error(
            'Section hierarchy too deep. Nested sections should not contain other sections.'
        );
        return 'nested';
    }
    return 'top';
};

export interface SectionProviderProps extends Partial<SectionContextProps> {
    children: React.ReactNode;
}

export const SectionProvider = ({ children, ...contextProps }: SectionProviderProps) => {
    const parentContext = useContext(SectionContext);
    const level = getLevel(parentContext?.level);

    const context = {
        expandable: false,
        level,
        ...contextProps,
    };

    return <SectionContext.Provider value={context}>{children}</SectionContext.Provider>;
};
