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

        <select v-model="activeTheme" class="theme-selector">
          <option value="green">P3_GREEN (녹색)</option>
          <option value="amber">HERCULES (호박)</option>
          <option value="vga">VGA_GRAY (회색)</option>
          <option value="ega">EGA_CYAN (청록)</option>
        </select>
      </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: {{ loggedInUser.toUpperCase() }}</span>
          <button @click="handleLogout" class="nav-item btn-logout">LOGOUT</button>
        </div>
      </div>
    </nav>

    <nav class="auth-nav" style="display: none;"></nav>

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

        <div v-if="activeMenu === 'main'" class="sub-page main-page" key="main">
          <div class="ascii-container">
            <pre class="ascii-art" v-html="formattedAscii"></pre>
          </div>
        </div>

        <div v-else-if="activeMenu === 'youtube'" id="videos-container" key="youtube">
          <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"
                    autocomplete="off" @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"
                    autocomplete="new-password" @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>

    <transition name="fade">
      <div v-if="isProcessing" class="tui-global-overlay">
        <TuiProgressBar :progress="overlayProgress" :status="overlayStatus" :username="loggedInUser" />
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import axios from 'axios';
import TuiProgressBar from '@/components/TuiProgressBar.vue';

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

const loginId = ref('');
const loginPw = ref('');

const activeMenu = ref('main');
const authToken = ref(localStorage.getItem('token'));
const activeTheme = ref(localStorage.getItem('theme') || 'green');

const isProcessing = ref(false);
const overlayProgress = ref(0);
const overlayStatus = ref('');

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

const loggedInUser = ref(localStorage.getItem('username') || 'anonymous');

// 🟢 [★복구] 유실되었던 로그인 상태 체크 computed 함수를 제자리에 원상 복구 완료
const isLoggedIn = computed(() => !!authToken.value);

const rawAscii = `
███████╗██████╗ ███████╗ ██████╗██╗ █████╗ ██╗
██╔════╝██╔══██╗██╔════╝██╔════╝██║██╔══██╗██║
███████╗██████╔╝█████╗  ██║     ██║███████║██║
╚════██║██╔═══╝ ██╔══╝  ██║     ██║██╔══██║██║
███████║██║     ███████╗╚██████╗██║██║  ██║███████╗
╚══════╝╚═╝     ╚══════╝ ╚═════╝╚═╝╚═╝  ╚═╝╚══════╝
███████╗ ██████╗ ██╗   ██╗██████╗  ██████╗███████╗
██╔════╝██╔═══██╗██║   ██║██╔══██╗██╔════╝██╔════╝
███████╗██║   ██║██║   ██║██████╔╝██║     █████╗
╚════██║██║   ██║██║   ██║██╔══██╗██║     ██╔══╝
███████║╚██████╔╝╚██████╔╝██║  ██║╚██████╗███████╗
╚══════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝ ╚═════╝╚══════╝
 ██████╗ ██████╗ ███╗   ███╗██████╗  █████╗ ███╗   ██╗██╗   ██╗
██╔════╝██╔═══██╗████╗ ████║██╔══██╗██╔══██╗████╗  ██║╚██╗ ██╔╝
██║     ██║   ██║██╔████╔██║██████╔╝███████║██╔██╗ ██║ ╚████╔╝
██║     ██║   ██║██║╚██╔╝██║██╔═══╝ ██╔══██║██║╚██╗██║  ╚██╔╝
╚██████╗╚██████╔╝██║ ╚═╝ ██║██║     ██║  ██║██║ ╚████║   ██║
 ╚═════╝ ╚═════╝ ╚═╝     ╚═╝╚═╝     ╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝`;

const formattedAscii = computed(() => {
  return rawAscii.replace(/ /g, '<span class="bg-block">█</span>');
});

const changeMenu = (id) => {
  if (activeMenu.value === id) return;

  isProcessing.value = true;
  overlayProgress.value = 0;
  overlayStatus.value = `INITIALIZING ROUTE ACCESS: /${id.toUpperCase()}...`;

  if (termInstance.value) {
    termInstance.value.echo(`\n[[b;var(--tui-color);]>] NAVIGATING TO /${id.toUpperCase()}... INITIALIZING PIPELINE.`);
  }

  const interval = setInterval(() => {
    overlayProgress.value += 5;

    if (overlayProgress.value === 25) {
      overlayStatus.value = `ALLOCATING MEMORY BUFFER FOR VUE_COMPONENT...`;
    }
    if (overlayProgress.value === 55) {
      overlayStatus.value = `DECRYPTING INTERFACE LOGS & SECURE ASSETS...`;
    }
    if (overlayProgress.value === 85) {
      activeMenu.value = id;
      overlayStatus.value = `MOUNTING VIRTUAL DOM TREE... SUCCESS.`;
    }

    if (overlayProgress.value >= 100) {
      clearInterval(interval);

      if (termInstance.value) {
        termInstance.value.echo(`[[b;var(--tui-color);][SUCCESS]] COMPONENT LOADED PERFECTLY.`);
      }

      setTimeout(() => {
        isProcessing.value = false;
      }, 120);
    }
  }, 20);
};

