/* global React, SEQ_UI, SEQ_LAYOUT */
const { brl, Avatar } = window.SEQ_UI;
const { Pill } = window.SEQ_LAYOUT;

// Portal do assinante — vista do CLIENTE pagante. Sem sidebar admin, layout próprio.

function Portal() {
  const [tab, setTab] = React.useState("inicio");
  const [subData, setSubData] = React.useState(null);

  // Tenta puxar primeira assinatura ativa do banco; fallback pra mock
  React.useEffect(() => {
    window.SEQ_API.listSubscriptions()
      .then(d => {
        const first = (d.subscriptions || []).find(r => (r.subscription?.status || r.status) === "active");
        if (first) {
          const s = first.subscription || first;
          const p = first.product;
          setSubData({
            plano: p?.name || "Plano ativo",
            valor: (s.amount ?? 0) / 100,
            proxima: s.nextChargeDate ? new Date(s.nextChargeDate).toLocaleDateString("pt-BR") : "—",
            desde: s.createdAt ? new Date(s.createdAt).toLocaleDateString("pt-BR") : "—",
            metodo: "Cartão ••••42",
          });
        }
      })
      .catch(() => {});
  }, []);

  const sub = subData || {
    plano: "Mentoria 1:1 mensal",
    valor: 1490,
    proxima: "10 mai 2025",
    desde: "10 set 2024",
    metodo: "Cartão Visa ••••42",
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--kp-paper)" }}>
      <PortalBar tab={tab} onTab={setTab}/>

      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "32px 22px 80px" }}>
        {/* Hello hero */}
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEU PORTAL · ASSINANTE PRO</div>
        <h1 className="kp-display" style={{ fontSize: "clamp(40px,5vw,68px)", lineHeight: 1.0, margin: "8px 0 28px" }}>
          Olá, <em>Diogo.</em><br/>
          Tudo certo <span style={{ color: "var(--kp-pink)" }}>por aqui.</span>
        </h1>

        {tab === "inicio" && <PortalHome sub={sub}/>}
        {tab === "assinatura" && <PortalAssinatura sub={sub}/>}
        {tab === "faturas" && <PortalFaturas/>}
        {tab === "acesso" && <PortalAcesso/>}
        {tab === "perfil" && <PortalPerfil/>}
      </div>
    </div>
  );
}

