/* eslint-disable */
const { useState, useEffect } = React;

function PartyApp() {
  const [data, setData] = useState(null); // {characters, quirks}
  const [dataError, setDataError] = useState(null);

  // flow stages: passwordGate -> emailLogin -> [cinematic if first] -> character | quirk | reveal
  const [stage, setStage] = useState('passwordGate');
  const [passed, setPassed] = useState(false);
  const [password, setPassword] = useState('');
  const [user, setUser] = useState(null);
  const [locking, setLocking] = useState(false);
  const [loginAttempt, setLoginAttempt] = useState(0);
  const [showLightsUp, setShowLightsUp] = useState(false);

  const [partyInfoOpen, setPartyInfoOpen] = useState(false);
  const [howToOpen, setHowToOpen] = useState(false);
  const [errorToast, setErrorToast] = useState(null);

  // Load data once
  useEffect(() => {
    window.loadPartyData()
      .then(setData)
      .catch(e => setDataError(e.message));
  }, []);

  function showToast(msg) {
    setErrorToast(msg);
    setTimeout(() => setErrorToast(null), 4000);
  }

  function handlePasswordPass(pw) {
    setPassword(pw);
    setPassed(true);
    setStage('emailLogin');
  }

  async function handleEmailSubmit(email) {
    let u;
    try {
      u = await window.PartyState.login(password, email);
    } catch (err) {
      showToast(err.message);
      // bounce back to a fresh email screen
      setLoginAttempt(a => a + 1);
      setStage('emailLogin');
      return;
    }
    setUser(u);

    // Routing for returning users
    if (u.lockedCharacter && u.lockedQuirk) {
      setStage('reveal');
    } else if (u.lockedCharacter && !u.lockedQuirk) {
      setStage('quirk');
    } else if (!u.hasSeenIntro) {
      setStage('cinematic');
    } else {
      setStage('character');
    }
  }

  function finishCinematic() {
    if (user) {
      setUser({ ...user, hasSeenIntro: true });
      window.PartyState.updateUser(user.email, { hasSeenIntro: true }).catch(() => {});
    }
    setShowLightsUp(true);
    setStage('character');
    setTimeout(() => setShowLightsUp(false), 1500);
  }

  // Rerolls update optimistically; the server patch is fire-and-forget
  // (index position is cosmetic — locks are what's permanent).
  function rerollCharacter() {
    if (!user) return;
    const next = (user.currentCharacterIndex + 1) % user.characterPool.length;
    setUser({ ...user, currentCharacterIndex: next });
    window.PartyState.updateUser(user.email, { currentCharacterIndex: next }).catch(() => {});
  }
  function rerollQuirk() {
    if (!user) return;
    const next = (user.currentQuirkIndex + 1) % user.quirkPool.length;
    setUser({ ...user, currentQuirkIndex: next });
    window.PartyState.updateUser(user.email, { currentQuirkIndex: next }).catch(() => {});
  }
  async function lockCharacter() {
    if (!user || locking) return;
    setLocking(true);
    try {
      const ch = user.characterPool[user.currentCharacterIndex];
      const u = await window.PartyState.updateUser(user.email, { lockedCharacter: ch });
      setUser(u);
      setStage('quirk');
    } catch (err) {
      showToast(err.message);
    }
    setLocking(false);
  }
  async function lockQuirk() {
    if (!user || locking) return;
    setLocking(true);
    try {
      const q = user.quirkPool[user.currentQuirkIndex];
      const u = await window.PartyState.updateUser(user.email, { lockedQuirk: q });
      setUser(u);
      setStage('reveal');
    } catch (err) {
      showToast(err.message);
    }
    setLocking(false);
  }

  // ── Render ────────────────────────────────────
  if (dataError) {
    return (
      <div className="screen">
        <h1 className="h-rpg" style={{fontSize:32}}>The scrolls are missing.</h1>
        <div className="speech">{dataError}</div>
      </div>
    );
  }
  if (!data) {
    return (
      <div className="screen">
        <div className="counter">LOADING THE GRIMOIRE...</div>
      </div>
    );
  }

  const C = window.PartyComponents;

  return (
    <>
      {showLightsUp && <div className="lights-up" style={{position:'fixed', inset:0, background:'#000', zIndex:40, pointerEvents:'none'}} />}

      {stage === 'passwordGate' && <C.PasswordGate onPass={handlePasswordPass} />}

      {stage === 'emailLogin' && passed && <C.EmailLogin key={loginAttempt} onSubmit={handleEmailSubmit} />}

      {stage === 'cinematic' && <C.CinematicIntro onDone={finishCinematic} />}

      {stage === 'character' && user && (
        <>
          <div className="screen" style={{maxWidth:640, marginBottom:8}}>
            <h1 className="h-rpg" style={{fontSize:'clamp(26px,4.5vw,38px)'}}>Welcome to this 'Party Quirks' themed birthday party</h1>
            <div className="body-text" style={{maxWidth:560}}>
              You will choose your <b>character</b>, then choose your <b>quirk</b>.
              Once chosen, there is no going back.
            </div>
          </div>
          <C.SelectionCard
            kind="character"
            item={user.characterPool[user.currentCharacterIndex]}
            idx={user.currentCharacterIndex}
            total={user.characterPool.length}
            onReroll={rerollCharacter}
            onLock={lockCharacter}
            onOpenPartyInfo={() => setPartyInfoOpen(true)}
            onOpenHowTo={() => setHowToOpen(true)}
          />
        </>
      )}

      {stage === 'quirk' && user && (
        <>
          <div className="screen" style={{maxWidth:640, marginBottom:8}}>
            <div className="counter" style={{color:'#7fb069'}}>CHARACTER LOCKED — {user.lockedCharacter.name}</div>
            <h1 className="h-rpg" style={{fontSize:'clamp(24px,4vw,34px)'}}>Now, your quirk awaits.</h1>
          </div>
          <C.SelectionCard
            kind="quirk"
            item={user.quirkPool[user.currentQuirkIndex]}
            idx={user.currentQuirkIndex}
            total={user.quirkPool.length}
            onReroll={rerollQuirk}
            onLock={lockQuirk}
            onOpenPartyInfo={() => setPartyInfoOpen(true)}
            onOpenHowTo={() => setHowToOpen(true)}
          />
        </>
      )}

      {stage === 'reveal' && user && user.lockedCharacter && user.lockedQuirk && (
        <C.RevealScreen
          character={user.lockedCharacter}
          quirk={user.lockedQuirk}
          onOpenPartyInfo={() => setPartyInfoOpen(true)}
          onOpenHowTo={() => setHowToOpen(true)}
        />
      )}

      {partyInfoOpen && <C.PartyInfoModal onClose={() => setPartyInfoOpen(false)} />}
      {howToOpen && <C.HowToPlayModal onClose={() => setHowToOpen(false)} />}

      {errorToast && <div className="toast show">{errorToast}</div>}
    </>
  );
}

window.PartyApp = PartyApp;
