// @ts-nocheck
/* Email+password auth against the worker's own /api/auth. The app is wrapped in <AuthGate>:
     no session → <LoginScreen> ; session → the app.
   The session ({ access_token, user }) lives in localStorage["premise.auth"] and is read at
   script load, so the fetch wrapper below attaches the token to every /api/* call before
   anything mounts. saveSession(s) writes (or clears) it and fires 'premise:auth'. */

const AUTH_KEY = 'premise.auth';
let __session = null;
try {
  const raw = localStorage.getItem(AUTH_KEY);
  const s = raw ? JSON.parse(raw) : null;
  if (s && s.access_token) __session = { access_token: s.access_token, user: s.user || null };
} catch (e) { __session = null; }

function saveSession(s) {
  __session = s && s.access_token ? { access_token: s.access_token, user: s.user || null } : null;
  try {
    if (__session) localStorage.setItem(AUTH_KEY, JSON.stringify(__session));
    else localStorage.removeItem(AUTH_KEY);
  } catch (e) { /* storage unavailable: the session lives in memory only */ }
  window.dispatchEvent(new CustomEvent('premise:auth', { detail: __session }));
}

// ── fetch wrapper: attach Authorization to /api calls ──
const _origFetch = window.fetch.bind(window);
window.fetch = function (input, init) {
  try {
    const url = typeof input === 'string' ? input : (input && input.url) || '';
    const isApi = url.indexOf('/api/') === 0 || url.indexOf(location.origin + '/api/') === 0;
    if (isApi) {
      init = init ? Object.assign({}, init) : {};
      const headers = new Headers(init.headers || (typeof input !== 'string' && input && input.headers) || {});
      if (__session && __session.access_token) headers.set('Authorization', 'Bearer ' + __session.access_token);
      init.headers = headers;
    }
  } catch (e) { /* ignore */ }
  return _origFetch(input, init);
};

// Login/signup error copy: the server's error code first, then the status.
function authErrCopy(status, code) {
  if (status === 0) return '连不上服务器';
  if (code === 'weak_password') return '密码至少 8 位';
  if (code === 'invalid_email') return '邮箱格式不对';
  if (code === 'email_taken' || status === 409) return '这个邮箱已经注册过了，直接登录';
  if (code === 'too_many_attempts' || status === 429) return '试太多次了，15 分钟后再来';
  if (code === 'invalid_credentials' || status === 401) return '邮箱或密码不对';
  return code || ('HTTP ' + status);
}

function LoginScreen({ onAuthed }) {
  const [mode, setMode] = React.useState('signin'); // 'signin' | 'signup'
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [note, setNote] = React.useState(null);
  async function submit(e) {
    if (e) e.preventDefault();
    if (!email.trim() || !pw || busy) return;
    setBusy(true); setErr(null); setNote(null);
    let r;
    try {
      r = await fetch(mode === 'signup' ? '/api/auth/signup' : '/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), password: pw }),
      });
    } catch (e2) { setErr(authErrCopy(0)); setBusy(false); return; }
    let body = null;
    try { body = await r.json(); } catch (e3) { /* not JSON */ }
    if (r.ok && body && body.token) {
      const s = { access_token: body.token, user: body.user || null };
      saveSession(s);
      setBusy(false);
      onAuthed(s);
      return;
    }
    setErr(authErrCopy(r.ok ? 0 : r.status, body && body.error));
    setBusy(false);
  }
  const field = { width: '100%', padding: '11px 13px', border: 'var(--bw) solid var(--ink)', background: 'var(--surface)', fontFamily: 'var(--font-mono)', fontSize: 13, outline: 'none', boxSizing: 'border-box' };
  const label = { fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--mute)', marginBottom: 6 };
  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--paper)', padding: 20 }}>
      <div className="col" style={{ gap: 18, alignItems: 'center' }}>
      <form onSubmit={submit} style={{ width: 'min(420px, 94vw)', background: 'var(--surface)', border: 'var(--bw) solid var(--ink)', boxShadow: '7px 7px 0 var(--ink)' }}>
        <div style={{ background: 'var(--ink)', color: 'var(--surface)', padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div className="brandmark" style={{ width: 30, height: 30 }}>P</div>
          <div className="col" style={{ gap: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: '0.02em' }}>PREMISE</div>
            <div className="mono" style={{ fontSize: 10, opacity: 0.7 }}>EVERY TOUCH, GROUNDED</div>
          </div>
        </div>
        <div style={{ padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="row" style={{ gap: 0, border: 'var(--bw) solid var(--ink)' }}>
            {['signin', 'signup'].map(m => (
              <button type="button" key={m} onClick={() => { setMode(m); setErr(null); setNote(null); }}
                style={{ flex: 1, padding: '8px 0', cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 12, border: 'none', borderRight: m === 'signin' ? 'var(--bw) solid var(--ink)' : 'none', background: mode === m ? 'var(--ink)' : 'var(--surface)', color: mode === m ? 'var(--surface)' : 'var(--ink)' }}>
                {m === 'signin' ? '登录' : '注册'}
              </button>
            ))}
          </div>
          <div>
            <div style={label}>邮箱</div>
            <input style={field} type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" autoFocus autoComplete="email" />
          </div>
          <div>
            <div style={label}>密码</div>
            <input style={field} type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" autoComplete={mode === 'signup' ? 'new-password' : 'current-password'} />
          </div>
          {err && <div style={{ border: 'var(--bw) solid var(--red)', background: 'var(--red-soft)', padding: '8px 11px' }}><span className="mono" style={{ fontSize: 11, color: 'var(--red)' }}>! {err}</span></div>}
          {note && <div className="mono" style={{ fontSize: 11, color: 'var(--green)', lineHeight: 1.5 }}>{note}</div>}
          <button type="submit" disabled={busy || !email.trim() || !pw}
            style={{ padding: '11px 0', background: 'var(--accent)', color: '#fff', border: 'var(--bw) solid var(--ink)', boxShadow: '3px 3px 0 var(--ink)', cursor: 'pointer', fontWeight: 700, fontSize: 13, fontFamily: 'var(--font-sans)', opacity: (busy || !email.trim() || !pw) ? 0.5 : 1 }}>
            {busy ? '…' : (mode === 'signup' ? '注册并进入' : '登录')}
          </button>
        </div>
      </form>
        {/* Personal motto under the auth card — faint mono italic, doesn't
            compete with PREMISE / EVERY TOUCH, GROUNDED. Stays English in
            both lang modes (it's a proverb, not product copy). */}
        <div className="mono" style={{ fontSize: 11, opacity: 0.5, fontStyle: 'italic', letterSpacing: '0.04em', textAlign: 'center' }}>
          where there&rsquo;s a will, there&rsquo;s a way
        </div>
      </div>
    </div>
  );
}

function AuthGate({ children }) {
  const [phase, setPhase] = React.useState(() => (__session && __session.access_token ? 'loading' : 'login')); // loading | login | app
  React.useEffect(() => {
    if (phase !== 'loading') return;
    let alive = true;
    (async () => {
      let status = 0;
      try { status = (await fetch('/api/auth/me')).status; } catch (e) { status = 0; }
      if (!alive) return;
      if (status === 401 || status === 403) { saveSession(null); setPhase('login'); }
      else setPhase('app'); // 200, or network / 5xx: let the office hooks surface the error
    })();
    return () => { alive = false; };
  }, []);
  if (phase === 'loading') return <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--paper)', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--mute)' }}>// loading…</div>;
  if (phase === 'login') return <LoginScreen onAuthed={() => setPhase('app')} />;
  return children;
}

