<script lang="ts">
	let {
		open = $bindable(false),
		tripData,
		onSaved
	}: {
		open: boolean;
		tripData: any;
		onSaved: () => void;
	} = $props();

	let saving = $state(false);
	let confirmDelete = $state(false);
	let sharing = $state(false);
	let shareUrl = $state('');
	let copied = $state(false);

	let name = $state('');
	let description = $state('');
	let startDate = $state('');
	let endDate = $state('');

	$effect(() => {
		if (open && tripData) {
			name = tripData.name || '';
			description = tripData.description || '';
			startDate = tripData.start_date || '';
			endDate = tripData.end_date || '';
			shareUrl = tripData.share_token
				? `${typeof window !== 'undefined' ? window.location.origin : ''}/trips/view/${tripData.share_token}`
				: '';
			confirmDelete = false;
			copied = false;
		}
	});

	function close() {
		open = false;
	}

	async function save() {
		saving = true;
		try {
			await fetch('/api/trips/trip/update', {
				method: 'POST',
				credentials: 'include',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					id: tripData.id,
					name,
					description,
					start_date: startDate,
					end_date: endDate
				})
			});
			close();
			onSaved();
		} catch (e) {
			console.error('Save failed:', e);
		} finally {
			saving = false;
		}
	}

	async function doDelete() {
		saving = true;
		try {
			await fetch('/api/trips/trip/delete', {
				method: 'POST',
				credentials: 'include',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ id: tripData.id })
			});
			window.location.href = '/trips';
		} catch (e) {
			console.error('Delete failed:', e);
		} finally {
			saving = false;
		}
	}

	async function toggleShare() {
		sharing = true;
		try {
			if (shareUrl) {
				await fetch('/api/trips/share/delete', {
					method: 'POST',
					credentials: 'include',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ trip_id: tripData.id })
				});
				shareUrl = '';
			} else {
				const res = await fetch('/api/trips/share/create', {
					method: 'POST',
					credentials: 'include',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ trip_id: tripData.id })
				});
				const data = await res.json();
				shareUrl = `${window.location.origin}/trips/view/${data.share_token}`;
			}
		} catch {
			// keep modal stable
		} finally {
			sharing = false;
		}
	}

	async function copyUrl() {
		if (!shareUrl) return;
		await navigator.clipboard.writeText(shareUrl);
		copied = true;
		setTimeout(() => (copied = false), 1800);
	}
