// Paywall — tela que bloqueia o app quando o trial expira.
// Renderizada DEPOIS do login mas ANTES do conteúdo principal,
// quando profile.plan === 'trial' e trial_ends_at já passou.
//
// Existem duas versões: WebPaywall (desktop, layout amplo) e
// MobilePaywall (celular, layout compacto). Ambas oferecem os 3
// planos com botão que abre o checkout Nexano.

(function () {
  const PLANS = [
    { id: 'mensal',    name: 'Mensal',    subtitle: 'Mais flexível',  total: 29.90,  months: 1,  color: '#6FB8FF' },
    { id: 'semestral', name: 'Semestral', subtitle: 'Equilibrado',    total: 149.40, months: 6,  color: '#FFB547', save: '17%' },
    { id: 'anual',     name: 'Anual',     subtitle: 'Melhor custo',   total: 238.80, months: 12, color: '#B197FC', save: '33%', recommended: true },
  ];

  const fmtBRL = (v) => `R$ ${v.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

  // ── Web Paywall (desktop) ──────────────────────────────────
  function WebPaywall({ user, onLogout, onRefresh, showToast }) {
    const choose = (planId) => {
      const plan = PLANS.find(p => p.id === planId);
      if (window.Checkout && window.Checkout.openCheckout(planId, user)) {
        showToast && showToast(`Abrindo checkout · ${plan.name}`);
      }
    };

    return (
      <div style={{
        minHeight: '100vh', background: CDV.bg, color: CDV.text,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 40, position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -200, right: -200, width: 600, height: 600, borderRadius: 99,
          background: `radial-gradient(circle, ${CDV.brand}33, transparent 60%)`, filter: 'blur(60px)', pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute', bottom: -200, left: -200, width: 600, height: 600, borderRadius: 99,
          background: `radial-gradient(circle, ${CDV.coral}22, transparent 60%)`, filter: 'blur(60px)', pointerEvents: 'none',
        }} />

        <div style={{ maxWidth: 1100, width: '100%', position: 'relative' }}>
          <div style={{ textAlign: 'center', marginBottom: 32 }}>
            <BrandLogo size={56} animated />
            <div style={{
              marginTop: 22, fontSize: 12, color: CDV.amber, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase',
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '8px 16px', borderRadius: 99,
              background: `${CDV.amber}1a`, border: `1px solid ${CDV.amber}40`,
            }}>
              <Icon name="sparkle" size={12} /> Seu período de teste terminou
            </div>
            <div style={{ fontFamily: fontDisplay, fontSize: 48, letterSpacing: -1.2, lineHeight: 1.1, marginTop: 18 }}>
              Continue com a <i style={{ color: CDV.brand }}>Central completa</i>
            </div>
            <div style={{ fontSize: 15, color: CDV.textDim, marginTop: 14, maxWidth: 540, marginInline: 'auto', lineHeight: 1.5 }}>
              Sofia 24/7, tarefas, hábitos, metas, finanças e backup em nuvem.
              Seus dados <b style={{ color: CDV.text }}>estão salvos</b> — só faltam você escolher um plano.
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginBottom: 22 }}>
            {PLANS.map(plan => (
              <PaywallCardWeb key={plan.id} plan={plan} onSelect={() => choose(plan.id)} />
            ))}
          </div>

          <div style={{
            padding: 22, borderRadius: 18,
            background: `linear-gradient(135deg, ${CDV.brand}14 0%, ${CDV.brand}06 50%, ${CDV.surface} 100%)`,
            border: `1px solid ${CDV.brand}30`, marginBottom: 22,
          }}>
            <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 12 }}>
              Todos os planos incluem
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
              {['Sofia IA ilimitada', 'Backup em nuvem', 'Cofrinhos e metas', 'Sincronização', 'Relatórios PDF', 'Suporte prioritário', 'Cancele a qualquer hora', '14 dias garantia'].map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: CDV.text }}>
                  <Icon name="check" size={12} color={CDV.mint} /> {f}
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'center', gap: 14, alignItems: 'center', fontSize: 12, color: CDV.textMuted }}>
            <button onClick={onRefresh} style={{
              background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, color: CDV.text,
              padding: '8px 16px', borderRadius: 10, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>Já paguei · atualizar</button>
            <span>·</span>
            <button onClick={onLogout} style={{
              background: 'transparent', border: 'none', color: CDV.textMuted,
              fontSize: 12, fontWeight: 500, cursor: 'pointer', textDecoration: 'underline', fontFamily: 'inherit',
            }}>Sair da conta</button>
          </div>
        </div>
      </div>
    );
  }

  function PaywallCardWeb({ plan, onSelect }) {
    const perMonth = plan.total / plan.months;
    const periodLabel = plan.months === 1 ? '/mês' : plan.months === 6 ? 'a cada 6 meses' : '/ano';
    return (
      <div style={{
        position: 'relative', padding: 28, borderRadius: 22,
        background: plan.recommended
          ? `linear-gradient(135deg, ${plan.color}22, ${plan.color}04)`
          : CDV.surface,
        border: `1.5px solid ${plan.recommended ? plan.color : CDV.stroke}`,
      }}>
        {plan.recommended && (
          <div style={{
            position: 'absolute', top: -12, left: 24, padding: '5px 12px',
            background: CDV.brandGrad, color: '#fff', borderRadius: 99,
            fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
            boxShadow: '0 4px 12px -4px rgba(177,151,252,0.5)',
          }}>MAIS POPULAR</div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: CDV.text }}>{plan.name}</div>
          {plan.save && (
            <span style={{
              fontSize: 11, fontWeight: 700, color: CDV.mint,
              background: `${CDV.mint}1a`, padding: '3px 8px', borderRadius: 99,
            }}>economize {plan.save}</span>
          )}
        </div>
        <div style={{ fontSize: 13, color: CDV.textDim, marginBottom: 16 }}>{plan.subtitle}</div>
        <div style={{ fontSize: 38, fontWeight: 800, color: CDV.text, letterSpacing: -1, lineHeight: 1 }}>
          {fmtBRL(plan.total)}
          <span style={{ fontSize: 14, fontWeight: 500, color: CDV.textDim, marginLeft: 6 }}>{periodLabel}</span>
        </div>
        {plan.months > 1 && (
          <div style={{ fontSize: 13, color: CDV.amber, fontWeight: 600, marginTop: 6 }}>
            equivale a {fmtBRL(perMonth)}/mês
          </div>
        )}
        <button onClick={onSelect} style={{
          marginTop: 22, width: '100%', height: 48, borderRadius: 12,
          background: plan.recommended ? CDV.brandGrad : CDV.surfaceHi,
          border: plan.recommended ? 'none' : `1px solid ${CDV.strokeHi}`,
          color: '#fff', fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: plan.recommended ? '0 8px 20px -8px rgba(177,151,252,0.6)' : 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          Assinar {plan.name} <Icon name="arrowRight" size={14} />
        </button>
      </div>
    );
  }

  // ── Mobile Paywall (celular) ───────────────────────────────
  function MobilePaywall({ user, onLogout, onRefresh, showToast }) {
    const choose = (planId) => {
      const plan = PLANS.find(p => p.id === planId);
      if (window.Checkout && window.Checkout.openCheckout(planId, user)) {
        showToast && showToast(`Abrindo checkout · ${plan.name}`);
      }
    };

    return (
      <div style={{
        minHeight: '100vh', background: CDV.bg, color: CDV.text,
        padding: '32px 22px 110px', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -100, right: -100, width: 300, height: 300, borderRadius: 99,
          background: `radial-gradient(circle, ${CDV.brand}33, transparent 60%)`, filter: 'blur(50px)', pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative', textAlign: 'center' }}>
          <BrandLogo size={52} animated />
          <div style={{
            marginTop: 18, fontSize: 10, color: CDV.amber, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px', borderRadius: 99,
            background: `${CDV.amber}1a`, border: `1px solid ${CDV.amber}40`,
          }}>
            <Icon name="sparkle" size={10} /> Seu trial terminou
          </div>
          <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, lineHeight: 1.15, marginTop: 14 }}>
            Continue com a <span style={{ background: CDV.brandGrad, WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>Central completa</span>
          </div>
          <div style={{ fontSize: 13, color: CDV.textDim, marginTop: 10, lineHeight: 1.5 }}>
            Seus dados estão salvos. Escolha um plano e siga de onde parou ✨
          </div>
        </div>

        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {PLANS.map(plan => (
            <PaywallCardMobile key={plan.id} plan={plan} onSelect={() => choose(plan.id)} />
          ))}
        </div>

        <div style={{
          marginTop: 20, padding: 16, borderRadius: 14,
          background: `${CDV.brand}10`, border: `1px solid ${CDV.brand}30`,
        }}>
          <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8 }}>
            Tudo incluído
          </div>
          <div style={{ fontSize: 12, color: CDV.text, lineHeight: 1.6 }}>
            Sofia IA ilimitada · Backup em nuvem · Cofrinhos e metas ilimitados ·
            Relatórios PDF · 14 dias garantia
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 24, alignItems: 'center', fontSize: 12 }}>
          <button onClick={onRefresh} style={{
            background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, color: CDV.text,
            padding: '8px 14px', borderRadius: 10, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          }}>Já paguei · atualizar</button>
          <button onClick={onLogout} style={{
            background: 'transparent', border: 'none', color: CDV.textMuted,
            fontSize: 12, fontWeight: 500, cursor: 'pointer', textDecoration: 'underline', fontFamily: 'inherit',
          }}>Sair</button>
        </div>
      </div>
    );
  }

  function PaywallCardMobile({ plan, onSelect }) {
    const perMonth = plan.total / plan.months;
    const periodLabel = plan.months === 1 ? '/mês' : plan.months === 6 ? '/sem' : '/ano';
    return (
      <div style={{
        position: 'relative', padding: 18, borderRadius: 18,
        background: plan.recommended ? `linear-gradient(135deg, ${plan.color}22, ${plan.color}04)` : CDV.surface,
        border: `1.5px solid ${plan.recommended ? plan.color : CDV.stroke}`,
      }}>
        {plan.recommended && (
          <div style={{
            position: 'absolute', top: -10, right: 14, padding: '4px 10px',
            background: CDV.brandGrad, color: '#fff', borderRadius: 99,
            fontSize: 9, fontWeight: 700, letterSpacing: 0.4,
          }}>POPULAR</div>
        )}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: CDV.text }}>{plan.name}</div>
            {plan.save && (
              <span style={{
                fontSize: 10, fontWeight: 700, color: CDV.mint,
                background: `${CDV.mint}1a`, padding: '2px 7px', borderRadius: 99,
              }}>-{plan.save}</span>
            )}
          </div>
        </div>
        <div style={{ fontSize: 11, color: CDV.textDim, marginBottom: 12 }}>{plan.subtitle}</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
          <div>
            <div style={{ fontSize: 28, fontWeight: 800, color: CDV.text, letterSpacing: -0.8, lineHeight: 1 }}>
              {fmtBRL(plan.total)}
              <span style={{ fontSize: 12, fontWeight: 500, color: CDV.textDim, marginLeft: 4 }}>{periodLabel}</span>
            </div>
            {plan.months > 1 && (
              <div style={{ fontSize: 11, color: CDV.amber, fontWeight: 600, marginTop: 3 }}>
                {fmtBRL(perMonth)}/mês
              </div>
            )}
          </div>
          <button onClick={onSelect} style={{
            padding: '10px 16px', borderRadius: 10, border: 'none',
            background: plan.recommended ? CDV.brandGrad : CDV.surfaceHi,
            border: plan.recommended ? 'none' : `1px solid ${CDV.strokeHi}`,
            color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            Assinar <Icon name="arrowRight" size={12} />
          </button>
        </div>
      </div>
    );
  }

  // Expõe globalmente
  window.WebPaywall = WebPaywall;
  window.MobilePaywall = MobilePaywall;
})();
