<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

const props = defineProps<{ boat: any; position: { x: number; y: number } }>()
const emit  = defineEmits<{ (e: 'close'): void; (e: 'bringToFront'): void }>()

const SPEED_UNITS = {
	knots: { label: 'KTS', convert: (v: number) => v.toFixed(1) },
	kph:   { label: 'KPH', convert: (v: number) => (v * 1.852).toFixed(1) },
	mph:   { label: 'MPH', convert: (v: number) => (v * 1.15078).toFixed(1) },
}
const UNIT_KEY = 'ais_units'
function loadUnits() {
	const s = localStorage.getItem(UNIT_KEY)
	return s ? JSON.parse(s) : { speed: 'knots' }
}
const prefs = ref(loadUnits())
function cycleSpeed() {
	const keys = Object.keys(SPEED_UNITS)
	const p = loadUnits()
	p.speed = keys[(keys.indexOf(p.speed) + 1) % keys.length]
	prefs.value = { ...p }
	localStorage.setItem(UNIT_KEY, JSON.stringify(p))
}
const speed = computed(() => SPEED_UNITS[prefs.value.speed as keyof typeof SPEED_UNITS])

// ── Derived data ──────────────────────────────────────────────────────────────
const name     = computed(() => props.boat.name?.trim() || props.boat.callsign?.trim() || `MMSI: ${props.boat.mmsi}`)
const heading  = computed(() => props.boat.heading ?? props.boat.course ?? 0)
const speedVal = computed(() => speed.value.convert(props.boat.speed ?? 0))
const rows = computed(() => [
	['MMSI',        props.boat.mmsi],
	['Country',     props.boat.country],
	['Callsign',    props.boat.callsign || '-'],
	['IMO',         props.boat.imo || '-'],
	['Ship Type',   props.boat.ship_type ?? '-'],
	['Lat / Lon',   `${props.boat.lat?.toFixed(5)}, ${props.boat.lon?.toFixed(5)}`],
	['Distance',    props.boat.distance != null ? `${props.boat.distance.toFixed(2)} nmi` : '-'],
	['Bearing',     props.boat.bearing != null ? `${props.boat.bearing}°` : '-'],
	['Destination', props.boat.destination || '-'],
	['ETA',         props.boat.eta || '-'],
	['Draught',     props.boat.draught != null ? `${props.boat.draught}m` : '-'],
	['RSSI',        props.boat.rssi != null ? `${props.boat.rssi.toFixed(1)} dB` : '-'],
	['Channels',    props.boat.channels || '-'],
	['Last Signal', props.boat.last_signal != null ? `${props.boat.last_signal}s ago` : '-'],
])

