
// OnboardingFlow.jsx — Onboarding screens:
//   1) WelcomeScreen   — pick a display name + identity colour
//   2) LaneClaimScreen  — claim one of five lanes (top/jungle/mid/adc/support)
//
// All three share a "cozy-rift" backdrop with floating mascots, runes and a
// faint wyrm silhouette. Visual vocabulary matches the existing Cozy Draft:
// terracotta border + corner dots, sticker buttons, position colours.

const { useState, useEffect, useMemo } = React;

// -----------------------------------------------------------------------------
// Shared background — floating mascots, runes, soft wyrm silhouettes
// -----------------------------------------------------------------------------
function CozyRiftBackdrop({ variant = 'welcome' }) {
  // Pre-computed sprinkle positions; deterministic so it doesn't shuffle on rerender.
  const decor = useMemo(() => [
  // paw mascots (floating)
  { kind: 'paw', top: '12%', left: '6%', size: 38, delay: 0, rot: -8 },
  { kind: 'paw', top: '70%', left: '88%', size: 30, delay: 0.6, rot: 12 },
  { kind: 'paw', top: '78%', left: '8%', size: 24, delay: 1.2, rot: -16 },
  // small paw prints
  { kind: 'print', top: '22%', left: '82%', size: 18, delay: 0.3, rot: 20 },
  { kind: 'print', top: '55%', left: '4%', size: 14, delay: 0.9, rot: -10 },
  { kind: 'print', top: '88%', left: '60%', size: 16, delay: 0.4, rot: 5 },
  // runes
  { kind: 'rune0', top: '34%', left: '92%', size: 26, delay: 0.5 },
  { kind: 'rune1', top: '8%', left: '46%', size: 22, delay: 0.7 },
  { kind: 'rune2', top: '90%', left: '32%', size: 28, delay: 1.0 },
  { kind: 'rune3', top: '48%', left: '94%', size: 20, delay: 1.3 },
  // sparkles
  { kind: 'spark', top: '18%', left: '24%', size: 14, delay: 0.2 },
  { kind: 'spark', top: '38%', left: '70%', size: 18, delay: 0.8 },
  { kind: 'spark', top: '64%', left: '30%', size: 12, delay: 1.4 },
  { kind: 'spark', top: '82%', left: '78%', size: 16, delay: 1.7 }],
  []);

  return (
    <div style={{
      position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none',
      background: 'radial-gradient(ellipse at top, var(--surface-nested) 0%, var(--surface-page) 100%)'
    }}>
      {/* Faint wyrm silhouettes */}
      <div style={{ position: 'absolute', top: '4%', right: '-40px', transform: 'rotate(-8deg)' }}>
        <window.WyrmSilhouette size={300} color="var(--accent-orange)" opacity={0.08} />
      </div>
      <div style={{ position: 'absolute', bottom: '-20px', left: '-60px', transform: 'scaleX(-1) rotate(6deg)' }}>
        <window.WyrmSilhouette size={260} color="#7CBF8E" opacity={0.06} />
      </div>

      {/* Floating decor */}
      {decor.map((d, i) => {
        const common = {
          position: 'absolute', top: d.top, left: d.left,
          animation: `float 3.6s ease-in-out ${d.delay}s infinite`,
          transform: d.rot ? `rotate(${d.rot}deg)` : undefined,
          opacity: d.kind === 'spark' ? 0.85 : 0.55
        };
        if (d.kind === 'paw') return <div key={i} style={common}><window.PawMascot size={d.size} color="var(--accent-orange)" /></div>;
        if (d.kind === 'print') return <div key={i} style={common}><window.PawPrint size={d.size} color="var(--accent-orange)" /></div>;
        if (d.kind === 'spark') return <div key={i} style={common}><window.CrystalSparkle size={d.size} color="var(--accent-orange)" /></div>;
        if (d.kind.startsWith('rune')) {
          const v = parseInt(d.kind.slice(4), 10);
          const tone = ['#C5B4E3', '#7CBF8E', '#F2A7C3', '#AED6F1'][v];
          return <div key={i} style={common}><window.RuneGlyph variant={v} size={d.size} color={tone} /></div>;
        }
        return null;
      })}
    </div>);

}

// -----------------------------------------------------------------------------
// Authentication Backend — Username/Password Auth & Realtime DB Indexing
// -----------------------------------------------------------------------------
async function createAccountWithUsername(username, email, password) {
  const cleanUsername = (username || '').trim().toLowerCase();
  if (!cleanUsername || cleanUsername.length < 2) {
    throw new Error('Username must be at least 2 characters.');
  }

  if (!password || password.length < 6) {
    throw new Error('Password must be at least 6 characters.');
  }

  if (!window.db) {
    throw new Error('Database is not initialized.');
  }

  // 1. Check if usernames/{username} exists (case-insensitive)
  const usernameSnap = await window.db.ref('usernames/' + cleanUsername).once('value');
  if (usernameSnap.exists()) {
    throw new Error('Username is already taken.');
  }

  // 2. Synthetic internal email credential
  const syntheticEmail = `${cleanUsername}@cozydraft.internal`;

  // 3. Create Firebase Auth account
  const userCredential = await firebase.auth().createUserWithEmailAndPassword(syntheticEmail, password);
  const uid = userCredential.user.uid;

  // 4. Granular per-leaf writes to usernames/{username} and users/{uid}
  const cleanEmail = email && email.trim() ? email.trim() : null;
  await window.db.ref(`usernames/${cleanUsername}`).set(uid);
  await window.db.ref(`users/${uid}/username`).set(cleanUsername);
  await window.db.ref(`users/${uid}/email`).set(cleanEmail);
  await window.db.ref(`users/${uid}/createdAt`).set(Date.now());

  // 5. Index real email if provided: emails/{sanitizedEmail} -> uid
  if (cleanEmail) {
    const sanitizedEmail = cleanEmail.toLowerCase().replace(/\./g, ',');
    await window.db.ref(`emails/${sanitizedEmail}`).set(uid);
  }

  return { user: userCredential.user, uid, username: cleanUsername };
}

