import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';

export type Density = 'comfortable' | 'compact';

export const DENSITY_KEY = 'liderra:density';

export interface DensityHandle {
    density: Ref<Density>;
    rowHeight: ComputedRef<number>;
    setDensity: (d: Density) => void;
    toggle: () => void;
}

function loadInitial(): Density {
    if (typeof localStorage === 'undefined') return 'comfortable';
    const raw = localStorage.getItem(DENSITY_KEY);
    return raw === 'compact' ? 'compact' : 'comfortable';
}

export function useDensity(): DensityHandle {
    const density = ref<Density>(loadInitial());

    const rowHeight = computed<number>(() => (density.value === 'compact' ? 36 : 44));

    function setDensity(d: Density): void {
        density.value = d;
    }

    function toggle(): void {
        density.value = density.value === 'comfortable' ? 'compact' : 'comfortable';
    }

    watch(
        density,
        (v) => {
            if (typeof localStorage !== 'undefined') {
                localStorage.setItem(DENSITY_KEY, v);
            }
        },
        { flush: 'sync' },
    );

    return { density, rowHeight, setDensity, toggle };
}