function PortalBar({ tab, onTab }) {
  const tabs = [
    { id: "inicio", l: "Início" },
    { id: "assinatura", l: "Assinatura" },
    { id: "faturas", l: "Faturas" },
    { id: "acesso", l: "Acesso ao produto" },
    { id: "perfil", l: "Perfil" },
  ];
  return (
    <header style={{ borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-white)" }}>
      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "14px 22px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div className="kp-display" style={{ fontSize: 22 }}>Sequência<em style={{ color: "var(--kp-pink)" }}>·</em></div>
          <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.2em", color: "var(--kp-muted)", paddingLeft: 12, borderLeft: "1.5px solid var(--kp-ink)" }}>PORTAL DO ASSINANTE</span>
        </div>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {tabs.map(t => (
            <button key={t.id} onClick={()=>onTab(t.id)} style={{
              padding: "8px 14px", border: "1.5px solid var(--kp-ink)", cursor: "pointer",
              background: tab === t.id ? "var(--kp-ink)" : "var(--kp-white)",
              color: tab === t.id ? "var(--kp-paper)" : "var(--kp-ink)",
              fontFamily: "var(--kp-mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
              boxShadow: tab === t.id ? "3px 3px 0 0 var(--kp-pink)" : "none",
            }}>{t.l}</button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Avatar initials="DK" size={32} bg="var(--kp-pink)"/>
          <button style={{ padding: "6px 10px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-white)", fontFamily: "var(--kp-mono)", fontSize: 9, letterSpacing: "0.14em", cursor: "pointer" }}>SAIR</button>
        </div>
      </div>
    </header>
  );
}

function PortalHome({ sub }) {
  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, marginBottom: 22 }}>
        {/* Plano atual */}
        <div className="kp-card" style={{ padding: 26, background: "var(--kp-pink-soft)" }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEU PLANO</div>
          <h2 className="kp-display" style={{ fontSize: 36, lineHeight: 1.05, margin: "6px 0 0" }}>{sub.plano}</h2>
          <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 12 }}>
            <span className="kp-display" style={{ fontSize: 44, fontStyle: "italic" }}>{brl(sub.valor)}<span style={{ fontSize: 14, color: "var(--kp-muted)" }}>/mês</span></span>
            <Pill bg="var(--kp-green)">ATIVO · EM DIA</Pill>
          </div>
          <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, fontSize: 12 }}>
            <div>
              <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", color: "var(--kp-muted)" }}>PRÓXIMA COBRANÇA</div>
              <div style={{ fontWeight: 500, marginTop: 2 }}>{sub.proxima}</div>
            </div>
            <div>
              <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", color: "var(--kp-muted)" }}>MÉTODO</div>
              <div style={{ fontWeight: 500, marginTop: 2 }}>{sub.metodo}</div>
            </div>
          </div>
        </div>

        {/* Acesso rápido */}
        <div className="kp-card" style={{ padding: 22, background: "var(--kp-ink)", color: "var(--kp-paper)" }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "rgba(247,241,232,0.5)" }}>ACESSO RÁPIDO</div>
          <h3 className="kp-display" style={{ fontSize: 22, color: "var(--kp-paper)", marginTop: 8, lineHeight: 1.1 }}>Suas próximas <em>2 sessões</em></h3>
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { d: "08 mai", h: "14:00", t: "Sessão semanal · Pricing", c: "var(--kp-pink)" },
              { d: "15 mai", h: "14:00", t: "Sessão semanal · Funil", c: "var(--kp-green)" },
            ].map((s,i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, padding: 10, background: "rgba(247,241,232,0.05)", border: "1.5px solid rgba(247,241,232,0.15)", alignItems: "center" }}>
                <div style={{ width: 44, padding: 6, background: s.c, border: "1.5px solid var(--kp-paper)", textAlign: "center" }}>
                  <div className="kp-mono" style={{ fontSize: 8.5, letterSpacing: "0.14em", color: "var(--kp-ink)" }}>{s.d.split(" ")[1].toUpperCase()}</div>
                  <div className="kp-display" style={{ fontSize: 18, color: "var(--kp-ink)", lineHeight: 1, fontStyle: "italic" }}>{s.d.split(" ")[0]}</div>
                </div>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{s.t}</div>
                  <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.14em", color: "rgba(247,241,232,0.55)", marginTop: 2 }}>{s.h} · GMEET</div>
                </div>
                <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.14em", color: s.c }}>ABRIR →</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Próximo conteúdo */}
      <div className="kp-card" style={{ padding: 0, marginBottom: 22 }}>
        <div style={{ padding: "14px 22px", borderBottom: "1.5px solid var(--kp-ink)", display: "flex", justifyContent: "space-between" }}>
          <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>CONTEÚDO LIBERADO</span>
          <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>3 NOVOS</span>
        </div>
        {[
          { n: "Pricing assimétrico · masterclass", t: "Vídeo · 42min", new: true, color: "var(--kp-pink)" },
          { n: "Template de proposta editorial", t: "PDF · 18 páginas", new: true, color: "var(--kp-green)" },
          { n: "Lista: 17 hooks que viralizam em B2B", t: "Notion · 3min de leitura", new: true, color: "var(--kp-cold)" },
          { n: "Diário do mês: como fechei 4 contratos", t: "Áudio · 28min", new: false, color: "var(--kp-yellow)" },
        ].map((c,i,a) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 14, padding: "14px 22px", alignItems: "center", borderBottom: i === a.length-1 ? "none" : "1px solid rgba(10,10,10,0.08)", background: i % 2 === 1 ? "var(--kp-soft)" : "var(--kp-white)" }}>
            <span style={{ width: 36, height: 36, background: c.color, border: "1.5px solid var(--kp-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--kp-display)", fontSize: 16, fontStyle: "italic" }}>{["▶","◢","◉","♪"][i]}</span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{c.n}</div>
              <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", color: "var(--kp-muted)", marginTop: 2 }}>{c.t}</div>
            </div>
            {c.new && <Pill bg="var(--kp-pink)">NOVO</Pill>}
            <button className="kp-btn kp-btn-sm">Abrir →</button>
          </div>
        ))}
      </div>
    </>
  );
}