async function signInWithUsernameOrEmail(identifier, password) {
  const cleanId = (identifier || '').trim().toLowerCase();
  if (!cleanId || !password) {
    throw new Error('Please enter username/email and password.');
  }

  if (!window.db) {
    throw new Error('Database is not initialized.');
  }

  let syntheticEmail = null;

  if (cleanId.includes('@')) {
    const sanitizedEmail = cleanId.replace(/\./g, ',');
    const emailSnap = await window.db.ref(`emails/${sanitizedEmail}`).once('value');
    const uid = emailSnap.val();
    if (!uid) {
      throw new Error('Invalid username/email or password.');
    }
    const userSnap = await window.db.ref(`users/${uid}/username`).once('value');
    const uname = userSnap.val();
    if (!uname) {
      throw new Error('Invalid username/email or password.');
    }
    syntheticEmail = `${uname}@cozydraft.internal`;
  } else {
    syntheticEmail = `${cleanId}@cozydraft.internal`;
  }

  try {
    const cred = await firebase.auth().signInWithEmailAndPassword(syntheticEmail, password);
    return cred;
  } catch (err) {
    // Avoid account enumeration by returning standard error message
    throw new Error('Invalid username/email or password.');
  }
}

// -----------------------------------------------------------------------------
// SignInScreen — "Welcome back" card matching reference design
// -----------------------------------------------------------------------------
function SignInScreen({ onSwitchToSignUp, onSuccess }) {
  const [identifier, setIdentifier] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const canSubmit = identifier.trim().length > 0 && password.length > 0;

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    if (!canSubmit || loading) return;

    setError(null);
    setLoading(true);
    try {
      await signInWithUsernameOrEmail(identifier, password);
      setLoading(false);
      if (onSuccess) onSuccess();
    } catch (err) {
      setLoading(false);
      setError(err.message || 'Invalid username/email or password.');
    }
  };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '40px 20px', position: 'relative'
    }}>
      <CozyRiftBackdrop variant="welcome" />

      {/* Header outside card matching reference design */}
      <div style={{ textAlign: 'center', marginBottom: 20, position: 'relative', zIndex: 2 }}>
        <div style={{ fontSize: 36, marginBottom: 4, display: 'inline-block' }}>🌸</div>
        <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 32, margin: '0 0 4px 0', lineHeight: 1.1 }}>
          Cozy Draft
        </h1>
        <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700 }}>
          Your profile, your pools — on any device
        </div>
      </div>

      {/* Main card matching reference design */}
      <div className="cozy-card pop-in" style={{
        position: 'relative', maxWidth: 440, width: '100%',
        padding: '28px 26px', background: 'var(--surface-card)',
        borderRadius: 22, zIndex: 2
      }}>
        <div className="corner-dot" style={{ top: 9, left: 9 }} />
        <div className="corner-dot" style={{ top: 9, right: 9 }} />

        <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, marginBottom: 18, lineHeight: 1.2 }}>
          Welcome back
        </h2>

        {error && (
          <div style={{
            background: '#FADBD8', color: '#78281F', border: '1.5px solid #F5B7B1',
            borderRadius: 12, padding: '10px 14px', fontSize: 13, fontWeight: 700,
            marginBottom: 16, textAlign: 'center'
          }}>
            ⚠️ {error}
          </div>
        )}

        <form onSubmit={handleSubmit}>
          {/* Identifier (Username or Email) */}
          <div style={{ marginBottom: 16, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              USERNAME OR EMAIL
            </label>
            <input
              type="text"
              value={identifier}
              onChange={(e) => setIdentifier(e.target.value)}
              placeholder="wallnut"
              autoFocus
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
          </div>

          {/* Password */}
          <div style={{ marginBottom: 24, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              PASSWORD
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
          </div>

          {/* Sign in button */}
          <button
            type="submit"
            disabled={!canSubmit || loading}
            className="cozy-btn"
            style={{
              width: '100%', padding: '14px',
              background: canSubmit && !loading ? 'var(--accent-orange)' : 'var(--border-default)',
              border: 'none', borderRadius: 16,
              fontFamily: 'Fredoka One, cursive', fontSize: 17, color: '#FFFFFF',
              cursor: canSubmit && !loading ? 'pointer' : 'not-allowed',
              boxShadow: canSubmit && !loading ? '0 4px 0 rgba(0,0,0,0.2)' : 'none',
              opacity: canSubmit && !loading ? 1 : 0.7,
              transition: 'all 0.18s ease'
            }}
          >
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
      </div>

      {/* Footer link matching reference design */}
      <div style={{ marginTop: 18, textAlign: 'center', fontSize: 13, color: 'var(--text-muted)', fontWeight: 700, zIndex: 2 }}>
        New here? <span onClick={onSwitchToSignUp} style={{ color: 'var(--accent-orange)', textDecoration: 'underline', cursor: 'pointer' }}>Create an account</span>
      </div>
    </div>
  );
}

// -----------------------------------------------------------------------------
// SignUpScreen — "Create your account" card matching reference design
// -----------------------------------------------------------------------------
function SignUpScreen({ onSwitchToSignIn, onSuccess }) {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);
  const [usernameError, setUsernameError] = useState(null);
  const [checkingUsername, setCheckingUsername] = useState(false);
  const [loading, setLoading] = useState(false);

  // Check username availability as the user finishes typing
  useEffect(() => {
    const cleanUsername = username.trim().toLowerCase();
    if (!cleanUsername || cleanUsername.length < 2) {
      setUsernameError(null);
      setCheckingUsername(false);
      return;
    }

    setCheckingUsername(true);
    const timer = setTimeout(async () => {
      if (window.db) {
        try {
          const snap = await window.db.ref('usernames/' + cleanUsername).once('value');
          if (snap.exists()) {
            setUsernameError('Username is already taken.');
          } else {
            setUsernameError(null);
          }
        } catch (e) {
          console.error("Username availability check failed:", e);
        }
      }
      setCheckingUsername(false);
    }, 350);

    return () => clearTimeout(timer);
  }, [username]);

  const canSubmit = username.trim().length >= 2 && !usernameError && password.length >= 6;

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    if (!canSubmit || loading) return;

    setError(null);
    setLoading(true);
    try {
      const res = await createAccountWithUsername(username, email, password);
      setLoading(false);
      if (onSuccess) onSuccess(res?.username || username.trim(), res?.uid);
    } catch (err) {
      setLoading(false);
      setError(err.message || 'Signup failed.');
    }
  };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '40px 20px', position: 'relative'
    }}>
      <CozyRiftBackdrop variant="welcome" />

      {/* Header outside card matching reference design */}
      <div style={{ textAlign: 'center', marginBottom: 20, position: 'relative', zIndex: 2 }}>
        <div style={{ fontSize: 36, marginBottom: 4, display: 'inline-block' }}>🌸</div>
        <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 32, margin: '0 0 4px 0', lineHeight: 1.1 }}>
          Cozy Draft
        </h1>
        <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700 }}>
          Your profile, your pools — on any device
        </div>
      </div>

      {/* Main card matching reference design */}
      <div className="cozy-card pop-in" style={{
        position: 'relative', maxWidth: 440, width: '100%',
        padding: '28px 26px', background: 'var(--surface-card)',
        borderRadius: 22, zIndex: 2
      }}>
        <div className="corner-dot" style={{ top: 9, left: 9 }} />
        <div className="corner-dot" style={{ top: 9, right: 9 }} />

        <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, marginBottom: 6, lineHeight: 1.2 }}>
          Create your account
        </h2>
        <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 600, marginBottom: 18, lineHeight: 1.4 }}>
          This is what you sign in with anywhere — phone, another browser, a friend's PC.
        </div>

        {error && (
          <div style={{
            background: '#FADBD8', color: '#78281F', border: '1.5px solid #F5B7B1',
            borderRadius: 12, padding: '10px 14px', fontSize: 13, fontWeight: 700,
            marginBottom: 16, textAlign: 'center'
          }}>
            ⚠️ {error}
          </div>
        )}

        <form onSubmit={handleSubmit}>
          {/* Username with live inline availability check */}
          <div style={{ marginBottom: 16, textAlign: 'left' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <label style={{
                fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
                letterSpacing: 0.6, textTransform: 'uppercase'
              }}>
                USERNAME
              </label>
              {checkingUsername && (
                <span style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700 }}>Checking…</span>
              )}
            </div>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="wallnut"
              autoFocus
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: usernameError ? '2px solid #D9534F' : '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
            {usernameError && (
              <div style={{ color: '#D9534F', fontSize: 12, fontWeight: 700, marginTop: 4 }}>
                ⚠️ {usernameError}
              </div>
            )}
          </div>

          {/* Email (Optional) */}
          <div style={{ marginBottom: 16, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              EMAIL (OPTIONAL)
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
          </div>

          {/* Password (at least 6 characters) */}
          <div style={{ marginBottom: 24, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              PASSWORD
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="at least 6 characters"
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
          </div>

          {/* Continue button */}
          <button
            type="submit"
            disabled={!canSubmit || loading}
            className="cozy-btn"
            style={{
              width: '100%', padding: '14px',
              background: canSubmit && !loading ? 'var(--accent-orange)' : 'var(--border-default)',
              border: 'none', borderRadius: 16,
              fontFamily: 'Fredoka One, cursive', fontSize: 17, color: '#FFFFFF',
              cursor: canSubmit && !loading ? 'pointer' : 'not-allowed',
              boxShadow: canSubmit && !loading ? '0 4px 0 rgba(0,0,0,0.2)' : 'none',
              opacity: canSubmit && !loading ? 1 : 0.7,
              transition: 'all 0.18s ease'
            }}
          >
            {loading ? 'Creating account…' : 'Continue →'}
          </button>
        </form>
      </div>

      {/* Footer link matching reference design */}
      <div style={{ marginTop: 18, textAlign: 'center', fontSize: 13, color: 'var(--text-muted)', fontWeight: 700, zIndex: 2 }}>
        Already have an account? <span onClick={onSwitchToSignIn} style={{ color: 'var(--accent-orange)', textDecoration: 'underline', cursor: 'pointer' }}>Sign in</span>
      </div>
    </div>
  );
}

// -----------------------------------------------------------------------------
// ProfileSetupScreen — Profile setup form matching reference design
// -----------------------------------------------------------------------------
function ProfileSetupScreen({ onContinue, initialUsername, createdUid, onSwitchToSignIn }) {
  const { IDENTITY_COLORS, myUserId, players, updatePlayerIdentity, setTempIdentity, resetSessionUserId } = window.useApp();
  const me = players.find((p) => p.id === myUserId) || players[0];

  const [displayName, setDisplayName] = useState(initialUsername || '');
  const [icon, setIcon] = useState('flower');
  const [identityColor, setIdentityColor] = useState(IDENTITY_COLORS ? IDENTITY_COLORS[0] : '#F2A7C3');
  const [preferredLane, setPreferredLane] = useState('MID');

  const AVATAR_ICONS = [
    { id: 'flower', label: 'Flower', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>🌸</span> },
    { id: 'clover', label: 'Clover', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>🍀</span> },
    { id: 'heart', label: 'Heart', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>💖</span> },
    { id: 'paw', label: 'Paw', render: (c) => <window.PawMascot size={26} color={c || 'var(--accent-orange)'} /> },
    { id: 'frog', label: 'Frog', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>🐸</span> },
    { id: 'bunny', label: 'Bunny', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>🐰</span> },
    { id: 'mask', label: 'Mask', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>🎭</span> },
    { id: 'ghost', label: 'Ghost', render: () => <span style={{ fontSize: 24, display: 'inline-block' }}>👻</span> },
    { id: 'star', label: 'Star', render: (c) => <window.LolIcon name="star" size={24} color={c || '#F7DFA0'} /> },
  ];

  const LANES = [
    { id: 'TOP', label: 'Top' },
    { id: 'JUNGLE', label: 'Jungle' },
    { id: 'MID', label: 'Mid' },
    { id: 'ADC', label: 'ADC' },
    { id: 'SUPPORT', label: 'Support' },
  ];

  // Validation: required fields are display name (min 2 chars), icon, and colour. Preferred lane is optional.
  const canSubmit = displayName.trim().length >= 2 && !!icon && !!identityColor;

  const handleSubmit = (e) => {
    if (e) e.preventDefault();
    if (!canSubmit) return;
    const trimmedName = displayName.trim();

    if (!localStorage.getItem('cozydraft-userid') && typeof resetSessionUserId === 'function') {
      resetSessionUserId();
    }

    const authUser = window.firebase && window.firebase.auth && window.firebase.auth().currentUser;
    const authUid = authUser ? authUser.uid : null;

    const uid = createdUid
      || authUid
      || (!authUser ? (window.sessionUserId || localStorage.getItem('cozydraft-userid')) : null);

    // Granular per-leaf writes to users/{uid}: displayName, icon, identityColor, preferredLane, profileSetupComplete
    if (window.db && uid) {
      try {
        window.db.ref(`users/${uid}/displayName`).set(trimmedName);
        window.db.ref(`users/${uid}/icon`).set(icon);
        window.db.ref(`users/${uid}/identityColor`).set(identityColor);
        window.db.ref(`users/${uid}/preferredLane`).set(preferredLane);
        window.db.ref(`users/${uid}/profileSetupComplete`).set(true);
      } catch (err) {
        console.error("Granular write to users/{uid} failed:", err);
      }
    }

    if (typeof setTempIdentity === 'function') {
      setTempIdentity({
        displayName: trimmedName,
        displayColor: identityColor,
        icon,
        preferredLane
      });
    }

    window.profileSetupPending = false;

    if (typeof onContinue === 'function') {
      onContinue();
    }
  };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '40px 20px', position: 'relative'
    }}>
      <CozyRiftBackdrop variant="welcome" />

      {/* Header outside card matching reference design */}
      <div style={{ textAlign: 'center', marginBottom: 20, position: 'relative', zIndex: 2 }}>
        <div style={{ fontSize: 36, marginBottom: 4, display: 'inline-block' }}>🌸</div>
        <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 32, margin: '0 0 4px 0', lineHeight: 1.1 }}>
          Cozy Draft
        </h1>
        <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700 }}>
          Your profile, your pools — on any device
        </div>
      </div>

      {/* Main Cozy Card Container matching reference design */}
      <div className="cozy-card pop-in" style={{
        position: 'relative', maxWidth: 460, width: '100%',
        padding: '28px 26px', background: 'var(--surface-card)',
        borderRadius: 22, zIndex: 2
      }}>
        <div className="corner-dot" style={{ top: 9, left: 9 }} />
        <div className="corner-dot" style={{ top: 9, right: 9 }} />

        <h2 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 24, marginBottom: 6, lineHeight: 1.2 }}>
          Set up your profile
        </h2>
        <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 600, marginBottom: 20, lineHeight: 1.4 }}>
          Choose your identity, avatar icon, colour, and preferred lane.
        </div>

        <form onSubmit={handleSubmit}>
          {/* Display Name */}
          <div style={{ marginBottom: 18, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              DISPLAY NAME
            </label>
            <input
              type="text"
              value={displayName}
              onChange={(e) => setDisplayName(e.target.value.slice(0, 20))}
              placeholder="wallnut"
              autoFocus
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--surface-nested)',
                border: '2px solid var(--border-default)',
                borderRadius: 14, fontFamily: 'Nunito', fontWeight: 700, fontSize: 15,
                color: 'var(--text-primary)', outline: 'none', transition: 'border-color 0.2s'
              }}
            />
          </div>

          {/* Icon Picker (Grid of Options) */}
          <div style={{ marginBottom: 18, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              ICON
            </label>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8,
              padding: '2px 0'
            }}>
              {AVATAR_ICONS.map((item) => {
                const selected = icon === item.id;
                return (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => setIcon(item.id)}
                    className="cozy-btn"
                    style={{
                      height: 48,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      background: selected ? identityColor + '30' : 'var(--surface-nested)',
                      border: selected ? '2.5px solid var(--border-emphasis)' : '1.5px solid var(--border-default)',
                      borderRadius: 14, cursor: 'pointer',
                      transform: selected ? 'scale(1.05)' : 'scale(1)',
                      boxShadow: selected ? `0 0 8px ${identityColor}` : 'none',
                      transition: 'all 0.15s ease'
                    }}
                    title={item.label}
                  >
                    {item.render(selected ? identityColor : 'var(--accent-orange)')}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Colour Swatch Picker */}
          <div style={{ marginBottom: 18, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              COLOUR
            </label>
            <div style={{
              display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-start',
              padding: '4px 0'
            }}>
              {IDENTITY_COLORS.map((c) => {
                const selected = c === identityColor;
                return (
                  <button
                    key={c}
                    type="button"
                    onClick={() => setIdentityColor(c)}
                    className="cozy-btn"
                    aria-label={`Select colour ${c}`}
                    style={{
                      width: 36, height: 36, borderRadius: '50%',
                      background: c,
                      border: selected ? '3px solid var(--text-primary)' : '2px solid var(--surface-card)',
                      boxShadow: selected ? `0 0 10px ${c}` : '0 2px 4px rgba(0,0,0,0.1)',
                      cursor: 'pointer',
                      transform: selected ? 'scale(1.18)' : 'scale(1)',
                      transition: 'all 0.15s ease'
                    }}
                  />
                );
              })}
            </div>
          </div>

          {/* Preferred Lane (Chip Selector: Top/Jungle/Mid/ADC/Support) */}
          <div style={{ marginBottom: 24, textAlign: 'left' }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 800, color: 'var(--text-muted)',
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6
            }}>
              PREFERRED LANE
            </label>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {LANES.map((lane) => {
                const selected = preferredLane === lane.id;
                const laneColor = window.POSITION_COLORS ? window.POSITION_COLORS[lane.id] : '#F7DFA0';
                return (
                  <button
                    key={lane.id}
                    type="button"
                    onClick={() => setPreferredLane(lane.id)}
                    className="cozy-btn"
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '7px 12px',
                      background: selected ? laneColor : 'var(--surface-nested)',
                      border: selected ? '2.5px solid var(--border-emphasis)' : '1.5px solid var(--border-default)',
                      borderRadius: 14,
                      fontFamily: 'Nunito', fontWeight: selected ? 800 : 700, fontSize: 13,
                      color: selected ? 'var(--text-on-light-pastel)' : 'var(--text-primary)',
                      boxShadow: selected ? '0 2px 6px rgba(0,0,0,0.15)' : 'none',
                      cursor: 'pointer',
                      transition: 'all 0.15s ease'
                    }}
                  >
                    <window.RoleIcon pos={lane.id} size={16} color={selected ? 'var(--text-on-light-pastel)' : 'var(--text-primary)'} />
                    <span>{lane.label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Create account / Submit Button */}
          <button
            type="submit"
            disabled={!canSubmit}
            className="cozy-btn"
            style={{
              width: '100%', padding: '14px',
              background: canSubmit ? 'var(--accent-orange)' : 'var(--border-default)',
              border: 'none', borderRadius: 16,
              fontFamily: 'Fredoka One, cursive', fontSize: 17, color: '#FFFFFF',
              cursor: canSubmit ? 'pointer' : 'not-allowed',
              boxShadow: canSubmit ? '0 4px 0 rgba(0,0,0,0.2)' : 'none',
              opacity: canSubmit ? 1 : 0.7,
              transition: 'all 0.18s ease'
            }}
          >
            Create account
          </button>
        </form>
      </div>

      {/* Footer Link matching reference design */}
      <div style={{ marginTop: 18, textAlign: 'center', fontSize: 13, color: 'var(--text-muted)', fontWeight: 700, zIndex: 2 }}>
        Already have an account? <span onClick={onSwitchToSignIn} style={{ color: 'var(--accent-orange)', textDecoration: 'underline', cursor: 'pointer' }}>Sign in</span>
      </div>
    </div>
  );
}

// -----------------------------------------------------------------------------
// SignUpFlowScreen — Single component containing credentials step & profile step internally
// -----------------------------------------------------------------------------
function SignUpFlowScreen({ onSwitchToSignIn, onComplete }) {
  const [step, setStep] = useState('credentials'); // 'credentials' | 'profile'
  const [createdUsername, setCreatedUsername] = useState('');
  const [createdUid, setCreatedUid] = useState(null);

  if (step === 'credentials') {
    return (
      <SignUpScreen
        onSwitchToSignIn={onSwitchToSignIn}
        onSuccess={(uname, uid) => {
          window.profileSetupPending = true;
          setCreatedUsername(uname);
          setCreatedUid(uid);
          setStep('profile');
        }}
      />
    );
  }

  return (
    <ProfileSetupScreen
      initialUsername={createdUsername}
      createdUid={createdUid}
      onContinue={onComplete}
      onSwitchToSignIn={onSwitchToSignIn}
    />
  );
}

// -----------------------------------------------------------------------------
// AuthFlowScreen — Controls switching between Sign In and Sign Up
// -----------------------------------------------------------------------------
function AuthFlowScreen({ onContinue }) {
  const [mode, setMode] = useState('signin'); // 'signin' | 'signup'

  if (mode === 'signin') {
    return (
      <SignInScreen
        onSwitchToSignUp={() => setMode('signup')}
        onSuccess={() => onContinue()}
      />
    );
  }

  return (
    <SignUpFlowScreen
      onSwitchToSignIn={() => setMode('signin')}
      onComplete={onContinue}
    />
  );
}

const WelcomeScreen = AuthFlowScreen;



// -----------------------------------------------------------------------------
// LaneClaimScreen — pick one of 5 lanes; show claimed/owned/locked states
// -----------------------------------------------------------------------------
function LaneCard({ player, ownerName, ownerColor, state, onClaim, onRelease }) {
  // state: 'open' | 'mine' | 'locked'
  const colors = window.POSITION_COLORS;
  const labels = window.POSITION_LABELS;
  const tint = colors[player.position];
  const archetype = window.ARCHETYPE_BY_POSITION[player.position];

  const cardStyle = {
    padding: 18,
    background: 'var(--surface-card)',
    border: state === 'mine' ? '2.5px dashed var(--border-emphasis)' : '2.5px solid var(--border-emphasis)',
    borderRadius: 22,
    boxShadow: state === 'mine' ?
    '0 0 0 3px var(--border-default), 4px 6px 16px var(--border-default)' :
    '4px 4px 0 var(--border-default)',
    opacity: state === 'locked' ? 0.62 : 1,
    transition: 'transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s',
    position: 'relative',
    minHeight: 320,
    display: 'flex', flexDirection: 'column', alignItems: 'center',
    cursor: state === 'open' ? 'pointer' : 'default'
  };

  return (
    <div
      className="lane-card"
      style={cardStyle}
      onClick={state === 'open' ? onClaim : undefined}>
      
      {/* corner dots */}
      <div className="corner-dot" style={{ top: 9, left: 9 }} />
      <div className="corner-dot" style={{ top: 9, right: 9 }} />
      <div className="corner-dot corner-dot-bl" />
      <div className="corner-dot corner-dot-br" />

      {/* "you" badge */}
      {state === 'mine' &&
      <div style={{
        position: 'absolute', top: -14, left: '50%', transform: 'translateX(-50%)',
        display: 'flex', alignItems: 'center', gap: 6,
        background: 'var(--accent-orange)', color: 'var(--surface-page)', borderRadius: 14,
        padding: '4px 14px', fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
        whiteSpace: 'nowrap', boxShadow: '0 3px 0 rgba(0,0,0,0.2)',
        zIndex: 3
      }}>
          <window.LaurelCrest size={16} color="var(--surface-page)" />
          you <window.CrystalSparkle size={12} color="var(--surface-page)" />
        </div>
      }

      {/* lock badge */}
      {state === 'locked' &&
      <div style={{
        position: 'absolute', top: -14, left: '50%', transform: 'translateX(-50%)',
        background: 'var(--text-primary)', color: 'var(--surface-page)', borderRadius: 14,
        padding: '4px 12px', fontFamily: 'Nunito', fontWeight: 800, fontSize: 12,
        whiteSpace: 'nowrap', boxShadow: '0 3px 0 rgba(0,0,0,0.2)',
        zIndex: 3
      }}>
          🔒 Locked
        </div>
      }

      {/* Hex frame with role icon */}
      <div style={{ marginTop: 14, marginBottom: 14, position: 'relative' }}>
        <window.HexFrame
          size={96}
          color={tint}
          borderColor="var(--border-emphasis)"
          borderWidth={3}
          glow={state === 'mine'}>
          
          <window.RoleIcon pos={player.position} size={54} />
        </window.HexFrame>

        {/* tiny archetype silhouette */}
        <div style={{
          position: 'absolute', bottom: -4, right: -10,
          background: 'var(--surface-card)', borderRadius: '50%', border: '2px solid var(--border-emphasis)',
          width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <window.RoleSilhouette archetype={archetype} size={22} color="var(--text-primary)" />
        </div>
      </div>

      {/* Lane name */}
      <div className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 22, marginBottom: 4 }}>
        {labels[player.position]}
      </div>

      {/* State-specific footer */}
      <div style={{ flex: 1, width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', gap: 10 }}>
        {state === 'open' &&
        <>
            <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
              ⚔️ Open slot
            </div>
            <window.CozyButton color="sage" small onClick={(e) => {e.stopPropagation();onClaim();}}>
              Claim this lane 🛡️
            </window.CozyButton>
          </>
        }

        {state === 'mine' &&
        <>
            <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: ownerColor + '70',
            border: '2px solid ' + ownerColor,
            borderRadius: 14, padding: '4px 10px',
            fontWeight: 800, fontSize: 13, color: 'var(--text-on-light-pastel)'
          }}>
              <window.HexFrame size={18} color={ownerColor} borderColor="var(--border-emphasis)" borderWidth={1.5} />
              {ownerName}
            </div>
            <button
            onClick={(e) => {e.stopPropagation();onRelease();}}
            style={{
              background: 'transparent', border: '1.5px solid var(--border-default)',
              borderRadius: 12, padding: '4px 12px',
              fontFamily: 'Nunito', fontWeight: 800, fontSize: 11,
              color: 'var(--accent-orange)', cursor: 'pointer'
            }}>
            
              Release lane
            </button>
          </>
        }

        {state === 'locked' &&
        <>
            <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: ownerColor + '70',
            border: '2px solid ' + ownerColor,
            borderRadius: 14, padding: '4px 10px',
            fontWeight: 800, fontSize: 13, color: 'var(--text-on-light-pastel)'
          }}>
              <window.HexFrame size={18} color={ownerColor} borderColor="var(--border-emphasis)" borderWidth={1.5} />
              {ownerName}
            </div>
            <window.CozyButton color="amber" small onClick={(e) => {
              e.stopPropagation();
              onClaim();
            }}>
              Reclaim lane 🔄
            </window.CozyButton>
          </>
        }

        {state === 'stale' &&
        <>
            <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: ownerColor + '50',
            border: '1.5px solid ' + ownerColor,
            borderRadius: 14, padding: '4px 10px',
            fontWeight: 800, fontSize: 13, color: 'var(--text-on-light-pastel)'
          }}>
              <window.HexFrame size={18} color={ownerColor} borderColor="var(--border-emphasis)" borderWidth={1.5} />
              {ownerName}
            </div>
            <window.CozyButton color="amber" small onClick={(e) => {
              e.stopPropagation();
              onClaim();
            }}>
              Reclaim lane 🔄
            </window.CozyButton>
          </>
        }
      </div>
    </div>);

}

