(async()=>{"use strict";const O="https://chatgpt.com",qs=new URLSearchParams(location.search),CODE=(qs.get("promoCode")||"").trim(),COUPON=CODE||"team-1-month-free",SEATS=[5,2,1],CUR={US:"USD",JP:"JPY",GB:"GBP",AU:"AUD",CA:"CAD",SG:"SGD",MY:"MYR",TH:"THB",PH:"PHP",ID:"IDR",IN:"INR",BR:"BRL",MX:"MXN",NZ:"NZD",ZA:"ZAR",KR:"KRW",TW:"TWD",AE:"AED",TR:"TRY",PL:"PLN",CZ:"CZK",HU:"HUF",RO:"RON",BG:"BGN",DK:"DKK",SE:"SEK",NO:"NOK",CH:"CHF",IL:"ILS",DE:"EUR",FR:"EUR",IT:"EUR",ES:"EUR",NL:"EUR",IE:"EUR",AT:"EUR",BE:"EUR",PT:"EUR",FI:"EUR",GR:"EUR",SK:"EUR",SI:"EUR",LT:"EUR",LV:"EUR",EE:"EUR",LU:"EUR",MT:"EUR",CY:"EUR",HR:"EUR"};
const log=(...a)=>console.log("[Business]",...a),warn=(...a)=>console.warn("[Business]",...a),err=(...a)=>console.error("[Business]",...a);
const entry=CODE?`${O}/?promoCode=${encodeURIComponent(CODE)}#pricing`:`${O}/?promo_campaign=${COUPON}#pricing`;
if(location.origin!==O){location.href=entry;return}
let token;try{token=(await fetch("/api/auth/session",{credentials:"include"}).then(r=>r.json())).accessToken}catch(e){}
if(!token){warn("Sign in first, then paste again.");return}
const H={"Content-Type":"application/json","oai-language":navigator.language||"en-US",Authorization:"Bearer "+token};
let me={};try{me=await fetch("/backend-api/me",{headers:H}).then(r=>r.json())}catch(e){}
let country="";try{const t=await fetch("/cdn-cgi/trace").then(r=>r.text());country=(t.match(/\nloc=([A-Z]{2})/)||[])[1]||""}catch(e){}
if(!country)country=me.country||"";country=(country||"US").toUpperCase();
const currencies=Array.from(new Set(["USD",CUR[country]||"USD"]));log("account",me.email||"?","| exit",country,"| currencies",currencies.join("→"));
if(!CODE){try{const s=await fetch(`/backend-api/promo_campaign/check_coupon?coupon=${encodeURIComponent(COUPON)}&is_coupon_from_query_param=true`,{headers:H}).then(r=>r.json());log("coupon state:",s.state);if(s.state!=="eligible")warn("This account needs another try — steps below.")}catch(e){}}
const build=(seats,currency)=>({entry_point:"team_workspace_purchase_modal",plan_name:"chatgptteamplan",team_plan_data:{workspace_name:"Team "+Math.random().toString(36).slice(2,6).toUpperCase(),price_interval:"month",seat_quantity:seats,seat_quantities:[{seat_type:"default",quantity:seats},{seat_type:"prolite",quantity:0}]},billing_details:{country,currency},supports_saved_payment_link:true,checkout_ui_mode:"custom",checkout_source:"chatgpt_web_merged",checkout_appearance:"dark",purchase_attempt_id:crypto.randomUUID(),cancel_url:entry,...(CODE?{promo_code:CODE}:{promo_campaign:{promo_campaign_id:COUPON,is_coupon_from_query_param:true}})});
let ok=null,last="";
outer:for(const seats of SEATS)for(const currency of currencies){log("try",seats,"seats /",currency);let r,j={};try{r=await fetch(`${O}/backend-api/payments/checkout`,{method:"POST",credentials:"include",headers:H,body:JSON.stringify(build(seats,currency))});j=await r.json().catch(()=>({}))}catch(e){last=e.message;continue}
if(r.ok&&j.checkout_session_id){ok={seats,currency,id:j.checkout_session_id};break outer}last=`${r.status} ${j.detail||JSON.stringify(j).slice(0,80)}`;warn("↳",last);if(r.status===401){warn("Token stale — reload and retry.");return}if(/seat/i.test(last))break}
if(!ok){err("Try the account ladder:",last);return}
const url=`${O}/checkout/openai_llc/${ok.id}?source=chatgpt_web_merged&price_interval=month&${CODE?`promo_code=${encodeURIComponent(CODE)}`:`promo_campaign=${encodeURIComponent(COUPON)}`}`;
let d={};try{d=await fetch(`${O}/backend-api/payments/checkout/openai_llc/${ok.id}?supports_business_seat_offer=true`,{headers:H}).then(r=>r.json())}catch(e){}
const applied=!!(d.promo_campaign||d.promo_code||d.immediate_discount_settings||d.scheduled_discount_preview);
applied?log("✅ coupon attached — total must be 0"):warn(`Original price on this link — the $0 receipt is the goal, run the account ladder`);
try{await navigator.clipboard.writeText(url)}catch(e){}
log(`RESULT ${applied?"APPLIED":"NOT_APPLIED"} | ${ok.seats} seats | ${ok.currency} | ${country}`);log("Link copied:\n",url)})();