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

// ── Smoke / Gandalf wrapper ──────────────────────────
function GandalfDisplay({ variant = 'normal', state = 'entering', onLeaveDone }) {
  // state: 'entering' | 'idle' | 'angry' | 'leaving'
  const [smokeOn, setSmokeOn] = useState(state === 'entering');

  useEffect(() => {
    if (state === 'entering') {
      setSmokeOn(true);
      const t = setTimeout(() => setSmokeOn(false), 1200);
      return () => clearTimeout(t);
    }
    if (state === 'leaving') {
      setSmokeOn(true);
      const t = setTimeout(() => {
        setSmokeOn(false);
        onLeaveDone && onLeaveDone();
      }, 900);
      return () => clearTimeout(t);
    }
  }, [state, onLeaveDone]);

  const cls =
    'gandalf' +
    (state === 'entering' ? ' entering' : '') +
    (state === 'angry' ? ' angry' : '') +
    (state === 'leaving' ? ' leaving' : '');

  return (
    <div className="gandalf-stage">
      <div
        className={cls}
        dangerouslySetInnerHTML={{ __html: window.GandalfSVG(variant === 'cool' ? 'cool' : (state === 'angry' ? 'angry' : 'normal')) }}
      />
      <div className={'smoke' + (smokeOn ? ' burst' : '')}>
        <span className="puff" />
        <span className="puff" />
        <span className="puff" />
        <span className="puff" />
        <span className="puff" />
        <span className="puff" />
      </div>
    </div>
  );
}

// ── Password Gate ────────────────────────────────────
// Small helper: play the 'entering' pose (rise + smoke) for the first 1.4s of a screen.
function useEntrance() {
  const [entered, setEntered] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setEntered(true), 1400);
    return () => clearTimeout(t);
  }, []);
  return entered;
}

function PasswordGate({ onPass }) {
  const entered = useEntrance();
  const [val, setVal] = useState('');
  const [shake, setShake] = useState(false);
  const [angry, setAngry] = useState(false);
  const [showShallNot, setShowShallNot] = useState(false);
  const [leaving, setLeaving] = useState(false);
  const [success, setSuccess] = useState(false);
  const [checking, setChecking] = useState(false);
  const [netError, setNetError] = useState(null);

  async function submit(e) {
    e.preventDefault();
    if (checking || success) return;
    setNetError(null);
    setChecking(true);
    let ok;
    try {
      ok = await window.PartyState.checkPassword(val);
    } catch (err) {
      setChecking(false);
      setNetError(err.message);
      return;
    }
    setChecking(false);
    if (ok) {
      setSuccess(true);
      setTimeout(() => setLeaving(true), 2200);
    } else {
      setAngry(true);
      setShowShallNot(true);
      setShake(true);
      setTimeout(() => {
        setShake(false);
        setAngry(false);
        setVal('');
        setTimeout(() => setShowShallNot(false), 600);
      }, 1200);
    }
  }

  return (
    <div className="screen">
      <GandalfDisplay
        variant="normal"
        state={leaving ? 'leaving' : (angry ? 'angry' : (entered ? 'idle' : 'entering'))}
        onLeaveDone={() => onPass(val)}
      />
      {showShallNot && (
        <div className="speech speech--shout">YOU SHALL NOT PASS</div>
      )}
      {success && !leaving && (
        <div className="speech">"Welcome, traveller. The path is open."</div>
      )}
      {!showShallNot && !success && (
        <div className="speech">{netError ? `"${netError}"` : '"Speak, friend, and enter…"'}</div>
      )}
      <form onSubmit={submit} style={{display:'flex',flexDirection:'column',gap:14,alignItems:'center',width:'100%'}}>
        <input
          className={'input' + (shake ? ' shake' : '')}
          type="password"
          value={val}
          onChange={(e) => setVal(e.target.value)}
          placeholder="enter the password"
          autoFocus
          disabled={success}
          aria-label="Password"
        />
        <button type="submit" className="btn btn--primary" disabled={success || checking}>
          {checking ? 'Consulting the wizard…' : 'Speak the words'}
        </button>
      </form>
      <div className="footnote">A password is required. The host has shared it.</div>
    </div>
  );
}

// ── Email Login ──────────────────────────────────────
function EmailLogin({ onSubmit }) {
  const entered = useEntrance();
  const [val, setVal] = useState('');
  const [leaving, setLeaving] = useState(false);
  const [emailToSend, setEmailToSend] = useState(null);

  function submit(e) {
    e.preventDefault();
    const v = val.trim();
    if (!/^\S+@\S+\.\S+$/.test(v)) return;
    setEmailToSend(v);
    setLeaving(true);
  }

  return (
    <div className="screen">
      <GandalfDisplay
        variant="cool"
        state={leaving ? 'leaving' : (entered ? 'idle' : 'entering')}
        onLeaveDone={() => onSubmit(emailToSend)}
      />
      <div className="speech">"I am the cool one. Just enter your email to start, or continue where you left off."</div>
      <form onSubmit={submit} style={{display:'flex',flexDirection:'column',gap:14,alignItems:'center',width:'100%'}}>
        <input
          className="input"
          type="email"
          value={val}
          onChange={(e) => setVal(e.target.value)}
          placeholder="your.email@example.com"
          autoFocus
          disabled={leaving}
          aria-label="Email"
        />
        <button type="submit" className="btn btn--primary" disabled={leaving}>Begin the journey</button>
      </form>
    </div>
  );
}

// ── Cinematic Intro ──────────────────────────────────
function CinematicIntro({ onDone }) {
  // Lines appear with timed delays, then "lights up" and reveals welcome.
  const lines = [
    'For when you cross that door,',
    'you are no longer you,',
    'and I am no longer me.',
  ];

  const [shown, setShown] = useState([]);
  const [done, setDone] = useState(false);

  useEffect(() => {
    const timers = [];
    // 0.6s, 2.6s, 4.6s
    lines.forEach((_, i) => {
      timers.push(setTimeout(() => {
        setShown((prev) => [...prev, i]);
      }, 600 + i * 2000));
    });
    // hold on the final line, then done
    timers.push(setTimeout(() => setDone(true), 600 + lines.length * 2000 + 2600));
    return () => timers.forEach(clearTimeout);
  }, []);

  function skip() {
    setDone(true);
  }

  if (done) {
    setTimeout(onDone, 0);
    return null;
  }

  return (
    <div className="cinematic" onClick={skip}>
      {lines.map((l, i) => (
        <div key={i} className={'cine-line' + (shown.includes(i) ? ' show' : '')}>{l}</div>
      ))}
      <div style={{position:'absolute', bottom:24, fontFamily:"'IM Fell English', serif", color:'rgba(255,245,220,0.3)', fontSize:13, fontStyle:'italic'}}>
        tap to skip
      </div>
    </div>
  );
}

window.PartyComponents = window.PartyComponents || {};
Object.assign(window.PartyComponents, { GandalfDisplay, PasswordGate, EmailLogin, CinematicIntro });
