<template>
    <div class="physical-gate-page">
        <div v-if="!displayKey" class="physical-gate-setup">
            <h1 class="physical-gate-title">Paparan kod kaunter</h1>
            <p class="physical-gate-hint">
                Masukkan kunci paparan (sama dengan <code>PHYSICAL_ATTENDANCE_GATE_DISPLAY_KEY</code> dalam tetapan pelayan),
                atau buka URL dengan parameter <code>?k=...</code>
            </p>
            <div class="form-group physical-gate-key-form">
                <input v-model="keyInput" type="password" class="form-control input-lg" placeholder="Kunci paparan"
                    @keyup.enter="applyKey" />
                <button type="button" class="btn btn-primary btn-lg btn-block" @click="applyKey">Mula paparan</button>
            </div>
        </div>

        <div v-else-if="error" class="physical-gate-error">
            <h1 class="physical-gate-title">Ralat</h1>
            <p>{{ error }}</p>
            <button type="button" class="btn btn-default" @click="retry">Cuba lagi</button>
        </div>

        <div v-else class="physical-gate-active">
            <div class="physical-gate-label">Kod kehadiran fizikal ({{ periodSeconds }}s)</div>
            <div class="physical-gate-code">{{ code || '—' }}</div>
            <div class="physical-gate-countdown">
                <span class="physical-gate-countdown-bar" :style="{ width: countdownPercent + '%' }"></span>
            </div>
            <p class="physical-gate-sub">Kod akan bertukar secara automatik. Pastikan skrin sentiasa menyala.</p>
        </div>
    </div>
</template>

<script>
export default {
    name: 'PhysicalGateDisplay',

    data: function () {
        return {
            displayKey: '',
            keyInput: '',
            code: '',
            secondsRemaining: 0,
            periodSeconds: 60,
            error: '',
            pollTimer: null,
            tickTimer: null,
        };
    },

    computed: {
        countdownPercent: function () {
            if (!this.periodSeconds) return 0;
            return Math.min(100, (this.secondsRemaining / this.periodSeconds) * 100);
        },
    },

    created: function () {
        this.util.setTitle('Kod kaunter — Kehadiran fizikal');
        var q = this.$route.query.k || this.$route.query.key;
        if (q) {
            this.displayKey = String(q);
        }
    },

    mounted: function () {
        if (this.displayKey) {
            this.startPolling();
        }
    },

    beforeDestroy: function () {
        this.stopTimers();
    },

    methods: {
        applyKey: function () {
            if (!this.keyInput) return;
            this.displayKey = this.keyInput;
            this.error = '';
            this.startPolling();
        },

        retry: function () {
            this.error = '';
            this.fetchCode();
        },

        fetchCode: function () {
            var vm = this;
            axios
                .get(config.API + 'physical-attendance-gate/current', {
                    headers: { 'X-Physical-Gate-Display-Key': vm.displayKey },
                })
                .then(function (res) {
                    vm.code = res.data.code;
                    vm.secondsRemaining = res.data.seconds_remaining;
                    vm.periodSeconds = res.data.period_seconds || 60;
                    vm.error = '';
                })
                .catch(function (err) {
                    var msg = 'Tidak dapat memuatkan kod.';
                    if (err.response && err.response.data && err.response.data.message) {
                        msg = err.response.data.message;
                    }
                    vm.error = msg;
                    vm.code = '';
                });
        },

        startPolling: function () {
            var vm = this;
            this.stopTimers();
            this.fetchCode();
            this.pollTimer = setInterval(function () {
                vm.fetchCode();
            }, 5000);
            this.tickTimer = setInterval(function () {
                if (vm.secondsRemaining > 0) {
                    vm.secondsRemaining -= 1;
                }
                if (vm.secondsRemaining <= 0 && !vm.error) {
                    vm.fetchCode();
                }
            }, 1000);
        },

        stopTimers: function () {
            if (this.pollTimer) {
                clearInterval(this.pollTimer);
                this.pollTimer = null;
            }
            if (this.tickTimer) {
                clearInterval(this.tickTimer);
                this.tickTimer = null;
            }
        },
    },
};
</script>

<style scoped>
.physical-gate-page {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24px;
    background: linear-gradient(160deg, #0f172a 0%, #1e3a5f 45%, #0f172a 100%);
    color: #e2e8f0;
}

.physical-gate-setup,
.physical-gate-error {
    max-width: 520px;
    width: 100%;
}

.physical-gate-title {
    font-size: 2rem;
    font-weight: 800;
    margin-bottom: 16px;
    color: #f8fafc;
}

.physical-gate-hint {
    font-size: 1.05rem;
    line-height: 1.5;
    margin-bottom: 20px;
    color: #94a3b8;
}

.physical-gate-key-form .btn {
    margin-top: 12px;
}

.physical-gate-active {
    text-align: center;
    width: 100%;
    max-width: 920px;
}

.physical-gate-label {
    font-size: 1.4rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: #94a3b8;
    margin-bottom: 20px;
}

.physical-gate-code {
    font-size: clamp(3.5rem, 14vw, 8rem);
    font-weight: 900;
    letter-spacing: 0.12em;
    font-family: 'SF Mono', 'Menlo', 'Consolas', monospace;
    color: #fbbf24;
    text-shadow: 0 0 40px rgba(251, 191, 36, 0.35);
    margin-bottom: 28px;
    word-break: break-all;
}

.physical-gate-countdown {
    height: 12px;
    border-radius: 999px;
    background: rgba(148, 163, 184, 0.25);
    overflow: hidden;
    margin: 0 auto 20px;
    max-width: 560px;
}

.physical-gate-countdown-bar {
    display: block;
    height: 100%;
    border-radius: 999px;
    background: linear-gradient(90deg, #38bdf8, #22d3ee);
    transition: width 0.3s ease;
}

.physical-gate-sub {
    font-size: 1.1rem;
    color: #94a3b8;
    margin: 0;
}
</style>