const triggerOverlayProcess = (durationMs, initialMsg) => {
  isProcessing.value = true;
  overlayProgress.value = 0;
  overlayStatus.value = initialMsg;

  const steps = 20;
  const stepTime = durationMs / steps;

  const interval = setInterval(() => {
    if (overlayProgress.value >= 100) {
      clearInterval(interval);
      setTimeout(() => {
        isProcessing.value = false;
      }, 150);
      return;
    }
    overlayProgress.value += (100 / steps);
  }, stepTime);
};

const apiKey = import.meta.env.VITE_YOUTUBE_API_KEY;
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 {
    // 💡 유튜브 규칙상 채널 ID의 앞 글자 'UC'를 'UU'로 바꾸면
    // 해당 채널의 '전체 업로드 영상 플레이리스트' ID가 됩니다. (비용 100유닛 -> 1유닛으로 단축)
    const uploadPlaylistId = channelId.replace(/^UC/, 'UU');
    const playlistApiUrl = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${uploadPlaylistId}&maxResults=${maxResults}&key=${apiKey}`;

    const res = await axios.get(playlistApiUrl);

    // 🌟 [매핑 매직] 유저님이 짜두신 기존 <template>의 video.id.videoId 및 video.snippet 구조와
    // 100% 호환되도록 데이터 골격을 가공하여 videos 배열에 주입합니다.
    if (res.data && res.data.items) {
      videos.value = res.data.items.map(item => ({
        id: { videoId: item.snippet.resourceId?.videoId },
        snippet: item.snippet
      }));
    } else {
      videos.value = [];
    }
  } catch (err) {
    console.error("유튜브 로드 실패:", err);
    // 에러 원인 추적용 가이드 로그
    if (err.response && err.response.status === 403) {
      console.warn("⚠️ [인프라 경고] 유튜브 API 할당량이 만료되었거나, 구글에 의해 API 키가 차단되었습니다.");
    }
  }
};

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

const handleLogout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('username');

  authToken.value = null;
  loggedInUser.value = 'anonymous';
  activeMenu.value = 'main';

  if (termInstance.value) {
    termInstance.value.echo(`\n[[b;red;][ALERT]] SESSION TERMINATED. USER LOGGED OUT.`);
    termInstance.value.set_prompt(`anonymous@specialsource:~$ `);
  }
};

const handleLoginSubmit = async () => {
  if (!loginId.value || !loginPw.value) {
    alert("아이디와 비밀번호를 모두 입력해 주세요.");
    return;
  }

  isProcessing.value = true;
  overlayProgress.value = 10;
  overlayStatus.value = 'Transmitting encryption keys to gateway...';

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

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

    overlayProgress.value = 40;
    overlayStatus.value = 'Validating query signature against PostgreSQL DB...';

    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);
      localStorage.setItem('username', loginId.value);

      authToken.value = response.data.token;
      loggedInUser.value = loginId.value;

      overlayProgress.value = 85;
      overlayStatus.value = 'Access Granted. Generating JWT Session token...';

      if (termInstance.value) {
        termInstance.value.echo(`[[b;var(--tui-color);][SUCCESS]] ACCESS GRANTED. CREDENTIALS VERIFIED.`);
        termInstance.value.set_prompt(`${loginId.value}@specialsource:~$ `);
      }

      overlayProgress.value = 100;
      overlayStatus.value = 'Session injection complete.';

      setTimeout(() => {
        isProcessing.value = false;
        loginId.value = '';
        loginPw.value = '';
        activeMenu.value = 'main';
      }, 400);
    }
  } catch (error) {
    console.error("로그인 실패:", error);
    isProcessing.value = false;

    if (termInstance.value) {
      termInstance.value.echo(`[[b;red;][CRITICAL ERROR]] ACCESS DENIED! INVALID ACCESS KEY.`);
    }
    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: `${loggedInUser.value}@specialsource:~$ `
    });
  }
});

watch(activeTheme, (newTheme) => {
  localStorage.setItem('theme', newTheme);
});
</script>

<style>
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;700&display=swap');

.homepage-wrapper,
.menu-btn,
.nav-item,
.terminal-box,
.tui-global-overlay,
.login-terminal-frame,
.project-item,
.about-text,
.contact-form,
.theme-selector,
:deep(.terminal),
:deep(.terminal span) {
  font-family: 'JetBrains Mono', monospace !important;
}

/* 🌟 레트로 마스터 테마 컬러 시스템 변수 */
.theme-green {
  --tui-color: #00ff00;
  --tui-dim: #008800;
  --tui-glow: rgba(0, 255, 0, 0.6);
  --tui-border: rgba(0, 255, 0, 0.2);
}
.theme-amber {
  --tui-color: #ffb000;
  --tui-dim: #aa6600;
  --tui-glow: rgba(255, 176, 0, 0.6);
  --tui-border: rgba(255, 176, 0, 0.2);
}
.theme-vga {
  --tui-color: #e2e8f0;
  --tui-dim: #718096;
  --tui-glow: rgba(226, 232, 240, 0.4);
  --tui-border: rgba(226, 232, 240, 0.2);
}
.theme-ega {
  --tui-color: #00ffff;
  --tui-dim: #008b8b;
  --tui-glow: rgba(0, 255, 255, 0.6);
  --tui-border: rgba(0, 255, 255, 0.2);
}
</style>

<style scoped>
:deep(.terminal), :deep(.terminal span) {
  --color: var(--tui-color) !important;
  text-shadow: 0 0 5px var(--tui-glow) !important;
}

.homepage-wrapper {
  background-color: #050505;
  color: var(--tui-color);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.theme-selector {
  background: #111;
  border: 1px solid var(--tui-border);
  color: var(--tui-color);
  font-size: 11px;
  padding: 3px 6px;
  outline: none;
  cursor: pointer;
  transition: 0.3s;
  box-shadow: 0 0 4px var(--tui-border);
}
.theme-selector:hover {
  border-color: var(--tui-color);
  box-shadow: 0 0 8px var(--tui-glow);
}

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

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

.nav-item {
  color: var(--tui-color) !important;
  text-decoration: none;
  background: none;
  border: 1px solid var(--tui-color) !important;
  padding: 6px 18px;
  margin-left: 10px;
  cursor: pointer;
  font-size: 13px;
  box-shadow: 0 0 5px var(--tui-border);
  transition: 0.3s;
}
.nav-item:hover, .nav-item.active-auth {
  background: var(--tui-border) !important;
  color: var(--tui-color) !important;
  box-shadow: 0 0 10px var(--tui-color);
}
.user-info { color: var(--tui-dim) !important; font-size: 12px; margin-right: 15px; 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: var(--tui-color); box-shadow: 0 0 8px var(--tui-color); }

/* --- 컨텐츠 영역 --- */
.content-area {
  flex: 1; padding: 20px; min-height: 400px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}
.sub-page { max-width: 1000px; margin: 0 auto; padding-top: 15px; width: 100%; }
.page-title { border-bottom: 1px solid var(--tui-border); padding-bottom: 10px; margin-bottom: 20px; color: var(--tui-color);}

.main-page {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  position: relative;
}

.tui-global-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.88);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: all;
}

.ascii-container {
  width: 100%;
  overflow: auto;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
.ascii-art {
  font-weight: bold;
  white-space: pre;
  display: block;
  margin: 0 auto;
  width: max-content;

  color: var(--tui-color) !important;
  font-size: 14px;
  line-height: 1.2;
  border: none;
  background: transparent;
  transform-origin: center;
  opacity: 1;

  animation: once-cyber-glitch-wobble 2.5s linear 1 forwards !important;
}

:deep(.bg-block) {
  color: #050505 !important;
  text-shadow: none !important;
}

/* 📺 유튜브 그리드 레이아웃 */
#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 var(--tui-border);
  position: relative;
  cursor: pointer;
  transition: 0.3s;
}
.video-card:hover { border-color: var(--tui-color); box-shadow: 0 0 10px var(--tui-border); }
.video-title { color: var(--tui-dim); margin-top: 10px; font-size: 14px; height: 40px; overflow: hidden; font-family: sans-serif; }
iframe { width: 100%; height: 180px; border-radius: 4px; }

/* 보안 로그인 프레임 */
.login-terminal-frame {
  max-width: 550px; margin: 40px auto;
  border: 1px dashed var(--tui-color); padding: 35px;
  background: #020a02; box-shadow: 0 0 15px var(--tui-border);
}
.login-gate-title { color: var(--tui-color); font-size: 20px; margin-bottom: 10px; font-weight: bold;}
.login-gate-desc { color: var(--tui-dim); 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 var(--tui-dim); padding-bottom: 5px; }
.login-label { width: 120px; color: var(--tui-color); font-weight: bold; font-size: 14px; }
.login-input {
  flex: 1; background: none; border: none; color: var(--tui-color);
  font-size: 15px; outline: none;
}
.login-submit-btn {
  margin-top: 15px; background: none; border: 1px solid var(--tui-color);
  color: var(--tui-color); padding: 12px;
  font-size: 14px; font-weight: bold; cursor: pointer; transition: 0.3s;
}
.login-submit-btn:hover { background: var(--tui-color); color: #000; box-shadow: 0 0 15px var(--tui-color); }

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

/* 애니메이션 트랜지션 */
.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-size: 12px;}
.monitor-status { color: var(--tui-dim); 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; }

/* 📱 반응형 분기점 */
@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: 15px;
    padding: 15px 20px;
    align-items: center;
  }
  .nav-menu {
    display: flex;
    gap: 12px 16px;
    flex-wrap: wrap;
    justify-content: center;
    width: 100%;
  }
  .menu-btn { font-size: 14px; }
  .auth-group { width: 100%; justify-content: center; margin-top: 5px; }
  .nav-item { margin: 0 6px; }

  .ascii-container {
    width: 100%;
    overflow-x: auto !important;
    overflow-y: hidden !important;
    padding: 20px 10px;
    display: block;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
  }

  .ascii-art {
    font-size: 11px !important;
    line-height: 1.35 !important;
    white-space: pre !important;
    word-break: keep-all !important;
    width: max-content !important;
    margin: 0 !important;
    -webkit-text-size-adjust: none !important;
    text-size-adjust: none !important;
    max-height: 999999px !important;
  }

  .crt-monitor-frame {
    height: 180px !important;
    margin: 10px 15px 15px !important;
  }
  .monitor-header { padding: 4px 10px; font-size: 10px; }
}
@keyframes blink { 0%, 100% { opacity: 0.4; } 50% { opacity: 1; } }

/* 🟢 [★완벽 교정] 모든 주요 타임라인 프레임에 color: var(--tui-color)를 강제 각인하여 테마 실시간 연동 보장 */
@keyframes once-cyber-glitch-wobble {
  0%, 25% { transform: translate(0) scale(1) skewX(0deg); color: var(--tui-color); text-shadow: 0 0 8px var(--tui-glow); opacity: 1; }
  26% { transform: translate(-3px, 1.5px) scale(1.02); color: #ffffff; text-shadow: 2px 0 #ff0000, -2px 0 #0000ff; }
  27% { transform: translate(3px, -1.5px) skewX(-2deg); color: var(--tui-color); }
  28% { transform: translate(-5px, 0) skewX(10deg); color: #ff00ff; text-shadow: -3px 0 magenta, 3px 0 cyan;}
  29% { transform: translate(5px, 0) skewX(-10deg); color: #00ffff; text-shadow: 3px 0 magenta, -3px 0 cyan;}
  30% { transform: translate(0); color: var(--tui-color); text-shadow: 0 0 15px var(--tui-color);}
  31%, 50% { transform: translate(0); color: var(--tui-color); text-shadow: 0 0 8px var(--tui-glow); }
  51% { transform: scale(1.05) skewY(1deg); color: #ffffff; opacity: 0.05; }
  53% { opacity: 1; transform: translate(0); color: var(--tui-color); text-shadow: 0 0 20px var(--tui-color), 0 0 40px var(--tui-glow); }
  90% { transform: translate(-2px, 1px); text-shadow: 2px 0 red, -2px 0 blue;}
  92% { transform: translate(2px, -1px); text-shadow: -2px 0 red, 2px 0 blue;}
  95% { transform: translate(0); color: var(--tui-color); text-shadow: 0 0 20px var(--tui-color); }
  100% { transform: translate(0) scale(1) skewX(0deg); color: var(--tui-color); text-shadow: 0 0 15px var(--tui-color), 0 0 30px var(--tui-glow); opacity: 1; }
}
</style>