// ── Compass HUD ───────────────────────────────────────────────────────────────
const compass = computed(() => {
	const hdg     = heading.value
	const spd     = props.boat.speed ?? 0
	const course  = props.boat.course ?? hdg
	const bearing = props.boat.bearing ?? 0

	// Compass tape: show ±60° window
	const tapeTicks: string[] = []
	for (let offset = -60; offset <= 60; offset += 5) {
		const deg  = ((hdg + offset) % 360 + 360) % 360
		const x    = 100 + (offset / 60) * 90
		const major = offset % 30 === 0
		const mid   = offset % 15 === 0

		if (major) {
			const lbl = ({ 0: 'N', 45: 'NE', 90: 'E', 135: 'SE', 180: 'S', 225: 'SW', 270: 'W', 315: 'NW' } as any)[deg]
				?? String(deg).padStart(3, '0')
			tapeTicks.push(`
                <line x1="${x}" y1="22" x2="${x}" y2="38" stroke="#0ff" stroke-width="2"/>
                <text x="${x}" y="50" text-anchor="middle" fill="#0ff" font-size="11" font-weight="bold">${lbl}</text>
            `)
		} else if (mid) {
			tapeTicks.push(`<line x1="${x}" y1="26" x2="${x}" y2="38" stroke="#0ff" stroke-width="1.5"/>`)
		} else {
			tapeTicks.push(`<line x1="${x}" y1="30" x2="${x}" y2="38" stroke="#0ff" stroke-width="1"/>`)
		}
	}

	// Depth/rudder gauge (visual only, based on course vs heading difference)
	const rudder = Math.max(-30, Math.min(30, ((course - hdg + 540) % 360) - 180))
	const rudX   = 100 + (rudder / 30) * 40

	// Speed arc (0–30 kts range)
	const spdPct  = Math.min(spd / 30, 1)
	const arcEnd  = 160 + spdPct * 140 // degrees on a 160–300° arc
	function polarToXY(cx: number, cy: number, r: number, deg: number) {
		const rad = (deg - 90) * Math.PI / 180
		return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) }
	}
	function describeArc(cx: number, cy: number, r: number, startDeg: number, endDeg: number) {
		const s   = polarToXY(cx, cy, r, startDeg)
		const e   = polarToXY(cx, cy, r, endDeg)
		const lg  = endDeg - startDeg > 180 ? 1 : 0
		return `M ${s.x} ${s.y} A ${r} ${r} 0 ${lg} 1 ${e.x} ${e.y}`
	}
	const spdArcPath = describeArc(100, 145, 52, 160, Math.max(161, arcEnd))

	// Course indicator needle angle (relative to up = heading)
	const courseRel = ((course - hdg + 540) % 360) - 180
	const courseRad = courseRel * Math.PI / 180
	const cNeedleX  = 100 + 44 * Math.sin(courseRad)
	const cNeedleY  = 145 - 44 * Math.cos(courseRad)

	// Bearing indicator
	const bearRel = ((bearing - hdg + 540) % 360) - 180
	const bearRad = bearRel * Math.PI / 180
	const bNeedleX = 100 + 52 * Math.sin(bearRad)
	const bNeedleY = 145 - 52 * Math.cos(bearRad)

	return `
        <svg width="200" height="200" viewBox="0 0 200 200" style="background:#000;border-radius:4px">
            <!-- Compass tape -->
            <rect x="10" y="18" width="180" height="40" fill="rgba(0,20,40,0.95)" rx="3"/>
            <line x1="10" y1="18" x2="190" y2="18" stroke="#0ff" stroke-width="1"/>
            <line x1="10" y1="58" x2="190" y2="58" stroke="#0ff" stroke-width="1"/>
            ${tapeTicks.join('')}
            <!-- Centre lubber line -->
            <polygon points="100,12 96,20 104,20" fill="#ff0"/>

            <!-- Heading readout -->
            <rect x="72" y="60" width="56" height="20" fill="rgba(0,0,0,0.9)" stroke="#0ff" stroke-width="1" rx="2"/>
            <text x="100" y="75" text-anchor="middle" fill="#0ff" font-size="13" font-weight="bold">${String(Math.round(hdg)).padStart(3, '0')}°</text>

            <!-- Rose ring -->
            <circle cx="100" cy="145" r="55" fill="rgba(0,20,40,0.6)" stroke="#0ff" stroke-width="1.5"/>
            <circle cx="100" cy="145" r="40" fill="none" stroke="rgba(0,255,255,0.15)" stroke-width="1"/>

            <!-- Ring tick marks -->
            ${Array.from({ length: 36 }, (_, i) => {
		const a   = i * 10
		const rad = (a - 90) * Math.PI / 180
		const r1  = a % 30 === 0 ? 44 : 50
		const sw  = a % 30 === 0 ? 2 : 1
		const x1  = 100 + r1 * Math.cos(rad)
		const y1  = 145 + r1 * Math.sin(rad)
		const x2  = 100 + 55 * Math.cos(rad)
		const y2  = 145 + 55 * Math.sin(rad)
		return `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="#0ff" stroke-width="${sw}" opacity="0.5"/>`
	}).join('')}

            <!-- Cardinal labels -->
            ${(['N','E','S','W'] as const).map((lbl, i) => {
		const a   = i * 90
		const rad = (a - 90) * Math.PI / 180
		const x   = 100 + 47 * Math.cos(rad)
		const y   = 145 + 47 * Math.sin(rad) + 4
		return `<text x="${x}" y="${y}" text-anchor="middle" fill="#0ff" font-size="9" font-weight="bold" opacity="0.7">${lbl}</text>`
	}).join('')}

            <!-- Course needle (green) -->
            <line x1="100" y1="145" x2="${cNeedleX}" y2="${cNeedleY}" stroke="#0f0" stroke-width="2.5"/>
            <circle cx="${cNeedleX}" cy="${cNeedleY}" r="3" fill="#0f0"/>

            <!-- Bearing needle (yellow dashed) -->
            <line x1="100" y1="145" x2="${bNeedleX}" y2="${bNeedleY}" stroke="#ff0" stroke-width="1.5" stroke-dasharray="4,3"/>
            <circle cx="${bNeedleX}" cy="${bNeedleY}" r="2.5" fill="#ff0"/>

            <!-- Ship symbol -->
            <polygon points="100,138 96,152 100,149 104,152" fill="#fff" stroke="#0ff" stroke-width="1"/>

            <!-- Speed arc -->
            <path d="${spdArcPath}" fill="none" stroke="#0f0" stroke-width="4" stroke-linecap="round"/>
            <path d="${describeArc(100, 145, 52, 160, 300)}" fill="none" stroke="rgba(0,255,0,0.15)" stroke-width="4"/>

            <!-- Speed readout -->
            <text x="100" y="190" text-anchor="middle" fill="#0f0" font-size="11" font-weight="bold">${speedVal.value} ${speed.value.label}</text>

            <!-- Rudder bar -->
            <rect x="60" y="175" width="80" height="6" fill="rgba(0,40,60,0.9)" rx="3"/>
            <line x1="100" y1="173" x2="100" y2="183" stroke="#0ff" stroke-width="1" opacity="0.5"/>
            <rect x="${rudX - 4}" y="174" width="8" height="8" fill="#ff0" rx="1"/>

            <!-- Legend -->
            <line x1="12" y1="163" x2="24" y2="163" stroke="#0f0" stroke-width="2"/>
            <text x="27" y="167" fill="#888" font-size="9">COG</text>
            <line x1="12" y1="173" x2="24" y2="173" stroke="#ff0" stroke-width="1.5" stroke-dasharray="4,3"/>
            <text x="27" y="177" fill="#888" font-size="9">BRG</text>
        </svg>
    `
})
</script>

