<!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; /* fill 요소가 벗어나지 않도록 */
    }
    /* 실제 모래(채워진 부분) */
    #hourglass-fill {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      background-color: #999;
      height: 100%;
      transition: height 0.1s linear; /* 0.1초 단위로 부드럽게 줄어듦 */
    }

    /* 숫자(게이지) 표시 */
    #gauge-number {
      font-size: 2em;
      margin-top: 20px;
      color: #333;
    }

    /* STOP 모드(파란 배경) */
    .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">카카오톡 인앱 브라우저에서만 플레이 가능합니다.</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 검사
    // ---------------------
    const userAgent = navigator.userAgent;
    const startBtn = document.getElementById("start-btn");
    const uaWarning = document.getElementById("ua-warning");

    // "KAKAOTALK"와 "(inapp)" 둘 다 포함되지 않으면 인앱 브라우저 아님
    if (
      !userAgent.includes("KAKAOTALK") ||
      !userAgent.includes("(inapp)")
    ) {
      // 플레이 불가
      uaWarning.style.display = "block";  // 경고 문구 보여주기
      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;   // 0~100
    let baseReduceRate = 5;  // 난이도(1초에 레벨 × baseReduceRate만큼 감소)
    let level = 1;
    let timeElapsed = 0;     // 총 버틴 시간(초)
    let totalClicks = 0;     // 전체 클릭 횟수
    let clickCountLastSecond = 0; // 최근 1초 클릭 횟수

    // STOP 관련
    let isStopMode = false;      // 실제 STOP 상태
    let isStopWarning = false;   // STOP 모드 임박 카운트다운 상태
    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초마다 게이지 감소

    // 0.1초 간격(1초에 10번)
    const TICK_INTERVAL = 100;
    const TICK_PER_SEC = 1000 / TICK_INTERVAL; // 10

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

    function startGame() {
      // 혹시 버튼이 비활성화 상태라면(=유저 에이전트 조건 불충분) 그냥 리턴
      if (startBtn.disabled) return;

      // 초기화
      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(() => {
        // 1) 시간 증가
        timeElapsed++;
        timeDisplay.textContent = timeElapsed;

        // 2) 레벨 계산(10초마다 +1)
        level = Math.floor(timeElapsed / 10) + 1;
        levelDisplay.textContent = level;

        // 3) 1초당 클릭량(CPS)
        cpsDisplay.textContent = clickCountLastSecond.toFixed(1);
        clickCountLastSecond = 0;

        // 4) 게이지 0 이하 → 게임오버
        if (gaugeNumber <= 0) {
          endGame();
        }
      }, 1000);

      // 서브 루프 (0.1초)
      subInterval = setInterval(() => {
        // STOP 모드/카운트다운 아닐 때만 게이지 자동 감소
        if (!isStopMode && !isStopWarning) {
          let reduceAmount = (level * baseReduceRate) / TICK_PER_SEC;
          gaugeNumber -= reduceAmount;
          if (gaugeNumber < 0) gaugeNumber = 0;

          // 위험 상태(게이지 <= 30)
          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) {
      // STOP 모드 경고 중이면 클릭 차단
      if (isStopWarning) {
        return;
      }

      // 클릭 이펙트
      createClickEffect(x, y);

      // 클릭 카운트
      totalClicks++;
      clickCountLastSecond++;

      if (isStopMode) {
        // STOP 모드 중 → 클릭 시 크게 감소
        gaugeNumber -= 5;
        if (gaugeNumber < 0) gaugeNumber = 0;
      } else {
        // 평상시 → +1
        gaugeNumber += 1;
        if (gaugeNumber > 100) gaugeNumber = 100;
      }

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

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

    // ---------------------
    // 7) STOP 모드 스케쥴링
    // ---------------------
    function scheduleStopMode() {
      // 10초 ~ 20초 사이 랜덤
      const randomDelay = Math.floor(Math.random() * 10 + 10) * 1000;

      // 실제 STOP 모드 시작 3초 전 미리 경고
      if (randomDelay > STOP_WARNING_DURATION) {
        setTimeout(showStopWarning, randomDelay - STOP_WARNING_DURATION);
      }

      // STOP 모드 시작
      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; // STOP 모드 ON
      document.body.classList.add("stop-mode");

      // STOP 모드 남은 시간 안내
      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(); // 다음 STOP 모드 예약
    }

    // ---------------------
    // 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);

      // 0.4초 뒤 제거
      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>