<template>
  <div class="homepage-wrapper">
    <nav class="auth-nav">
      <div class="nav-left">
        <span class="status-dot" :class="{ 'secure-mode': isLoggedIn }"></span>
        <span class="brand">SPECIALSOURCE.SYSTEM</span>
      </div>

      <div class="nav-menu">
        <button
            v-for="item in menuItems"
            :key="item.id"
            @click="changeMenu(item.id)"
            :class="['menu-btn', { active: activeMenu === item.id }]"
        >
          {{ item.name }}
        </button>
      </div>

      <div class="nav-right">
        <div v-if="!isLoggedIn" class="auth-group">
          <button @click="changeMenu('login')" :class="['nav-item', { 'active-auth': activeMenu === 'login' }]">LOGIN</button>
          <button @click="handleRegister" class="nav-item btn-reg">SIGN UP</button>
        </div>
        <div v-else class="auth-group">
          <span class="user-info">ACCESS GRANTED: ADMIN</span>
          <button @click="handleLogout" class="nav-item btn-logout">LOGOUT</button>
        </div>
      </div>
    </nav>

    <main class="content-area">
      <transition name="fade" mode="out-in">

        <div v-if="activeMenu === 'main'" id="videos-container" key="main">
          <div
              v-for="(video, index) in videos"
              :key="video.id.videoId"
              class="video-card"
              :class="{ 'new-item': index === 0 }"
              @click="openVideo(video.id.videoId)"
          >
            <iframe
                :src="`https://www.youtube-nocookie.com/embed/${video.id.videoId}`"
                frameborder="0"
                allowfullscreen
            ></iframe>
            <h5 class="video-title">{{ video.snippet.title }}</h5>
          </div>
        </div>

        <div v-else-if="activeMenu === 'login'" class="sub-page login-page" key="login">
          <div class="login-terminal-frame">
            <h2 class="login-gate-title">> SECURE_AUTHENTICATION_GATEWAY.EXE</h2>
            <p class="login-gate-desc">WARNING: UNAUTHORIZED ACCESS IS STRICTLY PROHIBITED BY COMPLIANCE LAW.</p>

            <div class="login-form-form">
              <div class="login-input-group">
                <label class="login-label">ACCESS ID_</label>
                <input
                    v-model="loginId"
                    type="text"
                    class="login-input"
                    placeholder="ENTER ACCESS ID"
                    @keyup.enter="handleLoginSubmit"
                >
              </div>
              <div class="login-input-group">
                <label class="login-label">ACCESS KEY_</label>
                <input
                    v-model="loginPw"
                    type="password"
                    class="login-input"
                    placeholder="ENTER ENCRYPTION KEY"
                    @keyup.enter="handleLoginSubmit"
                />
              </div>
              <button @click="handleLoginSubmit" class="login-submit-btn">
                [ INITIALIZE DECRYPT & ACCESS ]
              </button>
            </div>
          </div>
        </div>

        <div v-else-if="activeMenu === 'project'" class="sub-page project-page" key="project">
          <h2 class="page-title">> EXECUTING PROJECTS_LOG.EXE</h2>
          <div class="project-grid">
            <div class="project-item" v-for="i in 3" :key="i">
              <div class="item-header">PROJ_00{{i}}</div>
              <p>스페셜소스 자동 배포 시스템 고도화 프로젝트 진행 중...</p>
              <div class="status">STATUS: COMPLETED</div>
            </div>
          </div>
        </div>

        <div v-else-if="activeMenu === 'about'" class="sub-page about-page" key="about">
          <h2 class="page-title">> ACCESSING CORE_IDENTITY.DAT</h2>
          <p class="about-text">
            스페셜소스는 2021년 설립된 기술 중심의 컴퍼니입니다.<br>
            우리는 인프라 자동화와 효율적인 배포 파이프라인을 구축하여<br>
            개발자가 비즈니스 로직에만 집중할 수 있는 환경을 만듭니다.
          </p>
        </div>

        <div v-else-if="activeMenu === 'contact'" class="sub-page contact-page" key="contact">
          <h2 class="page-title">> INITIALIZING ENCRYPTED_COMM.INK</h2>
          <div class="contact-form">
            <p>EMAIL: specialsource.company@gmail.com</p>
            <p>LOCATION: SEOUL, SOUTH KOREA</p>
          </div>
        </div>
      </transition>
    </main>

    <div class="crt-monitor-frame">
      <div class="monitor-header">
        <span class="monitor-title">📟 SECURE TERMINAL CONSOLE V3.2 [ROOT/{{ activeMenu.toUpperCase() }}]</span>
        <span class="monitor-status">ACTIVE</span>
      </div>
      <div class="crt-screen-overlay">
        <div ref="terminalRef" class="terminal-box"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

