<script lang="ts">
	import PlacesAutocomplete from './PlacesAutocomplete.svelte';
	import ImageUpload from './ImageUpload.svelte';

	type ItemType = 'transportation' | 'lodging' | 'location' | 'note';

	let {
		open = $bindable(false),
		tripId,
		itemType = 'location',
		editItem = null,
		onSaved
	}: {
		open: boolean;
		tripId: string;
		itemType: ItemType;
		editItem?: any;
		onSaved: () => void;
	} = $props();

	let saving = $state(false);
	let confirmDelete = $state(false);
	let mediaImages = $state<any[]>([]);
	let mediaDocuments = $state<any[]>([]);

	// ── Form state ──
	let name = $state('');
	let description = $state('');
	let category = $state('');
	let date = $state('');
	let endDate = $state('');
	let startTime = $state('');
	let endTime = $state('');
	let flightNumber = $state('');
	let fromLocation = $state('');
	let toLocation = $state('');
	let reservationNumber = $state('');
	let link = $state('');
	let costPoints = $state(0);
	let costCash = $state(0);
	let address = $state('');
	let placeId = $state('');
	let latitude = $state<number | null>(null);
	let longitude = $state<number | null>(null);
	let hikeDistance = $state('');
	let hikeDifficulty = $state('');
	let hikeTime = $state('');
	let transportType = $state('plane');
	let lodgingType = $state('hotel');
	let content = $state('');

	let isEdit = $derived(!!editItem?.id);

	const locationCategories = ['restaurant', 'cafe', 'bar', 'attraction', 'hike', 'shopping', 'beach', 'museum', 'park'];
	const transportTypes = ['plane', 'train', 'car', 'bus', 'ferry'];
	const lodgingTypes = ['hotel', 'airbnb', 'hostel', 'resort', 'camping'];

	$effect(() => {
		if (open && editItem) {
			name = editItem.name || '';
			description = editItem.description || '';
			date = editItem.date || editItem.visit_date || editItem.check_in?.slice(0, 10) || '';
			endDate = editItem.end_date || editItem.check_out?.slice(0, 10) || '';
			startTime = editItem.start_time || editItem.date || '';
			endTime = editItem.end_time || editItem.end_date || '';
			category = editItem.category || '';
			flightNumber = editItem.flight_number || '';
			fromLocation = editItem.from_location || '';
			toLocation = editItem.to_location || '';
			reservationNumber = editItem.reservation_number || '';
			link = editItem.link || '';
			costPoints = editItem.cost_points || 0;
			costCash = editItem.cost_cash || 0;
			address = editItem.address || editItem.location || '';
			placeId = editItem.place_id || '';
			latitude = editItem.latitude || editItem.from_lat || null;
			longitude = editItem.longitude || editItem.from_lng || null;
			hikeDistance = editItem.hike_distance || '';
			hikeDifficulty = editItem.hike_difficulty || '';
			hikeTime = editItem.hike_time || '';
			transportType = editItem.type || 'plane';
			lodgingType = editItem.type || 'hotel';
			content = editItem.content || '';
			mediaImages = (editItem.images || []).map((i: any) => ({ ...i, url: `/images/${i.file_path}` }));
			mediaDocuments = (editItem.documents || []).map((d: any) => ({ ...d, url: `/api/trips/documents/${d.file_path}` }));
		} else if (open) {
			resetForm();
			mediaImages = [];
			mediaDocuments = [];
		}
		confirmDelete = false;
	});

	function resetForm() {
		name = ''; description = ''; category = ''; date = ''; endDate = '';
		startTime = ''; endTime = ''; flightNumber = ''; fromLocation = '';
		toLocation = ''; reservationNumber = ''; link = ''; costPoints = 0;
		costCash = 0; address = ''; placeId = ''; latitude = null; longitude = null;
		hikeDistance = ''; hikeDifficulty = ''; hikeTime = '';
		transportType = 'plane'; lodgingType = 'hotel'; content = '';
	}

	function close() { open = false; resetForm(); confirmDelete = false; }

	async function refreshMedia() {
		if (!editItem?.id) {
			onSaved();
			return;
		}

		try {
			const res = await fetch(`/api/trips/trip/${tripId}`, { credentials: 'include' });
			if (!res.ok) return;
			const data = await res.json();

			const collection =
				itemType === 'transportation' ? data.transportations :
				itemType === 'lodging' ? data.lodging :
				itemType === 'location' ? data.locations :
				data.notes;

			const nextItem = (collection || []).find((item: any) => item.id === editItem.id);
			if (!nextItem) return;

			mediaImages = (nextItem.images || []).map((image: any) => ({
				...image,
				url: `/images/${image.file_path}`
			}));
			mediaDocuments = (nextItem.documents || []).map((doc: any) => ({
				...doc,
				url: `/api/trips/documents/${doc.file_path}`
			}));
			onSaved();
		} catch (e) {
			console.error('Media refresh failed:', e);
		}
	}

	function handlePlaceSelect(details: any) {
		if (details.name) name = details.name;
		address = details.address || '';
		placeId = details.place_id || '';
		latitude = details.latitude;
		longitude = details.longitude;
		if (details.category && !category) category = details.category;
		if (itemType === 'lodging') address = details.address || details.name || '';
	}

	async function save() {
		saving = true;
		try {
			let endpoint: string;
			let payload: Record<string, any> = { trip_id: tripId };

			if (itemType === 'transportation') {
				payload = { ...payload, name, description, type: transportType, flight_number: flightNumber, from_location: fromLocation, to_location: toLocation, date: startTime || date, end_date: endTime || endDate, link, cost_points: costPoints, cost_cash: costCash, from_place_id: placeId, from_lat: latitude, from_lng: longitude };
				endpoint = isEdit ? '/api/trips/transportation/update' : '/api/trips/transportation';
			} else if (itemType === 'lodging') {
				payload = { ...payload, name, description, type: lodgingType, location: address, check_in: date, check_out: endDate, reservation_number: reservationNumber, link, cost_points: costPoints, cost_cash: costCash, place_id: placeId, latitude, longitude };
				endpoint = isEdit ? '/api/trips/lodging/update' : '/api/trips/lodging';
			} else if (itemType === 'note') {
				payload = { ...payload, name, content: description || content, date };
				endpoint = isEdit ? '/api/trips/note/update' : '/api/trips/note';
			} else {
				payload = { ...payload, name, description, category, visit_date: date, start_time: startTime, end_time: endTime, link, cost_points: costPoints, cost_cash: costCash, address, place_id: placeId, latitude, longitude, hike_distance: hikeDistance, hike_difficulty: hikeDifficulty, hike_time: hikeTime };
				endpoint = isEdit ? '/api/trips/location/update' : '/api/trips/location';
			}

			if (isEdit) payload.id = editItem.id;

			await fetch(endpoint, {
				method: 'POST', credentials: 'include',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify(payload)
			});
			close();
			onSaved();
		} catch (e) { console.error('Save failed:', e); }
		finally { saving = false; }
	}

	async function doDelete() {
		if (!isEdit) return;
		saving = true;
		try {
			await fetch(`/api/trips/${itemType}/delete`, {
				method: 'POST', credentials: 'include',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ id: editItem.id })
			});
			close();
			onSaved();
		} catch (e) { console.error('Delete failed:', e); }
		finally { saving = false; }
	}

	const titles: Record<ItemType, string> = {
		transportation: 'Transportation',
		lodging: 'Accommodation',
		location: 'Activity',
		note: 'Note'
	};
