const appVersion = '1.7.0';

const localStorageName = "matrix3DData"
const matrixDataFromStorage = JSON.parse(localStorage.getItem(localStorageName));
const localMatrixVersion = localStorage.getItem(localStorageName + '-matrixVersion');


const faucetWorkbookName = 'faucets'
const faucetTargetSheetName = 'allskus'
const faucetfullSheetName = faucetWorkbookName + '-' + faucetTargetSheetName
const localProdInfoStorageName = "prodInfoData"
const prodInfoDataFromStorage = JSON.parse(localStorage.getItem(localProdInfoStorageName));
const localProdInfoVersion = localStorage.getItem(localProdInfoStorageName + '-prodInfoVersion');

const accWorkbookName = 'acc'
const accTargetSheetName = 'allskus'
const accfullSheetName = accWorkbookName + '-' + accTargetSheetName
/*const localAccInfoStorageName = "accInfoData"
const accInfoDataFromStorage = JSON.parse(localStorage.getItem(localAccInfoStorageName));*/
/*const localAccInfoVersion = localStorage.getItem(localAccInfoStorageName + '-accInfoVersion');*/

const cfgWorkbookName = 'cfg'
const cfgTargetSheetName = 'allskus'
const cfgfullSheetName = cfgWorkbookName + '-' + cfgTargetSheetName
/*const localCfgInfoStorageName = "cfgInfoData"
const cfgInfoDataFromStorage = JSON.parse(localStorage.getItem(localCfgInfoStorageName));*/
/*
const localCfgInfoVersion = localStorage.getItem(localCfgInfoStorageName + '-cfgInfoVersion');
*/


function ctaElm(msg, btnMsg, callback) {
  const ctaContainer = document.getElementById('cta-container')
  const ctaElm = document.createElement('h3')
  ctaElm.id = 'cta-alert-elm'
  ctaElm.innerText = msg
  const ctaButton = document.createElement('button')
  ctaButton.id = 'cta-button'
  ctaButton.innerText = btnMsg
  ctaButton.onclick = callback
  ctaContainer.appendChild(ctaElm)
  ctaContainer.appendChild(ctaButton)
}
const cleanStr = (str) => {
  if (!str) return false
  return str.toLowerCase().replaceAll(' ', '')
}

const matrixData = matrixDataFromStorage ? matrixDataFromStorage : {}
const prodInfoData = prodInfoDataFromStorage ? prodInfoDataFromStorage : {}
console.log('matrixData', matrixData)
console.log('prodInfoData', prodInfoData)
const userInput = {
  sku: null,
  skuDescription: null,
  roomSelected: null,
  platformSelected: null,
  podStyleSelected: null
}
const creatButtonIndicator = '--PRIMARY'
const trayLinkKey = 'TRAY LINK'


///////////////////////////////////////
// POD STYLE HANDLER
const podStyleButtonHandler = (e) => {
  e.preventDefault()
  const podStyleOutputContainer = document.getElementById('pod-style-output-container')
  podStyleOutputContainer.innerHTML = ''
  userInput.podStyleSelected = e.target.value
  const outputObj = {}

  ///////////////////////////////
  // Compile the pod family list
  matrixData.matrix.forEach(row => {
    if (!Object.hasOwn(outputObj, row.ROOM)) outputObj[row.ROOM] = {}
    outputObj[row.ROOM][row['PLATFORM']] = row[userInput.podStyleSelected]

  })

  ///////////////////////////////
  // Build & Add the pod family title
  const podStyleTitle = document.createElement('h2')
  podStyleTitle.innerText = userInput.podStyleSelected
  podStyleOutputContainer.append(podStyleTitle)


  ///////////////////////////////
  // Build Pod Family Display
  const platformOptions = []
  for (const [key, value] of Object.entries(outputObj)) {
    const roomGroupElm = document.createElement('div')
    roomGroupElm.id = key + '-group-container'
    roomGroupElm.classList.add('group-container')
    const groupTitle = document.createElement('h3')
    groupTitle.innerText = key

    roomGroupElm.append(groupTitle)

    for (const [platformKey, platformValue] of Object.entries(value)) {

      if (platformKey) platformOptions.push(platformKey)
      const platformElm = document.createElement('div')
      platformElm.id = platformKey + '-platform-container'
      platformElm.classList.add('platform-container')
      const platformTitle = document.createElement('h3')
      platformTitle.innerText = platformKey
      const platformPod = document.createElement('p')
      platformPod.innerText = platformValue

      platformElm.append(platformTitle)
      platformElm.append(platformPod)
      roomGroupElm.append(platformElm)
    }

    podStyleOutputContainer.append(roomGroupElm)
  }
}

