// SellerOnboarding.jsx — multi-step onboarding for a new seller signing up to sell on Allen.
// Steps: business info -> RFC/tax -> address -> bank -> first product (optional) -> done.

const { useState: useOnbState } = React;

const STEPS = [
  { id: "negocio",    label: "Tu negocio" },
  { id: "fiscal",     label: "Datos fiscales" },
  { id: "direccion",  label: "Dirección" },
  { id: "banco",      label: "Cuenta bancaria" },
  { id: "verifica",   label: "Verificación" },
];

const SellerOnboarding = ({ onNav }) => {
  const [step, setStep] = useOnbState(0);
  const [form, setForm] = useOnbState({
    business: "", category: "herramientas", year: "", desc: "",
    rfc: "", regimen: "rif", razonSocial: "",
    street: "", area: "", city: "Puerto Vallarta", state: "Jalisco", zip: "",
    bank: "BBVA", clabe: "", titular: "",
    accept: false,
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toast = useToast();

  const next = () => {
    if (step < STEPS.length - 1) setStep(s => s + 1);
    else {
      toast("¡Solicitud enviada! Te avisamos en menos de 24 h");
      onNav("seller");
    }
  };
  const prev = () => step > 0 && setStep(s => s - 1);

  return (
    <div style={{ background: "var(--bg)", minHeight: "calc(100vh - 240px)" }}>
      <div style={{ maxWidth: 880, margin: "0 auto", padding: "40px 32px" }}>
        <Breadcrumb items={["Inicio", "Vende en Allen", "Registro"]} />
        <h1 className="display-sm" style={{ marginBottom: 8 }}>Vende en Allen</h1>
        <p className="body" style={{ color: "var(--fg-muted)", marginBottom: 32 }}>Te toma 5 minutos. Aprobamos tu tienda en menos de 24 horas.</p>

        {/* Stepper */}
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 32, gap: 8 }}>
          {STEPS.map((s, i) => (
            <button key={s.id} onClick={() => i < step && setStep(i)}
              style={{ flex: 1, background: "transparent", border: 0, cursor: i < step ? "pointer" : "default", textAlign: "left", padding: 0 }}>
              <div style={{ height: 4, borderRadius: 2, background: i <= step ? "var(--primary)" : "var(--border)" }} />
              <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 10,
                  background: i < step ? "var(--success)" : i === step ? "var(--primary)" : "var(--bg-elev-2)",
                  color: i <= step ? "#fff" : "var(--fg-muted)",
                  font: "700 11px var(--font-sans)",
                  display: "grid", placeItems: "center",
                }}>{i < step ? "✓" : i + 1}</span>
                <span style={{ font: i === step ? "700 12px var(--font-sans)" : "500 12px var(--font-sans)", color: i <= step ? "var(--fg-strong)" : "var(--fg-muted)" }}>{s.label}</span>
              </div>
            </button>
          ))}
        </div>

        <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-xl)", padding: 36 }}>
          {step === 0 && <StepBusiness form={form} set={set} />}
          {step === 1 && <StepTax form={form} set={set} />}
          {step === 2 && <StepAddress form={form} set={set} />}
          {step === 3 && <StepBank form={form} set={set} />}
          {step === 4 && <StepReview form={form} set={set} />}

          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 28, paddingTop: 20, borderTop: "1px solid var(--border-soft)" }}>
            <button onClick={prev} disabled={step === 0}
              style={{ background: "transparent", color: step === 0 ? "var(--fg-disabled)" : "var(--fg-strong)", border: 0, font: "600 13px var(--font-sans)", cursor: step === 0 ? "default" : "pointer", padding: "10px 0" }}>
              ← Atrás
            </button>
            <PrimaryButton onClick={next}>
              {step === STEPS.length - 1 ? "Enviar solicitud" : "Continuar"}
            </PrimaryButton>
          </div>
        </div>

        {/* Help footer */}
        <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 12, padding: 20, background: "var(--primary-soft)", borderRadius: "var(--radius-lg)" }}>
          <AllenIcon name="support_agent" size={22} color="var(--primary-press)" />
          <div style={{ flex: 1 }}>
            <div className="title-sm">¿Dudas con el registro?</div>
            <div className="body-sm" style={{ marginTop: 2 }}>WhatsApp: +52 33 5555 0202 · sellers@allenmx.com</div>
          </div>
        </div>
      </div>
    </div>
  );
};

