/* global React, IOSDevice, PrimaryButton */
// Yomee — Start Screen
// Entry-point. Onboarding carousel with 3 slides, primary CTA → SignUp,
// secondary "Iniciar sesión" → SignIn. Router/App live in App.jsx.

const { useState: useStateSS, useEffect: useEffectSS, useRef: useRefSS } = React;

// ────────────────────────────────────────────────
// Coin badge — mint circle with $ sign
// ────────────────────────────────────────────────
function CoinBadge({ size = 38, style }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        background: "var(--yo-mint-700)",
        border: "2.5px solid var(--yo-forest-900)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: "var(--font-mono)",
        fontWeight: 700,
        fontSize: size * 0.5,
        color: "var(--yo-forest-900)",
        boxShadow: "inset 0 -2px 0 rgba(0,0,0,0.08)",
        ...style,
      }}
    >
      $
    </div>
  );
}

// ────────────────────────────────────────────────
// Pagination — 3 dashes; active is a longer mint pill
// ────────────────────────────────────────────────
function Pagination({ index, total = 3, onChange }) {
  return (
    <div style={{ display: "flex", gap: 8, alignItems: "center", justifyContent: "center" }}>
      {Array.from({ length: total }).map((_, i) => {
        const active = i === index;
        return (
          <button
            key={i}
            onClick={() => onChange?.(i)}
            aria-label={`Ir al slide ${i + 1}`}
            style={{
              width: active ? 22 : 14,
              height: 4,
              borderRadius: 2,
              border: "none",
              background: active ? "var(--yo-mint-700)" : "#C9CDD2",
              padding: 0,
              cursor: "pointer",
              transition: "all 280ms cubic-bezier(.2,.7,.2,1)",
            }}
          />
        );
      })}
    </div>
  );
}

const SLIDES = [
  {
    mascot: "assets/pocopin-3.png",
    mascotStyle: { width: 220, left: 100, top: -170, transform: "scaleX(1)" },
    coins: [
      { left: 18, top: -22, size: 40 },
      { left: 62, top: 6,   size: 36 },
    ],
    body: (
      <>
        ¿Sabías que el mexicano promedio paga <span style={{ color: "var(--yo-coral)", fontWeight: 700, whiteSpace: "nowrap" }}>$15,000</span> al año en intereses?
      </>
    ),
  },
  {
    mascot: "assets/pocopin-3.png",
    mascotStyle: { width: 218, left: 102, top: -168, transform: "scaleX(-1)" },
    coins: [
      { left: 16, top: -16, size: 38 },
      { left: 60, top: 12,  size: 40 },
    ],
    body: (
      <>
        Hay tarjetas y créditos con la <span style={{ color: "var(--yo-coral)", fontWeight: 700, whiteSpace: "nowrap" }}>mitad del costo</span> esperándote.
      </>
    ),
  },
  {
    mascot: "assets/pocopin-6.png",
    mascotStyle: { width: 220, left: 100, top: -174, transform: "scaleX(1)" },
    coins: [
      { left: 16, top: -14, size: 38 },
      { left: 60, top: 14,  size: 38 },
    ],
    body: (
      <>
        ¿Y tú? ¿Cuánto dinero le <span style={{ color: "var(--yo-coral)", fontWeight: 700 }}>estás regalando</span> al banco hoy?
      </>
    ),
  },
];

const CARD_W = 326;
const CARD_H = 252;

