local SCRIPT_TITLE = 'Latin2SV'

--[[

lua file name: Latin2svPanel.lua

Add Latin 2 SV lyrics Panel in panel

Notice: Works only with script panel 
		introduced with Synthesizer V version >= 2.1.2

Convert LATIN to XSAMPA (Spanish, modo "all'italiana" adapted SynthV spanish) + pseudo-spanish support.
- Make it live when you type in #latinInput.
- Show rules/tips.
- It preserves line breaks from the original text.

Update: Creation js to lua & panel (JFA)
		2 - add "sc_e_i = SC + E / I → sh + vocal

Original JavaScript code author: Blancanegra
Subject: https://vi-control.net/community/threads/synthesizer-v-choir-voice-collections.169542/page-2#post-5823669
Web: https://cincelaser.com/latin2sv/
Author: https://vi-control.net/community/members/blancanegra.9788/

2026 - JF AVILES
--]]

function getClientInfo()
	return {
		name = SV:T(SCRIPT_TITLE),
		-- category = "_JFA_Panels",
		author = "JFAVILES",
		versionNumber = 2,
		minEditorVersion = 131329,
		type = "SidePanelSection"
	}
end

-- Generated by JFA TranslateScripts.lua
function getTranslations(langCode)
	return getArrayLanguageStrings()[langCode]
end

