<template>
	<form
		class="search"
		@submit.prevent="() => search()"
	>
		<input
			v-model="query"
			:placeholder="placeholder || 'Search'"
			class="query"
			@input="() => search(true)"
		>

		<button
			type="submit"
			class="search-button"
		><Icon icon="search" /></button>
	</form>
</template>

<script>
function search(typing) {
	if (!typing || this.eager) {
		this.$router.replace({
			query: { query: this.query || undefined },
			params: { ...this.$route.params, pageNumber: 1 },
		});
	}
}

function resetQuery() {
	this.query = this.$route.query.query || null;
}

export default {
	props: {
		placeholder: {
			type: String,
			default: null,
		},
		eager: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			query: this.$route.query.query || null,
		};
	},
	watch: {
		$route: resetQuery,
	},
	methods: {
		search,
	},
};
</script>

<style lang="scss" scoped>
.search {
    display: flex;
    width: 100%;
}

.query {
    max-width: 40rem;
	min-width: 10rem;
    color: var(--text);
    background: var(--background);
    flex-grow: 1;
    box-sizing: border-box;
    padding: 1rem;
    border: none;
    box-sizing: border-box;
    box-shadow: 0 0 3px var(--darken-weak);
    font-size: 1rem;
    outline: none;

    &:focus {
        box-shadow: 0 0 3px var(--primary);
    }
}

.search-button {
    padding: 1rem;
    background: none;
    border: none;

    .icon {
        fill: var(--shadow);
    }

    &:hover {
        cursor: pointer;

        .icon {
            fill: var(--primary);
        }
    }
}
</style>
