@extends('auth.layouts.guest')

@section('title', 'Verify OTP')

@section('hero')
    <div class="mx-auto w-100" style="max-width: 34rem;">
        <a href="{{ route('website.home') }}" class="d-inline-block mb-4">
            <img src="{{ asset('kiyohr.png') }}" alt="KiyoHR logo" height="40" class="d-block">
        </a>

        <div class="login-feature-icon mb-4" style="width: 3.25rem; height: 3.25rem; font-size: 1.35rem;">
            <i class="bi bi-shield-lock"></i>
        </div>

        <h1 class="display-6 fw-bold mb-3">Verify it&apos;s you</h1>
        <p class="text-muted mb-4">
            Two-factor authentication keeps your HR data safe. Enter the verification code to finish signing in.
        </p>

        <div class="row g-3">
            <div class="col-md-6">
                <div class="login-feature-chip d-flex align-items-start gap-2 h-100">
                    <span class="login-feature-icon"><i class="bi bi-envelope-check"></i></span>
                    <div>
                        <div class="fw-semibold small">Email codes</div>
                        <div class="text-muted small mb-0">Sent to your inbox</div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="login-feature-chip d-flex align-items-start gap-2 h-100">
                    <span class="login-feature-icon"><i class="bi bi-phone"></i></span>
                    <div>
                        <div class="fw-semibold small">Authenticator</div>
                        <div class="text-muted small mb-0">Google / Microsoft Auth</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('content')
    @php
        $isTotp = ($method ?? 'email') === 'totp';
        $oldCode = old('code', '');
    @endphp

    <div class="text-center text-lg-start mb-4">
        <p class="text-uppercase text-muted small fw-semibold mb-1" style="letter-spacing: 0.14em;">Security check</p>
        <h1 class="h3 fw-bold mb-1">Enter verification code</h1>
        @if($isTotp)
            <p class="text-muted small mb-0">Open your authenticator app and enter the 6-digit code for KiyoHR.</p>
        @else
            <p class="text-muted small mb-0">
                We sent a 6-digit code to
                <span class="fw-semibold text-slate-700">{{ $maskedEmail ?? 'your email' }}</span>.
            </p>
        @endif
    </div>

    @if(! empty($userName))
        <div class="otp-user-chip mb-4">
            <span class="otp-user-avatar">{{ strtoupper(substr($userName, 0, 1)) }}</span>
            <div class="min-w-0">
                <div class="fw-semibold small text-truncate">{{ $userName }}</div>
                <div class="text-muted" style="font-size: 0.75rem;">{{ $isTotp ? 'Authenticator app' : 'Email verification' }}</div>
            </div>
        </div>
    @endif

    @if(session('success'))
        <div class="alert alert-success py-2 small mb-3 d-flex align-items-center gap-2" role="alert">
            <i class="bi bi-check-circle-fill"></i>
            <span>{{ session('success') }}</span>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger py-2 small mb-3 d-flex align-items-center gap-2" role="alert">
            <i class="bi bi-exclamation-circle-fill"></i>
            <span>{{ session('error') }}</span>
        </div>
    @endif

    <form method="POST" action="{{ route('two-factor.verify') }}" id="otpForm" class="mb-3">
        @csrf
        <input type="hidden" name="code" id="code" value="{{ $oldCode }}">

        <label for="otp-slot-0" class="form-label small fw-semibold d-block text-center text-lg-start mb-2">6-digit code</label>

        <div class="otp-slots-wrap mx-auto mx-lg-0">
            <div class="otp-slots @error('code') has-error @enderror @if(strlen($oldCode) === 6) is-complete @endif" id="otpSlots" role="group" aria-label="One-time password">
                @for($i = 0; $i < 6; $i++)
                    <input
                        type="text"
                        id="{{ $i === 0 ? 'otp-slot-0' : 'otp-slot-'.$i }}"
                        class="otp-slot"
                        inputmode="numeric"
                        enterkeyhint="{{ $i === 5 ? 'done' : 'next' }}"
                        maxlength="6"
                        autocomplete="{{ $i === 0 ? 'one-time-code' : 'off' }}"
                        aria-label="Digit {{ $i + 1 }} of 6"
                        data-index="{{ $i }}"
                        value="{{ strlen($oldCode) === 6 ? $oldCode[$i] : '' }}"
                    >
                @endfor
            </div>
        </div>

        @error('code')
            <div class="invalid-feedback d-block text-center text-lg-start mt-2">{{ $message }}</div>
        @enderror

        <button type="submit" class="btn btn-kiyo w-100 login-submit-btn mt-4" id="otpSubmit" disabled>
            Verify &amp; continue
        </button>
    </form>

    <div class="d-flex flex-column flex-sm-row align-items-center justify-content-between gap-2 text-center text-sm-start">
        @if(! $isTotp)
            <form method="POST" action="{{ route('two-factor.resend') }}" class="m-0">
                @csrf
                <button type="submit" class="btn btn-link btn-sm text-decoration-none p-0 fw-semibold" style="color: var(--kiyo-primary-dark);">
                    <i class="bi bi-arrow-clockwise me-1"></i>Resend code
                </button>
            </form>
        @else
            <span class="small text-muted">
                <i class="bi bi-info-circle me-1"></i>Codes refresh every 30 seconds
            </span>
        @endif

        <a href="{{ route('login') }}" class="small text-muted text-decoration-none">
            Use a different account
        </a>
    </div>

    <p class="text-center text-muted mt-4 mb-0" style="font-size: 0.7rem;">
        &copy; {{ date('Y') }} {{ config('app.vendor', 'Kiyo Solutions') }} | v{{ config('app.version', '1.0') }}
    </p>