-- Generated by JFA TranslateScripts.lua
function getArrayLanguageStrings()
	return {
		["en-us"] = {
			{"Start input text", "Start input text"},
			{"Version", "Version"},
			{"author", "author"},
			{"minEditorVersion", "minEditorVersion"},
			{"Latin to SV2", "Latin to SV2"},
			{"The Latin diphthongs AE and OE are pronounced as a single E.", "The Latin diphthongs AE and OE are pronounced as a single E."},
			{"C before A, O or U is pronounced like 'k'.", "C before A, O or U is pronounced like 'k'."},
			{"In Latin, C before E or I sounds like the Spanish 'ch'. In Spanish, C before E or I sounds like 'zeta', the phoneme 'C' (English 'th').", "In Latin, C before E or I sounds like the Spanish 'ch'. In Spanish, C before E or I sounds like 'zeta', the phoneme 'C' (English 'th')."},
			{"La secuencia CC ante E o I suena como 'kch' (ecce → ecche).", "The sequence CC before E or I sounds like 'kch' (ecce → ecche). 'kch' (ecce → ecche)."},
			{"CH from Greek (CHORUS, CHRISTUS) is pronounced like 'k'.", "CH from Greek (CHORUS, CHRISTUS) is pronounced like 'k'."},
			{"G before E or I is pronounced like the Italian /dʒ/, similar to the French 'j'; we use 'y'.", "G before E or I is pronounced like the Italian /dʒ/, similar to the French 'j'; we use 'y'."},
			{"The sequence GN is pronounced like 'ñ'. Leave unchanged if the GN sound is preferred.", "The sequence GN is pronounced like 'ñ'. Leave unchanged if the GN sound is preferred."},
			{"GU before a vowel is pronounced with a semivowel [w] (XSAMPA 'U'). In lyrics we write (¨ü) for a diphthong or (u-) for hiatus.", "GU before a vowel is pronounced with a semivowel [w] (XSAMPA 'U'). In lyrics we write (¨ü) for a diphthong or (u-) for hiatus."},
			{"We break the diphthong IU/UI with a hyphen.", "We break the diphthong IU/UI with a hyphen."},
			{"J (JESUS, JERUSALEM) is pronounced like a short i; we use 'y'.", "J (JESUS, JERUSALEM) is pronounced like a short i; we use 'y'."},
			{"The LL has a double articulation which we force with the hyphen to avoid 'll'. An 'l' is pronounced in each syllable as in Italian. The same occurs with the CC group (k+k) where the hyphen is not necessary.", "The LL has a double articulation which we force with the hyphen to avoid 'll'. An 'l' is pronounced in each syllable as in Italian. The same occurs with the CC group (k+k) where the hyphen is not necessary."},
			{"PH is pronounced like 'f'.", "PH is pronounced like 'f'."},
			{"The U is pronounced as a semivowel.", "The U is pronounced as a semivowel."},
			{"When SC comes before E or I, it is pronounced like 'sh'. This phoneme must be added manually to the phoneme label of the note.", "When SC comes before E or I, it is pronounced like 'sh'. This phoneme must be added manually to the phoneme label of the note."},
			{"The 't' sounds approximately 'ts'.", "The 't' sounds approximately 'ts'."},
			{"TH is pronounced like a normal 't'.", "TH is pronounced like a normal 't'."},
			{"The Latin V is pronounced like the Spanish B; in pseudo we write it with 'b'. In cases, the V may be preferable.", "The Latin V is pronounced like the Spanish B; in pseudo we write it with 'b'. In cases, the V may be preferable."},
			{"The letter X is pronounced like 'ks', just like in Spanish.", "The letter X is pronounced like 'ks', just like in Spanish."},
			{"Z is mapped to 'ds' avoiding 'C'.", "Z is mapped to 'ds' avoiding 'C'."},
			{"Input activated!", "Input activated!"},
			{"Stop input text", "Stop input text"},
			{"Input disabled", "Input disabled"},
			{"Rules", "Rules"}, 
			{"Latin:", "Latin:"}, 
			{"Pseudo spanish:", "Pseudo spanish:"}, 
			{"Phonemes:", "Phonemes:"}, 
			{"Rules conversions:", "Rules conversions:"},
		},
		["es-la"] = {
			{"Start input text", "Iniciar texto entrada"},
			{"Version", "Versión"},
			{"author", "autor"},
			{"minEditorVersion", "minEditorVersion"},
			{"Latin to SV2", "Del latín al SV2"},
			{"The Latin diphthongs AE and OE are pronounced as a single E.", "Los diptongos latinos AE y OE se pronuncian como una sola E."},
			{"C before A, O or U is pronounced like 'k'.", "C ante A, O o U se pronuncia como 'k'."},
			{"In Latin, C before E or I sounds like the Spanish 'ch'. In Spanish, C before E or I sounds like 'zeta', the phoneme 'C' (English 'th').", "En latín C ante E o I suena como 'ch' española. En español C ante E o I suena como zeta, fonema 'C' ('th' inglesa)."},
			{"The sequence CC before E or I sounds like 'kch' (ecce → ecche). 'kch' (ecce → ecche).", "La secuencia CC ante E o I suena como 'kch' (ecce → ecche)."},
			{"CH from Greek (CHORUS, CHRISTUS) is pronounced like 'k'.", "CH procedente del griego (CHORUS, CHRISTUS) se pronuncia como 'k'."},
			{"G before E or I is pronounced like the Italian /dʒ/, similar to the French 'j'; we use 'y'.", "G ante E o I se pronuncia como la /dʒ/ italiana, similar a la 'j' francesa; usamos 'y'."},
			{"The sequence GN is pronounced like 'ñ'. Leave unchanged if the GN sound is preferred.", "La secuencia GN se pronuncia como 'ñ'. Dejar sin cambios si se prefiere el sonido GN."},
			{"GU before a vowel is pronounced with a semivowel [w] (XSAMPA 'U'). In lyrics we write (¨ü) for a diphthong or (u-) for hiatus.", "GU ante vocal se pronuncia con semivocal [w] (XSAMPA 'U'). En lyrics escribimos (¨ü) para diptongo o (u-) para hiato."},
			{"We break the diphthong IU/UI with a hyphen.", "Rompemos el diptongo IU/UI con guión."},
			{"J (JESUS, JERUSALEM) is pronounced like a short i; we use 'y'.", "J (JESUS, JERUSALEM) se pronuncia como una i corta; usamos 'y'."},
			{"The LL has a double articulation which we force with the hyphen to avoid 'll'. An 'l' is pronounced in each syllable as in Italian. The same occurs with the CC group (k+k) where the hyphen is not necessary.", "La LL tiene articulación doble que forzamos con el guión para evitar 'll' .Se pronuncia una 'l' en cada sílaba como en italiano. Lo mismo ocurre con el grupo CC (k+k) donde no es necesario el guión."},
			{"PH is pronounced like 'f'.", "PH se pronuncia como 'f'."},
			{"The U is pronounced as a semivowel.", "Se pronuncia la U como semivocal."},
			{"When SC comes before E or I, it is pronounced like 'sh'. This phoneme must be added manually to the phoneme label of the note.", "Cuando SC va antes de E o I se pronuncia como 'sh'. Este fonema hay que añadirlo a mano en la etiqueta de fonemas de la nota."},
			{"The 't' sounds approximately 'ts'.", "La 't' suena aproximadamente 'ts'."},
			{"TH is pronounced like a normal 't'.", "TH se pronuncia como 't' normal."},
			{"The Latin V is pronounced like the Spanish B; in pseudo we write it with 'b'. In cases, the V may be preferable.", "La V latina se pronuncia como B española; en pseudo la escribimos con 'b'. Encasos, peude ser preferible la V."},
			{"The letter X is pronounced like 'ks', just like in Spanish.", "La X se pronuncia como 'ks' igual que en español."},
			{"Z is mapped to 'ds' avoiding 'C'.", "La Z se mapea a 'ds' evitando 'C'."},
			{"Input activated!", "¡Entrada activada!"},
			{"Stop input text", "Stop input text"},
			{"Input disabled", "Entrada deshabilitada"},
			{"Rules", "Normas"},
			{"Latin:", "Latin:"},
			{"Pseudo spanish:", "Pseudo español:"},
			{"Phonemes:", "Fonemas:"},
			{"Rules conversions:", "Conversiones reglas:"},
		}
	}
end

-- Define a class "NotesObject"
NotesObject = {
	displayVersion = true,	-- display version
	displayAuthor = false,	-- display author
	errorMessages = {},
	hostinfo = nil,
	osType = "",
	osName = "",
	hostName = "",
	languageCode = "", 
	hostVersion = "",
	hostVersionNumber = 0,
	debug = false,
	controls = {},					-- controls panel
	startButtonText = SV:T("Start input text"),
	statusTextValue = nil,   		-- text panel
	latinTextValue = nil,   		-- Latin text panel
	pseudoSpanishValue = nil,   	-- pseudo spanish text panel
	phonemesTextValue = nil,   		-- Phonemes text panel
	rulesTextValue = nil,   		-- rules text panel
	infosToDisplay = "",
	isTextInputActive = false,
	isFirstTimeActived = true,
	RULE_TIPS = {},
	rulesListChoice = {},
	logs = {}
}


