let currentProfile = null;
let activeTab = "overview";
const manifestCache = new Map();
function element(id) {
    return document.getElementById(id);
}
function record(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value)
        ? value
        : {};
}
function list(value) {
    return Array.isArray(value) ? value : [];
}
function displayValue(value) {
    if (value == null || value === "")
        return "—";
    if (typeof value === "boolean")
        return value ? "Oui" : "Non";
    return String(value);
}
function clear(id) {
    const target = element(id);
    target === null || target === void 0 ? void 0 : target.replaceChildren();
    return target;
}
function addKeyValue(target, label, value) {
    if (!target)
        return;
    const card = document.createElement("div");
    card.className = "sub-profile-ci-item";
    const term = document.createElement("span");
    term.className = "sub-profile-ci-item__label";
    term.textContent = label;
    const detail = document.createElement("span");
    detail.className = "sub-profile-ci-item__value";
    detail.textContent = displayValue(value);
    card.append(term, detail);
    target.appendChild(card);
}
function addTextRows(target, rows, emptyText) {
    if (!target)
        return;
    target.replaceChildren();
    if (!rows.length) {
        const empty = document.createElement("p");
        empty.className = "muted";
        empty.textContent = emptyText;
        target.appendChild(empty);
        return;
    }
    const ul = document.createElement("ul");
    for (const text of rows) {
        const li = document.createElement("li");
        li.textContent = text;
        ul.appendChild(li);
    }
    target.appendChild(ul);
}
function renderOverview(profile) {
    const ci = record(profile.ci_profile);
    const project = record(ci.project);
    const target = clear("subProfileCiOverview");
    const labels = {
        project_id: "ID projet",
        name: "Nom du projet",
        description: "Description",
        author: "Auteur",
        language: "Langue attendue",
        expected_rolls: "Lots prévus",
        expected_images: "Images prévues",
        expected_records: "Records prévus",
        imaging_project_id: "ID projet d'imagerie",
    };
    for (const key of Object.keys(labels)) {
        if (project[key] != null && project[key] !== "")
            addKeyValue(target, labels[key], project[key]);
    }
    for (const raw of list(project.additional_requirements)) {
        const row = record(raw);
        addKeyValue(target, String(row.label || "Exigence"), row.value);
    }
    if (!(target === null || target === void 0 ? void 0 : target.childElementCount))
        addKeyValue(target, "Profil CI", "Aucun détail importé");
}
function fieldCount(configured) {
    if (Array.isArray(configured))
        return configured.length;
    const mapping = record(configured);
    return Object.values(mapping).reduce((total, value) => total + (Array.isArray(value) ? value.length : 0), 0);
}
function renderDoctypeDetails(profile) {
    const target = clear("subProfileCiDoctypeDetails");
    if (!target)
        return;
    const ci = record(profile.ci_profile);
    const profiles = record(ci.doctype_profiles);
    const fieldMapping = record(profile.doctype_fields);
    for (const rawName of list(profile.doc_types)) {
        const name = String(rawName || "").trim();
        if (!name)
            continue;
        const details = record(profiles[name]);
        const card = document.createElement("article");
        card.className = "sub-profile-ci-doctype";
        const title = document.createElement("h4");
        title.textContent = name;
        const meta = document.createElement("p");
        const kind = String(details.kind || "").toLowerCase() === "non_data" ? "Non-Data" : "Data";
        const headerOnly = details.header_key_only ? " · Header Key Only" : "";
        meta.className = "muted";
        meta.textContent = `${kind}${headerOnly} · ${fieldCount(fieldMapping[name])} association(s) de champ`;
        card.append(title, meta);
        const description = String(details.description || "").trim();
        if (description) {
            const paragraph = document.createElement("p");
            paragraph.textContent = description;
            card.appendChild(paragraph);
        }
        const events = list(details.allowed_event_types).map((value) => String(value)).filter(Boolean);
        if (events.length) {
            const eventLine = document.createElement("p");
            eventLine.textContent = `Event Types : ${events.join(", ")}`;
            card.appendChild(eventLine);
        }
        const source = String(details.source_sheet || "").trim();
        if (source) {
            const sourceLine = document.createElement("p");
            sourceLine.className = "muted";
            sourceLine.textContent = `Feuille CI : ${source}`;
            card.appendChild(sourceLine);
        }
        target.appendChild(card);
    }
}
function renderInstructions(profile) {
    const ci = record(profile.ci_profile);
    const special = list(ci.special_instructions)
        .map((raw) => String(record(raw).text || "").trim())
        .filter(Boolean);
    addTextRows(element("subProfileCiSpecialInstructions"), special, "Aucune instruction spéciale importée.");
    const validation = record(ci.validation);
    const validationLines = list(validation.instructions)
        .map((raw) => String(record(raw).text || "").trim())
        .filter(Boolean);
    const requiredFields = list(validation.required_fields)
        .map((raw) => String(record(raw).field_label || record(raw).field_name || "").trim())
        .filter(Boolean);
    if (requiredFields.length) {
        validationLines.push(`Champs à valider : ${requiredFields.join(", ")}`);
    }
    addTextRows(element("subProfileCiValidation"), validationLines, "Aucune règle de validation avant soumission importée.");
}
function renderSources(profile) {
    const ci = record(profile.ci_profile);
    const source = record(ci.source);
    const sourceTarget = clear("subProfileCiSource");
    addKeyValue(sourceTarget, "Fichier CI", source.file_name);
    addKeyValue(sourceTarget, "Importé le", source.imported_at);
    addKeyValue(sourceTarget, "SHA-256", source.sha256);
    addKeyValue(sourceTarget, "Version du profil", ci.schema_version);
    const manifest = record(ci.manifest_summary);
    const manifestTarget = clear("subProfileCiManifestSummary");
    addKeyValue(manifestTarget, "Lots uniques", manifest.entry_count);
    addKeyValue(manifestTarget, "Lots à keyer", manifest.key_count);
    addKeyValue(manifestTarget, "Images prévues", manifest.expected_images);
    addKeyValue(manifestTarget, "Lots Test Key", manifest.test_key_count);
    const assets = record(ci.asset_summary);
    const assetTarget = clear("subProfileCiAssetSummary");
    addKeyValue(assetTarget, "Références visuelles", assets.asset_count);
    const categories = record(assets.categories);
    for (const [category, count] of Object.entries(categories)) {
        addKeyValue(assetTarget, `Référence · ${category}`, count);
    }
}
function renderManifest(entries) {
    const body = clear("subProfileCiManifestBody");
    const status = element("subProfileCiManifestStatus");
    const search = element("subProfileCiManifestSearch");
    const query = String((search === null || search === void 0 ? void 0 : search.value) || "").trim().toLocaleLowerCase();
    const filtered = query
        ? entries.filter((entry) => String(entry.batch_name || "").toLocaleLowerCase().includes(query))
        : entries;
    const visible = filtered.slice(0, 100);
    for (const entry of visible) {
        const tr = document.createElement("tr");
        for (const value of [
            entry.batch_name,
            entry.expected_image_count,
            entry.priority === "test_key" ? "Test Key" : "Key",
            entry.source_sheet,
        ]) {
            const td = document.createElement("td");
            td.textContent = displayValue(value);
            tr.appendChild(td);
        }
        body === null || body === void 0 ? void 0 : body.appendChild(tr);
    }
    if (status) {
        status.textContent = filtered.length > visible.length
            ? `${visible.length} lots affichés sur ${filtered.length}. Affinez la recherche.`
            : `${filtered.length} lot(s) affiché(s).`;
    }
}
async function loadManifest() {
    const id = Number(currentProfile === null || currentProfile === void 0 ? void 0 : currentProfile.id);
    if (!Number.isFinite(id) || id <= 0)
        return;
    if (manifestCache.has(id)) {
        renderManifest(manifestCache.get(id) || []);
        return;
    }
    const status = element("subProfileCiManifestStatus");
    if (status)
        status.textContent = "Chargement des lots du CI…";
    try {
        const response = await fetch(`/api/sub-projects/${id}/ci-manifest`, {
            credentials: "same-origin",
            headers: { Accept: "application/json" },
        });
        const payload = await response.json();
        if (!response.ok || payload.ok === false)
            throw new Error(payload.error || response.statusText);
        const entries = Array.isArray(payload.entries) ? payload.entries : [];
        manifestCache.set(id, entries);
        renderManifest(entries);
    }
    catch (error) {
        if (status)
            status.textContent = error instanceof Error ? error.message : "Chargement impossible";
    }
}
export function activateSubProjectProfileTab(tabName) {
    const wanted = tabName || "overview";
    activeTab = wanted;
    document.querySelectorAll("[data-sub-profile-tab]").forEach((tab) => {
        const active = tab.dataset.subProfileTab === wanted;
        tab.classList.toggle("is-active", active);
        tab.setAttribute("aria-selected", active ? "true" : "false");
    });
    document.querySelectorAll("[data-sub-profile-panel]").forEach((panel) => {
        panel.hidden = panel.dataset.subProfilePanel !== wanted;
    });
    if (wanted === "sources")
        void loadManifest();
}
export function renderSubProjectCiProfile(profile) {
    currentProfile = profile;
    const search = element("subProfileCiManifestSearch");
    if (search)
        search.value = "";
    clear("subProfileCiManifestBody");
    const manifestStatus = element("subProfileCiManifestStatus");
    if (manifestStatus)
        manifestStatus.textContent = "Ouvrez cet onglet pour charger le manifeste.";
    renderOverview(profile);
    renderDoctypeDetails(profile);
    renderInstructions(profile);
    renderSources(profile);
    activateSubProjectProfileTab(activeTab);
}
export function initSubProjectCiProfileTabs() {
    var _a;
    document.querySelectorAll("[data-sub-profile-tab]").forEach((tab) => {
        tab.addEventListener("click", () => activateSubProjectProfileTab(tab.dataset.subProfileTab || "overview"));
    });
    (_a = element("subProfileCiManifestSearch")) === null || _a === void 0 ? void 0 : _a.addEventListener("input", () => {
        const id = Number(currentProfile === null || currentProfile === void 0 ? void 0 : currentProfile.id);
        if (manifestCache.has(id))
            renderManifest(manifestCache.get(id) || []);
    });
    activateSubProjectProfileTab("overview");
}
