<script setup lang="ts">
// 입장 전 프리조인 — 실제 로컬 카메라/마이크를 미리보기하고 초기 on/off 상태를 정한 뒤 입장한다.
// 권한이 거부되면 미리보기 없이 '권한 거부 상태로 입장(참관)'을 안내한다.
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import MeetingIcon from './MeetingIcon.vue'
import UserAvatar from '@/components/UserAvatar.vue'

interface PrejoinRoom {
  name: string
  hostName: string | null
  restricted: boolean
  isHost: boolean
}
interface Props {
  room: PrejoinRoom
  myName: string
  myAvatarUrl: string | null
}
defineProps<Props>()
const emit = defineEmits<{
  (e: 'enter', opts: { mic: boolean; cam: boolean }): void
  (e: 'cancel'): void
}>()

const videoEl = ref<HTMLVideoElement | null>(null)
const micOn = ref(true)
const camOn = ref(true)
const denied = ref(false) // 미디어 권한 획득 실패 여부
let stream: MediaStream | null = null

// 트랙 enabled 동기화
function applyTrackState() {
  if (!stream) return
  stream.getAudioTracks().forEach((t) => (t.enabled = micOn.value))
  stream.getVideoTracks().forEach((t) => (t.enabled = camOn.value))
}
watch([micOn, camOn], applyTrackState)

onMounted(async () => {
  try {
    stream = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true,
    })
    if (videoEl.value) videoEl.value.srcObject = stream
    applyTrackState()
  } catch {
    // 권한 거부/장치 없음 — 미리보기 불가, 토글은 off 로
    denied.value = true
    micOn.value = false
    camOn.value = false
  }
})

onBeforeUnmount(stopPreview)

// 미리보기 트랙 정리(입장 시 LiveKit 이 다시 장치를 획득하므로 여기서 해제)
function stopPreview() {
  if (stream) {
    stream.getTracks().forEach((t) => t.stop())
    stream = null
  }
  if (videoEl.value) videoEl.value.srcObject = null
}

function enter() {
  stopPreview()
  emit('enter', { mic: micOn.value, cam: camOn.value })
}
</script>

