// retoor <retoor@molodetz.nl>

import { Component } from "./Component.js";
import { Http } from "../Http.js";
import { Poller } from "../Poller.js";

const IDLE_INTERVAL_MS = 15000;
const ACTIVE_INTERVAL_MS = 4000;
const ACTIVE_STATES = ["pending", "running"];

export class AppIsslop extends Component {
    connectedCallback() {
        this._render();
        this._form = this.querySelector("[data-isslop-form]");
        this._input = this.querySelector("[data-isslop-url]");
        this._button = this.querySelector("[data-isslop-run]");
        this._error = this.querySelector("[data-isslop-error]");
        this._list = this.querySelector("[data-isslop-list]");
        this._empty = this.querySelector("[data-isslop-empty]");
        this._form.addEventListener("submit", (event) => this._submit(event));
        this._poller = new Poller(() => this._refresh(), IDLE_INTERVAL_MS, { pauseHidden: true });
    }

    disconnectedCallback() {
        if (this._poller) this._poller.stop();
    }

    _render() {
        this.innerHTML = `
            <section class="isslop-form-card">
                <form class="isslop-form" data-isslop-form autocomplete="off" aria-label="Analyze a source">
                    <div class="isslop-form-row">
                        <input type="url" name="url" class="isslop-input" data-isslop-url
                               placeholder="https://github.com/owner/repository or https://example.com"
                               required aria-required="true" maxlength="2048"
                               aria-label="Repository or website URL to classify">
                        <button type="submit" class="btn btn-primary isslop-run-btn" data-isslop-run>Classify</button>
                    </div>
                    <p class="isslop-form-error" data-isslop-error hidden role="alert"></p>
                </form>
            </section>
            <section class="isslop-history" aria-label="My analyses">
                <h2 class="isslop-history-title">My analyses</h2>
                <p class="isslop-history-empty" data-isslop-empty>No analyses yet. Submit a repository or website above.</p>
                <ul class="isslop-history-list" data-isslop-list></ul>
            </section>
        `;
    }

    async _submit(event) {
        event.preventDefault();
        const url = this._input.value.trim();
        if (!url) return;
        this._button.disabled = true;
        this._error.hidden = true;
        try {
            const result = await Http.sendForm("/tools/isslop/run", { url });
            window.location.href = result.report_url;
        } catch (error) {
            this._error.textContent = error.message || "Could not start the analysis.";
            this._error.hidden = false;
            this._button.disabled = false;
        }
    }

    async _refresh() {
        let payload;
        try {
            payload = await Http.getJson("/tools/isslop/list");
        } catch (error) {
            return;
        }
        const analyses = payload.analyses || [];
        this._empty.hidden = analyses.length > 0;
        this._list.replaceChildren(...analyses.map((row) => this._row(row)));
        const busy = analyses.some((row) => ACTIVE_STATES.includes(row.status));
        const interval = busy ? ACTIVE_INTERVAL_MS : IDLE_INTERVAL_MS;
        if (interval !== this._interval) {
            this._interval = interval;
            this._poller.stop();
            this._poller = new Poller(() => this._refresh(), interval, { pauseHidden: true, immediate: false });
        }
    }

    _row(analysis) {
        const item = document.createElement("li");
        item.className = "isslop-history-item";
        const link = document.createElement("a");
        link.className = "isslop-history-link";
        link.href = analysis.report_url;
        const grade = document.createElement("span");
        const gradeValue = analysis.grade || (ACTIVE_STATES.includes(analysis.status) ? "…" : "?");
        grade.className = `isslop-grade-badge isslop-grade-${(analysis.grade || "pending").toLowerCase()}`;
        grade.textContent = gradeValue;
        const meta = document.createElement("span");
        meta.className = "isslop-history-meta";
        const source = document.createElement("span");
        source.className = "isslop-history-source";
        source.textContent = analysis.source_url;
        const detail = document.createElement("span");
        detail.className = "isslop-history-detail";
        detail.textContent = this._detailText(analysis);
        if (analysis.created_at) {
            const when = document.createElement("time");
            when.dateTime = analysis.created_at;
            when.setAttribute("data-dt", "");
            when.setAttribute("data-dt-mode", "ago");
            detail.append(" · ", when);
        }
        meta.append(source, detail);
        link.append(grade, meta);
        item.appendChild(link);
        return item;
    }

    _detailText(analysis) {
        if (analysis.status === "failed") return `failed: ${analysis.error || "unknown error"}`;
        if (ACTIVE_STATES.includes(analysis.status)) return analysis.status;
        const parts = [];
        if (analysis.category) parts.push(analysis.category);
        if (analysis.human_percent !== null && analysis.human_percent !== undefined) {
            parts.push(`${analysis.human_percent}% human`);
        }
        if (analysis.files_analyzed) parts.push(`${analysis.files_analyzed} files`);
        return parts.join(" · ");
    }
}

customElements.define("dp-isslop", AppIsslop);
