const fs = require('fs');
const path = require('path');

const dir = path.dirname(__filename);
const editPath = path.join(dir, 'edit.js');
const newModalPath = path.join(dir, '_modal_new.js');

const editContent = fs.readFileSync(editPath, 'utf8');
const newModal = fs.readFileSync(newModalPath, 'utf8');

const lines = editContent.split(/\r?\n/);
console.log('Original lines:', lines.length);

// Find the line that starts buildModalHeader
let startLine = -1;
let endLine = -1;

for (let i = 0; i < lines.length; i++) {
    if (lines[i].includes('const buildModalHeader') && lines[i].includes('el(')) {
        startLine = i;
        console.log('Found buildModalHeader at line', i + 1, ':', lines[i].trim().substring(0, 50));
    }
    if (lines[i].includes('const selectionModal') && lines[i].includes('isModalOpen')) {
        // Find the closing of selectionModal - it ends with `      );`
        for (let j = i + 1; j < lines.length; j++) {
            if (lines[j].trim() === ');' && lines[j].startsWith('      ')) {
                endLine = j;
                break;
            }
        }
        console.log('Found selectionModal end at line', endLine + 1);
    }
}

if (startLine === -1 || endLine === -1) {
    console.error('Could not find boundaries! startLine:', startLine, 'endLine:', endLine);
    process.exit(1);
}

// Splice: keep lines before startLine, insert new modal, keep lines after endLine
const before = lines.slice(0, startLine);
const after = lines.slice(endLine + 1);
const newContent = before.join('\n') + '\n' + newModal + '\n' + after.join('\n');

fs.writeFileSync(editPath, newContent, 'utf8');

const newLines = newContent.split('\n');
console.log('New lines:', newLines.length);
console.log('Removed', (endLine - startLine + 1), 'lines, inserted new modal code');
console.log('Done!');