const videos = ref([]);
const terminalRef = ref(null);
const termInstance = ref(null);

// 로그인 폼 양방향 바인딩 변수
const loginId = ref('admin');
const loginPw = ref('1234');

// 메뉴 및 인증 토큰 반응형 변수화
const activeMenu = ref('main');
const authToken = ref(localStorage.getItem('token'));

const menuItems = [
  { id: 'main', name: 'HOME' },
  { id: 'project', name: 'PROJECT' },
  { id: 'about', name: 'ABOUT' },
  { id: 'contact', name: 'CONTACT' }
];

// 실시간 로그인 여부 체크
const isLoggedIn = computed(() => !!authToken.value);

const changeMenu = (id) => {
  activeMenu.value = id;
  if (termInstance.value) {
    termInstance.value.echo(`\n[[b;green;]>] NAVIGATING TO /${id.toUpperCase()}... SUCCESS.`);
  }
};

// 📺 유튜브 API 세팅 (8개 출력)
const apiKey = 'AIzaSyD51LHwqoY8spjq6rsY_RlhBXzb96j7D6o';
const channelId = 'UC8L92ju0V88s6TcmLPb8Bkg';
const maxResults = 8;
const apiUrl = `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${channelId}&maxResults=${maxResults}&order=date&type=video&key=${apiKey}`;

const fetchVideos = async () => {
  try {
    const res = await axios.get(apiUrl);
    videos.value = res.data.items || [];
  } catch (err) { console.error("유튜브 로드 실패:", err); }
};

const openVideo = (id) => window.open(`https://www.youtube.com/watch?v=${id}`);
const handleRegister = () => alert("회원가입은 현재 관리자 승인제로 운영됩니다.");

// 로그아웃 로직 (새로고침 없이 실시간 상태 갱신)
const handleLogout = () => {
  localStorage.removeItem('token');
  authToken.value = null;
  activeMenu.value = 'main';
  if (termInstance.value) {
    termInstance.value.echo(`\n[[b;red;][ALERT]] SESSION TERMINATED. USER LOGGED OUT.`);
  }
};

// 🔥 [핵심 기능] 보안 로그인 처리 및 터미널 동시 출력 로직
const handleLoginSubmit = async () => {
  if (!loginId.value || !loginPw.value) {
    alert("아이디와 비밀번호를 모두 입력해 주세요.");
    return;
  }

  if (termInstance.value) {
    termInstance.value.echo(`\n[SYS] INITIALIZING SECURITY GATEWAY CONNECTION...`);
    termInstance.value.echo(`[SYS] TRANSMITTING CREDENTIALS [USER: ${loginId.value}]`);
    termInstance.value.echo(`[SYS] VALIDATING AGAINST CENTRAL POSTGRES_DB CORE...`);
  }

  try {
    const apiBaseUrl = import.meta.env.VITE_API_URL || '';

    const response = await axios.post(`${apiBaseUrl}/api/login`, {
      username: loginId.value,
      password: loginPw.value
    },
    {
      withCredentials: true
    }
    );

    if (response.data && response.data.token) {
      localStorage.setItem('token', response.data.token);
      authToken.value = response.data.token;

      if (termInstance.value) {
        termInstance.value.echo(`[[b;green;][SUCCESS]] ACCESS GRANTED. CREDENTIALS VERIFIED.`);
      }

      loginId.value = '';
      loginPw.value = '';
      activeMenu.value = 'main';
    }
  } catch (error) {
    console.error("로그인 실패:", error);
    if (termInstance.value) {
      termInstance.value.echo(`[[b;red;][CRITICAL ERROR]] ACCESS DENIED! INVALID ACCESS KEY.`);
      termInstance.value.echo(`[[b;red;][WARN]] IP LOGGED. UNAUTHORIZED ATTEMPT REGISTERED.`);
    }
    alert("인증에 실패했습니다. 액세스 키를 확인하세요.");
  }
};

