// ============================================================
// flow2a.jsx · I0 hub + IP1–IP5 (Personal import sub-wizard)
// ============================================================

const IMPORT_STEPS = ["Plantilla", "Subir", "Mapear", "Revisar", "Importar"];
function tenantHeader(breadcrumb, badge) {
  return { kind: "tenant", breadcrumb, badge, badgeTone: "gray",
    person: { name: window.b("director.full_name"), sub: window.b("director.title"), avatarName: window.b("director.full_name"), color: "var(--tenant-brand)" } };
}
function ImportWizard({ step, breadcrumb, head, children, footer, badge }) {
  return (
    <ScreenFrame header={tenantHeader(breadcrumb, badge)} maxWidth={880}>
      <WizardStepper steps={IMPORT_STEPS} current={step} style={{ marginBottom: 30 }} />
      {head}
      {children}
      {footer}
    </ScreenFrame>
  );
}

// ---------- I0 · Hub ----------
function I0({ state = "happy", openModal }) {
  const cats = [
    { icon: "users", t: "Personal", d: "Maestros · ateliers · coord · finanzas · portero", count: "0 cargados · esperado ~28", status: ["VACÍO", "gray"], go: "IP1" },
    { icon: "home", t: "Familias y tutores", d: "Padres, madres, abuelos", count: "0 cargados · esperado ~614", status: ["VACÍO", "gray"], go: "IF4" },
    { icon: "backpack", t: "Alumnos", d: "Asignación a grupos + vinculación con tutores", count: "0 cargados · esperado ~325", status: ["VACÍO", "gray"], go: "IA4" },
    { icon: "receipt", t: "Conceptos de cobro", d: "Inscripción · colegiaturas · descuentos", count: "0 configurados · template disponible", status: ["VACÍO", "gray"], go: "I4" },
    { icon: "calendar-check", t: "Calendario académico", d: "Ya armado en onboarding · 185 días · 2 vacaciones", count: "Ciclo 2026–2027 · listo", status: ["CONFIGURADO", "success"], go: null },
  ];
  return (
    <ScreenFrame header={tenantHeader(["Dashboard", "Centro de carga"])} maxWidth={980}>
      <WizardHead title={"Cargar la comunidad de " + window.b("school.short_name")} subtitle="5 categorías para que la escuela arranque · puedes hacerlas en cualquier orden · todo es reversible." />
      {state === "loading" ? <SLoading variant="cards" rows={6} cols={3} /> : (
        <React.Fragment>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
            {cats.map((c, i) => (
              <Card key={i} interactive className="animate-fade-up" onClick={() => c.go && window.goTo(c.go)} style={{ padding: 18, animationDelay: (0.05 * i) + "s" }}>
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 12 }}>
                  <IconBox icon={c.icon} size={40} iconSize={20} />
                  <Badge tone={c.status[1]} dot={c.status[1] !== "gray"}>{c.status[0]}</Badge>
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{c.t}</div>
                <div style={{ fontSize: 12, color: "var(--xk-text-secondary)", marginTop: 4, lineHeight: 1.45, minHeight: 34 }}>{c.d}</div>
                <div style={{ fontSize: 11.5, color: "var(--xk-text-muted)", marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--xk-border)" }}>{c.count}</div>
              </Card>
            ))}
            {/* Concierge card */}
            <Card className="animate-fade-up" style={{ padding: 18, border: "1px dashed var(--xk-border-strong)", background: "var(--xk-surface-2)", animationDelay: "0.3s" }}>
              <IconBox icon="headset" size={40} bg="var(--xk-surface-3)" color="var(--xk-text-secondary)" iconSize={20} />
              <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 12 }}>¿Prefieres concierge?</div>
              <div style={{ fontSize: 12, color: "var(--xk-text-secondary)", marginTop: 4, lineHeight: 1.45 }}>Manda los CSV a hola@xokai.app · Xokai los procesa en 24 h.</div>
              <Btn variant="secondary" size="sm" style={{ marginTop: 12 }} onClick={() => openModal(<MConfirmDestructive title="Enviar solicitud a concierge" description={"Xokai recibirá tu solicitud para procesar la carga de " + window.b("school.short_name") + ". Te contactamos a " + window.b("director.email") + " en menos de 24 h."} actionLabel="Enviar solicitud" onClose={openModal.close} onConfirm={openModal.close} />)}>Solicitar concierge</Btn>
            </Card>
          </div>
          {/* Footer progress */}
          <div style={{ marginTop: 22, display: "flex", alignItems: "center", gap: 16, padding: "16px 18px", background: "var(--xk-surface)", border: "1px solid var(--xk-border)", borderRadius: 12 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 7 }}>
                <span style={{ fontSize: 12.5, fontWeight: 600 }}>Progreso · 1 de 5 categorías</span>
                <span className="xk-mono" style={{ fontSize: 12, color: "var(--xk-text-muted)" }}>20%</span>
              </div>
              <div style={{ height: 6, background: "var(--xk-surface-2)", borderRadius: 999, overflow: "hidden" }}><div style={{ height: "100%", width: "20%", background: "var(--tenant-brand)", borderRadius: 999, transition: "width 400ms ease" }}></div></div>
            </div>
            <Btn variant="secondary" disabled icon="lock">Activar magic link masivo a padres</Btn>
          </div>
        </React.Fragment>
      )}
    </ScreenFrame>
  );
}

