/* ============================================================
   CRUIG — Billing: Checkout, Paywall, PlanView, Affiliates
   ============================================================ */

/* ---------- Checkout (Stripe Payment Links) ---------- */
function Checkout({role, planId, onClose, onDone}){
  const plans = CRUIG.PLANS[role];
  const [sel, setSel] = useState(planId || 's');
  const [demoStage, setDemoStage] = useState(null); // null | processing | done
  const [userId, setUserId] = useState(null);
  const plan = plans.find(p=>p.id===sel);
  const roleLabel = role==='creator'?'Criador':'Empresa';

  // Usuário logado → liga o pagamento Stripe à conta (client_reference_id)
  useEffect(()=>{
    CruigAPI.get('/auth/me').then(({user})=> user && setUserId(user.id)).catch(()=>{});
  },[]);

  /* Abre o Payment Link real da Stripe em nova aba, já vinculado ao usuário logado.
     O campo "plan" usado pelo webhook (ver worker/src/routes/stripe.js) vem do
     metadata configurado em cada Payment Link no painel Stripe (ex: plan=creator:s) —
     query params só suportam client_reference_id / prefilled_email. */
  const payWithStripe = ()=>{
    if(!plan.stripeLink) return;
    const url = new URL(plan.stripeLink);
    if(userId) url.searchParams.set('client_reference_id', userId);
    window.open(url.toString(), '_blank', 'noopener,noreferrer');
  };

  /* Simulação demo (sem cobrança real) */
  const runDemo = ()=>{
    setDemoStage('processing');
    setTimeout(()=>{ setDemoStage('done'); setTimeout(()=>{ onDone && onDone(); }, 1400); }, 1800);
  };

  return (
    <Modal open onClose={demoStage==='processing'?()=>{}:onClose} width={860} pad={false}>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', minHeight:500}} className="checkout-grid">

        {/* ── Lado esquerdo: resumo do plano ── */}
        <div style={{background:'var(--green-dark)', padding:34, color:'#fff', display:'flex', flexDirection:'column', borderRadius:'var(--r-xl) 0 0 var(--r-xl)'}}>
          <Logo variant="white" height={26}/>
          <div style={{marginTop:28, marginBottom:14}}>
            <span className="badge" style={{background:'rgba(255,255,255,.14)', color:'#fff'}}>Plano {roleLabel}</span>
          </div>
          <h2 style={{color:'#fff', fontSize:25, lineHeight:1.1, marginBottom:10}}>Assinatura {plan.name}</h2>
          <div style={{display:'flex', alignItems:'baseline', gap:6, margin:'6px 0 4px', whiteSpace:'nowrap'}}>
            <span style={{fontFamily:'var(--display)', fontWeight:700, fontSize:44, whiteSpace:'nowrap'}}>{CRUIG.brl(plan.price)}</span>
            <span style={{opacity:.7, fontSize:16}}>{plan.per}</span>
          </div>
          {plan.total
            ? <p style={{opacity:.75, fontSize:13.5}}>{CRUIG.brl(plan.total)} à vista · {plan.save}</p>
            : <p style={{opacity:.6, fontSize:13}}>Cobrança mensal · cancele quando quiser</p>}

          {/* selector de plano inline */}
          <div style={{display:'flex', gap:6, marginTop:22, marginBottom:18}}>
            {plans.map(p=>(
              <button key={p.id} onClick={()=>setSel(p.id)} style={{flex:1, padding:'9px 4px', borderRadius:10, textAlign:'center', border:'none', cursor:'pointer', transition:'all .15s',
                background: sel===p.id?'var(--lime)':'rgba(255,255,255,.1)', color: sel===p.id?'var(--green-dark)':'rgba(255,255,255,.85)'}}>
                <div style={{fontSize:12, fontWeight:700}}>{p.name}</div>
                <div style={{fontSize:11, opacity:.85, marginTop:2}}>{CRUIG.brl(p.price)}{p.per}</div>
              </button>
            ))}
          </div>

          <div style={{display:'flex', flexDirection:'column', gap:9}}>
            {(role==='creator'
              ?['Inscrições ilimitadas em campanhas','Mensagens ilimitadas com marcas','Perfil em destaque na busca','Afiliados — R$ 30 por indicação']
              :['Busca de criadores ilimitada','Campanhas ilimitadas','Mensagens ilimitadas','Filtros avançados de nicho e região']
            ).map((f,i)=>(
              <div key={i} style={{display:'flex', gap:9, alignItems:'center', fontSize:13.5, opacity:.93}}>
                <Icon name="check" size={15} sw={2.8} style={{color:'var(--lime)', flexShrink:0}}/>{f}
              </div>
            ))}
          </div>
          <div style={{marginTop:'auto', paddingTop:22, display:'flex', gap:8, alignItems:'center', opacity:.55, fontSize:12}}>
            <Icon name="lock" size={13}/> Pagamento processado pela Stripe · PCI-DSS
          </div>
        </div>

        {/* ── Lado direito: ação de pagamento ── */}
        <div style={{padding:36, position:'relative', display:'flex', flexDirection:'column', justifyContent:'center', borderRadius:'0 var(--r-xl) var(--r-xl) 0'}}>
          {demoStage==='done' ? (
            <div style={{textAlign:'center'}}>
              <div style={{width:78,height:78,borderRadius:'50%',background:'var(--lime)',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 18px', boxShadow:'var(--sh-lime)'}}><Icon name="check" size={40} sw={2.8} style={{color:'var(--green-dark)'}}/></div>
              <h3 style={{fontSize:23, marginBottom:8}}>Pagamento aprovado!</h3>
              <p className="faint" style={{fontSize:14}}>Plano {plan.name} ativado. Voltando ao painel…</p>
            </div>
          ) : (
            <>
              <button onClick={onClose} style={{position:'absolute', top:20, right:20, color:'var(--ink-faint)', padding:6}}><Icon name="close" size={20}/></button>

              <div style={{textAlign:'center', marginBottom:28}}>
                <h3 style={{fontSize:22, marginBottom:6}}>Finalizar assinatura</h3>
                <p className="faint" style={{fontSize:14}}>Plano {plan.name} · {CRUIG.brl(plan.price)}{plan.per}</p>
              </div>

              {/* ── BOTÃO REAL STRIPE ── */}
              <button
                className="btn btn-dark btn-block btn-lg"
                onClick={payWithStripe}
                style={{background:'#635bff', justifyContent:'center', gap:12, marginBottom:16, fontSize:17, padding:'17px 22px'}}>
                <StripeLogo/>
                Pagar com Stripe
                <Icon name="arrow" size={18}/>
              </button>

              <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:16}}>
                <div style={{flex:1, height:1, background:'var(--line)'}}></div>
                <span className="faint" style={{fontSize:12, fontWeight:600}}>aceita</span>
                <div style={{flex:1, height:1, background:'var(--line)'}}></div>
              </div>

              {/* métodos aceitos */}
              <div style={{display:'flex', gap:8, justifyContent:'center', marginBottom:22}}>
                {[['#eb001b/#f79e1b','Mastercard'],['#1a1f71/#1a1f71','Visa'],['Pix','#00b578'],['Boleto','#e17b00']].map(([c,l],i)=>(
                  <span key={i} style={{display:'flex', alignItems:'center', justifyContent:'center', padding:'5px 11px', borderRadius:8, border:'1px solid var(--line)', fontSize:11.5, fontWeight:700, color:'var(--ink-soft)', background:'#fff', gap:5}}>
                    {i===0 && <span style={{display:'inline-flex', gap:-4}}><span style={{width:18,height:12,borderRadius:2,background:'#eb001b',display:'inline-block'}}></span><span style={{width:18,height:12,borderRadius:2,background:'#f79e1b',display:'inline-block',marginLeft:-6,opacity:.9}}></span></span>}
                    {i===1 && <span style={{fontFamily:'var(--display)', fontWeight:800, color:'#1a1f71', fontSize:13}}>VISA</span>}
                    {i===2 && <span style={{color:'#00b578', fontWeight:800, fontSize:11}}>PIX</span>}
                    {i===3 && <span style={{color:'#e17b00', fontWeight:800, fontSize:10}}>BOLETO</span>}
                  </span>
                ))}
              </div>

              <div style={{padding:16, borderRadius:14, background:'var(--beige-deep)', border:'1px solid var(--beige-line)', marginBottom:18}}>
                <div style={{display:'flex', gap:10, alignItems:'flex-start'}}>
                  <Icon name="verified" size={17} style={{color:'var(--lime-700)', flexShrink:0, marginTop:1}}/>
                  <p style={{fontSize:13, lineHeight:1.55, color:'var(--ink-soft)'}}>
                    Você será redirecionado para a página de pagamento segura da <b style={{color:'var(--ink)'}}>Stripe</b>. Após a confirmação, seu plano é ativado automaticamente.
                  </p>
                </div>
              </div>

              {/* divisor demo */}
              <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:12}}>
                <div style={{flex:1, height:1, background:'var(--line)'}}></div>
                <span className="faint" style={{fontSize:11}}>ou</span>
                <div style={{flex:1, height:1, background:'var(--line)'}}></div>
              </div>
              <button
                className="btn btn-ghost btn-block btn-sm"
                onClick={runDemo}
                disabled={demoStage==='processing'}
                style={{fontSize:13, color:'var(--ink-faint)'}}>
                {demoStage==='processing'
                  ? <><span className="spin" style={{width:15,height:15,border:'2px solid rgba(0,0,0,.15)',borderTopColor:'var(--graphite)',borderRadius:'50%',display:'inline-block'}}></span>Simulando…</>
                  : '⚗️ Simular pagamento (demo do protótipo)'}
              </button>
            </>
          )}
        </div>
      </div>
    </Modal>
  );
}

