<template>
	<form
		class="search"
		@submit.prevent="search"
	>
		<input
			ref="search"
			v-model="query"
			type="search"
			class="search-input"
			placeholder="Search..."
		>
		<button
			type="submit"
			class="search-button"
		><Icon
			icon="search"
		/></button>
	</form>
</template>

<script>
async function search() {
	this.$router.push({ name: 'search', query: { q: this.query } });
	this.$emit('search');
}

function searching(to) {
	if (to) {
		this.$refs.search.focus();
	}
}

function route(to) {
	if (to.name !== 'search') {
		this.query = null;
	}
}

export default {
	props: {
		searching: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			query: this.$route.query ? this.$route.query.q : null,
		};
	},
	watch: {
		$route: route,
		searching,
	},
	methods: {
		search,
	},
};
</script>

<style lang="scss" scoped>
@import 'theme';

.search {
    height: 100%;
    max-width: 20rem;
    display: flex;
    flex-grow: 1;
    align-items: center;
    justify-content: flex-end;
    padding: 0 1rem 0 0;
    border-left: solid 1px var(--shadow-hint);

    &.compact {
        padding: 0;
        border: none;

		.search-input {
			padding: .75rem .5rem .75rem .75rem;
		}

        .search-button {
            padding: 1rem 1rem .75rem .25rem;
            margin: 0;
        }
    }
}

.search-input {
    height: 100%;
    width: 100%;
    padding: .5rem 0 .5rem .5rem;
    border: none;
    color: var(--text);
    background: var(--background);
    outline: none;
    font-size: 1rem;
    outline: none;

    &::placeholder {
        color: var(--shadow);
    }

    &::-webkit-search-cancel-button {
        -webkit-appearance: none;
        padding: .5rem;
        position: relative;
        right: 0;
        color: var(--text);
        background: url('/img/cancel-circle2.svg');
        opacity: .25;

        &:hover {
            opacity: .5;
            cursor: pointer;
        }
    }

    &:focus::placeholder {
        color: var(--shadow-weak);
    }
}

.search-button {
    height: 100%;
    padding: 0 1rem;
    background: none;
    border: none;
    margin: .3rem 0 0 0;
    outline: none;

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

    &:hover {
        cursor: pointer;

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