// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { SeoProgressSocket } from "./SeoProgressSocket.js";

const STATUS_LABEL = {
    pass: "pass",
    warn: "warn",
    fail: "fail",
    info: "info",
    skip: "skip",
};

export class SeoDiagnostics {
    constructor() {
        this.root = document.querySelector("[data-seo-tool]");
        if (!this.root) return;
        this.form = this.root.querySelector("[data-seo-form]");
        this.modeSelect = this.root.querySelector("[data-seo-mode]");
        this.pagesField = this.root.querySelector("[data-seo-pages]");
        this.errorBox = this.root.querySelector("[data-seo-error]");
        this.live = this.root.querySelector("[data-seo-live]");
        this.statusText = this.root.querySelector("[data-seo-status]");
        this.countText = this.root.querySelector("[data-seo-count]");
        this.bar = this.root.querySelector("[data-seo-bar]");
        this.log = this.root.querySelector("[data-seo-log]");
        this.report = this.root.querySelector("[data-seo-report]");
        this.socket = null;
        this.uid = null;
        this._bind();
    }

    _bind() {
        this.modeSelect.addEventListener("change", () => this._syncMode());
        this._syncMode();
        this.form.addEventListener("submit", (event) => {
            event.preventDefault();
            this._start();
        });
    }

    _syncMode() {
        const sitemap = this.modeSelect.value === "sitemap";
        this.pagesField.hidden = !sitemap;
    }

    async _start() {
        this._setError("");
        const url = this.form.url.value.trim();
        if (!url) return;
        const params = {
            url,
            mode: this.modeSelect.value,
            max_pages: this.form.max_pages ? this.form.max_pages.value : 10,
        };
        this._resetLive();
        try {
            const data = await Http.send("/tools/seo/run", params);
            this.uid = data.uid;
            this._watch(data.uid);
        } catch (error) {
            this._setError(error.message || "Could not start the audit.");
            this.live.hidden = true;
        }
    }

    _resetLive() {
        if (this.socket) this.socket.close();
        this.report.hidden = true;
        this.report.querySelector("[data-seo-categories]").innerHTML = "";
        this.report.querySelector("[data-seo-checks]").innerHTML = "";
        this.live.hidden = false;
        this.log.innerHTML = "";
        this.bar.style.width = "0%";
        this.countText.textContent = "";
        this.statusText.textContent = "Starting…";
        this.form.querySelector("[data-seo-run]").disabled = true;
    }

    _watch(uid) {
        this.socket = new SeoProgressSocket(uid, {
            onMessage: (frame) => this._frame(frame),
            onClose: () => {},
        });
        this.socket.connect();
    }

    _frame(frame) {
        const type = frame.type;
        if (type === "stage") {
            this.statusText.textContent = frame.message || "Working…";
        } else if (type === "target") {
            const total = (frame.urls || []).length;
            this.countText.textContent = total ? `0 / ${total} pages` : "";
            this.statusText.textContent = `Auditing ${frame.url}`;
        } else if (type === "progress") {
            const total = frame.total || 1;
            const done = frame.done || 0;
            this.bar.style.width = `${Math.round((done / total) * 100)}%`;
            this.countText.textContent = `${done} / ${total} pages`;
            if (frame.message) this.statusText.textContent = frame.message;
        } else if (type === "page_loaded") {
            this.bar.style.width = `${Math.round((frame.done / frame.total) * 100)}%`;
            this.countText.textContent = `${frame.done} / ${frame.total} pages`;
            this._appendLog(`${frame.status} ${frame.url}`);
        } else if (type === "report_ready") {
            this.statusText.textContent = "Compiling report…";
        } else if (type === "done") {
            this.bar.style.width = "100%";
            this.statusText.textContent = "Done";
            this.form.querySelector("[data-seo-run]").disabled = false;
            const reportUrl = frame.report_url || `/tools/seo/${this.uid}/report`;
            if (frame.report && Object.keys(frame.report).length) {
                this._renderReport(frame.report, reportUrl);
            } else {
                this._loadReport(reportUrl);
            }
        } else if (type === "failed") {
            this.statusText.textContent = "Failed";
            this._setError(frame.message || frame.error || "The audit failed.");
            this.form.querySelector("[data-seo-run]").disabled = false;
        }
    }

    _appendLog(text) {
        const item = document.createElement("li");
        item.textContent = text;
        this.log.prepend(item);
    }

    async _loadReport(url) {
        this.form.querySelector("[data-seo-run]").disabled = false;
        let report;
        try {
            report = await Http.getJson(url);
        } catch (error) {
            this._setError("Could not load the report.");
            return;
        }
        this._renderReport(report, url);
    }

    _renderReport(report, url) {
        this.report.hidden = false;
        this.report.querySelector("[data-seo-score]").textContent = report.score ?? 0;
        const gauge = this.report.querySelector("[data-seo-gauge]");
        gauge.className = `seo-gauge seo-grade-${(report.grade || "f").toLowerCase()}`;
        this.report.querySelector("[data-seo-grade]").textContent = report.grade || "";
        this.report.querySelector("[data-seo-target]").textContent = report.target || "";
        this.report.querySelector("[data-seo-report-link]").href = url.replace(/\?.*$/, "");
        const counts = report.counts || {};
        this.report.querySelector("[data-seo-counts]").innerHTML = ["pass", "warn", "fail", "info"]
            .map((key) => `<span class="seo-chip seo-chip-${key}">${counts[key] || 0} ${key}</span>`)
            .join("");
        this._renderCategories(report.categories || {});
        this._renderChecks(report.categories || {}, report.checks || [], report.page_count || 1);
    }

    _renderCategories(categories) {
        const host = this.report.querySelector("[data-seo-categories]");
        host.innerHTML = Object.entries(categories)
            .map(([name, meta]) => {
                const score = meta.score === null || meta.score === undefined ? "" : `<span class="seo-cat-score">${meta.score}</span>`;
                return `<div class="seo-cat-pill"><span class="seo-cat-name">${this._title(name)}</span>${score}</div>`;
            })
            .join("");
    }

    _renderChecks(categories, checks, pageCount) {
        const host = this.report.querySelector("[data-seo-checks]");
        const groups = Object.keys(categories).map((cat) => {
            const items = checks.filter((c) => c.category === cat);
            const rows = items.map((check) => this._checkRow(check, pageCount)).join("");
            return `<section class="seo-check-group"><h2>${this._title(cat)}</h2>${rows}</section>`;
        });
        host.innerHTML = groups.join("");
    }

    _checkRow(check, pageCount) {
        const status = STATUS_LABEL[check.status] || check.status;
        const url = check.url && pageCount > 1 ? `<span class="seo-check-url">${this._escape(check.url)}</span>` : "";
        const value = check.value ? `<span class="seo-check-value">${this._escape(check.value)}</span>` : "";
        const rec = check.recommendation ? `<span class="seo-check-rec">${this._escape(check.recommendation)}</span>` : "";
        return `<div class="seo-check seo-check-${check.status}">
            <span class="seo-check-status">${status}</span>
            <div class="seo-check-body">
                <span class="seo-check-title">${this._escape(check.title)} ${url}</span>
                ${value}${rec}
            </div>
            <span class="seo-check-severity seo-sev-${check.severity}">${check.severity}</span>
        </div>`;
    }

    _title(text) {
        return String(text).replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
    }

    _escape(text) {
        const div = document.createElement("div");
        div.textContent = text == null ? "" : String(text);
        return div.innerHTML;
    }

    _setError(message) {
        if (!this.errorBox) return;
        this.errorBox.textContent = message;
        this.errorBox.hidden = !message;
    }
}