<template>
	<div class="ship-popup" :style="{ left: pos.x + 'px', top: pos.y + 'px' }">

		<!-- Header -->
		<div ref="header" class="sp-header" @mousedown="onMouseDown" @touchstart.passive="onTouchStart">
			<h3 class="sp-name">
				🚢
				<span>{{ name.toUpperCase() }}</span>
				<span class="sp-mmsi"> / {{ boat.mmsi }}</span>
			</h3>
			<button class="sp-close" @click.stop="emit('close')">×</button>
		</div>

		<!-- Meta -->
		<div class="sp-meta">
			<div class="flex-c">
				<span>{{ boat.operator || boat.owner || '' }}</span>
				<span>{{ boat.country || 'Unknown Country' }}</span>
			</div>
			<div class="flex-c align-x-end">
				<span>{{ boat.ship_type || '' }}</span>
				<span style="text-transform:capitalize">{{ boat.type || 'Unknown' }}</span>
			</div>
		</div>

		<!-- Body -->
		<div class="sp-body">
			<!-- Gauges -->
			<div class="sp-gauges">
				<div class="sp-gauge-wrap">
					<div class="sp-gauge-label">Speed</div>
					<div class="sp-gauge" @click.stop="cycleSpeed">
						<span class="sp-gauge-val">{{ speedVal }}</span>
						<span class="sp-gauge-unit">{{ speed.label }}</span>
					</div>
				</div>
				<div class="sp-gauge-wrap">
					<div class="sp-gauge-label">Course</div>
					<div class="sp-gauge">
						<span class="sp-gauge-val">{{ boat.course != null ? boat.course.toFixed(0) : '-' }}</span>
						<span class="sp-gauge-unit">°</span>
					</div>
				</div>
				<div class="sp-gauge-wrap">
					<div class="sp-gauge-label">Heading</div>
					<div class="sp-gauge">
						<span class="sp-gauge-val">{{ boat.heading != null ? boat.heading.toFixed(0) : '-' }}</span>
						<span class="sp-gauge-unit">°</span>
					</div>
				</div>
				<div class="sp-gauge-wrap">
					<div class="sp-gauge-label">Distance</div>
					<div class="sp-gauge">
						<span class="sp-gauge-val">{{ boat.distance?.toFixed(1) ?? '-' }}</span>
						<span class="sp-gauge-unit">NMI</span>
					</div>
				</div>
			</div>

			<!-- Compass HUD -->
			<div class="sp-compass" v-html="compass"/>
		</div>

		<!-- Details table -->
		<div class="sp-details">
			<div v-for="[label, val] in rows" :key="label" class="sp-detail-row">
				<span class="sp-detail-label">{{ label }}</span>
				<span class="sp-detail-val">{{ val ?? '-' }}</span>
			</div>
		</div>

	</div>