// ---------- IP1 · Plantilla ----------
function IP1({ state = "happy" }) {
  const cols = [
    ["nombre_completo", "SÍ", "Ana Sofía Reyes Domínguez"],
    ["email", "SÍ", "ana.reyes@habitatlc.mx"],
    ["puesto", "SÍ", "Maestra titular · Coordinadora · Portero…"],
    ["telefono", "OPCIONAL", "33 1234 5678"],
    ["nivel_asignado", "OPCIONAL", "Primaria · Kinder · null si coord general"],
    ["grupo_titular", "OPCIONAL", "3°-A · K2-A · null si no es titular"],
    ["rfc", "OPCIONAL", "RERA850314ABC"],
  ];
  return (
    <ImportWizard step={1} breadcrumb={["Centro de carga", "Personal"]} badge="Sub-wizard 1 de 3 con CSV"
      head={<WizardHead eyebrow="Paso 1 de 5" title="Descarga la plantilla para Personal" subtitle="Si ya tienes los datos en Excel, sáltate este paso · solo asegura que las columnas se parezcan al template." />}
      footer={<WizardFooter backLabel="← Centro de carga" onBack={() => window.goTo("I0")} nextLabel="Ya tengo el archivo · subir" />}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Card style={{ padding: 18, border: "2px solid var(--xk-accent)", background: "var(--xokai-purple-tint)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <Icon name="file-spreadsheet" size={28} color="var(--xk-accent)" /><Badge tone="purple">RECOMENDADO</Badge>
          </div>
          <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 12 }}>Excel · .xlsx</div>
          <div style={{ fontSize: 12, color: "var(--xk-text-secondary)", marginTop: 3 }}>Funciona con Numbers y Google Sheets</div>
          <Btn variant="primary" full icon="download" style={{ marginTop: 14 }}>Descargar template-personal.xlsx</Btn>
        </Card>
        <Card style={{ padding: 18 }}>
          <Icon name="file-text" size={28} color="var(--xk-text-secondary)" />
          <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 12 }}>CSV · .csv</div>
          <div style={{ fontSize: 12, color: "var(--xk-text-secondary)", marginTop: 3 }}>UTF-8 con BOM · sistemas legacy</div>
          <Btn variant="secondary" full icon="download" style={{ marginTop: 14 }}>Descargar template-personal.csv</Btn>
        </Card>
      </div>
      <Label style={{ marginTop: 22 }}>Columnas que incluye la plantilla</Label>
      <DataTable style={{ marginTop: 10 }} columns={[{ label: "Columna", w: "1.2fr" }, { label: "Requerido", w: "0.8fr" }, { label: "Ejemplo", w: "1.8fr" }]}>
        {cols.map((c, i) => (
          <TRow key={i} last={i === cols.length - 1} columns={[{ w: "1.2fr" }, { w: "0.8fr" }, { w: "1.8fr" }]}
            cells={[
              <span className="xk-mono" style={{ fontSize: 12.5, fontWeight: 500 }}>{c[0]}</span>,
              <Badge tone={c[1] === "SÍ" ? "danger" : "gray"}>{c[1]}</Badge>,
              <span style={{ fontSize: 12.5, color: "var(--xk-text-muted)" }}>{c[2]}</span>,
            ]} />
        ))}
      </DataTable>
      <Banner tone="neutral" icon="lightbulb" style={{ marginTop: 16 }}>¿Ya tienes el archivo de tu sistema actual? No necesitas reescribirlo · en el siguiente paso Xokai detecta automáticamente columnas con otros nombres y las empareja.</Banner>
    </ImportWizard>
  );
}

