// Yomee — Personal Info Screen
// First post-auth onboarding step. Captures name, age, gender.
// Uses OnboardingHeader + TextField + SegmentedSelect from OnboardingShared.jsx
// Uses PrimaryButton from Shared.jsx
/* global React, OnboardingHeader, TextField, SegmentedSelect, PrimaryButton */

const { useState: useStatePI, useEffect: useEffectPI } = React;

function PersonalInfoScreen({ onBack, onContinue }) {
  // Read every persona-driven field reactively from the global persona
  // context. Switching the active persona via the Demo pill must update the
  // form fields instantly without a remount.
  const yomeeUser = (window.useYomeeUser && window.useYomeeUser()) || {};
  const personaGenderToken =
    yomeeUser.gender === "female" ? "f" :
    yomeeUser.gender === "male"   ? "m" : "";
  const name   = yomeeUser.name  || "";
  const age    = yomeeUser.age != null ? String(yomeeUser.age) : "";
  const gender = personaGenderToken;
  const [errors, setErrors] = useStatePI({});
  const [touched, setTouched] = useStatePI({});

  const validate = () => {
    const e = {};
    if (!name.trim()) e.name = "Ingresa tu nombre para continuar.";
    else if (name.trim().length < 2)
      e.name = "El nombre debe tener al menos 2 letras.";
    else if (!/^[\p{L} '\-]+$/u.test(name.trim()))
      e.name = "Usa solo letras, espacios o guiones.";

    if (!age) e.age = "Ingresa tu edad.";
    else {
      const n = parseInt(age, 10);
      if (Number.isNaN(n)) e.age = "La edad debe ser un número.";
      else if (n < 18) e.age = "Debes ser mayor de 18 años para usar Yomee.";
      else if (n > 120) e.age = "Verifica tu edad.";
    }

    if (!gender) e.gender = "Selecciona una opción.";
    return e;
  };

  // Reset transient touched/errors state when the active persona changes
  // so the form doesn't carry over a previous user's validation flags.
  useEffectPI(() => {
    setTouched({});
    setErrors({});
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [yomeeUser.personaKey]);

  useEffectPI(() => {
    if (!touched.name && !touched.age && !touched.gender) return;
    const e = validate();
    const filtered = {};
    Object.keys(e).forEach((k) => {
      if (touched[k]) filtered[k] = e[k];
    });
    setErrors(filtered);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [name, age, gender, touched]);

  const submit = () => {
    setTouched({ name: true, age: true, gender: true });
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) onContinue();
  };

  const allValid =
    name.trim() && age && gender && Object.keys(validate()).length === 0;

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        height: "100%",
        background: "var(--yo-bg)",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <OnboardingHeader onBack={onBack} progress={0.16} screenKey="personal-info" />

      <div
        style={{
          flex: 1,
          padding: "130px 24px 16px",
          display: "flex",
          flexDirection: "column",
          minHeight: 0,
          overflow: "auto",
        }}
      >
        <h1
          style={{
            margin: 0,
            fontFamily: "var(--font-mono)",
            fontWeight: 500,
            fontSize: 26,
            lineHeight: "34px",
            letterSpacing: "0.005em",
            color: "var(--yo-ink)",
          }}
        >
          Antes de empezar,
          <br />
          confírmanos tus datos.
        </h1>
        <p
          style={{
            margin: "10px 0 28px",
            fontFamily: "var(--font-body)",
            fontSize: 15,
            lineHeight: "22px",
            color: "var(--yo-ink-700, rgba(20,32,28,0.72))",
          }}
        >
          Así podremos personalizar tu experiencia.
        </p>

        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {/* All three fields read directly from the active persona via
              the global context above — onChange is a no-op so values
              always reflect activePersona.{name,age,gender}. */}
          <TextField
            label="Nombre"
            value={name}
            onChange={() => {}}
            placeholder="Abramo Escobar"
            error={errors.name}
          />
          <TextField
            label="Edad"
            value={age}
            onChange={() => {}}
            placeholder="32"
            placeholderColor="rgba(20,32,28,0.32)"
            inputMode="numeric"
            maxLength={3}
            error={errors.age}
          />
          <SegmentedSelect
            label="Género"
            value={gender}
            onChange={() => {}}
            options={[
              { value: "f", label: "Femenino" },
              { value: "m", label: "Masculino" },
              { value: "x", label: "Otro" },
            ]}
            error={errors.gender}
          />
        </div>
      </div>

      <div
        style={{
          padding: "12px 24px 28px",
          background: "var(--yo-bg)",
          flexShrink: 0,
          borderTop: "0px solid transparent",
        }}
      >
        <PrimaryButton onClick={submit} disabled={!allValid}>
          Continuar
        </PrimaryButton>
      </div>
    </div>
  );
}

window.PersonalInfoScreen = PersonalInfoScreen;
