import React from 'react';
import Script from 'next/script';
import { DEFAULT_CLIENT_SIDE_API_URL, DEFAULT_CLIENT_SIDE_SCRIPT_URL } from './constants';

/**
 * Options defines the configuration options for DataDome JavaScript Tag.
 */
type Options = Record<string, unknown> & { endpoint?: string };

/**
 * DataDomeComponentProps defines the properties for the DataDomeComponent.
 * @property {string} clientSideKey - The client-side key for DataDome.
 * @property {Options} [options] - Additional options for DataDome.
 * @property {string} [tagsUrl] - The URL for the DataDome tags script.
 */
interface ComponentProps {
    clientSideKey: string;
    options?: Options;
    tagsUrl?: string;
}

/**
 * DataDomeComponent is a React component that loads the DataDome JavaScript Tag.
 */
export const DataDomeComponent: React.FC<ComponentProps> = ({
    clientSideKey,
    options = {},
    tagsUrl = DEFAULT_CLIENT_SIDE_SCRIPT_URL,
}: {
    clientSideKey: string;
    options?: Options;
    tagsUrl?: string;
}) => {
    const mergedOptions: Options = {
        ...options,
        endpoint: options.endpoint ?? DEFAULT_CLIENT_SIDE_API_URL,
    };

    const jsTagOptions = `
        window.ddjskey = '${clientSideKey}';
        window.ddoptions = ${JSON.stringify(mergedOptions)};
    `;

    return (
        <>
            <Script id="jstag-options" strategy="beforeInteractive">
                {jsTagOptions}
            </Script>
            <Script src={tagsUrl} strategy="beforeInteractive" />
        </>
    );
};
