<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8" />
  <title>클릭해서 살아남기</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />

  <style>
    /* ====================================== 
       전체 화면 기본 스타일 
    ====================================== */
    body {
      margin: 0;
      padding: 0;
      font-family: sans-serif;
      background-color: #f4f4f4;
      overflow: hidden;
      user-select: none;
      /* 모바일에서 드래그로 브라우저 UI가 튀어나오지 않도록 */
      touch-action: none; 
    }
    .center-container {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
    }

    /* ====================================== 
       시작 화면 
    ====================================== */
    #start-screen {
      width: 100%;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      box-sizing: border-box;
      padding: 20px;
    }
    #start-screen h1 {
      font-size: 2em;
      margin-bottom: 20px;
    }
    #start-screen .game-desc {
      max-width: 600px;
      text-align: left;
      margin-bottom: 30px;
    }
    /* 유저 에이전트 안내 문구 */
    #ua-warning {
      margin-bottom: 20px;
      color: red;
      font-weight: bold;
      display: none; /* 기본은 숨김 */
    }
    #start-btn {
      padding: 15px 30px;
      font-size: 1em;
      cursor: pointer;
    }
    /* 비활성화된 버튼 스타일 */
    #start-btn:disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }

    /* ====================================== 
       게임 화면 
    ====================================== */
    #game-screen {
      display: none;
      width: 100%;
      height: 100vh;
      position: relative;
    }
    #info-bar {
      position: absolute;
      top: 10px;
      left: 10px;
      color: #333;
      font-size: 1em;
    }
    #info-bar span {
      margin-right: 20px;
    }
    #hourglass {
      position: relative;
      width: 80px;
      height: 120px;
      margin: 0 auto;
      border: 4px solid #333;
      border-radius: 10px;
      box-sizing: border-box;
      overflow: hidden;
    }
    #hourglass-fill {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      background-color: #999;
      height: 100%;
      transition: height 0.1s linear;
    }
    #gauge-number {
      font-size: 2em;
      margin-top: 20px;
      color: #333;
    }
    .stop-mode {
      background-color: #87cefa !important;
    }
    .danger-mode {
      background-color: #ffe5e5 !important;
    }

    /* ====================================== 
       STOP 모드 경고 (카운트다운) 박스 
    ====================================== */
    #stop-warning-box {
      display: none;
      position: absolute;
      top: 80px;
      left: 50%;
      transform: translateX(-50%);
      background-color: rgba(255, 165, 0, 0.9);
      color: #fff;
      padding: 10px 20px;
      border-radius: 8px;
      font-size: 1.2em;
      z-index: 9999;
      text-align: center;
      pointer-events: all;
    }

    /* ====================================== 
       STOP 모드 남은 시간 안내 
    ====================================== */
    #stop-mode-display {
      display: none;
      position: absolute;
      top: 140px;
      left: 50%;
      transform: translateX(-50%);
      background-color: rgba(0, 0, 0, 0.6);
      color: #fff;
      padding: 10px 20px;
      border-radius: 8px;
      font-size: 1.2em;
      z-index: 9999;
      text-align: center;
    }

    /* ====================================== 
       게임 오버 화면 
    ====================================== */
    #game-over-screen {
      display: none;
      width: 100%;
      height: 100vh;
      background-color: rgba(0, 0, 0, 0.6);
      color: #fff;
      position: absolute;
      top: 0;
      left: 0;
    }
    #game-over-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
    }
    #game-over-content h2 {
      margin-bottom: 20px;
    }
    #restart-btn {
      padding: 10px 20px;
      font-size: 1em;
      cursor: pointer;
    }

    /* ====================================== 
       클릭 이펙트 
    ====================================== */
    .click-effect {
      position: absolute;
      width: 20px;
      height: 20px;
      border: 2px solid rgba(255, 0, 0, 0.6);
      border-radius: 50%;
      pointer-events: none;
      animation: clickAnim 0.4s ease-out forwards;
    }
    @keyframes clickAnim {
      from {
        opacity: 1;
        transform: scale(1);
      }
      to {
        opacity: 0;
        transform: scale(2);
      }
    }
  </style>