///////////////////////////////////////
// CREATE THE POD DISPLAY
const generatePodEntryDisplayData = (sku, room, skuDesc, podStyleSelected, platformSelected) => {

  const tableID = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);

  const createElm = (elmType, id, classesString, innerTextString) => {
    const newElm = document.createElement(elmType)
    if (id) newElm.id = id
    if (classesString) {
      const classesArray = classesString.split(' ')
      classesArray.forEach(classText => newElm.classList.add(classText.replaceAll(' ', '')))
    }
    if (innerTextString) newElm.innerText = innerTextString
    return newElm
  }


  const podEntryDisplayContainer = document.getElementById('pod-entry-data-container')
  const podFamilyContainerElm = createElm('div', tableID + '-container', 'pod-family-container', )
  const podFamilyTableElm = createElm('table', tableID, 'data-table')
  const podFamilyNotesElm = createElm('div', tableID + '-notes', 'pod-family-notes')


  const deleteTableButtonElm = createElm('button', 'delete-table-button', 'delete-button')
  deleteTableButtonElm.onclick = removeTableButtonHandler
  deleteTableButtonElm.setAttribute('data-key', tableID)
  deleteTableButtonElm.innerText = 'X'
  podFamilyNotesElm.append(deleteTableButtonElm)


  // Create the labor row
  const laborRow = createElm('tr', 'pod-labor-container', 'data-row')
  laborRow.append(createElm('td', 'pod-style-data-item', 'data-item', 'mdsetools'))
  // The labor row is appended later after the mounting charges are found in the row and added.


  // Create the block and tray rows
  const blockRow = createElm('tr', 'pod-block-container', 'data-row')
  const trayRow = createElm('tr', 'pod-tray-container', 'data-row')
  let block = false
  let tray = false
  let trayLink = false
  let platform = false
  let addHdw = ''
  const checkIfEmptyOrNA = (item) => {

    return typeof item === 'string' && item && cleanStr(item) !== '' && cleanStr(item) !== "n/a"
  }

  let podQuantity = '1'
  matrixData.matrix.forEach(row => {
    console.log('-------START--------')
    console.log('row', row)

    // Get selected platform
    if (cleanStr(row.PLATFORM) === cleanStr(platformSelected) && podStyleSelected) {
      console.log('podStyleSelected', podStyleSelected)

      // Create the block row
      if (checkIfEmptyOrNA(row[podStyleSelected])) {
        console.log('row[podStyleSelected]', row[podStyleSelected])

        const podArray = row[podStyleSelected].split('~')
        console.log('---->', podArray)
        const pod = podArray[0]
        if (podArray[1]) podQuantity = podArray[1]

        block = createElm('td', 'pod-style-data-item', 'data-item', pod)
        blockRow.append(block)
      }
      platform = row.PLATFORM

      // Add mounting charges based on type of pod
      laborRow.append(createElm('td', 'pod-style-data-item', 'data-item mounting-charges', row['MOUNTING CHARGES']))

      // Create the tray row
      console.log('---TRAY ROW---')
      // See if there is a link to a tray column
      if (Object.keys(matrixData.trayLinks).includes(podStyleSelected)) {
        trayLink = matrixData.trayLinks[podStyleSelected]

        console.log('trayLink2-IN', trayLink)
        if (checkIfEmptyOrNA(row[trayLink])) {
          console.log('row[trayLink]', row[trayLink])
          tray = createElm('td', 'pod-style-data-item', 'data-item', row[trayLink])
          trayRow.append(tray)

        }
      }


      // Check for additional hardware
      if (Object.hasOwn(row, 'ADDL HDWE RQD')) {
        addHdw = row['ADDL HDWE RQD']
      }
    }
    console.log('-------END--------')
  })

  podFamilyTableElm.append(laborRow)

  if (block) {
    blockRow.append(createElm('td', 'pod-style-data-item', 'data-item', podQuantity))
    podFamilyTableElm.append(blockRow)
  }
  if (tray) {
    trayRow.append(createElm('td', 'pod-style-data-item', 'data-item', '1'))
    podFamilyTableElm.append(trayRow)
  }
  if (platform) podFamilyNotesElm.append('Notes: ' + platform)


  // Create the SKU row

  if (sku) {
    const skuList = sku.split(',')
    skuList.forEach(skuName => {
      const skuRow = createElm('tr', 'pod-labor-container', 'data-row')
      skuRow.append(createElm('td', 'pod-style-data-item', 'data-item', skuName))
      skuRow.append(createElm('td', 'pod-style-data-item', 'data-item', '1'))
      podFamilyTableElm.append(skuRow)
    })


  }

  // Create the Additional Hardware row(s)
  addHdw.split(',').forEach(hdwSKU => {
    if (hdwSKU && hdwSKU.replaceAll(' ', '') !== '') {
      const hardwareRow = createElm('tr', 'pod-hardware-container', 'data-row')
      hardwareRow.append(createElm('td', 'pod-style-data-item', 'data-item', hdwSKU))
      hardwareRow.append(createElm('td', 'pod-style-data-item', 'data-item', '1'))
      podFamilyTableElm.append(hardwareRow)
    }


  })


  podFamilyContainerElm.append(podFamilyTableElm)
  podFamilyContainerElm.append(podFamilyNotesElm)
  podEntryDisplayContainer.append(podFamilyContainerElm)


}

