// Stage 1 (sign-in) + Stage 2 (loading) intro flow.
// All marks/wordmarks are original — not a recreation of any company's brand.

const SignInScreen = ({ onDone, onSkip }) => {
  const [exiting, setExiting] = React.useState(false);
  const [userText, setUserText] = React.useState("");
  const [passText, setPassText] = React.useState("");
  const [rememberOn, setRememberOn] = React.useState(false);
  const tRef = React.useRef([]);

  React.useEffect(() => {
    const typeText = (text, setter, startDelay, speed, done) => {
      let index = 0;

      const tick = () => {
        index += 1;
        setter(text.slice(0, index));

        if (index < text.length) {
          tRef.current.push(setTimeout(tick, speed));
        } else if (done) {
          done();
        }
      };

      tRef.current.push(setTimeout(tick, startDelay));
    };

    typeText("ConnorTan", setUserText, 500, 120, () => {
      typeText("password123", setPassText, 250, 95, () => {
        tRef.current.push(setTimeout(() => setRememberOn(true), 250));
      });
    });
    tRef.current.push(setTimeout(() => setExiting(true), 3600));
    tRef.current.push(setTimeout(() => onDone(), 4200));

    return () => tRef.current.forEach((timer) => clearTimeout(timer));
  }, []);

  return (
    <div className={`signin ${exiting ? "exit" : ""}`} aria-hidden={exiting}>
      <SplashArt
        userText={userText}
        passText={passText}
        rememberOn={rememberOn}
        onUserChange={setUserText}
        onPassChange={setPassText}
      />
    </div>
  );
};

const LoadingScreen = ({ onDone, onSkip, onExitStart }) => {
  const [progress, setProgress] = React.useState(0);
  const [statusIdx, setStatusIdx] = React.useState(0);
  const [exiting, setExiting] = React.useState(false);
  const tRef = React.useRef([]);
  const STATUSES = ["Authenticating…", "Loading assets…", "Preparing client…", "Almost there…"];

  React.useEffect(() => {
    const t = (ms, fn) => tRef.current.push(setTimeout(fn, ms));

    // bar fills over 4400ms with eased ramp, starting from 0%
    const start = performance.now();
    const dur = 4400;
    let raf;
    const tick = (now) => {
      const k = Math.min(1, (now - start) / dur);
      // Smooth easing that starts at 0% and reaches 100% at k=1
      const eased = k * k * (3 - 2 * k);
      setProgress(eased);
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    tRef.current.push(() => cancelAnimationFrame(raf));

    // status text cycle
    t(1000,  () => setStatusIdx(1));
    t(2000, () => setStatusIdx(2));
    t(3000, () => setStatusIdx(3));

    // exit — onExitStart fires the moment fade-out begins so the
    // portfolio underneath can crossfade in over the same 500ms.
    t(4500, () => { setExiting(true); if (onExitStart) onExitStart(); });
    t(5100, () => onDone());

    return () => tRef.current.forEach((x) => typeof x === "function" ? x() : clearTimeout(x));
  }, []);

  const handleSkip = () => {
    tRef.current.forEach((x) => typeof x === "function" ? x() : clearTimeout(x));
    onSkip();
  };

  return (
    <div className={`loadscr ${exiting ? "exit" : ""}`} aria-hidden={exiting}>
      <div className="ls-glow"></div>
      <div className="ls-particles">
        {Array.from({ length: 6 }).map((_, i) => (
          <span key={i} className="particle" style={{
            left:  `${45 + Math.cos(i / 6 * Math.PI * 2) * 18}%`,
            top:   `${42 + Math.sin(i / 6 * Math.PI * 2) * 14}%`,
            animationDuration: `${3 + Math.random() * 2}s`,
            animationDelay: `${i * 0.4}s`,
          }}/>
        ))}
      </div>
      <div className="ls-stack">
        <div className={`ls-crest ${exiting ? "out" : ""}`}>
          <img src={LOL.logo} alt="League of Legends" className="ls-logo-img" draggable="false" />
        </div>
        <div className="ls-bar">
          <div className="ls-fill" style={{ width: `${progress * 100}%` }}>
            <div className="ls-shimmer"></div>
          </div>
        </div>
        <div className="ls-status">
          {STATUSES[statusIdx]}
        </div>
      </div>
      <button className="skip-btn dark" onClick={handleSkip}>SKIP INTRO →</button>
    </div>
  );
};

// SplashArt: use an image asset so the UI can match the provided screenshot
// exactly when you place the original image at `public/assets/riotgameslogin.png`.
const SplashArt = ({ userText, passText, rememberOn, onUserChange, onPassChange }) => (
  <div className="splash-art">
    <img src="/assets/riotgameslogin.png" alt="splash" className="splash-art-img"/>
    <div className="splash-overlay">
      <input
        className="overlay-user-field"
        type="text"
        value={userText}
        onChange={(event) => onUserChange(event.target.value)}
        placeholder="USERNAME"
        autoComplete="username"
        spellCheck="false"
        autoCapitalize="off"
        autoCorrect="off"
        aria-label="Username"
      />
      <input
        className="overlay-pass"
        type="password"
        value={passText}
        onChange={(event) => onPassChange(event.target.value)}
        placeholder="PASSWORD"
        autoComplete="current-password"
        spellCheck="false"
        autoCapitalize="off"
        autoCorrect="off"
        aria-label="Password"
      />
      <div className={`overlay-remember ${rememberOn ? "on" : ""}`}>
        <span className="overlay-box"></span>
        <span className="overlay-check">✓</span>
      </div>
      <div className="overlay-captcha-blocker" aria-hidden="true">
        This website isn't affiliated with Riot Games.
      </div>
    </div>
  </div>
);

window.SignInScreen = SignInScreen;
window.LoadingScreen = LoadingScreen;