</head>
<body>

  <!-- ======================================
       시작 화면
  ====================================== -->
  <div id="start-screen">
    <div class="center-container">
      <h1>클릭해서 살아남기</h1>

      <div class="game-desc">
        <p>
          시작하면 화면 중앙에 보이는 숫자가 빠르게 줄어듭니다.<br />
          화면을 클릭(또는 터치)해서 숫자를 다시 올리면서 0이 되지 않도록 버텨보세요!
        </p>
        <ul>
          <li>레벨은 10초마다 올라갑니다 (레벨이 오를수록 게이지가 더 빨리 줄어듭니다).</li>
          <li>STOP 모드가 시작되기 전, 카운트다운 안내가 나오며 그 동안에는 클릭이 차단됩니다.</li>
          <li>STOP 모드 중 자동 감소는 멈추지만, 클릭할 때마다 게이지가 크게 줄어듭니다.</li>
          <li>게이지가 0이 되면 게임 오버! 최대한 오래 버텨보세요.</li>
        </ul>
      </div>

      <!-- 카카오톡 인앱 브라우저 전용 안내 -->
      <div id="ua-warning">카카오톡 인앱 브라우저에서만 플레이 가능합니다.<br>현재 UA: <span id="ua-string"></span></div>

      <button id="start-btn">시작하기</button>
    </div>
  </div>


  <!-- ======================================
       게임 화면
  ====================================== -->
  <div id="game-screen">
    <!-- 정보 표시 -->
    <div id="info-bar">
      <span>레벨: <span id="level-display">1</span></span>
      <span>버틴 시간: <span id="time-display">0</span>s</span>
      <span>1초당 클릭량: <span id="cps-display">0</span></span>
    </div>

    <div class="center-container">
      <div id="hourglass">
        <!-- 모래가 찬 부분 -->
        <div id="hourglass-fill"></div>
      </div>
      <div id="gauge-number">100</div>
    </div>

    <!-- STOP 모드 경고 박스 (카운트다운) -->
    <div id="stop-warning-box"></div>

    <!-- STOP 모드 남은 시간 안내 -->
    <div id="stop-mode-display"></div>
  </div>


  <!-- ======================================
       게임 오버 화면
  ====================================== -->
  <div id="game-over-screen">
    <div id="game-over-content">
      <h2>게임 오버</h2>
      <p id="final-level"></p>
      <p id="final-time"></p>
      <p id="final-cps"></p>
      <button id="restart-btn">다시하기</button>
    </div>
  </div>


  <script>
    // ---------------------
    // 1) User-Agent 검사 (카카오톡 인앱 브라우저 전용)
    // ---------------------
    // User-Agent 문자열을 소문자로 변환하여 검사
    const ua = navigator.userAgent.toLowerCase();
    const startBtn = document.getElementById("start-btn");
    const uaWarning = document.getElementById("ua-warning");
    const uaStringSpan = document.getElementById("ua-string");

    // kakaotalk와 inapp 문자열이 모두 포함되어 있어야 함
    if (ua.indexOf("kakaotalk") === -1 || ua.indexOf("inapp") === -1) {
      uaWarning.style.display = "block";  // 경고 문구 표시
      // 현재 UA를 함께 안내
      uaStringSpan.textContent = navigator.userAgent;
      startBtn.disabled = true;           // 버튼 비활성화
      startBtn.textContent = "플레이 불가";
    }

    // ---------------------
    // 2) HTML 요소 참조
    // ---------------------
    const startScreen = document.getElementById("start-screen");
    const gameScreen = document.getElementById("game-screen");
    const gameOverScreen = document.getElementById("game-over-screen");

    const stopWarningBox = document.getElementById("stop-warning-box");
    const stopModeDisplay = document.getElementById("stop-mode-display");

    // 게임 진행 정보
    const gaugeNumberEl = document.getElementById("gauge-number");
    const hourglassFillEl = document.getElementById("hourglass-fill");
    const levelDisplay = document.getElementById("level-display");
    const timeDisplay = document.getElementById("time-display");
    const cpsDisplay = document.getElementById("cps-display");

    // 게임 오버 정보
    const finalLevelEl = document.getElementById("final-level");
    const finalTimeEl = document.getElementById("final-time");
    const finalCpsEl = document.getElementById("final-cps");
    const restartBtn = document.getElementById("restart-btn");

    // ---------------------
    // 3) 전역 변수
    // ---------------------
    let gaugeNumber = 100;   
    let baseReduceRate = 5;  // 난이도 (1초에 레벨×5만큼 감소)
    let level = 1;
    let timeElapsed = 0;
    let totalClicks = 0;
    let clickCountLastSecond = 0;

    let isStopMode = false;      
    let isStopWarning = false;  
    let stopInterval = null;
    let stopWarningTimer = null;
    let stopModeInterval = null;

    const STOP_WARNING_DURATION = 3000; // 3초 카운트다운
    const STOP_MODE_DURATION = 5000;    // STOP 모드 5초

    let mainInterval = null; // 1초마다 시간/레벨/CPS 처리
    let subInterval = null;  // 0.1초마다 게이지 감소

    const TICK_INTERVAL = 100; 
    const TICK_PER_SEC = 1000 / TICK_INTERVAL; // 10

    // ---------------------
    // 4) 시작 버튼 이벤트
    // ---------------------
    startBtn.addEventListener("click", startGame);

    // 전체화면 요청 함수
    function requestFullScreen() {
      const docElem = document.documentElement;
      if (docElem.requestFullscreen) {
        docElem.requestFullscreen();
      } else if (docElem.mozRequestFullScreen) {
        docElem.mozRequestFullScreen();
      } else if (docElem.webkitRequestFullscreen) {
        docElem.webkitRequestFullscreen();
      } else if (docElem.msRequestFullscreen) {
        docElem.msRequestFullscreen();
      }
    }

    function startGame() {
      // 인앱 브라우저 체크 (버튼이 비활성화면 그냥 리턴)
      if (startBtn.disabled) return;

      // 게임 시작 시 전체화면 전환 시도
      requestFullScreen();

      // 초기화
      gaugeNumber = 100;
      baseReduceRate = 5; 
      level = 1;
      timeElapsed = 0;
      totalClicks = 0;
      clickCountLastSecond = 0;
      isStopMode = false;
      isStopWarning = false;

      gaugeNumberEl.textContent = gaugeNumber;
      levelDisplay.textContent = level;
      timeDisplay.textContent = timeElapsed;
      cpsDisplay.textContent = "0";

      updateHourglassFill(gaugeNumber);

      // 화면 전환
      startScreen.style.display = "none";
      gameScreen.style.display = "block";
      gameOverScreen.style.display = "none";
      document.body.classList.remove("stop-mode", "danger-mode");

      stopWarningBox.style.display = "none";
      stopModeDisplay.style.display = "none";

      // 메인 루프 (1초)
      mainInterval = setInterval(() => {
        timeElapsed++;
        timeDisplay.textContent = timeElapsed;

        level = Math.floor(timeElapsed / 10) + 1;
        levelDisplay.textContent = level;

        cpsDisplay.textContent = clickCountLastSecond.toFixed(1);
        clickCountLastSecond = 0;

        if (gaugeNumber <= 0) {
          endGame();
        }
      }, 1000);

      // 서브 루프 (0.1초)
      subInterval = setInterval(() => {
        if (!isStopMode && !isStopWarning) {
          let reduceAmount = (level * baseReduceRate) / TICK_PER_SEC;
          gaugeNumber -= reduceAmount;
          if (gaugeNumber < 0) gaugeNumber = 0;

          if (gaugeNumber <= 30) {
            document.body.classList.add("danger-mode");
          } else {
            document.body.classList.remove("danger-mode");
          }

          gaugeNumberEl.textContent = Math.floor(gaugeNumber);
          updateHourglassFill(gaugeNumber);
        }
      }, TICK_INTERVAL);

      // STOP 모드 예약
      scheduleStopMode();

      // PC 마우스 클릭 이벤트
      document.body.addEventListener("click", onClickPC, { passive: false });
      // 모바일 멀티터치 이벤트
      document.body.addEventListener("touchstart", onTouchScreen, { passive: false });
    }

    // ---------------------
    // 5) 클릭/터치 이벤트
    // ---------------------
    function onClickPC(e) {
      processClick(e.pageX, e.pageY);
    }
    function onTouchScreen(e) {
      for (let i = 0; i < e.touches.length; i++) {
        const touch = e.touches[i];
        processClick(touch.pageX, touch.pageY);
      }
    }
    function processClick(x, y) {
      if (isStopWarning) {
        // STOP 모드 경고 중이면 클릭 무시
        return;
      }
      createClickEffect(x, y);

      totalClicks++;
      clickCountLastSecond++;

      if (isStopMode) {
        gaugeNumber -= 5;
        if (gaugeNumber < 0) gaugeNumber = 0;
      } else {
        gaugeNumber += 1;
        if (gaugeNumber > 100) gaugeNumber = 100;
      }

      gaugeNumberEl.textContent = Math.floor(gaugeNumber);
      updateHourglassFill(gaugeNumber);
    }

    // ---------------------
    // 6) 게이지 시각화
    // ---------------------
    function updateHourglassFill(value) {
      const percent = value; 
      hourglassFillEl.style.height = percent + "%";
    }

    // ---------------------
    // 7) STOP 모드 스케쥴링
    // ---------------------
    function scheduleStopMode() {
      const randomDelay = Math.floor(Math.random() * 10 + 10) * 1000;
      if (randomDelay > STOP_WARNING_DURATION) {
        setTimeout(showStopWarning, randomDelay - STOP_WARNING_DURATION);
      }
      stopInterval = setTimeout(activateStopMode, randomDelay);
    }

    // ---------------------
    // 8) STOP 모드 사전 안내(카운트다운)
    // ---------------------
    function showStopWarning() {
      if (gaugeNumber <= 0) return;
      isStopWarning = true;

      stopWarningBox.style.display = "block";
      let countdown = STOP_WARNING_DURATION / 1000; // 3초
      stopWarningBox.textContent = `STOP 모드 ${countdown}초 전 (손을 떼세요!)`;

      stopWarningTimer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
          clearInterval(stopWarningTimer);
          stopWarningBox.style.display = "none";
          isStopWarning = false;
        } else {
          stopWarningBox.textContent = `STOP 모드 ${countdown}초 전 (손을 떼세요!)`;
        }
      }, 1000);
    }

    // ---------------------
    // 9) STOP 모드 진입
    // ---------------------
    function activateStopMode() {
      clearInterval(stopWarningTimer);
      stopWarningBox.style.display = "none";
      isStopWarning = false;

      isStopMode = true;
      document.body.classList.add("stop-mode");

      stopModeDisplay.style.display = "block";
      let stopRemaining = STOP_MODE_DURATION / 1000; // 5초
      stopModeDisplay.textContent = `STOP 모드 ${stopRemaining}초 남음`;

      stopModeInterval = setInterval(() => {
        stopRemaining--;
        if (stopRemaining <= 0) {
          clearInterval(stopModeInterval);
          stopModeDisplay.style.display = "none";
          deactivateStopMode();
        } else {
          stopModeDisplay.textContent = `STOP 모드 ${stopRemaining}초 남음`;
        }
      }, 1000);
    }

    // ---------------------
    // 10) STOP 모드 해제
    // ---------------------
    function deactivateStopMode() {
      isStopMode = false;
      document.body.classList.remove("stop-mode");
      stopModeDisplay.style.display = "none";
      scheduleStopMode();
    }

    // ---------------------
    // 11) 클릭 이펙트 생성
    // ---------------------
    function createClickEffect(x, y) {
      const effect = document.createElement("div");
      effect.className = "click-effect";
      effect.style.left = (x - 10) + "px";
      effect.style.top = (y - 10) + "px";
      document.body.appendChild(effect);

      setTimeout(() => {
        if (effect.parentNode) {
          effect.parentNode.removeChild(effect);
        }
      }, 400);
    }

    // ---------------------
    // 12) 게임 오버 처리
    // ---------------------
    function endGame() {
      clearInterval(mainInterval);
      clearInterval(subInterval);
      clearTimeout(stopInterval);
      clearInterval(stopWarningTimer);
      clearInterval(stopModeInterval);

      document.body.removeEventListener("click", onClickPC);
      document.body.removeEventListener("touchstart", onTouchScreen);

      const avgCPS = (totalClicks / timeElapsed).toFixed(2);
      finalLevelEl.textContent = `최종 레벨: ${level}`;
      finalTimeEl.textContent = `버틴 시간: ${timeElapsed}초`;
      finalCpsEl.textContent = `평균 1초당 클릭량: ${avgCPS}`;

      gameOverScreen.style.display = "block";
    }

    // ---------------------
    // 13) 다시하기 버튼
    // ---------------------
    restartBtn.addEventListener("click", () => {
      gameOverScreen.style.display = "none";
      startScreen.style.display = "block";
    });
  </script>
</body>
</html>