///////////////////////////////////////
// POD SELECTION HANDLERS
function platformSelectHandler(e) {
  e.preventDefault()
  userInput.platformSelected = e.target.value

}

function roomSelectHandler(e) {
  e.preventDefault()
  userInput.roomSelected = e.target.value

}

///////////////////////////////////////
// START POD STYLE BUTTONS
const initPodStyleButtons = (matrixData) => {
  const podStyleButtonContainer = document.getElementById('pod-style-button-container')
  podStyleButtonContainer.innerHTML = ''
  Object.keys(Object.keys(matrixData).length > 0 && matrixData.metadata).forEach(buttonName => {
    if (buttonName.includes(creatButtonIndicator)) {
      const cleanButtonName = buttonName.replace(creatButtonIndicator, '')
      const button = document.createElement('button')
      button.classList.add("pod-style-button")
      button.classList.add("button-" + cleanButtonName.replaceAll(' ', ''));
      button.value = buttonName
      button.onclick = podStyleButtonHandler
      button.innerText = cleanButtonName
      podStyleButtonContainer.append(button)
    }
  })

  createRoomSelectInput()
  createPlatformSelectButton()
}


///////////////////////////////////////
// GRAB AND CREATE MATRIXDATA
function ExcelImport(event) {
  var input = event.target;
  var reader = new FileReader();

  reader.onload = function () {
    var fileData = reader.result;

    var wb = XLSX.read(fileData, {
      type: 'binary'
    });

    wb.SheetNames.forEach(function (sheetName) {
      if (sheetName.toLowerCase() === 'matrix') {
        var rowObj = XLSX.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
        var jsonObj = JSON.stringify(rowObj);

        matrixData.matrix = JSON.parse(jsonObj)

        // CREATE METADATA
        matrixData.metadata = {}
        matrixData.matrix.forEach(row => {
          for (const [key, value] of Object.entries(row)) {
            if (!Object.hasOwn(matrixData.metadata, key)) matrixData.metadata[key] = []
            if (!matrixData.metadata[key].includes(value)) matrixData.metadata[key].push(value)
          }
        })

        // CREATE TRAY LINKS
        matrixData.trayLinks = {}
        matrixData.matrix.forEach(row => {

          if (row.ROOM === trayLinkKey) {
            matrixData.trayLinks = row
          }
        })

        console.log('MATRIXDATA==>', matrixData)
        localStorage.setItem(localStorageName, JSON.stringify(matrixData));
        initPodStyleButtons(matrixData)
      } else if (sheetName.toLowerCase() === 'version') {

        const version = wb.Sheets.Version.B3.v;
        console.log('version', version)
        document.getElementById('matrix-spreadsheet-version-wrap').innerHTML = '<p>Matrix Spreadsheet Version: <span id="matrix-spreadsheet-version"> ' + version + '</span></p>'

        localStorage.setItem(localStorageName + '-matrixVersion', version);

      }
    })
  };
  reader.readAsBinaryString(input.files[0]);

  // Show Matrix buttons
  document.getElementById('search-inputs-form').classList.remove('hide')
  document.getElementById('matrix-version-number').innerText = 'v: ' + localMatrixVersion
  document.getElementById('matrix-version-number').innerHTML = '<span class="sucess-notice">Successfully Upladed!</span>'
};