</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">Trip settings</div>
				<div class="modal-title">Edit Trip</div>
			</div>
			<button class="modal-close" onclick={close} aria-label="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">Trip profile</div>
				<div class="intro-copy">Keep the trip name, date range, and sharing state in one calmer control surface.</div>
			</div>

			<section class="form-section">
				<div class="section-title">Primary info</div>
				<div class="field">
					<label class="field-label">Trip name</label>
					<input class="field-input" type="text" bind:value={name} placeholder="Trip name" />
				</div>
				<div class="field">
					<label class="field-label">Description</label>
					<textarea class="field-input field-textarea" bind:value={description} rows="4" placeholder="What is this trip about?"></textarea>
				</div>
			</section>

			<section class="form-section">
				<div class="section-title">Dates</div>
				<div class="field-row">
					<div class="field">
						<label class="field-label">Start date</label>
						<input class="field-input" type="date" bind:value={startDate} />
					</div>
					<div class="field">
						<label class="field-label">End date</label>
						<input class="field-input" type="date" bind:value={endDate} />
					</div>
				</div>
			</section>

			<section class="form-section">
				<div class="section-row">
					<div class="share-copy">
						<div class="section-title">Sharing</div>
						<div class="section-copy">Create a viewer link for this trip, or revoke it when you want the itinerary private again.</div>
					</div>
					<button class="share-toggle" onclick={toggleShare} disabled={sharing}>
						{shareUrl ? 'Revoke link' : 'Create share link'}
					</button>
				</div>

				{#if shareUrl}
					<div class="share-stack">
						<div class="share-pill">
							<div class="share-label">Viewer link</div>
							<div class="share-value">{shareUrl}</div>
						</div>
						<div class="share-actions">
							<button class="copy-btn" onclick={copyUrl}>{copied ? 'Copied' : 'Copy link'}</button>
						</div>
					</div>
				{:else}
					<div class="share-empty">No public trip link yet.</div>
				{/if}
			</section>
		</div>

		<div class="modal-footer">
			{#if confirmDelete}
				<div class="delete-confirm">
					<span class="delete-msg">Delete this trip permanently?</span>
				</div>
				<div class="footer-right">
					<button class="btn-danger" onclick={doDelete} disabled={saving}>Delete trip</button>
					<button class="btn-cancel" onclick={() => (confirmDelete = false)}>Keep trip</button>
				</div>
			{:else}
				<button class="btn-delete-text" onclick={() => (confirmDelete = true)}>Delete Trip</button>
				<div class="footer-right">
					<button class="btn-cancel" onclick={close}>Cancel</button>
					<button class="btn-save" onclick={save} disabled={saving || !name.trim()}>
						{saving ? 'Saving...' : 'Save'}
					</button>
				</div>
			{/if}
		</div>
	</div>
</div>
{/if}

<style>
	.modal-overlay {
		position: fixed;
		inset: 0;
		display: flex;
		justify-content: flex-end;
		background: rgba(26, 18, 11, 0.36);
		backdrop-filter: blur(10px);
		z-index: 70;
		animation: modalFade 150ms ease;
	}

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

	.modal-sheet {
		width: 520px;
		max-width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, rgba(252, 248, 242, 0.98), rgba(245, 237, 228, 0.98));
		box-shadow: -18px 0 54px rgba(34, 23, 13, 0.14);
		animation: modalSlide 200ms ease;
	}

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

	.modal-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		padding: 22px 24px 18px;
		border-bottom: 1px solid rgba(150, 123, 95, 0.12);
	}

	.modal-head-copy {
		display: grid;
		gap: 6px;
	}

	.modal-kicker,
	.intro-line,
	.section-title,
	.share-label,
	.field-label {
		font-size: 11px;
		text-transform: uppercase;
		letter-spacing: 0.16em;
		color: #8f7861;
	}

	.modal-title {
		font-size: 1.85rem;
		font-weight: 650;
		line-height: 0.98;
		letter-spacing: -0.04em;
		color: #24180f;
	}

	.modal-close {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 38px;
		height: 38px;
		border-radius: 999px;
		border: 1px solid rgba(150, 123, 95, 0.12);
		background: rgba(255, 255, 255, 0.6);
		color: #6a5644;
		cursor: pointer;
	}

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

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

	.modal-intro {
		display: grid;
		gap: 6px;
		padding: 0 2px;
	}

	.intro-copy,
	.section-copy {
		color: #655444;
		line-height: 1.55;
		font-size: 0.96rem;
	}

	.form-section {
		display: grid;
		gap: 14px;
		padding: 18px;
		border-radius: 24px;
		background: rgba(255, 251, 246, 0.68);
		border: 1px solid rgba(150, 123, 95, 0.12);
	}

	.section-row {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 12px;
	}

	.share-copy {
		display: grid;
		gap: 6px;
	}

	.field {
		display: flex;
		flex-direction: column;
		gap: 6px;
	}

	.field-label {
		font-weight: 600;
		letter-spacing: 0.12em;
	}

	.field-input {
		padding: 12px 14px;
		border-radius: 16px;
		border: 1px solid rgba(150, 123, 95, 0.14);
		background: rgba(255, 251, 246, 0.96);
		color: #24180f;
		font-size: 0.98rem;
		font-family: var(--font);
	}

	.field-input:focus {
		outline: none;
		border-color: rgba(110, 80, 48, 0.42);
		box-shadow: 0 0 0 4px rgba(167, 127, 76, 0.12);
	}

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

	.field-row {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 12px;
	}

	.share-toggle,
	.copy-btn,
	.btn-cancel,
	.btn-save,
	.btn-danger {
		min-height: 42px;
		padding: 0 16px;
		border-radius: 999px;
		font: inherit;
		font-size: 0.9rem;
		font-weight: 600;
		cursor: pointer;
	}

	.share-toggle,
	.btn-save {
		background: #2f2218;
		color: #fff7ef;
		border: none;
	}

	.share-toggle:disabled,
	.btn-save:disabled,
	.btn-danger:disabled {
		opacity: 0.55;
		cursor: default;
	}

	.share-stack {
		display: grid;
		gap: 12px;
	}

	.share-pill {
		display: grid;
		gap: 6px;
		padding: 14px 16px;
		border-radius: 18px;
		background: rgba(246, 237, 226, 0.82);
		border: 1px solid rgba(150, 123, 95, 0.12);
	}

	.share-value {
		font-size: 0.92rem;
		line-height: 1.45;
		color: #3d2b1c;
		word-break: break-all;
	}

	.share-actions {
		display: flex;
		justify-content: flex-start;
	}

	.copy-btn,
	.btn-cancel {
		background: rgba(255, 251, 246, 0.96);
		color: #5e4d3d;
		border: 1px solid rgba(150, 123, 95, 0.14);
	}

	.share-empty {
		padding: 14px 16px;
		border-radius: 18px;
		background: rgba(246, 237, 226, 0.62);
		border: 1px dashed rgba(150, 123, 95, 0.18);
		color: #705e4f;
	}

	.modal-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
		padding: 16px 24px 18px;
		border-top: 1px solid rgba(150, 123, 95, 0.12);
		background: rgba(251, 246, 240, 0.82);
	}

	.footer-right {
		display: flex;
		gap: 8px;
	}

	.btn-delete-text {
		background: none;
		border: none;
		padding: 0;
		font: inherit;
		font-size: 0.9rem;
		font-weight: 600;
		color: #a23e26;
		cursor: pointer;
	}

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

	.delete-msg {
		font-size: 0.92rem;
		font-weight: 600;
		color: #a23e26;
	}

	.btn-danger {
		background: #a23e26;
		color: white;
		border: none;
	}

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

		.modal-header {
			padding: 18px 16px 14px;
		}

		.modal-body {
			padding: 16px 16px 22px;
		}

		.section-row,
		.field-row {
			grid-template-columns: 1fr;
			display: grid;
		}

		.modal-footer {
			padding: 14px 16px calc(12px + env(safe-area-inset-bottom, 0px));
			flex-wrap: wrap;
		}

		.footer-right {
			width: 100%;
		}

		.footer-right :global(button) {
			flex: 1;
		}
	}
</style>
