export type StyleSheet<T extends Record<string, unknown>> = T & Record<string, Record<string, unknown>>;

/**
 * Creates a proxy that resolves responsive style variants at access time.
 * @param sheet
 */
export const createStyles = <T extends Record<string, unknown>>(sheet: StyleSheet<T>): T =>
    new Proxy(sheet, {
        get: (target: StyleSheet<T>, property: string | symbol, receiver: unknown) =>
        {
            if (typeof property !== 'string')
            {
                return Reflect.get(target, property, receiver);
            }

            const medias = getMedia(target).filter((media) =>
            {
                if (!Object.prototype.hasOwnProperty.call(target[media], property))
                {
                    return false;
                }

                return matchMedia(media).matches;
            });

            if (medias.length === 0)
            {
                return target[property as keyof StyleSheet<T>];
            }

            return target[medias[medias.length - 1]][property];
        },
    }) as T;

function getMedia<T extends Record<string, unknown>>(target: StyleSheet<T>): string[]
{
    const properties = Object.keys(target);
    const regex = /\(.*\)/;

    return properties.filter((property) => regex.test(property));
}
