/* global React, PrimaryButton */
// Yomee — Analyzing Screen
// Transitional screen that sits between Upload and the Dashboard / Confidence
// Gate. Simulates the back-end work in two phases so the user understands
// what's happening AND that we don't keep their files:
//   1) "Analizando tus estados de cuenta…"
//   2) "Eliminando tus archivos de forma segura…"
// After both phases complete, calls onDone() so the Router can advance to
// the next screen (review or radiografía).
//
// Total duration ≈ 5s of work (varied per step so the rhythm feels human
// rather than metronomic) + ~1.6s confetti hold before the Router advances.
// Pocopin mascot (pocopin-4.png) is the focal element with a soft floating
// loop while work is in progress, and a small bounce on completion.

const { useState: useAnalyzingState, useEffect: useAnalyzingEffect } = React;

// ────────────────────────────────────────────────
// Step definitions — order matters; each duration is the visible "in
// progress" time before the row flips to its done state.
// ────────────────────────────────────────────────
const ANALYZING_STEPS = [
  {
    key: "analyze",
    inProgress: "Analizando tus estados de cuenta",
    done: "Análisis completo",
    duration: 1900,
  },
  {
    key: "delete",
    inProgress: "Eliminando tus archivos de forma segura",
    done: "Archivos eliminados",
    duration: 1300,
  },
  {
    key: "build",
    inProgress: "Creando tu radiografía",
    done: "Radiografía lista",
    duration: 1800,
  },
];

// Confetti hold time — how long the celebration plays before the Router
// advances. Long enough for users to register the moment, short enough to
// stay snappy.
const CONFETTI_HOLD_MS = 1600;

// Tiny in-row spinner — same visual language as the upload area's spinner
// so this screen feels like a continuation of that interaction.
function StepSpinner({ size = 20 }) {
  return (
    <div
      aria-label="Procesando"
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        border: "2.2px solid rgba(51,51,51,0.18)",
        borderTopColor: "var(--yo-ink)",
        animation: "yo-analyze-spin 0.7s linear infinite",
        flexShrink: 0,
      }}
    />
  );
}

// Filled mint check — matches the success indicator on file rows.
function StepCheck({ size = 22 }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        background: "var(--yo-mint-700)",
        flexShrink: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        animation: "yo-analyze-pop 220ms cubic-bezier(.2,.8,.2,1)",
      }}
    >
      <svg width={size * 0.55} height={size * 0.55} viewBox="0 0 12 12" aria-hidden="true">
        <path
          d="M2.5 6.2 L4.9 8.6 L9.5 3.6"
          fill="none"
          stroke="#fff"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </div>
  );
}

// Empty placeholder dot for steps that haven't started yet.
function StepPending({ size = 20 }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        border: "2px solid rgba(51,51,51,0.18)",
        background: "transparent",
        flexShrink: 0,
      }}
    />
  );
}

// ────────────────────────────────────────────────
// Confetti — lightweight CSS-only burst. Generates ~36 colored chips that
// fall from the top with random horizontal drift, rotation and delay.
// Colors are pulled from the brand palette so the burst feels on-system.
// ────────────────────────────────────────────────
const CONFETTI_COLORS = [
  "var(--yo-mint-700)",
  "var(--yo-forest-500)",
  "var(--yo-orange-soft)",
  "var(--yo-coral)",
  "var(--yo-yellow)",
  "var(--yo-lavender)",
];

function Confetti({ count = 36 }) {
  const pieces = React.useMemo(() => {
    return Array.from({ length: count }, (_, i) => {
      const left = Math.random() * 100;
      const delay = Math.random() * 350;
      const duration = 1200 + Math.random() * 900;
      const drift = (Math.random() - 0.5) * 120;
      const rot = Math.random() * 720 - 360;
      const size = 6 + Math.random() * 6;
      const color =
        CONFETTI_COLORS[Math.floor(Math.random() * CONFETTI_COLORS.length)];
      const isCircle = Math.random() < 0.3;
      return { left, delay, duration, drift, rot, size, color, isCircle, i };
    });
  }, [count]);
  return (
    <div
      aria-hidden="true"
      style={{
        position: "absolute",
        inset: 0,
        pointerEvents: "none",
        overflow: "hidden",
        zIndex: 30,
      }}
    >
      {pieces.map((p) => (
        <span
          key={p.i}
          style={{
            position: "absolute",
            top: -16,
            left: `${p.left}%`,
            width: p.size,
            height: p.isCircle ? p.size : p.size * 1.6,
            background: p.color,
            borderRadius: p.isCircle ? "50%" : 2,
            opacity: 0,
            transform: `translate(0, 0) rotate(0deg)`,
            animation: `yo-confetti-fall ${p.duration}ms cubic-bezier(.2,.7,.3,1) ${p.delay}ms forwards`,
            ["--drift"]: `${p.drift}px`,
            ["--rot"]: `${p.rot}deg`,
          }}
        />
      ))}
    </div>
  );
}

