<template>
  <div class="webpage-link-edit-dialog">
    <div class="title">{{ lang.ssEditWebLink }}</div>
    
    <Input 
      class="input"
      ref="inputRef"
      v-model:value="url" 
      :placeholder="lang.ssWebUrlPh"
      @enter="save()"
    />

    <div class="btns">
      <Button @click="emit('close')" style="margin-right: 10px;">{{ lang.ssCancel }}</Button>
      <Button type="primary" @click="save()">{{ lang.ssConfirm }}</Button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue'
import { useSlidesStore } from '@/store'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import message from '@/utils/message'
import { lang } from '@/main'

import Input from '@/components/Input.vue'
import Button from '@/components/Button.vue'

const emit = defineEmits<{
  (event: 'close'): void
}>()

const props = defineProps<{
  elementId: string
  currentUrl: string
}>()

const slidesStore = useSlidesStore()
const { addHistorySnapshot } = useHistorySnapshot()

const url = ref(props.currentUrl)
const inputRef = ref<InstanceType<typeof Input>>()

onMounted(() => {
  nextTick(() => {
    inputRef.value?.focus()
  })
})

const save = () => {
  if (!url.value) {
    message.error(lang.ssWebUrlReq)
    return
  }

  // 验证URL格式
  try {
    new URL(url.value)
  }
  catch {
    message.error(lang.ssWebUrlInvalid)
    return
  }

  // 更新元素链接
  slidesStore.updateElement({ 
    id: props.elementId, 
    props: { url: url.value } 
  })

  // 添加历史记录
  addHistorySnapshot()

  emit('close')
}
</script>

<style lang="scss" scoped>
.webpage-link-edit-dialog {
  font-size: 13px;
  line-height: 1.675;
}

.title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.input {
  width: 100%;
  height: 32px;
}

.btns {
  margin-top: 20px;
  text-align: right;
}
</style> 