const PROFILE_COOKIE_NAME = 'singlechat_profile';
const PROFILE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;

function readCookie(name) {
  const prefix = `${name}=`;
  const cookie = document.cookie
    .split('; ')
    .find((entry) => entry.startsWith(prefix));

  return cookie ? cookie.slice(prefix.length) : null;
}

export function readProfileCookie() {
  const cookieValue = readCookie(PROFILE_COOKIE_NAME);
  if (!cookieValue) return null;

  try {
    return JSON.parse(decodeURIComponent(cookieValue));
  } catch (error) {
    console.warn('Profil-Cookie konnte nicht gelesen werden:', error);
    return null;
  }
}

export function writeProfileCookie(profile) {
  const normalizedProfile = {
    nickname: typeof profile.nickname === 'string' ? profile.nickname.trim() : '',
    gender: typeof profile.gender === 'string' ? profile.gender : '',
    age: Number(profile.age) || 18,
    country: typeof profile.country === 'string' ? profile.country : ''
  };

  document.cookie = [
    `${PROFILE_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(normalizedProfile))}`,
    `Max-Age=${PROFILE_COOKIE_MAX_AGE}`,
    'Path=/',
    'SameSite=Lax'
  ].join('; ');
}
