from pyscript import document, when

class vigenere:
    def __init__(self, key):
        self.key = key.lower()
        self.alpha = 'abcdefghijklmnopqrstuvwxyz'

    def encdec(self, text, is_cipher):
        text = text.lower()
        # FIXED: True means we are decrypting a cipher (shift backwards), False means encoding (shift forwards)
        factor = -1 if is_cipher else 1

        result = []
        j = 0

        for char in text:
            if char in self.alpha:
                text_idx = self.alpha.index(char)
                key_char = self.key[j % len(self.key)]
                key_idx = self.alpha.index(key_char)

                new_idx = (text_idx + factor * key_idx) % 26
                result.append(self.alpha[new_idx])
                j += 1
            else:
                result.append(char)

        return "".join(result)

# FIXED: Added the explicit click binding decorator
@when("click", "#btn-encode")
def handle_encode(event):
    text = document.getElementById("message").value
    key = document.getElementById("cipher-key").value
    
    if not key:
        document.getElementById("output").innerText = "Error: Key cannot be empty!"
        return
        
    # FIXED: Properly create a class instance and call its internal method
    cipher_tool = vigenere(key)
    encrypted_text = cipher_tool.encdec(text, is_cipher=False)
    document.getElementById("output").innerText = encrypted_text

# FIXED: Added the explicit click binding decorator
@when("click", "#btn-decode")
def handle_decode(event):
    text = document.getElementById("message").value
    key = document.getElementById("cipher-key").value
    
    if not key:
        document.getElementById("output").innerText = "Error: Key cannot be empty!"
        return
        
    # FIXED: Properly create a class instance and call its internal method
    cipher_tool = vigenere(key)
    decrypted_text = cipher_tool.encdec(text, is_cipher=True)
    document.getElementById("output").innerText = decrypted_text