// ──────────────────────────────────────────────────────────────────
// Auth + Onboarding screens.
// Welcome, Login, SignUpOptions, Onboarding 1/2/3, RoleSelection.
//
// Voice: terse, mat-ready, confident. System-style metadata
// (build codes, timestamps) as decorative scaffolding.
// ──────────────────────────────────────────────────────────────────

// ── Rotating word — cycles through a list with a quick fade. ────────────
const ROTATING_WHO = ["ATHLETES", "COACHES", "GYMS", "FANS", "PARENTS"];
const RotatingWord = ({ words = ROTATING_WHO, interval = 5000, brackets = false }) => {
  const [idx, setIdx] = React.useState(0);
  const [visible, setVisible] = React.useState(true);
  React.useEffect(() => {
    const id = setInterval(() => {
      setVisible(false);
      setTimeout(() => {
        setIdx((i) => (i + 1) % words.length);
        setVisible(true);
      }, 220);
    }, interval);
    return () => clearInterval(id);
  }, [interval, words.length]);
  return (
    <span
      style={{
        color: "var(--accent)",
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(4px)",
        transition: "opacity 220ms ease, transform 220ms ease",
        display: "inline-block",
      }}
    >
      {brackets ? `[${words[idx]}]` : words[idx]}
    </span>
  );
};

// ── Welcome ──────────────────────────────────────────────────────
const WelcomeScreen = ({ onSignIn, onStart, photo = "athlete" }) => {
  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--bg-primary)" }}>
      {/* Full-bleed athletic photo placeholder */}
      <PhotoPlaceholder
        kind={photo}
        style={{
          position: "absolute",
          inset: 0,
        }}
      />
      {/* Dim scrim from bottom for legibility */}
      <div
        style={{
          position: "absolute",
          inset: 0,
          background: "linear-gradient(180deg, rgba(13,8,8,0.35) 0%, rgba(13,8,8,0.1) 30%, rgba(13,8,8,0.85) 75%, rgba(13,8,8,0.98) 100%)",
        }}
      />
      {/* Subtle T-monogram watermark off to one side */}
      <img
        src="assets/tkdn-t.png"
        alt=""
        style={{
          position: "absolute",
          top: "8%",
          right: "4%",
          width: 380,
          opacity: 0.07,
          mixBlendMode: "screen",
        }}
      />

      {/* Top - wordmark only */}
      <div
        style={{
          position: "absolute",
          top: 64,
          left: -16,
          right: 20,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          color: "rgba(255,255,255,0.85)",
        }}
      >
        <img src="assets/tkdn-wordmark.png" alt="TAKEDOWN" style={{ height: 26, objectFit: "contain" }} />
      </div>

      {/* Bottom - headline + CTAs */}
      <div
        style={{
          position: "absolute",
          left: 20,
          right: 20,
          bottom: 56,
          color: "#fff",
        }}
      >
        <Overline style={{ color: "rgba(255,255,255,0.5)", marginBottom: 16, fontStyle: "italic", fontFamily: "'Avenir Next', 'Figtree', sans-serif" }}>
          COMBAT SPORT LIVES HERE.
        </Overline>
        <div
          className="t-h1"
          style={{
            color: "#fff",
            marginBottom: 8,
          }}
        >
          HOMEBASE
          <br />
          FOR
          <br />
          <RotatingWord /><span style={{ color: "var(--accent)" }}>.</span>
        </div>
        <p className="t-body-lg" style={{ color: "rgba(255,255,255,0.7)", margin: "20px 0 28px", maxWidth: 300 }}>
          Gear, training content, rankings, events, and sponsorships.
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <Button label="GET STARTED" rightIcon={<I.ArrowRight />} fullWidth size="large" onClick={onStart} tone="mono" />
          <Button label="I HAVE AN ACCOUNT" fullWidth size="large" variant="ghost" onClick={onSignIn} tone="mono" />
        </div>
      </div>
    </div>
  );
};