</template>

<style scoped>
.ship-popup {
	position: fixed;
	z-index: 9999;
	pointer-events: auto;
	background: rgba(0,10,20,0.92);
	border: 1px solid rgba(0,200,255,0.3);
	border-radius: 8px;
	box-shadow: 0 4px 24px rgba(0,0,0,0.6);
	overflow: hidden;
	font-family: monospace;
	color: #ccc;
	min-width: 360px;
}

.sp-header {
	position: relative;
	padding: 12px 16px;
	border-bottom: 1px solid rgba(0,200,255,0.2);
	cursor: move;
	user-select: none;
	-webkit-user-select: none;
	background: rgba(0,20,40,0.6);
}

.sp-name {
	margin: 0 24px 0 0;
	color: #7eeee1;
	font-size: 16px;
}
.sp-mmsi { color: white; }

.sp-meta {
	font-size: 11px;
	color: #888;
	display: flex;
	justify-content: space-between;
	gap: 8px;
	padding: 8px 16px;
	border-bottom: 1px solid rgba(0,200,255,0.15);
}

.sp-close {
	position: absolute;
	top: 8px;
	right: 8px;
	background: rgba(255,255,255,0.1);
	border: none;
	color: white;
	width: 24px;
	height: 24px;
	border-radius: 4px;
	cursor: pointer;
	font-size: 16px;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: background 0.2s;
}
.sp-close:hover { background: rgba(255,255,255,0.25); }

.sp-body {
	display: flex;
	gap: 12px;
	padding: 12px 16px;
	border-bottom: 1px solid rgba(0,200,255,0.15);
}

.sp-gauges     { flex: 0 0 110px; display: flex; flex-direction: column; gap: 8px; }
.sp-gauge-wrap {}

.sp-gauge-label {
	color: #888;
	font-size: 10px;
	font-weight: bold;
	margin-bottom: 2px;
}

.sp-gauge {
	padding: 5px 6px;
	background: rgba(0,0,0,0.95);
	border: 2px solid #0ff;
	border-radius: 3px;
	cursor: pointer;
	display: flex;
	align-items: flex-end;
	justify-content: center;
	gap: 4px;
	transition: border-color 0.15s;
}
.sp-gauge:hover   { border-color: #0f0; }
.sp-gauge-val     { font-size: 18px; font-weight: bold; color: #0ff; }
.sp-gauge-unit    { font-size: 10px; color: #0ff; margin-bottom: 2px; }

.sp-compass { flex: 1; }

.sp-details {
	padding: 8px 16px 12px;
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 5px 16px;
	max-height: 180px;
	overflow-y: auto;
}
.sp-detail-row   { display: flex; flex-direction: column; }
.sp-detail-label { color: #888; font-size: 9px; font-weight: bold; }
.sp-detail-val   { color: #0ff; font-size: 12px; }
</style>