-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
	self:getHostInformations()
	
	self.controls = self:getControls()
	
	self:initializeControlsValues()
	self:setControlsCallback()
	
	self.startInpuptValue = SV:create("WidgetValue")
	self.statusTextValue = SV:create("WidgetValue")
	self.statusTextValue:setValue("")
	self.statusTextValue:setEnabled(false)
	
	self.latinTextValue = SV:create("WidgetValue")
	self.latinTextValue:setValue("")
	self.latinTextValue:setEnabled(false)

	self.pseudoSpanishValue = SV:create("WidgetValue")
	self.pseudoSpanishValue:setValue("")
	self.pseudoSpanishValue:setEnabled(false)

	self.phonemesTextValue = SV:create("WidgetValue")
	self.phonemesTextValue:setValue("")
	self.phonemesTextValue:setEnabled(false)

	self.rulesTextValue = SV:create("WidgetValue")
	self.rulesTextValue:setValue("")
	self.rulesTextValue:setEnabled(false)

	self:setButtonStartInputControlCallback()

	local infos = getClientInfo()

	self.infosToDisplay = ""
	if self.displayVersion then
		self.infosToDisplay = self.infosToDisplay .. SV:T("Version") .. ": " ..  infos.versionNumber
		if self.displayAuthor then
			self.infosToDisplay = self.infosToDisplay .. " - " .. SV:T("author") .. ": " .. infos.author
		end
	end
	
	-- self.infosToDisplay = self.infosToDisplay .. SV:T("minEditorVersion") .. ": " ..  infos.minEditorVersion
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(SV:T("Latin to SV2") .. "...")

	
    return self
end

-- Set rules conversions text Initialization
function NotesObject:setRulesInit()
	self:setRulesText()
	self.rulesListChoice = self:getRulesHeaders()
	self:rulesUpdate(0)
end

-- Set rules conversions text
function NotesObject:setRulesText()
	local rulesText = ""
	
	self.RULE_TIPS = {
	  {
		id = "ae_oe",
		title= "AE / OE → e",
		description= SV:T("The Latin diphthongs AE and OE are pronounced as a single E."),
		exampleLatin= "LAETITIA",
		examplePseudo= "letitsia",
		exampleXsampa= "l e t i t s i a"
	  },
	  {
		id= "c_other",
		title= "C + A / O / U → k",
		description= SV:T("C before A, O or U is pronounced like 'k'."),
		exampleLatin= "CORPUS",
		examplePseudo= "corpus",
		exampleXsampa= "k o r p u s"
	  },
	  {
		id= "c_e_i",
		title= "C + E / I → ch",
		description= SV:T("C before E or I sounds like the Spanish 'ch'."),
		exampleLatin= "CECILIA",
		examplePseudo= "chechilia",
		exampleXsampa= "ch e ch i l i a"
	  },
	  {
		id= "cc_e_i",
		title= "CC + E / I → k + ch",
		description= SV:T("The sequence CC before E or I sounds like 'kch' (ecce → ecche). 'kch' (ecce → ecche)."),
		exampleLatin= "ECCE",
		examplePseudo= "ecche",
		exampleXsampa= "e k ch e"
	  },
	  {
		id= "ch_greek",
		title= "CH (griego) → k",
		description= SV:T("CH from Greek (CHORUS, CHRISTUS) is pronounced like 'k'."),
		exampleLatin= "CHORUS",
		examplePseudo= "corus",
		exampleXsampa= "k o r u s"
	  },
	  {
		id= "g_e_i",
		title= "G + E / I → y",
		description= SV:T("G before E or I is pronounced like the Italian /dʒ/, similar to the French 'j'; we use 'y'."),
		exampleLatin= "REGINA",
		examplePseudo= "reyina",
		exampleXsampa= "r e y i n a"
	  },
	  {
		id= "gn",
		title= "GN → ñ",
		description= SV:T("The sequence GN is pronounced like 'ñ'. Leave unchanged if the GN sound is preferred."),
		exampleLatin= "AGNUS",
		examplePseudo= "añus",
		exampleXsampa= "a J u s"
	  },
	  {
		id= "gu_vowel",
		title= "GU + vocal → gU",
		description= SV:T("GU before a vowel is pronounced with a semivowel [w] (XSAMPA 'U'). In lyrics we write (¨ü) for a diphthong or (u-) for hiatus."),
		exampleLatin= "SANGUINE",
		examplePseudo= "sangüine, sangu-ine",
		exampleXsampa= "s a n g U i n e, s a n g u i n e"
	  },
	  {
		id= "hiato_iu",
		title= "IU / UI (JULIUS, FILIUS)",
		description= SV:T("We break the diphthong IU/UI with a hyphen."),
		exampleLatin= "JULIUS",
		examplePseudo= "yuli-us",
		exampleXsampa= "y u l i u s"
	  },
	  {
		id= "j",
		title= "J → y",
		description= SV:T("J (JESUS, JERUSALEM) is pronounced like a short i; we use 'y'."),
		exampleLatin= "JESUS",
		examplePseudo= "yesus",
		exampleXsampa= "y e s u s"
	  },
	  {
		id= "ll",
		title= "LL → l-l",
		description= SV:T("The LL has a double articulation which we force with the hyphen to avoid 'll'. An 'l' is pronounced in each syllable as in Italian. The same occurs with the CC group (k+k) where the hyphen is not necessary."),
		exampleLatin= "ALLELUIA",
		examplePseudo= "al-lelu-ia",
		exampleXsampa= "a l l e l u i a"
	  },
	  {
		id= "ph",
		title= "PH → f",
		description= SV:T("PH is pronounced like 'f'."),
		exampleLatin= "PHARISEI",
		examplePseudo= "farisei",
		exampleXsampa= "f a r i s e i"
	  },
	  {
		id= "qu_vowel",
		title= "QU + vocal → kU",
		description= SV:T("The U is pronounced as a semivowel."),
		exampleLatin= "QUOQUE",
		examplePseudo= "kuokue",
		exampleXsampa= "k U o k U e"
	  },
	  {
		id= "sc_e_i",
		title= "SC + E / I → sh + vocal",
		description= "When SC comes before E or I, it is pronounced like 'sh'. This phoneme must be added manually to the phoneme label of the note.",
		exampleLatin= "SUSCIPE",
		examplePseudo= "sushipe",
		exampleXsampa= "s u sh i p e"
	  },
	  {
		id= "ti_vowel",
		title= "TI + vocal → 'tsi' (~ t s I)",
		description= SV:T("The 't' sounds approximately 'ts'."),
		exampleLatin= "GRATIA",
		examplePseudo= "gratsia",
		exampleXsampa= "g r a t s I a"
	  },
	  {
		id= "th",
		title= "TH → t",
		description= SV:T("TH is pronounced like a normal 't'."),
		exampleLatin= "THEOS",
		examplePseudo= "teos",
		exampleXsampa= "t e o s"
	  },
	  {
		id= "v",
		title= "V → b / B",
		description= SV:T("The Latin V is pronounced like the Spanish B; in pseudo we write it with 'b'. In cases, the V may be preferable."),
		exampleLatin= "VITA",
		examplePseudo= "bita",
		exampleXsampa= "b i t a"
	  },
	  {
		id= "x",
		title= "X → k s",
		description= SV:T("The letter X is pronounced like 'ks', just like in Spanish."),
		exampleLatin= "EXCELSIS",
		examplePseudo= "excelsis",
		exampleXsampa= "e k ch e l s i s"
	  },
	  {
		id= "z",
		title= "Z → d s",
		description= SV:T("Z is mapped to 'ds' avoiding 'C'."),
		exampleLatin= "ZONA",
		examplePseudo= "dsona",
		exampleXsampa= "d s o n a"
	  }
	}

	for _, text in pairs(self.RULE_TIPS) do
		rulesText = rulesText .. text.id .. " " .. text.title .. "\r"
		rulesText = rulesText .. text.description .. "\r"
		rulesText = rulesText .. text.exampleLatin .. "\r"
		rulesText = rulesText .. text.examplePseudo .. "\r"
		rulesText = rulesText .. text.exampleXsampa .. "\r"
	end
	
	return rulesText
