<%- include('partials/header', { title, user }) %>
<%
const firstName = user.full_name.split(' ')[0];
const leaveEarned = Number(leave.earned || 0);
const leaveUsedPct = leaveEarned ? Math.min(100, Math.round((Number(leave.used_days || 0) / leaveEarned) * 100)) : 0;
%>
<section class="staff-hero">
	<div class="staff-hero-top">
		<div>
			<p class="staff-hero-kicker">Staff portal · <%= department %></p>
			<h1><%= typeof greeting !== 'undefined' ? greeting : 'Welcome back' %>, <%= firstName %></h1>
			<p class="staff-hero-sub"><%= typeof todayLabel !== 'undefined' ? todayLabel : '' %></p>
		</div>
	</div>
	<div class="staff-hero-stats">
		<a class="staff-hero-stat" href="/requests/new?type=leave">
			<small>Annual leave available</small>
			<strong><%= remainingLeave %> <span>days</span></strong>
			<span class="staff-hero-meter" aria-hidden="true"><span style="width: <%= leaveUsedPct %>%"></span></span>
			<em><%= leave.used_days %> of <%= leaveEarned %> earned days taken<%= leave.pending_days ? ` · ${leave.pending_days} pending` : '' %></em>
		</a>
		<div class="staff-hero-stat">
			<small>Petty cash balance</small>
			<strong>KES <%= money(pettyCashBalance) %></strong>
			<em>Available in the company treasury</em>
		</div>
		<a class="staff-hero-stat" href="/requests">
			<small>Requests in progress</small>
			<strong><%= typeof openRequests !== 'undefined' ? openRequests : pendingRequisitions %> <span>open</span></strong>
			<em>Petty cash, hardware and leave awaiting a decision</em>
		</a>
	</div>
</section>
<%- include('partials/cover-requests') %>
<% if (pettyCashAcknowledgement) { const receiptReference = `PC-${new Date(pettyCashAcknowledgement.submittedAt).getFullYear()}-${String(pettyCashAcknowledgement.id).padStart(6, '0')}`; %>
<div class="approval-receipt-modal" id="petty-cash-acknowledgement" role="presentation">
	<div class="approval-receipt-backdrop" data-petty-cash-ack-close></div>
	<section class="approval-receipt-dialog" role="dialog" aria-modal="true" aria-labelledby="petty-cash-acknowledgement-title">
		<header><h2 id="petty-cash-acknowledgement-title"><span aria-hidden="true">&#10003;</span> Petty cash request received</h2><button class="approval-receipt-close" type="button" data-petty-cash-ack-close aria-label="Close acknowledgement">&times;</button></header>
		<div class="approval-receipt-content">
			<div class="approval-receipt-success petty-cash-acknowledgement-success" role="status" aria-live="polite"><span aria-hidden="true">&#10003;</span><div><strong>Your request has been submitted</strong><p>It is now waiting for <%= pettyCashAcknowledgement.approver %> to review.</p></div></div>
			<section class="approval-receipt-summary"><h3>Submission acknowledgement</h3><dl>
				<div><dt>Request reference</dt><dd><%= receiptReference %></dd></div>
				<div><dt>Requested amount</dt><dd>KES <%= money(pettyCashAcknowledgement.amount) %></dd></div>
				<div><dt>Category</dt><dd><%= pettyCashAcknowledgement.category %></dd></div>
				<% if (pettyCashAcknowledgement.category === 'Fare') { %>
				<div><dt>From</dt><dd><%= pettyCashAcknowledgement.fareFrom || '—' %></dd></div>
				<div><dt>To</dt><dd><%= pettyCashAcknowledgement.fareTo || '—' %></dd></div>
				<% } else { %>
				<% if (pettyCashAcknowledgement.targetLocation) { %><div><dt>Target location</dt><dd><%= pettyCashAcknowledgement.targetLocation %></dd></div><% } %>
				<% if (pettyCashAcknowledgement.items?.length) { %><div><dt>Expense items</dt><dd><%= pettyCashAcknowledgement.items.map((item) => `${item.description} (KES ${money(item.amount)})`).join('; ') %></dd></div><% } %>
				<% } %>
			</dl></section>
		</div>
		<footer><button class="button success" type="button" data-petty-cash-ack-close>Done</button></footer>
	</section>
</div>
<script>
(() => {
	const modal = document.getElementById('petty-cash-acknowledgement');
	if (!modal) return;
	const close = () => { modal.remove(); document.body.classList.remove('modal-open'); };
	modal.querySelectorAll('[data-petty-cash-ack-close]').forEach((button) => button.addEventListener('click', close));
	document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && modal.isConnected) close(); });
	modal.querySelector('[data-petty-cash-ack-close]').focus();
	document.body.classList.add('modal-open');
})();
</script>
<% } %>
<% const canRequestHardware = user.position_level !== 'front_office'; %>
<section class="staff-actions-grid<%= canRequestHardware ? '' : ' two' %>" aria-label="Quick actions">
	<button class="staff-action-card petty" type="button" data-petty-cash-open>
		<span class="staff-action-text"><em>Finance</em><strong>Request petty cash</strong><small>Fare, field logistics or office sundries — paid to your M-Pesa</small></span>
		<span class="staff-action-arrow" aria-hidden="true">&rarr;</span>
	</button>
	<% if (canRequestHardware) { %>
	<button class="staff-action-card hardware" type="button" data-hardware-open>
		<span class="staff-action-text"><em>Stock</em><strong>Request hardware</strong><small>Pick devices and SIMs from the stock catalogue</small></span>
		<span class="staff-action-arrow" aria-hidden="true">&rarr;</span>
	</button>
	<% } %>
	<a class="staff-action-card leave" href="/requests/new?type=leave">
		<span class="staff-action-text"><em>Time off</em><strong>Apply for leave</strong><small><%= remainingLeave %> days of annual leave available</small></span>
		<span class="staff-action-arrow" aria-hidden="true">&rarr;</span>
	</a>
