/**
 * Client-only cookie utilities.
 * Import as: import { ... } from '@/lib/cookies/client'
 *
 * Uses js-cookie under the hood — never call js-cookie (Cookies.*) or
 * document.cookie directly; always go through these functions.
 *
 * All functions are client-only: they guard against server-side execution and
 * must only be called inside client components or useEffect hooks.
 */
import Cookies from 'js-cookie';

import { COLOR_SCHEME_COOKIE_OPTIONS, COOKIE_NAMES, type CookieOptions } from './constants';

function toJsCookieAttributes(options: CookieOptions): Cookies.CookieAttributes {
  const attrs: Cookies.CookieAttributes = {};
  if (options.path !== undefined) attrs.path = options.path;
  if (options.maxAge !== undefined) attrs.expires = new Date(Date.now() + options.maxAge * 1000);
  if (options.sameSite !== undefined) attrs.sameSite = options.sameSite;
  if (options.secure !== undefined) attrs.secure = options.secure;
  return attrs;
}

/**
 * Read a cookie by name.
 * Returns undefined when the cookie is absent or when called on the server.
 */
export function getClientCookie(name: string): string | undefined {
  if (typeof document === 'undefined') return undefined;
  return Cookies.get(name);
}

/**
 * Write a cookie.
 * Defaults to the standard 1-year / SameSite=Lax options.
 */
export function setClientCookie(
  name: string,
  value: string,
  options: CookieOptions = COLOR_SCHEME_COOKIE_OPTIONS,
): void {
  if (typeof document === 'undefined') return;
  Cookies.set(name, value, toJsCookieAttributes(options));
}

/**
 * Delete a cookie.
 */
export function deleteClientCookie(name: string, path = '/'): void {
  if (typeof document === 'undefined') return;
  Cookies.remove(name, { path });
}

/**
 * Read the persisted MUI color scheme from document.cookie.
 * Returns 'light' when the cookie is absent.
 */
export function getColorSchemeCookie(): 'light' | 'dark' {
  const value = getClientCookie(COOKIE_NAMES.COLOR_SCHEME);
  return value === 'dark' ? 'dark' : 'light';
}
