/* global React, RC */
// Login — Editorial Motorsport cover.
// One column, full-bleed, sweeping serif type, single underline input.
// Reads like the inside front of a magazine: masthead at the top, the
// hero "feature" with a giant headline, single form below, footer at
// the foot. Same aesthetic as the public viewer.

const { useState: useSL, useRef: useRL, useEffect: useEL } = React;

function LiveLogin({ onLogin, toast }) {
  const [email, setEmail] = useSL('admin@racecast.local');
  const [pw, setPw] = useSL('');
  const [loading, setLoading] = useSL(false);
  const [showPw, setShowPw] = useSL(false);
  const [shake, setShake] = useSL(false);
  const cardRef = useRL(null);

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!email || !pw) {
      toast?.('E-Mail und Passwort erforderlich', 'error');
      return triggerShake();
    }
    setLoading(true);
    try {
      const res = await RC.login(email.trim(), pw);
      await onLogin?.(res.token, res.user);
    } catch (err) {
      const msg = err.message === 'invalid credentials' ? 'Ungültige Zugangsdaten' : err.message;
      toast?.(msg, 'error');
      triggerShake();
    } finally {
      setLoading(false);
    }
  };
  const triggerShake = () => {
    setShake(true);
    setTimeout(() => setShake(false), 500);
  };

  return (
    <div className="ed-root" style={{ minHeight: '100%', position: 'relative' }}>
      <div className="ed-grain" aria-hidden="true" />
      <div className="ed-vignette" aria-hidden="true" />

      <div className="ed-page">
        <div className="ed-shell">

          {/* Masthead */}
          <header className="ed-masthead" style={{ padding: '28px 0 18px' }}>
            <div className="ed-masthead__logo">
              <span style={{ fontStyle: 'italic' }}>RaceCast</span>
              <span style={{
                fontFamily: 'var(--ed-body)', fontStyle: 'italic',
                fontSize: 12, letterSpacing: '0.2em', textTransform: 'uppercase',
                color: 'var(--ed-cream-faint)', marginLeft: 10,
              }}>
                Editoriale
              </span>
            </div>
            <div className="ed-masthead__center">
              No. 01 · The Onboard Issue
            </div>
            <div className="ed-masthead__right">
              <span className="ed-strip" style={{ color: 'var(--ed-cream-faint)' }}>
                paddock access
              </span>
            </div>
          </header>
          <hr className="ed-hr ed-hr--strong" />
          <hr className="ed-hr" style={{ marginTop: 4 }} />

          {/* Hero */}
          <main style={{
            flex: 1, display: 'grid',
            gridTemplateColumns: 'minmax(0, 1.3fr) minmax(0, 0.9fr)',
            gap: 64, padding: '64px 0', alignItems: 'center',
          }} className="ed-login-grid">

            <section style={{ position: 'relative' }}>
              <div className="ed-card__lead" style={{ marginBottom: 22 }}>
                A racing dispatch
              </div>
              <h1 style={{
                fontFamily: 'var(--ed-serif)',
                fontVariationSettings: "'opsz' 144, 'SOFT' 50, 'WONK' 0",
                fontWeight: 320,
                fontSize: 'clamp(56px, 9vw, 132px)',
                lineHeight: 0.86, letterSpacing: '-0.03em',
                margin: 0, color: 'var(--ed-cream)',
              }}>
                See the race
                <br />
                <em style={{
                  fontStyle: 'italic', fontWeight: 300,
                  fontVariationSettings: "'opsz' 144, 'SOFT' 100, 'WONK' 1",
                  color: 'var(--ed-ferrari)',
                }}>from inside</em>
                <span style={{
                  display: 'inline-block', width: '0.18em', height: '0.18em',
                  background: 'var(--ed-ferrari)', borderRadius: '50%',
                  marginLeft: '0.18em', marginBottom: '0.06em',
                  transform: 'translateY(-0.4em)',
                }} />
              </h1>
              <p style={{
                fontFamily: 'var(--ed-body)', fontSize: 17, lineHeight: 1.55,
                color: 'var(--ed-cream-dim)', marginTop: 32, maxWidth: 460,
              }}>
                Onboard streams in broadcast quality, telemetry from the cockpit, and a paddock-grade control room — assembled by the engineers who run the team, not the marketing department.
              </p>

              {/* Tagline strip */}
              <div style={{ display: 'flex', gap: 32, marginTop: 56, flexWrap: 'wrap' }}>
                <FactCell label="Codec" value="H.265" />
                <FactCell label="Transport" value="SRT · RTMP" />
                <FactCell label="Latency" value="~ 320 ms" />
                <FactCell label="Format" value="LL-HLS · WHEP" />
              </div>
            </section>

            {/* Form */}
            <section ref={cardRef} style={{
              borderTop: '1px solid var(--ed-rule-strong)',
              borderBottom: '1px solid var(--ed-rule-strong)',
              padding: '40px 0',
              animation: shake ? 'ed-shake 0.45s cubic-bezier(0.36, 0.07, 0.19, 0.97) both' : 'none',
            }}>
              <form onSubmit={submit}>
                <div className="ed-card__lead">Sign in</div>
                <h2 style={{
                  fontFamily: 'var(--ed-serif)',
                  fontVariationSettings: "'opsz' 64, 'SOFT' 30",
                  fontWeight: 320, fontSize: 36, lineHeight: 1.05,
                  letterSpacing: '-0.015em', margin: '0 0 32px',
                  color: 'var(--ed-cream)',
                }}>
                  Enter the <em style={{ fontStyle: 'italic',
                    fontVariationSettings: "'opsz' 64, 'SOFT' 100, 'WONK' 1" }}>paddock</em>.
                </h2>

                <label style={{ display: 'block', marginBottom: 22 }}>
                  <span className="ed-label" style={{ display: 'block', marginBottom: 6 }}>E-mail</span>
                  <input className="ed-input" value={email} onChange={(e) => setEmail(e.target.value)}
                         placeholder="engineer@team.local" autoFocus />
                </label>

                <label style={{ display: 'block', marginBottom: 28 }}>
                  <span className="ed-label" style={{ display: 'block', marginBottom: 6 }}>Password</span>
                  <div style={{ position: 'relative' }}>
                    <input
                      className="ed-input"
                      type={showPw ? 'text' : 'password'}
                      value={pw}
                      onChange={(e) => setPw(e.target.value)}
                      placeholder="••••••••"
                      style={{ paddingRight: 70 }}
                    />
                    <button type="button"
                            onClick={() => setShowPw((s) => !s)}
                            style={{
                              position: 'absolute', right: 0, bottom: 12,
                              background: 'transparent', border: 0,
                              color: 'var(--ed-cream-faint)', cursor: 'pointer',
                              fontFamily: 'var(--ed-body)', fontStyle: 'italic',
                              fontSize: 12, letterSpacing: '0.05em',
                            }}>
                      {showPw ? 'hide' : 'show'}
                    </button>
                  </div>
                </label>

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
                  <span style={{
                    fontFamily: 'var(--ed-mono)', fontSize: 11,
                    color: 'var(--ed-cream-faint)',
                  }}>
                    rc / {new Date().getFullYear()}.{new Date().getMonth() + 1}
                  </span>
                  <button type="submit" className="ed-btn ed-btn--ferrari" disabled={loading}>
                    {loading ? 'connecting…' : 'start engine ›'}
                  </button>
                </div>
              </form>
            </section>
          </main>

          <hr className="ed-hr" />
          <footer className="ed-footer">
            <div className="ed-footer__left">
              <span style={{ fontStyle: 'italic' }}>An onboard publication</span>
              <span style={{ color: 'var(--ed-cream-trace)' }}>·</span>
              <span>{new Date().getFullYear()}</span>
            </div>
            <div className="ed-footer__right">
              <span style={{ fontStyle: 'italic' }}>
                public viewer? append <span style={{
                  fontFamily: 'var(--ed-mono)', fontStyle: 'normal',
                  color: 'var(--ed-cream-dim)',
                }}>?view=&lt;slug&gt;</span> to the URL
              </span>
            </div>
          </footer>
        </div>
      </div>

      <style>{`
        @keyframes ed-shake {
          10%, 90% { transform: translateX(-1px); }
          20%, 80% { transform: translateX(2px); }
          30%, 50%, 70% { transform: translateX(-4px); }
          40%, 60% { transform: translateX(4px); }
        }
        @media (max-width: 880px) {
          .ed-login-grid { grid-template-columns: 1fr !important; gap: 32px !important; padding: 32px 0 !important; }
        }
      `}</style>
    </div>
  );
}

function FactCell({ label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{
        fontFamily: 'var(--ed-body)', fontStyle: 'italic',
        fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'var(--ed-cream-faint)',
      }}>{label}</span>
      <span style={{
        fontFamily: 'var(--ed-mono)', fontSize: 14,
        color: 'var(--ed-cream)',
      }}>{value}</span>
    </div>
  );
}

window.LiveLogin = LiveLogin;
