// Yomee — Question 1 Screen ("Hagamos números")
// Fifth onboarding step. Slider + editable number combo for total debt and monthly payment.
// Uses OnboardingHeader from OnboardingShared.jsx; PrimaryButton from Shared.jsx
/* global React, OnboardingHeader, PrimaryButton */

const { useState: useStateQ1, useEffect: useEffectQ1, useRef: useRefQ1 } = React;

function CurrencySliderField({ value, onChange, min, max, step, disabled }) {
  const [draft, setDraft] = useStateQ1(null);
  const inputRef = useRefQ1(null);

  const fmt = (n) =>
    "$" + (Number.isFinite(n) ? n : 0).toLocaleString("en-US");

  const clamp = (n) => Math.max(min, Math.min(max, n));
  const snap = (n) => Math.round(n / step) * step;

  const handleInputChange = (raw) => {
    const digits = raw.replace(/[^\d]/g, "").slice(0, 10);
    setDraft(digits);
    const n = digits === "" ? 0 : parseInt(digits, 10);
    onChange(clamp(n));
  };

  const handleBlur = () => {
    setDraft(null);
  };

  const displayed =
    draft !== null
      ? draft === ""
        ? ""
        : "$" + parseInt(draft, 10).toLocaleString("en-US")
      : fmt(value);

  const pct = max > min ? ((value - min) / (max - min)) * 100 : 0;
  const GREEN = "#2BAE80";
  const TRACK_GRAY = "#E0E0E0";

  const sliderClassRef = useRefQ1(
    "yo-sl-" + Math.random().toString(36).slice(2, 8),
  );
  const sliderClass = sliderClassRef.current;

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 8,
        opacity: disabled ? 0.45 : 1,
        pointerEvents: disabled ? "none" : "auto",
      }}
      aria-disabled={disabled || undefined}
    >
      <div
        onClick={() => !disabled && inputRef.current && inputRef.current.focus()}
        style={{
          width: "100%",
          boxSizing: "border-box",
          borderRadius: 14,
          background: "#fff",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          padding: "18px 20px",
          cursor: disabled ? "not-allowed" : "text",
        }}
      >
        <input
          ref={inputRef}
          type="text"
          inputMode="numeric"
          pattern="[0-9]*"
          disabled={disabled}
          value={displayed}
          onFocus={(e) => {
            const digits = String(value || "").replace(/[^\d]/g, "");
            setDraft(digits === "0" ? "" : digits);
            requestAnimationFrame(() => {
              try { e.target.select(); } catch (_) {}
            });
          }}
          onBlur={handleBlur}
          onChange={(e) => handleInputChange(e.target.value)}
          style={{
            width: "100%",
            border: "none",
            outline: "none",
            background: "transparent",
            textAlign: "center",
            fontFamily: "var(--font-mono)",
            fontWeight: 700,
            fontSize: 28,
            letterSpacing: "0.005em",
            color: "#1a1a1a",
          }}
        />
      </div>

      <div>
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={clamp(value)}
          onChange={(e) => onChange(snap(clamp(parseInt(e.target.value, 10))))}
          disabled={disabled}
          className={sliderClass}
          style={{
            display: "block",
            width: "100%",
            height: 22,
            WebkitAppearance: "none",
            appearance: "none",
            outline: "none",
            background: "transparent",
            margin: 0,
            padding: 0,
          }}
        />
        <style>{`
          .${sliderClass} {
            background: transparent;
          }
          .${sliderClass}::-webkit-slider-runnable-track {
            height: 4px;
            border-radius: 0;
            background: linear-gradient(
              to right,
              ${GREEN} 0%,
              ${GREEN} ${pct}%,
              ${TRACK_GRAY} ${pct}%,
              ${TRACK_GRAY} 100%
            );
          }
          .${sliderClass}::-moz-range-track {
            height: 4px;
            border-radius: 0;
            background: ${TRACK_GRAY};
          }
          .${sliderClass}::-moz-range-progress {
            height: 4px;
            border-radius: 0;
            background: ${GREEN};
          }
          .${sliderClass}::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: ${GREEN};
            border: none;
            box-shadow: none;
            outline: none;
            margin-top: -9px;
            cursor: pointer;
          }
          .${sliderClass}::-moz-range-thumb {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: ${GREEN};
            border: none;
            box-shadow: none;
            outline: none;
            cursor: pointer;
          }
          .${sliderClass}:focus {
            outline: none;
          }
        `}</style>

        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginTop: 4,
            fontFamily: "var(--font-body)",
            fontSize: 11,
            color: "#aaa",
          }}
        >
          <span>{fmt(min)}</span>
          <span>{fmt(max)}</span>
        </div>
      </div>
    </div>
  );
}

