/**
 * Minimal in-house cookie helper for the public front-end.
 *
 * Replaces the old `$.cookie` plugin (formerly `core/js/plugins/mtc_cookies.js`).
 * Same surface as the common third-party libs: get / set / remove with options.
 *
 * Zero external dependencies.
 */

/**
 * Reads a cookie value, or `undefined` if not set.
 *
 * @param {string} name
 * @returns {string | undefined}
 */
export function get(name) {
    if (!document.cookie) {
        return undefined;
    }

    const cookies = document.cookie.split('; ');
    for (const cookie of cookies) {
        const eq = cookie.indexOf('=');
        if (eq < 0) {
            continue;
        }
        const key = decodeURIComponent(cookie.slice(0, eq));
        if (key === name) {
            try {
                return decodeURIComponent(cookie.slice(eq + 1));
            } catch (err) {
                return cookie.slice(eq + 1);
            }
        }
    }
    return undefined;
}

/**
 * Writes a cookie.
 *
 * @param {string} name
 * @param {string} value
 * @param {{
 *   expires?: number | Date,
 *   path?: string,
 *   domain?: string,
 *   secure?: boolean,
 *   sameSite?: 'Strict' | 'Lax' | 'None',
 * }} [options]
 */
export function set(name, value, options = {}) {
    const parts = [
        `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
    ];

    if (typeof options.expires === 'number') {
        // Days from now — matches the old `$.cookie` plugin's semantics.
        const expiresAt = new Date();
        expiresAt.setTime(expiresAt.getTime() + options.expires * 86400000);
        parts.push(`expires=${expiresAt.toUTCString()}`);
    } else if (options.expires instanceof Date) {
        parts.push(`expires=${options.expires.toUTCString()}`);
    }

    if (options.path) {
        parts.push(`path=${options.path}`);
    }
    if (options.domain) {
        parts.push(`domain=${options.domain}`);
    }
    if (options.secure) {
        parts.push('secure');
    }
    if (options.sameSite) {
        parts.push(`SameSite=${options.sameSite}`);
    }

    document.cookie = parts.join('; ');
}

/**
 * Removes a cookie. `path` / `domain` must match the values used when the
 * cookie was set, otherwise the browser will not clear it.
 *
 * @param {string} name
 * @param {{ path?: string, domain?: string }} [options]
 */
export function remove(name, options = {}) {
    set(name, '', { ...options, expires: -1 });
}
