/* Lock screen — client-side workspace password gate.
   The password itself never appears in source; only its hashes do.
   SHA-256 (crypto.subtle) is used on secure contexts (https / localhost);
   FNV-1a-32 is the sync fallback for plain-http LAN testing on a phone. */
const AG = window.GreydigiComponents;

const PASS_SHA256 = '7dfc8fa761b5e1ac19aa90ef87e0d7c559e26a216d9fc04d160f2204e8ac3574';
const PASS_FNV = 'b0ea6993';

async function hashPassword(text) {
  if (window.crypto && crypto.subtle) {
    const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
    return { algo: 'sha', hex: Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('') };
  }
  let h = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = (h * 0x01000193) >>> 0; }
  return { algo: 'fnv', hex: h.toString(16).padStart(8, '0') };
}

function LockScreen({ onUnlock }) {
  const [pw, setPw] = React.useState('');
  const [error, setError] = React.useState(false);
  const [checking, setChecking] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!pw || checking) return;
    setChecking(true);
    const { algo, hex } = await hashPassword(pw);
    const ok = (algo === 'sha' && hex === PASS_SHA256) || (algo === 'fnv' && hex === PASS_FNV);
    if (ok) {
      try { localStorage.setItem(LOCK_KEY, '1'); } catch (err) {}
      onUnlock();
    } else {
      setChecking(false);
      setError(false);
      requestAnimationFrame(() => setError(true)); // restart shake on repeat failures
      setPw('');
    }
  };

  return (
    <div className="lock-screen">
      <form className={'lock-card' + (error ? ' is-error' : '')} onSubmit={submit}>
        <AG.Logo height={40} />
        <div>
          <h1 className="lock-title">AI Recruiting</h1>
          <div className="lock-sub">Enter the workspace password to continue</div>
        </div>
        <input
          className="field-input lock-input"
          type="password"
          value={pw}
          onChange={(e) => { setPw(e.target.value); setError(false); }}
          placeholder="Password"
          autoFocus
          autoComplete="current-password"
          aria-label="Workspace password"
        />
        {error && <div className="lock-error">Wrong password — try again</div>}
        <button className="lock-submit" type="submit" disabled={!pw || checking}>
          {checking ? 'Checking…' : 'Unlock workspace'}
        </button>
        <div className="lock-note"><Icon name="users" size={12} /> Aironauts · Greydigi internal tool</div>
      </form>
    </div>
  );
}

Object.assign(window, { LockScreen });
