// Real account screen wired to Stripe via the backend's /billing endpoints.
// Plan + credits come from the profile; "Trocar cartão / Cancelar" hands the
// user to Stripe's Customer Portal; "Upgrade" / "Comprar pacote" hands to
// Stripe Checkout. Recent transactions are pulled from /me/credits/transactions.

const PLAN_LABELS = {
  none: { name: "Sem plano", monthly: 0, total: 0 },
  pack_5: { name: "Pay per use", monthly: 0, total: 5 },
  plan_40: { name: "Creator", monthly: 39, total: 40 },
  plan_120: { name: "Pro", monthly: 79, total: 120 },
};

const REASON_LABELS = {
  pack_purchase: "Pacote comprado",
  plan_renewal: "Plano renovado",
  thumbnail_generation: "Geração de thumbnail",
  thumbnail_refund: "Reembolso de geração",
  avatar_generation: "Geração de avatar",
  avatar_emotion_edit: "Edição de emoção",
  dev_seed: "Créditos dev",
};

const formatBRL = (n) => `R$ ${Number(n).toFixed(2).replace(".", ",")}`;
const formatDate = (iso) => iso ? new Date(iso).toLocaleDateString("pt-BR") : "—";

const Account = ({ onUpgrade, onLogout, user, profile, onProfileChange }) => {
  const meta = (user && user.user_metadata) || {};
  const fullName = meta.full_name || meta.name || "";
  const avatarUrl = meta.avatar_url || meta.picture || "";
  const email = (user && user.email) || "";

  const [transactions, setTransactions] = React.useState(null);
  const [busy, setBusy] = React.useState(null); // "checkout" | "portal" | null
  const [error, setError] = React.useState(null);

  // Account deletion (LGPD erasure). Two-step: reveal a confirm field, then
  // require the user to type EXCLUIR before the DELETE /me call fires.
  const [deleteOpen, setDeleteOpen] = React.useState(false);
  const [deleteConfirm, setDeleteConfirm] = React.useState("");
  const [deleting, setDeleting] = React.useState(false);

  const deleteAccount = async () => {
    if (deleting || deleteConfirm !== "EXCLUIR") return;
    setDeleting(true);
    setError(null);
    try {
      await window.gtAPI.fetch("/me", {
        method: "DELETE",
        body: JSON.stringify({ confirm: "EXCLUIR" }),
      });
      // Account is gone — drop the local session and return to the landing page.
      try { await window.gtAuth.signOut(); } catch (_) {}
      window.location.href = "/";
    } catch (e) {
      setError(e.message || "falha ao excluir a conta");
      setDeleting(false);
    }
  };

  React.useEffect(() => {
    let active = true;
    (async () => {
      // Reconcile the local profile with Stripe's truth — fixes any drift from
      // missed webhooks. Then refresh profile + load the credit log.
      try { await window.gtAPI.fetch("/billing/sync", { method: "POST" }); }
      catch (e) { console.warn("billing sync failed (non-fatal):", e); }
      if (!active) return;
      if (onProfileChange) onProfileChange();
      try {
        const res = await window.gtAPI.fetch("/me/credits/transactions?limit=20");
        if (active) setTransactions(res.items || []);
      } catch (e) {
        if (active) console.warn("transactions fetch failed:", e);
      }
    })();
    return () => { active = false; };
  }, [onProfileChange]);

  const planKey = profile?.plan || "none";
  const planInfo = PLAN_LABELS[planKey] || PLAN_LABELS.none;
  const isSubscriber = planKey === "plan_40" || planKey === "plan_120";
  const credits = profile?.credits_remaining ?? 0;
  // Loose "used this period" inference. Without reliable cycle anchoring on the
  // client we just show credits_remaining vs the plan's total.
  const usedPct = isSubscriber && planInfo.total
    ? Math.max(0, Math.min(100, (1 - credits / planInfo.total) * 100))
    : 0;

  const startCheckout = async (plan) => {
    if (busy) return;
    setBusy("checkout");
    setError(null);
    try {
      const res = await window.gtAPI.fetch("/billing/checkout", {
        method: "POST",
        body: JSON.stringify({ plan }),
      });
      if (res?.url) window.location.href = res.url;
      else throw new Error("Stripe não devolveu URL");
    } catch (e) {
      setError(e.message || "falha ao abrir checkout");
      setBusy(null);
    }
  };

  const openPortal = async () => {
    if (busy) return;
    setBusy("portal");
    setError(null);
    try {
      const res = await window.gtAPI.fetch("/billing/portal", { method: "POST" });
      if (res?.url) window.location.href = res.url;
      else throw new Error("Stripe não devolveu URL");
    } catch (e) {
      setError(e.message || "falha ao abrir portal");
      setBusy(null);
    }
  };

  return (
    <div className="fade-in">
      <div className="row-gap" style={{marginBottom: 22}}>
        <div>
          <div className="eyebrow"><span className="dot" />Conta & Plano</div>
          <h1 className="display" style={{fontSize: 36, margin: "4px 0 0"}}>Configurações</h1>
        </div>
      </div>

      {error && (
        <div className="card" style={{padding: 14, borderColor: "var(--brand)", color: "var(--brand)", marginBottom: 16}}>
          {error}
        </div>
      )}

      <div className="account-grid">
        {/* Credits + actions */}
        <div className="card usage-card">
          <div className="eyebrow">CRÉDITOS</div>
          <div className="row-gap" style={{alignItems: "flex-end", gap: 12, marginTop: 6}}>
            <div className="big-num">{credits}{isSubscriber && planInfo.total
              ? <span style={{color: "var(--text-3)", fontSize: 32}}>/{planInfo.total}</span>
              : null}
            </div>
            <div className="muted-2" style={{paddingBottom: 12}}>disponíveis</div>
          </div>
          {isSubscriber && planInfo.total ? (
            <>
              <div className="meter-big"><div className="fill" style={{width: `${usedPct}%`}} /></div>
              <div className="row-gap muted" style={{justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 12}}>
                <span>renova em {formatDate(profile?.plan_renews_at)}</span>
                <span>{credits} restantes</span>
              </div>
            </>
          ) : (
            <div className="muted-2" style={{fontSize: 13, lineHeight: 1.5, marginTop: 8}}>
              Cada thumbnail gerada usa 1 crédito. Compre um pacote ou assine pra liberar mais.
            </div>
          )}
          <div className="row-gap" style={{gap: 8, marginTop: 18}}>
            <button className="btn btn-primary" style={{flex: 1}}
                    onClick={() => startCheckout("pack_5")} disabled={busy != null}>
              <Icon name="zap" size={14} /> {busy === "checkout" ? "Abrindo…" : "Comprar pacote +5"}
            </button>
            {!isSubscriber && (
              <button className="btn" onClick={onUpgrade} disabled={busy != null}>
                Ver planos
              </button>
            )}
          </div>
        </div>

        {/* Current plan */}
        <div className="card" style={{padding: 24}}>
          <div className="eyebrow">PLANO ATUAL</div>
          <div className="row-gap" style={{marginTop: 8, marginBottom: 14}}>
            <h3 className="display" style={{fontSize: 28, margin: 0}}>{planInfo.name}</h3>
            {isSubscriber && <span className="chip brand">ativo</span>}
            {!isSubscriber && planKey !== "none" && <span className="chip">único</span>}
          </div>
          <div className="col-gap" style={{gap: 10}}>
            <div className="row-gap" style={{justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)"}}>
              <span className="muted-2">Valor</span>
              <span className="mono">{isSubscriber ? `${formatBRL(planInfo.monthly)} / mês` : "—"}</span>
            </div>
            <div className="row-gap" style={{justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)"}}>
              <span className="muted-2">Próxima cobrança</span>
              <span className="mono">{formatDate(profile?.plan_renews_at)}</span>
            </div>
            <div className="row-gap" style={{justifyContent: "space-between", padding: "10px 0"}}>
              <span className="muted-2">Status</span>
              <span className="chip green">{isSubscriber ? "Em dia" : "—"}</span>
            </div>
          </div>
          <div className="row-gap" style={{gap: 8, marginTop: 16}}>
            {isSubscriber ? (
              <>
                <button className="btn btn-sm" onClick={openPortal} disabled={busy != null}>
                  {busy === "portal" ? "Abrindo…" : "Gerenciar plano"}
                </button>
                <button className="btn btn-sm btn-ghost" onClick={onUpgrade}
                        style={{color: "var(--text-3)"}}>
                  Trocar plano
                </button>
              </>
            ) : (
              <>
                <button className="btn btn-sm btn-primary" onClick={onUpgrade}>
                  <Icon name="zap" size={12} /> Assinar plano
                </button>
                {profile?.stripe_customer_id && (
                  <button className="btn btn-sm" onClick={openPortal} disabled={busy != null}>
                    Histórico Stripe
                  </button>
                )}
              </>
            )}
          </div>
        </div>

        {/* Profile (Google-derived; read-only since we use OAuth) */}
        <div className="card" style={{padding: 24, gridColumn: "span 2"}}>
          <div className="eyebrow">PERFIL</div>
          <div className="row-gap" style={{gap: 18, marginTop: 14}}>
            <div style={{width: 64, height: 64, borderRadius: "50%", overflow: "hidden"}}>
              {avatarUrl
                ? <img src={avatarUrl} alt="" referrerPolicy="no-referrer" style={{width: "100%", height: "100%", objectFit: "cover"}} />
                : <FacePlaceholder tone={0} emotion="happy" size={64} />}
            </div>
            <div style={{flex: 1, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14}}>
              <div className="field">
                <label>Nome</label>
                <input type="text" defaultValue={fullName} readOnly />
              </div>
              <div className="field">
                <label>Email</label>
                <input type="text" defaultValue={email} readOnly />
              </div>
            </div>
          </div>
          <div className="row-gap" style={{gap: 8, marginTop: 18}}>
            <button className="btn btn-ghost" onClick={onLogout} style={{color: "var(--text-3)"}}>
              Sair da conta
            </button>
          </div>
        </div>

        {/* Danger zone — account deletion (LGPD erasure) */}
        <div className="card" style={{padding: 24, gridColumn: "span 2", borderColor: "var(--brand)"}}>
          <div className="eyebrow" style={{color: "var(--brand)"}}>ZONA DE PERIGO</div>
          <h3 style={{fontFamily: "var(--font-display)", fontSize: 18, margin: "10px 0 6px"}}>Excluir conta</h3>
          <p className="muted-2" style={{fontSize: 13, lineHeight: 1.6, margin: "0 0 14px", maxWidth: 560}}>
            Remove permanentemente seu perfil, avatares, thumbnails, imagens armazenadas e histórico de
            créditos, e cancela qualquer assinatura ativa. Esta ação é <strong>irreversível</strong> e os
            créditos restantes não são reembolsados.
          </p>

          {!deleteOpen ? (
            <button className="btn btn-sm" onClick={() => { setDeleteOpen(true); setError(null); }}
                    style={{borderColor: "var(--brand)", color: "var(--brand)"}}>
              Excluir minha conta
            </button>
          ) : (
            <div className="col-gap" style={{gap: 12, maxWidth: 420}}>
              <div className="field">
                <label>Digite <strong>EXCLUIR</strong> para confirmar</label>
                <input
                  type="text"
                  value={deleteConfirm}
                  onChange={(e) => setDeleteConfirm(e.target.value)}
                  placeholder="EXCLUIR"
                  autoFocus
                />
              </div>
              <div className="row-gap" style={{gap: 8}}>
                <button
                  className="btn btn-sm btn-primary"
                  onClick={deleteAccount}
                  disabled={deleting || deleteConfirm !== "EXCLUIR"}
                >
                  {deleting ? "Excluindo…" : "Confirmar exclusão"}
                </button>
                <button className="btn btn-sm btn-ghost" disabled={deleting}
                        onClick={() => { setDeleteOpen(false); setDeleteConfirm(""); }}>
                  Cancelar
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Transactions */}
        <div className="card" style={{padding: 24, gridColumn: "span 2"}}>
          <div className="row-gap" style={{marginBottom: 14}}>
            <div className="eyebrow">EXTRATO DE CRÉDITOS</div>
            <div className="spacer" />
            {profile?.stripe_customer_id && (
              <button className="btn btn-sm btn-ghost" onClick={openPortal} disabled={busy != null}>
                Faturas no Stripe
              </button>
            )}
          </div>
          {transactions === null && <div className="muted" style={{fontSize: 13}}>Carregando…</div>}
          {transactions && transactions.length === 0 && (
            <div className="muted" style={{fontSize: 13}}>
              Nenhum movimento ainda. Compre créditos pra começar.
            </div>
          )}
          {transactions && transactions.length > 0 && transactions.map((tx, i) => {
            const isCredit = tx.delta > 0;
            const label = REASON_LABELS[tx.reason] || tx.reason;
            return (
              <div key={tx.id}
                   className="row-gap"
                   style={{padding: "12px 0", borderBottom: i < transactions.length - 1 ? "1px solid var(--border)" : 0, gap: 18}}>
                <span className="mono muted-2" style={{width: 110}}>{formatDate(tx.created_at)}</span>
                <span style={{flex: 1}}>{label}</span>
                <span className="mono" style={{color: isCredit ? "#10b981" : "var(--text-2)"}}>
                  {isCredit ? "+" : ""}{tx.delta} créd.
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

window.Account = Account;
