/* Refer & Earn — two tabs: Free reviews (give 50/get 50) + Cash earnings */
const REF_LINK = 'reviewbuddie.com/r/BRONTIX50';
const REFS = [
  { name:'Kavya Home Labs', date:'Jul 18, 2026', status:'Rewarded' },
  { name:'Nutriblend Foods', date:'Jul 11, 2026', status:'On trial' },
  { name:'Zesta Cosmetics',  date:'Jul 02, 2026', status:'Signed up' },
  { name:'UrbanPaws',        date:'Jun 24, 2026', status:'Invited' },
];
const LEDGER = [
  { name:'Kavya Home Labs', plan:'Growth · ₹2,499/mo', amt:'₹500', state:'Available', date:'Jul 20', via:'link' },
  { name:'Nutriblend Foods', plan:'Starter · ₹999/mo', amt:'₹200', state:'Pending', date:'Jul 12', via:'code' },
];
const PARTNER_CODE = 'BRONTIX40';
const refStatusCls = {
  Rewarded:  'bg-emerald-50 text-emerald-700',
  'On trial':'bg-sky-50 text-sky-700',
  'Signed up':'bg-amber-50 text-amber-700',
  Invited:   'bg-gray-100 text-gray-500',
};
function CopyLinkCard() {
  const [copied, setCopied] = React.useState(false);
  const copy = () => { try { navigator.clipboard.writeText('https://' + REF_LINK); } catch(e){}; setCopied(true); setTimeout(()=>setCopied(false), 1800); };
  const share = (label) => window.rbToast ? window.rbToast(`Opening ${label} share (demo)`) : null;
  return (
    <Card className="p-6">
      <p className="text-[13px] font-bold text-ink flex items-center gap-2">Your referral link <InfoTip text="Your unique invite link for other sellers — rewards are credited automatically when they upgrade to a paid plan."/></p>
      <p className="text-[12px] text-ink-muted mt-0.5">Share it with other sellers — you both get <span className="font-bold text-ink">+50 free reviews</span> when they upgrade to a paid plan.</p>
      <div className="mt-4 flex flex-col sm:flex-row gap-2.5">
        <div className="flex-1 flex items-center px-4 h-11 rounded-xl bg-surface-subtle border border-line text-[13.5px] font-semibold text-ink truncate">{REF_LINK}</div>
        <button onClick={copy} className={"h-11 px-5 rounded-xl text-[13px] font-bold text-white transition shrink-0 " + (copied ? 'bg-emerald-500' : 'bg-gradient-to-b from-brand to-brand-dark shadow-btn hover:shadow-lg')}>{copied ? 'Copied ✓' : 'Copy link'}</button>
      </div>
      <div className="mt-3 flex items-center gap-2">
        {['WhatsApp','Email','X'].map(s => (
          <button key={s} onClick={()=>share(s)} className="px-3.5 py-1.5 rounded-lg border border-line text-[12px] font-semibold text-ink-muted hover:text-ink hover:border-gray-300 transition">{s}</button>
        ))}
      </div>
    </Card>
  );
}
function RefStat({ label, value, sub }) {
  return (
    <Card className="p-5">
      <p className="text-[11.5px] font-semibold uppercase tracking-wider text-ink-muted">{label}</p>
      <p className="text-[26px] font-extrabold text-ink mt-1 leading-none">{value}</p>
      {sub && <p className="text-[11.5px] text-ink-soft mt-1.5">{sub}</p>}
    </Card>
  );
}
function HowItWorksStrip({ steps }) {
  return (
    <Card className="p-5">
      <div className="grid sm:grid-cols-3 gap-4">
        {steps.map((s,i)=>(
          <div key={i} className="flex items-start gap-3">
            <span className="w-7 h-7 rounded-full acc-bg text-white text-[12px] font-bold flex items-center justify-center shrink-0">{i+1}</span>
            <div>
              <p className="text-[13px] font-bold text-ink leading-tight">{s.t}</p>
              <p className="text-[12px] text-ink-muted mt-0.5 leading-snug">{s.d}</p>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}
function ReferralsTab() {
  return (
    <div className="space-y-5">
      <HowItWorksStrip steps={[
        { t:'Share your link', d:'Send it to seller friends on WhatsApp or email.' },
        { t:'They go paid', d:'They sign up and upgrade to any paid plan.' },
        { t:'You both earn', d:'+50 free reviews credited to both accounts.' },
      ]}/>
      <CopyLinkCard/>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <RefStat label="Invites sent" value="12"/>
        <RefStat label="Signed up" value="4"/>
        <RefStat label="Went paid" value="2"/>
        <RefStat label="Reviews earned" value="100" sub="+50 per paid signup"/>
      </div>
      <Card className="overflow-hidden">
        <div className="grid items-center gap-3 px-5 py-3 bg-surface-subtle text-[11px] font-semibold uppercase tracking-wider text-ink-muted" style={{gridTemplateColumns:'1.4fr 1fr 110px'}}>
          <span>Seller</span><span>Joined</span><span>Status</span>
        </div>
        <div className="divide-y divide-gray-100">
          {REFS.map((r,i)=>(
            <div key={i} className="grid items-center gap-3 px-5 py-3.5" style={{gridTemplateColumns:'1.4fr 1fr 110px'}}>
              <p className="text-[13px] font-bold text-ink truncate">{r.name}</p>
              <p className="text-[12.5px] text-ink-muted">{r.date}</p>
              <span className={"inline-flex justify-center px-2.5 py-1 rounded-full text-[11px] font-bold " + refStatusCls[r.status]}>{r.status}</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}
function PartnerLinkCard() {
  const [copied, setCopied] = React.useState(false);
  const copy = () => { try { navigator.clipboard.writeText('https://reviewbuddie.com/p/BRONTIX'); } catch(e){}; setCopied(true); setTimeout(()=>setCopied(false), 1800); };
  return (
    <Card className="p-6">
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <p className="text-[13px] font-bold text-ink flex items-center gap-2">Your partner link <InfoTip text="Your affiliate link — unlike the referral link, every paid signup through it earns you cash commission for 12 months."/></p>
          <p className="text-[12px] text-ink-muted mt-0.5">Separate from your free-reviews link — every paid signup through it earns you commission for 12 months.</p>
        </div>
        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[11px] font-bold">20% × 12 months commission</span>
      </div>
      <div className="mt-4 flex flex-col sm:flex-row gap-2.5">
        <div className="flex-1 flex items-center px-4 h-11 rounded-xl bg-surface-subtle border border-line text-[13.5px] font-semibold text-ink truncate">reviewbuddie.com/p/BRONTIX</div>
        <button onClick={copy} className={"h-11 px-5 rounded-xl text-[13px] font-bold text-white transition shrink-0 " + (copied ? 'bg-emerald-500' : 'bg-gradient-to-b from-brand to-brand-dark shadow-btn hover:shadow-lg')}>{copied ? 'Copied ✓' : 'Copy link'}</button>
      </div>
    </Card>
  );
}
function TierCard() {
  const active = 7, goal = 100;
  const pct = Math.min(100, Math.round(active/goal*100));
  return (
    <Card className="p-6">
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <div>
          <p className="text-[13px] font-bold text-ink flex items-center gap-2">Commission tier <InfoTip text="Your current commission rate. Reaching the active-seller goal moves you to a higher rate for future signups."/></p>
          <p className="text-[12px] text-ink-muted mt-0.5">You earn <span className="font-bold text-ink">20% for 12 months</span> on every referred seller. Cross <span className="font-bold text-ink">100 active paid sellers</span> and it becomes <span className="font-bold text-ink">30%</span> — for all of them.</p>
        </div>
        <div className="text-right">
          <p className="text-[22px] font-extrabold text-ink leading-none">{active}<span className="text-[13px] text-ink-muted font-semibold"> / {goal}</span></p>
          <p className="text-[11px] text-ink-soft mt-1">active paid sellers</p>
        </div>
      </div>
      <div className="mt-4 h-2.5 rounded-full bg-surface-subtle overflow-hidden">
        <div className="h-full rounded-full acc-bg transition-all" style={{width: pct + '%'}}></div>
      </div>
      <div className="mt-2 flex justify-between text-[11px] font-semibold text-ink-soft">
        <span>20% tier</span><span>{goal - active} more to unlock 30%</span>
      </div>
    </Card>
  );
}
function CouponsCard() { return null; }
function SectionLabel({ children }) {
  return <p className="text-[11.5px] font-bold uppercase tracking-[0.12em] text-ink-soft pt-2">{children}</p>;
}
function ColHeader({ title, sub }) {
  return (
    <div className="pb-1">
      <p className="text-[14px] font-extrabold text-ink">{title}</p>
      <p className="text-[12px] text-ink-muted mt-0.5">{sub}</p>
    </div>
  );
}
function EarningsTab({ onNav }) {
  const toast = (m) => window.rbToast ? window.rbToast(m) : null;
  const [copied, setCopied] = React.useState(null);
  const copy = (key, text) => { try { navigator.clipboard.writeText(text); } catch(e){}; setCopied(key); setTimeout(()=>setCopied(null), 1800); };
  const active = 7, goal = 100, pct = Math.round(active/goal*100);
  return (
    <div className="space-y-5">
      {/* earnings summary band */}
      <Card className="p-0 overflow-hidden">
        <div className="px-6 py-5 text-white" style={{background:'linear-gradient(150deg,var(--sidebar-bg,#0E1A24),#173042)'}}>
          <div className="flex items-center justify-between gap-6 flex-wrap">
            <div className="flex items-stretch gap-8 flex-wrap">
              {[['Available to withdraw','₹500','ready for payout'],['Pending','₹200','clears in 30 days'],['Lifetime earned','₹1,900','across 2 sellers']].map(([label,value,sub],i)=>(
                <div key={label} className={"flex flex-col justify-between " + (i>0 ? 'pl-8 border-l border-white/10' : '')}>
                  <p className="text-[11px] font-bold uppercase tracking-[0.12em] text-white/50 whitespace-nowrap">{label}</p>
                  <p className={"font-extrabold leading-none mt-2 whitespace-nowrap " + (i===0 ? 'text-[30px]' : 'text-[22px] text-white/90')}>{value}</p>
                  <p className="text-[11px] font-semibold text-white/45 mt-1.5 whitespace-nowrap">{sub}</p>
                </div>
              ))}
            </div>
            <div className="flex items-center gap-2.5">
              <button onClick={()=>toast('Withdrawal requested (demo)')} className="h-10 px-5 rounded-full text-[13px] font-bold text-ink bg-white hover:bg-white/90 transition shadow-sm whitespace-nowrap">Withdraw ₹500</button>
              <button onClick={()=>onNav && onNav('settings:payouts')} className="h-10 px-4 rounded-full text-[13px] font-bold text-white/80 border border-white/25 hover:bg-white/10 transition whitespace-nowrap">Payout settings</button>
            </div>
          </div>
        </div>
        {/* tier progress strip */}
        <div className="px-6 py-3.5 flex items-center gap-4 bg-surface-subtle border-t border-line/60">
          <p className="text-[12.5px] font-bold text-ink whitespace-nowrap">20% commission × 12 months</p>
          <div className="flex-1 h-2 rounded-full bg-white border border-line overflow-hidden min-w-[120px]"><div className="h-full rounded-full acc-bg" style={{width:pct+'%'}}></div></div>
          <p className="text-[12px] text-ink-muted whitespace-nowrap"><span className="font-bold text-ink">{active}/{goal}</span> active sellers · {goal-active} more unlocks <span className="font-bold text-ink">30%</span></p>
        </div>
      </Card>

      <div className="grid lg:grid-cols-5 gap-5 items-start">
        {/* Left — share tools */}
        <div className="lg:col-span-3 space-y-5">
          <Card className="p-6">
            <p className="text-[13px] font-bold text-ink flex items-center gap-2 whitespace-nowrap">Share your link or code <InfoTip text="Link and code carry the same offer and the same credit to you — the code is for channels where links don't work."/></p>
            <p className="text-[12px] text-ink-muted mt-1">They get <span className="font-bold text-ink">40% off their first month</span> (monthly plans); every paid signup earns you 20% of their plan, monthly, for 12 months.</p>
            <div className="mt-4 flex flex-col sm:flex-row gap-2.5">
              <div className="flex-1 flex items-center px-4 h-11 rounded-xl bg-surface-subtle border border-line text-[13.5px] font-semibold text-ink truncate">reviewbuddie.com/p/BRONTIX</div>
              <button onClick={()=>copy('link','https://reviewbuddie.com/p/BRONTIX')} className={"h-11 px-5 rounded-xl text-[13px] font-bold text-white transition shrink-0 whitespace-nowrap " + (copied==='link' ? 'bg-emerald-500' : 'bg-gradient-to-b from-brand to-brand-dark shadow-btn hover:shadow-lg')}>{copied==='link' ? 'Copied ✓' : 'Copy link'}</button>
            </div>
            <div className="mt-5 pt-5 border-t border-line/70">
              <div className="flex items-center justify-between gap-3">
                <p className="text-[12px] font-bold uppercase tracking-[0.1em] text-ink-soft">Or your coupon code</p>
                <button onClick={()=>toast('Code change request sent (demo)')} className="text-[12px] font-bold acc-text hover:opacity-80">Request custom code</button>
              </div>
              <div className="mt-3 flex items-center gap-3 flex-wrap">
                <button onClick={()=>copy('code', PARTNER_CODE)} className="px-4 py-2 rounded-lg border border-dashed border-brand/50 bg-brand/5 text-brand text-[14px] font-extrabold tracking-wide hover:bg-brand/10 transition whitespace-nowrap">{copied==='code' ? 'Copied ✓' : PARTNER_CODE}</button>
                <p className="flex-1 text-[12px] text-ink-muted min-w-[180px] leading-snug">Same offer, same credit to you — use it where links don't work: podcasts, videos, stories. New accounts only, monthly plans.</p>
              </div>
            </div>
          </Card>
        </div>
        {/* Right — commissions ledger */}
        <Card className="lg:col-span-2 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-line flex items-center justify-between gap-3">
            <p className="text-[13px] font-bold text-ink flex items-center gap-2 whitespace-nowrap">Recent commissions <InfoTip text="Commissions earned per referred seller — amounts stay Pending for 30 days after their payment, then become Available."/></p>
            <button onClick={()=>onNav && onNav('settings:payouts')} className="text-[12px] font-bold acc-text hover:opacity-80 whitespace-nowrap">Full ledger →</button>
          </div>
          <div className="divide-y divide-gray-100">
            {LEDGER.map((r,i)=>(
              <div key={i} className="flex items-center gap-3 px-5 py-3.5">
                <div className="min-w-0 flex-1">
                  <p className="text-[13px] font-bold text-ink truncate">{r.name}</p>
                  <p className="text-[11.5px] text-ink-soft truncate">{r.plan} · via {r.via}</p>
                </div>
                <p className="text-[13px] font-bold text-ink">{r.amt}</p>
                <span className={"inline-flex justify-center px-2 py-1 rounded-full text-[11px] font-bold " + (r.state==='Available' ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700')}>{r.state}</span>
              </div>
            ))}
          </div>
          <div className="px-5 py-4 bg-surface-subtle border-t border-line/60">
            <p className="text-[12px] text-ink-muted leading-relaxed">Commissions stay <span className="font-bold text-ink">Pending for 30 days</span> after the referred seller's payment, then move to Available.</p>
          </div>
        </Card>
      </div>
      <HowItWorksStrip steps={[
        { t:'Share your link or code', d:'Same offer either way — they get 40% off their first month on monthly plans.' },
        { t:'They subscribe', d:'You earn 20% of their plan, every month, for 12 months.' },
        { t:'Grow to 30%', d:'Cross 100 active paid sellers and all commissions jump to 30%.' },
      ]}/>
    </div>
  );
}
function ReferEarn({ onNav }) {
  const [tab, setTab] = React.useState('refs');
  return (
    <>
      <PageHeader title="Refer & Earn"/>
      <div className="px-7 py-6 space-y-5 max-w-[1120px]">
        <div className="inline-flex p-1 rounded-xl bg-surface-subtle border border-line gap-1">
          {[['refs','Free reviews'],['cash','Partner program']].map(([id,label])=>(
            <button key={id} onClick={()=>setTab(id)} className={"px-4 py-2 rounded-lg text-[13px] font-bold transition " + (tab===id ? 'bg-white text-ink shadow-soft' : 'text-ink-muted hover:text-ink')}>{label}</button>
          ))}
        </div>
        {tab==='refs' ? <ReferralsTab/> : <EarningsTab onNav={onNav}/>}
      </div>
    </>
  );
}
Object.assign(window, { ReferEarn });
