document.addEventListener('DOMContentLoaded', function () {

    let nextChapterUrl = '';
    let externalUrl = '';
    let gateName = 'Shopee';


    /* ==========================================
       NẾU VỪA QUAY LẠI TỪ SHOPEE
       -> CHUYỂN SANG CHƯƠNG KẾ
    ========================================== */

    function goToPendingChapter() {

        const pending =
            sessionStorage.getItem('tinhha-pending-chapter');

        if (!pending) {
            return;
        }

        sessionStorage.removeItem('tinhha-pending-chapter');

        window.location.href = pending;
    }


    /*
     * Trường hợp Shopee mở cùng tab:
     * khi người đọc Back trở lại trang truyện,
     * trạng thái này sẽ đưa họ sang Chương 2.
     */
    const pendingOnLoad =
        sessionStorage.getItem('tinhha-pending-chapter');

    if (pendingOnLoad) {

        sessionStorage.removeItem('tinhha-pending-chapter');

        window.location.replace(pendingOnLoad);

        return;
    }


    /* ==========================================
       TẠO MÀN HÌNH KHÓA
    ========================================== */

    const gate = document.createElement('div');

    gate.id = 'tinhha-reading-gate';

    gate.style.cssText = `
        display:none;
        position:fixed;
        inset:0;
        z-index:999999;
        background:rgba(26,21,34,.72);
        backdrop-filter:blur(4px);
        -webkit-backdrop-filter:blur(4px);
        align-items:center;
        justify-content:center;
        box-sizing:border-box;
        padding:20px;
    `;


    gate.innerHTML = `

        <div style="
            width:100%;
            max-width:420px;
            background:#fffdf8;
            border:1px solid #dfd1b9;
            border-radius:20px;
            box-sizing:border-box;
            padding:32px 25px 28px;
            text-align:center;
            position:relative;
            box-shadow:0 20px 60px rgba(0,0,0,.25);
        ">

            <!-- Đóng -->
            <button
                id="tinhha-gate-close"
                type="button"
                aria-label="Đóng"
                style="
                    position:absolute;
                    right:14px;
                    top:11px;
                    border:0;
                    background:transparent;
                    color:#9b9690;
                    font-size:25px;
                    line-height:1;
                    cursor:pointer;
                "
            >
                ×
            </button>


            <!-- Hoa văn -->
            <div style="
                color:#795dff;
                font-size:22px;
                margin-bottom:8px;
            ">
                ✦
            </div>


            <!-- Tiêu đề -->
            <div style="
                font-family:Georgia,'Times New Roman',serif;
                font-size:22px;
                font-weight:700;
                color:#5b4630;
                line-height:1.4;
                margin-bottom:12px;
            ">
                Tiếp tục đọc truyện
            </div>


            <!-- Nội dung -->
            <div
                id="tinhha-gate-description"
                style="
                    font-family:Georgia,'Times New Roman',serif;
                    font-size:15px;
                    line-height:1.7;
                    color:#766d65;
                    margin-bottom:22px;
                "
            >
                Hãy bấm liên kết Shopee bên dưới
                để tiếp tục đọc chương tiếp theo.
            </div>


            <!-- Nút Shopee -->
            <a
                id="tinhha-gate-link"
                href="#"
                target="_blank"
                rel="noopener sponsored"
                style="
                    display:inline-block;
                    padding:12px 29px;
                    border-radius:25px;
                    background:#ee4d2d;
                    color:#ffffff;
                    text-decoration:none;
                    font-family:Arial,sans-serif;
                    font-size:14px;
                    font-weight:700;
                    box-shadow:0 5px 15px rgba(238,77,45,.22);
                "
            >
                🛍 MỞ SHOPEE
            </a>


            <div style="
                font-family:Georgia,'Times New Roman',serif;
                font-size:12px;
                line-height:1.5;
                color:#9a938b;
                margin-top:15px;
            ">
                Sau khi mở liên kết, hãy quay lại
                Tinh Hà Thư Viện để tiếp tục đọc.
            </div>

        </div>
    `;


    document.body.appendChild(gate);


    const closeButton =
        document.getElementById('tinhha-gate-close');

    const externalButton =
        document.getElementById('tinhha-gate-link');

    const description =
        document.getElementById('tinhha-gate-description');


    /* ==========================================
       BẤM "CHƯƠNG TIẾP"
    ========================================== */

    document.addEventListener(
        'click',
        function (event) {

            const button =
                event.target.closest('.tinhha-gated-next');

            if (!button) {
                return;
            }


            /*
             * Quan trọng:
             * Không cho href="#" làm bất kỳ điều gì.
             */
            event.preventDefault();
            event.stopPropagation();


            nextChapterUrl =
                button.getAttribute('data-next-url');

            externalUrl =
                button.getAttribute('data-gate-url');

            gateName =
                button.getAttribute('data-gate-name')
                || 'liên kết';


            if (!nextChapterUrl || !externalUrl) {

                console.error(
                    'Tinh Hà: Thiếu link chương kế hoặc link ngoài.'
                );

                return;
            }


            description.innerHTML =
                'Hãy bấm liên kết <strong>' +
                gateName +
                '</strong> bên dưới ' +
                'để tiếp tục đọc chương tiếp theo.';


            externalButton.href =
                externalUrl;

            externalButton.innerHTML =
                '🛍 MỞ ' + gateName.toUpperCase();


            gate.style.display =
                'flex';

        },
        true
    );


    /* ==========================================
       ĐÓNG MÀN HÌNH
    ========================================== */

    closeButton.addEventListener(
        'click',
        function () {

            gate.style.display = 'none';

        }
    );


    gate.addEventListener(
        'click',
        function (event) {

            if (event.target === gate) {

                gate.style.display = 'none';

            }

        }
    );


    /* ==========================================
       BẮT BUỘC CLICK LINK SHOPEE
    ========================================== */

    externalButton.addEventListener(
        'click',
        function () {

            if (!nextChapterUrl) {
                return;
            }


            /*
             * Chỉ sau khi người đọc CLICK Shopee
             * mới ghi nhận Chương 2.
             */
            sessionStorage.setItem(
                'tinhha-pending-chapter',
                nextChapterUrl
            );


            /*
             * Shopee được mở bởi href + target="_blank".
             *
             * Trong lúc người đọc đang ở Shopee,
             * tab Tinh Hà sẽ tự chuyển sang Chương 2.
             */
            setTimeout(
                function () {

                    const pending =
                        sessionStorage.getItem(
                            'tinhha-pending-chapter'
                        );

                    if (!pending) {
                        return;
                    }


                    sessionStorage.removeItem(
                        'tinhha-pending-chapter'
                    );


                    window.location.href =
                        pending;

                },
                500
            );

        }
    );


    /* ==========================================
       DỰ PHÒNG CHO IPHONE / SAFARI / APP SHOPEE
    ========================================== */

    document.addEventListener(
        'visibilitychange',
        function () {

            if (
                document.visibilityState === 'visible'
            ) {

                goToPendingChapter();

            }

        }
    );


    window.addEventListener(
        'pageshow',
        function () {

            goToPendingChapter();

        }
    );

});