/* =========================================================
   TXXD - IC SOI CẦU
   ---------------------------------------------------------
   Mục đích:
   - Đọc các kết quả Tài/Xỉu đã được backend công bố.
   - Lưu lịch sử gần nhất tại localStorage.
   - Tính thống kê có trọng số theo độ mới.
   - Không biết trước kết quả hiện tại.
   - Không thay đổi điểm, lựa chọn hoặc kết quả trò chơi.
========================================================= */

const IC_CONFIG = {
    API_URL:
        "/api/v1/games/tai-xiu/round/current",

    POLL_INTERVAL_MS:
        1000,

    STORAGE_KEY:
        "txxd_tai_xiu_ic_history_v1",

    MAX_STORED_RESULTS:
        30,

    MAX_VISIBLE_RESULTS:
        12,

    ANALYSIS_WINDOW:
        20,

    RECENCY_DECAY:
        0.91
};

const IC_STATE = {
    history: [],
    lastSavedRoundCode: null,
    timerId: null,
    requestRunning: false
};

/* =========================================================
   DOM
========================================================= */

function icGetElement(id) {
    return document.getElementById(id);
}

function icSetText(id, value) {
    const element =
        icGetElement(id);

    if (element) {
        element.textContent =
            String(value);
    }
}

/* =========================================================
   STORAGE
========================================================= */

function icLoadHistory() {
    try {
        const raw =
            localStorage.getItem(
                IC_CONFIG.STORAGE_KEY
            );

        if (!raw) {
            IC_STATE.history = [];
            return;
        }

        const parsed =
            JSON.parse(raw);

        if (!Array.isArray(parsed)) {
            IC_STATE.history = [];
            return;
        }

        IC_STATE.history =
            parsed
                .filter(icIsValidHistoryItem)
                .slice(
                    0,
                    IC_CONFIG.MAX_STORED_RESULTS
                );

        if (IC_STATE.history.length > 0) {
            IC_STATE.lastSavedRoundCode =
                IC_STATE.history[0].roundCode;
        }
    } catch (error) {
        console.warn(
            "[IC SOI CAU] Không đọc được lịch sử:",
            error
        );

        IC_STATE.history = [];
    }
}

function icSaveHistory() {
    try {
        localStorage.setItem(
            IC_CONFIG.STORAGE_KEY,
            JSON.stringify(
                IC_STATE.history
            )
        );
    } catch (error) {
        console.warn(
            "[IC SOI CAU] Không lưu được lịch sử:",
            error
        );
    }
}

function icIsValidHistoryItem(item) {
    if (
        !item ||
        typeof item !== "object"
    ) {
        return false;
    }

    const validResult =
        [
            "TAI",
            "XIU",
            "TRIPLE"
        ].includes(item.resultType);

    const validDice =
        Array.isArray(item.diceValues) &&
        item.diceValues.length === 3 &&
        item.diceValues.every(
            (value) =>
                Number.isInteger(Number(value)) &&
                Number(value) >= 1 &&
                Number(value) <= 6
        );

    return Boolean(
        item.roundCode &&
        validResult &&
        validDice &&
        Number.isInteger(
            Number(item.total)
        )
    );
}

/* =========================================================
   API
========================================================= */

async function icFetchCurrentRound() {
    if (IC_STATE.requestRunning) {
        return;
    }

    IC_STATE.requestRunning = true;

    try {
        const response =
            await fetch(
                IC_CONFIG.API_URL,
                {
                    method: "GET",
                    headers: {
                        Accept:
                            "application/json"
                    },
                    cache:
                        "no-store"
                }
            );

        if (!response.ok) {
            throw new Error(
                `HTTP ${response.status}`
            );
        }

        const round =
            await response.json();

        icProcessRound(round);

        icSetStatus(
            "Đang phân tích",
            "ready"
        );
    } catch (error) {
        console.warn(
            "[IC SOI CAU] Không đọc được phiên:",
            error
        );

        icSetStatus(
            "Mất dữ liệu",
            "error"
        );
    } finally {
        IC_STATE.requestRunning = false;
    }
}

/* =========================================================
   XỬ LÝ KẾT QUẢ
========================================================= */