function CardFrame({ index, total, onDot, slides }) {
  return (
    <div style={{ position: "relative", width: CARD_W, margin: "0 auto" }}>
      <div
        style={{
          position: "relative",
          background: "#fff",
          border: "2px solid var(--yo-ink)",
          borderRadius: 28,
          height: CARD_H,
          padding: "0 28px",
          zIndex: 1,
        }}
      >
        <div
          style={{
            position: "absolute",
            left: 28,
            right: 28,
            top: 0,
            bottom: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {slides.map((s, i) => (
            <p
              key={i}
              style={{
                position: "absolute",
                left: 0,
                right: 0,
                margin: 0,
                fontFamily: "var(--font-mono)",
                fontWeight: 500,
                fontSize: 20,
                lineHeight: "30px",
                letterSpacing: "0.01em",
                color: "var(--yo-ink)",
                textAlign: "center",
                opacity: i === index ? 1 : 0,
                transition: "opacity 320ms ease-out",
                pointerEvents: i === index ? "auto" : "none",
              }}
            >
              {s.body}
            </p>
          ))}
        </div>

        <div
          style={{
            position: "absolute",
            left: 0,
            right: 0,
            bottom: 22,
            display: "flex",
            justifyContent: "center",
          }}
        >
          <Pagination index={index} total={total} onChange={onDot} />
        </div>
      </div>

      {slides.map((s, i) => (
        <div
          key={`coins-${i}`}
          style={{
            position: "absolute",
            inset: 0,
            opacity: i === index ? 1 : 0,
            transition: "opacity 320ms ease-out",
            pointerEvents: "none",
            zIndex: 3,
          }}
        >
          {s.coins.map((c, ci) => (
            <CoinBadge
              key={ci}
              size={c.size}
              style={{
                position: "absolute",
                left: c.left,
                top: c.top,
              }}
            />
          ))}
        </div>
      ))}

      {slides.map((s, i) => (
        <img
          key={`mascot-${i}`}
          src={s.mascot}
          alt=""
          style={{
            position: "absolute",
            pointerEvents: "none",
            zIndex: 2,
            opacity: i === index ? 1 : 0,
            transition: "opacity 320ms ease-out",
            ...s.mascotStyle,
          }}
        />
      ))}
    </div>
  );
}

function StartScreen({ onPrimary, onSignIn }) {
  const [index, setIndex] = useStateSS(0);
  const touchStart = useRefSS(null);

  const [auto, setAuto] = useStateSS(true);
  useEffectSS(() => {
    if (!auto) return;
    const t = setTimeout(() => setIndex((i) => (i + 1) % SLIDES.length), 4200);
    return () => clearTimeout(t);
  }, [index, auto]);

  function go(i) {
    setAuto(false);
    setIndex(((i % SLIDES.length) + SLIDES.length) % SLIDES.length);
  }

  function onTouchStart(e) {
    touchStart.current = e.touches[0].clientX;
  }
  function onTouchEnd(e) {
    if (touchStart.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (Math.abs(dx) > 40) go(dx < 0 ? index + 1 : index - 1);
    touchStart.current = null;
  }

  const dragStart = useRefSS(null);
  function onMouseDown(e) { dragStart.current = e.clientX; }
  function onMouseUp(e) {
    if (dragStart.current == null) return;
    const dx = e.clientX - dragStart.current;
    if (Math.abs(dx) > 40) go(dx < 0 ? index + 1 : index - 1);
    dragStart.current = null;
  }

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        height: "100%",
        background: "var(--yo-bg)",
        fontFamily: "var(--font-body)",
        color: "var(--yo-ink)",
        overflow: "hidden",
      }}
    >
      <div style={{ paddingTop: 64, display: "flex", justifyContent: "center" }}>
        <img src="assets/yomee-logo-wordmark.png" alt="Yomee" style={{ width: 151, height: "auto" }} />
      </div>

      <div
        style={{ marginTop: 185, position: "relative" }}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        onMouseDown={onMouseDown}
        onMouseUp={onMouseUp}
      >
        <CardFrame
          index={index}
          total={SLIDES.length}
          onDot={go}
          slides={SLIDES}
        />
      </div>

      <p
        style={{
          textAlign: "center",
          fontFamily: "var(--font-body)",
          fontSize: 14,
          lineHeight: "20px",
          letterSpacing: "0.02em",
          color: "var(--yo-ink)",
          margin: 0,
          marginTop: 38,
          padding: "0 32px",
        }}
      >
        Haz tu diagnóstico gratis en 2 minutos<br />
        y ahorra dinero de inmediato
      </p>

      {/* Primary CTA */}
      <div style={{ padding: "28px 24px 0" }}>
        <PrimaryButton onClick={() => onPrimary?.()} trailingArrow>
          Ver cuanto estoy pagando
        </PrimaryButton>
      </div>

      <div style={{ marginTop: 22, textAlign: "center" }}>
        <span
          style={{
            fontFamily: "var(--font-body)",
            fontSize: 14,
            color: "var(--yo-ink)",
            letterSpacing: "0.01em",
          }}
        >
          ¿Ya tienes cuenta?{" "}
        </span>
        <button
          onClick={() => onSignIn?.()}
          style={{
            background: "transparent",
            border: "none",
            padding: 0,
            cursor: "pointer",
            fontFamily: "var(--font-body)",
            fontSize: 14,
            fontWeight: 700,
            color: "var(--yo-ink)",
            textDecoration: "underline",
            textUnderlineOffset: 3,
            textDecorationThickness: 1.5,
            letterSpacing: "0.01em",
            whiteSpace: "nowrap",
          }}
        >
          Iniciar sesión
        </button>
      </div>
    </div>
  );
}

window.StartScreen = StartScreen;
window.CoinBadge = CoinBadge;
window.Pagination = Pagination;
window.CardFrame = CardFrame;
