//access_hr1
import api from "../../api.js";

export default new Vue({
	el:"#wotd",
	data() {
		return {
			data:{},
			permissions:[],
			editable:false
		}
	},
	components: {
	},
	async mounted(){
		this.data = await api.get[`wotd`]()

		// Ensure key is always 'wotd'
		if (this.data && !this.data.key) {
			this.data.key = 'wotd';
		}

		this.permissions = await api.get[`permissions`]()

		// Manually update the display span with loaded value (workaround for Vue reactivity)
		setTimeout(() => {
			const displaySpan = document.getElementById('wotd-display');
			if (displaySpan && this.data && this.data.value) {
				displaySpan.textContent = this.data.value;
			}
		}, 100);

		// Setup edit and save handlers (workaround for Vue/AngularJS conflict)
		const editLink = document.getElementById('wotd-edit');
		const saveButton = document.getElementById('wotd-save');
		const cancelButton = document.getElementById('wotd-cancel');

		if(editLink) {
			if(this.isPermissions('access_hr')) {
				// Show edit link and add click handler
				editLink.style.setProperty('display', 'inline-block', 'important');
				editLink.addEventListener('click', (e) => {
					e.preventDefault();
					e.stopPropagation();
					this.toggleEdit();
				});
			} else {
				// Keep edit link hidden if no permission
				editLink.style.setProperty('display', 'none', 'important');
			}
		}

		if (saveButton) {
			saveButton.addEventListener('click', async (e) => {
				e.preventDefault();
				await this.save();
			});
		}

		if (cancelButton) {
			cancelButton.addEventListener('click', (e) => {
				e.preventDefault();
				this.cancel();
			});
		}
	},
	methods: {
		isPermissions(p){
			return this.permissions.find(el=>el.permissions == p) != null
		},
		toggleEdit(){
			const displaySpan = document.getElementById('wotd-display');
			const input = document.getElementById('wotd-input');
			const saveButton = document.getElementById('wotd-save');
			const cancelButton = document.getElementById('wotd-cancel');
			const editLink = document.getElementById('wotd-edit');

			if (this.editable) {
				// Switch to display mode
				if (displaySpan) displaySpan.style.setProperty('display', 'inline', 'important');
				if (input) input.style.setProperty('display', 'none', 'important');
				if (saveButton) saveButton.style.setProperty('display', 'none', 'important');
				if (cancelButton) cancelButton.style.setProperty('display', 'none', 'important');
				if (editLink) editLink.style.setProperty('display', 'inline-block', 'important');
				this.editable = false;
			} else {
				// Switch to edit mode
				if (displaySpan) displaySpan.style.setProperty('display', 'none', 'important');
				if (input) {
					input.style.setProperty('display', 'inline', 'important');
					input.style.setProperty('visibility', 'visible', 'important');
					setTimeout(() => input.focus(), 50);
				}
				if (saveButton) {
					saveButton.style.setProperty('display', 'inline', 'important');
					saveButton.style.setProperty('visibility', 'visible', 'important');
				}
				if (cancelButton) {
					cancelButton.style.setProperty('display', 'inline', 'important');
					cancelButton.style.setProperty('visibility', 'visible', 'important');
				}
				if (editLink) editLink.style.setProperty('display', 'none', 'important');
				this.editable = true;
			}
		},
		cancel(){
			// Reset input to original value
			const input = document.getElementById('wotd-input');
			if (input && this.data) {
				input.value = this.data.value;
			}
			// Switch back to display mode without saving
			this.toggleEdit();
		},
		async save(){
			try {
				// Get the actual value from the input element (v-model might not be syncing)
				const input = document.getElementById('wotd-input');
				const actualValue = input ? input.value : this.data.value;

				// Ensure we're sending the correct payload with the actual input value
				const payload = {
					id: this.data.id,
					key: 'wotd',
					value: actualValue
				};

				const response = await fetch('/api/v1/settings', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
					},
					body: JSON.stringify(payload)
				});

				if (response.ok) {
					const result = await response.json();

					// Update local data with saved value
					if (result.data) {
						this.data = result.data;
						// Ensure key is set
						if (!this.data.key) {
							this.data.key = 'wotd';
						}
					} else {
						// If no data returned, update with the value we just saved
						this.data.value = actualValue;
					}

					// Update the display span with the new value
					const displaySpan = document.getElementById('wotd-display');
					if (displaySpan) {
						displaySpan.textContent = actualValue;
					}

					this.toggleEdit(); // Switch back to display mode
				} else {
					throw new Error('Server returned ' + response.status);
				}
			} catch (error) {
				console.error('[WOTD] Save error:', error);
				alert('Failed to save: ' + error.message);
			}
		}

	},
	template:html`
		<div class="widget widget-classic">
			<div class="widget-content">
				<div class="headline">
					<h4>
						<span style="font-weight: normal;">Message of the day:</span>
						<span id="wotd-display" style="font-weight: bold; font-size: 1.1em;">{{data.value}}</span>
						<input id="wotd-input" v-model="data.value" type="text" style="display: none;">
						<button id="wotd-save" style="display: none;">save</button>
						<button id="wotd-cancel" style="display: none; margin-left: 5px;">cancel</button>
						<span id="wotd-edit" class="editable editable-click" style="cursor: pointer; display: none;"></span>
					</h4>
				</div>
			</div>
		</div>`
});