function icProcessRound(round) {
    if (
        !round ||
        typeof round !== "object"
    ) {
        return;
    }

    const phase =
        String(
            round.phase || ""
        ).toUpperCase();

    /*
     * Tuyệt đối không lấy dữ liệu khi backend
     * chưa công bố kết quả.
     */
    if (
        phase !== "RESULT" &&
        phase !== "WAITING"
    ) {
        return;
    }

    const roundCode =
        String(
            round.roundCode || ""
        ).trim();

    const resultType =
        String(
            round.resultType || ""
        ).toUpperCase();

    const diceValues =
        Array.isArray(
            round.diceValues
        )
            ? round.diceValues.map(Number)
            : [];

    const total =
        Number(round.total);

    if (!roundCode) {
        return;
    }

    if (
        ![
            "TAI",
            "XIU",
            "TRIPLE"
        ].includes(resultType)
    ) {
        return;
    }

    if (
        diceValues.length !== 3 ||
        diceValues.some(
            (value) =>
                !Number.isInteger(value) ||
                value < 1 ||
                value > 6
        )
    ) {
        return;
    }

    const calculatedTotal =
        diceValues.reduce(
            (sum, value) =>
                sum + value,
            0
        );

    if (
        !Number.isInteger(total) ||
        total !== calculatedTotal
    ) {
        return;
    }

    const alreadyExists =
        IC_STATE.history.some(
            (item) =>
                item.roundCode ===
                roundCode
        );

    if (alreadyExists) {
        return;
    }

    const item = {
        roundCode,
        resultType,
        resultLabel:
            String(
                round.resultLabel ||
                icResultLabel(resultType)
            ),
        diceValues,
        total,
        resolvedAt:
            round.resolvedAt ||
            new Date().toISOString()
    };

    IC_STATE.history.unshift(item);

    IC_STATE.history =
        IC_STATE.history.slice(
            0,
            IC_CONFIG.MAX_STORED_RESULTS
        );

    IC_STATE.lastSavedRoundCode =
        roundCode;

    icSaveHistory();
    icRender();
}

/* =========================================================
   PHÂN TÍCH
========================================================= */

function icGetAnalysisHistory() {
    return IC_STATE.history.slice(
        0,
        IC_CONFIG.ANALYSIS_WINDOW
    );
}

function icCalculateAnalysis() {
    const history =
        icGetAnalysisHistory();

    const totalSamples =
        history.length;

    if (totalSamples === 0) {
        return {
            totalSamples: 0,
            taiCount: 0,
            xiuCount: 0,
            tripleCount: 0,
            taiPercent: 0,
            xiuPercent: 0,
            triplePercent: 0,
            averageTotal: null,
            streakLabel: "Chưa có",
            streakLength: 0,
            trendScore: 50,
            trendLabel: "Chưa đủ dữ liệu",
            confidenceLabel:
                "Chưa đủ mẫu",
            commentary:
                "IC đang chờ các kết quả chính thức từ backend."
        };
    }

    let taiCount = 0;
    let xiuCount = 0;
    let tripleCount = 0;
    let sumTotal = 0;

    history.forEach((item) => {
        sumTotal +=
            Number(item.total) || 0;

        if (
            item.resultType === "TAI"
        ) {
            taiCount += 1;
        }

        if (
            item.resultType === "XIU"
        ) {
            xiuCount += 1;
        }

        if (
            item.resultType === "TRIPLE"
        ) {
            tripleCount += 1;
        }
    });

    /*
     * Tỷ lệ Tài/Xỉu bỏ qua bộ ba khi tính
     * cán cân hai phía.
     */
    const directionalSamples =
        taiCount + xiuCount;

    const taiPercent =
        directionalSamples > 0
            ? Math.round(
                (
                    taiCount /
                    directionalSamples
                ) * 100
            )
            : 0;

    const xiuPercent =
        directionalSamples > 0
            ? 100 - taiPercent
            : 0;

    const triplePercent =
        Math.round(
            (
                tripleCount /
                totalSamples
            ) * 100
        );

    const averageTotal =
        sumTotal / totalSamples;

    const streak =
        icCalculateCurrentStreak(
            history
        );

    const weightedTrend =
        icCalculateWeightedTrend(
            history
        );

    const confidenceLabel =
        icCalculateConfidence(
            totalSamples
        );

    const trendLabel =
        icTrendLabel(
            weightedTrend
        );

    const commentary =
        icBuildCommentary({
            totalSamples,
            taiPercent,
            xiuPercent,
            triplePercent,
            averageTotal,
            streak,
            trendScore:
                weightedTrend
        });

    return {
        totalSamples,
        taiCount,
        xiuCount,
        tripleCount,
        taiPercent,
        xiuPercent,
        triplePercent,
        averageTotal,
        streakLabel:
            streak.label,
        streakLength:
            streak.length,
        trendScore:
            weightedTrend,
        trendLabel,
        confidenceLabel,
        commentary
    };
}