// ---------- IP2 · Subir ----------
function IP2({ state = "happy" }) {
  const [drag, setDrag] = useState(false);
  const showError = state === "error";
  return (
    <ImportWizard step={2} breadcrumb={["Centro de carga", "Personal"]}
      head={<WizardHead eyebrow="Paso 2 de 5" title={"Sube el archivo con el personal de " + window.b("school.short_name")} subtitle="Acepta .xlsx, .xls y .csv hasta 5 MB · una sola hoja por archivo." />}
      footer={<WizardFooter backLabel="← Atrás" nextLabel="Continuar a mapear" nextDisabled={state === "empty"} />}>
      <div onDragOver={e => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)} onDrop={e => { e.preventDefault(); setDrag(false); }}
        style={{ borderRadius: 14, border: "2px dashed " + (drag ? "var(--xk-accent)" : "var(--xk-accent-medium)"),
          background: drag ? "var(--xk-accent-light)" : "var(--xokai-purple-tint)", padding: "40px 24px", textAlign: "center", transition: "all 160ms ease" }}>
        <Icon name="upload-cloud" size={drag ? 54 : 48} color="var(--xk-accent)" style={{ transition: "all 160ms ease" }} />
        <div style={{ fontSize: 15, fontWeight: 600, marginTop: 12 }}>Arrastra tu archivo aquí</div>
        <div style={{ fontSize: 13, color: "var(--xk-text-secondary)", marginTop: 3 }}>o haz click para seleccionar desde tu computadora</div>
        <div style={{ marginTop: 16 }}><Btn variant="primary" icon="folder">Seleccionar archivo</Btn></div>
        <div style={{ fontSize: 11.5, color: "var(--xk-text-muted)", marginTop: 14 }}>Formatos: .xlsx · .xls · .csv · máximo 5 MB · UTF-8</div>
      </div>

      {showError && <Banner tone="danger" icon="alert-circle" style={{ marginTop: 16 }}>No pudimos leer este archivo · solo aceptamos .xlsx, .xls o .csv · este archivo es .docx. ¿Lo exportas de nuevo?</Banner>}

      {state !== "empty" && !showError && (
        <React.Fragment>
          <Label style={{ marginTop: 22 }}>Archivos subidos recientemente</Label>
          <Card style={{ padding: "12px 16px", marginTop: 10, display: "flex", alignItems: "center", gap: 12 }}>
            <Icon name="file-spreadsheet" size={22} color="var(--xk-success)" />
            <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600 }}>personal-habitat-jun.xlsx</div><div style={{ fontSize: 11.5, color: "var(--xk-text-muted)" }}>28 filas · 8 columnas · subido hace 2 min</div></div>
            <Badge tone="success" dot>VÁLIDO</Badge>
            <button className="xk-iconbtn"><Icon name="x" size={16} /></button>
          </Card>
        </React.Fragment>
      )}
      <Banner tone="success" icon="shield-check" style={{ marginTop: 16 }}>El archivo no se almacena en Xokai · solo procesamos las filas para crear los registros · el archivo original se borra al finalizar la importación.</Banner>
    </ImportWizard>
  );
}