const StepBusiness = ({ form, set }) => (
  <>
    <h2 className="headline-sm" style={{ marginBottom: 6 }}>Cuéntanos de tu negocio</h2>
    <p className="body-sm" style={{ marginBottom: 24 }}>Estos datos se ven en tu tienda pública.</p>
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Field label="Nombre comercial">
        <TextInput placeholder="Ferretería El Tornillo" value={form.business} onChange={e => set("business", e.target.value)} />
      </Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Field label="Categoría principal">
          <select value={form.category} onChange={e => set("category", e.target.value)}
            style={{ ...inputStyle, width: "100%", appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
            {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
        </Field>
        <Field label="Año de fundación" hint="Opcional">
          <TextInput type="number" placeholder="2001" value={form.year} onChange={e => set("year", e.target.value)} />
        </Field>
      </div>
      <Field label="Descripción de tu tienda" hint="Máximo 200 caracteres. Lo ven los compradores en tu perfil.">
        <textarea rows={3} value={form.desc} onChange={e => set("desc", e.target.value)}
          placeholder="Ferretería con 25 años en Puerto Vallarta. Tornillería, herramientas y materiales para construcción."
          style={{ ...inputStyle, fontFamily: "var(--font-sans)", resize: "vertical" }} />
      </Field>
    </div>
  </>
);

const StepTax = ({ form, set }) => (
  <>
    <h2 className="headline-sm" style={{ marginBottom: 6 }}>Datos fiscales</h2>
    <p className="body-sm" style={{ marginBottom: 24 }}>Necesarios para facturar y cumplir con SAT. Cifrados extremo a extremo.</p>
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Field label="Razón social"><TextInput placeholder="Tornillería El Tornillo S.A. de C.V." value={form.razonSocial} onChange={e => set("razonSocial", e.target.value)} /></Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Field label="RFC con homoclave"><TextInput placeholder="TTO010415AB1" value={form.rfc} onChange={e => set("rfc", e.target.value.toUpperCase())} maxLength={13} style={{ fontFamily: "var(--font-mono)", letterSpacing: ".08em" }} /></Field>
        <Field label="Régimen fiscal">
          <select value={form.regimen} onChange={e => set("regimen", e.target.value)}
            style={{ ...inputStyle, width: "100%", appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
            <option value="rif">RIF — Régimen de Incorporación Fiscal</option>
            <option value="rg">Régimen General</option>
            <option value="resico">RESICO — Régimen Simplificado de Confianza</option>
            <option value="moral">Persona Moral</option>
          </select>
        </Field>
      </div>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
        <AllenIcon name="lock" size={18} color="var(--fg-muted)" />
        <span className="body-sm">Tus datos fiscales están cifrados. Solo el SAT y tú podemos verlos. Allen usa ellos para emitir tu CFDI de comisión.</span>
      </div>
    </div>
  </>
);

const StepAddress = ({ form, set }) => (
  <>
    <h2 className="headline-sm" style={{ marginBottom: 6 }}>Dirección de origen</h2>
    <p className="body-sm" style={{ marginBottom: 24 }}>Desde dónde envías tus pedidos. Puedes agregar más direcciones después.</p>
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Field label="Calle y número"><TextInput placeholder="Av. Francisco Villa 1180" value={form.street} onChange={e => set("street", e.target.value)} /></Field>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
        <Field label="Colonia"><TextInput placeholder="Versalles" value={form.area} onChange={e => set("area", e.target.value)} /></Field>
        <Field label="Código postal"><TextInput placeholder="48330" value={form.zip} onChange={e => set("zip", e.target.value)} maxLength={5} /></Field>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Field label="Ciudad"><TextInput value={form.city} onChange={e => set("city", e.target.value)} /></Field>
        <Field label="Estado"><TextInput value={form.state} onChange={e => set("state", e.target.value)} /></Field>
      </div>
    </div>
  </>
);

const StepBank = ({ form, set }) => (
  <>
    <h2 className="headline-sm" style={{ marginBottom: 6 }}>Cuenta para depósitos</h2>
    <p className="body-sm" style={{ marginBottom: 24 }}>Allen deposita el monto neto de tus ventas (descontada la comisión) cada lunes.</p>
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Field label="Banco">
        <select value={form.bank} onChange={e => set("bank", e.target.value)}
          style={{ ...inputStyle, width: "100%", appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
          {["BBVA", "Banorte", "Santander", "Banamex", "HSBC", "Scotiabank", "Banco Azteca", "Inbursa", "Mercado Pago"].map(b => <option key={b} value={b}>{b}</option>)}
        </select>
      </Field>
      <Field label="CLABE interbancaria" hint="18 dígitos">
        <TextInput placeholder="012 320 0123 4567 8901" value={form.clabe} onChange={e => set("clabe", e.target.value.replace(/\D/g, ""))} maxLength={18} style={{ fontFamily: "var(--font-mono)", letterSpacing: ".05em" }} />
      </Field>
      <Field label="Titular de la cuenta"><TextInput placeholder="Tornillería El Tornillo S.A. de C.V." value={form.titular} onChange={e => set("titular", e.target.value)} /></Field>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 14, background: "var(--success-bg)", borderRadius: "var(--radius-md)" }}>
        <AllenIcon name="verified" size={18} color="var(--success)" />
        <div className="body-sm" style={{ color: "var(--fg-strong)" }}>
          <strong>Cuenta verificada por SPEI.</strong> Validamos que el titular coincida con tu razón social.
        </div>
      </div>
    </div>
  </>
);

const StepReview = ({ form, set }) => (
  <>
    <h2 className="headline-sm" style={{ marginBottom: 6 }}>Revisa y envía</h2>
    <p className="body-sm" style={{ marginBottom: 24 }}>Te avisamos en menos de 24 horas. Mientras tanto, puedes preparar tu primer producto.</p>

    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {[
        { k: "Negocio",      v: form.business || "—" },
        { k: "Categoría",    v: CATEGORIES.find(c => c.id === form.category)?.label },
        { k: "RFC",          v: form.rfc || "—", mono: true },
        { k: "Razón social", v: form.razonSocial || "—" },
        { k: "Dirección",    v: form.street ? `${form.street}, ${form.area}, ${form.city}` : "—" },
        { k: "Banco",        v: `${form.bank} · ${form.clabe ? "•••• " + form.clabe.slice(-4) : "—"}` },
      ].map(row => (
        <div key={row.k} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border-soft)" }}>
          <span className="body-sm">{row.k}</span>
          <span style={{ font: "600 14px var(--font-sans)", color: "var(--fg-strong)", fontFamily: row.mono ? "var(--font-mono)" : undefined, textAlign: "right", maxWidth: "60%" }}>{row.v}</span>
        </div>
      ))}
    </div>

    <label style={{ display: "flex", gap: 12, marginTop: 20, cursor: "pointer", padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
      <input type="checkbox" checked={form.accept} onChange={e => set("accept", e.target.checked)} style={{ accentColor: "var(--primary)", width: 18, height: 18, marginTop: 2 }} />
      <span className="body-sm" style={{ color: "var(--fg-strong)" }}>
        Acepto el <a style={{ color: "var(--primary)", fontWeight: 700 }}>Contrato de Vendedor</a>, la comisión <strong>8.5% por venta</strong> + <strong>2.9% + $4 MXN</strong> de procesamiento de pago, y la <a style={{ color: "var(--primary)", fontWeight: 700 }}>Política de Devoluciones</a> de Allen.
      </span>
    </label>
  </>
);

window.SellerOnboarding = SellerOnboarding;
