/**
 * @fileoverview Utility module for blocks.js
 * @module games.quebracabecas.blocks.blocks
 */

"use strict";

import * as Blockly from "blockly/core";
import "blockly/blocks";
import { javascriptGenerator } from "blockly/javascript";


const HUE_TIPO = "#ff6b9d";      
const HUE_PATAS = "#c41e3a";    
const HUE_CORPO = "#9333ea";     
const HUE_MOVIMENTO = "#ed1b2f"; 
const HUE_SOM = "#ed0973";   

export const registerBlocks = () => {
  defineBlocks();
  defineGenerators();
};

export const generateDynamicToolbox = (allowedBlocks = []) => {
  const blockDefinitions = {
    animal_tipo: { kind: "block", type: "animal_tipo" },
    animal_patas: { kind: "block", type: "animal_patas" },
    animal_cobertura: { kind: "block", type: "animal_cobertura" },
    animal_locomocao: { kind: "block", type: "animal_locomocao" },
    animal_som: { kind: "block", type: "animal_som" },
  };

  const toolboxContents = {
    kind: "categoryToolbox",
    contents: [
      {
        kind: "category",
        name: "Tipo de Animal",
        colour: HUE_TIPO,
        contents: [],
        cssConfig: { container: "cat_tipo" },
      },
      {
        kind: "category",
        name: "Patas",
        colour: HUE_PATAS,
        contents: [],
        cssConfig: { container: "cat_patas" },
      },
      {
        kind: "category",
        name: "Corpo",
        colour: HUE_CORPO,
        contents: [],
        cssConfig: { container: "cat_corpo" },
      },
      {
        kind: "category",
        name: "Movimento",
        colour: HUE_MOVIMENTO,
        contents: [],
        cssConfig: { container: "cat_movimento" },
      },
      {
        kind: "category",
        name: "Som",
        colour: HUE_SOM,
        contents: [],
        cssConfig: { container: "cat_som" },
      },
    ],
  };

  const categoryMap = {
    animal_tipo: 0,
    animal_patas: 1,
    animal_cobertura: 2,
    animal_locomocao: 3,
    animal_som: 4,
  };

  allowedBlocks.forEach((blockId) => {
    const blockDef = blockDefinitions[blockId];
    if (!blockDef) return;

    const categoryIndex = categoryMap[blockId];
    if (categoryIndex !== undefined && toolboxContents.contents[categoryIndex]) {
      if (!toolboxContents.contents[categoryIndex].contents) {
        toolboxContents.contents[categoryIndex].contents = [];
      }
      toolboxContents.contents[categoryIndex].contents.push(blockDef);
    }
  });

  // Filtra categorias vazias
  toolboxContents.contents = toolboxContents.contents.filter(
    (cat) => cat.contents && cat.contents.length > 0
  );

  return toolboxContents;
};

const defineBlocks = () => {
  // Bloco Pai: Tipo (Abre o escopo para as características)
  Blockly.Blocks["animal_tipo"] = {
    init: function () {
      this.appendDummyInput()
        .appendField("Definir o tipo do animal:")
        .appendField(new Blockly.FieldDropdown([
          ["Mamífero", "mamifero"],
          ["Ave", "ave"],
          ["Réptil", "reptil"],
          ["Anfíbio", "anfibio"],
          ["Peixe", "peixe"],
          ["Inseto", "inseto"],
          ["Aracnídeo", "aracnideo"],
          ["Molusco", "molusco"]
        ]), "TIPO");
      
      this.appendStatementInput("CARACTERISTICAS")
        .setCheck(null)
        .appendField("com as características:");
        
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);
      this.setColour(HUE_TIPO);
      this.setTooltip("Define o tipo do animal e agrupa suas características.");
    },
  };

  Blockly.Blocks["animal_patas"] = {
    init: function () {
      this.appendDummyInput()
        .appendField("Quantidade de patas:")
        .appendField(new Blockly.FieldDropdown([
          ["0", "0"], ["2", "2"], ["4", "4"], ["6", "6"], ["8", "8"]
        ]), "VALOR");
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);
      this.setColour(HUE_PATAS);
    },
  };

  Blockly.Blocks["animal_cobertura"] = {
    init: function () {
      this.appendDummyInput()
        .appendField("Cobertura do corpo:")
        .appendField(new Blockly.FieldDropdown([
          ["Pelos", "Pelos"], ["Penas", "Penas"], ["Escamas", "Escamas"],
          ["Casco", "Casco"], ["Pele Úmida", "Pele Úmida"], ["Pele Escamosa", "Pele Escamosa"], ["Exoesqueleto", "Exoesqueleto"]
        ]), "VALOR");
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);
      this.setColour(HUE_CORPO);
    },
  };

  Blockly.Blocks["animal_locomocao"] = {
    init: function () {
      this.appendDummyInput()
        .appendField("Como se locomove:")
        .appendField(new Blockly.FieldDropdown([
          ["Anda", "Anda"], ["Voa", "Voa"], ["Nada", "Nada"],
          ["Rasteja", "Rasteja"], ["Pula", "Pula"]
        ]), "VALOR");
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);
      this.setColour(HUE_MOVIMENTO);
    },
  };

  Blockly.Blocks["animal_som"] = {
    init: function () {
      this.appendDummyInput()
        .appendField("Som que emite:")
        .appendField(new Blockly.FieldDropdown([
          ["Miado", "Miau"], ["Latido", "Auau"], ["Grasnado", "Quack"],
          ["Zumbido", "Zumbido"], ["Rugido", "Rugido"], ["Coaxado", "Coaxado"], ["Silencioso", "Silencioso"]
        ]), "VALOR");
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);
      this.setColour(HUE_SOM);
    },
  };
};

const defineGenerators = () => {
  javascriptGenerator.STATEMENT_PREFIX = "highlightBlock(%1);\n";
  javascriptGenerator.addReservedWords("highlightBlock");

  // Gerador do Bloco Pai – gera código sequencial, sem callback
  javascriptGenerator.forBlock["animal_tipo"] = function (block) {
    const tipo = block.getFieldValue("TIPO");
    const caracteristicasInternas = javascriptGenerator.statementToCode(block, "CARACTERISTICAS");
    
    return `definirTipoAnimal("${tipo}");
${caracteristicasInternas}`;
  };

  // Geradores dos Blocos Filhos
  javascriptGenerator.forBlock["animal_patas"] = function (block) {
    const valor = block.getFieldValue("VALOR");
    return `definirCaracteristica("patas", ${parseInt(valor, 10)});\n`;
  };

  javascriptGenerator.forBlock["animal_cobertura"] = function (block) {
    const valor = block.getFieldValue("VALOR");
    return `definirCaracteristica("cobertura", "${valor}");\n`;
  };

  javascriptGenerator.forBlock["animal_locomocao"] = function (block) {
    const valor = block.getFieldValue("VALOR");
    return `definirCaracteristica("locomocao", "${valor}");\n`;
  };

  javascriptGenerator.forBlock["animal_som"] = function (block) {
    const valor = block.getFieldValue("VALOR");
    return `definirCaracteristica("som", "${valor}");\n`;
  };
};