// ---------- IP3 · Mapear ----------
function IP3({ state = "happy" }) {
  const rows = [
    ["nombre_completo", "full_name", "DETECTADO", false],
    ["correo", "email", "DETECTADO", false],
    ["puesto_actual", "— Elige campo —", "REVISAR", true],
    ["telefono_personal", "phone", "DETECTADO", false],
    ["nivel_asignado", "academic_level", "DETECTADO", false],
    ["grupo_titular", "homeroom_group", "DETECTADO", false],
    ["fecha_ingreso_inst", "— Elige campo —", "REVISAR", true],
    ["rfc", "rfc", "DETECTADO", false],
  ];
  const cols = [{ w: "1.4fr" }, { w: "40px", align: "center" }, { w: "1.6fr" }, { w: "0.9fr", align: "right" }];
  return (
    <ImportWizard step={3} breadcrumb={["Centro de carga", "Personal"]}
      head={<WizardHead eyebrow="Paso 3 de 5" title="Empareja las columnas del archivo con los campos de Xokai" subtitle="Detectamos automáticamente 6 de 8 columnas · revisa las 2 que faltan (marcadas en amarillo)." />}
      footer={<WizardFooter saveLabel="Guardar borrador" nextLabel="Continuar a revisión" />}>
      <Card style={{ padding: "12px 16px", marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
        <Icon name="file-spreadsheet" size={22} color="var(--xk-success)" />
        <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600 }}>personal-habitat-jun.xlsx</div><div style={{ fontSize: 11.5, color: "var(--xk-text-muted)" }}>28 filas · 8 columnas · subido hace 12 segundos</div></div>
        <Btn variant="secondary" size="sm" icon="refresh-cw">Cambiar archivo</Btn>
      </Card>
      <DataTable columns={[{ label: "Columna en tu archivo", w: "1.4fr" }, { label: "", w: "40px", align: "center" }, { label: "Campo en Xokai", w: "1.6fr" }, { label: "Status", w: "0.9fr", align: "right" }]}>
        {rows.map((r, i) => (
          <TRow key={i} last={i === rows.length - 1} columns={cols} tint={r[3] ? "var(--xk-warning-tint)" : null}
            cells={[
              <span className="xk-mono" style={{ fontSize: 12.5, fontWeight: 500 }}>{r[0]}</span>,
              <Icon name="arrow-right" size={14} color="var(--xk-text-muted)" />,
              <div style={{ maxWidth: 240 }}><Select value={r[1]} error={r[3]} options={r[3] ? ["— Elige campo —", "role", "title", "position", "hired_at", "start_date", "Ignorar esta columna"] : [r[1]]} /></div>,
              <Badge tone={r[3] ? "warning" : "success"} dot>{r[2]}</Badge>,
            ]} />
        ))}
      </DataTable>
      <Banner tone="info" style={{ marginTop: 16 }}>Xokai recordará este mapeo · si subes otro archivo con las mismas columnas, no tendrás que mapear de nuevo.</Banner>
    </ImportWizard>
  );
}