function LaneClaimScreen({ onDone, onBackToLobby, onCreateNewLobby }) {
  const {
    players, myUserId, claimLane, releaseLane, updatePlayerIdentity,
    setMyUser, lobbyCode, sessionUserId, setOnboarded, setLobbyCode, resetLobby, leaveLobby,
    claimSubstitute, tempIdentity, userProfile
  } = window.useApp();
  const me = players.find((p) => p.ownerId && p.ownerId === sessionUserId) || players.find((p) => p.id === myUserId) || players[0];

  const myClaim = players.find((p) => p.ownerId === sessionUserId);
  const mySessionName = (tempIdentity && tempIdentity.displayName) || userProfile?.displayName || myClaim?.name || (me.ownerId ? me.name : null) || 'You';

  const [reclaimTarget, setReclaimTarget] = useState(null);
  const [confirmTapCount, setConfirmTapCount] = useState(0);

  const handleRequestReclaim = (player) => {
    setReclaimTarget(player);
    setConfirmTapCount(0);
  };

  const COLOR_EMOJIS = {
    '#F2A7C3': '🌸', // rose
    '#F7DFA0': '🍯', // honey/yellow
    '#B8E0C0': '🌿', // sage/green
    '#AED6F1': '💧', // sky/blue
    '#C5B4E3': '🔮', // lilac/purple
    '#F2C795': '🍑', // peach/orange
    '#E8A0A0': '🍎', // coral/red
    '#A8D8C9': '🍃', // mint/teal
  };

  // Move "me" to a new lane: transfer name+colour, release old slot, claim new.
  const moveTo = (targetPlayer, force = false) => {
    const mySlot = players.find((p) => p.ownerId && p.ownerId === sessionUserId);
    const myName = (tempIdentity && tempIdentity.displayName) || mySlot?.name || me.name;
    const myColor = (tempIdentity && tempIdentity.displayColor) || mySlot?.identityColor || me.identityColor;
    if (mySlot && mySlot.id === targetPlayer.id) {
      updatePlayerIdentity(targetPlayer.id, { name: myName, identityColor: myColor });
      claimLane(targetPlayer.id, sessionUserId, true);
      return;
    }
    // Save my identity, move to new slot, mark new claimed, old unclaimed.
    if (mySlot && mySlot.id !== targetPlayer.id) releaseLane(mySlot.id);
    // Write identity onto target slot, mark claimed, move myUserId
    updatePlayerIdentity(targetPlayer.id, { name: myName, identityColor: myColor });
    claimLane(targetPlayer.id, sessionUserId, force || true);
    setMyUser(targetPlayer.id);
  };

  return (
    <div style={{
      minHeight: '100vh', padding: 24, position: 'relative',
      display: 'flex', flexDirection: 'column', alignItems: 'center'
    }}>
      <CozyRiftBackdrop variant="claim" />

      <div style={{ position: 'relative', width: '100%', maxWidth: 1240 }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginBottom: 18, gap: 12, flexWrap: 'wrap'
        }}>
          <div>
            <h1 className="fredoka" style={{ color: 'var(--accent-orange)', fontSize: 28, margin: 0, display: 'flex', alignItems: 'center', gap: 10 }}>
              <window.PawMascot size={36} /> Lock in your lane
            </h1>
            <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700, marginTop: 2 }}>
              Once everyone picks a lane, you'll start cooking up champion pools together! 🍲
            </div>
          </div>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            background: 'var(--surface-card)', border: '2px solid var(--border-emphasis)',
            borderRadius: 16, padding: '6px 14px',
            fontFamily: 'Nunito', fontWeight: 800, fontSize: 13, color: 'var(--text-primary)',
            boxShadow: '0 3px 0 var(--border-default)'
          }}>
            <window.HexFrame size={22} color="#F7DFA0" borderColor="var(--border-emphasis)" borderWidth={1.5} />
            LOBBY: <span style={{ fontFamily: 'Fredoka One, cursive', color: 'var(--accent-orange)', fontSize: 16, letterSpacing: 1 }}>{lobbyCode}</span>
          </div>
        </div>

        {/* Lane cards */}
        <div className="lane-grid" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(5, 1fr)',
          gap: 16
        }}>
          {players.filter(p => !p.isSub).map((p) => {
            const authUser = window.firebase && window.firebase.auth && window.firebase.auth().currentUser;
            const authUid = authUser ? authUser.uid : null;
            const isMine = !!(p && (p.claimed || p.ownerId || p.uid) && (
              (authUid && (p.uid === authUid || p.ownerId === authUid)) ||
              (!authUid && sessionUserId && p.ownerId === sessionUserId)
            ));
            const isClaimed = (p.claimed || !!p.ownerId || !!p.uid) && !isMine;
            let state = 'open';
            let ownerName = '';
            let ownerColor = '#F7DFA0';
            if (isMine) {
              state = 'mine';
              ownerName = p.name;
              ownerColor = p.identityColor;
            } else if (isClaimed) {
              state = p.online ? 'locked' : 'stale';
              ownerName = p.name;
              ownerColor = p.identityColor;
            }
            return (
              <LaneCard
                key={p.id}
                player={p}
                state={state}
                ownerName={ownerName}
                ownerColor={ownerColor}
                onClaim={() => {
                  if (isClaimed) {
                    handleRequestReclaim(p);
                  } else {
                    moveTo(p);
                  }
                }}
                onRelease={() => releaseLane(p.id)} />);
          })}
        </div>

        <SubstituteCard
          me={me}
          tempIdentity={tempIdentity}
          updatePlayerIdentity={updatePlayerIdentity}
          claimSubstitute={claimSubstitute}
          setOnboarded={setOnboarded}
          onDone={onDone}
        />

        {/* Footer */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: 24, gap: 12 }}>
          <window.CozyButton color="terracotta" disabled={!myClaim} onClick={onDone}
          style={{ fontSize: 16, padding: '12px 32px' }}>
            Head to the lobby 🍲
          </window.CozyButton>
        </div>
      </div>

      {/* Reclaim confirmation modal */}
      {reclaimTarget && (
        <div
          onMouseDown={e => { if (e.target === e.currentTarget) { setReclaimTarget(null); setConfirmTapCount(0); } }}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(0, 0, 0, 0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 16,
          }}
        >
          <div className="cozy-card pop-in" style={{
            width: '100%', maxWidth: 440, padding: 24,
            display: 'flex', flexDirection: 'column', gap: 14,
            textAlign: 'center', background: 'var(--surface-card)', borderRadius: 20,
            position: 'relative'
          }}>
            <div className="corner-dot" style={{ top: 9, left: 9 }} />
            <div className="corner-dot" style={{ top: 9, right: 9 }} />
            <div className="corner-dot corner-dot-bl" />
            <div className="corner-dot corner-dot-br" />

            <div style={{ marginTop: 4 }}>
              <h2 className="fredoka" style={{ color: reclaimTarget.online ? '#D9534F' : 'var(--accent-orange)', fontSize: 22, margin: 0 }}>
                {reclaimTarget.online ? 'Take Over Active Lane ⚠️' : 'Reclaim Lane 🔄'}
              </h2>
              <p style={{ color: 'var(--text-primary)', fontWeight: 700, fontSize: 14, marginTop: 12, lineHeight: 1.5 }}>
                {reclaimTarget.online
                  ? `${reclaimTarget.name} is currently active in this lane. Are you sure you want to take over? This may disrupt them.`
                  : `${reclaimTarget.name} hasn't been active. Claim this lane as ${mySessionName}?`}
              </p>
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 10 }}>
              <window.CozyButton color="cream" onClick={() => { setReclaimTarget(null); setConfirmTapCount(0); }}>
                Cancel 👋
              </window.CozyButton>

              {!reclaimTarget.online ? (
                <window.CozyButton color="sage" onClick={() => {
                  moveTo(reclaimTarget, true);
                  setReclaimTarget(null);
                  setConfirmTapCount(0);
                }}>
                  Claim lane 🛡️
                </window.CozyButton>
              ) : (
                <window.CozyButton
                  color={confirmTapCount === 1 ? "terracotta" : "cream"}
                  style={confirmTapCount === 1 ? { background: '#E85555', color: '#FFF', fontWeight: 900 } : {}}
                  onClick={() => {
                    if (confirmTapCount === 0) {
                      setConfirmTapCount(1);
                    } else {
                      moveTo(reclaimTarget, true);
                      setReclaimTarget(null);
                      setConfirmTapCount(0);
                    }
                  }}>
                  {confirmTapCount === 1 ? "Tap again to confirm ⚠️" : "Confirm Takeover ⚠️"}
                </window.CozyButton>
              )}
            </div>
          </div>
        </div>
      )}

      <style>{`
        .lane-card:hover { transform: translateY(-4px); }
        @media (max-width: 1400px) and (min-width: 901px) {
          .lane-grid { grid-template-columns: repeat(3, 1fr) !important; }
        }
        @media (max-width: 900px) {
          .lane-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>);

}

// -----------------------------------------------------------------------------
// SubstituteCard — bordered card matching reference design
// -----------------------------------------------------------------------------
function SubstituteCard({ me, tempIdentity, updatePlayerIdentity, claimSubstitute, setOnboarded, onDone }) {
  const POSITIONS = ['TOP', 'JUNGLE', 'MID', 'ADC', 'SUPPORT'];
  const POSITION_LABELS = window.POSITION_LABELS;
  const POSITION_COLORS = window.POSITION_COLORS;

  const [selectedRoles, setSelectedRoles] = useState([]);

  const toggleRole = (pos) => {
    setSelectedRoles(prev =>
      prev.includes(pos) ? prev.filter(r => r !== pos) : [...prev, pos]
    );
  };

  const handleBecomeSub = () => {
    const myName = (tempIdentity && tempIdentity.displayName) || me.name;
    const myColor = (tempIdentity && tempIdentity.displayColor) || me.identityColor;
    updatePlayerIdentity(me.id, { name: myName, identityColor: myColor });
    claimSubstitute(me.id, selectedRoles);
    setOnboarded(true);
    onDone();
  };

  return (
    <div className="cozy-card sub-card" style={{
      width: '100%',
      padding: '16px 20px',
      marginTop: 20,
      background: 'var(--surface-card)',
      position: 'relative',
      borderRadius: 20
    }}>
      {/* corner dots */}
      <div className="corner-dot" style={{ top: 9, left: 9 }} />
      <div className="corner-dot" style={{ top: 9, right: 9 }} />
      <div className="corner-dot corner-dot-bl" />
      <div className="corner-dot corner-dot-br" />

      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 16,
        flexWrap: 'wrap'
      }}>
        {/* Hex Frame icon */}
        <div style={{ flexShrink: 0 }}>
          <window.HexFrame size={54} color="#F7DFA0" borderColor="var(--border-emphasis)" borderWidth={2.5}>
            <span style={{ fontSize: 24 }}>🪑</span>
          </window.HexFrame>
        </div>

        {/* Text & Chips */}
        <div style={{ flex: 1, minWidth: 280, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div>
            <h3 className="fredoka" style={{ color: 'var(--text-primary)', fontSize: 18, margin: 0, lineHeight: 1.2 }}>
              Not playing a fixed lane? Join as a Substitute
            </h3>
            <div style={{ color: 'var(--text-muted)', fontSize: 13, fontWeight: 700, marginTop: 2 }}>
              Subs get their own champion pool and flag which lanes they can fill in for.
            </div>
          </div>

          {/* Role preference chips */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 4 }}>
            {POSITIONS.map(pos => {
              const active = selectedRoles.includes(pos);
              const chipBg = active ? (POSITION_COLORS[pos] || '#F7DFA0') : 'var(--surface-nested)';
              return (
                <button
                  key={pos}
                  type="button"
                  onClick={() => toggleRole(pos)}
                  className="cozy-btn"
                  style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '4px 12px',
                    background: chipBg,
                    border: active ? '2px solid var(--border-emphasis)' : '1.5px solid var(--border-default)',
                    borderRadius: 14,
                    fontFamily: 'Nunito', fontWeight: active ? 800 : 700, fontSize: 12,
                    color: active ? 'var(--text-on-light)' : 'var(--text-muted)',
                    boxShadow: active ? '0 2px 0 var(--border-default)' : 'none',
                    cursor: 'pointer',
                    transition: 'all 0.15s cubic-bezier(0.34, 1.56, 0.64, 1)'
                  }}
                >
                  <window.RoleIcon pos={pos} size={14} />
                  <span>{POSITION_LABELS[pos]}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Action Button */}
        <div className="sub-action-btn-wrap" style={{ flexShrink: 0 }}>
          <window.CozyButton color="lavender" onClick={handleBecomeSub} style={{ padding: '10px 20px', fontSize: 14 }}>
            Become a substitute 🪑
          </window.CozyButton>
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          .sub-card > div {
            flex-direction: column !important;
            align-items: stretch !important;
          }
          .sub-action-btn-wrap {
            width: 100% !important;
            margin-top: 8px;
          }
          .sub-action-btn-wrap button {
            width: 100% !important;
            justify-content: center !important;
          }
        }
      `}</style>
    </div>
  );
}

// -----------------------------------------------------------------------------
// OnboardingFlow — wraps the screens with state
// -----------------------------------------------------------------------------
function OnboardingFlow({ onComplete }) {
  const handleAuthComplete = () => {
    if (typeof onComplete === 'function') {
      onComplete();
    }
  };

  return (
    <div data-screen-label="Onboarding" style={{ position: 'relative', minHeight: '100vh' }}>
      <WelcomeScreen onContinue={handleAuthComplete} />
    </div>
  );
}

Object.assign(window, { OnboardingFlow, WelcomeScreen, ProfileSetupScreen, SignInScreen, SignUpScreen, SignUpFlowScreen, AuthFlowScreen, LaneClaimScreen, SubstituteCard, createAccountWithUsername, signInWithUsernameOrEmail });