/* Logo Stripe — wordmark tipográfico simples */
function StripeLogo(){
  return (
    <span style={{fontFamily:'var(--display)', fontWeight:700, fontSize:18, letterSpacing:'-.02em', color:'#fff', lineHeight:1}}>
      stripe
    </span>
  );
}

/* ---------- Paywall ---------- */
function Paywall({reason, onClose, onUpgrade}){
  return (
    <Modal open onClose={onClose} width={440}>
      <div style={{textAlign:'center'}}>
        <div style={{width:64,height:64,borderRadius:18,background:'var(--orange-100)',color:'var(--orange-600)',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 18px'}}><Icon name="lock" size={30}/></div>
        <h3 style={{fontSize:22, marginBottom:10}}>Hora de assinar</h3>
        <p className="muted" style={{fontSize:14.5, lineHeight:1.55, marginBottom:22}}>{reason}</p>
        <button className="btn btn-lime btn-block btn-lg" onClick={onUpgrade}><Icon name="bolt" size={17} fill/>Ver planos</button>
        <button className="btn btn-block" style={{marginTop:8, color:'var(--ink-soft)'}} onClick={onClose}>Agora não</button>
      </div>
    </Modal>
  );
}

/* ---------- Plan management view ---------- */
function PlanView({role, pro, onUpgrade, showToast}){
  const plans = CRUIG.PLANS[role];
  const history = [
    {date:'01 Jun 2026', desc:'Assinatura Anual', amount: role==='creator'?1164:1524, status:'Pago'},
    {date:'12 Mai 2026', desc:'Inscrição avulsa', amount:0, status:'Grátis'},
  ];
  return (
    <div style={{display:'flex', flexDirection:'column', gap:20, maxWidth:920}}>
      <div className="card card-pad" style={{display:'flex', alignItems:'center', gap:18, flexWrap:'wrap', background: pro?'linear-gradient(100deg,#fff,#f6fae5)':'#fff', border: pro?'1.5px solid var(--lime)':'1px solid var(--line)'}}>
        <div style={{width:50,height:50,borderRadius:14,background: pro?'var(--lime)':'var(--beige-deep)',color:'var(--green-dark)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}><Icon name={pro?'bolt':'lock'} size={24} fill={pro}/></div>
        <div style={{flex:1, minWidth:200}}>
          <h3 style={{fontSize:19}}>{pro? 'Plano Anual ativo' : 'Plano Grátis'}</h3>
          <p className="muted" style={{fontSize:14, marginTop:3}}>{pro? `Renova em 01 Jun 2027 · ${CRUIG.brl(plans[2].price)}/mês` : 'Recursos limitados. Assine para liberar tudo.'}</p>
        </div>
        {pro ? <button className="btn btn-ghost" onClick={()=>showToast && showToast('Gerenciamento de assinatura aberto.')}>Gerenciar</button> : <button className="btn btn-lime" onClick={()=>onUpgrade('s')}>Fazer upgrade</button>}
      </div>

      <div>
        <h3 style={{fontSize:18, marginBottom:14}}>Planos disponíveis</h3>
        <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16}} className="grid-3">
          {plans.map(p=>(
            <div key={p.id} className="card card-pad" style={{border: p.popular?'2px solid var(--lime)':'1px solid var(--line)', position:'relative'}}>
              {p.popular && <span className="badge badge-lime" style={{position:'absolute', top:-11, left:20}}>Recomendado</span>}
              <h4 style={{fontSize:17, marginBottom:8}}>{p.name}</h4>
              <div style={{display:'flex', alignItems:'baseline', gap:4}}><span style={{fontFamily:'var(--display)', fontWeight:700, fontSize:30, color:'var(--green-dark)'}}>{CRUIG.brl(p.price)}</span><span className="faint" style={{fontSize:13}}>{p.per}</span></div>
              <p className="faint" style={{fontSize:12.5, margintop:4, minHeight:18}}>{p.total? `${CRUIG.brl(p.total)} · ${p.save}`:'cobrança mensal'}</p>
              <button className={`btn btn-block ${p.popular?'btn-lime':'btn-ghost'}`} style={{marginTop:14}} onClick={()=>onUpgrade(p.id)}>Assinar</button>
            </div>
          ))}
        </div>
      </div>

      <div className="card card-pad">
        <h3 style={{fontSize:18, marginBottom:16}}>Histórico de pagamentos</h3>
        <table style={{width:'100%', borderCollapse:'collapse'}}>
          <thead><tr style={{textAlign:'left'}}>{['Data','Descrição','Valor','Status'].map(h=> <th key={h} style={{fontSize:12, fontWeight:700, color:'var(--ink-faint)', textTransform:'uppercase', letterSpacing:'.05em', padding:'0 0 12px'}}>{h}</th>)}</tr></thead>
          <tbody>
            {history.map((r,i)=>(
              <tr key={i} style={{borderTop:'1px solid var(--line)'}}>
                <td style={{padding:'13px 0', fontSize:14}}>{r.date}</td>
                <td style={{padding:'13px 0', fontSize:14, fontWeight:600, color:'var(--green-dark)'}}>{r.desc}</td>
                <td style={{padding:'13px 0', fontSize:14}} className="mono-num">{r.amount? CRUIG.brl(r.amount):'—'}</td>
                <td style={{padding:'13px 0'}}><span className={`badge ${r.status==='Pago'?'badge-lime':'badge-gray'}`}>{r.status}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------- Affiliates ---------- */
function Affiliates({showToast}){
  const [copied, setCopied] = useState(false);
  const link = 'cruig.com/r/marinalopes';
  const referrals = [
    {name:'Lara M.', date:'02 Jun', status:'Ativa', value:30},
    {name:'João P.', date:'28 Mai', status:'Ativa', value:30},
    {name:'Bruno S.', date:'21 Mai', status:'Ativa', value:30},
    {name:'Carla T.', date:'14 Mai', status:'Pendente', value:0},
    {name:'Igor F.', date:'09 Mai', status:'Ativa', value:30},
  ];
  const active = referrals.filter(r=>r.status==='Ativa').length;
  const copy = ()=>{ navigator.clipboard && navigator.clipboard.writeText('https://'+link); setCopied(true); showToast('Link copiado!'); setTimeout(()=>setCopied(false),2000); };
  return (
    <div style={{display:'flex', flexDirection:'column', gap:20, maxWidth:960}}>
      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr', gap:16}} className="grid-3">
        <div className="card card-pad" style={{background:'linear-gradient(115deg, var(--green-dark), #0a4f10)', color:'#fff', border:'none'}}>
          <span style={{fontSize:13, fontWeight:700, opacity:.8}}>Saldo disponível</span>
          <div style={{fontFamily:'var(--display)', fontWeight:700, fontSize:40, margin:'6px 0 14px'}}>R$ 240</div>
          <button className="btn btn-lime btn-sm" onClick={()=>showToast('Saque solicitado! Cai na conta em até 1 dia útil.')}><Icon name="cash" size={15}/>Sacar agora</button>
        </div>
        <Stat label="Indicações ativas" value={active} icon="users"/>
        <Stat label="Total ganho" value="R$ 390" delta={26} icon="trend" accent="var(--orange)"/>
      </div>

      <div className="card card-pad">
        <h3 style={{fontSize:18, marginBottom:6}}>Seu link de indicação</h3>
        <p className="faint" style={{fontSize:13.5, marginBottom:16}}>Ganhe <b style={{color:'var(--lime-700)'}}>R$ 30</b> para cada indicação que assinar um plano. Saque automático a partir de R$ 50.</p>
        <div style={{display:'flex', gap:10, flexWrap:'wrap'}}>
          <div style={{flex:1, minWidth:240, display:'flex', alignItems:'center', gap:10, padding:'12px 16px', borderRadius:12, border:'1.5px dashed var(--line-strong)', background:'var(--beige-deep)'}}>
            <Icon name="link" size={18} style={{color:'var(--ink-faint)'}}/><span style={{fontWeight:600, color:'var(--green-dark)', fontSize:14.5}}>{link}</span>
          </div>
          <button className="btn btn-dark" onClick={copy}>{copied? <><Icon name="check" size={16} sw={3}/>Copiado</> : 'Copiar link'}</button>
        </div>
      </div>

      <div className="card card-pad">
        <h3 style={{fontSize:18, marginBottom:16}}>Suas indicações</h3>
        <table style={{width:'100%', borderCollapse:'collapse'}}>
          <thead><tr style={{textAlign:'left'}}>{['Indicado','Data','Status','Comissão'].map(h=> <th key={h} style={{fontSize:12, fontWeight:700, color:'var(--ink-faint)', textTransform:'uppercase', letterSpacing:'.05em', padding:'0 0 12px'}}>{h}</th>)}</tr></thead>
          <tbody>
            {referrals.map((r,i)=>(
              <tr key={i} style={{borderTop:'1px solid var(--line)'}}>
                <td style={{padding:'13px 0', display:'flex', alignItems:'center', gap:10}}><Avatar name={r.name} size={32} colorIdx={i}/><span style={{fontWeight:600, fontSize:14}}>{r.name}</span></td>
                <td style={{padding:'13px 0', fontSize:14, color:'var(--ink-soft)'}}>{r.date}</td>
                <td style={{padding:'13px 0'}}><span className={`badge ${r.status==='Ativa'?'badge-lime':'badge-gray'}`}>{r.status}</span></td>
                <td style={{padding:'13px 0', fontWeight:700, fontSize:14}} className="mono-num">{r.value? '+ '+CRUIG.brl(r.value):'—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, {Checkout, Paywall, PlanView, Affiliates});
