'use client';

/**
 * Login-less gate for the Executive dashboard (mirrors NOC's NOCAuthWrapper).
 * On mount it verifies the exec display cookie via GET /api/executive/auth;
 * if unauthenticated it renders a token-entry screen that POSTs the token to
 * bind it to this device. Replaces the old proxy-level executive_session gate.
 */
import { useCallback, useEffect, useState } from 'react';
import { Shield, ArrowRight } from 'lucide-react';
import { PulseGlyph } from './PulseGlyph';
import { Slash } from './primitives';

type AuthState = 'checking' | 'authed' | 'denied';

export function ExecutiveAuthWrapper({ children }: { children: React.ReactNode }) {
    const [state, setState] = useState<AuthState>('checking');

    const check = useCallback(async () => {
        try {
            const res = await fetch('/api/executive/auth', { cache: 'no-store' });
            const data = await res.json();
            setState(data.authenticated ? 'authed' : 'denied');
        } catch {
            setState('denied');
        }
    }, []);

    useEffect(() => {
        // check() setStates only after an awaited fetch (async continuation),
        // not synchronously in the effect body — so no cascading render.
        // eslint-disable-next-line react-hooks/set-state-in-effect
        check();
    }, [check]);

    if (state === 'authed') return <>{children}</>;
    if (state === 'checking') {
        return (
            <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>
                Verifying access…
            </div>
        );
    }
    return <TokenEntry onAuthed={() => setState('authed')} />;
}

function TokenEntry({ onAuthed }: { onAuthed: () => void }) {
    const [token, setToken] = useState('');
    const [error, setError] = useState<string | null>(null);
    const [busy, setBusy] = useState(false);

    const submit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!token.trim() || busy) return;
        setBusy(true);
        setError(null);
        try {
            const res = await fetch('/api/executive/auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: token.trim() }),
            });
            const data = await res.json();
            if (res.ok && data.success) {
                onAuthed();
            } else {
                setError(data.error || 'Invalid token');
            }
        } catch {
            setError('Could not reach the server');
        } finally {
            setBusy(false);
        }
    };

    return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
            <form onSubmit={submit} className="glass-card" style={{ width: 420, maxWidth: '100%', padding: 36, display: 'flex', flexDirection: 'column', gap: 18 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <PulseGlyph size={44} />
                    <div>
                        <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 17, color: 'var(--fg)' }}>UpTime Sentinel</div>
                        <div className="eyebrow" style={{ color: 'var(--accent)' }}>Executive Command</div>
                    </div>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--fg-2)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
                    <Shield size={18} style={{ color: 'var(--cyan)', flex: 'none' }} />
                    <span>Enter your display token to view the dashboard. The token locks to this device on first use.</span>
                </div>

                <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    <span className="eyebrow">Display token</span>
                    <input
                        type="password"
                        value={token}
                        onChange={(e) => setToken(e.target.value)}
                        placeholder="exec_…"
                        autoFocus
                        style={{
                            fontFamily: 'var(--font-mono)', fontSize: 14, padding: '12px 14px', color: 'var(--fg)',
                            background: 'var(--card-bg)', border: `1px solid ${error ? 'var(--crit)' : 'var(--hair-2)'}`, borderRadius: 2, outline: 'none',
                        }}
                    />
                </label>

                {error && <div style={{ color: 'var(--crit-fg)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>{error}</div>}

                <button
                    type="submit"
                    disabled={busy || !token.trim()}
                    className="pill"
                    style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '12px 18px', border: 'none',
                        cursor: busy || !token.trim() ? 'default' : 'pointer', opacity: busy || !token.trim() ? 0.6 : 1,
                        background: 'linear-gradient(135deg, var(--magenta), var(--violet))', color: '#fff',
                        fontFamily: 'var(--font-heading)', fontSize: 13, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em',
                    }}
                >
                    {busy ? 'Verifying…' : <>Enter <ArrowRight size={15} /></>}
                </button>

                <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                    <Slash style={{ height: 12 }} /> Tokens are issued by an administrator in Settings → Executive Tokens.
                </div>
            </form>
        </div>
    );
}
