/**
 * Copyright 2025 Wingify Software Pvt. Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from 'react';

interface VWOScriptProps {
  accountId: string;
  type?: 'ASYNC' | 'SYNC';
  settingsTimeout?: number;
  hideElement?: string;
  hideElementStyle?: string;
  scriptAttributes?: React.ScriptHTMLAttributes<HTMLScriptElement>;
  linkAttributes?: React.LinkHTMLAttributes<HTMLLinkElement>;
}

export const VWOScript: React.FC<VWOScriptProps> = ({
  accountId,
  type = 'ASYNC',
  settingsTimeout = 2000,
  hideElement = 'body',
  hideElementStyle = 'opacity:0 !important;filter:alpha(opacity=0) !important;background:none !important',
  scriptAttributes = {},
  linkAttributes = {},
}) => {
  try {
    const scriptType = typeof type === 'string' ? type.toLowerCase() : 'async';
    const smartCode = `window._vwo_code||(function(){var w=window,d=document;var account_id=${accountId},version=2.2,settings_tolerance=${settingsTimeout},hide_element='${hideElement}',hide_element_style='${hideElementStyle}';if(f=!1,v=d.querySelector('#vwoCode'),cc={},-1<d.URL.indexOf('__vwo_disable__')||w._vwo_code)return;try{var e=JSON.parse(localStorage.getItem('_vwo_'+account_id+'_config'));cc=e&&'object'==typeof e?e:{}}catch(e){}function r(t){try{return decodeURIComponent(t)}catch(e){return t}}var s=(()=>{var e={combination:[],combinationChoose:[],split:[],exclude:[],uuid:null,consent:null,optOut:null},t=d.cookie||'';if(t)for(var i,n,o=/(?:^|;\\s*)(?:(_vis_opt_exp_(\\d+)_combi=([^;]*))|(_vis_opt_exp_(\\d+)_combi_choose=([^;]*))|(_vis_opt_exp_(\\d+)_split=([^:;]*))|(_vis_opt_exp_(\\d+)_exclude=[^;]*)|(_vis_opt_out=([^;]*))|(_vwo_global_opt_out=[^;]*)|(_vwo_uuid=([^;]*))|(_vwo_consent=([^;]*)))/g;null!==(i=o.exec(t));)try{i[1]?e.combination.push({id:i[2],value:r(i[3])}):i[4]?e.combinationChoose.push({id:i[5],value:r(i[6])}):i[7]?e.split.push({id:i[8],value:r(i[9])}):i[10]?e.exclude.push({id:i[11]}):i[12]?e.optOut=r(i[13]):i[14]?e.optOut=!0:i[15]?e.uuid=r(i[16]):i[17]&&(n=r(i[18]),e.consent=n&&3<=n.length?n.substring(0,3):null)}catch(e){}return e})();function n(){var e=(()=>{if(w.VWO&&Array.isArray(w.VWO))for(var e=0;e<w.VWO.length;e++){var t=w.VWO[e];if(Array.isArray(t)&&('setVisitorId'===t[0]||'setSessionId'===t[0]))return!0}return!1})(),t='a='+account_id+'&u='+encodeURIComponent(w._vis_opt_url||d.URL)+'&vn='+version+'&ph=1'+('undefined'!=typeof platform?'&p='+platform:'')+'&st='+w.performance.now(),e=(!e&&((e=(()=>{var e,t=[],i={},n=w.VWO&&w.VWO.appliedCampaigns||{};for(e in n){var o=n[e]&&n[e].v;o&&(t.push(e+'-'+o+'-1'),i[e]=!0)}if(s&&s.combination)for(var r=0;r<s.combination.length;r++){var a=s.combination[r];i[a.id]||t.push(a.id+'-'+a.value)}return t.join('|')})())&&(t+='&c='+e),(e=(()=>{var e=[],t={};if(s&&s.combinationChoose)for(var i=0;i<s.combinationChoose.length;i++){var n=s.combinationChoose[i];e.push(n.id+'-'+n.value),t[n.id]=!0}if(s&&s.split)for(var o=0;o<s.split.length;o++)t[(n=s.split[o]).id]||e.push(n.id+'-'+n.value);return e.join('|')})())&&(t+='&cc='+e),e=(()=>{var e={},t=[];if(w.VWO&&Array.isArray(w.VWO))for(var i=0;i<w.VWO.length;i++){var n=w.VWO[i];if(Array.isArray(n)&&'setVariation'===n[0]&&n[1]&&Array.isArray(n[1]))for(var o=0;o<n[1].length;o++){var r,a=n[1][o];a&&'object'==typeof a&&(r=a.e,a=a.v,r)&&a&&(e[r]=a)}}for(r in e)t.push(r+'-'+e[r]);return t.join('|')})())&&(t+='&sv='+e),s&&s.optOut&&(t+='&o='+s.optOut),(()=>{var e=[],t={};if(s&&s.exclude)for(var i=0;i<s.exclude.length;i++){var n=s.exclude[i];t[n.id]||(e.push(n.id),t[n.id]=!0)}return e.join('|')})());return e&&(t+='&e='+e),s&&s.uuid&&(t+='&id='+s.uuid),s&&s.consent&&(t+='&consent='+s.consent),w.name&&-1<w.name.indexOf('_vis_preview')&&(t+='&pM=true'),w.VWO&&w.VWO.ed&&(t+='&ed='+w.VWO.ed),t}code={nonce:v&&v.nonce,library_tolerance:function(){return'undefined'!=typeof library_tolerance?library_tolerance:void 0},settings_tolerance:function(){return cc.sT||settings_tolerance},hide_element_style:function(){return'{'+(cc.hES||hide_element_style)+'}'},hide_element:function(){return performance.getEntriesByName('first-contentful-paint')[0]?'':'string'==typeof cc.hE?cc.hE:hide_element},getVersion:function(){return version},finish:function(e){var t;f||(f=!0,(t=d.getElementById('_vis_opt_path_hides'))&&t.parentNode.removeChild(t),e&&((new Image).src='https://dev.visualwebsiteoptimizer.com/ee.gif?a='+account_id+e))},finished:function(){return f},addScript:function(e){var t=d.createElement('script');t.type='text/javascript',e.src?t.src=e.src:t.text=e.text,v&&t.setAttribute('nonce',v.nonce),d.getElementsByTagName('head')[0].appendChild(t)},load:function(e,t){t=t||{};var i=new XMLHttpRequest;i.open('GET',e,!0),i.withCredentials=!t.dSC,i.responseType=t.responseType||'text',i.onload=function(){if(t.onloadCb)return t.onloadCb(i,e);200===i.status?w._vwo_code.addScript({text:i.responseText}):w._vwo_code.finish('&e=loading_failure:'+e)},i.onerror=function(){if(t.onerrorCb)return t.onerrorCb(e);w._vwo_code.finish('&e=loading_failure:'+e)},i.send()},init:function(){var e,t,i=this.settings_tolerance(),i=(w._vwo_settings_timer=setTimeout(function(){w._vwo_code.finish()},i),'body'!==this.hide_element()?(e=d.createElement('style'),t=(i=this.hide_element())?i+this.hide_element_style():'',i=d.getElementsByTagName('head')[0],e.setAttribute('id','_vis_opt_path_hides'),v&&e.setAttribute('nonce',v.nonce),e.setAttribute('type','text/css'),e.styleSheet?e.styleSheet.cssText=t:e.appendChild(d.createTextNode(t)),i.appendChild(e)):(e=d.getElementsByTagName('head')[0],(t=d.createElement('div')).style.cssText='z-index: 2147483647 !important;position: fixed !important;left: 0 !important;top: 0 !important;width: 100% !important;height: 100% !important;background:white!important;',t.setAttribute('id','_vis_opt_path_hides'),t.classList.add('_vis_hide_layer'),e.parentNode.insertBefore(t,e.nextSibling)),'https://dev.visualwebsiteoptimizer.com/j.php?'+n());-1!==w.location.search.indexOf('_vwo_xhr')?this.addScript({src:i}):this.load(i+'&x=true',{l:1})}};w._vwo_code=code;code.init();})();(function(){var t=window;function d(){var e;t._vwo_code&&(e=d.hidingStyle=document.getElementById('_vis_opt_path_hides')||d.hidingStyle,t._vwo_code.finished()||t._vwo_code.libExecuted||t.VWO&&t.VWO.dNR||(document.getElementById('_vis_opt_path_hides')||document.getElementsByTagName('head')[0].appendChild(e),requestAnimationFrame(d)))}d();})();`;

    if (!accountId) {
      console.error('VWO: Account ID is required');
      return null;
    }

    if (scriptType !== 'async' && scriptType !== 'sync') {
      console.error('VWO: Invalid type. Must be either "ASYNC" or "SYNC"');
      return null;
    }

    if (scriptType === 'sync') {
      return (
        <script
          {...scriptAttributes}
          referrerPolicy="no-referrer-when-downgrade"
          id="vwoCode"
          src={`https://dev.visualwebsiteoptimizer.com/lib/${accountId}.js`}
        />
      );
    }

    return (
      <>
        <link
          rel="preconnect"
          href="https://dev.visualwebsiteoptimizer.com"
          {...linkAttributes}
        />
        <script
          {...scriptAttributes}
          type="text/javascript"
          id="vwoCode"
          dangerouslySetInnerHTML={{ __html: smartCode }}
        />
      </>
    );
  } catch (e) {
    console.error('VWO Script Error:', e);
    return null;
  }
};
