/**
 * Haprial Theme - Core JavaScript
 * Theme toggle, search, barrage, floating tools, and animations
 */

(function() {
  'use strict';

  // ===== Theme Toggle =====
  window.toggleTheme = function() {
    var html = document.documentElement;
    var current = html.getAttribute('data-theme');
    var next = current === 'dark' ? 'light' : 'dark';
    html.setAttribute('data-theme', next);
    try { localStorage.setItem('theme', next); } catch(e) {}

    // Rotate animation on toggle button
    var btn = document.getElementById('theme-toggle');
    if (btn) {
      btn.classList.add('rotate');
      setTimeout(function() { btn.classList.remove('rotate'); }, 500);
    }

    // Update icon
    var icon = btn ? btn.querySelector('i') : null;
    if (icon) {
      icon.className = next === 'dark' ? 'ri-moon-line' : 'ri-sun-line';
    }
  };

  // Set initial icon
  function setThemeIcon() {
    var theme = document.documentElement.getAttribute('data-theme');
    var btn = document.getElementById('theme-toggle');
    var icon = btn ? btn.querySelector('i') : null;
    if (icon) {
      icon.className = theme === 'dark' ? 'ri-moon-line' : 'ri-sun-line';
    }
  }

  // ===== Avatar Theme Tip =====
  function initAvatarTip() {
    var tip = document.getElementById('avatar-theme-tip');
    if (!tip) return;
    // Show tip briefly on first visit
    var shown = sessionStorage.getItem('avatarTipShown');
    if (!shown) {
      tip.classList.add('is-visible');
      sessionStorage.setItem('avatarTipShown', '1');
      setTimeout(function() {
        tip.classList.remove('is-visible');
        tip.classList.add('is-hidden');
      }, 4000);
    }
  }

  // ===== Search Modal =====
  window.openSearchModal = function() {
    var modal = document.getElementById('search-modal');
    if (modal) {
      modal.classList.add('show');
      var input = document.getElementById('search-input');
      if (input) setTimeout(function() { input.focus(); }, 100);
    }
  };

  window.closeSearchModal = function() {
    var modal = document.getElementById('search-modal');
    if (modal) modal.classList.remove('show');
  };

  // ===== Inline Search Mode =====
  window.toggleSearchMode = function(show) {
    var header = document.querySelector('.section-header.normal-mode');
    var container = document.getElementById('search-container');
    var searchHeader = document.querySelector('.searchable-header-container');

    if (show) {
      if (header) header.style.display = 'none';
      if (container) container.style.display = 'block';
      var input = document.getElementById('inline-search-input');
      if (input) setTimeout(function() { input.focus(); }, 100);
    } else {
      if (header) header.style.display = '';
      if (container) container.style.display = 'none';
      var results = document.getElementById('inline-search-results');
      if (results) {
        results.classList.remove('show');
        results.innerHTML = '';
      }
    }
  };

  // Load search index dynamically
  function loadSearchIndex(cb) {
    if (window.searchIndex) { cb && cb(window.searchIndex); return; }
    fetch('/index.json').then(function(r) { return r.json(); }).then(function(data) {
      window.searchIndex = data;
      cb && cb(data);
    }).catch(function() { cb && cb(null); });
  }

  // Inline search handler
  function initInlineSearch() {
    var input = document.getElementById('inline-search-input');
    var resultsContainer = document.getElementById('inline-search-results');
    if (!input || !resultsContainer) return;

    input.addEventListener('input', function() {
      var query = this.value.trim().toLowerCase();
      if (!query) {
        resultsContainer.classList.remove('show');
        resultsContainer.innerHTML = '';
        return;
      }

      if (!window.searchIndex) { loadSearchIndex(function() { input.dispatchEvent(new Event('input')); }); return; }

      var results = searchIndex.filter(function(item) {
        return item.title.toLowerCase().indexOf(query) !== -1 ||
               (item.summary && item.summary.toLowerCase().indexOf(query) !== -1);
      });

      if (results.length === 0) {
        resultsContainer.innerHTML = '<div class="no-result">未找到相关文章</div>';
      } else {
        resultsContainer.innerHTML = results.map(function(item) {
          return '<a href="' + item.url + '" class="search-result-item">' +
                 '<span class="search-result-title">' + item.title + '</span>' +
                 '<span class="search-result-date">' + item.date + '</span>' +
                 '</a>';
        }).join('');
      }
      resultsContainer.classList.add('show');
    });
  }

  // Modal search handler
  function initModalSearch() {
    var input = document.getElementById('search-input');
    var resultsContainer = document.getElementById('search-results');
    if (!input || !resultsContainer) return;

    input.addEventListener('keydown', function(e) {
      if (e.key === 'Enter') {
        var query = this.value.trim().toLowerCase();
        if (!query) return;

        if (!window.searchIndex) { loadSearchIndex(function() { input.dispatchEvent(new Event('keydown')); }); return; }

        var results = searchIndex.filter(function(item) {
          return item.title.toLowerCase().indexOf(query) !== -1 ||
                 (item.summary && item.summary.toLowerCase().indexOf(query) !== -1);
        });

        if (results.length === 0) {
          resultsContainer.innerHTML = '<p class="no-result">未找到相关文章</p>';
        } else {
          resultsContainer.innerHTML = results.map(function(item) {
            return '<div class="search-result-item" onclick="location.href=\'' + item.url + '\'">' +
                   '<span class="search-result-title">' + item.title + '</span>' +
                   '<span class="search-result-date">' + item.date + '</span>' +
                   (item.summary ? '<span class="search-result-summary">' + item.summary + '</span>' : '') +
                   '</div>';
          }).join('');
        }
      }
    });
  }

  // Close modal on Escape
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeSearchModal();
  });

  // Close modal on backdrop click
  document.addEventListener('click', function(e) {
    var modal = document.getElementById('search-modal');
    if (modal && e.target === modal) closeSearchModal();
  });

  // ===== Floating Tools: Back to Top =====
  function initBackToTop() {
    var btn = document.getElementById('back-to-top');
    if (!btn) return;

    window.addEventListener('scroll', function() {
      if (window.scrollY > 300) {
        btn.classList.add('show');
      } else {
        btn.classList.remove('show');
      }
    }, { passive: true });

    btn.addEventListener('click', function(e) {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  }

  // ===== Floating Tools Visibility =====
  function initFloatingTools() {
    var tools = document.getElementById('floating-tools');
    if (!tools) return;

    var lastScroll = 0;
    window.addEventListener('scroll', function() {
      var current = window.scrollY;
      if (current > lastScroll && current > 300) {
        tools.classList.add('hidden');
      } else {
        tools.classList.remove('hidden');
      }
      lastScroll = current;
    }, { passive: true });
  }

  // ===== Selection Popup =====
  function initSelectionPopup() {
    var popup = null;

    document.addEventListener('mouseup', function() {
      setTimeout(function() {
        var sel = window.getSelection();
        var text = sel ? sel.toString().trim() : '';
        if (text.length > 0 && text.length < 200) {
          if (!popup) {
            popup = document.createElement('div');
            popup.id = 'selection-popup';
            popup.innerHTML = '<i class="ri-search-line"></i> 搜索"';
            document.body.appendChild(popup);
          }
          var range = sel.getRangeAt(0);
          var rect = range.getBoundingClientRect();
          popup.style.display = 'flex';
          popup.style.left = rect.left + rect.width / 2 + 'px';
          popup.style.top = rect.top - 10 + window.scrollY + 'px';
          popup.querySelector('i').nextSibling.textContent = '搜索"' + text.substring(0, 20) + (text.length > 20 ? '...' : '') + '"';

          popup.onclick = function() {
            window.open('https://www.google.com/search?q=' + encodeURIComponent(text), '_blank');
            popup.style.display = 'none';
          };
        } else if (popup) {
          popup.style.display = 'none';
        }
      }, 10);
    });

    document.addEventListener('mousedown', function(e) {
      if (popup && e.target !== popup) {
        popup.style.display = 'none';
      }
    });
  }

  // ===== Search Hint Text (Greeting) =====
  function setSearchHint() {
    var hintEl = document.getElementById('search-hint-text');
    if (!hintEl) return;

    var hour = new Date().getHours();
    var greetings;
    if (hour < 6) greetings = ['早点睡对皮肤好', '夜猫子你好', '明天再看吧'];
    else if (hour < 11) greetings = ['早安！元气满满', '新的一天，加油', '早起的鸟儿有虫吃'];
    else if (hour < 14) greetings = ['中午好！记得干饭', '午饭吃好了吗', '午后适合摸鱼'];
    else if (hour < 18) greetings = ['下午好！喝杯茶吧', '下午茶时间到了', '下午适合发呆'];
    else greetings = ['晚上好！放松一下', '今晚月色不错', '夜深了，读篇好文'];

    var text = greetings[Math.floor(Math.random() * greetings.length)];
    hintEl.textContent = text;

    var wrapper = document.getElementById('search-hint-wrapper');
    if (wrapper) {
      wrapper.classList.add('visible');
      setTimeout(function() {
        wrapper.classList.remove('visible');
      }, 5000);
    }
  }

  // ===== PJAX-like Page Transitions =====
  function initPageTransitions() {
    document.addEventListener('click', function(e) {
      var link = e.target.closest('a');
      if (!link) return;
      var href = link.getAttribute('href');
      if (!href || href.startsWith('#') || href.startsWith('javascript:') || link.target === '_blank') return;
      if (href.startsWith('http') && !href.startsWith(window.location.origin)) return;

      e.preventDefault();
      var wrapper = document.getElementById('pjax-container');
      if (!wrapper) {
        window.location.href = href;
        return;
      }

      wrapper.classList.add('pjax-leave');
      setTimeout(function() {
        window.location.href = href;
      }, 300);
    });
  }

  // ===== Blog Image Blur Animation =====
  function initImageBlur() {
    var images = document.querySelectorAll('.blog-img');
    images.forEach(function(img) {
      if (img.complete) return;
      img.style.filter = 'blur(10px)';
      img.style.transition = 'filter 1s ease';
      img.addEventListener('load', function() {
        img.style.filter = 'blur(0)';
      });
    });
  }

  // ===== Initialize Everything =====
  function init() {
    setThemeIcon();
    initAvatarTip();
    initBackToTop();
    initFloatingTools();
    initInlineSearch();
    initModalSearch();
    initSelectionPopup();
    initPageTransitions();
    initImageBlur();
    setSearchHint();

    // Pause barrage when page is hidden (optimization 4)
    document.addEventListener('visibilitychange', function() {
      var barrager = document.getElementById('barrager');
      if (!barrager) return;
      barrager.style.animationPlayState = document.hidden ? 'paused' : 'running';
      barrager.querySelectorAll('.barrage-item').forEach(function(item) {
        item.style.animationPlayState = document.hidden ? 'paused' : 'running';
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();