// ── Login ────────────────────────────────────────────────────────
const LoginScreen = ({ onBack, onLogin, onForgot, onSignup }) => {
  const [email, setEmail] = React.useState("alex@dojo.gg");
  const [pw, setPw] = React.useState("•••••••••");
  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--bg-primary)" }}>
      <TopBar
        left={
          <button onClick={onBack} style={{ background: "transparent", border: "none", color: "var(--text-primary)", padding: 4, cursor: "pointer" }}>
            <I.ArrowLeft size={22} />
          </button>
        }
      />
      <div style={{ padding: "8px 20px 0", height: "calc(100% - 86px)", overflow: "auto" }} className="no-scrollbar">
        <Overline style={{ color: "var(--accent)" }}>STEP 01 · SIGN IN</Overline>
        <h1 className="t-h2" style={{ marginTop: 8 }}>Welcome back.</h1>
        <p className="t-body-lg" style={{ color: "var(--text-secondary)", marginTop: 8 }}>
          Pick up where your last build left off. Drafts and orders are synced.
        </p>

        <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 32 }}>
          <TextInput label="Email" value={email} onChange={setEmail} />
          <TextInput label="Password" value={pw} onChange={setPw} isPassword />
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: -4 }}>
            <button
              onClick={onForgot}
              className="t-sub-sm"
              style={{ color: "var(--accent)", background: "transparent", border: "none", cursor: "pointer", padding: 4 }}
            >
              Forgot password?
            </button>
          </div>
        </div>

        <Button label="SIGN IN" fullWidth size="large" tone="mono" rightIcon={<I.ArrowRight />} onClick={onLogin} style={{ marginTop: 16 }} />

        {/* Divider */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "28px 0" }}>
          <Hairline />
          <Overline style={{ color: "var(--text-tertiary)" }}>OR</Overline>
          <Hairline />
        </div>

        <SocialRow />

        <div style={{ marginTop: 40, textAlign: "center" }}>
          <span className="t-body" style={{ color: "var(--text-secondary)" }}>New here? </span>
          <button onClick={onSignup} className="t-body-bold" style={{ color: "var(--accent)", background: "transparent", border: "none", cursor: "pointer", padding: 0 }}>
            Create account →
          </button>
        </div>
      </div>
    </div>
  );
};

// ── SocialRow (Apple / Google / X / Meta) ────────────────────────
const SocialRow = ({ onProvider }) => {
  const items = [
    {
      key: "apple",
      bg: "var(--text-primary)",
      fg: "var(--bg-primary)",
      icon: (
        <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17.04 12.78c-.02-2.21 1.8-3.27 1.88-3.32-1.03-1.5-2.62-1.7-3.18-1.72-1.35-.14-2.64.8-3.33.8-.69 0-1.75-.78-2.88-.76-1.48.02-2.85.86-3.61 2.18-1.54 2.67-.39 6.62 1.11 8.79.73 1.06 1.6 2.25 2.74 2.21 1.1-.04 1.51-.71 2.84-.71 1.33 0 1.7.71 2.87.69 1.18-.02 1.93-1.08 2.66-2.15.84-1.23 1.18-2.42 1.2-2.48-.03-.01-2.3-.88-2.3-3.53zm-2.18-6.48c.6-.72 1-1.73.89-2.73-.86.03-1.9.57-2.51 1.29-.55.64-1.04 1.67-.91 2.65.96.08 1.94-.49 2.53-1.21z"/>
        </svg>
      ),
    },
    {
      key: "google",
      bg: "var(--text-primary)",
      fg: "var(--bg-primary)",
      icon: (
        <svg width="22" height="22" viewBox="0 0 24 24">
          <path fill="#4285F4" d="M21.6 12.23c0-.71-.06-1.39-.18-2.05H12v3.87h5.37a4.59 4.59 0 0 1-2 3v2.5h3.23c1.89-1.74 2.97-4.3 2.97-7.32z"/>
          <path fill="#34A853" d="M12 22c2.7 0 4.96-.9 6.62-2.45l-3.23-2.5c-.9.6-2.04.95-3.39.95-2.6 0-4.81-1.76-5.6-4.12H3.07v2.58A10 10 0 0 0 12 22z"/>
          <path fill="#FBBC05" d="M6.4 13.88a6 6 0 0 1 0-3.76V7.54H3.07a10 10 0 0 0 0 8.92l3.33-2.58z"/>
          <path fill="#EA4335" d="M12 5.88c1.47 0 2.79.5 3.83 1.5l2.87-2.87C16.95 2.99 14.7 2 12 2A10 10 0 0 0 3.07 7.54L6.4 10.12C7.19 7.76 9.4 5.88 12 5.88z"/>
        </svg>
      ),
    },
    {
      key: "x",
      bg: "var(--text-primary)",
      fg: "var(--bg-primary)",
      icon: (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
          <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
        </svg>
      ),
    },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {items.map((s) => (
        <button
          key={s.key}
          onClick={() => onProvider && onProvider(s.key)}
          style={{
            height: 48,
            border: "1px solid var(--border-default)",
            background: "transparent",
            color: "var(--text-primary)",
            borderRadius: "var(--r-sm)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 12,
            fontFamily: "inherit",
            fontSize: 14,
            fontWeight: 600,
            letterSpacing: 0.04,
            cursor: "pointer",
            WebkitTapHighlightColor: "transparent",
          }}
        >
          {s.icon}
          <span>Continue with {s.key.charAt(0).toUpperCase() + s.key.slice(1)}</span>
        </button>
      ))}
    </div>
  );
};