end

-- Get rules conversions headers
function NotesObject:getRulesHeaders()
	local rulesHeaders = {}
	for _, text in pairs(self.RULE_TIPS) do
		table.insert(rulesHeaders, text.id .. ": " .. text.title)
	end
	return rulesHeaders
end

-- Get rule conversions description
function NotesObject:getRuleDescription(iRule)
	local ruleDescription = ""
	local text = self.RULE_TIPS[iRule]
	ruleDescription = ruleDescription .. text.id .. ": " .. text.title .. "\r"
	ruleDescription = ruleDescription .. text.description .. "\r"
	ruleDescription = ruleDescription .. text.exampleLatin .. "\r"
	ruleDescription = ruleDescription .. text.examplePseudo .. "\r"
	ruleDescription = ruleDescription .. text.exampleXsampa .. "\r"
	
	return ruleDescription
end

-- -- On note selection change
-- function NotesObject:onSelectionChanged()
-- end

-- Trim string
function NotesObject:trim(s)
  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

-- Simple trim string
function NotesObject:simpleTrim(s)
  return string.gsub(s, '[ \t]+%f[\r\n%z]', '')
end

-- Show message dialog
function NotesObject:show(message)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), message)
end

-- Get selected groups
function NotesObject:getSelectedGroups()
	return SV:getArrangement():getSelection():getSelectedGroups()
end

-- Get current track
function NotesObject:getCurrentTrack()
	return SV:getMainEditor():getCurrentTrack()
end

-- Get timeAxis
function NotesObject:getTimeAxis()
	return self:getProject():getTimeAxis()
end

-- Get project
function NotesObject:getProject()
	return SV:getProject()
end

-- Add log into self.logs
function NotesObject:addLogs(message)
	table.insert(self.logs, message)
end

-- Display logs into panel
function NotesObject:addLogsInPanel()
	for i = 1, #self.logs do
		self:addTextPanel(self.logs[i])
	end
end

-- Store error message
function NotesObject:error(message)
	table.insert(self.errorMessages, message)
end

-- Display error messages
function NotesObject:displayErrors()
	local result = ""
	if #self.errorMessages > 0 then
		for _, m in pairs(self.errorMessages) do
			result = result .. m .. "\r"
		end
	end
	return result
end

