let selections = {
  genero: "",
  estetica: "",
  visual: "",
  tipoCamera: "",
  marca: "",
  modelo: "",
  lente: "",
  abertura: "",
  velocidade: "",
  iso: "",
  formato: "",
  efeito: "",
  iluminacao: "",
  sujeito: "",
  artMedium: "",
  camera: "",
  color: "",
  dimensionality: "",
  display: "",
  geometry: "",
  intangibles: "",
  lighting: "",
  material: "",
  postProcessing: "",
  artist: "",
  style: "",
  aspectRatio: "",
  acao: "",
  local: "",
  detalhesFundo: "",
  vestuario: "",
  perspectiva: "",
  epocaTema: "",
  expressao: "",
  motivo: "",
  detalhesCena: "", // Novo campo adicionado
};
function populateSelect(selector, items) {
  const $select = $(selector);
  $select.empty();
  $select.append('');
  items.forEach((item) => {
    $select.append(
      ``
    );
  });
  $select.select2({
    templateResult: formatOption,
    templateSelection: formatOption,
    allowClear: true,
    placeholder: "Selecione uma opção ou deixe em branco",
  });
  // Inicializa tooltips no dropdown quando aberto
  $select.on("select2:open", function () {
    setTimeout(() => {
      // Remove tooltips antigos
      $(".select2-results__option .fas.fa-question-circle").tooltip("dispose");
      // Inicializa novos tooltips nos ícones
      $(".select2-results__option .fas.fa-question-circle").each(function () {
        const $this = $(this);
        const description = $this.attr("title");
        if (description) {
          $this.tooltip({
            placement: "right",
            trigger: "hover",
            container: "body",
            boundary: "window",
          });
        }
      });
    }, 0);
  });
  // Remove todos os tooltips ao fechar o dropdown
  $select.on("select2:close", function () {
    setTimeout(() => {
      $(".tooltip").remove();
    }, 100);
  });
  // Inicializa tooltips na opção selecionada ao mudar
  $select.on("change", function () {
    $(".select2-selection__rendered .fas.fa-question-circle").tooltip(
      "dispose"
    );
    $(".select2-selection__rendered .fas.fa-question-circle").each(function () {
      const $this = $(this);
      const description = $this.attr("title");
      if (description) {
        $this.tooltip({
          placement: "bottom",
          trigger: "hover",
          container: "body",
          boundary: "window",
        });
      }
    });
  });
}
function formatOption(option) {
  // Caso seja o placeholder vazio
  if (!option.id && option.text === "") {
    return $("Selecione uma opção ou deixe em branco");
  }
  // Obtém a descrição da opção
  const description = option.element
    ? option.element.dataset.description || ""
    : "";
  // Cria o elemento de texto
  const $text = $(`${option.text}`);
  // Cria um container flex para alinhar texto e ícone
  const $option = $(
    ''
  );
  $option.append($text);
  // Se houver descrição, adiciona o ícone com tooltip
  if (description) {
    const $icon = $('');
    $icon.attr("data-bs-toggle", "tooltip").attr("title", description);
    $option.append($icon);
  }
  return $option;
}
function updatePrompt() {
  let prompt = [];
  if (selections.genero)
    prompt.push(`Uma foto de ${selections.genero.toLowerCase()}`);
  if (selections.estetica && selections.estetica !== "Nenhum")
    prompt.push(`no estilo ${selections.estetica.toLowerCase()}`);
  if (selections.visual && selections.visual !== "Nenhum")
    prompt.push(`mostrando ${selections.visual.toLowerCase()}`);
  if (selections.sujeito) prompt.push(`de ${selections.sujeito}`);
  if (selections.acao)
    prompt.push(`realizando a ação ${selections.acao.toLowerCase()}`);
  if (selections.local)
    prompt.push(`em um local ${selections.local.toLowerCase()}`);
  if (selections.detalhesFundo)
    prompt.push(
      `com detalhes de fundo como ${selections.detalhesFundo.toLowerCase()}`
    );
  if (selections.vestuario)
    prompt.push(`vestindo ${selections.vestuario.toLowerCase()}`);
  if (selections.perspectiva)
    prompt.push(`na perspectiva ${selections.perspectiva.toLowerCase()}`);
  if (selections.epocaTema)
    prompt.push(`com tema ou época ${selections.epocaTema.toLowerCase()}`);
  if (selections.expressao)
    prompt.push(`com expressão ${selections.expressao.toLowerCase()}`);
  if (selections.motivo)
    prompt.push(`por motivo de ${selections.motivo.toLowerCase()}`);
  if (selections.detalhesCena)
    prompt.push(
      `com detalhes da cena como ${selections.detalhesCena.toLowerCase()}`
    );
  if (selections.aspectRatio)
    prompt.push(`em aspect ratio ${selections.aspectRatio.toLowerCase()}`);
  if (
    selections.tipoCamera === "Câmera Profissional" &&
    selections.marca &&
    selections.modelo
  ) {
    prompt.push(
      `tirada com uma câmera ${selections.marca} ${selections.modelo}`
    );
    if (selections.lente) prompt.push(`lente ${selections.lente}`);
    if (selections.abertura) prompt.push(`abertura ${selections.abertura}`);
    if (selections.velocidade)
      prompt.push(`velocidade do obturador ${selections.velocidade}`);
    if (selections.iso) prompt.push(`ISO ${selections.iso}`);
    if (selections.formato) prompt.push(`em formato ${selections.formato}`);
  } else if (selections.tipoCamera) {
    prompt.push(`tirada com ${selections.tipoCamera.toLowerCase()}`);
  }
  if (selections.efeito && selections.efeito !== "Nenhum")
    prompt.push(`com efeito ${selections.efeito.toLowerCase()}`);
  if (selections.iluminacao && selections.iluminacao !== "Nenhum")
    prompt.push(`com iluminação ${selections.iluminacao.toLowerCase()}`);
  if (selections.artMedium)
    prompt.push(`em meio artístico ${selections.artMedium.toLowerCase()}`);
  if (selections.camera)
    prompt.push(`usando câmera ${selections.camera.toLowerCase()}`);
  if (selections.color) prompt.push(`em ${selections.color.toLowerCase()}`);
  if (selections.dimensionality)
    prompt.push(`em ${selections.dimensionality.toLowerCase()}`);
  if (selections.display)
    prompt.push(`exibido em ${selections.display.toLowerCase()}`);
  if (selections.geometry)
    prompt.push(`com geometria ${selections.geometry.toLowerCase()}`);
  if (selections.intangibles)
    prompt.push(`evocando ${selections.intangibles.toLowerCase()}`);
  if (selections.lighting)
    prompt.push(`com iluminação ${selections.lighting.toLowerCase()}`);
  if (selections.material)
    prompt.push(`feito de ${selections.material.toLowerCase()}`);
  if (selections.postProcessing)
    prompt.push(
      `com pós-processamento ${selections.postProcessing.toLowerCase()}`
    );
  if (selections.artist)
    prompt.push(`arte inspirada em ${selections.artist.toLowerCase()}`);
  if (selections.style)
    prompt.push(`no estilo de ${selections.style.toLowerCase()}`);
  $(".textarea-prompt").val(prompt.length ? `${prompt.join(", ")}.` : "");
}
$(document).ready(function () {
  $(".select2").select2({
    allowClear: true,
    placeholder: "Selecione uma opção ou deixe em branco",
  });
  populateSelect(".select-genero", options.generos);
  populateSelect(".select-estetica", options.esteticas);
  populateSelect(".select-visual", options.visuais);
  populateSelect(".select-tipo-camera", options.tiposCamera);
  populateSelect(".select-marca", options.marcas);
  populateSelect(".select-modelo", options.modelos.Canon);
  populateSelect(".select-lente", options.lentes.Canon);
  populateSelect(".select-abertura", options.aberturas);
  populateSelect(".select-velocidade", options.velocidades);
  populateSelect(".select-iso", options.isos);
  populateSelect(".select-formato", options.formatos);
  populateSelect(".select-efeito", options.efeitos);
  populateSelect(".select-iluminacao", options.iluminacoes); // Novo select para iluminação
  populateSelect(".select-art-medium", options.artMedium);
  populateSelect(".select-camera", options.camera);
  populateSelect(".select-color", options.color);
  populateSelect(".select-dimensionality", options.dimensionalities);
  populateSelect(".select-display", options.displays);
  populateSelect(".select-geometry", options.geometries);
  populateSelect(".select-intangibles", options.intangibles);
  populateSelect(".select-lighting", options.lightings);
  populateSelect(".select-material", options.materials);
  populateSelect(".select-post-processing", options.postProcessings);
  populateSelect(".select-artist", options.artists);
  populateSelect(".select-style", options.styles);
  populateSelect(".select-aspect-ratio", options.aspectRatios);
  populateSelect(".select-perspectiva", options.perspectivas);
  $(".select-marca").on("change", function () {
    const marca = $(this).val() || "";
    selections.marca = marca;
    populateSelect(
      ".select-modelo",
      options.modelos[marca] || [{ value: "", text: "Nenhum", description: "" }]
    );
    populateSelect(
      ".select-lente",
      options.lentes[marca] || [{ value: "", text: "Nenhum", description: "" }]
    );
    selections.modelo = "";
    selections.lente = "";
    updatePrompt();
  });
  $(".select-genero").on("change", function () {
    selections.genero = $(this).val() || "";
    updatePrompt();
  });
  $(".select-estetica").on("change", function () {
    selections.estetica = $(this).val() || "";
    updatePrompt();
  });
  $(".select-visual").on("change", function () {
    selections.visual = $(this).val() || "";
    updatePrompt();
  });
  $(".select-tipo-camera").on("change", function () {
    selections.tipoCamera = $(this).val() || "";
    if (selections.tipoCamera === "Câmera Profissional") {
      $("#camera-profissional-options").show();
    } else {
      $("#camera-profissional-options").hide();
    }
    updatePrompt();
  });
  $(".select-modelo").on("change", function () {
    selections.modelo = $(this).val() || "";
    updatePrompt();
  });
  $(".select-lente").on("change", function () {
    selections.lente = $(this).val() || "";
    updatePrompt();
  });
  $(".select-abertura").on("change", function () {
    selections.abertura = $(this).val() || "";
    updatePrompt();
  });
  $(".select-velocidade").on("change", function () {
    selections.velocidade = $(this).val() || "";
    updatePrompt();
  });
  $(".select-iso").on("change", function () {
    selections.iso = $(this).val() || "";
    updatePrompt();
  });
  $(".select-formato").on("change", function () {
    selections.formato = $(this).val() || "";
    updatePrompt();
  });
  $(".select-efeito").on("change", function () {
    selections.efeito = $(this).val() || "";
    updatePrompt();
  });
  $(".select-iluminacao").on("change", function () {
    // Alterado para select
    selections.iluminacao = $(this).val() || "";
    updatePrompt();
  });
  $("#select-sujeito").on("input", function () {
    selections.sujeito = $(this).val();
    updatePrompt();
  });
  $(".select-art-medium").on("change", function () {
    selections.artMedium = $(this).val() || "";
    updatePrompt();
  });
  $(".select-camera").on("change", function () {
    selections.camera = $(this).val() || "";
    updatePrompt();
  });
  $(".select-color").on("change", function () {
    selections.color = $(this).val() || "";
    updatePrompt();
  });
  $(".select-dimensionality").on("change", function () {
    selections.dimensionality = $(this).val() || "";
    updatePrompt();
  });
  $(".select-display").on("change", function () {
    selections.display = $(this).val() || "";
    updatePrompt();
  });
  $(".select-geometry").on("change", function () {
    selections.geometry = $(this).val() || "";
    updatePrompt();
  });
  $(".select-intangibles").on("change", function () {
    selections.intangibles = $(this).val() || "";
    updatePrompt();
  });
  $(".select-lighting").on("change", function () {
    selections.lighting = $(this).val() || "";
    updatePrompt();
  });
  $(".select-material").on("change", function () {
    selections.material = $(this).val() || "";
    updatePrompt();
  });
  $(".select-post-processing").on("change", function () {
    selections.postProcessing = $(this).val() || "";
    updatePrompt();
  });
  $(".select-artist").on("change", function () {
    selections.artist = $(this).val() || "";
    updatePrompt();
  });
  $(".select-style").on("change", function () {
    selections.style = $(this).val() || "";
    updatePrompt();
  });
  $(".select-aspect-ratio").on("change", function () {
    selections.aspectRatio = $(this).val() || "";
    updatePrompt();
  });
  $("#input-acao").on("input", function () {
    selections.acao = $(this).val();
    updatePrompt();
  });
  $("#input-local").on("input", function () {
    selections.local = $(this).val();
    updatePrompt();
  });
  $("#input-detalhes-fundo").on("input", function () {
    selections.detalhesFundo = $(this).val();
    updatePrompt();
  });
  $("#input-vestuario").on("input", function () {
    selections.vestuario = $(this).val();
    updatePrompt();
  });
  $(".select-perspectiva").on("change", function () {
    selections.perspectiva = $(this).val() || "";
    updatePrompt();
  });
  $("#input-epoca-tema").on("input", function () {
    selections.epocaTema = $(this).val();
    updatePrompt();
  });
  $("#input-expressao").on("input", function () {
    selections.expressao = $(this).val();
    updatePrompt();
  });
  $("#input-motivo").on("input", function () {
    selections.motivo = $(this).val();
    updatePrompt();
  });
  $("#input-detalhes-cena").on("input", function () {
    // Novo listener
    selections.detalhesCena = $(this).val();
    updatePrompt();
  });
  $("#copyBtn").on("click", function (event) {
    event.preventDefault();
    event.stopPropagation();
    const promptText = $("#textarea-prompt").val();
    if (promptText) {
      navigator.clipboard
        .writeText(promptText)
        .then(() => {
          const originalText = $("#copyBtn").text();
          $("#copyBtn").text("Copiado!");
          setTimeout(() => {
            $("#copyBtn").text(originalText);
          }, 2000);
        })
        .catch((err) => {
          console.error("Erro ao copiar o texto: ", err);
        });
    }
  });
  $("#resetBtn").on("click", function () {
    $(".select2").val("").trigger("change");
    $(".form-control").val("");
    selections = {
      genero: "",
      estetica: "",
      visual: "",
      tipoCamera: "",
      marca: "",
      modelo: "",
      lente: "",
      abertura: "",
      velocidade: "",
      iso: "",
      formato: "",
      efeito: "",
      iluminacao: "",
      sujeito: "",
      artMedium: "",
      camera: "",
      color: "",
      dimensionality: "",
      display: "",
      geometry: "",
      intangibles: "",
      lighting: "",
      material: "",
      postProcessing: "",
      artist: "",
      style: "",
      aspectRatio: "",
      acao: "",
      local: "",
      detalhesFundo: "",
      vestuario: "",
      perspectiva: "",
      epocaTema: "",
      expressao: "",
      motivo: "",
      detalhesCena: "",
    };
    $("#camera-profissional-options").hide();
    updatePrompt();
  });
});