// ── SignUp options ───────────────────────────────────────────────
const SignUpOptionsScreen = ({ onBack, onEmail, onSignIn }) => (
  <div style={{ position: "absolute", inset: 0, background: "var(--bg-primary)" }}>
    <TopBar
      left={
        <button onClick={onBack} style={{ background: "transparent", border: "none", color: "var(--text-primary)", padding: 4, cursor: "pointer" }}>
          <I.ArrowLeft size={22} />
        </button>
      }
    />
    <div style={{ padding: "8px 20px 0", height: "calc(100% - 86px)", overflow: "auto" }} className="no-scrollbar">
      <Overline style={{ color: "var(--accent)" }}>JOIN THOUSANDS OF ATHLETES</Overline>
      <h1 className="t-h2" style={{ marginTop: 8 }}>Get on the mat.</h1>
      <p className="t-body-lg" style={{ color: "var(--text-secondary)", marginTop: 8 }}>
        Build a kit, track your record, get in front of scouts. Free to join - pay only when you order.
      </p>

      <div style={{ marginTop: 32, marginBottom: 20 }}>
        <Button
          label="CONTINUE WITH EMAIL"
          fullWidth
          size="large"
          tone="mono"
          rightIcon={<I.ArrowRight />}
          onClick={onEmail}
        />
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "8px 0 20px" }}>
        <Hairline />
        <Overline style={{ color: "var(--text-tertiary)" }}>OR</Overline>
        <Hairline />
      </div>
      <SocialRow />

      <div style={{ marginTop: 28 }}>
        <p className="t-caption-lg" style={{ color: "var(--text-tertiary)", lineHeight: 1.5 }}>
          By continuing you agree to Takedown's Terms and Privacy Policy. We're a small team in a sweaty gym; we don't sell your data.
        </p>
      </div>

      <div style={{ marginTop: 32, textAlign: "center" }}>
        <span className="t-body" style={{ color: "var(--text-secondary)" }}>Already on the team? </span>
        <button onClick={onSignIn} className="t-body-bold" style={{ color: "var(--accent)", background: "transparent", border: "none", cursor: "pointer", padding: 0 }}>
          Sign in →
        </button>
      </div>
    </div>
  </div>
);

// ── Onboarding 3-step ────────────────────────────────────────────
const ONBOARDING_STEPS = [
  {
    code: "01 · YOUR MAT PRESENCE",
    title: "One profile.",
    body: "Log bouts, build a record, follow your room. Coaches and scouts see the same profile you do - no fragmented inbox.",
    photo: "mat",
    feature: "match log · roster · scout dm",
  },
  {
    code: "02 · BUILD YOUR KIT",
    title: "Custom apparel.",
    body: "Singlets, fight shorts, rashguards on a live canvas. Pick zones, drop your logo, ship in 14 days. No minimum order.",
    photo: "canvas",
    feature: "custom designer · 7 fabric zones · made in USA",
  },
  {
    code: "03 · FOR PROS",
    title: "On every mat that matters.",
    body: "Same platform RAF, PFL, and NHSCA athletes use. Get noticed by recruiters, hear about open mats, score the latest drops first.",
    photo: "gym",
    feature: "scout flags · room invites · early drops",
  },
];

