<%
const form = typeof leaveForm === 'undefined' || !leaveForm ? {} : leaveForm;
const leaveTypeInfo = {
	annual: { note: 'Deducted from your annual balance' },
	sick: { note: 'Up to 14 working days a year · doctor\'s note required' },
	maternity: { note: 'Up to 90 calendar days a year' },
	paternity: { note: 'Up to 14 calendar days a year' },
	compassionate: { note: 'Up to 5 working days a year · bereavement or family emergencies' },
	unpaid: { note: 'Not deducted · taken without pay' }
};
const requestable = Math.max(0, leave?.requestable || 0);
const typeAllowances = typeof allowances === 'undefined' || !allowances ? {} : allowances;
%>
<form method="post" action="/requests" enctype="multipart/form-data" class="leave-layout" data-leave-form data-requestable="<%= requestable %>" data-today="<%= requestDate %>" data-planned="<%= (plannedLeaveTypes || []).join(',') %>" data-reason-types="<%= (reasonLeaveTypes || []).join(',') %>" data-allowances="<%= JSON.stringify(typeAllowances) %>" data-cover-commitments="<%= JSON.stringify(typeof coverCommitments === 'undefined' ? [] : coverCommitments) %>">
	<input type="hidden" name="request_type" value="leave">
	<input type="hidden" name="department" value="<%= currentUser.department || '' %>">
	<div class="leave-main">
		<section class="leave-card">
			<header><span class="leave-step-number">1</span><div><h2>Type of leave</h2><p>Only annual leave reduces your annual balance; other types have their own yearly allowance.</p></div></header>
			<div class="leave-type-grid" role="radiogroup" aria-label="Type of leave">
				<% leaveTypes.forEach((leaveType) => { const info = leaveTypeInfo[leaveType] || { note: '' }; %>
				<label class="leave-type-option leave-type-<%= leaveType %>">
					<input type="radio" name="leave_type" value="<%= leaveType %>" required <%= form.leave_type === leaveType ? 'checked' : '' %>>
					<span class="leave-type-body"><span class="leave-type-check" aria-hidden="true"></span><strong><%= leaveType.charAt(0).toUpperCase() + leaveType.slice(1) %></strong><small><%= info.note %></small></span>
				</label>
				<% }) %>
			</div>
		</section>

		<section class="leave-card">
			<header><span class="leave-step-number">2</span><div><h2>When</h2><p>Saturdays count as half days; Sundays are not counted.</p></div></header>
			<div class="grid two">
				<label>First day of leave<input type="date" name="start_date" value="<%= form.start_date || '' %>" required data-leave-start></label>
				<label>Last day of leave<input type="date" name="end_date" value="<%= form.end_date || '' %>" required data-leave-end></label>
			</div>
			<p class="leave-days-chip" data-leave-days hidden></p>
		</section>

		<section class="leave-card">
			<header><span class="leave-step-number">3</span><div><h2>Handover</h2><p>Who will cover your work while you're away.</p></div></header>
			<% const pickable = colleagues || []; const chosenCover = Number(form.standing_in_id) || null; const ownTeam = pickable.filter((person) => person.sameDepartment); const others = pickable.filter((person) => !person.sameDepartment); %>
			<label>Colleague covering your duties
				<select name="standing_in_id">
					<option value="">Not arranged yet</option>
					<% [[ownTeam, 'Your department'], [others, ownTeam.length ? 'Other departments' : 'Colleagues']].forEach(([group, label]) => { if (!group.length) return; %>
					<optgroup label="<%= label %>"><% group.forEach((person) => { %><option value="<%= person.id %>" <%= chosenCover === person.id ? 'selected' : '' %>><%= person.name %> · <%= person.position %><%= person.sameDepartment || !person.department ? '' : ` · ${person.department}` %></option><% }) %></optgroup>
					<% }) %>
				</select>
			</label>
			<p class="hint leave-cover-hint">They'll get an email and a request on their dashboard to accept or decline covering for you.</p>
		</section>

		<% const showReason = (reasonLeaveTypes || []).includes(form.leave_type); %>
		<section class="leave-card" data-leave-reason-section <%= showReason ? '' : 'hidden' %>>
			<header><span class="leave-step-number">4</span><div><h2>Reason</h2><p>A short note for your approvers.</p></div></header>
			<label><span class="visually-hidden">Reason for leave</span><textarea name="reason_for_request" rows="4" maxlength="500" placeholder="A short explanation for your approvers" data-leave-reason <%= showReason ? 'required' : 'disabled' %>><%= form.reason_for_request || '' %></textarea></label>
			<p class="leave-char-count" data-leave-count>0 / 500</p>
		</section>

		<% const isSick = form.leave_type === 'sick'; %>
		<section class="leave-card" data-leave-note-section <%= isSick ? '' : 'hidden' %>>
			<header><span class="leave-step-number">4</span><div><h2>Doctor's note</h2><p>Sick leave needs a note from your doctor or clinic. A PDF or a clear photo, up to 5 MB.</p></div></header>
			<label class="leave-note-drop">
				
				<span class="leave-note-text"><strong data-leave-note-name>Choose a file</strong><small>PDF, JPG or PNG</small></span>
				<input type="file" name="doctor_note" accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png" data-leave-note <%= isSick ? 'required' : 'disabled' %>>
			</label>
			<% if (isSick && typeof error !== 'undefined' && error) { %><p class="hint leave-note-reattach">Files aren't kept when the form shows an error — please attach the note again.</p><% } %>
		</section>
	</div>

	<aside class="leave-aside">
		<section class="leave-balance-card">
			<span class="leave-balance-label">Annual leave available</span>
			<strong class="leave-balance-figure"><%= requestable %> <small>days</small></strong>
			<dl>
				<div><dt>Earned this year</dt><dd><%= leave.earned %> of <%= leave.annual_entitlement %></dd></div>
				<div><dt>Carried forward</dt><dd><%= leave.carried_forward %><%= leave.carried_expires ? ' (expired)' : '' %></dd></div>
				<div><dt>Taken</dt><dd><%= leave.used_days %></dd></div>
				<div><dt>Awaiting approval</dt><dd><%= leave.pending_days %></dd></div>
			</dl>
		</section>

		<% Object.entries(typeAllowances).forEach(([leaveType, allowance]) => { %>
		<section class="leave-balance-card leave-allowance-card" data-leave-allowance="<%= leaveType %>" <%= form.leave_type === leaveType ? '' : 'hidden' %>>
			<span class="leave-balance-label"><%= leaveType.charAt(0).toUpperCase() + leaveType.slice(1) %> leave left this year</span>
			<strong class="leave-balance-figure"><%= allowance.remaining %> <small><%= allowance.unit %> days</small></strong>
			<dl>
				<div><dt>Yearly allowance</dt><dd><%= allowance.limit %> <%= allowance.unit %> days</dd></div>
				<div><dt>Taken or awaiting approval</dt><dd><%= allowance.used %></dd></div>
			</dl>
		</section>
		<% }) %>

		<section class="leave-preview-card" data-leave-preview hidden>
			<h3>This application</h3>
			<dl>
				<div><dt data-preview-days-label>Working days</dt><dd data-preview-days>—</dd></div>
				<div><dt>Back at work</dt><dd data-preview-return>—</dd></div>
				<div data-preview-balance-row><dt data-preview-balance-label>Annual balance after</dt><dd data-preview-balance>—</dd></div>
			</dl>
			<p class="leave-warning" data-leave-warning hidden></p>
			<p class="leave-cover-clash" data-leave-cover-clash hidden></p>
		</section>

		<section class="leave-route-card">
			<h3>Approval route</h3>
			<% if (!leaveRoute || !leaveRoute.length) { %><p class="muted small">No approvers are configured for your position.</p><% } else { %>
			<ol>
				<% leaveRoute.forEach((step) => { %><li><strong><%= step.label %></strong><span><%= step.person %></span></li><% }) %>
			</ol>
			<% } %>
		</section>

		<div class="leave-actions">
			<button class="button primary block" type="submit" data-leave-submit>Submit for approval</button>
			<a class="button outline block" href="/dashboard">Cancel</a>
		</div>
	</aside>
</form>
<script>
(() => {
	const form = document.querySelector('[data-leave-form]');
	if (!form) return;
	const start = form.querySelector('[data-leave-start]');
	const end = form.querySelector('[data-leave-end]');
	const chip = form.querySelector('[data-leave-days]');
	const preview = form.querySelector('[data-leave-preview]');
	const warning = form.querySelector('[data-leave-warning]');
	const submit = form.querySelector('[data-leave-submit]');
	const reason = form.querySelector('[data-leave-reason]');
	const count = form.querySelector('[data-leave-count]');
	const requestable = Number(form.dataset.requestable || 0);
	const today = form.dataset.today;
	const planned = (form.dataset.planned || '').split(',');
	const reasonTypes = (form.dataset.reasonTypes || '').split(',');
	const reasonSection = form.querySelector('[data-leave-reason-section]');
	const noteSection = form.querySelector('[data-leave-note-section]');
	const note = form.querySelector('[data-leave-note]');
	const noteName = form.querySelector('[data-leave-note-name]');
	note.addEventListener('change', () => {
		const chosen = note.files?.[0];
		const tooBig = chosen && chosen.size > 5 * 1024 * 1024;
		note.setCustomValidity(tooBig ? 'The file is larger than 5 MB.' : '');
		noteName.textContent = chosen ? (tooBig ? `${chosen.name} — too large (max 5 MB)` : chosen.name) : 'Choose a file';
	});
	let allowances = {};
	try { allowances = JSON.parse(form.dataset.allowances || '{}'); } catch {}
	const allowanceCards = [...form.querySelectorAll('[data-leave-allowance]')];
	// Leave the applicant has agreed (or been asked) to cover; overlapping it is allowed but flagged.
	let commitments = [];
	try { commitments = JSON.parse(form.dataset.coverCommitments || '[]'); } catch {}
	const clashNotice = form.querySelector('[data-leave-cover-clash]');
	// Maternity and paternity allowances are in calendar days, matching the server's check.
	const calendarDays = (from, to) => Math.round((to - from) / 86400000) + 1;
	const dayName = new Intl.DateTimeFormat('en-GB', { weekday: 'short', day: '2-digit', month: 'short', timeZone: 'UTC' });
	const parse = (value) => (value ? new Date(`${value}T00:00:00Z`) : null);
	// Mirrors the server's rule: Saturdays are half days, Sundays are not counted.
	const workingDays = (from, to) => {
		let total = 0;
		for (const day = new Date(from); day <= to; day.setUTCDate(day.getUTCDate() + 1)) {
			const weekday = day.getUTCDay();
			total += weekday === 6 ? 0.5 : weekday === 0 ? 0 : 1;
		}
		return Math.round(total * 100) / 100;
	};
	const nextWorkingDay = (date) => {
		const day = new Date(date);
		do { day.setUTCDate(day.getUTCDate() + 1); } while (day.getUTCDay() === 0);
		return day;
	};
	const update = () => {
		const type = form.querySelector('input[name="leave_type"]:checked')?.value || '';
		// The reason is asked for (and required) only for unpaid and compassionate leave; a disabled field isn't sent.
		const needsReason = reasonTypes.includes(type);
		reasonSection.hidden = !needsReason;
		reason.required = needsReason;
		// Sick leave asks for the doctor's note; a disabled file input isn't sent.
		const isSick = type === 'sick';
		noteSection.hidden = !isSick;
		note.required = isSick;
		note.disabled = !isSick;
		reason.disabled = !needsReason;
		// Planned leave starts today or later; sick and compassionate leave can be recorded afterwards.
		start.min = planned.includes(type) ? today : '';
		end.min = start.value || start.min;
		const from = parse(start.value);
		const to = parse(end.value);
		const valid = from && to && to >= from;
		const days = valid ? workingDays(from, to) : 0;
		chip.hidden = !valid;
		preview.hidden = !valid;
		let problem = '';
		if (from && to && to < from) problem = 'The last day is before the first day.';
		else if (valid && days === 0) problem = 'These dates don\'t include any working days.';
		else if (valid && planned.includes(type) && start.value < today) problem = 'Planned leave can\'t start in the past.';
		else if (valid && type === 'annual' && days > requestable) problem = `That's ${days} days, but you can request up to ${requestable}.`;
		const allowance = allowances[type];
		const allowanceUsed = valid && allowance ? (allowance.unit === 'calendar' ? calendarDays(from, to) : days) : 0;
		if (!problem && allowance && allowanceUsed > allowance.remaining) {
			problem = `That's ${allowanceUsed} ${allowance.unit} days, but you have ${allowance.remaining} ${allowance.unit} days of ${type} leave left this year.`;
		}
		allowanceCards.forEach((card) => { card.hidden = card.dataset.leaveAllowance !== type; });
		const clashes = valid ? commitments.filter((item) => item.start <= end.value && item.end >= start.value) : [];
		clashNotice.hidden = !clashes.length;
		clashNotice.textContent = clashes.length
			? `You're covering for ${clashes.map((item) => `${item.applicant} (${item.start === item.end ? item.start : `${item.start} to ${item.end}`})`).join(', ')} during these dates. You can still apply — your approver will see this, and if your leave is approved they'll be asked to choose someone else.`
			: '';
		if (valid) {
			// Maternity and paternity are counted in calendar days; everything else in working days.
			const countUnit = allowance?.unit === 'calendar' ? 'calendar' : 'working';
			const counted = countUnit === 'calendar' ? allowanceUsed : days;
			chip.textContent = `${counted} ${countUnit} ${counted === 1 ? 'day' : 'days'} · ${dayName.format(from)} – ${dayName.format(to)}`;
			form.querySelector('[data-preview-days-label]').textContent = countUnit === 'calendar' ? 'Calendar days' : 'Working days';
			form.querySelector('[data-preview-days]').textContent = String(counted);
			form.querySelector('[data-preview-return]').textContent = dayName.format(nextWorkingDay(to));
			const balanceRow = form.querySelector('[data-preview-balance-row]');
			balanceRow.hidden = type !== 'annual' && !allowance;
			form.querySelector('[data-preview-balance-label]').textContent = allowance ? `${type.charAt(0).toUpperCase() + type.slice(1)} leave left after` : 'Annual balance after';
			form.querySelector('[data-preview-balance]').textContent = allowance
				? `${Math.max(0, Math.round((allowance.remaining - allowanceUsed) * 100) / 100)} ${allowance.unit} days`
				: `${Math.round((requestable - days) * 100) / 100} days`;
		}
		warning.hidden = !problem;
		warning.textContent = problem;
		chip.classList.toggle('is-problem', Boolean(problem));
		submit.disabled = Boolean(problem);
	};
	const updateCount = () => { count.textContent = `${reason.value.length} / 500`; };
	form.addEventListener('change', update);
	start.addEventListener('input', update);
	end.addEventListener('input', update);
	reason.addEventListener('input', updateCount);
	update();
	updateCount();
})();
</script>
