// AdminGate.jsx — password gate for any Administration change.
//
// Anywhere in the app, call:
//   window.askAdminPassword('Save settings', () => doSave())
// — if already unlocked this session, the callback runs immediately;
// — otherwise a modal prompts for the admin password. On success the
//   callback runs and the unlock is cached in sessionStorage so the
//   admin doesn't get prompted on every click in the same session.
//
// Default password (prototype): 3873134
// In production this will validate against the server.

const ADMIN_PASSWORD = '3873134';

function AdminGateMount() {
  const [request, setRequest] = React.useState(null); // { label, callback }
  const [pwd, setPwd] = React.useState('');
  const [error, setError] = React.useState(false);
  const [shake, setShake] = React.useState(false);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    window.askAdminPassword = (label, callback) => {
      if (sessionStorage.getItem('admin-unlocked') === '1') {
        callback();
        return;
      }
      setRequest({ label, callback });
      setPwd('');
      setError(false);
    };
  }, []);

  React.useEffect(() => {
    if (request && inputRef.current) {
      setTimeout(() => inputRef.current.focus(), 50);
    }
  }, [request]);

  if (!request) return null;

  const submit = (e) => {
    if (e) e.preventDefault();
    if (pwd === ADMIN_PASSWORD) {
      sessionStorage.setItem('admin-unlocked', '1');
      const cb = request.callback;
      setRequest(null);
      setPwd('');
      cb();
    } else {
      setError(true);
      setShake(true);
      setTimeout(() => setShake(false), 400);
    }
  };

  const cancel = () => { setRequest(null); setPwd(''); setError(false); };

  return (
    <div className="install-modal" onClick={cancel}>
      <form
        className="install-modal__card"
        onClick={(e) => e.stopPropagation()}
        onSubmit={submit}
        style={{maxWidth: 420, animation: shake ? 'shake 280ms cubic-bezier(.36,.07,.19,.97)' : 'none'}}
      >
        <style>{`@keyframes shake {
          10%,90% { transform: translateX(-2px); }
          20%,80% { transform: translateX(4px); }
          30%,50%,70% { transform: translateX(-6px); }
          40%,60% { transform: translateX(6px); }
        }`}</style>

        <div style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14}}>
          <div style={{width: 44, height: 44, borderRadius: 10, background: 'var(--color-navy)', display: 'grid', placeItems: 'center', color: 'var(--color-yellow)', flexShrink: 0}}>
            <Lock size={20}/>
          </div>
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontWeight: 700, fontSize: 17, color: 'var(--color-navy)'}}>Administrator Password</div>
            <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 2}}>
              {request.label}
            </div>
          </div>
          <button type="button" className="install-banner__close" onClick={cancel}><X size={18}/></button>
        </div>

        <div style={{padding: 12, background: 'var(--color-grey-50)', border: '1px solid var(--color-grey-200)', borderRadius: 8, marginBottom: 14, fontSize: 12, color: 'var(--color-grey-700)', lineHeight: 1.5}}>
          Administration changes require re-authentication. Enter the admin password to continue. The unlock applies for the rest of this session.
        </div>

        <div style={{marginBottom: 12}}>
          <label style={{fontSize: 11, fontWeight: 700, color: 'var(--color-grey-600)', textTransform: 'uppercase', letterSpacing: '0.08em', display: 'block', marginBottom: 6}}>
            Password
          </label>
          <input
            ref={inputRef}
            type="password"
            className="input"
            value={pwd}
            onChange={(e) => { setPwd(e.target.value); setError(false); }}
            style={{
              width: '100%',
              height: 44,
              fontSize: 16,
              letterSpacing: '0.2em',
              borderColor: error ? '#dc2626' : 'var(--color-grey-300)',
              background: error ? '#fef2f2' : 'white',
            }}
            placeholder="••••••••"
            autoComplete="off"
          />
          {error ? (
            <div style={{fontSize: 12, color: '#dc2626', marginTop: 6, display: 'flex', alignItems: 'center', gap: 4}}>
              <AlertTriangle size={12}/> Incorrect password. Try again.
            </div>
          ) : (
            <div style={{fontSize: 11, color: 'var(--color-grey-500)', marginTop: 6}}>
              Default prototype password: <code style={{background: 'var(--color-grey-100)', padding: '1px 5px', borderRadius: 3, fontFamily: 'monospace'}}>3873134</code>
            </div>
          )}
        </div>

        <div style={{display: 'flex', gap: 8, justifyContent: 'flex-end'}}>
          <button type="button" className="btn btn--ghost" onClick={cancel}>Cancel</button>
          <button type="submit" className="btn btn--primary">
            <Check size={14}/> Unlock &amp; Continue
          </button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { AdminGateMount });
