/* ─── Pricing / upgrade modal — v2 (premium) ─────────────────────────────────
   Dark hero header (headline + billing toggle + plan-fit slider) with cards
   overlapping the edge; recommended card inverts to the accent gradient.
   Opened via window.__openPricing(). */

const PLANS_V2 = [
  { name:'Starter',    reviews:50,  bonus:60,  USD:{m:29,a:15},  INR:{m:1499,a:799} },
  { name:'Growth',     reviews:250, bonus:300, USD:{m:79,a:39},  INR:{m:3999,a:1999}, popular:true },
  { name:'Pro',        reviews:700, bonus:840, USD:{m:149,a:89}, INR:{m:7499,a:4499} },
  { name:'Enterprise', reviews:Infinity, bonus:null, USD:{m:299,a:199}, INR:{m:14999,a:9999} },
];
const CUR_V2 = { USD:{sym:'$', fmt:n=>'$'+n.toLocaleString('en-US')}, INR:{sym:'₹', fmt:n=>'₹'+n.toLocaleString('en-IN')} };
const SHARED_FEATURES = ['All Marketplaces','Unlimited Surveys','Unlimited Products','Unlimited Giveaways','Unlimited Users','All Integrations'];
const fmtN = n => n === Infinity ? 'Unlimited' : n.toLocaleString();

function PlanCardV2({ p, annual, cur, highlight, badge, discount }) {
  const C = CUR_V2[cur];
  const price = p[cur];
  const base = annual ? price.a : price.m;
  const mo = discount ? Math.round(base*(1-discount)) : base;
  const shownReviews = annual && p.bonus ? p.bonus : p.reviews;
  const perReview = p.reviews === Infinity ? null : (mo / shownReviews);
  return (
    <div className={"relative rounded-2xl p-5 flex flex-col gap-4 transition-all duration-300 "+(highlight
      ? "text-white shadow-pop lg:scale-[1.04] lg:-translate-y-1"
      : "bg-white border border-line shadow-card")}
      style={highlight ? {background:'linear-gradient(160deg,var(--accent),var(--accent-dark))'} : {}}>
      {badge && (
        <span className={"absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.08em] whitespace-nowrap shadow-sm "+(highlight?"bg-white acc-text":"bg-ink text-white")}>{badge}</span>
      )}
      <div className="flex items-center justify-between">
        <p className={"text-[13px] font-bold "+(highlight?"text-white":"text-ink")}>{p.name}</p>
        {perReview && <span className={"text-[10px] font-bold px-2 py-0.5 rounded-full "+(highlight?"bg-white/15 text-white":"bg-brand-50 text-brand")}>{C.sym}{perReview.toFixed(2)}/review</span>}
      </div>
      <div>
        <p className={"text-[30px] font-extrabold tracking-tight leading-none "+(highlight?"text-white":"text-ink")}>
          {fmtN(shownReviews)}
        </p>
        <p className={"text-[11.5px] font-bold uppercase tracking-[0.1em] mt-1.5 "+(highlight?"text-white/70":"text-ink-soft")}>reviews {p.reviews!==Infinity && '/ month'}{annual && p.bonus ? ' · +20% bonus' : ''}</p>
      </div>
      <div className={"pt-4 border-t "+(highlight?"border-white/20":"border-line/70")}>
        <div className="flex items-baseline gap-2">
          <span className={"text-[24px] font-extrabold "+(highlight?"text-white":"text-ink")}>{C.fmt(mo)}</span>
          <span className={"text-[12px] "+(highlight?"text-white/70":"text-ink-muted")}>/mo</span>
          {(annual || discount) && <span className={"text-[12px] line-through "+(highlight?"text-white/50":"text-ink-soft")}>{C.fmt(price.m)}</span>}
        </div>
        <p className={"text-[11px] mt-0.5 "+(highlight?"text-white/70":"text-ink-soft")}>{discount ? <span className="font-bold">coupon applied · {Math.round(discount*100)}% off</span> : annual ? <>billed annually · <span className="font-bold">save {C.fmt((price.m-price.a)*12)}/yr</span></> : 'billed monthly'}</p>
      </div>
      <button className={"mt-auto w-full rounded-full py-2.5 text-[13px] font-bold transition-all "+(highlight
        ? "bg-white acc-text hover:bg-white/90 shadow-sm"
        : "text-ink border border-line bg-white hover:border-ink-soft hover:bg-surface-subtle")}>
        Choose {p.name}
      </button>
    </div>
  );
}