const OnboardingScreen = ({ step = 0, onNext, onSkip, onBack }) => {
  const s = ONBOARDING_STEPS[step];
  const last = step === ONBOARDING_STEPS.length - 1;
  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--bg-primary)" }}>
      {/* Top - skip + step indicator */}
      <div
        style={{
          position: "absolute",
          top: 64,
          left: 20,
          right: 20,
          zIndex: 10,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <div style={{ display: "flex", gap: 6 }}>
          {ONBOARDING_STEPS.map((_, i) => (
            <div
              key={i}
              style={{
                width: i === step ? 28 : 16,
                height: 3,
                background: i === step ? "var(--text-primary)" : i < step ? "var(--text-secondary)" : "var(--border-subtle)",
                transition: "width var(--t-base)",
              }}
            />
          ))}
        </div>
        <button onClick={onSkip} className="t-overline" style={{ color: "var(--text-secondary)", background: "transparent", border: "none", cursor: "pointer", padding: 4 }}>
          SKIP →
        </button>
      </div>

      {/* Photo half */}
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: "55%" }}>
        <PhotoPlaceholder kind={s.photo} style={{ position: "absolute", inset: 0 }} />
        <div
          style={{
            position: "absolute",
            inset: 0,
            background: "linear-gradient(180deg, rgba(13,8,8,0.5) 0%, transparent 30%, transparent 70%, var(--bg-primary) 100%)",
          }}
        />
        {/* Corner crosshair marks - tactical */}
        {[
          [16, 120, "TL"],
          [null, 120, "TR"],
          [16, null, "BL"],
          [null, null, "BR"],
        ].map(([l, t, k], i) => (
          <CornerMark key={k} corner={k} />
        ))}

        {/* feature label, anchored bottom-left of photo */}
        <div
          style={{
            position: "absolute",
            left: 20,
            bottom: 24,
            color: "rgba(255,255,255,0.92)",
          }}
        >
          <div className="t-overline" style={{ color: "rgba(255,255,255,0.55)" }}>{s.feature}</div>
        </div>
      </div>

      {/* Copy half */}
      <div style={{ position: "absolute", top: "55%", left: 0, right: 0, bottom: 0, padding: "0 20px", display: "flex", flexDirection: "column" }}>
        <Overline style={{ color: "var(--accent)", marginTop: 28 }}>{s.code}</Overline>
        <h1 className="t-h2" style={{ marginTop: 12, textWrap: "balance" }}>{s.title}</h1>
        <p className="t-body-lg" style={{ color: "var(--text-secondary)", marginTop: 12 }}>{s.body}</p>

        <div style={{ marginTop: "auto", marginBottom: 32, display: "flex", gap: 10 }}>
          {step > 0 && (
            <Button label="BACK" variant="secondary" tone="mono" onClick={onBack} size="large" />
          )}
          <Button
            label={last ? "ENTER APP" : "NEXT"}
            tone="mono"
            rightIcon={<I.ArrowRight />}
            fullWidth
            size="large"
            onClick={onNext}
          />
        </div>
      </div>
    </div>
  );
};

const CornerMark = ({ corner = "TL", color = "rgba(255,255,255,0.5)" }) => {
  const size = 16;
  const stroke = 1.5;
  const offset = 14;
  const pos = {
    TL: { top: offset, left: offset },
    TR: { top: offset, right: offset },
    BL: { bottom: offset, left: offset },
    BR: { bottom: offset, right: offset },
  }[corner];
  const lineH = { background: color, position: "absolute", height: stroke };
  const lineV = { background: color, position: "absolute", width: stroke };
  return (
    <div style={{ position: "absolute", width: size, height: size, ...pos }}>
      <div style={{ ...lineH, width: size, top: corner.includes("T") ? 0 : "auto", bottom: corner.includes("B") ? 0 : "auto", left: corner.includes("L") ? 0 : "auto", right: corner.includes("R") ? 0 : "auto" }} />
      <div style={{ ...lineV, height: size, top: corner.includes("T") ? 0 : "auto", bottom: corner.includes("B") ? 0 : "auto", left: corner.includes("L") ? 0 : "auto", right: corner.includes("R") ? 0 : "auto" }} />
    </div>
  );
};