///////////////////////////////////////
// UTILITY: Grab and Read Excel Workbook
function gatherExcelSheetData(input, targetSheetName, dataObj, workbookName, nameforLocalStorage, outputSuccessElm) {

  var reader = new FileReader();

  reader.onload = function () {
  

    var fileData = reader.result;

    var wb = XLSX.read(fileData, {
      type: 'binary'
    });

    /* const allowedProductTypes = ['faucets', 'trim']*/
    wb.SheetNames.forEach(function (sheetName) {
     
      if (sheetName.toLowerCase().replaceAll(' ', '') === targetSheetName) {
        var rowObj = XLSX.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
       
        /*  var jsonObj = JSON.stringify(rowObj);
		    console.log('jsonObj->',jsonObj)
        const rawProdInfoData = JSON.parse(jsonObj)
			    console.log('rawProdInfoData->',rawProdInfoData)*/
        const cleanName = sheetName.toLowerCase().replaceAll(' ', '')
        const fullCleanName = workbookName + '-' + cleanName
        dataObj[fullCleanName] = {}
        rowObj.forEach((row, i) => {
         

          if (i === 0) {
            const rowKeys = Object.keys(row)
            dataObj[fullCleanName].date = rowKeys[1]
          } else {
            const rowValues = Object.values(row)
            /* if (rowValues[2] && allowedProductTypes.includes(rowValues[2].toLowerCase().replaceAll(' ', ''))) */
            dataObj[fullCleanName][rowValues[0]] = rowValues[1]
          }

        })


      }
      /*	else if (sheetName.toLowerCase() === 'version') {

        const version = wb.Sheets.Version.B3.v;
        console.log('version', version)
        document.getElementById('matrix-spreadsheet-version-wrap').innerHTML = '<p>Matrix Spreadsheet Version: <span id="matrix-spreadsheet-version"> ' + version + '</span></p>'

        localStorage.setItem(localStorageName + '-matrixVersion', version);

      }*/
    })
    console.log('dataObj==>', dataObj)
    console.log('JSON.stringify(prodInfoData)==>', JSON.stringify(dataObj))
    localStorage.setItem(nameforLocalStorage, JSON.stringify(dataObj));
    if (outputSuccessElm) document.getElementById(outputSuccessElm).innerHTML = '<span class="sucess-notice">Successfully Upladed!</span>'
  };
  reader.readAsBinaryString(input.files[0])
}

