<script>
    let { adminPath = '/loom' } = $props();
    let code = $state('');
    let error = $state(null);
    let loading = $state(false);

    async function handleVerify(e) {
        e.preventDefault();
        loading = true;
        error = null;

        try {
            const response = await axios.post(`${adminPath}/two-factor`, {
                code
            });
            window.location.href = response.data.redirect || adminPath;
        } catch (e) {
            error = e.response?.data?.message || 'Invalid 2FA code.';
        } finally {
            loading = false;
        }
    }
</script>

<div class="ui middle aligned center aligned grid" style="height: 100vh;">
    <div class="column" style="max-width: 450px;">
        <h2 class="ui teal image header">
            <div class="content">
                Two-Factor Verification
            </div>
        </h2>
        <form class="ui large form {error ? 'error' : ''}" onsubmit={handleVerify}>
            <div class="ui stacked segment">
                <p>Please enter the verification code from your authenticator app.</p>
                <div class="field">
                    <div class="ui left icon input">
                        <i class="key icon"></i>
                        <input type="text" name="code" placeholder="000000" bind:value={code} required autocomplete="one-time-code">
                    </div>
                </div>
                <button class="ui fluid large teal submit button {loading ? 'loading' : ''}" type="submit">
                    Verify
                </button>
            </div>

            {#if error}
                <div class="ui error message" style="display: block;">
                    <p>{error}</p>
                </div>
            {/if}
        </form>
    </div>
</div>