// ---------- IP4 · Revisar ----------
function IP4({ state = "happy", openModal }) {
  const cols = [{ w: "1.4fr" }, { w: "1.6fr" }, { w: "1.3fr" }, { w: "0.9fr" }, { w: "36px", align: "right" }];
  const rows = [
    ["Ana Sofía Reyes Domínguez", "ana.reyes@habitatlc.mx", "Maestra titular K2-A", "LISTO", "success", false],
    ["Carlos Méndez Ruiz", "carlos.mendez@habitatlc.mx", "Coordinador escolar", "LISTO", "success", false],
    ["María Fernanda López", "mfernandalopez@gmail", "Atelierista", "EMAIL INVÁLIDO", "warning", true],
    ["José Antonio Pérez", "joseperez@habitatlc.mx", "Maestro de inglés", "EMAIL DUPLICADO", "warning", true],
    ["Laura Vázquez García", "laura.vazquez@habitatlc.mx", "Maestra titular 1°-A", "LISTO", "success", false],
  ];
  return (
    <ImportWizard step={4} breadcrumb={["Centro de carga", "Personal"]} badge="2 filas con warning"
      head={<WizardHead eyebrow="Paso 4 de 5" title="28 personas detectadas · 26 listas · 2 con warning" subtitle="Las warnings no bloquean el import · puedes corregirlas ahora o después en el perfil de cada persona." />}
      footer={<WizardFooter backLabel="← Atrás · ajustar mapeo" next={false}>
        <Btn variant="secondary" onClick={() => openModal(<MConfirmDestructive title="Importar solo los listos" description="Se crearán 26 cuentas activas. Las 2 filas con warning quedarán pendientes de revisión." actionLabel="Sí, importar 26" onClose={openModal.close} onConfirm={() => { openModal.close(); window.goTo("IP5"); }} />)}>Importar solo los 26 listos</Btn>
        <Btn variant="primary" onClick={() => openModal(<MConfirmDestructive title="Importar las 28 personas" description="Esta acción crea 28 cuentas activas (26 listas + 2 con warning). Las warnings se podrán corregir después." actionLabel="Sí, importar 28" confirmWord="IMPORTAR" affected={28} onClose={openModal.close} onConfirm={() => { openModal.close(); window.goTo("IP5"); }} />)}>Importar las 28</Btn>
      </WizardFooter>}>
      <KpiGrid style={{ marginBottom: 16 }} items={[
        { label: "Total filas", value: "28" },
        { label: "Listos para importar", value: "26", tone: "success" },
        { label: "Con warning", value: "2", tone: "warning" },
        { label: "Bloqueantes", value: "0" },
      ]} />
      <DataTable columns={[{ label: "Nombre", w: "1.4fr" }, { label: "Email", w: "1.6fr" }, { label: "Puesto", w: "1.3fr" }, { label: "Status", w: "0.9fr" }, { label: "", w: "36px", align: "right" }]}>
        {rows.map((r, i) => (
          <TRow key={i} columns={cols} tint={r[5] ? "var(--xk-warning-tint)" : null}
            cells={[
              <span style={{ fontSize: 13, fontWeight: 500 }}>{r[0]}</span>,
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: r[5] ? "var(--xk-warning)" : "var(--xk-text-secondary)" }}>{r[5] && <Icon name="alert-triangle" size={13} color="var(--xk-warning)" />}{r[1]}</span>,
              <span style={{ fontSize: 12.5, color: "var(--xk-text-secondary)" }}>{r[2]}</span>,
              <Badge tone={r[4]} dot>{r[3]}</Badge>,
              r[5] ? <button onClick={() => openModal(<MEditRow onClose={openModal.close} name={r[0]} email={r[1]} />)} className="xk-iconbtn is-warn"><Icon name="pencil" size={15} /></button>
                   : <button className="xk-iconbtn"><Icon name="more-vertical" size={15} /></button>,
            ]} />
        ))}
        <TRow last columns={[{ w: "1fr" }]} cells={[<button style={{ width: "100%", border: "none", background: "transparent", cursor: "pointer", fontSize: 12.5, color: "var(--xk-text-secondary)", padding: 4, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>Ver siguientes 10 personas <Icon name="chevron-down" size={14} /></button>]} />
      </DataTable>
    </ImportWizard>
  );
}
// inline edit-row modal
function MEditRow({ onClose, name, email }) {
  return (
    <ModalShell width={460} onClose={onClose}>
      <div style={{ padding: 24 }}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Corregir fila</h3>
        <p style={{ margin: "6px 0 18px", fontSize: 13, color: "var(--xk-text-secondary)" }}>{name}</p>
        <Field label="Email" error="Revisa el dominio · falta .com / .mx"><Input value={email} error /></Field>
        <div style={{ display: "flex", gap: 10, marginTop: 22, justifyContent: "flex-end" }}>
          <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" onClick={onClose}>Guardar fila</Btn>
        </div>
      </div>
    </ModalShell>
  );
}
window.MEditRow = MEditRow;