// ── Role selection ────────────────────────────────────────────────
const ROLES = [
  {
    key: "athlete",
    code: "A · 01",
    title: "WRESTLER",
    body: "You step on the mat. Track record, study technique, get scouted. Singlets, sweats, and shoes.",
    moduleKey: "athlete",
  },
  {
    key: "builder",
    code: "B · 02",
    title: "TEAM DESIGNER",
    body: "You design for your room. Manage drafts, approvals, bulk team orders. Wholesale unlocked at 12+.",
    moduleKey: "builder",
  },
  {
    key: "coach",
    code: "C · 03",
    title: "COACH / ROOM",
    body: "You run a wrestling room or gym. Build a roster, post matches, scout talent.",
    moduleKey: "dojo",
  },
];

const RoleSelectionScreen = ({ onContinue, onBack }) => {
  const [picked, setPicked] = React.useState("athlete");
  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--bg-primary)" }}>
      <TopBar
        left={
          <button onClick={onBack} style={{ background: "transparent", border: "none", color: "var(--text-primary)", padding: 4, cursor: "pointer" }}>
            <I.ArrowLeft size={22} />
          </button>
        }
      />
      <div style={{ padding: "8px 20px 0", height: "calc(100% - 86px)", display: "flex", flexDirection: "column" }}>
        <Overline style={{ color: "var(--accent)" }}>STEP · ROLE</Overline>
        <h1 className="t-h2" style={{ marginTop: 8 }}>Where do you stand?</h1>
        <p className="t-body-lg" style={{ color: "var(--text-secondary)", marginTop: 8 }}>
          You can be more than one. Pick your primary; we'll set the rest up later.
        </p>

        <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 10 }}>
          {ROLES.map((r) => {
            const sel = picked === r.key;
            return (
              <button
                key={r.key}
                onClick={() => setPicked(r.key)}
                style={{
                  textAlign: "left",
                  background: "transparent",
                  border: `${sel ? 2 : 1}px solid ${sel ? "var(--text-primary)" : "var(--border-subtle)"}`,
                  padding: sel ? 19 : 20,
                  borderRadius: "var(--r-sm)",
                  cursor: "pointer",
                  color: "var(--text-primary)",
                  transition: "border-color var(--t-fast)",
                  WebkitTapHighlightColor: "transparent",
                  position: "relative",
                }}
              >
                {/* module tint accent stripe */}
                <div
                  style={{
                    position: "absolute",
                    top: sel ? 18 : 19,
                    left: sel ? 18 : 19,
                    bottom: sel ? 18 : 19,
                    width: 3,
                    background: MODULE_TINTS[r.moduleKey],
                    opacity: sel ? 1 : 0.5,
                  }}
                />
                <div style={{ paddingLeft: 16, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div>
                    <Overline style={{ color: "var(--text-tertiary)" }}>{r.code}</Overline>
                    <div className="t-h4" style={{ marginTop: 6 }}>{r.title}</div>
                    <p className="t-body" style={{ color: "var(--text-secondary)", marginTop: 4 }}>{r.body}</p>
                  </div>
                  <div
                    style={{
                      width: 22,
                      height: 22,
                      borderRadius: "var(--r-full)",
                      border: `1.5px solid ${sel ? "var(--text-primary)" : "var(--border-default)"}`,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      flexShrink: 0,
                      marginTop: 4,
                    }}
                  >
                    {sel && <div style={{ width: 10, height: 10, borderRadius: "var(--r-full)", background: "var(--text-primary)" }} />}
                  </div>
                </div>
              </button>
            );
          })}
        </div>

        <div style={{ marginTop: "auto", marginBottom: 28 }}>
          <Button label="CONTINUE" fullWidth size="large" tone="mono" rightIcon={<I.ArrowRight />} onClick={() => onContinue && onContinue(picked)} />
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  WelcomeScreen,
  LoginScreen,
  SignUpOptionsScreen,
  OnboardingScreen,
  RoleSelectionScreen,
  SocialRow,
  CornerMark,
  ONBOARDING_STEPS,
  RotatingWord,
});
