/* global React, OnboardingHeader, PrimaryButton */
// Yomee — Extraction Review (Confidence Gate)
// /onboarding/review
//
// Inserted between Upload and Radiografía when the user has uploaded
// exactly 3 files (the full UPLOAD_SEQUENCE). The screen shows a single
// low-confidence (65%) extraction card for the THIRD uploaded file and
// asks the user to confirm 3 hardcoded fields before continuing.
//
// Design notes:
//   • Tokens come from colors_and_type.css. The original brief was
//     written in Tailwind shorthand (bg-primary, font-heading, etc.) —
//     we translate to the existing var(--yo-*) tokens so this screen
//     matches the rest of the app rather than introducing a new system.
//   • Mascot uses pocopin-3.png (the existing mascot in this repo).
//   • CTA uses PrimaryButton variant="primary" — the disabled state is
//     the system's standard 22%-ink fill, not a gradient.
//
// Analytics: track() calls are stubbed (window.track || no-op) and fire
// on mount + on the CONTINUAR tap.

const { useState: useStateER, useEffect: useEffectER } = React;

// Hardcoded extraction values — prototype only. Per the brief these are
// matched to the third uploaded file (Nu) regardless of which actual
// file ended up in slot [2] of the UPLOAD_SEQUENCE.
const REVIEW_FILE = {
  name: "Nu_Morada_Feb2026.pdf",
  bank: "Nu",
};
const REVIEW_FIELDS = [
  { key: "deuda",     label: "Deuda total detectada",            value: "$22,146" },
  { key: "intereses", label: "Intereses y comisiones detectados", value: "$7,887"  },
  { key: "minimo",    label: "Pago mínimo detectado",            value: "$1,987"  },
];

const _track = (...args) => {
  if (typeof window !== "undefined" && typeof window.track === "function") {
    window.track(...args);
  }
};

// ────────────────────────────────────────────────
// SuccessCheckSmall — green circle + white checkmark for the inline
// Pocopin tip card. Smaller than the file-row check in UploadScreen.
// ────────────────────────────────────────────────
function ReviewSuccessCheck() {
  return (
    <div
      style={{
        width: 28,
        height: 28,
        borderRadius: "50%",
        background: "var(--yo-mint-700)",
        flexShrink: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">
        <path
          d="M3 7.2 L5.8 10 L11 4.6"
          fill="none"
          stroke="#fff"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </div>
  );
}

// ────────────────────────────────────────────────
// Confidence badge — amber pill with dot + "Confianza 65%"
// ────────────────────────────────────────────────
function ConfidenceBadge({ pct = 65 }) {
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        background: "rgb(255, 248, 230)",      // amber-50
        border: "1px solid rgb(253, 224, 161)",// amber-200
        borderRadius: 999,
        padding: "4px 10px",
        flexShrink: 0,
      }}
    >
      <span
        aria-hidden="true"
        style={{
          width: 6,
          height: 6,
          borderRadius: "50%",
          background: "rgb(245, 188, 64)", // amber-400
        }}
      />
      <span
        style={{
          fontFamily: "var(--font-mono)",
          fontWeight: 700,
          fontSize: 11,
          letterSpacing: "0.04em",
          color: "rgb(133, 77, 14)",       // amber-800
          whiteSpace: "nowrap",
        }}
      >
        Confianza {pct}%
      </span>
    </div>
  );
}

// ────────────────────────────────────────────────
// Circular checkbox — primary-bordered circle that fills with mint and
// a white check on toggle. Matches the brief's "circular checkbox"
// pattern; uses the app's mint accent so it sits in the existing palette
// instead of introducing a new "primary" color.
// ────────────────────────────────────────────────
function CircleCheckbox({ checked, onToggle, label }) {
  return (
    <button
      type="button"
      onClick={onToggle}
      aria-pressed={checked}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 10,
        width: "100%",
        background: "transparent",
        border: "none",
        padding: 0,
        cursor: "pointer",
        textAlign: "left",
      }}
    >
      <span
        aria-hidden="true"
        style={{
          width: 20,
          height: 20,
          borderRadius: "50%",
          border: "2px solid var(--yo-mint-700)",
          background: checked ? "var(--yo-mint-700)" : "#fff",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
          transition: "background 160ms ease-out",
        }}
      >
        {checked && (
          <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
            <path
              d="M2.5 6.4 L4.9 8.6 L9.5 3.6"
              fill="none"
              stroke="#fff"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        )}
      </span>
      <span
        style={{
          fontFamily: "var(--font-body)",
          fontSize: 14,
          lineHeight: "20px",
          color: "var(--yo-ink)",
          letterSpacing: "0.01em",
        }}
      >
        {label}
      </span>
    </button>
  );
}

