export const saveCampaign = (pageTemplate, isTest = false) => {
  if (typeof window !== 'undefined') {
    let params = new URLSearchParams(document.location.search.substring(1));
    if (isTest) {
      params = new URLSearchParams('?campaign=campaign&channel=channel');
    }
    const campaign = params.get('campaign');
    const channel = params.get('channel');
    const thirtyDays = 2592000000;
    const now = new Date().getTime();

    // Store pageType
    localStorage.setItem('pageTemplate', pageTemplate);

    // Add to local storage
    if (campaign && channel) {
      // Remove old params
      if (localStorage.getItem('providerCampaign') || localStorage.getItem('providerChannel')) {
        localStorage.removeItem('providerCampaign');
        localStorage.removeItem('providerChannel');
        localStorage.removeItem('providerExpiry');
      }

      // Add new params
      localStorage.setItem('providerCampaign', campaign);
      localStorage.setItem('providerChannel', channel);
      localStorage.setItem('providerExpiry', now + thirtyDays);

      // Remove if expired
      if (now > localStorage.expiry) {
        localStorage.removeItem('providerCampaign');
        localStorage.removeItem('providerChannel');
        localStorage.removeItem('providerExpiry');
      }
    }
  }
};

export const getLink = (provider, pageTemplate) => {
  const campaign = localStorage.getItem('providerCampaign');
  const channel = localStorage.getItem('providerChannel');
  if (
    campaign &&
    channel &&
    provider.links?.campaigns[campaign] &&
    provider.links?.campaigns[campaign][channel]
  ) {
    return provider.links.campaigns[campaign][channel];
  }
  if (pageTemplate === 'event') {
    return provider.links.static.event_page || provider?.links?.static?.default;
  }
  if (pageTemplate === 'live_stream_providers') {
    return provider.links.static.provider_page || provider?.links?.static?.default;
  }
  return provider?.links?.static?.default;
};