@endsection

@push('scripts')
<script>
(function () {
    const slots = Array.from(document.querySelectorAll('.otp-slot'));
    const hidden = document.getElementById('code');
    const form = document.getElementById('otpForm');
    const submitBtn = document.getElementById('otpSubmit');
    const container = document.getElementById('otpSlots');

    function readValue() {
        return slots.map((s) => s.value.replace(/\D/g, '').slice(-1)).join('').slice(0, 6);
    }

    function writeValue(value) {
        const digits = value.replace(/\D/g, '').slice(0, 6);
        slots.forEach((slot, i) => {
            slot.value = digits[i] ?? '';
        });
        return digits;
    }

    function sync() {
        const value = writeValue(readValue());
        hidden.value = value;
        submitBtn.disabled = value.length !== 6;
        container.classList.toggle('is-complete', value.length === 6);
    }

    function focusSlot(index) {
        if (index >= 0 && index < slots.length) {
            slots[index].focus();
            slots[index].select();
        }
    }

    slots.forEach((slot, index) => {
        slot.addEventListener('input', () => {
            const raw = slot.value.replace(/\D/g, '');

            if (raw.length > 1) {
                const combined = readValue().slice(0, index) + raw;
                writeValue(combined);
                focusSlot(Math.min(index + raw.length, slots.length - 1));
            } else {
                slot.value = raw.slice(-1);
                if (slot.value && index < slots.length - 1) {
                    focusSlot(index + 1);
                }
            }

            sync();

            if (hidden.value.length === 6) {
                submitBtn.focus();
            }
        });

        slot.addEventListener('keydown', (e) => {
            if (e.key === 'Backspace') {
                if (!slot.value && index > 0) {
                    slots[index - 1].value = '';
                    sync();
                    focusSlot(index - 1);
                    e.preventDefault();
                }
                return;
            }

            if (e.key === 'ArrowLeft' && index > 0) {
                e.preventDefault();
                focusSlot(index - 1);
            }

            if (e.key === 'ArrowRight' && index < slots.length - 1) {
                e.preventDefault();
                focusSlot(index + 1);
            }
        });

        slot.addEventListener('paste', (e) => {
            e.preventDefault();
            const pasted = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
            writeValue(pasted);
            sync();
            focusSlot(Math.min(Math.max(pasted.length - 1, 0), slots.length - 1));
        });

        slot.addEventListener('focus', () => slot.select());
    });

    form.addEventListener('submit', () => {
        sync();
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Verifying…';
    });

    sync();
    const firstEmpty = slots.findIndex((s) => !s.value);
    focusSlot(firstEmpty === -1 ? slots.length - 1 : firstEmpty);
})();
</script>
@endpush