/* Sign-out second-confirm (brutalist scrim modal). */
function SignOutConfirm({ email, onCancel, onConfirm }) {
  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,10,10,0.42)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={onCancel}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(360px, 92vw)', background: 'var(--surface)', border: 'var(--bw) solid var(--ink)', boxShadow: '7px 7px 0 var(--ink)' }}>
        <div style={{ background: 'var(--ink)', color: 'var(--surface)', padding: '11px 15px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="logout" size={15} />
          <span className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase' }}>退出登录</span>
        </div>
        <div style={{ padding: '16px 16px 4px' }}>
          <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>{window.t('确定退出','Confirm sign out')}{email ? <> <b>{email}</b></> : '登录'}{window.t('？','?')}</div>
          <div className="mono faint" style={{ fontSize: 10.5, marginTop: 6 }}>下次进来需要重新登录。</div>
        </div>
        <div style={{ padding: '12px 14px', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Btn variant="ghost" onClick={onCancel}>取消</Btn>
          <Btn variant="primary" icon="logout" onClick={onConfirm}>退出登录</Btn>
        </div>
      </div>
    </div>
  );
}

/* Sidebar footer identity — the signed-in user, else a dash. */
function SidebarUser() {
  const cur = () => (__session && __session.user && __session.user.email) || null;
  const [email, setEmail] = React.useState(cur);
  const [confirm, setConfirm] = React.useState(false);
  React.useEffect(() => {
    const h = () => setEmail(cur());
    window.addEventListener('premise:auth', h);
    return () => window.removeEventListener('premise:auth', h);
  }, []);
  function doSignOut() { saveSession(null); location.reload(); }
  const name = email ? (email.split('@')[0] || email) : '—';
  const sub = email || '—';
  return (
    <>
      <Avatar name={name} />
      <div className="col grow" style={{ gap: 0, minWidth: 0 }}>
        <div className="truncate" style={{ fontSize: 12.5, fontWeight: 700, textTransform: 'uppercase' }}>{name}</div>
        <div className="brandsub truncate" style={{ textTransform: 'none' }}>{sub}</div>
      </div>
      {email && <button className="iconbtn" onClick={() => setConfirm(true)} title="退出登录"><Icon name="logout" size={15} /></button>}
      {confirm && <SignOutConfirm email={email} onCancel={() => setConfirm(false)} onConfirm={doSignOut} />}
    </>
  );
}

Object.assign(window, { AuthGate, LoginScreen, SidebarUser, saveSession });
