'use client';

import { ShareContentType } from '@/utils/share';

declare global {
  interface Window {
    AF_SMART_SCRIPT: {
      generateOneLinkURL: (config: {
        oneLinkURL: string;
        webReferrer: string;
        afParameters: {
          mediaSource: {
            keys: string[];
            defaultValue: string;
          };
          campaign: {
            keys: string[];
            defaultValue: string;
          };
          googleClickIdKey: string;
          afSub2: {
            keys: string[];
          };
          afCustom: Array<{
            paramKey: string;
            keys?: string[];
            defaultValue?: string;
          }>;
        };
      }) => { clickURL: string };
    };
  }
}

const AF_ONELINK_URL = 'https://suno.onelink.me/BYx9/';

const getOneLinkUrl = ({
  contentType,
  contentId,
}: {
  contentType: ShareContentType;
  contentId: string;
}) => {
  if (
    typeof window === 'undefined' ||
    !window.AF_SMART_SCRIPT ||
    !window.AF_SMART_SCRIPT.generateOneLinkURL
  ) {
    return AF_ONELINK_URL;
  }

  //Initializing Smart Script arguments
  const webReferrer = 'web_referrer';
  const mediaSource = { keys: ['utm_source'], defaultValue: 'Direct' };
  const campaign = { keys: ['utm_campaign'], defaultValue: 'None' };
  const googleClickIdKey = 'af_sub1';
  const afSub2 = { keys: ['fbclid'] };
  const sh = { paramKey: 'sh', keys: ['sh'] };
  const sct = { paramKey: 'sct', keys: ['sct'], defaultValue: contentType };
  const scid = { paramKey: 'scid', keys: ['scid'], defaultValue: contentId };
  const custom_ss_ui = { paramKey: 'af_ss_ui', defaultValue: 'true' };

  //Call the function after embedding the code through a global parameter on the window object called window.AF_SMART_SCRIPT.
  //Onelink URL is generated.
  const result = window.AF_SMART_SCRIPT.generateOneLinkURL({
    oneLinkURL: AF_ONELINK_URL,
    webReferrer: webReferrer,
    afParameters: {
      mediaSource: mediaSource,
      campaign: campaign,
      googleClickIdKey: googleClickIdKey,
      afSub2: afSub2,
      afCustom: [sh, sct, scid, custom_ss_ui],
    },
  });

  return result.clickURL;
  // If needed, you can download the script from: https://onelinksmartscript.appsflyer.com/onelink-smart-script-latest.js

  // See an example of implementation and how to place the URL result behind a CTA on your website: https://appsflyersdk.github.io/appsflyer-onelink-smart-script/examples/utm_parameters.html?utm_campaign=mycmpn&utm_source=mysource

  // See an example of how to display a QR code: https://appsflyersdk.github.io/appsflyer-onelink-smart-script/examples/qr_code.html?inmedia=my_email&incmp=my_campaign
};

export { getOneLinkUrl };
