<script lang="ts">
	import { getContext } from 'svelte';
	import FaRegTrashAlt from 'svelte-icons/fa/FaRegTrashAlt.svelte';

	import FaUndo from 'svelte-icons/fa/FaUndo.svelte';
	import FaTimes from 'svelte-icons/fa/FaTimes.svelte';
	import { goto } from '$app/navigation';
	import type { Writable } from 'svelte/store';
	import type { Room, Member } from '../../types/room.type';
	import type ReconnectingWebSocket from 'reconnecting-websocket';
	const room: Writable<Room> = getContext('room');
	const member: Writable<Member>= getContext('member');
	const { send, ws } = getContext<{send: Function, ws: ReconnectingWebSocket}>('ws');
	let editing = false;
	let name = $room.name;
	let r: HTMLInputElement;
</script>

<div class="head">
	<div class="title">
		{#if !editing}
			<h1
				on:dblclick={() => {
                    if(!$member.isAdmin) return
					editing = true;
					name = $room.name;
					r.focus();
					console.log("OPENED")
				}}
			>
				{$room.name}<span on:dblclick|stopPropagation>#{$room.id_code}</span>
			</h1>
		{/if}

		<input
			type="text"
			class="input"
			class:hide={!editing}
			on:focusout={() => {
				editing = false;
			}}
			bind:value={name}
			bind:this={r}
			on:keydown={(e) => {
				if (e.key == 'Escape') {
					editing = false;
				} else if (e.key == 'Enter') {
					send('set_name', { name });
					editing = false;
				}
			}}
		/>
	</div>

	<div class="icons">
        {#if $member.isAdmin}
            <div class="icon trash" data-testid="delete"><FaRegTrashAlt /></div>
        {/if}
		
		<div
			class="icon refresh"
			on:click={() => {
                console.log(ws)
				ws.reconnect();
			}}
			on:keydown={() => {}}
			data-testid="refresh"
		>
			<FaUndo />
		</div>
		<div
			data-testid="leave"
			class="icon trash"
			on:click={() => {
				ws.close();
                goto('/room/join')
			}}
			on:keydown={() => {}}
		>
			<FaTimes />
		</div>
	</div>
</div>

<style lang="scss">
	.hide {
		width: 0;
		height: 0;
		padding: 0;
		border: none;
		opacity: 0;
	}
	.title {
		max-width: 50%;
		margin: 10px 0;
		font-size: 2em;
		// height: 50px;
		input {
			font-size: inherit;
			font-weight: 700;
			transition: all 0s;
			transition: border 0.3s;
			padding-left: 0;
			padding-top: 0;
		}
		h1 {
			margin: 0;
			font-weight: 700;
			font-size: inherit;
			span {
				font-size: 0.5em;
				color: grey;
			}
		}
	}
	.head {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.icon {
		width: 20px;
		height: 20px;
		transition: 0.2s;
		cursor: pointer;
		display: flex;
		&:hover {
			transform: scale(1.1);
		}
	}

	.trash {
		color: $red;
	}

	.refresh {
		color: $contrast;
		&:hover {
			transform: rotate(-360deg);
		}
	}

	.icons {
		display: flex;
		gap: 20px;
		align-items: center;
	}
</style>