</section>
<%- include('partials/dispatch-queue') %>
<% if (pettyCashDrafts.length || hardwareDrafts.length) { %>
<section class="staff-panel staff-drafts-panel">
	<div class="staff-panel-head"><div><h2>Saved drafts</h2><p>Pick up where you left off</p></div><span class="staff-panel-count"><%= pettyCashDrafts.length + hardwareDrafts.length %> saved</span></div>
	<ul class="staff-draft-cards">
		<% pettyCashDrafts.forEach((draft) => { %>
		<li><span class="staff-request-icon petty" aria-hidden="true">PC</span><div><strong><%= draft.details?.category || 'Petty cash request' %></strong><small><%= draft.details?.category === 'Office sundries' ? 'Office' : draft.details?.category === 'Fare' ? (draft.details?.fare_from && draft.details?.fare_to ? `${draft.details.fare_from} to ${draft.details.fare_to}` : 'Route not set') : draft.details?.target_location || 'Site not set' %> · KES <%= money(draft.details?.amount_requested || 0) %></small></div><button class="button outline small" type="button" data-petty-cash-edit="<%= JSON.stringify({ id: draft.id, details: draft.details }) %>">Continue</button></li>
		<% }) %>
		<% hardwareDrafts.forEach((draft) => { const items = draft.details?.items || []; const itemNames = items.map((item) => item.stock_type).filter(Boolean).join(', '); %>
		<li><span class="staff-request-icon hardware" aria-hidden="true">RQ</span><div><strong><%= itemNames || 'Hardware request draft' %></strong><small><%= requestWhere(draft.details) || 'Client and site not set' %> · <%= items.length %> item<%= items.length === 1 ? '' : 's' %></small></div><button class="button outline small" type="button" data-hardware-edit="<%= JSON.stringify({ id: draft.id, details: draft.details }) %>">Continue</button></li>
		<% }) %>
	</ul>
</section>
<% } %>
<% if (canRequestHardware) { %>
<div class="hardware-request-modal" id="hardware-request-modal" hidden aria-hidden="true">
	<div class="hardware-request-backdrop" data-hardware-close></div>
	<section class="hardware-request-dialog" role="dialog" aria-modal="true" aria-labelledby="hardware-request-title">
		<header><div><h2 id="hardware-request-title">Request hardware</h2><p>Status: <span data-hardware-status>New draft</span> · <%= requestDate %></p></div><button class="hardware-request-close" type="button" data-hardware-close aria-label="Close">&times;</button></header>
		<form method="post" action="/requests" class="hardware-request-form" data-hardware-form>
			<%- include('partials/hardware-request-fields', { currentUser, requestDate, stockProducts, hardwareDraft: null }) %>
			<footer><button class="button outline" type="submit" name="action" value="discard" formnovalidate>Discard request</button><button class="button primary" type="submit" name="action" value="submit">Submit Request</button></footer>
		</form>
	</section>
</div>
<script>
(() => {
	const modal = document.getElementById('hardware-request-modal');
	const formApi = window.HardwareRequestForm;
	if (!modal || !formApi) return;
	const openButton = document.querySelector('[data-hardware-open]');
	const close = () => { modal.hidden = true; modal.setAttribute('aria-hidden', 'true'); document.body.classList.remove('modal-open'); };
	const open = () => { modal.hidden = false; modal.setAttribute('aria-hidden', 'false'); document.body.classList.add('modal-open'); modal.querySelector('[data-stock-type]').focus(); };
	openButton?.addEventListener('click', () => { formApi.reset(); modal.querySelector('[data-hardware-status]').textContent = 'New draft'; open(); });
	modal.querySelectorAll('[data-hardware-close]').forEach((button) => button.addEventListener('click', close));
	document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && !modal.hidden) close(); });
	document.querySelectorAll('[data-hardware-edit]').forEach((button) => button.addEventListener('click', () => {
		formApi.loadDraft(JSON.parse(button.dataset.hardwareEdit));
		modal.querySelector('[data-hardware-status]').textContent = 'Draft';
		open();
	}));
})();
</script>
<% } %>
<div class="petty-cash-modal" id="petty-cash-modal" hidden aria-hidden="true">
	<div class="petty-cash-backdrop" data-petty-cash-close></div>
	<section class="petty-cash-dialog" role="dialog" aria-modal="true" aria-labelledby="petty-cash-title">
		<header><h2 id="petty-cash-title">Request petty cash</h2><button class="petty-cash-close" type="button" data-petty-cash-close aria-label="Close">&times;</button></header>
		<form method="post" action="/requests" class="petty-cash-form" data-petty-cash-form>
			<%- include('partials/petty-cash-fields', { currentUser, requestDate, pettyCashDraft: null }) %>
			<footer><button class="button primary" type="submit" name="action" value="submit">Submit petty cash request</button></footer>
		</form>
	</section>
