// ── Relations (Master‑Detail) ────────────────────────────────────────
async function loadAndDrawRelations() {
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/tables/relations`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const text = await res.text();
        let data;
        try { data = JSON.parse(text); } catch (e) { console.error('Invalid JSON'); return; }
        if (data.success) {
            window.allRelations = data.relations;
            drawRelationArrows();
            loadAndDrawBadges();
        }
    } catch (err) { console.error('Could not load relations', err); }
}

function drawRelationArrows() {
    const svg = document.getElementById('relationsSvg');
    if (!svg) return;
    svg.innerHTML = '';
    const container = document.getElementById('selectedTablesContainer');
    const hint = document.getElementById('relationHint');
    let drawnRelations = 0;

    // Ensure arrowhead marker exists
    if (!document.getElementById('arrowhead')) {
        const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
        const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
        marker.id = 'arrowhead';
        marker.setAttribute('viewBox', '0 0 10 10');
        marker.setAttribute('refX', '9');
        marker.setAttribute('refY', '5');
        marker.setAttribute('markerWidth', '6');
        marker.setAttribute('markerHeight', '6');
        marker.setAttribute('orient', 'auto');
        const arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        arrow.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z');
        arrow.setAttribute('fill', 'currentColor');
        marker.appendChild(arrow);
        defs.appendChild(marker);
        svg.appendChild(defs);
    }

    window.allRelations.forEach(rel => {
        const masterCard = container.querySelector(`.table-card[data-table="${rel.master_table}"]`);
        const detailCard = container.querySelector(`.table-card[data-table="${rel.detail_table}"]`);
        if (!masterCard || !detailCard) return;

        const mRect = masterCard.getBoundingClientRect();
        const dRect = detailCard.getBoundingClientRect();
        const cRect = container.getBoundingClientRect();
        const x1 = mRect.right - cRect.left;
        const y1 = mRect.top + mRect.height / 2 - cRect.top;
        const x2 = dRect.left - cRect.left;
        const y2 = dRect.top + dRect.height / 2 - cRect.top;
        const dx = Math.abs(x2 - x1) * 0.5;

        const d = `M${x1},${y1} C${x1 + dx},${y1} ${x2 - dx},${y2} ${x2},${y2}`;
        const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
        group.classList.add('relation-arrow-group');
        group.setAttribute('data-rel-id', rel.id);

        const hitPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        hitPath.setAttribute('d', d);
        hitPath.setAttribute('fill', 'none');
        hitPath.setAttribute('stroke', 'transparent');
        hitPath.setAttribute('stroke-width', '16');
        hitPath.setAttribute('data-rel-id', rel.id);
        hitPath.classList.add('relation-arrow-hit');
        hitPath.style.cursor = 'pointer';
        hitPath.style.pointerEvents = 'stroke';

        const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute('d', d);
        path.setAttribute('fill', 'none');
        path.setAttribute('stroke', 'currentColor');
        path.setAttribute('stroke-width', '2.5');
        path.setAttribute('marker-end', 'url(#arrowhead)');
        path.setAttribute('data-rel-id', rel.id);
        path.classList.add('relation-arrow-line');
        path.style.cursor = 'pointer';
        path.style.pointerEvents = 'none';

        group.appendChild(hitPath);
        group.appendChild(path);
        svg.appendChild(group);
        drawnRelations++;
    });

    if (hint) hint.classList.toggle('d-none', drawnRelations === 0);
}

function openRelationModal(source, target) {
    document.getElementById('relMasterTable').value = source.table;
    document.getElementById('relDetailTable').value = target.table;
    populateFieldSelect(source.table, document.getElementById('relMasterField'), source.field);
    populateFieldSelect(target.table, document.getElementById('relDetailField'), target.field);
    document.getElementById('relDispInline').checked = true;
    document.getElementById('relAddForeignKey').checked = false;
    document.getElementById('relOnDeleteAction').value = 'CASCADE';
    document.getElementById('relOnUpdateAction').value = 'CASCADE';
    document.getElementById('relShowDetailsLinks').checked = true;
    document.getElementById('relDetailsLinkSingle').checked = true;
    document.getElementById('relHideDetailsNoRecords').checked = false;
    document.getElementById('relShowProceedLink').checked = true;
    document.getElementById('relHideIfEmpty').checked = false;
    document.getElementById('relDisplayChildCount').checked = false;
    const badgeColorInput = document.getElementById('relBadgeColor');
    badgeColorInput.value = window.tablesThemeColorInput?.('--tables-accent', badgeColorInput) || badgeColorInput.value;
    const colorRow = document.getElementById('relBadgeColorRow');
    if (colorRow) colorRow.style.display = 'none';
    document.getElementById('relDisplayOrder').value = nextRelationDisplayOrder(source.table);
    const relWhere = document.getElementById('relWhere'); if (relWhere) relWhere.value = '';
    document.querySelectorAll('#relationModal .master-page-check, #relationModal .detail-page-check, #relationModal .page-check').forEach(cb => cb.checked = false);
    new bootstrap.Modal(document.getElementById('relationModal')).show();
}

function nextRelationDisplayOrder(masterTable) {
    const relations = Array.isArray(window.allRelations) ? window.allRelations : [];
    const orders = relations
        .filter(rel => rel && rel.master_table === masterTable)
        .map(rel => Number.parseInt(rel.display_order ?? 0, 10))
        .filter(Number.isFinite);
    return orders.length ? Math.max(...orders) + 10 : 10;
}

function relationPagesFrom(rel, key, fallback = []) {
    return Array.isArray(rel?.[key]) ? rel[key] : fallback;
}

async function populateFieldSelect(tableName, selectElement, selectedField = null) {
    selectElement.innerHTML = '<option value="">Loading...</option>';
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/tables/details/${tableName}`);
        const data = await res.json();
        if (data.success) {
            selectElement.innerHTML = '';
            data.columns.forEach(col => {
                const option = document.createElement('option');
                option.value = col.COLUMN_NAME;
                option.textContent = col.COLUMN_NAME;
                if (col.COLUMN_NAME === selectedField) option.selected = true;
                selectElement.appendChild(option);
            });
        }
    } catch (err) {
        selectElement.innerHTML = '<option value="">Error</option>';
    }
}

