<template>
  <div class="chassis-control">
    <div class="main-wrap">
      <section class="map-area">
        <div class="area-bar">
          <span class="area-bar__title">
            <svg viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.4" class="area-bar__icon">
              <polygon points="1 4.5 1 15 6 12.5 12 15 17 12.5 17 1.5 12 4 6 1.5" />
              <line x1="6" y1="1.5" x2="6" y2="12.5" />
              <line x1="12" y1="4" x2="12" y2="15" />
            </svg>
            MAP VIEW
          </span>
          <div class="map-controller">
            <div class="btn-container">
                <el-icon :size="16" class="map-action-icon" @click="zoomCanvas(true)"><zoom-out /></el-icon>
            </div>
            <div class="btn-container">
                <el-icon :size="16" class="map-action-icon" @click="zoomCanvas(false)"><zoom-in /></el-icon>
            </div>
            <div class="btn-container">
                <!-- @click="centerCanvasView" -->
                <el-icon :size="16" class="map-action-icon"><Location /></el-icon>
            </div>
        </div>
        </div>

        <div class="map-body">
          <!-- <canvas ref="mapCanvas" /> -->
           <MapCanvas :mapName="robotStore.current_map" :isDragging="!isDragging" />
        </div>
      </section>

      <aside class="panel">
        <!-- Direction -->
        <div class="card">
          <div class="card__head">
            <h3>方向控制</h3>
            <el-tag size="small" effect="dark" type="info">长按持续移动</el-tag>
          </div>

          <div class="dpad">
            <button class="dpad__btn dpad__btn--up"
              @pointerdown="onPointerDown($event, 'forward')"
              @pointerup="onPointerEnd" @pointercancel="onPointerEnd">
              <svg viewBox="0 0 14 14"><path d="M7 1L13 11H1Z" fill="currentColor" /></svg>
              <small>前进</small>
            </button>

            <button class="dpad__btn dpad__btn--lt"
              @pointerdown="onPointerDown($event, 'left')"
              @pointerup="onPointerEnd" @pointercancel="onPointerEnd">
              <svg viewBox="0 0 14 14"><path d="M1 7L11 1V13Z" fill="currentColor" /></svg>
              <small>左转</small>
            </button>

            <div class="dpad__core"><span /></div>

            <button class="dpad__btn dpad__btn--rt"
              @pointerdown="onPointerDown($event, 'right')"
              @pointerup="onPointerEnd" @pointercancel="onPointerEnd">
              <svg viewBox="0 0 14 14"><path d="M13 7L3 1V13Z" fill="currentColor" /></svg>
              <small>右转</small>
            </button>

            <button class="dpad__btn dpad__btn--dn"
              @pointerdown="onPointerDown($event, 'backward')"
              @pointerup="onPointerEnd" @pointercancel="onPointerEnd">
              <svg viewBox="0 0 14 14"><path d="M7 13L1 3H13Z" fill="currentColor" /></svg>
              <small>后退</small>
            </button>
          </div>

        </div>

        <!-- Parameters -->
        <div class="card">
          <div class="card__head"><h3>参数设置</h3></div>

          <div class="param" v-for="p in paramList" :key="p.key">
            <div class="param__head">
              <span>{{ p.label }}</span>
              <b class="param__val">{{ formatVal(p) }}</b>
            </div>
            <el-slider
              v-model="p.model"
              :min="p.min" :max="p.max" :step="p.step"
              :show-tooltip="false"
            />
          </div>
        </div>
        <div class="card">
            <el-switch
                v-model="isDragging"
                size="large"
                inline-prompt
                active-text="开启地图选点"
                inactive-text="关闭地图选点"
            />
            <div v-if="isDragging">
                <el-row  :gutter="20">
                    <el-col :span="6">X:</el-col>
                    <el-col :span="18"><el-input /></el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">Y:</el-col>
                    <el-col :span="18"><el-input /></el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">Angle:</el-col>
                    <el-col :span="18"><el-input /></el-col>
                </el-row>
                <el-button type="danger" round size="large" class="estop" plain>
                    ⬣ 紧急停止
                </el-button>
            </div>
        </div>
      </aside>
    </div>

    <footer class="status-bar">
      <div class="chip" v-for="s in statusItems" :key="s.label">
        <span class="chip__label">{{ s.label }}</span>
        <span class="chip__val" :class="{ 'chip__val--ok': s.ok }">{{ s.value }}</span>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ZoomIn, ZoomOut, Location } from '@element-plus/icons-vue'
import { useRobotStore } from '@/stores/robot'
import { moveRobot, stopRobot } from '@/api/agv.js'
import MapCanvas from './MapCanvas.vue'

// const props = defineProps({
//     mapName: {
//         type: String,
//         default: ''
//     }
// })