///////////////////////////////////////
// GRAB AND CREATE PRODINFODATA
function ProdInfoExcelImport(event) {
  var input = event.target;
  const dataObj = prodInfoData
  const targetSheetName = faucetTargetSheetName
  const workbookName = faucetWorkbookName
  const nameforLocalStorage = localProdInfoStorageName

  gatherExcelSheetData(input, targetSheetName, dataObj, workbookName, nameforLocalStorage, 'faucets-info-date')


};
///////////////////////////////////////
// GRAB AND CREATE ACCINFODATA
function ACCInfoExcelImport(event) {
  var input = event.target;
  const dataObj = prodInfoData
  const targetSheetName = accTargetSheetName
  const workbookName = accWorkbookName
  const nameforLocalStorage = localProdInfoStorageName

  const success = gatherExcelSheetData(input, targetSheetName, dataObj, workbookName, nameforLocalStorage, 'acc-info-date')


};
///////////////////////////////////////
// GRAB AND CREATE CFGINFODATA
function CFGInfoExcelImport(event) {
  var input = event.target;
  const dataObj = prodInfoData
  const targetSheetName = cfgTargetSheetName
  const workbookName = cfgWorkbookName
  const nameforLocalStorage = localProdInfoStorageName

  const success = gatherExcelSheetData(input, targetSheetName, dataObj, workbookName, nameforLocalStorage, 'cfg-info-date')

};
///////////////////////////////////////
// Create Platform Button
function createPlatformSelectButton() {
  const outputObj = {}

  ///////////////////////////////
  // onchange for datalist input
  const platformInput = document.getElementById('platform-select-input')
  platformInput.onchange = platformSelectHandler

  ///////////////////////////////
  // Compile the pod family list
  if (Object.keys(matrixData).length > 0) matrixData.matrix.forEach(row => {
    if (!Object.hasOwn(outputObj, row.ROOM)) outputObj[row.ROOM] = {}
    outputObj[row.ROOM][row['PLATFORM']] = row[userInput.podStyleSelected]

  })


  ///////////////////////////////
  // Build Platform dropdown menu
  const platformButtonContainer = document.getElementById('platform-select-wrap')
  const platformSelectElm = document.createElement('datalist')

  platformSelectElm.id = 'platform-select'
  platformSelectElm.classList.add('pod-filter-select')


  const platformOptions = []
  for (const [key, value] of Object.entries(outputObj)) {
    for (const [platformKey, platformValue] of Object.entries(value)) {

      if (platformKey) platformOptions.push(platformKey)

    }
  }
  const platformOptionElm = document.createElement('option')
  platformOptionElm.innerText = '- Choose a Platform -'
  platformSelectElm.append(platformOptionElm)

  ///////////////////////////////
  // Add Platform options to dropdown menu
  platformOptions.forEach(option => {
    const platformOptionElm = document.createElement('option')
    platformOptionElm.innerText = option
    platformSelectElm.append(platformOptionElm)
  })


  ///////////////////////////////
  // Add Everything to the DOM
  platformButtonContainer.prepend(platformSelectElm)

}

///////////////////////////////////////
// Create Room Button
function createRoomSelectInput() {
  const outputObj = {}

  ///////////////////////////////
  // Build Room dropdown menu
  const platformButtonContainer = document.getElementById('room-select-wrap')
  const roomSelectElm = document.createElement('select')
  roomSelectElm.id = 'room-select'
  roomSelectElm.onchange = roomSelectHandler
  roomSelectElm.classList.add('pod-filter-select')

  ///////////////////////////////
  // Add the default (first) option
  const roomOptionElm = document.createElement('option')
  roomOptionElm.innerText = '- Choose a Room -'
  roomSelectElm.append(roomOptionElm)


  ///////////////////////////////
  // Compile the room list
  const roommOptions = []

  if (Object.keys(matrixData).length > 0) {
    matrixData.metadata.ROOM.forEach(room => {
      const roomOptionElm = document.createElement('option')
      roomOptionElm.innerText = room
      roomSelectElm.append(roomOptionElm)
    })
  }

  ///////////////////////////////
  // Add Everything to the DOM
  platformButtonContainer.prepend(roomSelectElm)
}


