/**
 * Utility for managing portal selection cookies
 */

export const portals = {
  general: {
    url: 'https://app.codeframeai.com',
    name: 'General AI Portal',
    cookieValue: 'general'
  },
  education: {
    url: 'https://education.codeframeai.com',
    name: 'Education Portal',
    cookieValue: 'education'
  },
  research: {
    url: 'https://mr.codeframeai.com',
    name: 'Market Research Portal',
    cookieValue: 'research'
  }
};

export const setPortalCookie = (value: string, days: number = 365) => {
  if (typeof window === 'undefined') return;

  const expires = new Date();
  expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));

  const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
  let cookieString = `selectedPortal=${value};expires=${expires.toUTCString()};path=/`;

  if (!isLocalhost) {
    cookieString += `;domain=.codeframeai.com`;
  }

  document.cookie = cookieString;
};

export const getPortalCookie = () => {
  if (typeof window === 'undefined') return null;

  const nameEQ = "selectedPortal=";
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
};

export const handleSignupFlow = () => {
  return '/products';
};

export const handleLoginFlow = () => {
  if (typeof window === 'undefined') return 'https://app.codeframeai.com';

  const portalValue = getPortalCookie();

  if (portalValue && portals[portalValue as keyof typeof portals]) {
    return portals[portalValue as keyof typeof portals].url;
  } else {
    return '/products';
  }
};