onMounted(() => {
  fetchVideos();

  const globaljQuery = window.$;
  if (globaljQuery && terminalRef.value) {
    termInstance.value = globaljQuery(terminalRef.value).terminal({
      'hello': function () { this.echo('Hello, Welcome to Specialsource.company'); },
      'help': function () {
        this.echo(`- hello          : Say hello\n- specialsource  : Core info\n- email          : Contact\n- clear          : Clear console`);
      },
      'specialsource': function () { this.echo('SPECIALSOURCE Established 2021.01.'); },
      'email': function () { this.echo('specialsource.company@gmail.com'); },
    }, {
      greetings: `[SYSTEM V3.2] INTERFACE ONLINE. TYPE 'help' FOR COMMANDS.`,
      prompt: 'admin@specialsource:~$ '
    });
  }
});
</script>

<style scoped>
.homepage-wrapper {
  background-color: #050505;
  color: #00ff00;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* --- GNB --- */
.auth-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 40px;
  background: #000;
  border-bottom: 1px solid rgba(0, 255, 0, 0.2);
}
.nav-menu { display: flex; gap: 20px; }
.menu-btn {
  background: none; border: none; color: #008800;
  font-family: monospace; font-size: 16px; cursor: pointer;
  transition: 0.3s;
}
.menu-btn:hover, .menu-btn.active { color: #00ff00; text-shadow: 0 0 10px #00ff00; }

.auth-group { display: flex; align-items: center; }

/* 로그인/회원가입 버튼 테마 깔맞춤 고정 */
.nav-item {
  color: #00ff00 !important;
  text-decoration: none;
  background: none;
  border: 1px solid #00ff00 !important;
  padding: 6px 18px;
  margin-left: 10px;
  cursor: pointer;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
  box-shadow: 0 0 5px rgba(0, 255, 0, 0.3);
  transition: 0.3s;
}
.nav-item:hover, .nav-item.active-auth {
  background: rgba(0, 255, 0, 0.2) !important;
  color: #00ff00 !important;
  box-shadow: 0 0 10px #00ff00;
}
.user-info { color: #008800 !important; font-size: 12px; margin-right: 15px; font-family: monospace; letter-spacing: 1px;}
.status-dot { width: 8px; height: 8px; background: #ff3b3b; border-radius: 50%; box-shadow: 0 0 8px #ff3b3b; transition: 0.5s; }
.status-dot.secure-mode { background: #00ff00; box-shadow: 0 0 8px #00ff00; }

/* --- 컨텐츠 영역 --- */
.content-area {
  flex: 1; padding: 20px; min-height: 400px;
  overflow-y: auto;
}
.sub-page { max-width: 1000px; margin: 0 auto; padding-top: 15px; }
.page-title { font-family: monospace; border-bottom: 1px solid #113311; padding-bottom: 10px; margin-bottom: 20px; color: #00ff00;}

/* 📺 유튜브 그리드 레이아웃 (4열 8개 무화) */
#videos-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 10px 20px;
  max-width: 1300px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}
.video-card {
  width: 100%;
  background: #000;
  padding: 10px;
  border: 1px solid #113311;
  position: relative;
  cursor: pointer;
  transition: 0.3s;
}
.video-card:hover { border-color: #00ff00; box-shadow: 0 0 10px rgba(0, 255, 0, 0.3); }
.video-title { color: #00aa00; margin-top: 10px; font-size: 14px; height: 40px; overflow: hidden; font-family: sans-serif; }
iframe { width: 100%; height: 180px; border-radius: 4px; }

.new-item::before {
  content: 'NEW'; position: absolute; top: -5px; left: -5px;
  background: #00ff00; color: #000; font-size: 10px; font-weight: bold;
  padding: 2px 5px; box-shadow: 0 0 5px #00ff00; z-index: 10;
}

/* 🔐 [신규 추가] 컨텐츠 내장형 해커 로그인 박스 디자인 스타일 양식 */
.login-terminal-frame {
  max-width: 550px; margin: 40px auto;
  border: 1px dashed #00ff00; padding: 35px;
  background: #020a02; box-shadow: 0 0 15px rgba(0, 255, 0, 0.1);
  font-family: 'Courier New', Courier, monospace;
}
.login-gate-title { color: #00ff00; font-size: 20px; margin-bottom: 10px; font-weight: bold;}
.login-gate-desc { color: #008800; font-size: 12px; margin-bottom: 30px; line-height: 1.4; }
.login-form-form { display: flex; flex-direction: column; gap: 20px; }
.login-input-group { display: flex; align-items: center; border-bottom: 1px solid #005500; padding-bottom: 5px; }
.login-label { width: 120px; color: #00ff00; font-weight: bold; font-size: 14px; }
.login-input {
  flex: 1; background: none; border: none; color: #00ff00;
  font-family: 'Courier New', Courier, monospace; font-size: 15px; outline: none;
}
.login-input::placeholder { color: #004400; }
.login-submit-btn {
  margin-top: 15px; background: none; border: 1px solid #00ff00;
  color: #00ff00; padding: 12px; font-family: 'Courier New', Courier, monospace;
  font-size: 14px; font-weight: bold; cursor: pointer; transition: 0.3s;
}
.login-submit-btn:hover { background: #00ff00; color: #000; box-shadow: 0 0 15px #00ff00; }

/* 프로젝트 리스트 */
.project-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
.project-item { border: 1px solid #113311; padding: 15px; background: #080808; font-family: monospace;}
.item-header { font-weight: bold; margin-bottom: 10px; color: #00ff00; }
.about-text { font-family: monospace; line-height: 2; color: #00cc00;}
.contact-form { font-family: monospace; line-height: 2; color: #00cc00;}

/* 애니메이션 트랜지션 */
.fade-enter-active, .fade-leave-active { transition: opacity 0.25s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; }

/* --- 하단 CRT 터미널 영역 --- */
.crt-monitor-frame {
  height: 300px; margin: 10px 40px 30px;
  border: 2px solid #1a1a1a; background: #0a0a0a; overflow: hidden;
}
.monitor-header { background: #151515; padding: 5px 15px; color: #555; display: flex; justify-content: space-between; font-family: monospace; font-size: 12px;}
.monitor-status { color: #00aa00; animation: blink 2s infinite; }
.crt-screen-overlay { position: relative; height: calc(100% - 30px); background: #020802; }
.crt-screen-overlay::before {
  content: " "; display: block; position: absolute; top: 0; left: 0; bottom: 0; right: 0;
  background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%), linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
  z-index: 2; background-size: 100% 4px, 6px 100%; pointer-events: none;
}
.terminal-box { width: 100%; height: 100%; padding: 10px; }

:deep(.terminal), :deep(.terminal span) {
  --color: #33ff33 !important; font-family: monospace !important;
  text-shadow: 0 0 5px rgba(51, 255, 51, 0.6) !important;
}

/* 📱 반응형 분기점 */
@media screen and (max-width: 1100px) {
  #videos-container { grid-template-columns: repeat(2, 1fr); }
  .project-grid { grid-template-columns: repeat(2, 1fr); }
}
@media screen and (max-width: 650px) {
  #videos-container { grid-template-columns: 1fr; }
  .project-grid { grid-template-columns: 1fr; }
  .auth-nav { flex-direction: column; gap: 12px; padding: 15px 20px; }
}
@keyframes blink { 0%, 100% { opacity: 0.4; } 50% { opacity: 1; } }
</style>