// const VITE_AGV_DEVICE_ID = import.meta.env.VITE_AGV_DEVICE_ID

const robotStore = useRobotStore()

const maxSpeed = ref(0.6)
const rotationAngle = ref(0)

const paramList = reactive([
  { key: 'speed', label: '速度', model: maxSpeed, min: 0, max: 1, step: 0.1, unit: 'm/s', digits: 1 },
  { key: 'rot', label: '旋转角度', model: rotationAngle, min: -1, max: 1, step: 0.1, unit: 'm/s', digits: 0 },
])

const statusItems = [
  { label: '位置', value: `${robotStore.position.x},${robotStore.position.y}` },
  { label: '航向', value: robotStore.position.angle },
  { label: '电量', value: `${robotStore.battery * 100} %`, ok: true },
]

function formatVal(p) {
  const v = typeof p.model === 'object' ? p.model.value : p.model
  return (typeof v === 'number' ? v.toFixed(p.digits) : v) + ' ' + p.unit
}

const isDragging = ref(false)
const moveRobotData = ref({
    vx: 0,
    vy: 0,
    vz: 0
})

/* long-press stubs */
const onPress = async (_dir) => {
    if (_dir === 'forward') {
        moveRobotData.value.vx = maxSpeed.value
    } else if (_dir === 'backward') {
        moveRobotData.value.vx = -maxSpeed.value
    } else if (_dir === 'left') {
        moveRobotData.value.vy = maxSpeed.value
    } else {
        moveRobotData.value.vy = -maxSpeed.value
    }
    moveRobotData.value.vz = rotationAngle.value
    const res = await moveRobot({
        ip: robotStore.ip,
        deviceId: robotStore.agvDeviceId,
        ...moveRobotData.value 
    })
}

function onRelease() { 
    moveRobotData.value.vx = 0;
    moveRobotData.value.vy = 0;
    stopRobot({
        ip: robotStore.ip,
        // deviceId: VITE_AGV_DEVICE_ID
        deviceId: robotStore.agvDeviceId,
    })
}

const activePointerIds = new Set()

const onPointerDown = (event, direction) => {
    if (event.pointerType === 'mouse' && event.button !== 0) return

    event.preventDefault()
    activePointerIds.add(event.pointerId)
    event.currentTarget?.setPointerCapture?.(event.pointerId)
    onPress(direction)
}

const onPointerEnd = (event) => {
    event.preventDefault()
    if (!activePointerIds.has(event.pointerId)) return

    activePointerIds.delete(event.pointerId)
    if (event.currentTarget?.hasPointerCapture?.(event.pointerId)) {
        event.currentTarget.releasePointerCapture(event.pointerId)
    }
    onRelease()
}

const releaseActivePointers = () => {
    if (!activePointerIds.size) return
    activePointerIds.clear()
    onRelease()
}

onMounted(() => {
    window.addEventListener('blur', releaseActivePointers)
})

onBeforeUnmount(() => {
    window.removeEventListener('blur', releaseActivePointers)
    releaseActivePointers()
})

</script>