</div>
<script>
(() => {
	const modal = document.getElementById('petty-cash-modal');
	const formApi = window.PettyCashForm;
	if (!modal || !formApi) return;
	const openButton = document.querySelector('[data-petty-cash-open]');
	const close = () => { modal.hidden = true; modal.setAttribute('aria-hidden', 'true'); document.body.classList.remove('modal-open'); };
	const open = () => { modal.hidden = false; modal.setAttribute('aria-hidden', 'false'); document.body.classList.add('modal-open'); modal.querySelector('[name="category"]').focus(); };
	openButton?.addEventListener('click', () => { formApi.reset(); open(); });
	modal.querySelectorAll('[data-petty-cash-close]').forEach((button) => button.addEventListener('click', close));
	document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && !modal.hidden) close(); });
	document.querySelectorAll('[data-petty-cash-edit]').forEach((button) => button.addEventListener('click', () => {
		formApi.loadDraft(JSON.parse(button.dataset.pettyCashEdit));
		open();
	}));
})();
</script>
<section class="staff-panel staff-recents">
	<div class="staff-panel-head"><div><h2>Recent requests</h2><p>Your latest petty cash, hardware and leave requests</p></div><a class="staff-panel-link" href="/requests">View all &rarr;</a></div>
	<% if (!staffRequests.length) { %>
		<div class="staff-empty"><p>You haven’t submitted any requests yet. Use the quick actions above to get started.</p></div>
	<% } else { %>
	<ul class="staff-request-list">
		<% staffRequests.forEach((request) => {
			const details = request.details || {};
			const kind = request.request_type === 'petty_cash' ? 'petty' : request.request_type === 'leave' ? 'leave' : 'hardware';
			const prefix = kind === 'petty' ? 'PC' : kind === 'leave' ? 'LV' : 'RQ';
			const icon = kind === 'petty' ? 'PC' : kind === 'leave' ? 'LV' : 'RQ';
			const title = kind === 'leave' ? `${(details.leave_type || 'Leave').replace(/^./, (c) => c.toUpperCase())} leave` : kind === 'hardware' ? (details.item_requested || 'Hardware request') : (details.category || 'Petty cash');
			const value = kind === 'leave' ? `${details.days_requested || 0} days` : kind === 'hardware' ? `${details.quantity || 0} unit${Number(details.quantity) === 1 ? '' : 's'}` : `KES ${money(details.amount_requested || 0)}`;
			const subtitle = kind === 'leave'
				? `${details.start_date ? fmtDay(details.start_date) : '—'} → ${details.end_date ? fmtDay(details.end_date) : '—'}`
				: kind === 'hardware'
					? ((details.serial_numbers?.length || (details.items || []).some((line) => Number(line.issued_quantity || 0))) ? `Issued: ${(details.items || []).flatMap((line) => issuedLineLabels(line)).join('; ') || details.serial_numbers.join(', ')}` : details.client_name ? `For ${details.client_name}` : 'Hardware requisition')
					: (details.description_of_need || details.target_location || 'Petty cash request');
			const reminder = (typeof reminderStates !== 'undefined' && reminderStates[request.id]) || null;
			const statusText = reminder ? (reminder.processing ? 'Payout processing' : 'Awaiting payout')
				: request.status === 'approved' ? (kind === 'hardware' ? 'Stock issued' : kind === 'petty' ? 'Paid' : 'Approved')
				: request.status === 'rejected' ? 'Rejected'
				: request.status === 'computed' ? requestStatusLabel(request) : 'In review';
			const statusClass = reminder || request.status === 'computed' ? 'awaiting' : request.status === 'approved' ? 'approved' : request.status === 'rejected' ? 'rejected' : 'pending';
		%>
		<li class="staff-request-item">
			<span class="staff-request-icon <%= kind %>" aria-hidden="true"><%- icon %></span>
			<div class="staff-request-main">
				<a class="staff-request-title" href="/requests/<%= request.id %>"><%= title %></a>
				<small><span class="staff-request-ref">#<%= prefix %>-<%= String(request.id).padStart(3, '0') %></span> · <%= subtitle %></small>
			</div>
			<strong class="staff-request-value"><%= value %></strong>
			<div class="staff-request-status">
				<span class="staff-pill <%= statusClass %>"><%= statusText %></span>
				<% if (reminder && reminder.canSend) { %>
				<form method="post" action="/requests/<%= request.id %>/remind-payout" class="staff-remind-form"><input type="hidden" name="return_to" value="/dashboard"><button class="staff-remind-button" type="submit">Remind Admin & Logistics</button></form>
				<% } else if (reminder && reminder.nextAt) { %>
				<small>Reminder sent · next after <%= reminder.nextAt %></small>
				<% } %>
			</div>
			<time class="staff-request-date" datetime="<%= new Date(request.submitted_at).toISOString() %>"><%= fmtDay(request.submitted_at) %></time>
		</li>
		<% }) %>
	</ul>
	<% } %>
</section>
<%- include('partials/footer') %>