<template>
  <div class="prejoin">
    <div class="pj-card">
      <div class="pj-preview">
        <video
          ref="videoEl"
          class="pj-video"
          :class="{ hidden: !camOn }"
          autoplay
          playsinline
          muted
        />
        <div
          v-if="!camOn"
          class="pj-off"
        >
          <span class="av-lg"><UserAvatar
            :url="myAvatarUrl"
            :name="myName"
          /></span>
        </div>
        <div class="pj-selflbl">
          {{ myName }} (나)
        </div>
        <div class="pj-prectrl">
          <button
            type="button"
            class="pj-rb"
            :class="{ off: !micOn }"
            :disabled="denied"
            title="마이크"
            @click="micOn = !micOn"
          >
            <MeetingIcon :name="micOn ? 'mic' : 'micOff'" />
          </button>
          <button
            type="button"
            class="pj-rb"
            :class="{ off: !camOn }"
            :disabled="denied"
            title="카메라"
            @click="camOn = !camOn"
          >
            <MeetingIcon :name="camOn ? 'cam' : 'camOff'" />
          </button>
        </div>
      </div>

      <div class="pj-side">
        <div class="pj-room">
          <span class="pj-kicker">입장하려는 방</span>
          <div class="pj-roomname">
            {{ room.name }}
            <span
              v-if="room.restricted"
              class="rr-badge lock"
            ><MeetingIcon name="lock" />제한</span>
          </div>
          <div
            v-if="room.hostName"
            class="pj-roomhost"
          >
            <MeetingIcon name="host" /><span>{{ room.hostName }}</span>
          </div>
        </div>
        <div class="pj-checklist">
          <div
            class="pj-chk"
            :class="{ ok: micOn }"
          >
            <MeetingIcon :name="micOn ? 'mic' : 'micOff'" /><span>마이크 {{ micOn ? '켜짐' : '꺼짐' }}</span>
          </div>
          <div
            class="pj-chk"
            :class="{ ok: camOn }"
          >
            <MeetingIcon :name="camOn ? 'cam' : 'camOff'" /><span>카메라 {{ camOn ? '켜짐' : '꺼짐' }}</span>
          </div>
        </div>
        <button
          type="button"
          class="btn primary pj-enter"
          @click="enter"
        >
          지금 입장
        </button>
        <button
          type="button"
          class="pj-cancel"
          @click="emit('cancel')"
        >
          ← 로비로 돌아가기
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.prejoin {
  height: 100%;
  display: grid;
  place-items: center;
  padding: 1.875rem;
}
.pj-card {
  display: flex;
  gap: 1.375rem;
  width: min(56.25rem, 100%);
  background: var(--d-panel);
  border: 1px solid var(--d-border);
  border-radius: 1.125rem;
  padding: 1.375rem;
  box-shadow: 0 30px 80px rgba(0, 0, 0, 0.45);
}
.pj-preview {
  position: relative;
  flex: 1;
  aspect-ratio: 16/9;
  border-radius: 0.8125rem;
  overflow: hidden;
  background: var(--tile);
}
.pj-video {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transform: scaleX(-1);
}
.pj-video.hidden {
  display: none;
}
.pj-off {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
  background: var(--tile);
}
.av-lg {
  width: clamp(3.5rem, 12vh, 6rem);
  height: clamp(3.5rem, 12vh, 6rem);
  flex-shrink: 0;
}
.pj-selflbl {
  position: absolute;
  left: 0.875rem;
  bottom: 0.875rem;
  z-index: 3;
  font-size: 0.8125rem;
  font-weight: 600;
  color: #fff;
  background: rgba(0, 0, 0, 0.42);
  padding: 0.3125rem 0.6875rem;
  border-radius: 0.4375rem;
  -webkit-backdrop-filter: blur(6px);
  backdrop-filter: blur(6px);
}
.pj-prectrl {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0.875rem;
  z-index: 3;
  display: flex;
  justify-content: center;
  gap: 0.75rem;
}
.pj-rb {
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  border: none;
  background: rgba(255, 255, 255, 0.16);
  color: #fff;
  display: grid;
  place-items: center;
  cursor: pointer;
  -webkit-backdrop-filter: blur(8px);
  backdrop-filter: blur(8px);
}
.pj-rb svg {
  width: 1.3125rem;
  height: 1.3125rem;
}
.pj-rb:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.28);
}
.pj-rb.off {
  background: var(--red);
}
.pj-rb:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.pj-side {
  width: 17.875rem;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 0.875rem;
}
.pj-room {
  padding-bottom: 0.875rem;
  border-bottom: 1px solid var(--d-border);
}
.pj-kicker {
  font-size: 0.6875rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  color: var(--d-text-3);
}
.pj-roomname {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-top: 0.375rem;
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--d-text);
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.rr-badge.lock {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.6875rem;
  font-weight: 600;
  padding: 0.125rem 0.5rem;
  border-radius: 1.25rem;
  line-height: 1.5;
  color: var(--d-text-2);
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid var(--d-border);
}
.rr-badge.lock svg {
  width: 0.6875rem;
  height: 0.6875rem;
}
.pj-roomhost {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  margin-top: 0.5rem;
  font-size: 0.8125rem;
  color: var(--d-text-2);
}
.pj-roomhost span {
  line-height: 1;
}
.pj-roomhost svg {
  width: 0.875rem;
  height: 0.875rem;
  flex-shrink: 0;
}
.pj-checklist {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.pj-chk {
  display: flex;
  align-items: center;
  gap: 0.5625rem;
  font-size: 0.8125rem;
  color: var(--d-text-3);
}
.pj-chk svg {
  width: 1rem;
  height: 1rem;
}
.pj-chk.ok {
  color: var(--d-text);
}
.pj-enter {
  height: 2.875rem;
  border-radius: 0.625rem;
  justify-content: center;
  font-size: 0.9375rem;
  margin-top: auto;
}
.pj-cancel {
  border: none;
  background: transparent;
  color: var(--d-text-2);
  font-family: inherit;
  font-size: 0.8125rem;
  cursor: pointer;
  padding: 0.25rem;
}
.pj-cancel:hover {
  color: var(--d-text);
}

/* 공용 .btn primary 가 라이트 테마 기준이므로 입장 버튼 색을 명시 */
.pj-enter.btn.primary {
  background: var(--accent);
  border: none;
  color: #fff;
}
.pj-enter.btn.primary:hover {
  background: var(--accent-hover);
}

@media (max-width: 53.75rem) {
  .pj-card {
    flex-direction: column;
  }
  .pj-side {
    width: 100%;
  }
}
</style>