/*
 * Điểm xu hướng:
 *
 * 0   = thiên hoàn toàn về Xỉu trong lịch sử
 * 50  = cân bằng
 * 100 = thiên hoàn toàn về Tài trong lịch sử
 *
 * Phiên mới hơn có trọng số lớn hơn.
 */
function icCalculateWeightedTrend(
    history
) {
    let weightedValue = 0;
    let totalWeight = 0;

    history.forEach(
        (item, index) => {
            const weight =
                Math.pow(
                    IC_CONFIG.RECENCY_DECAY,
                    index
                );

            if (
                item.resultType ===
                "TAI"
            ) {
                weightedValue += weight;
                totalWeight += weight;
                return;
            }

            if (
                item.resultType ===
                "XIU"
            ) {
                weightedValue -= weight;
                totalWeight += weight;
            }
        }
    );

    if (totalWeight === 0) {
        return 50;
    }

    const normalized =
        weightedValue /
        totalWeight;

    return Math.round(
        Math.max(
            0,
            Math.min(
                100,
                50 + normalized * 50
            )
        )
    );
}

function icCalculateCurrentStreak(
    history
) {
    if (history.length === 0) {
        return {
            type: null,
            length: 0,
            label: "Chưa có"
        };
    }

    /*
     * Bộ ba ngắt chuỗi Tài/Xỉu.
     */
    const first =
        history[0];

    if (
        first.resultType ===
        "TRIPLE"
    ) {
        return {
            type: "TRIPLE",
            length: 1,
            label: "Bộ ba"
        };
    }

    let length = 0;

    for (const item of history) {
        if (
            item.resultType !==
            first.resultType
        ) {
            break;
        }

        length += 1;
    }

    return {
        type: first.resultType,
        length,
        label:
            `${icResultLabel(
                first.resultType
            )} ×${length}`
    };
}

function icCalculateConfidence(
    sampleCount
) {
    if (sampleCount < 4) {
        return "Rất ít dữ liệu";
    }

    if (sampleCount < 8) {
        return "Ít dữ liệu";
    }

    if (sampleCount < 15) {
        return "Mức vừa";
    }

    return "Đủ mẫu thống kê";
}

function icTrendLabel(score) {
    if (score >= 68) {
        return "Nghiêng Tài mạnh";
    }

    if (score >= 58) {
        return "Nghiêng Tài";
    }

    if (score <= 32) {
        return "Nghiêng Xỉu mạnh";
    }

    if (score <= 42) {
        return "Nghiêng Xỉu";
    }

    return "Đang cân bằng";
}

function icBuildCommentary(data) {
    if (data.totalSamples < 3) {
        return (
            "Mẫu hiện tại còn ít. " +
            "IC chưa đưa ra xu hướng rõ."
        );
    }

    const parts = [];

    if (
        data.trendScore >= 58
    ) {
        parts.push(
            `Chuỗi gần đây đang nghiêng về Tài (${data.taiPercent}%).`
        );
    } else if (
        data.trendScore <= 42
    ) {
        parts.push(
            `Chuỗi gần đây đang nghiêng về Xỉu (${data.xiuPercent}%).`
        );
    } else {
        parts.push(
            "Tần suất Tài và Xỉu hiện khá cân bằng."
        );
    }

    if (
        data.streak.length >= 3
    ) {
        parts.push(
            `Đang có chuỗi ${data.streak.label}.`
        );
    }

    if (
        data.averageTotal >= 12
    ) {
        parts.push(
            `Tổng trung bình đang ở mức cao (${data.averageTotal.toFixed(1)}).`
        );
    } else if (
        data.averageTotal <= 9
    ) {
        parts.push(
            `Tổng trung bình đang ở mức thấp (${data.averageTotal.toFixed(1)}).`
        );
    }

    if (
        data.triplePercent >= 15
    ) {
        parts.push(
            `Bộ ba chiếm ${data.triplePercent}% số mẫu gần nhất.`
        );
    }

    return parts.join(" ");
}