-- Get host informations
function NotesObject:getHostInformations()
	self.hostinfo = SV:getHostInfo()
	self.osType = self.hostinfo.osType  -- "macOS", "Linux", "Unknown", "Windows"
	self.osName = self.hostinfo.osName
	self.hostName = self.hostinfo.hostName
	self.languageCode = self.hostinfo.languageCode
	self.hostVersion = self.hostinfo.hostVersion
	self.hostVersionNumber = self.hostinfo.hostVersionNumber
end

-- Get controls panel
function NotesObject:getControls()

	local controls = {
		rulesValue = {
			value = SV:create("WidgetValue"),
			defaultValue = 0,
			paramKey = "rules"
		},
		latinTextValue = {
			value = SV:create("WidgetValue"),
			defaultValue = "",
			paramKey = "latin"
		},
		pseudoSpanishValue = {
			value = SV:create("WidgetValue"),
			defaultValue = "",
			paramKey = "pseudoSpanish"
		},
		phonemesTextValue = {
			value = SV:create("WidgetValue"),
			defaultValue = "",
			paramKey = "phonemes"
		}
	}
	return controls
end

-- Initialize widget values
function NotesObject:initializeControlsValues()
	-- Initialize widget values
	for key, control in pairs(self.controls) do
		control.value:setValue(control.defaultValue)
		-- self:addLogs(key .. "=" .. tostring(control.defaultValue))
		-- self:addLogs(key .. "=" .. self:getObjectProperties(control))
	end
end

-- Set controls callback
function NotesObject:setControlsCallback()
	for key, control in pairs(self.controls) do
		control.value:setValueChangeCallback(function()
				-- SV:refreshSidePanel()
				if control.paramKey == "rules" then
					self:rulesUpdate(self.controls.rulesValue.value:getValue())
				end
		end
		)
	end
end

-- Rules update
function NotesObject:rulesUpdate(val)
	local text = self:getRuleDescription(val + 1)
	self.rulesTextValue:setValue(text)
end

-- Display message
function NotesObject:displayMessage(message)
	self:clearTextPanel()
	self:addTextPanel(self.infosToDisplay)
	self:addTextPanel(message)
end

-- Get object properties
function NotesObject:getObjectProperties(obj, level)
	local result = ""
	local level = level or 0
	local maxLevel = 3
	level = level + 1
	
	for k, v in pairs(obj) do
		if obj[k] ~= nil then
			result = result .. "(level: " .. level .. ") " .. k .. "=" .. tostring(v) .. "\r"
			if type(v) == "table" then
				result = result .. ", size:" .. #v .. ": "
				if level < maxLevel then
					result = result .. self:getObjectProperties(v, level) .. "\r"
				else
					result = result .. "\r"
				end
			end
		end
	end
	return result
end

-- Get string format from seconds
function NotesObject:secondsToClock(timestamp)
	return string.format("%01dmn %02.1fs",
	  math.floor(timestamp/60)%60, 
	  timestamp%60):gsub("%.",",")
end

-- Split string by sep char
function NotesObject:split(str, sep)
   local result = {}
   local regex = ("([^%s]+)"):format(sep)
   for each in str:gmatch(regex) do
	  table.insert(result, each)
   end
   return result
end

-- Display message box in panel
function NotesObject:addTextPanel(message)
	local old = self.statusTextValue:getValue()
	local sepLine = "\r"
	if #old > 0 then
		message = old .. sepLine .. message
	end
	self.statusTextValue:setValue(message)
end

-- Clear display message in panel
function NotesObject:clearTextPanel()
	self.statusTextValue:setValue("")
end

-- Set button start input text control callback
function NotesObject:setButtonStartInputControlCallback()

	-- Button start input text
	self.startInpuptValue:setValueChangeCallback(function()
			self:getProject():newUndoRecord()
			self.isTextInputActive = not self.isTextInputActive
			SV:setTimeout(100, function() self:startTextInput() end)
		end
	)
end

-- Start text input
function NotesObject:startTextInput()
	if self.isTextInputActive then
		if self.isFirstTimeActived then
			self.isFirstTimeActived = false
			self:displayMessage(SV:T("Input actived!"))
			self.startButtonText = SV:T("Stop input text")
			local latinText = self.latinTextValue:getValue()
			SV:refreshSidePanel()
			self.latinTextValue:setValue(latinText)
		end
		self:conversion()
		SV:setTimeout(100, function() self:startTextInput() end)
	else
		self.isFirstTimeActived = true
		self.isTextInputActive = false
		self:displayMessage(SV:T("Input disabled"))
		self.startButtonText = SV:T("Start input text")
		SV:refreshSidePanel()
	end
end

-- Conversion
function NotesObject:conversion()
	if #self.latinTextValue:getValue() > 0 then
		local result = self:convertText(self.latinTextValue:getValue())
		self.pseudoSpanishValue:setValue(result.respell)
		self.phonemesTextValue:setValue(result.phonemes)
	end
end

-- Stop text input
function NotesObject:stopTextInput()
	self.isTextInputActive = false
end

-- Normalize Latin text: lowercase and remove accents
function NotesObject:normalizeLatin(text)
  text = text:lower()
  
  -- Replace accented characters
  text = text:gsub("[áàâä]", "a")
  text = text:gsub("[éèêë]", "e")
  text = text:gsub("[íìîï]", "i")
  text = text:gsub("[óòôö]", "o")
  text = text:gsub("[úùûü]", "u")
  
  -- Keep only letters and spaces
  text = text:gsub("[^a-z%s]", " ")
  
  return text
