// onboarding.jsx — AFEX PAY seller self-service onboarding (functional).
// Collects structured data -> POST /signup -> uploads KYC docs -> shows the
// provider KYC link (hybrid: we store docs AND the seller finishes KYC at the provider).
function Onboarding({ go }) {
  const STEPS = ["Dados da empresa", "Dados bancários", "Documentos", "Revisão"];
  const [step, setStep] = React.useState(0);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const [result, setResult] = React.useState(null);

  const [form, setForm] = React.useState({
    legalName: "", tradingName: "", document: "", email: "", phone: "", monthlyRevenue: "", segment: "",
    street: "", streetNumber: "", neighborhood: "", city: "", state: "", zipCode: "",
    bank: "", branchNumber: "", accountNumber: "", accountCheckDigit: "", accountType: "checking", pixKey: "",
    repName: "", repDocument: "",
  });
  const [docs, setDocs] = React.useState({});
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target ? e.target.value : e }));
  const pickDoc = (type, file) => setDocs((d) => ({ ...d, [type]: file }));
  const onlyDigits = (s) => (s || "").replace(/\D/g, "");

  const back = () => step > 0 && setStep(step - 1);
  const next = () => (step < 3 ? setStep(step + 1) : submit());

  async function submit() {
    setSubmitting(true);
    setError("");
    try {
      const doc = onlyDigits(form.document);
      const payload = {
        legalName: form.legalName,
        tradingName: form.tradingName || undefined,
        document: doc,
        email: form.email,
        phone: onlyDigits(form.phone) || undefined,
        monthlyRevenueCents: form.monthlyRevenue ? Number(onlyDigits(form.monthlyRevenue)) : undefined,
        segment: form.segment || undefined,
        address: {
          street: form.street, streetNumber: form.streetNumber, neighborhood: form.neighborhood,
          city: form.city, state: form.state, zipCode: onlyDigits(form.zipCode),
        },
        bankAccount: {
          holderName: form.legalName, holderType: "company",
          holderDocument: doc, bank: onlyDigits(form.bank) || form.bank, branchNumber: form.branchNumber,
          accountNumber: onlyDigits(form.accountNumber), accountCheckDigit: onlyDigits(form.accountCheckDigit),
          type: form.accountType,
        },
        pixKey: form.pixKey || undefined,
        representative: form.repName ? { name: form.repName, document: onlyDigits(form.repDocument) } : undefined,
      };
      const sm = await api.onboarding.signup(payload);
      for (const [type, file] of Object.entries(docs)) {
        if (file) await api.onboarding.uploadDocument(sm.id, type, file, sm.uploadToken);
      }
      setResult({ id: sm.id, kycLinkUrl: sm.kycLinkUrl });
    } catch (e) {
      setError(e.message || "Não foi possível enviar o cadastro.");
    } finally {
      setSubmitting(false);
    }
  }

  if (result) return <OnbStatus go={go} result={result} />;

  return (
    <div style={{ minHeight: "100%", background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <div className="row between" style={{ padding: "20px 32px", borderBottom: "1px solid var(--line)" }}>
        <Logo size={30} />
        <div className="row gap-16">
          <span className="faint" style={{ fontSize: 13.5 }}>Etapa {step + 1} de {STEPS.length}</span>
          <button className="btn btn-subtle btn-sm" onClick={() => go("auth/login")}>Sair</button>
        </div>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "300px 1fr" }} className="onb-grid">
        <div className="hide-mobile" style={{ borderRight: "1px solid var(--line)", padding: "40px 32px", background: "var(--bg-2)" }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>Abra sua conta</div>
          <div className="col gap-4">
            {STEPS.map((s, i) => (
              <div key={s} className="row gap-12" style={{ padding: "12px 0", opacity: i <= step ? 1 : 0.5 }}>
                <div style={{
                  width: 30, height: 30, borderRadius: "50%", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 13, fontWeight: 700, fontFamily: "var(--font-display)",
                  background: i < step ? "var(--green)" : i === step ? "var(--accent)" : "var(--surface-2)",
                  color: i <= step ? "#fff" : "var(--ink-faint)", border: i > step ? "1px solid var(--line-2)" : "none", transition: "all .3s",
                }}>{i < step ? <I.check size={16} /> : i + 1}</div>
                <div className="col" style={{ lineHeight: 1.2 }}>
                  <span style={{ fontSize: 14, fontWeight: 600, color: i === step ? "var(--ink)" : "var(--ink-soft)" }}>{s}</span>
                  {i === step && <span className="faint" style={{ fontSize: 12 }}>Em andamento</span>}
                </div>
              </div>
            ))}
          </div>
          <div className="card card-pad col gap-8" style={{ marginTop: 32, background: "var(--surface)" }}>
            <I.shield size={18} style={{ color: "var(--accent)" }} />
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>Seus dados estão seguros</div>
            <div className="faint" style={{ fontSize: 12.5, lineHeight: 1.5 }}>As fotos do KYC são enviadas direto à adquirente regulada.</div>
          </div>
        </div>

        <div style={{ overflow: "auto", padding: "48px 56px" }} className="onb-body">
          <div className="col gap-24 fade-up" key={step} style={{ maxWidth: 640, margin: "0 auto" }}>
            <div className="col gap-6">
              <div className="bar" style={{ width: 120, marginBottom: 14 }}><i style={{ width: `${(step + 1) * 25}%` }} /></div>
              <h1 style={{ fontSize: 30 }}>{STEPS[step]}</h1>
              <p className="muted" style={{ margin: 0, fontSize: 15 }}>{[
                "Conte pra gente sobre a sua empresa.",
                "Para onde enviaremos seus repasses.",
                "Envie os documentos para verificação (KYC).",
                "Revise tudo antes de enviar para análise.",
              ][step]}</p>
            </div>

            {step === 0 && <OnbCompany form={form} set={set} />}
            {step === 1 && <OnbBank form={form} set={set} />}
            {step === 2 && <OnbDocs docs={docs} pickDoc={pickDoc} />}
            {step === 3 && <OnbReview form={form} docs={docs} />}

            {error && (
              <div className="card card-pad row gap-10" style={{ background: "var(--red-wash)", border: "1px solid rgba(255,92,92,0.3)" }}>
                <I.alert size={18} style={{ color: "var(--red)", flexShrink: 0 }} />
                <span style={{ fontSize: 13.5, color: "var(--ink-soft)" }}>{error}</span>
              </div>
            )}

            <div className="row between" style={{ marginTop: 8 }}>
              <button className="btn btn-ghost" onClick={back} disabled={step === 0 || submitting}><I.chevL size={16} /> Voltar</button>
              <button className="btn btn-primary" onClick={next} disabled={submitting}>
                {submitting ? "Enviando…" : step === 3 ? "Enviar para análise" : "Continuar"} <I.arrowRight size={16} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

const Fld = ({ label, ph, value, onChange, w }) => (
  <div className="field" style={{ flex: w || 1 }}>
    <label className="label">{label}</label>
    <input className="input" placeholder={ph} value={value} onChange={onChange} />
  </div>
);

function OnbCompany({ form, set }) {
  return (
    <div className="col gap-16">
      <Fld label="Razão social" ph="Minha Loja LTDA" value={form.legalName} onChange={set("legalName")} />
      <div className="row gap-16">
        <Fld label="CNPJ" ph="00.000.000/0000-00" value={form.document} onChange={set("document")} />
        <Fld label="Nome fantasia" ph="Minha Loja" value={form.tradingName} onChange={set("tradingName")} />
      </div>
      <div className="row gap-16">
        <Fld label="E-mail" ph="contato@minhaloja.com" value={form.email} onChange={set("email")} />
        <Fld label="Telefone" ph="(11) 99999-9999" value={form.phone} onChange={set("phone")} w={0.7} />
      </div>
      <div className="row gap-16">
        <Fld label="Faturamento mensal" ph="R$ 0,00" value={form.monthlyRevenue} onChange={set("monthlyRevenue")} />
        <Fld label="Segmento" ph="Moda e acessórios" value={form.segment} onChange={set("segment")} />
      </div>
      <div className="row gap-16">
        <Fld label="Rua" ph="Av. Paulista" value={form.street} onChange={set("street")} />
        <Fld label="Número" ph="1000" value={form.streetNumber} onChange={set("streetNumber")} w={0.4} />
      </div>
      <div className="row gap-16">
        <Fld label="Bairro" ph="Bela Vista" value={form.neighborhood} onChange={set("neighborhood")} />
        <Fld label="Cidade" ph="São Paulo" value={form.city} onChange={set("city")} />
        <Fld label="UF" ph="SP" value={form.state} onChange={set("state")} w={0.3} />
        <Fld label="CEP" ph="01310-100" value={form.zipCode} onChange={set("zipCode")} w={0.6} />
      </div>
      <div className="row gap-16">
        <Fld label="Representante legal" ph="Nome do sócio" value={form.repName} onChange={set("repName")} />
        <Fld label="CPF do representante" ph="000.000.000-00" value={form.repDocument} onChange={set("repDocument")} />
      </div>
    </div>
  );
}

function OnbBank({ form, set }) {
  return (
    <div className="col gap-16">
      <div className="row gap-16">
        <Fld label="Banco (código)" ph="341" value={form.bank} onChange={set("bank")} w={0.6} />
        <div className="field" style={{ flex: 0.7 }}>
          <label className="label">Tipo de conta</label>
          <select className="input" value={form.accountType} onChange={set("accountType")}>
            <option value="checking">Corrente</option>
            <option value="savings">Poupança</option>
          </select>
        </div>
      </div>
      <div className="row gap-16">
        <Fld label="Agência" ph="0001" value={form.branchNumber} onChange={set("branchNumber")} w={0.5} />
        <Fld label="Conta" ph="12345" value={form.accountNumber} onChange={set("accountNumber")} />
        <Fld label="Dígito" ph="6" value={form.accountCheckDigit} onChange={set("accountCheckDigit")} w={0.3} />
      </div>
      <Fld label="Chave PIX (recebimento)" ph="e-mail, CPF/CNPJ, telefone ou aleatória" value={form.pixKey} onChange={set("pixKey")} />
      <div className="card card-pad row gap-12" style={{ background: "var(--green-wash)", border: "1px solid rgba(34,197,94,0.25)" }}>
        <I.shield size={20} style={{ color: "var(--green)", flexShrink: 0 }} />
        <span style={{ fontSize: 13.5, color: "var(--ink-soft)" }}>A titularidade da conta deve corresponder ao documento cadastrado.</span>
      </div>
    </div>
  );
}

function DocRow({ label, sub, type, file, onPick }) {
  const ref = React.useRef();
  const up = !!file;
  return (
    <div className="card card-pad row between" style={{ padding: 18 }}>
      <div className="row gap-14">
        <div style={{ width: 44, height: 44, borderRadius: 10, background: up ? "var(--green-wash)" : "var(--surface-2)", color: up ? "var(--green)" : "var(--ink-faint)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          {up ? <I.checkCircle size={22} /> : <I.doc size={22} />}
        </div>
        <div className="col gap-2">
          <span style={{ fontSize: 14.5, fontWeight: 600 }}>{label}</span>
          <span className="faint" style={{ fontSize: 12.5 }}>{up ? file.name : sub}</span>
        </div>
      </div>
      <input ref={ref} type="file" accept="image/*,application/pdf" style={{ display: "none" }} onChange={(e) => onPick(type, e.target.files[0])} />
      <button className={"btn btn-sm " + (up ? "btn-subtle" : "btn-ghost")} onClick={() => ref.current.click()}>{up ? "Substituir" : "Enviar"}</button>
    </div>
  );
}

function OnbDocs({ docs, pickDoc }) {
  return (
    <div className="col gap-12">
      <DocRow label="Documento da empresa" sub="Contrato social / Cartão CNPJ · PDF ou foto" type="company_doc" file={docs.company_doc} onPick={pickDoc} />
      <DocRow label="Documento do representante" sub="RG ou CNH · foto" type="rep_doc" file={docs.rep_doc} onPick={pickDoc} />
      <DocRow label="Selfie com o documento" sub="Foto sua segurando o documento" type="selfie_with_doc" file={docs.selfie_with_doc} onPick={pickDoc} />
    </div>
  );
}

function OnbReview({ form, docs }) {
  const onlyDigits = (s) => (s || "").replace(/\D/g, "");
  const docCount = Object.values(docs).filter(Boolean).length;
  const rows = [
    ["Empresa", form.legalName || "—"],
    ["Documento", form.document || "—"],
    ["E-mail", form.email || "—"],
    ["Conta", form.bank ? `Banco ${onlyDigits(form.bank)} · Ag ${form.branchNumber} · CC ${form.accountNumber}-${form.accountCheckDigit}` : "—"],
    ["Chave PIX", form.pixKey || "—"],
    ["Documentos", `${docCount} de 3 anexados`],
  ];
  return (
    <div className="col gap-16">
      <div className="card" style={{ overflow: "hidden" }}>
        {rows.map(([k, v], i) => (
          <div key={k} className="row between" style={{ padding: "16px 20px", borderTop: i ? "1px solid var(--line)" : "none" }}>
            <span className="muted" style={{ fontSize: 14 }}>{k}</span>
            <span style={{ fontSize: 14, fontWeight: 600, textAlign: "right" }}>{v}</span>
          </div>
        ))}
      </div>
      <label className="row gap-10" style={{ fontSize: 13.5, color: "var(--ink-soft)", cursor: "pointer" }}>
        <input type="checkbox" defaultChecked style={{ accentColor: "var(--accent)" }} />
        Declaro que as informações são verdadeiras.
      </label>
    </div>
  );
}

function OnbStatus({ go, result }) {
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");

  async function openKyc() {
    setLoading(true);
    setErr("");
    try {
      // Generated on demand (manual trigger) because the link expires in ~20 min.
      const link = await api.onboarding.kycLink(result.id);
      window.open(link.url, "_blank", "noopener");
    } catch (e) {
      setErr("Não foi possível gerar o link agora. Tente de novo.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ minHeight: "100%", display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "radial-gradient(800px 500px at 50% 0%, rgba(255,90,0,0.1), transparent 60%), var(--bg)" }}>
      <div className="col gap-24 fade-up" style={{ maxWidth: 460, textAlign: "center", alignItems: "center" }}>
        <div style={{ width: 80, height: 80, borderRadius: 22, background: "var(--green-wash)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.check size={40} /></div>
        <div className="col gap-10">
          <h1 style={{ fontSize: 32 }}>Cadastro enviado!</h1>
          <p className="muted" style={{ margin: 0, fontSize: 16, lineHeight: 1.55 }}>
            Falta um passo: gere o link e conclua a <b>verificação de identidade (foto)</b> na página segura da adquirente. O link expira em ~20 min — abra quando estiver pronto.
          </p>
        </div>
        <button className="btn btn-primary btn-lg btn-block" onClick={openKyc} disabled={loading}>
          {loading ? "Gerando link…" : <>Gerar link de verificação <I.arrowRight size={18} /></>}
        </button>
        {err && <span style={{ color: "var(--red)", fontSize: 13 }}>{err}</span>}
        <button className="btn btn-subtle btn-block" onClick={() => go("auth/login")}>Voltar ao login</button>
        <span className="faint" style={{ fontSize: 13 }}>Análise concluída em até 24h úteis · ID {result.id ? result.id.slice(-8) : ""}</span>
      </div>
    </div>
  );
}

window.Onboarding = Onboarding;