function PortalAssinatura({ sub }) {
  return (
    <>
      <div className="kp-card" style={{ padding: 26, background: "var(--kp-pink-soft)", marginBottom: 22 }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>ASSINATURA ATUAL</div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 8, flexWrap: "wrap", gap: 12 }}>
          <h2 className="kp-display" style={{ fontSize: 32, margin: 0 }}>{sub.plano}</h2>
          <span className="kp-display" style={{ fontSize: 36, fontStyle: "italic" }}>{brl(sub.valor)}<span style={{ fontSize: 14, color: "var(--kp-muted)" }}>/mês</span></span>
        </div>
        <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
          {[
            { l: "Cliente desde", v: sub.desde },
            { l: "Próxima cobrança", v: sub.proxima },
            { l: "Pagamento", v: sub.metodo },
          ].map((s,i) => (
            <div key={i} style={{ padding: 12, background: "var(--kp-white)", border: "1.5px solid var(--kp-ink)" }}>
              <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", color: "var(--kp-muted)" }}>{s.l.toUpperCase()}</div>
              <div style={{ fontSize: 13.5, fontWeight: 500, marginTop: 4 }}>{s.v}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 22 }}>
        <div className="kp-card" style={{ padding: 22 }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>UPGRADES DISPONÍVEIS</div>
          <h3 className="kp-display" style={{ fontSize: 22, marginTop: 6 }}>Plano anual <em>−2 meses</em></h3>
          <div style={{ marginTop: 8, fontSize: 13, color: "var(--kp-muted)" }}>Pague 10 meses, leve 12. Economize <strong style={{ color: "var(--kp-pink)" }}>{brl(2980)}</strong>/ano.</div>
          <button className="kp-btn kp-btn-ink" style={{ marginTop: 14 }}>Mudar pra anual →</button>
        </div>
        <div className="kp-card" style={{ padding: 22 }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>GERENCIAR</div>
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            <button className="kp-btn" style={{ justifyContent: "flex-start", width: "100%" }}>Trocar método de pagamento</button>
            <button className="kp-btn" style={{ justifyContent: "flex-start", width: "100%" }}>Pausar assinatura por 30 dias</button>
            <button className="kp-btn" style={{ justifyContent: "flex-start", width: "100%", color: "#B22" }}>Cancelar assinatura</button>
          </div>
        </div>
      </div>
    </>
  );
}

function PortalFaturas() {
  const fats = [
    { d: "10 abr 2025", v: 1490, s: "paga", m: "Cartão" },
    { d: "10 mar 2025", v: 1490, s: "paga", m: "Cartão" },
    { d: "10 fev 2025", v: 1490, s: "paga", m: "PIX" },
    { d: "10 jan 2025", v: 1490, s: "paga", m: "PIX" },
    { d: "10 dez 2024", v: 1490, s: "paga", m: "Cartão" },
    { d: "10 nov 2024", v: 1490, s: "paga", m: "Cartão" },
    { d: "10 out 2024", v: 1490, s: "paga", m: "PIX" },
    { d: "10 set 2024", v: 1490, s: "paga", m: "PIX" },
  ];
  return (
    <div className="kp-card" style={{ padding: 0 }}>
      <div style={{ padding: "14px 22px", borderBottom: "1.5px solid var(--kp-ink)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>HISTÓRICO DE FATURAS</span>
        <span style={{ fontSize: 13 }}>Total pago: <strong className="kp-display" style={{ fontStyle: "italic", fontSize: 18 }}>{brl(11920)}</strong></span>
      </div>
      {fats.map((f,i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr auto", gap: 12, padding: "13px 22px", alignItems: "center", borderBottom: i === fats.length-1 ? "none" : "1px solid rgba(10,10,10,0.08)", background: i % 2 === 1 ? "var(--kp-soft)" : "var(--kp-white)" }}>
          <span className="kp-mono" style={{ fontSize: 10.5, letterSpacing: "0.14em" }}>{f.d}</span>
          <span style={{ fontSize: 12.5, color: "var(--kp-muted)" }}>{f.m}</span>
          <Pill bg="var(--kp-green)">{f.s}</Pill>
          <span className="kp-display" style={{ fontSize: 20, fontStyle: "italic" }}>{brl(f.v)}</span>
          <button className="kp-btn kp-btn-sm">PDF ↓</button>
        </div>
      ))}
    </div>
  );
}

function PortalAcesso() {
  return (
    <>
      <div className="kp-card" style={{ padding: 26, marginBottom: 22, background: "var(--kp-green)" }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEU ACESSO</div>
        <h2 className="kp-display" style={{ fontSize: 32, marginTop: 6 }}>Tudo que <em>você liberou</em>.</h2>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(260px,1fr))", gap: 16 }}>
        {[
          { t: "Curso Sequência Viral", c: "32 vídeos · 18h", color: "var(--kp-pink)", e: "▶" },
          { t: "Templates de proposta", c: "12 modelos editáveis", color: "var(--kp-cold)", e: "◢" },
          { t: "Grupo VIP no Discord", c: "248 membros ativos", color: "var(--kp-yellow)", e: "◉" },
          { t: "Sessões 1:1 mensais", c: "Próxima: 08 mai", color: "var(--kp-pink-soft)", e: "♪" },
        ].map((p,i) => (
          <div key={i} className="kp-card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ background: p.color, padding: 22, borderBottom: "1.5px solid var(--kp-ink)", fontFamily: "var(--kp-display)", fontSize: 56, fontStyle: "italic", lineHeight: 1 }}>{p.e}</div>
            <div style={{ padding: 16 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{p.t}</div>
              <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.14em", color: "var(--kp-muted)", marginTop: 4 }}>{p.c}</div>
              <button className="kp-btn kp-btn-sm" style={{ marginTop: 12, width: "100%" }}>Acessar →</button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function PortalPerfil() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      <div className="kp-card" style={{ padding: 22 }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEUS DADOS</div>
        <div style={{ marginTop: 14, display: "grid", gap: 10 }}>
          <PortalField l="Nome" v="Diogo Krieger"/>
          <PortalField l="Email" v="diogo@costaperf.com"/>
          <PortalField l="CPF" v="123.456.789-00"/>
          <PortalField l="Celular" v="(11) 99000-1234"/>
        </div>
      </div>
      <div className="kp-card" style={{ padding: 22 }}>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>SEGURANÇA</div>
        <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
          <button className="kp-btn" style={{ justifyContent: "flex-start" }}>Trocar senha</button>
          <button className="kp-btn" style={{ justifyContent: "flex-start" }}>Ativar 2FA</button>
          <button className="kp-btn" style={{ justifyContent: "flex-start" }}>Sessões ativas (2)</button>
          <button className="kp-btn" style={{ justifyContent: "flex-start", color: "#B22" }}>Excluir conta (LGPD)</button>
        </div>
      </div>
    </div>
  );
}
function PortalField({ l, v }) {
  return (
    <div style={{ padding: 12, background: "var(--kp-soft)", border: "1.5px solid var(--kp-ink)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <div>
        <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", color: "var(--kp-muted)" }}>{l.toUpperCase()}</div>
        <div style={{ fontSize: 13.5, fontWeight: 500, marginTop: 2 }}>{v}</div>
      </div>
      <button className="kp-btn kp-btn-sm">editar</button>
    </div>
  );
}

window.SEQ_PORTAL = Portal;
