// Simple example, see optional options for more configuration.
document.addEventListener("DOMContentLoaded", () => {
	const option_values_module = {
		init() {
			this.option_values = window.OrphicWPBlockOptions;
		},
		//get setter
		get(option_name) {
			return this.option_values[option_name];
		},
		set(option_name, value) {
			this.option_values[option_name] = value;
		},
	};
	option_values_module.init();

	//module theme
	const theme_module = {
		custom_button: null,
		classic_button: null,

		init() {
			this.custom_button = document.querySelector(
				".orphic-wp-block-option-page-button.custom-button",
			);
			this.classic_button = document.querySelector(
				".orphic-wp-block-option-page-button.classic-button",
			);
			this.events();
		},

		events() {
			// Utiliser des fonctions fléchées
			this.custom_button.addEventListener("click", () =>
				this.clickOnCustomButton(),
			);
			this.classic_button.addEventListener("click", () =>
				this.clickOnClassicButton(),
			);
		},

		clickOnCustomButton() {
			if (!this.custom_button.classList.contains("active")) {
				this.setGlobalColorPalette(
					window.ConstBlockOrphicOptionValue.GLOBAL_COLOR_PALETTE_CUSTOM,
				);
				this.toggleActiveButton(this.classic_button);
				this.toggleActiveButton(this.custom_button);
				this.toggleColorsContainer(this.getColorsContainer());
				this.toggleClassicColorsContainer(this.getClassicColorsContainer(), false);
			}
		},

		clickOnClassicButton() {
			if (!this.classic_button.classList.contains("active")) {
				this.setGlobalColorPalette(
					window.ConstBlockOrphicOptionValue.GLOBAL_COLOR_PALETTE_CLASSIC,
				);
				this.toggleActiveButton(this.classic_button);
				this.toggleActiveButton(this.custom_button);
				this.toggleColorsContainer(this.getColorsContainer());
				this.toggleClassicColorsContainer(this.getClassicColorsContainer(), true);
			}
		},

		getColorsContainer() {
			return document.querySelector(
				".orphic-wp-block-option-page-theme-container-choice-color",
			);
		},
		
		getClassicColorsContainer() {
			return document.querySelector(
				".orphic-wp-block-option-page-theme-container-classic-colors",
			);
		},

		toggleActiveButton(button) {
			button.classList.toggle("active");
		},

		toggleColorsContainer(container) {
			container.classList.toggle("visible");
		},
		
		toggleClassicColorsContainer(container, show) {
			if (show) {
				container.classList.add("visible");
			} else {
				container.classList.remove("visible");
			}
		},

		/**
		 * Set the global color palette
		 * @param {window.ConstBlockOrphicOptionValue} palette
		 */
		setGlobalColorPalette(palette) {
			option_values_module.set(
				window.ConstBlockOrphicOptionName.GLOBAL_COLOR_PALETTE,
				palette,
			);
		},
	};
	theme_module.init();

	const save_module = {
		save_button: null,
		init() {
			this.save_button = document.querySelector(
				".orphic-wp-block-option-page-button.save-button",
			);
			this.events();
		},
		events() {
			this.save_button.addEventListener("click", async () =>
				this.clickOnSaveButton(),
			);
		},
		clickOnSaveButton() {
			this.save_options();
			this.save_active_blocks();
			this.save_active_modules();
			this.save_breakpoint_settings();

      //save the current panel in local storage
      localStorage.setItem("orphic_wp_block_option_page_current_panel", tabsUIModule.currentPanel);

      //wait 2 seconds
      setTimeout(() => {
        //reload the page
        location.reload();
      }, 2000);

      
		},
    async save_options (){
      this.ui_onload();
      this.save_colors();
      this.save_google_api_key();
      this.ui_saved();
    },
    async save_google_api_key (){
      const formData = new FormData();
      const google_api_key = document.querySelector(".orphic-wp-block-option-page-google-map-api-key-input");
      formData.append("action", "orphic_wp_block_save_google_api_key");
      formData.append("google_api_key", google_api_key.value);
      this.ui_send();
      const response = await fetch(window.ajax_object.ajax_url, {
				method: "POST",
				body: formData,
			});

      const response_json = await response.json();
    },
		async save_colors() {
			const formData = new FormData();
			formData.append("action", "orphic_wp_block_save_colors");
			formData.append(
				"plugin_colors",
				JSON.stringify(
					option_values_module.get(
						window.ConstBlockOrphicOptionName.PLUGIN_COLORS_CUSTOM,
					),
				),
			);
			formData.append(
				"global_color_palette",
				option_values_module.get(
					window.ConstBlockOrphicOptionName.GLOBAL_COLOR_PALETTE,
				),
			);
			this.ui_send();
			await fetch(window.ajax_object.ajax_url, {
				method: "POST",
				body: formData,
			});
		},
    async save_breakpoint_settings() {
      const formData = new FormData();
      formData.append("action", "orphic_wp_block_save_breakpoint_settings");
      formData.append("breakpoint_settings", JSON.stringify({
        mobile: document.getElementById('mobile-breakpoint').value,
        tabletMin: document.getElementById('tablet-breakpoint').value,
        tabletMax: document.getElementById('tablet-breakpoint-max').value,
        desktop: document.getElementById('desktop-breakpoint').value
      }));
      this.ui_send();
      await fetch(window.ajax_object.ajax_url, {
        method: "POST",
        body: formData,
      });
    },

		async save_active_blocks() {
			const active_checkboxes = document.querySelectorAll(
				".orphic-blocks-seclector-checkboxes:checked",
			);

			const active_checkboxes_values = [];
			active_checkboxes.forEach((checkbox) =>
				active_checkboxes_values.push(checkbox.value),
			);
			this.ui_onload();

			const formData = new FormData();

			formData.append("action", "orphic_wp_block_save_active_blocks");
			formData.append(
				"active_blocks",
				JSON.stringify(active_checkboxes_values),
			);
			this.ui_send();
			let response = await fetch(window.ajax_object.ajax_url, {
				method: "POST",
				body: formData,
			});
			response = await response.json();
		},

		async save_active_modules() {
			const active_checkboxes = document.querySelectorAll(
				".orphic-modules-selector-checkboxes:checked",
			);

			const active_checkboxes_values = [];
			active_checkboxes.forEach((checkbox) =>
				active_checkboxes_values.push(checkbox.value),
			);
			this.ui_onload();

			const formData = new FormData();

			formData.append("action", "orphic_wp_block_save_active_modules");
			formData.append(
				"active_modules",
				JSON.stringify(active_checkboxes_values),
			);
			this.ui_send();
			let response = await fetch(window.ajax_object.ajax_url, {
				method: "POST",
				body: formData,
			});
			response = await response.json();
			
		},

		ui_onload() {
			this.save_button.disabled = true;
			this.save_button.innerHTML = "loading...";
		},

		ui_send() {
			this.save_button.innerHTML = "saving...";
			this.save_button.classList.add("saving");
		},

		ui_saved() {
			this.save_button.disabled = false;
			this.save_button.innerHTML = "save";
			this.save_button.classList.remove("saving");
		},
	};
	save_module.init();

	const colorsPickrModule = {
		init() {
			this.picker_container = document.querySelectorAll(
				".color-picker-container",
			);
			this.setPickrs();
		},

		setPickrs() {
			for (picker of this.picker_container) {
				const color_slug = picker.getAttribute("data-color-slug");
				const color_save = picker.getAttribute("data-color-save");

				const color_picker = picker.querySelector(".color-picker");
				const pickr = Pickr.create({
					el: color_picker,
					theme: "nano", // or 'monolith', or 'nano'
					position: "right", // Position the picker on the right side
					swatches: window.themeJsonColors.map(
						(theme_color) => theme_color.color,
					),
					default: color_save,
					components: {
						preview: true,
						opacity: true,
						hue: true,
						interaction: {
							hex: true,
							rgba: true,
							hsla: true,
							hsva: true,
							input: true,
							clear: true,
							save: true,
						},
					},
				}).on("save", (color) => {
					option_values_module
						.get(window.ConstBlockOrphicOptionName.PLUGIN_COLORS_CUSTOM)
						.forEach((meta) => {
							if (meta.slug === color_slug) {
								meta.color = color.toHEXA().toString();
								console.log(meta);
							}
						});
				});
			}
		},
	};
	colorsPickrModule.init();

  //reset default breakpoint settings. Create module if more feature for breakpoint.
	document.querySelectorAll('.reset-default').forEach(button => {
		button.addEventListener('click', function() {
			const input = this.previousElementSibling;
			input.value = this.getAttribute('data-default');
		});
	});
});