const COUPONS_V2 = { 'WELCOME20':.2, 'DIWALI30':.3, 'BUDDIE10':.1 };

function PricingModal({ onClose }) {
  const [annual, setAnnual] = React.useState(true);
  const [cur, setCur] = React.useState('INR');
  const [code, setCode] = React.useState('');
  const [coupon, setCoupon] = React.useState(null); // {code, off}
  const [cErr, setCErr] = React.useState(false);
  const applyCoupon = () => {
    const k = code.trim().toUpperCase(); if(!k) return;
    if (COUPONS_V2[k]) { setCoupon({ code:k, off:COUPONS_V2[k] }); setCErr(false); }
    else { setCoupon(null); setCErr(true); }
  };
  const showHelper = window.__pricingHelper !== false;
  const [vol, setVol] = React.useState(showHelper ? 250 : null);
  const recommended = vol !== null ? (PLANS_V2.find(p => p.reviews >= vol) || PLANS_V2[PLANS_V2.length-1]) : null;
  React.useEffect(() => {
    const h = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h); return () => document.removeEventListener('keydown', h);
  }, []);
  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center bg-ink/50 backdrop-blur-[2px] overflow-y-auto py-8 px-4" onClick={onClose}>
      <div className="bg-white rounded-3xl shadow-pop w-full max-w-5xl overflow-hidden relative" onClick={e=>e.stopPropagation()}>

        {/* ── dark hero header ── */}
        <div className="relative px-8 pt-8 pb-24 text-center"
             style={{background:'var(--sidebar-bg,#0E1A24)'}}>
          <div className="absolute inset-0 pointer-events-none" aria-hidden="true"
               style={{backgroundImage:'radial-gradient(rgba(255,255,255,.05) 1px, transparent 1px)', backgroundSize:'20px 20px'}}></div>
          <div className="absolute -top-24 left-1/2 -translate-x-1/2 w-[560px] h-[300px] rounded-full pointer-events-none" aria-hidden="true"
               style={{background:'radial-gradient(ellipse, var(--accent-ring) 0%, transparent 65%)'}}></div>
          <button onClick={onClose} className="absolute top-5 right-5 w-9 h-9 rounded-full text-white/50 hover:text-white hover:bg-white/10 flex items-center justify-center transition-colors z-10">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 6l12 12M18 6L6 18" strokeLinecap="round"/></svg>
          </button>
          <div className="relative">
            <p className="text-[11px] font-bold uppercase tracking-[0.2em] acc-text mb-3" style={{color:'var(--accent-light,#8B79EC)'}}>Upgrade</p>
            <h2 className="text-[26px] font-extrabold tracking-tight text-white leading-tight">Powerful plans for every stage<br className="hidden sm:block"/> of your seller journey</h2>

            {/* region + billing toggles */}
            <div className="flex justify-center items-center gap-3 mt-6 flex-wrap">
              <div className="inline-flex items-center gap-1 bg-white/10 rounded-full p-1">
                <button onClick={()=>setCur('INR')} className={"whitespace-nowrap px-4 py-2 rounded-full text-[13px] font-bold transition-colors "+(cur==='INR'?"bg-white text-ink shadow-sm":"text-white/60 hover:text-white")}>🇮🇳 India</button>
                <button onClick={()=>setCur('USD')} className={"whitespace-nowrap px-4 py-2 rounded-full text-[13px] font-bold transition-colors "+(cur==='USD'?"bg-white text-ink shadow-sm":"text-white/60 hover:text-white")}>🌍 Global</button>
              </div>
              <div className="inline-flex items-center gap-1 bg-white/10 rounded-full p-1">
                <button onClick={()=>setAnnual(false)} className={"whitespace-nowrap px-4 py-2 rounded-full text-[13px] font-bold transition-colors "+(!annual?"bg-white text-ink shadow-sm":"text-white/60 hover:text-white")}>Monthly</button>
                <button onClick={()=>setAnnual(true)} className={"whitespace-nowrap px-4 py-2 rounded-full text-[13px] font-bold transition-colors "+(annual?"bg-white text-ink shadow-sm":"text-white/60 hover:text-white")}>Annual <span className="acc-text">· +20%</span></button>
              </div>
            </div>

            {/* coupon */}
            <div className="flex justify-center items-center gap-2 mt-5 flex-wrap">
              {coupon ? (
                <span className="inline-flex items-center gap-2 text-[12px] font-bold px-3.5 py-2 rounded-full bg-green-400/15 text-green-300 border border-green-400/30">
                  🎟 {coupon.code} · {Math.round(coupon.off*100)}% off applied
                  <button onClick={()=>{setCoupon(null);setCode('');}} className="text-green-300/60 hover:text-green-300"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6"><path d="M6 6l12 12M18 6L6 18" strokeLinecap="round"></path></svg></button>
                </span>
              ) : (
                <div className="inline-flex items-center gap-1 bg-white/10 rounded-full p-1">
                  <input value={code} onChange={e=>{setCode(e.target.value);setCErr(false);}} onKeyDown={e=>e.key==='Enter'&&applyCoupon()} placeholder="Coupon code"
                    className="w-36 h-8 rounded-full px-4 text-[12px] font-bold uppercase tracking-wide text-white placeholder:normal-case placeholder:font-medium placeholder:text-white/40 bg-transparent outline-none"/>
                  <button onClick={applyCoupon} disabled={!code.trim()} className="h-8 px-4 rounded-full text-[12px] font-bold bg-white text-ink shadow-sm disabled:opacity-40 whitespace-nowrap">Apply</button>
                </div>
              )}
              {cErr && <span className="text-[12px] font-bold text-red-400">Invalid code</span>}
            </div>

            {/* plan-fit slider */}
            {showHelper && (
              <div className="mt-7 max-w-md mx-auto text-left">
                <div className="flex items-baseline justify-between gap-3">
                  <p className="text-[12.5px] font-semibold text-white/80 whitespace-nowrap">Reviews you collect monthly</p>
                  <p className="text-[15px] font-extrabold text-white whitespace-nowrap">{vol >= 750 ? '700+' : vol}</p>
                </div>
                <input type="range" min="25" max="775" step="25" value={vol} onChange={e=>setVol(+e.target.value)}
                  className="w-full mt-2 accent-[var(--accent)]"/>
              </div>
            )}
          </div>
        </div>

        {/* ── cards overlapping the hero ── */}
        <div className="px-8 -mt-16 relative">
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {PLANS_V2.map(p => {
              const isRec = recommended ? recommended.name === p.name : p.popular;
              return <PlanCardV2 key={p.name} p={p} annual={annual} cur={cur} highlight={isRec} discount={coupon?coupon.off:0}
                badge={isRec ? (recommended ? 'Recommended for you' : 'Most popular') : null}/>;
            })}
          </div>
        </div>

        {/* ── footer ── */}
        <div className="px-8 pb-7 pt-5">
          <div className="rounded-2xl border border-line bg-surface-subtle px-5 py-3.5 flex items-center justify-between gap-3 flex-wrap">
            <p className="text-[12.5px] text-ink-muted"><span className="font-bold text-ink">You're on the Free plan</span> — 10 reviews per month, no credit card required.</p>
            <span className="inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full bg-green-50 text-green-700"><span className="w-1.5 h-1.5 rounded-full bg-green-500"></span>Current plan</span>
          </div>
          <div className="mt-5 pt-5 border-t border-line/70">
            <p className="text-[11px] font-bold uppercase tracking-[0.12em] text-ink-soft text-center mb-3">Every subscription includes</p>
            <div className="flex flex-wrap justify-center gap-x-6 gap-y-2">
              {SHARED_FEATURES.map(f => (
                <span key={f} className="inline-flex items-center gap-1.5 text-[12.5px] text-ink-muted">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" className="text-brand"><path d="M5 12l5 5L20 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>{f}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PricingModalHost() {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => { window.__openPricing = () => setOpen(true); return () => { delete window.__openPricing; }; }, []);
  return open ? <PricingModal onClose={()=>setOpen(false)}/> : null;
}

window.PricingModalHost = PricingModalHost;
{
  const el = document.createElement('div');
  document.body.appendChild(el);
  ReactDOM.createRoot(el).render(<PricingModalHost/>);
}
