// mb-club.jsx — Clube de benefícios (assinatura, estilo iFood Clube)

const CLUB_BENEFITS = [
  { ic: "bike", t: "Entrega grátis", d: "Em lojas selecionadas, sem taxa." },
  { ic: "coin", t: "BemCash em dobro", d: "O dobro de cashback em todas as compras." },
  { ic: "ticket", t: "Cupons exclusivos", d: "Ofertas só para membros, toda semana." },
  { ic: "bolt", t: "Acesso antecipado", d: "Promoções e BemCash Turbo antes de todo mundo." },
  { ic: "headset", t: "Atendimento prioritário", d: "Suporte na frente da fila." },
];
const CLUB_PLANS = [
  { id: "mensal", label: "Mensal", price: 9.9, per: "/mês", note: "Cancele quando quiser" },
  { id: "anual", label: "Anual", price: 99, per: "/ano", note: "2 meses grátis", best: true },
];

function ClubScreen({ member, onSubscribe, onCancel, onBack }) {
  const [plan, setPlan] = React.useState("anual");
  const [loading, setLoading] = React.useState(false);

  // Planos reais da API
  const [apiPlans, setApiPlans] = React.useState(null);
  React.useEffect(() => {
    API.club.plans().then(d => {
      if (d.plans?.length) {
        setApiPlans(d.plans.map(p => ({
          id: p.id,
          label: p.period === "mensal" ? "Mensal" : "Anual",
          price: parseFloat(p.price),
          per: p.period === "mensal" ? "/mês" : "/ano",
          note: p.period === "anual" ? "2 meses grátis" : "Cancele quando quiser",
          best: p.period === "anual",
          benefits: p.benefits || [],
          _raw: p,
        })));
        setPlan(d.plans.find(p => p.period === "anual")?.id || d.plans[0]?.id);
      }
    }).catch(() => {});
  }, []);

  const plans = apiPlans || CLUB_PLANS;
  const sel = plans.find(p => p.id === plan) || plans[0];

  const handleSubscribe = async () => {
    if (!sel?._raw?.id) { onSubscribe(); return; }
    setLoading(true);
    try {
      await API.club.subscribe({ plan_id: sel._raw.id });
      onSubscribe();
    } catch (_) { onSubscribe(); } // fallback local
    finally { setLoading(false); }
  };

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <div style={{ flex: 1, overflow: "auto", paddingBottom: member ? 24 : 96 }}>
        {/* hero */}
        <div style={{ position: "relative", background: "var(--turbo-grad)", padding: "52px 20px 26px", color: "#fff", overflow: "hidden" }}>
          <div style={{ position: "absolute", top: 50, left: 14 }}><IconBtn name="arrowL" onClick={onBack} size={40} bg="rgba(255,255,255,.92)" /></div>
          <Icon name="bolt" size={150} color="rgba(255,255,255,.12)" fill="rgba(255,255,255,.12)" sw={0} style={{ position: "absolute", right: -20, top: -14 }} />
          <div style={{ marginTop: 18, display: "inline-flex", alignItems: "center", gap: 7, background: "rgba(255,255,255,.2)", padding: "5px 12px", borderRadius: 999, font: "800 11px var(--ui)", letterSpacing: ".06em" }}>
            <Icon name="star" size={13} color="#fff" fill="#fff" sw={1.5} />CLUBE MORAR BEM
          </div>
          <h1 style={{ margin: "12px 0 0", font: "900 27px var(--ui)", lineHeight: 1.12 }}>{member ? "Você é membro 🎉" : "Mais vantagens em cada compra"}</h1>
          <p style={{ font: "500 14px var(--ui)", opacity: .95, margin: "8px 0 0", maxWidth: 290, lineHeight: 1.5 }}>
            {member ? "Aproveite entrega grátis, BemCash em dobro e ofertas exclusivas." : "Assine o Clube e economize todo mês com benefícios exclusivos."}
          </p>
        </div>

        {/* benefits */}
        <div style={{ padding: "20px 16px 4px" }}>
          <div style={{ font: "800 16px var(--ui)", color: "var(--text)", marginBottom: 12 }}>Seus benefícios</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {CLUB_BENEFITS.map(b => (
              <div key={b.t} style={{ display: "flex", gap: 12, alignItems: "center", background: "var(--surface)", borderRadius: 16, padding: 13, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
                <div style={{ width: 42, height: 42, borderRadius: 12, background: "var(--cb-bg)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={b.ic} size={21} color="var(--cb)" fill={b.ic === "bolt" ? "var(--cb)" : "none"} sw={1.8} /></div>
                <div style={{ flex: 1 }}><div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{b.t}</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>{b.d}</div></div>
                {member && <Icon name="check" size={18} color="var(--cb)" sw={3} />}
              </div>
            ))}
          </div>
        </div>

        {/* plans */}
        {!member && (
          <div style={{ padding: "18px 16px 4px" }}>
            <div style={{ font: "800 16px var(--ui)", color: "var(--text)", marginBottom: 12 }}>Escolha seu plano</div>
            <div style={{ display: "flex", gap: 12 }}>
              {CLUB_PLANS.map(p => {
                const on = plan === p.id;
                return (
                  <button key={p.id} onClick={() => setPlan(p.id)} style={{ flex: 1, textAlign: "left", cursor: "pointer", borderRadius: 16, padding: "15px 14px", background: "var(--surface)", border: on ? "2px solid var(--accent)" : "2px solid var(--line)", position: "relative" }}>
                    {p.best && <span style={{ position: "absolute", top: -9, right: 12, font: "800 9.5px var(--ui)", color: "#fff", background: "var(--turbo-grad)", padding: "3px 8px", borderRadius: 999 }}>MELHOR</span>}
                    <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)" }}>{p.label}</div>
                    <div style={{ marginTop: 6, font: "900 22px var(--ui)", color: "var(--text)" }}>{money(p.price)}<span style={{ font: "600 12px var(--ui)", color: "var(--muted)" }}>{p.per}</span></div>
                    <div style={{ font: "600 11px var(--ui)", color: on ? "var(--accent)" : "var(--muted)", marginTop: 4 }}>{p.note}</div>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {member && (
          <div style={{ padding: "18px 16px 0" }}>
            <div style={{ background: "var(--surface)", borderRadius: 16, padding: 16, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div><div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>Plano Anual</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>Renova em 12 jun 2027</div></div>
                <span style={{ font: "700 11px var(--ui)", color: "var(--cb)", background: "var(--cb-bg)", padding: "4px 10px", borderRadius: 999 }}>ATIVO</span>
              </div>
              <button onClick={onCancel} style={{ marginTop: 14, background: "none", border: "none", cursor: "pointer", font: "700 13px var(--ui)", color: "var(--muted)", textDecoration: "underline", padding: 2 }}>Gerenciar assinatura</button>
            </div>
          </div>
        )}
      </div>

      {!member && (
        <div style={{ padding: "12px 16px 26px", background: "var(--surface)", borderTop: "1px solid var(--line)" }}>
          <Btn full disabled={loading} onClick={handleSubscribe}>
            <span style={{ display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between" }}>
              <span>{loading ? "Processando…" : "Assinar Clube"}</span>
              {!loading && <span>{money(sel?.price || 0)}{sel?.per}</span>}
            </span>
          </Btn>
          <div style={{ textAlign: "center", font: "500 11px var(--ui)", color: "var(--muted)", marginTop: 8 }}>Renovação automática · cancele quando quiser</div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CLUB_BENEFITS, CLUB_PLANS, ClubScreen });
