import * as XLSX from 'xlsx';

export function xlsxToWorkbookData(arrayBuffer) {
    const wb = XLSX.read(arrayBuffer, { type: 'array', cellStyles: true, sheetStubs: true });

    const sheets = {};
    const sheetOrder = [];

    wb.SheetNames.forEach((sheetName, sheetIndex) => {
        const ws = wb.Sheets[sheetName];
        const sheetId = `sheet_${sheetIndex}`;
        sheetOrder.push(sheetId);

        const cellData = {};
        const ref = ws['!ref'];
        if (!ref) {
            sheets[sheetId] = { id: sheetId, name: sheetName, cellData };
            return;
        }

        const range = XLSX.utils.decode_range(ref);
        for (let r = range.s.r; r <= range.e.r; r++) {
            for (let c = range.s.c; c <= range.e.c; c++) {
                const cellAddress = XLSX.utils.encode_cell({ r, c });
                const cell = ws[cellAddress];
                if (!cell) continue;

                // CellValueType: 1=STRING, 2=NUMBER, 3=BOOLEAN
                let t;
                if (cell.t === 'n') t = 2;
                else if (cell.t === 'b') t = 3;
                else t = 1;

                if (!cellData[r]) cellData[r] = {};
                cellData[r][c] = { v: cell.v !== undefined ? cell.v : (cell.w || ''), t };
            }
        }

        const mergeData = (ws['!merges'] || []).map(m => ({
            startRow: m.s.r,
            startColumn: m.s.c,
            endRow: m.e.r,
            endColumn: m.e.c,
        }));

        sheets[sheetId] = { id: sheetId, name: sheetName, cellData, mergeData };
    });

    return {
        id: 'imported-workbook',
        name: wb.SheetNames[0] || 'Sheet',
        appVersion: '0.18.0',
        locale: 'enUS',
        styles: {},
        sheetOrder,
        sheets,
    };
}