function openEditRelationModal(rel) {
    if (!rel || !rel.id) return;

    document.getElementById('editRelId').value = rel.id;
    document.getElementById('editRelMasterTable').value = rel.master_table || '';
    document.getElementById('editRelDetailTable').value = rel.detail_table || '';

    populateFieldSelect(rel.master_table, document.getElementById('editRelMasterField'), rel.master_field);
    populateFieldSelect(rel.detail_table, document.getElementById('editRelDetailField'), rel.detail_field);

    const display = rel.display_option || 'inline';
    const displayRadio = document.querySelector(`input[name="editRelDisplayOption"][value="${display}"]`);
    if (displayRadio) displayRadio.checked = true;

    document.getElementById('editRelHideIfEmpty').checked = !!rel.hide_if_empty;
    document.getElementById('editRelShowDetailsLinks').checked = rel.show_details_links !== false;
    const linkMode = rel.details_link_mode || 'single';
    const linkModeRadio = document.querySelector(`input[name="editRelDetailsLinkMode"][value="${linkMode}"]`);
    if (linkModeRadio) linkModeRadio.checked = true;
    document.getElementById('editRelHideDetailsNoRecords').checked = !!rel.hide_details_no_records;
    document.getElementById('editRelShowProceedLink').checked = rel.show_proceed_link !== false;
    document.getElementById('editRelAddForeignKey').checked = !!rel.add_foreign_key;
    document.getElementById('editRelOnDeleteAction').value = rel.on_delete_action || 'CASCADE';
    document.getElementById('editRelOnUpdateAction').value = rel.on_update_action || 'CASCADE';
    document.getElementById('editRelDisplayChildCount').checked = !!rel.display_child_count;
    const badgeColorInput = document.getElementById('editRelBadgeColor');
    badgeColorInput.value = rel.count_badge_color
        || window.tablesThemeColorInput?.('--tables-accent', badgeColorInput)
        || badgeColorInput.value;
    document.getElementById('editRelDisplayOrder').value = Number.parseInt(rel.display_order ?? 10, 10) || 10;
    const editRelWhere = document.getElementById('editRelWhere'); if (editRelWhere) editRelWhere.value = rel.where || '';

    const colorRow = document.getElementById('editRelBadgeColorRow');
    if (colorRow) colorRow.style.display = rel.display_child_count ? 'flex' : 'none';

    const legacyPages = Array.isArray(rel.pages) ? rel.pages : [];
    const masterPages = relationPagesFrom(rel, 'master_pages', legacyPages);
    const detailPages = relationPagesFrom(rel, 'detail_pages', rel.show_master_on_detail ? ['view'] : []);
    const pages = relationPagesFrom(rel, 'pages', []);
    document.querySelectorAll('#editRelationModal .edit-master-page-check').forEach(cb => {
        cb.checked = masterPages.includes(cb.value);
    });
    document.querySelectorAll('#editRelationModal .edit-detail-page-check').forEach(cb => {
        cb.checked = detailPages.includes(cb.value);
    });
    document.querySelectorAll('#editRelationModal .edit-page-check').forEach(cb => {
        cb.checked = pages.includes(cb.value);
    });

    new bootstrap.Modal(document.getElementById('editRelationModal')).show();
}

async function loadAndDrawBadges() {
    document.querySelectorAll('.relation-count-badge').forEach(el => el.remove());

    const relations = Array.isArray(window.allRelations) ? window.allRelations : [];
    const badgeRelations = relations.filter(rel => rel && rel.display_child_count);
    if (badgeRelations.length === 0) return;

    await Promise.all(badgeRelations.map(async (rel) => {
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/tables/relation-count/${encodeURIComponent(rel.id)}`);
            const data = await res.json();
            if (!data.success) return;

            const detailCard = document.querySelector(`.table-card[data-table="${rel.detail_table}"]`);
            if (!detailCard) return;

            const title = detailCard.querySelector('.card-title');
            if (!title) return;

            const badge = document.createElement('span');
            badge.className = 'relation-count-badge';
            badge.style.backgroundColor = rel.count_badge_color || 'var(--tables-accent)';
            badge.textContent = String(data.count ?? 0);
            badge.title = `${rel.detail_table} child records for relation ${rel.master_table}.${rel.master_field} → ${rel.detail_table}.${rel.detail_field}`;
            title.appendChild(badge);
        } catch (err) {
            // Badge counts are an optional visual aid; avoid noisy console warnings on load.
        }
    }));
}

// Expose globally
window.loadAndDrawRelations = loadAndDrawRelations;
window.drawRelationArrows = drawRelationArrows;
window.openRelationModal = openRelationModal;
window.populateFieldSelect = populateFieldSelect;
window.openEditRelationModal = openEditRelationModal;
window.loadAndDrawBadges = loadAndDrawBadges;