// ────────────────────────────────────────────────
// Read-only / lightly editable field. Uses the app's input shape
// (16px radius, ink border-soft, mono text).
// ────────────────────────────────────────────────
function ReviewField({ label, value, onChange }) {
  return (
    <label
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 6,
      }}
    >
      <span
        style={{
          fontFamily: "var(--font-mono)",
          fontWeight: 500,
          fontSize: 11,
          letterSpacing: "0.08em",
          textTransform: "uppercase",
          color: "var(--yo-ink-muted)",
        }}
      >
        {label}
      </span>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange && onChange(e.target.value)}
        style={{
          height: 44,
          background: "var(--yo-bg-alt)",
          border: "1px solid rgba(51,51,51,0.12)",
          borderRadius: 12,
          padding: "0 14px",
          fontFamily: "var(--font-mono)",
          fontWeight: 700,
          fontSize: 15,
          letterSpacing: "0.01em",
          color: "var(--yo-ink)",
          outline: "none",
        }}
      />
    </label>
  );
}

// ────────────────────────────────────────────────
// Main screen
// ────────────────────────────────────────────────
function ExtractionReviewScreen({ onBack, onContinue }) {
  const [confirmed, setConfirmed] = useStateER(false);
  const [processing, setProcessing] = useStateER(false);
  // Editable copies of the extracted values — the user can correct any
  // field, but no validation is enforced (prototype rule).
  const [fields, setFields] = useStateER(() =>
    REVIEW_FIELDS.reduce((acc, f) => ({ ...acc, [f.key]: f.value }), {}),
  );

  // Fire confidence_gate_triggered on mount.
  useEffectER(() => {
    _track("confidence_gate_triggered", {
      numLowConfidenceFiles: 1,
      screen: "/onboarding/review",
    });
  }, []);

  const handleContinue = () => {
    if (!confirmed || processing) return;
    _track("extraction_review_completed", { screen: "/onboarding/review" });
    setProcessing(true);
    setTimeout(() => {
      onContinue && onContinue();
    }, 1500);
  };

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

      {/* Scrollable content */}
      <div
        style={{
          flex: 1,
          padding: "118px 24px 180px",
          display: "flex",
          flexDirection: "column",
          minHeight: 0,
          overflow: "auto",
        }}
      >
        {/* Title */}
        <h1
          style={{
            margin: "0",
            fontFamily: '"Geist Mono", var(--font-mono)',
            fontWeight: 900,
            fontSize: 22,
            lineHeight: "28px",
            color: "var(--yo-ink)",
            letterSpacing: "-0.005em",
            textAlign: "center",
          }}
        >
          Un paso más para tu diagnóstico exacto
        </h1>

        {/* Subtitle */}
        <p
          style={{
            margin: "8px 0 0",
            fontFamily: "var(--font-body)",
            fontSize: 13,
            lineHeight: "19px",
            color: "var(--yo-ink-muted)",
            textAlign: "center",
            letterSpacing: "0.01em",
          }}
        >
          Algunos datos necesitan tu confirmación.{" "}
          <span
            style={{
              fontWeight: 700,
              color: "var(--yo-mint-700)",
            }}
          >
            Entre más precisos, mejor tu radiografía.
          </span>
        </p>

        {/* Pocopin tip card */}
        <div
          style={{
            marginTop: 14,
            background: "rgba(55,183,139,0.06)",
            border: "1px solid rgba(55,183,139,0.18)",
            borderRadius: 14,
            padding: 12,
            display: "flex",
            alignItems: "flex-start",
            gap: 10,
          }}
        >
          <ReviewSuccessCheck />
          <div
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 12,
              lineHeight: "17px",
              color: "rgba(25,85,62,0.9)",
              letterSpacing: "0.01em",
            }}
          >
            Tu archivo se procesó. Solo verifica que los{" "}
            <strong style={{ fontWeight: 700 }}>3 números clave</strong>{" "}
            sean correctos — no tienes que revisarlo todo.
          </div>
        </div>

        {/* Confidence card */}
        <section
          style={{
            marginTop: 18,
            background: "#fff",
            borderRadius: 16,
            border: "1px solid rgba(51,51,51,0.08)",
            boxShadow: "0 4px 12px -6px rgba(20,32,28,0.10)",
            padding: 16,
            display: "flex",
            flexDirection: "column",
            gap: 14,
          }}
        >
          {/* Header row */}
          <div
            style={{
              display: "flex",
              alignItems: "flex-start",
              justifyContent: "space-between",
              gap: 12,
            }}
          >
            <div style={{ minWidth: 0, flex: 1 }}>
              <div
                style={{
                  fontFamily: "var(--font-mono)",
                  fontWeight: 700,
                  fontSize: 13,
                  color: "var(--yo-ink)",
                  letterSpacing: "0.005em",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {REVIEW_FILE.name}
              </div>
              <div
                style={{
                  marginTop: 2,
                  fontFamily: "var(--font-body)",
                  fontSize: 11,
                  color: "var(--yo-ink-muted)",
                  letterSpacing: "0.02em",
                }}
              >
                {REVIEW_FILE.bank}
              </div>
            </div>
            <ConfidenceBadge pct={65} />
          </div>

          {/* Editable fields */}
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 10,
            }}
          >
            {REVIEW_FIELDS.map((f) => (
              <ReviewField
                key={f.key}
                label={f.label}
                value={fields[f.key]}
                onChange={(v) =>
                  setFields((prev) => ({ ...prev, [f.key]: v }))
                }
              />
            ))}
          </div>

          {/* Divider */}
          <div
            style={{
              height: 1,
              background: "rgba(51,51,51,0.10)",
            }}
          />

          {/* Confirmation row */}
          <CircleCheckbox
            checked={confirmed}
            onToggle={() => setConfirmed((v) => !v)}
            label="Confirmo que estos datos son correctos"
          />
        </section>
      </div>

      {/* Fixed footer CTA */}
      <div
        style={{
          position: "absolute",
          left: 0,
          right: 0,
          bottom: 0,
          padding: "12px 24px 24px",
          background: "var(--yo-bg)",
          flexShrink: 0,
        }}
      >
        <PrimaryButton
          onClick={handleContinue}
          disabled={!confirmed || processing}
        >
          {processing ? "GENERANDO TU RADIOGRAFÍA…" : "CONTINUAR"}
        </PrimaryButton>
      </div>

      {/* Processing overlay — Pocopin + spinner + label */}
      {processing && (
        <div
          style={{
            position: "absolute",
            inset: 0,
            background: "rgba(245,240,235,0.94)",
            zIndex: 60,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "column",
            gap: 14,
            animation: "yo-er-fade 200ms ease-out",
          }}
        >
          <div
            style={{
              position: "relative",
              width: 96,
              height: 96,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <div
              aria-hidden="true"
              style={{
                position: "absolute",
                inset: 0,
                borderRadius: "50%",
                border: "3px solid rgba(55,183,139,0.18)",
                borderTopColor: "var(--yo-mint-700)",
                animation: "yo-er-spin 0.9s linear infinite",
              }}
            />
            <img
              src="assets/pocopin-3.png"
              alt=""
              style={{ width: 64, height: 64, objectFit: "contain" }}
            />
          </div>
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontWeight: 700,
              fontSize: 13,
              letterSpacing: "0.10em",
              textTransform: "uppercase",
              color: "var(--yo-ink)",
            }}
          >
            Generando tu radiografía…
          </div>
        </div>
      )}

      <style>{`
        @keyframes yo-er-spin { to { transform: rotate(360deg); } }
        @keyframes yo-er-fade { from { opacity: 0; } to { opacity: 1; } }
      `}</style>
    </div>
  );
}

window.ExtractionReviewScreen = ExtractionReviewScreen;
