/* Lightweight client-side password gate.
   Compares SHA-256 of input against a stored hash so the literal password
   isn't searchable in source. NOT real security — anyone determined could
   brute force the hash or skip the gate via DevTools. Intended only to
   prevent casual access while this prototype is being shared internally. */

const SESSION_KEY = 'vamana_platform_auth';
const PASSWORD_HASH = 'acf845daddac64ae5605b44d904e2d483e482e99e5de2de626fff25b9f6c53ca';

// crypto.subtle requires HTTPS (or localhost). If we're on plain HTTP for any
// reason (cached redirect failure, manual http:// nav), upgrade immediately —
// otherwise the digest call below throws and the app never mounts.
if (typeof location !== 'undefined'
    && location.protocol === 'http:'
    && location.hostname !== 'localhost'
    && location.hostname !== '127.0.0.1') {
  location.replace('https://' + location.host + location.pathname + location.search + location.hash);
}

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

function PasswordGate({ children }) {
  const [authed, setAuthed] = React.useState(
    () => sessionStorage.getItem(SESSION_KEY) === 'true'
  );
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState(false);
  const [pending, setPending] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (pending) return;
    setPending(true);
    setError(false);
    const hash = await sha256Hex(password);
    if (hash === PASSWORD_HASH) {
      sessionStorage.setItem(SESSION_KEY, 'true');
      setAuthed(true);
    } else {
      setError(true);
      setTimeout(() => setError(false), 2000);
    }
    setPending(false);
  };

  if (authed) return children;

  return (
    <div style={{
      position: 'fixed', inset: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg-primary, #FAFAF8)',
      fontFamily: 'var(--font-sans)',
      padding: 24,
    }}>
      <form onSubmit={handleSubmit} style={{
        width: '100%', maxWidth: 380,
        background: 'var(--bg-elevated, #FFFFFF)',
        border: '1px solid var(--border-subtle, #E8E6E0)',
        borderRadius: 'var(--radius-lg, 12px)',
        padding: 32,
        boxShadow: '0 1px 3px rgba(0,0,0,0.04), 0 12px 32px -8px rgba(0,0,0,0.08)',
      }}>
        <div style={{ marginBottom: 28 }}>
          <div style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 11,
            fontWeight: 500,
            letterSpacing: '0.06em',
            textTransform: 'uppercase',
            color: 'var(--accent)',
            marginBottom: 6,
          }}>
            // Vamana AI
          </div>
          <h1 style={{
            fontFamily: 'var(--font-heading)',
            fontSize: 22,
            fontWeight: 600,
            letterSpacing: '-0.02em',
            margin: 0,
            color: 'var(--text-primary)',
          }}>
            Platform Preview
          </h1>
          <p style={{
            fontSize: 13,
            color: 'var(--text-secondary)',
            margin: '6px 0 0',
            lineHeight: 1.5,
          }}>
            Internal preview. Enter the password shared by the team.
          </p>
        </div>

        <label style={{
          display: 'block',
          fontSize: 10,
          fontWeight: 500,
          letterSpacing: '0.06em',
          textTransform: 'uppercase',
          color: 'var(--text-tertiary)',
          marginBottom: 6,
        }}>
          Password
        </label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          autoFocus
          disabled={pending}
          style={{
            width: '100%',
            padding: '10px 12px',
            fontFamily: 'var(--font-mono)',
            fontSize: 13,
            background: error ? 'rgba(220,38,38,0.04)' : 'var(--bg-inset)',
            border: `1px solid ${error ? '#DC2626' : 'var(--border-subtle)'}`,
            borderRadius: 'var(--radius-md, 6px)',
            color: 'var(--text-primary)',
            outline: 'none',
            boxSizing: 'border-box',
            transition: 'border-color 0.15s, background 0.15s',
          }}
        />
        {error && (
          <div style={{
            fontSize: 11,
            color: '#DC2626',
            marginTop: 6,
          }}>
            Incorrect password.
          </div>
        )}

        <button
          type="submit"
          disabled={pending || !password}
          style={{
            width: '100%',
            marginTop: 16,
            padding: '10px 12px',
            fontFamily: 'var(--font-sans)',
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: '-0.005em',
            background: 'var(--accent)',
            color: '#FFFFFF',
            border: 'none',
            borderRadius: 'var(--radius-md, 6px)',
            cursor: pending || !password ? 'not-allowed' : 'pointer',
            opacity: pending || !password ? 0.5 : 1,
            transition: 'opacity 0.15s, background 0.15s',
          }}
        >
          {pending ? 'Checking…' : 'Unlock'}
        </button>
      </form>
    </div>
  );
}