<style lang="scss" scoped>
.chassis-control {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: $color-background-base;
    color: $color-text-primary;
    font-family: $font-family-body;
    overflow: hidden;
    user-select: none;

    .main-wrap {
        flex: 1;
        display: flex;
        min-height: 0;
        gap: 0;

        .map-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-width: 0;
            border-right: 1px solid $color-accent-border;

            .area-bar {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                padding: 0 16px;
                background: $color-background-panel;
                border-bottom: 1px solid $color-accent-border;
                flex-shrink: 0;

                &__title {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    font-family: $font-family-heading;
                    font-size: 13px;
                    font-weight: 700;
                    letter-spacing: 1.5px;
                    color: $color-text-secondary;
                    text-transform: uppercase;
                }

                &__icon {
                    width: 16px;
                    height: 16px;
                }

                &__actions {
                    display: flex;
                    gap: 4px;
                }

                .map-controller {
                    display: flex;
                    align-items: center;
                    gap: 12px;

                    .btn-container {
                        width: 32px;
                        height: 32px;
                        border-radius: 8px;
                        background: $color-accent-soft;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 1px solid transparent;

                        &:hover {
                            border-color: $color-accent-primary;
                            cursor: pointer;
                        }
                    }
                }

                :deep(.el-button) {
                    font-size: 12px;
                    color: $color-text-secondary;
                    border-color: $color-accent-border;
                    background: transparent;

                    &:hover {
                        color: $color-accent-primary;
                        border-color: $color-accent-border-strong;
                    }
                }
            }

            .map-body {
                flex: 1;
                position: relative;
                overflow: hidden;
                background: $color-background-base;

                // canvas {
                //     position: absolute;
                //     inset: 0;
                // }
            }
        }

        .panel {
            width: 360px;
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
            gap: 0;
            overflow-y: auto;
            background: $color-background-panel;

            .card {
                padding: 18px 20px;
                border-bottom: 1px solid $color-accent-border;

                &__head {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 16px;

                    h3 {
                        font-family: $font-family-heading;
                        font-size: 14px;
                        font-weight: 700;
                        letter-spacing: 1.2px;
                        color: $color-text-secondary;
                        margin: 0;
                        text-transform: uppercase;
                    }
                }

                :deep(.el-tag) {
                    font-size: 10px;
                    height: 20px;
                    background: $color-accent-tag-background;
                    border-color: $color-accent-border;
                    color: $color-accent-primary;
                }

                .dpad {
                    display: grid;
                    grid-template-columns: repeat(3, 76px);
                    grid-template-rows: repeat(3, 64px);
                    gap: 6px;
                    justify-content: center;
                    margin-bottom: 18px;

                    &__btn {
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        gap: 4px;
                        border: 1px solid $color-accent-border;
                        border-radius: 8px;
                        background: $color-background-card;
                        color: $color-text-primary;
                        cursor: pointer;
                        transition: all .15s ease;
                        touch-action: none;
                        -webkit-user-select: none;

                        svg {
                            width: 14px;
                            height: 14px;
                        }

                        small {
                            font-size: 10px;
                            letter-spacing: .5px;
                            color: $color-text-secondary;
                        }

                        &:hover {
                            border-color: $color-accent-border-strong;
                            background: $color-background-card-hover;
                            color: $color-accent-primary;
                        }

                        &:active {
                            background: $color-accent-primary;
                            color: $color-background-base;
                            border-color: $color-accent-primary;
                            box-shadow: 0 0 24px $color-accent-glow;
                            transform: scale(.94);
                        
                            small {
                                color: $color-background-base;
                            }
                        }

                        &--up {
                            grid-column: 2;
                            grid-row: 1;
                        }

                        &--lt {
                            grid-column: 1;
                            grid-row: 2;
                        }

                        &--rt {
                            grid-column: 3;
                            grid-row: 2;
                        }

                        &--dn {
                            grid-column: 2;
                            grid-row: 3;
                        }
                    }

                    &__core {
                        grid-column: 2;
                        grid-row: 2;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 1px solid $color-accent-border;
                        border-radius: 8px;
                        background: $color-accent-core-background;

                        span {
                            width: 10px;
                            height: 10px;
                            border-radius: 50%;
                            background: $color-accent-primary;
                            opacity: .3;
                        }
                    }
                }

                .estop {
                    width: 100%;
                    height: 42px !important;
                    font-size: 14px;
                    font-weight: 600;
                    letter-spacing: 1px;
                    border-color: $color-danger !important;
                    color: $color-danger !important;
                    background: $color-danger-background !important;

                    &:hover {
                        background: $color-danger-background-hover !important;
                    }
                }

                .param {
                    margin-bottom: 18px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    &__head {
                        display: flex;
                        justify-content: space-between;
                        align-items: baseline;
                        margin-bottom: 8px;
                        font-size: 13px;
                        color: $color-text-secondary;
                    }

                    &__val {
                        font-family: $font-family-monospace;
                        font-size: 13px;
                        font-weight: 500;
                        color: $color-accent-primary;
                    }

                    :deep(.el-slider) {
                        .el-slider__runway {
                            height: 4px;
                            background: $color-white-muted;
                            border-radius: 2px;
                        }
                        .el-slider__bar {
                            height: 4px;
                            background: $color-accent-primary;
                            border-radius: 2px;
                        }
                        .el-slider__button-wrapper {
                            top: -16px;
                        }
                        .el-slider__button {
                            width: 14px;
                            height: 14px;
                            border: 2px solid $color-accent-primary;
                            background: $color-background-base;
                            box-shadow: 0 0 8px $color-accent-glow;
                            transition: box-shadow .2s;

                            &:hover {
                                box-shadow: 0 0 14px $color-accent-slider-glow;
                            }
                        }
                    }
                }
            }
        }
    }

    .status-bar {
        display: flex;
        align-items: center;
        gap: 16px;
        height: 38px;
        padding: 0 24px;
        background: $color-background-card;
        border-top: 1px solid $color-accent-border;
        flex-shrink: 0;

        .chip {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 3px 12px;
            border-radius: 4px;
            background: $color-white-subtle;
            border: 1px solid $color-accent-border;

            &__label {
                font-size: 10px;
                color: $color-text-secondary;
                letter-spacing: .5px;
            }

            &__val  {
                font-family: $font-family-monospace;
                font-size: 11px;
                color: $color-text-bright;
                font-weight: 500;

                &--ok {
                    color: $color-success;
                }
            }
        }
    }
}

.map-action-icon {
    color: $color-canvas-robot;
}

</style>