// ---------- IP5 · Importación completada ----------
function IP5({ state = "happy" }) {
  return (
    <ScreenFrame header={tenantHeader(["Centro de carga", "Personal", "Listo"])} maxWidth={780}>
      <CelebrationHero variant="soft" icon="users" confettiCount={12} title="28 personas importadas" subtitle="Procesadas en 3.2 segundos · 1 categoría de 5 lista."
        summary={[
          { icon: "user-check", value: "26", label: "cuentas activas" },
          { icon: "graduation-cap", value: "13", label: "maestros titulares" },
          { icon: "alert-triangle", value: "2", label: "con warning" },
        ]} />
      <div style={{ marginTop: 26, display: "flex", flexDirection: "column", gap: 22 }}>
        <div className="animate-fade-up" style={{ animationDelay: "0.15s" }}>
          <KpiGrid items={[
            { label: "Creados", value: "26", sub: "cuentas activas", tone: "success" },
            { label: "Con warning", value: "2", sub: "requieren edición", tone: "warning" },
            { label: "Maestros titulares", value: "13", sub: "de 13 grupos" },
            { label: "Roles otros", value: "15", sub: "coord · atelier · admin" },
          ]} />
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.3s" }}>
          <Eyebrow>Progreso del centro de carga</Eyebrow>
          <ProgressGrid done={["Personal", "Calendario"]} counts={{ Personal: "28 cargados", Familias: "0 / ~614", Alumnos: "0 / ~325", Conceptos: "0 configurados", Calendario: "Listo" }} />
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.45s" }}>
          <Banner tone="warning" icon="lightbulb"><strong style={{ color: "var(--xk-text)" }}>Siguiente paso recomendado · cargar Familias antes que Alumnos</strong> · así los alumnos pueden vincularse automáticamente con sus tutores.</Banner>
        </div>
        <div className="animate-fade-up" style={{ animationDelay: "0.6s", display: "flex", gap: 12 }}>
          <Btn variant="secondary" full onClick={() => window.goTo("I0")}>Ver el personal importado</Btn>
          <Btn variant="primary" full iconRight="arrow-right" onClick={() => window.goTo("IF4")}>Continuar con Familias</Btn>
        </div>
      </div>
    </ScreenFrame>
  );
}
function ProgressGrid({ done = [], counts = {} }) {
  const cats = ["Personal", "Familias", "Alumnos", "Conceptos", "Calendario"];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 10 }}>
      {cats.map((c, i) => {
        const isDone = done.includes(c);
        return (
          <div key={i} style={{ padding: "14px 12px", borderRadius: 12, textAlign: "center",
            border: isDone ? "1px solid color-mix(in oklab, var(--xk-success) 35%, transparent)" : "1px solid var(--xk-border)",
            background: isDone ? "var(--xk-success-tint)" : "var(--xk-surface)" }}>
            {isDone && <Icon name="check-circle-2" size={16} color="var(--xk-success)" />}
            <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: isDone ? 5 : 0 }}>{c}</div>
            <div style={{ fontSize: 11, color: isDone ? "var(--xk-success)" : "var(--xk-text-muted)", marginTop: 3 }}>{counts[c]}</div>
          </div>
        );
      })}
    </div>
  );
}
window.ProgressGrid = ProgressGrid;

Object.assign(window, { I0, IP1, IP2, IP3, IP4, IP5 });
