// auto-split module

const GITLAB = {
    host: (window.GITLAB && window.GITLAB.host) || "https://git.steinert.cc",
    projectId: (window.GITLAB && window.GITLAB.projectId) || "qa/templates",
    ref: (window.GITLAB && window.GITLAB.ref) || "main",
    path: (window.GITLAB && window.GITLAB.path) || "templates",
    token: (window.GITLAB && window.GITLAB.token) || ""
};

// auto-split module


function glHeaders() {
    const h = {
        "Accept": "application/json"
    };
    if (GITLAB.token && GITLAB.token.trim()) h["PRIVATE-TOKEN"] = GITLAB.token.trim();
    return h;
}


async function listGitlabTemplates() {
    const url = `${GITLAB.host}/api/v4/projects/${encodeURIComponent(GITLAB.projectId)}/repository/tree?path=${encodeURIComponent(GITLAB.path)}&ref=${encodeURIComponent(GITLAB.ref)}&per_page=100`;
    const r = await fetch(url, {
        headers: glHeaders()
    });
    if (!r.ok) throw new Error(`GitLab Tree ${r.status}`);
    const items = await r.json();
    return items.filter(it => it.type === "blob" && /\.ya?ml$/i.test(it.name)).map(it => ({
        name: it.name,
        path: it.path
    }));
}


async function fetchGitlabFileRaw(filePath) {
    const url = `${GITLAB.host}/api/v4/projects/${encodeURIComponent(GITLAB.projectId)}/repository/files/${encodeURIComponent(filePath)}/raw?ref=${encodeURIComponent(GITLAB.ref)}`;
    const r = await fetch(url, {
        headers: glHeaders(),
        cache: "no-store"
    });
    if (!r.ok) throw new Error(`GitLab Raw ${r.status}`);
    return await r.text();
}


async function populateGitlabDropdown() {
    const sel = els.gitlabTplSelect,
        tag = els.gitlabTplStatus;
    if (!sel) return;
    sel.innerHTML = `<option value="">— GitLab-Templates laden —</option>`;
    try {
        tag && (tag.textContent = "GitLab: lade Liste…");
        const files = await listGitlabTemplates();
        files.forEach(f => {
            const opt = document.createElement('option');
            opt.value = f.path;
            opt.textContent = f.name;
            sel.appendChild(opt);
        });
        tag && (tag.textContent = files.length ? `GitLab: ${files.length} Vorlage(n)` : "GitLab: keine YAMLs gefunden");
    } catch (e) {
        tag && (tag.textContent = "GitLab: Fehler");
        console.error("[GitLab] list failed:", e);
        alert("GitLab-Liste konnte nicht geladen werden: " + e.message);
    }
}


function loadYAMLText(yamlText) {
    const obj = parseTemplate(yamlText);
    if (!obj || !Array.isArray(obj.steps)) throw new Error('Ungültige Vorlage: "steps" fehlt.');
    // Normalisieren: type→kind, default "step"
    obj.steps = obj.steps.map(s => {
        const k = s.kind || s.type || 'step';
        if (k === 'group') return {
            kind: 'group',
            title: s.title || s.name || '',
            collapsed: !!s.collapsed
        };
        return {
            kind: 'step',
            id: s.id,
            title: s.title,
            expected: s.expected,
            required: !!s.required,
            status: s.status || '',
            comment: s.comment || '',
            evidence: s.evidence || ''
        };
    });
    template = obj;
    if (els.tplName) els.tplName.textContent = obj.name || '—';
    if (obj.module) els.module.value = obj.module;
    if (obj.module_version) els.moduleVersion.value = obj.module_version;
    if (obj.pbx_version) els.pbxVersion.value = obj.pbx_version;
    renderSteps(obj.steps);
    if (els.statusTag) els.statusTag.textContent = 'Vorlage geladen';
    updateAutosave();
}