///////////////////////////////////////
// MATRIX SEARCH FORM HANDLER
const matrixSearchFormSubmitHandler = (event) => {
  event.preventDefault()
  var formData = document.getElementById("search-inputs-form").elements;
  const sku = userInput.sku
  const room = userInput.roomSelected
  const skuDesc = userInput.skuDescription
  const podStyle = userInput.podStyleSelected
  const platformSelected = userInput.platformSelected

  generatePodEntryDisplayData(sku, room, skuDesc, podStyle, platformSelected)
}


///////////////////////////////////////
// ACCESSORIES FORM HANDLER
const accessoriesFormSubmitHandler = (event) => {
  event.preventDefault()
  const podELm = document.getElementById('pod-input')
  const skuELm = document.getElementById('sku-input')
  const groomedSkuELm = skuELm.value.replaceAll(',', ' ')

  const lineNumberSeedELm = document.getElementById('line-number-seed-input')
  const skusGroupedArray = groomedSkuELm.split(/\r?\n/).filter(group => group !== '')
  const groomedSkusGroupedArray = skusGroupedArray.map(group => group.replace(/[\s~`!@#$%^&*(){}\[\];:"'<,.>?\/\\|_+=-]/g, '|'))
 
  groomedSkusGroupedArray.forEach(group => {
    console.log('group', group)
  })

  const AccessoresOutputDiv = document.getElementById('accessories-output')
  AccessoresOutputDiv.innerHTML = ''
  const optionsDiv = document.getElementById('accessories-container')

  let line = lineNumberSeedELm.value ? lineNumberSeedELm.value * 1 : 1

  groomedSkusGroupedArray.forEach(group => {
    let rowsUsed = 2 // Two rows for the labor charge and pod.
    const singleSKUsArray = group.split('|')
    const displayElm = document.createElement('table')
    displayElm.innerHTML = ' <tr><td>ACCTOOLS</td><td>1</td></tr>'
      + '<tr><td>' + podELm.value.toUpperCase() + '</td><td>1</td><td>' + line + '</td></tr>';


    singleSKUsArray.forEach(skuGroup => {
      if (skuGroup.replaceAll(' ', '') !== '') {
        const skusOutputElm = document.createElement('tr')
        skuGroup.split('|').forEach(sku => {

          if (sku.replaceAll(' ', '') !== '') {

            const skuNumberTD = document.createElement('td')
            const quantityTD = document.createElement('td')
            const hlItmTD = document.createElement('td')

            skuNumberTD.innerText = sku.toUpperCase()
            quantityTD.innerText = '1'
            hlItmTD.innerText = line

            skusOutputElm.append(skuNumberTD)
            skusOutputElm.append(quantityTD)
            skusOutputElm.append(hlItmTD)
          }
        })

        displayElm.append(skusOutputElm)
        rowsUsed++
      } // Go to next row
    })


    AccessoresOutputDiv.append(displayElm)
    line = line + rowsUsed // move line number to next group
  })

  //		
  //		for (const row of matrixData) {
  //			console.log('row',row)
  //		if(row.ROOM.includes(inputElm.value )) {
  //		   
  //		     optionsDiv.innerHTML = optionsDiv.innerHTML + '<p>' + Object.entries(row).map(entry => '<span> ' + entry[0] +': MDSETOOLS<br/>' + entry[1] + '<span>' + '</p>')
  //		   }
  //		}
}


///////////////////////////////////////
// CFG FORM HANDLER
const cfgFormSubmitHandler = (event) => {
  event.preventDefault()
  const skuELm = document.getElementById('cfg-sku-input')
  const groomedSkuELm = skuELm.value.replaceAll(',', ' ')
  const lineNumberSeedELm = document.getElementById('cfg-line-number-seed-input')
  const skusGroupedArray = groomedSkuELm.split(/\r?\n/).filter(group => group !== '')
  const groomedSkusGroupedArray = skusGroupedArray.map(group => group.replace(/[\s~`!@#$%^&*(){}\[\];:"'<,.>?\/\\|_+=-]/g, '|'))

  groomedSkusGroupedArray.forEach(group => {
    console.log('group', group)
  })

  const CFGOutputDiv = document.getElementById('cfg-output')
  CFGOutputDiv.innerHTML = ''
  const optionsDiv = document.getElementById('cfg-container')

  let line = lineNumberSeedELm.value ? lineNumberSeedELm.value * 1 : 1

  groomedSkusGroupedArray.forEach(group => {
    let rowsUsed = 1 // Two rows for the labor charge and pod.
    const singleSKUsArray = group.split('|')
    const displayElm = document.createElement('table')
    displayElm.innerHTML = ' <tr><td>CFGTOOLS</td><td>1</td></tr>'


    singleSKUsArray.forEach(skuGroup => {
      if (skuGroup.replaceAll(' ', '') !== '') {
        const skusOutputElm = document.createElement('tr')
        skuGroup.split('|').forEach(sku => {

          if (sku.replaceAll(' ', '') !== '') {

            const skuNumberTD = document.createElement('td')
            const quantityTD = document.createElement('td')
            const hlItmTD = document.createElement('td')

            skuNumberTD.innerText = sku.toUpperCase()
            quantityTD.innerText = '1'
            hlItmTD.innerText = line

            skusOutputElm.append(skuNumberTD)
            skusOutputElm.append(quantityTD)
            skusOutputElm.append(hlItmTD)
          }
        })

        displayElm.append(skusOutputElm)
        rowsUsed++
      } // Go to next row
    })

    CFGOutputDiv.append(displayElm)
    line = line + rowsUsed // move line number to next group
  })

  //		
  //		for (const row of matrixData) {
  //			console.log('row',row)
  //		if(row.ROOM.includes(inputElm.value )) {
  //		   
  //		     optionsDiv.innerHTML = optionsDiv.innerHTML + '<p>' + Object.entries(row).map(entry => '<span> ' + entry[0] +': MDSETOOLS<br/>' + entry[1] + '<span>' + '</p>')
  //		   }
  //		}
}


///////////////////////////////////////
// Tab Controller Button 
const tabControllerButtonHandler = (element) => {
  const currentTab = document.querySelector('.tab-open')
  if (currentTab) currentTab.classList.remove('tab-open')
  document.getElementById(element.value).classList.add('tab-open')
}


///////////////////////////////////////
// Onload Setup
window.onload = () => {
  document.getElementById('app-version').innerText = appVersion
  if (Object.keys(matrixData).length > 0) {
    initPodStyleButtons(matrixData)
    // Show Matrix buttons
    document.getElementById('search-inputs-form').classList.remove('hide')

    localMatrixVersion
    console.log('localMatrixVersion', localMatrixVersion)
    document.getElementById('matrix-spreadsheet-version-wrap').innerHTML = '<p>Matrix Spreadsheet Version: <span id="matrix-spreadsheet-version"> ' + localMatrixVersion + '</span></p>'
  }

  if (localMatrixVersion) document.getElementById('matrix-version-number').innerText = 'v: ' + localMatrixVersion

  if (Object.keys(prodInfoData).length > 0) {

    if (Object.hasOwn(prodInfoData, 'faucets-allskus')) document.getElementById('faucets-info-date').innerText = prodInfoData['faucets-allskus'].date
    if (Object.hasOwn(prodInfoData, 'acc-allskus')) document.getElementById('acc-info-date').innerText = prodInfoData['acc-allskus'].date
    if (Object.hasOwn(prodInfoData, 'cfg-allskus')) document.getElementById('cfg-info-date').innerText = prodInfoData['cfg-allskus'].date
  }
  //	ctaElm('test', 'button text', ()=>{alert('It worked')})

  // If the Matrix and all three Prod Info spreadsheets are not loaded, open loading area.
  if (Object.keys(matrixData).length <= 0 || Object.keys(prodInfoData).length <= 2) {
    handleDataLoadOpenButton()
  }
}


///////////////////////////////////////
// Handlers
const handleDataLoadOpenButton = () => {
  const elm = document.getElementById('data-load-container')
  const classes = elm.classList
  if (classes.contains('open')) {
    classes.remove('open')
  } else {
    classes.add('open')
  }

}

const userInputHandler = (e) => {
  userInput[e.target.dataset.key] = e.target.value
  const fullSheetName = faucetfullSheetName

  let matchFound = false
  Object.keys(prodInfoData).some(fullSheetName => {
    for (const entry of Object.entries(prodInfoData[fullSheetName])) {

      if (e.target.value.toLowerCase().replaceAll(' ', '') === entry[0].toLowerCase().replaceAll(' ', '')) {
        document.getElementById('sku-detail').innerHTML = (entry[1])


        // Find style and input platform box
        const options = {}
        // Structure: First item is Matrix 3D spreadsheet standard and the rest are options.
        options.ac = ['ac', 'towel', 'towelbar', 'rod', 'ring', 'paper', 'knob', 'toilet', 'robe', 'hook']
        options.pulldown = ['p/d', 'pd', 'pulldown']
        options.pullout = ['p/o', 'po', 'pullout']
        options.sip = ['sip', 'butler']
        options.soap = ['soap', 'dispenser']
        options.lav = ['lav']
        options.tubfiller = ['tf', 't/f', 'tubfiller']
        options.potfiller = ['potfiller', 'p/f', 'pf']
        options.widespread = ['w/s', 'ws', 'widespread']
        options.nebia = ['nebia']
        options.romantub = ['r/t', 'rt', 'roman']
        options.showerhead = ['shower head', 's/h', 'showerhead', 'rainshower', 'rain']
        options.slidebar = ['slide', 'slidebar', 'slide bar']
        options.mcoreTransfer = ['transfer', 'xfer']
        options.mcoreStacked = ['stacked']
        options.mcore = ['m-core', 'mcore']
        options.mcore = ['w/m', 'wallmount']
        options.posi = ['posi']
        options.moentrol = ['moentrol']
        options.tubshower = ['t/s', 'ts', 'tub', 'trim']
        options.verticalspa = ['v/s', 'vs', 'vo', 'v/o', 'spa']
        options.bodyspray = ['body', 'bodyspray']
        options.onehole = ['1h', 'one hole']
        options.twohole = ['2h', 'two hole']
        options.threehole = ['3h', 'three hole']
        options.fourhole = ['4h', 'four hole']

    
        for (const values of Object.values(options)) {
     

          const foundMatch = values.some(name => {

            if (entry[1].toLowerCase().includes(name)) {
              document.getElementById('platform-select-input').value = values[0]
              matchFound = true
              return true
            }

          })

          if (foundMatch) return true
        }

        break
      } else {
        document.getElementById('sku-detail').innerHTML = '&#10144; ' + e.target.value + ' was not found in the Product Information spreadsheet.'
        document.getElementById('platform-select-input').value = ''
      }
    }
  })

}

const removeTableButtonHandler = (e) => {
  const elem = document.getElementById(e.target.dataset.key + '-container');
  elem.parentNode.removeChild(elem);
}


/*
40225
40606
58910BN
58911
58912
CA47711L
40311CGR
46301CGR
46302CBNGR
46200
76162SRS
CA40519
CA47511
CA42519
*/