</script>

{#if open}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="modal-overlay" onclick={close}>
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="modal-sheet" onclick={(e) => e.stopPropagation()}>
		<div class="modal-header">
			<div class="modal-head-copy">
				<div class="modal-kicker">{isEdit ? 'Edit' : 'Add'}</div>
				<div class="modal-title">{titles[itemType]}</div>
			</div>
			<button class="modal-close" onclick={close}>
				<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
			</button>
		</div>

		<div class="modal-body">
			<div class="modal-intro">
				<div class="intro-line">{titles[itemType]} details</div>
				<div class="intro-copy">
					{#if itemType === 'transportation'}
						Keep timing, route, and booking details in one clean travel leg.
					{:else if itemType === 'lodging'}
						Track where you are staying, when you arrive, and what confirms the stay.
					{:else if itemType === 'location'}
						Capture the stop, why it matters, and when it belongs in the trip.
					{:else}
						Save a reminder, handoff note, or journal line for this trip.
					{/if}
				</div>
			</div>

			<!-- Name (with Places search for location & lodging) -->
			<section class="form-section">
				<div class="section-title">Primary info</div>
				{#if itemType === 'location' || itemType === 'lodging'}
					<div class="field">
						<label class="field-label">Name</label>
						<PlacesAutocomplete bind:value={name} placeholder={itemType === 'lodging' ? 'Search hotel or address...' : 'Search place or type name...'} onSelect={handlePlaceSelect} />
					</div>
				{:else}
					<div class="field">
						<label class="field-label">Name</label>
						<input class="field-input" type="text" bind:value={name} placeholder={itemType === 'note' ? 'Note title' : 'Name'} />
					</div>
				{/if}

				<!-- Type selectors -->
				{#if itemType === 'transportation'}
					<div class="field">
						<label class="field-label">Type</label>
						<select class="field-input" bind:value={transportType}>
							{#each transportTypes as t}<option value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>{/each}
						</select>
					</div>
					{#if transportType === 'plane'}
						<div class="field">
							<label class="field-label">Flight Number</label>
							<input class="field-input" type="text" bind:value={flightNumber} placeholder="UA 2341" />
						</div>
					{/if}
					<div class="field-row">
						<div class="field"><label class="field-label">From</label><input class="field-input" type="text" bind:value={fromLocation} /></div>
						<div class="field"><label class="field-label">To</label><input class="field-input" type="text" bind:value={toLocation} /></div>
					</div>
					<div class="field-row">
						<div class="field"><label class="field-label">Departure</label><input class="field-input" type="datetime-local" bind:value={startTime} /></div>
						<div class="field"><label class="field-label">Arrival</label><input class="field-input" type="datetime-local" bind:value={endTime} /></div>
					</div>
				{:else if itemType === 'lodging'}
					<div class="field">
						<label class="field-label">Type</label>
						<select class="field-input" bind:value={lodgingType}>
							{#each lodgingTypes as t}<option value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>{/each}
						</select>
					</div>
					<div class="field-row">
						<div class="field"><label class="field-label">Check-in</label><input class="field-input" type="date" bind:value={date} /></div>
						<div class="field"><label class="field-label">Check-out</label><input class="field-input" type="date" bind:value={endDate} /></div>
					</div>
					<div class="field">
						<label class="field-label">Reservation #</label>
						<input class="field-input" type="text" bind:value={reservationNumber} />
					</div>
				{:else if itemType === 'location'}
					<div class="field">
						<label class="field-label">Category</label>
						<select class="field-input" bind:value={category}>
							<option value="">Select...</option>
							{#each locationCategories as c}<option value={c}>{c.charAt(0).toUpperCase() + c.slice(1)}</option>{/each}
						</select>
					</div>
					<div class="field">
						<label class="field-label">Visit Date</label>
						<input class="field-input" type="date" bind:value={date} />
					</div>
					<div class="field-row">
						<div class="field"><label class="field-label">Start Time</label><input class="field-input" type="datetime-local" bind:value={startTime} /></div>
						<div class="field"><label class="field-label">End Time</label><input class="field-input" type="datetime-local" bind:value={endTime} /></div>
					</div>
					{#if category === 'hike'}
						<div class="field-row">
							<div class="field"><label class="field-label">Distance</label><input class="field-input" type="text" bind:value={hikeDistance} placeholder="5.2 miles" /></div>
							<div class="field">
								<label class="field-label">Difficulty</label>
								<select class="field-input" bind:value={hikeDifficulty}>
									<option value="">Select...</option>
									<option value="easy">Easy</option>
									<option value="moderate">Moderate</option>
									<option value="hard">Hard</option>
									<option value="strenuous">Strenuous</option>
								</select>
							</div>
							<div class="field"><label class="field-label">Duration</label><input class="field-input" type="text" bind:value={hikeTime} placeholder="3 hours" /></div>
						</div>
					{/if}
				{:else if itemType === 'note'}
					<div class="field">
						<label class="field-label">Date</label>
						<input class="field-input" type="date" bind:value={date} />
					</div>
				{/if}
			</section>

			<section class="form-section">
				<div class="section-title">{itemType === 'note' ? 'Content' : 'Details'}</div>
				{#if itemType === 'note'}
					<div class="field">
						<label class="field-label">Content</label>
						<textarea class="field-input field-textarea" bind:value={content} rows="6" placeholder="Write your note..."></textarea>
					</div>
				{:else}
					<div class="field">
						<label class="field-label">Description</label>
						<textarea class="field-input field-textarea" bind:value={description} rows="3" placeholder="Details..."></textarea>
					</div>
				{/if}
			</section>

			<!-- Link -->
			{#if itemType !== 'note'}
				<section class="form-section">
					<div class="section-title">Booking + cost</div>
					<div class="field">
						<label class="field-label">Link</label>
						<input class="field-input" type="url" bind:value={link} placeholder="https://..." />
					</div>
					<div class="field-row">
						<div class="field"><label class="field-label">Points</label><input class="field-input" type="number" bind:value={costPoints} /></div>
						<div class="field"><label class="field-label">Cash ($)</label><input class="field-input" type="number" step="0.01" bind:value={costCash} /></div>
					</div>
				</section>
			{/if}

			<!-- Images & Documents (edit mode only) -->
			{#if isEdit && itemType !== 'note'}
				<section class="form-section">
					<div class="section-title">Attachments</div>
					<div class="field">
						<label class="field-label">Photos & Documents</label>
						<ImageUpload
							entityType={itemType}
							entityId={editItem.id}
							images={mediaImages}
							documents={mediaDocuments}
							onUpload={refreshMedia}
						/>
					</div>
				</section>
			{/if}
		</div>

		<div class="modal-footer">
			{#if isEdit}
				{#if confirmDelete}
					<div class="delete-confirm">
						<span class="delete-msg">Delete this item?</span>
						<button class="btn-danger" onclick={doDelete} disabled={saving}>Yes, delete</button>
						<button class="btn-cancel" onclick={() => confirmDelete = false}>Cancel</button>
					</div>
				{/if}
			{/if}
			<div class="footer-right">
				{#if isEdit && !confirmDelete}
					<button class="btn-delete" onclick={() => confirmDelete = true}>
						<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
					</button>
				{/if}
				<button class="btn-cancel" onclick={close}>Cancel</button>
				<button class="btn-save" onclick={save} disabled={saving || !name.trim()}>
					{saving ? 'Saving...' : isEdit ? 'Save' : 'Add'}
				</button>
			</div>
		</div>
	</div>
</div>
{/if}

<style>
	.modal-overlay {
		position: fixed;
		inset: 0;
		z-index: 70;
		display: flex;
		justify-content: flex-end;
		background:
			linear-gradient(180deg, rgba(53, 40, 31, 0.1), rgba(24, 17, 12, 0.42)),
			rgba(17, 11, 7, 0.28);
		backdrop-filter: blur(10px);
		animation: modalFade 180ms ease;
	}

	@keyframes modalFade {
		from { opacity: 0; }
		to { opacity: 1; }
	}

	.modal-sheet {
		width: min(560px, 100%);
		height: 100%;
		display: flex;
		flex-direction: column;
		background:
			linear-gradient(180deg, rgba(255, 250, 242, 0.98), rgba(247, 239, 229, 0.98));
		border-left: 1px solid rgba(122, 96, 70, 0.18);
		box-shadow: -24px 0 64px rgba(39, 26, 16, 0.18);
		animation: modalSlide 220ms cubic-bezier(0.22, 1, 0.36, 1);
	}

	@keyframes modalSlide {
		from { transform: translateX(100%); }
		to { transform: translateX(0); }
	}

	.modal-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 18px;
		padding: 28px 28px 20px;
		border-bottom: 1px solid rgba(122, 96, 70, 0.14);
		background:
			linear-gradient(180deg, rgba(255, 248, 237, 0.92), rgba(255, 248, 237, 0.74));
	}

	.modal-head-copy {
		display: flex;
		flex-direction: column;
		gap: 6px;
		min-width: 0;
	}

	.modal-kicker {
		font-size: 0.68rem;
		font-weight: 700;
		letter-spacing: 0.16em;
		text-transform: uppercase;
		color: rgba(124, 94, 61, 0.7);
	}

	.modal-title {
		font-size: clamp(1.35rem, 1.15rem + 0.55vw, 1.82rem);
		line-height: 1.04;
		font-weight: 600;
		letter-spacing: -0.03em;
		color: #27190f;
	}

	.modal-close {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 40px;
		height: 40px;
		padding: 0;
		border: 1px solid rgba(122, 96, 70, 0.16);
		border-radius: 999px;
		background: rgba(255, 252, 247, 0.82);
		color: rgba(90, 69, 50, 0.72);
		cursor: pointer;
		transition: background 160ms ease, color 160ms ease, transform 160ms ease;
	}

	.modal-close:hover {
		background: rgba(255, 252, 247, 1);
		color: #3d2b1d;
		transform: translateY(-1px);
	}

	.modal-close svg {
		width: 16px;
		height: 16px;
	}

	.modal-body {
		flex: 1;
		overflow-y: auto;
		padding: 24px 28px 32px;
		display: flex;
		flex-direction: column;
		gap: 18px;
	}

	.modal-intro {
		padding: 18px 18px 16px;
		border-radius: 24px;
		background: rgba(252, 245, 236, 0.92);
		border: 1px solid rgba(140, 112, 82, 0.13);
		box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.5);
	}

	.intro-line {
		font-size: 0.92rem;
		font-weight: 600;
		color: #3f2c1d;
		letter-spacing: -0.02em;
	}

	.intro-copy {
		margin-top: 8px;
		max-width: 42ch;
		font-size: 0.92rem;
		line-height: 1.55;
		color: rgba(92, 72, 53, 0.84);
	}

	.form-section {
		display: flex;
		flex-direction: column;
		gap: 14px;
		padding: 18px;
		border-radius: 24px;
		background: rgba(255, 252, 248, 0.78);
		border: 1px solid rgba(140, 112, 82, 0.12);
		box-shadow:
			inset 0 1px 0 rgba(255, 255, 255, 0.5),
			0 12px 28px rgba(75, 49, 27, 0.04);
	}

	.section-title {
		font-size: 0.74rem;
		font-weight: 700;
		letter-spacing: 0.14em;
		text-transform: uppercase;
		color: rgba(124, 94, 61, 0.72);
	}

	.field {
		display: flex;
		flex-direction: column;
		gap: 7px;
		min-width: 0;
	}

	.field-label {
		font-size: 0.74rem;
		font-weight: 700;
		letter-spacing: 0.1em;
		text-transform: uppercase;
		color: rgba(110, 82, 57, 0.74);
	}

	.field-input {
		width: 100%;
		padding: 12px 14px;
		border-radius: 16px;
		border: 1px solid rgba(128, 103, 79, 0.14);
		background: rgba(255, 255, 255, 0.86);
		color: #281a11;
		font-size: 0.96rem;
		line-height: 1.35;
		font-family: var(--font);
		box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.46);
		transition: border-color 150ms ease, box-shadow 150ms ease, background 150ms ease;
	}

	.field-input::placeholder {
		color: rgba(123, 102, 85, 0.66);
	}

	.field-input:focus {
		outline: none;
		border-color: rgba(184, 134, 82, 0.58);
		background: rgba(255, 255, 255, 0.96);
		box-shadow:
			0 0 0 4px rgba(184, 134, 82, 0.12),
			inset 0 1px 0 rgba(255, 255, 255, 0.55);
	}

	.field-textarea {
		resize: vertical;
		min-height: 104px;
	}

	.field-row {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 12px;
	}

	.modal-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16px;
		padding: 18px 28px 22px;
		border-top: 1px solid rgba(122, 96, 70, 0.14);
		background:
			linear-gradient(180deg, rgba(255, 250, 242, 0.68), rgba(253, 246, 238, 0.92));
	}

	.footer-right {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.btn-cancel,
	.btn-save,
	.btn-danger {
		font-family: var(--font);
		font-size: 0.92rem;
		font-weight: 600;
		cursor: pointer;
		transition: transform 150ms ease, background 150ms ease, border-color 150ms ease, color 150ms ease, box-shadow 150ms ease;
	}

	.btn-cancel {
		padding: 10px 16px;
		border-radius: 999px;
		background: rgba(255, 251, 247, 0.8);
		color: #5c4837;
		border: 1px solid rgba(128, 103, 79, 0.18);
	}

	.btn-cancel:hover {
		background: rgba(255, 251, 247, 1);
		color: #352418;
	}

	.btn-save {
		padding: 10px 18px;
		border-radius: 999px;
		background: linear-gradient(135deg, #2f2013, #59412c);
		color: #fff8f1;
		border: none;
		box-shadow: 0 12px 24px rgba(55, 37, 23, 0.18);
	}

	.btn-save:hover:not(:disabled) {
		transform: translateY(-1px);
		box-shadow: 0 14px 26px rgba(55, 37, 23, 0.22);
	}

	.btn-save:disabled {
		opacity: 0.45;
		cursor: default;
		box-shadow: none;
	}

	.btn-delete {
		width: 40px;
		height: 40px;
		padding: 0;
		border-radius: 999px;
		background: rgba(137, 41, 27, 0.08);
		border: 1px solid rgba(137, 41, 27, 0.18);
		color: #8f3928;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: transform 150ms ease, background 150ms ease;
	}

	.btn-delete:hover {
		transform: translateY(-1px);
		background: rgba(137, 41, 27, 0.12);
	}

	.btn-delete svg {
		width: 16px;
		height: 16px;
	}

	.delete-confirm {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 10px;
	}

	.delete-msg {
		font-size: 0.88rem;
		font-weight: 600;
		color: #8f3928;
	}

	.btn-danger {
		padding: 9px 14px;
		border-radius: 999px;
		background: #8f3928;
		color: #fff7f3;
		border: none;
	}

	.btn-danger:hover {
		transform: translateY(-1px);
		background: #7e2e1f;
	}

	@media (max-width: 768px) {
		.modal-sheet {
			width: 100%;
		}

		.modal-header {
			padding: 24px 18px 18px;
		}

		.modal-body {
			padding: 18px 18px 28px;
			gap: 14px;
		}

		.modal-intro,
		.form-section {
			padding: 16px;
			border-radius: 20px;
		}

		.field-row {
			grid-template-columns: minmax(0, 1fr);
		}

		.modal-footer {
			padding: 10px 14px 12px;
			flex-direction: column;
			align-items: stretch;
			gap: 10px;
		}

		.delete-confirm {
			justify-content: center;
		}

		.btn-delete {
			width: 42px;
			height: 42px;
			align-self: flex-start;
		}

		.footer-right {
			width: 100%;
			display: grid;
			grid-template-columns: auto 1fr 1fr;
			gap: 8px;
		}

		.btn-cancel,
		.btn-save {
			justify-content: center;
			text-align: center;
			padding-top: 9px;
			padding-bottom: 9px;
		}
	}
</style>