/* =========================================================
   RENDER
========================================================= */

function icRender() {
    const analysis =
        icCalculateAnalysis();

    icRenderSequence();

    icSetText(
        "ic-tai-percent",
        `${analysis.taiPercent}%`
    );

    icSetText(
        "ic-xiu-percent",
        `${analysis.xiuPercent}%`
    );

    icSetText(
        "ic-current-streak",
        analysis.streakLabel
    );

    icSetText(
        "ic-average-total",
        analysis.averageTotal === null
            ? "-"
            : analysis.averageTotal.toFixed(1)
    );

    icSetText(
        "ic-trend-label",
        analysis.trendLabel
    );

    icSetText(
        "ic-confidence-label",
        analysis.confidenceLabel
    );

    icSetText(
        "ic-sample-count",
        `${analysis.totalSamples} phiên`
    );

    icSetText(
        "ic-commentary-text",
        analysis.commentary
    );

    const pointer =
        icGetElement(
            "ic-trend-pointer"
        );

    if (pointer) {
        pointer.style.left =
            `${analysis.trendScore}%`;
    }
}

function icRenderSequence() {
    const container =
        icGetElement(
            "ic-history-sequence"
        );

    if (!container) {
        return;
    }

    container.innerHTML = "";

    const items =
        IC_STATE.history.slice(
            0,
            IC_CONFIG.MAX_VISIBLE_RESULTS
        );

    if (items.length === 0) {
        for (
            let index = 0;
            index < 12;
            index += 1
        ) {
            const chip =
                document.createElement(
                    "span"
                );

            chip.className =
                "ic-result-chip";

            chip.textContent = "-";

            container.appendChild(
                chip
            );
        }

        return;
    }

    items.forEach((item) => {
        const chip =
            document.createElement(
                "span"
            );

        let modifier = "";

        if (
            item.resultType === "TAI"
        ) {
            modifier = "tai";
        } else if (
            item.resultType === "XIU"
        ) {
            modifier = "xiu";
        } else {
            modifier = "triple";
        }

        chip.className =
            `ic-result-chip ic-result-chip--${modifier}`;

        chip.textContent =
            item.resultType === "TAI"
                ? "T"
                : item.resultType === "XIU"
                    ? "X"
                    : "B";

        chip.title =
            `${item.resultLabel} · ` +
            `${item.diceValues.join("-")} · ` +
            `Tổng ${item.total}`;

        container.appendChild(
            chip
        );
    });
}

function icSetStatus(
    text,
    type
) {
    const element =
        icGetElement(
            "ic-analysis-status"
        );

    if (!element) {
        return;
    }

    element.textContent = text;

    element.classList.remove(
        "ic-analysis__status--loading",
        "ic-analysis__status--error"
    );

    if (type === "loading") {
        element.classList.add(
            "ic-analysis__status--loading"
        );
    }

    if (type === "error") {
        element.classList.add(
            "ic-analysis__status--error"
        );
    }
}

/* =========================================================
   UTILITIES
========================================================= */

function icResultLabel(type) {
    if (type === "TAI") {
        return "Tài";
    }

    if (type === "XIU") {
        return "Xỉu";
    }

    if (type === "TRIPLE") {
        return "Bộ ba";
    }

    return type;
}

/* =========================================================
   KHỞI ĐỘNG
========================================================= */

function initializeIcSoiCau() {
    if (
        !icGetElement(
            "ic-soi-cau"
        )
    ) {
        console.warn(
            "[IC SOI CAU] Không tìm thấy giao diện IC."
        );
        return;
    }

    icLoadHistory();
    icRender();

    icSetStatus(
        "Đang kết nối",
        "loading"
    );

    icFetchCurrentRound();

    IC_STATE.timerId =
        window.setInterval(
            icFetchCurrentRound,
            IC_CONFIG.POLL_INTERVAL_MS
        );

    console.info(
        "[IC SOI CAU] Đã khởi động."
    );
}

window.addEventListener(
    "beforeunload",
    () => {
        if (IC_STATE.timerId) {
            window.clearInterval(
                IC_STATE.timerId
            );
        }
    }
);

document.addEventListener(
    "DOMContentLoaded",
    initializeIcSoiCau
);