function StepRow({ status, label }) {
  const isDone = status === "done";
  const isActive = status === "active";
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "10px 14px",
        background: "#fff",
        borderRadius: 12,
        boxShadow: "0 1px 0 rgba(20,32,28,0.04)",
        opacity: status === "pending" ? 0.55 : 1,
        transition: "opacity 200ms ease-out",
      }}
    >
      {isDone ? (
        <StepCheck />
      ) : isActive ? (
        <StepSpinner />
      ) : (
        <StepPending />
      )}
      <div
        style={{
          flex: 1,
          fontFamily: "var(--font-body)",
          fontSize: 14,
          fontWeight: isActive || isDone ? 600 : 500,
          color: isDone ? "#1a1a1a" : isActive ? "#1a1a1a" : "#888",
          letterSpacing: "0.005em",
          lineHeight: "20px",
        }}
      >
        {label}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────
// Main screen
// ────────────────────────────────────────────────
function AnalyzingScreen({ fileCount = 0, onDone }) {
  // 0..ANALYZING_STEPS.length — number of steps that have completed.
  const [completed, setCompleted] = useAnalyzingState(0);
  const [allDone, setAllDone] = useAnalyzingState(false);
  // Drives the confetti overlay. Flips on as soon as the last step finishes
  // and stays on until the Router advances away from this screen.
  const [showConfetti, setShowConfetti] = useAnalyzingState(false);

  useAnalyzingEffect(() => {
    let cancelled = false;
    const timeouts = [];
    let elapsed = 0;
    ANALYZING_STEPS.forEach((step, i) => {
      elapsed += step.duration;
      const t = setTimeout(() => {
        if (cancelled) return;
        setCompleted(i + 1);
        if (i === ANALYZING_STEPS.length - 1) {
          setAllDone(true);
          setShowConfetti(true);
          // Navigation no longer happens automatically — the user must press
          // the CONTINUAR button below, which becomes enabled once allDone
          // flips. This acts as a stopper before the dashboard so users can
          // register the completion moment on their own time.
        }
      }, elapsed);
      timeouts.push(t);
    });
    return () => {
      cancelled = true;
      timeouts.forEach((t) => clearTimeout(t));
    };
  }, []);

  const currentStep = completed; // index of the step that's currently active
  const headline = allDone
    ? "¡Listo!"
    : currentStep === 0
      ? "Estamos analizando tus archivos"
      : currentStep === 1
        ? "Protegiendo tu información"
        : "Construyendo tu radiografía";
  const subhead = allDone
    ? "Tu radiografía está lista"
    : currentStep === 0
      ? "Pocopin está leyendo cada movimiento de tus estados de cuenta"
      : currentStep === 1
        ? "Borramos tus archivos en cuanto terminamos. No los guardamos."
        : "Estamos uniendo todo para mostrarte tu situación real";

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        height: "100%",
        background: "var(--yo-bg)",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}
    >
      {/* Content — vertically centered, with a slight top bias so the mascot
          sits higher than dead-center which feels more "active". */}
      <div
        style={{
          flex: 1,
          padding: "96px 24px 24px",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "flex-start",
        }}
      >
        {/* Mascot — soft floating loop while work is in progress, gentle
            pop-in on mount and a celebratory bounce on completion. */}
        <div
          style={{
            position: "relative",
            width: 184,
            height: 184,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            marginBottom: 18,
          }}
        >
          {/* Soft halo ring behind the mascot — pulses while loading. */}
          <div
            aria-hidden="true"
            style={{
              position: "absolute",
              inset: 12,
              borderRadius: "50%",
              background:
                "radial-gradient(circle at 50% 50%, rgba(55,183,139,0.18) 0%, rgba(55,183,139,0.08) 45%, rgba(55,183,139,0) 70%)",
              animation: allDone
                ? "none"
                : "yo-analyze-pulse 2.2s ease-in-out infinite",
            }}
          />
          <img
            src="assets/pocopin-4.png"
            alt=""
            style={{
              position: "relative",
              width: 168,
              height: 168,
              objectFit: "contain",
              animation: allDone
                ? "yo-analyze-bounce 600ms cubic-bezier(.2,.8,.2,1)"
                : "yo-analyze-float 3.4s ease-in-out infinite",
            }}
          />
        </div>

        {/* Headline */}
        <h1
          style={{
            margin: 0,
            fontFamily: '"Geist Mono", var(--font-mono)',
            fontWeight: 900,
            fontSize: 26,
            lineHeight: "32px",
            color: "#1a1a1a",
            letterSpacing: "-0.01em",
            textAlign: "center",
          }}
        >
          {headline}
        </h1>
        <p
          style={{
            margin: "8px 0 0",
            fontFamily: "var(--font-body)",
            fontSize: 14,
            lineHeight: "20px",
            color: "#555",
            textAlign: "center",
            maxWidth: 280,
          }}
        >
          {subhead}
        </p>

        {/* File count chip — only when meaningful (≥ 1). */}
        {fileCount > 0 && !allDone && (
          <div
            style={{
              marginTop: 14,
              padding: "6px 12px",
              borderRadius: 999,
              background: "rgba(51,51,51,0.06)",
              fontFamily: "var(--font-mono)",
              fontSize: 12,
              fontWeight: 600,
              color: "#1a1a1a",
              letterSpacing: "0.02em",
            }}
          >
            {fileCount === 1
              ? "1 estado de cuenta"
              : `${fileCount} estados de cuenta`}
          </div>
        )}

        {/* Step list */}
        <div
          style={{
            marginTop: 28,
            width: "100%",
            maxWidth: 360,
            display: "flex",
            flexDirection: "column",
            gap: 10,
          }}
        >
          {ANALYZING_STEPS.map((step, i) => {
            let status = "pending";
            if (i < completed) status = "done";
            else if (i === completed) status = "active";
            const label =
              status === "done" ? step.done : step.inProgress + (status === "active" ? "…" : "");
            return <StepRow key={step.key} status={status} label={label} />;
          })}
        </div>

        {/* Privacy note — reinforces the "we don't keep your files" promise. */}
        <div
          style={{
            marginTop: 18,
            fontFamily: "var(--font-body)",
            fontSize: 12,
            color: "#aaa",
            textAlign: "center",
            maxWidth: 300,
          }}
        >
          Tus archivos se eliminan de forma permanente una vez procesados
        </div>
      </div>

      {/* CONTINUAR stopper — disabled while the simulation is running, enabled
          once all steps complete. Matches the Start Screen primary CTA style
          (PrimaryButton, primary variant). */}
      <div
        style={{
          padding: "0 24px 28px",
          position: "relative",
          zIndex: 40,
        }}
      >
        <PrimaryButton
          onClick={() => onDone && onDone()}
          disabled={!allDone}
        >
          CONTINUAR
        </PrimaryButton>
      </div>

      {/* Celebratory confetti — plays once all 3 steps finish, before the
          Router advances. Fixed-overlay so it spans the full screen. */}
      {showConfetti && <Confetti />}

      <style>{`
        @keyframes yo-analyze-spin { to { transform: rotate(360deg); } }
        @keyframes yo-analyze-pulse {
          0%, 100% { transform: scale(1);   opacity: 0.85; }
          50%      { transform: scale(1.08); opacity: 1; }
        }
        @keyframes yo-analyze-float {
          0%, 100% { transform: translateY(0); }
          50%      { transform: translateY(-6px); }
        }
        @keyframes yo-analyze-bounce {
          0%   { transform: scale(1);    }
          40%  { transform: scale(1.10); }
          70%  { transform: scale(0.97); }
          100% { transform: scale(1);    }
        }
        @keyframes yo-analyze-pop {
          0%   { transform: scale(0.6); opacity: 0; }
          100% { transform: scale(1);   opacity: 1; }
        }
        @keyframes yo-confetti-fall {
          0%   { transform: translate(0, 0) rotate(0deg); opacity: 0; }
          10%  { opacity: 1; }
          100% {
            transform: translate(var(--drift), 110vh) rotate(var(--rot));
            opacity: 1;
          }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { AnalyzingScreen, ANALYZING_STEPS });