function Question1Screen({ onBack, onContinue }) {
  const TOTAL_MIN = 0;
  const TOTAL_MAX = 500000;
  const TOTAL_STEP = 5000;
  const MONTHLY_MIN = 0;

  const MONTHLY_DEFAULT = 3200;

  // Reactive bind to the active persona. Switching persona via the Demo
  // pill must snap the sliders + checkbox to the new persona's values
  // instantly — no remount required.
  const yomeeUser = (window.useYomeeUser && window.useYomeeUser()) || {};
  const personaTotal =
    Number.isFinite(yomeeUser.debt) ? yomeeUser.debt : 65000;
  const personaMonthly =
    Number.isFinite(yomeeUser.payment) ? yomeeUser.payment : MONTHLY_DEFAULT;
  const personaCantPay = yomeeUser.payment === 0;

  const [total, setTotal] = useStateQ1(personaTotal);
  const [monthly, setMonthly] = useStateQ1(personaMonthly);
  const [cantPay, setCantPay] = useStateQ1(personaCantPay);

  // When the active persona changes, snap every field back to that
  // persona's values — keyed on personaKey so this only fires on switch.
  useEffectQ1(() => {
    setTotal(personaTotal);
    setMonthly(personaMonthly);
    setCantPay(personaCantPay);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [yomeeUser.personaKey]);

  const monthlyMax = Math.max(0, total);

  const monthlyStep =
    total <= 50000 ? 500 : total <= 200000 ? 1000 : 5000;

  useEffectQ1(() => {
    if (monthly > monthlyMax) setMonthly(monthlyMax);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [monthlyMax]);

  const submit = () => {
    if (allValid) {
      onContinue({ total, monthly: cantPay ? 0 : monthly });
    }
  };

  const allValid = total > 0 && (cantPay || monthly > 0);

  const handleCantPayToggle = () => {
    setCantPay((prev) => {
      const next = !prev;
      if (next) {
        setMonthly(0);
      } else {
        setMonthly(Math.min(MONTHLY_DEFAULT, Math.max(0, total)));
      }
      return next;
    });
  };

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

      <div
        style={{
          flex: 1,
          padding: "150px 24px 28px",
          display: "flex",
          flexDirection: "column",
          minHeight: 0,
          overflow: "auto",
        }}
      >
        <h1
          style={{
            margin: "0 0 28px",
            fontFamily: "var(--font-mono)",
            fontWeight: 500,
            fontSize: 26,
            lineHeight: "34px",
            letterSpacing: "0.005em",
            color: "var(--yo-ink)",
          }}
        >
          Hagamos números
        </h1>

        <div style={{ marginBottom: 24 }}>
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontWeight: 500,
              fontSize: 18,
              color: "var(--yo-ink)",
              marginBottom: 6,
            }}
          >
            ¿Cuánto debes en total hoy?
          </div>
          <div
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 13.5,
              lineHeight: "19px",
              color: "var(--yo-ink-700, rgba(20,32,28,0.72))",
              marginBottom: 12,
            }}
          >
            Incluye tarjetas, préstamos o financiamientos activos.
          </div>
          <CurrencySliderField
            value={total}
            onChange={setTotal}
            min={TOTAL_MIN}
            max={TOTAL_MAX}
            step={TOTAL_STEP}
          />
        </div>

        <div>
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontWeight: 500,
              fontSize: 18,
              color: "var(--yo-ink)",
              marginBottom: 6,
            }}
          >
            ¿Cuánto pagas cada mes?
          </div>
          <div
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 13.5,
              lineHeight: "19px",
              color: "var(--yo-ink-700, rgba(20,32,28,0.72))",
              marginBottom: 12,
            }}
          >
            Si eres totalero, escribe la misma cantidad que arriba.
          </div>
          <CurrencySliderField
            value={cantPay ? 0 : monthly}
            onChange={setMonthly}
            min={MONTHLY_MIN}
            max={monthlyMax}
            step={monthlyStep}
            disabled={cantPay}
          />

          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              marginTop: 12,
              cursor: "pointer",
              userSelect: "none",
            }}
          >
            <input
              type="checkbox"
              checked={cantPay}
              onChange={handleCantPayToggle}
              style={{
                width: 18,
                height: 18,
                accentColor: "#6B4FA0",
                cursor: "pointer",
                margin: 0,
                flexShrink: 0,
              }}
            />
            <span
              style={{
                fontFamily: "var(--font-body)",
                fontSize: 14,
                lineHeight: "20px",
                color: "#333333",
              }}
            >
              Por ahora no puedo pagar
            </span>
          </label>

          <div
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 13,
              color: "#999999",
              textAlign: "center",
              marginTop: 32,
            }}
          >
            Puedes usar montos aproximados
          </div>
        </div>

        <div style={{ flex: 1, minHeight: 24 }} />

        <PrimaryButton onClick={submit} disabled={!allValid}>
          Continuar
        </PrimaryButton>
      </div>
    </div>
  );
}

window.Question1Screen = Question1Screen;
window.CurrencySliderField = CurrencySliderField;