end

-- Check if character is a vowel
function NotesObject:isVowel(ch)
  return ch and (ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u")
end

-- Get vowel phoneme
function NotesObject:vowelPhoneme(ch)
  if ch and (ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u") then
    return ch
  end
  return ch
end

-- ============================================================
-- 2. DIPHTHONGS
-- ============================================================

-- Read diphthong at position i in word
-- AE, OE -> /e/
-- AU, OU and others: left as two vowels (not handled here)
function NotesObject:readDiphthong(word, i)
  local ch = word:sub(i, i)
  local next = word:sub(i + 1, i + 1)
  
  if next == "" then
    return nil
  end
  
  local pair = ch .. next
  
  if pair == "ae" or pair == "oe" then
    return {
      phonemes = {"e"},
      respell = "e",
      jump = 2
    }
  end
  
  return nil
end

-- ============================================================
-- 2b. PROBLEMATIC HIATUSES IN PSEUDO (for SynthV)
-- ============================================================

-- Check if character is a respelling vowel
function NotesObject:isRespellingVowel(ch)
  return ch and (ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u" or ch == "y")
end

-- Insert hyphens in hiatuses that SynthV tends to diphthongize
-- but that we want to separate into syllables (currently only iu/ui)
function NotesObject:insertHiatusHyphens(word)
  local result = ""
  
  for i = 1, #word do
    local ch = word:sub(i, i)
    local next = word:sub(i + 1, i + 1)
    
    result = result .. ch
    
    if next ~= "" and self:isRespellingVowel(ch) and self:isRespellingVowel(next) then
      local pair = ch .. next
      -- Currently, only iu/ui
      if pair == "iu" or pair == "ui" then
        result = result .. "-"
      end
    end
  end
  
  return result
end

-- ============================================================
-- 3. LATIN → XSAMPA (Spanish mode, all'italiana)
-- ============================================================

function NotesObject:latinWordToXSAMPA(word)
  local w = word
  local out = {}
  local i = 1
  
  while i <= #w do
    local ch = w:sub(i, i)
    local next = w:sub(i + 1, i + 1)
    local next2 = w:sub(i + 2, i + 2)
    local prev = i > 1 and w:sub(i - 1, i - 1) or " "
    
    -- --- 3.1 Diphthongs AE/OE ---
    local dip = self:readDiphthong(w, i)
    if dip then
      for _, p in ipairs(dip.phonemes) do
        table.insert(out, p)
      end
      i = i + dip.jump
      goto continue
    end
    
    -- --- 3.2 Three-letter groups ---
    -- SC + E/I → "sh"
    if ch == "s" and next == "c" and (next2 == "e" or next2 == "i") then
      table.insert(out, "sh")
      i = i + 3
      goto continue
    end
    
    -- TI + vowel → "t s I vowel"
    -- Ex: GRATIA → g r a t s I a
    if ch == "t" and next == "i" and self:isVowel(next2) and prev ~= "s" then
      table.insert(out, "t")
      table.insert(out, "s")
      table.insert(out, "I")
      table.insert(out, self:vowelPhoneme(next2))
      i = i + 3
      goto continue
    end
    
    -- GU + vowel → g U vowel
    if ch == "g" and next == "u" and self:isVowel(next2) then
      table.insert(out, "g")
      table.insert(out, "U")
      table.insert(out, self:vowelPhoneme(next2))
      i = i + 3
      goto continue
    end
    
    -- QU + vowel → k U vowel
    if ch == "q" and next == "u" and self:isVowel(next2) then
      table.insert(out, "k")
      table.insert(out, "U")
      table.insert(out, self:vowelPhoneme(next2))
      i = i + 3
      goto continue
    end
    
    -- --- 3.3 Two-letter groups ---
    -- CC + E/I → k + ch (ECCE → e k ch e)
    if ch == "c" and next == "c" then
      local after = w:sub(i + 2, i + 2)
      if after == "e" or after == "i" then
        table.insert(out, "k")
        table.insert(out, "ch")
        i = i + 2
        goto continue
      else
        table.insert(out, "k")
        table.insert(out, "k")
        i = i + 2
        goto continue
      end
    end
    
    -- GN → J (ñ)
    if ch == "g" and next == "n" then
      table.insert(out, "J")
      i = i + 2
      goto continue
    end
    
    -- PH → f
    if ch == "p" and next == "h" then
      table.insert(out, "f")
      i = i + 2
      goto continue
    end
    
    -- TH → t
    if ch == "t" and next == "h" then
      table.insert(out, "t")
      i = i + 2
      goto continue
    end
    
    -- CH (χ) → k
    if ch == "c" and next == "h" then
      table.insert(out, "k")
      i = i + 2
      goto continue
    end
    
    -- LL → l l
    if ch == "l" and next == "l" then
      table.insert(out, "l")
      table.insert(out, "l")
      i = i + 2
      goto continue
    end
    
    -- RR → rr (multiple vibrant)
    if ch == "r" and next == "r" then
      table.insert(out, "rr")
      i = i + 2
      goto continue
    end
    
    -- --- 3.4 Simple vowels ---
    if self:isVowel(ch) then
      table.insert(out, self:vowelPhoneme(ch))
      i = i + 1
      goto continue
    end
    
    -- --- 3.5 Simple consonants ---
    -- B → b / B
    if ch == "b" then
      if i == 1 or prev == "m" or prev == "n" then
        table.insert(out, "b")
      else
        table.insert(out, "B")
      end
      i = i + 1
      goto continue
    end
    
    -- D → d / D
    if ch == "d" then
      if i == 1 or prev == "l" or prev == "n" then
        table.insert(out, "d")
      else
        table.insert(out, "D")
      end
      i = i + 1
      goto continue
    end
    
    -- F, L, M, P, S (without R)
    if ch == "f" or ch == "l" or ch == "m" or ch == "p" or ch == "s" then
      table.insert(out, ch)
      i = i + 1
      goto continue
    end
    
    -- H silent
    if ch == "h" then
      i = i + 1
      goto continue
    end
    
    -- C: C + E/I → "ch"; rest → "k"
    if ch == "c" then
      if next == "e" or next == "i" then
        table.insert(out, "ch")
      else
        table.insert(out, "k")
      end
      i = i + 1
      goto continue
    end
    
    -- G: G + E/I → "y"; rest → "g"
    if ch == "g" then
      if next == "e" or next == "i" then
        table.insert(out, "y")
      else
        table.insert(out, "g")
      end
      i = i + 1
      goto continue
    end
    
    -- Latin V → Spanish B (we don't use /v/)
    if ch == "v" then
      if i == 1 or prev == "m" or prev == "n" then
        table.insert(out, "b")
      else
        table.insert(out, "B")
      end
      i = i + 1
      goto continue
    end
    
    -- J → y (Jesus, Jerusalem)
    if ch == "j" then
      table.insert(out, "y")
      i = i + 1
      goto continue
    end
    
    -- W literal → semivowel U (like [w])
    if ch == "w" then
      table.insert(out, "U")
      i = i + 1
      goto continue
    end
    
    -- X → k s
    if ch == "x" then
      table.insert(out, "k")
      table.insert(out, "s")
      i = i + 1
      goto continue
    end
    
    -- Z → d s
    if ch == "z" then
      table.insert(out, "d")
      table.insert(out, "s")
      i = i + 1
      goto continue
    end
    
    -- R: simple vs multiple (rr)
    if ch == "r" then
      if i == 1 or prev == "l" or prev == "n" or prev == "s" then
        table.insert(out, "rr") -- multiple vibrant
      else
        table.insert(out, "r") -- simple vibrant
      end
      i = i + 1
      goto continue
    end
    
    -- T, K, Y as is
    if ch == "t" or ch == "k" or ch == "y" then
      table.insert(out, ch)
      i = i + 1
      goto continue
    end
    
    -- M, N (if not handled before)
    if ch == "m" or ch == "n" then
      table.insert(out, ch)
      i = i + 1
      goto continue
    end
    
    -- Any other non-space letter
    if ch ~= " " then
      table.insert(out, ch)
    end
    
    i = i + 1
    ::continue::
  end
  
  return table.concat(out, " ")
end

-- ============================================================
-- 4. LATIN → RE-SPELLING VISUAL (pseudo-Spanish)
-- ============================================================

function NotesObject:latinWordToRespelling(word)
  local w = word
  local out = ""
  local i = 1
  
  while i <= #w do
    local ch = w:sub(i, i)
    local next = w:sub(i + 1, i + 1)
    local next2 = w:sub(i + 2, i + 2)
    local prev = i > 1 and w:sub(i - 1, i - 1) or " "
    
    -- --- diphthongs AE/OE -> "e" ---
    local dip = self:readDiphthong(w, i)
    if dip then
      out = out .. dip.respell
      i = i + dip.jump
      goto continue
    end
    
    local pair = ch .. (next or "")
    
    -- GN → ñ
    if pair == "gn" then
      out = out .. "ñ"
      i = i + 2
      goto continue
    end
    
    -- PH → f
    if pair == "ph" then
      out = out .. "f"
      i = i + 2
      goto continue
    end
    
    -- TH → t
    if pair == "th" then
      out = out .. "t"
      i = i + 2
      goto continue
    end
    
    -- CH (χ) → c (Christus → cristus)
    if pair == "ch" then
      out = out .. "c"
      i = i + 2
      goto continue
    end
    
    -- CC + E/I → "cche" (ecce → ecche)
    if ch == "c" and next == "c" and (next2 == "e" or next2 == "i") then
      out = out .. "cche"
      i = i + 3
      goto continue
    end
    
    -- LL → "l-l"
    if ch == "l" and next == "l" then
      out = out .. "l-l"
      i = i + 2
      goto continue
    end
    
    -- QU + vowel -> "ku" + vowel
    if ch == "q" and next == "u" and self:isVowel(next2) then
      out = out .. "ku" .. next2
      i = i + 3
      goto continue
    end
    
    -- GU + E/I -> "gü" + vowel
    if ch == "g" and next == "u" and (next2 == "e" or next2 == "i") then
      out = out .. "gü" .. next2
      i = i + 3
      goto continue
    end
    
    -- SC + E/I -> "sh"
    if ch == "s" and next == "c" and (next2 == "e" or next2 == "i") then
      out = out .. "sh"
      i = i + 2
      goto continue
    end
    
    -- TI + vowel -> "tsi" + vowel
    -- Ex: GRATIA → gratsia
    if ch == "t" and next == "i" and self:isVowel(next2) and prev ~= "s" then
      out = out .. "tsi" .. next2
      i = i + 3
      goto continue
    end
    
    -- X → "x"
    if ch == "x" then
      out = out .. "x"
      i = i + 1
      goto continue
    end
    
    -- C:
    -- - before E/I → "ch"
    -- - rest → "c"
    if ch == "c" then
      if next == "e" or next == "i" then
        out = out .. "ch"
      else
        out = out .. "c"
      end
      i = i + 1
      goto continue
    end
    
    -- G:
    -- - before E/I → "y"
    -- - rest → "g"
    if ch == "g" then
      if next == "e" or next == "i" then
        out = out .. "y"
      else
        out = out .. "g"
      end
      i = i + 1
      goto continue
    end
    
    -- Latin V → "b" (volvo → bolbo)
    if ch == "v" then
      out = out .. "b"
      i = i + 1
      goto continue
    end
    
    -- Z → "ds" (zona → dsona)
    if ch == "z" then
      out = out .. "ds"
      i = i + 1
      goto continue
    end
    
    -- J → "y" (Jesus → yesus)
    if ch == "j" then
      out = out .. "y"
      i = i + 1
      goto continue
    end
    
    -- W → "u" (web → ueb)
    if ch == "w" then
      out = out .. "u"
      i = i + 1
      goto continue
    end
    
    -- H silent
    if ch == "h" then
      i = i + 1
      goto continue
    end
    
    -- Rest of letters as is
    if ch ~= " " then
      out = out .. ch
    end
    
    i = i + 1
    ::continue::
  end
  
  -- Break IU / UI with hyphen to guide SynthV
  return self:insertHiatusHyphens(out)
end

-- ============================================================
-- 5. FULL TEXT CONVERSION (maintaining line breaks)
-- ============================================================

function NotesObject:convertText(text)
  local norm = self:normalizeLatin(text)
  
  -- Split by lines to maintain breaks
  local lines = {}
  for line in norm:gmatch("[^\r\n]+") do
    table.insert(lines, line)
  end
  
  -- Handle case where text is empty or single line
  if #lines == 0 then
    lines = {norm}
  end
  
  local respLines = {}
  local phonemeLines = {}
  
  for _, line in ipairs(lines) do
    if line:match("^%s*$") then
      -- Empty line → keep empty
      table.insert(respLines, "")
      table.insert(phonemeLines, "")
    else
      local words = {}
      for word in line:gmatch("%S+") do
        table.insert(words, word)
      end
      
      local respWords = {}
      local phonWords = {}
      
      for _, word in ipairs(words) do
        table.insert(respWords, self:latinWordToRespelling(word))
        table.insert(phonWords, self:latinWordToXSAMPA(word))
      end
      
      table.insert(respLines, table.concat(respWords, " "))
      table.insert(phonemeLines, table.concat(phonWords, "  |  "))
    end
  end
  
  return {
    respell = table.concat(respLines, "\n"),
    phonemes = table.concat(phonemeLines, "\n")
  }
end

-- Get section
function NotesObject:getSection()
	
	local startInputTextButton = {
				type = "Container",
				columns = {
					{
						type = "Button",
						text = self.startButtonText,
						width = 1.0,
						value = self.startInpuptValue
					}
				}
			}

	local latinText = 
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.latinTextValue,
						height = 100,
						width = 1.0,
						readOnly = false
					}
				}
			}
	local pseudoSpanishText = 
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.pseudoSpanishValue,
						height = 100,
						width = 1.0,
						readOnly = false
					}
				}
			}
	local phonemesText = 
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.phonemesTextValue,
						height = 100,
						width = 1.0,
						readOnly = false
					}
				}
			}

	local comboBoxRules = {
			type = "Container",
			columns = {
				{
					type = "ComboBox",
					text = SV:T("Rules"),
					value = self.controls.rulesValue.value,
					choices = self.rulesListChoice,
					width = 1.0
				}
			}
		}
		
	local rulesText = 
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.rulesTextValue,
						height = 200,
						width = 1.0,
						readOnly = true
					}
				}
			}
			
	
	-- Define CheckBox & button & textarea
	local section = {
		title = SV:T(SCRIPT_TITLE),
		rows = {
			startInputTextButton,
			{
				type = "Container",
				columns = {
					{
						type = "TextArea",
						value = self.statusTextValue,
						height = 40,
						width = 1.0,
						readOnly = true
					}
				}
			},
			{
				type = "Label",
				text = SV:T("Latin:"),
			},
			latinText,
			{
				type = "Label",
				text = SV:T("Pseudo spanish:"),
			},
			pseudoSpanishText,
			{
				type = "Label",
				text = SV:T("Phonemes:"),
			},
			phonemesText,
			{
				type = "Label",
				text = SV:T("Rules conversions:"),
			},
			comboBoxRules,
			rulesText
		}
	}
	return section
end

-- Get panel section state
function NotesObject:getPanelSectionState()

	self.startInpuptValue:setEnabled(true)
	local errors = self:displayErrors()
	if #errors > 0 then
		self:addTextPanel(errors)
	end
	
	-- Get section data
	local section = self:getSection()

	return section
end

-- Initialize main internal object	
local notesObject = NotesObject:new()

-- Get panel section state called by Synthesizer V internal system
function getSidePanelSectionState()
	notesObject:setRulesInit()
	local section = notesObject:getPanelSectionState()

	return section
end
