// Password gate — covers the page until the user enters the correct password.
// Hash check is client-side and only deters casual viewing.
// For real auth, layer Cloudflare Access on top (see DEPLOY.md).

const SESSION_KEY = "zintex-stack-unlock";

async function sha256Hex(text) {
  const buf = new TextEncoder().encode(text);
  const hash = await crypto.subtle.digest("SHA-256", buf);
  return [...new Uint8Array(hash)].map(b => b.toString(16).padStart(2, "0")).join("");
}

function isUnlocked() {
  const cfg = window.CONFIG || {};
  try {
    const raw = sessionStorage.getItem(SESSION_KEY);
    if (!raw) return false;
    const { hash, expires } = JSON.parse(raw);
    if (hash !== cfg.passwordHash) return false;
    if (Date.now() > expires) return false;
    return true;
  } catch {
    return false;
  }
}

function markUnlocked() {
  const cfg = window.CONFIG || {};
  const minutes = Number(cfg.sessionMinutes) || 480;
  sessionStorage.setItem(SESSION_KEY, JSON.stringify({
    hash: cfg.passwordHash,
    expires: Date.now() + minutes * 60 * 1000,
  }));
}

function lock() {
  sessionStorage.removeItem(SESSION_KEY);
  location.reload();
}

function PasswordGate({ onUnlock }) {
  const [pw, setPw] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    ref.current && ref.current.focus();
  }, []);

  const submit = async (e) => {
    e && e.preventDefault();
    setBusy(true);
    setErr("");
    const expected = (window.CONFIG && window.CONFIG.passwordHash) || "";
    const actual = await sha256Hex(pw);
    if (actual === expected) {
      markUnlocked();
      onUnlock();
    } else {
      setErr("Incorrect password.");
      setPw("");
      setBusy(false);
    }
  };

  return (
    <div className="gate-wrap">
      <div className="gate-card">
        <div className="gate-mark">Z</div>
        <div className="gate-title">ZINTEX REMODELING</div>
        <div className="gate-sub">Tech Stack · Internal</div>
        <form onSubmit={submit} className="gate-form">
          <label htmlFor="gate-pw" className="gate-label">Password</label>
          <input
            id="gate-pw"
            ref={ref}
            type="password"
            value={pw}
            onChange={(e) => setPw(e.target.value)}
            autoComplete="current-password"
            disabled={busy}
          />
          <button type="submit" className="gate-btn" disabled={busy || !pw}>
            {busy ? "Checking…" : "Enter"}
          </button>
          {err && <div className="gate-err">{err}</div>}
        </form>
        <div className="gate-foot">Authorized personnel only.</div>
      </div>
    </div>
  );
}

window.PasswordGate = PasswordGate;
window.isUnlocked = isUnlocked;
window.lockSession = lock;
