// C# WebView2 communication
function postMessage(msg) {
  if (window.chrome && window.chrome.webview) {
    window.chrome.webview.postMessage(msg);
  }
}

// Items will be loaded async
let items = [];

// DOM elements
const list = document.getElementById('list');
const search = document.getElementById('search');
const stats = document.getElementById('stats');
const filterBtns = document.querySelectorAll('.filter-btn');
const closeBtn = document.getElementById('close-btn');
const iconBtn = document.getElementById('icon');
const iconWrapper = document.getElementById('icon-wrapper');
const panel = document.getElementById('panel');
const collapseBtn = document.getElementById('collapse-btn');

// Detail view elements
const listView = document.getElementById('list-view');
const detailView = document.getElementById('detail-view');
const backBtn = document.getElementById('back-btn');
const detailName = document.getElementById('detail-name');
const detailCategory = document.getElementById('detail-category');
const detailRarity = document.getElementById('detail-rarity');
const detailDesc = document.getElementById('detail-desc');
const detailTag = document.getElementById('detail-tag');
const detailUsage = document.getElementById('detail-usage');
const detailDecompose = document.getElementById('detail-decompose');
const detailObtain = document.getElementById('detail-obtain');
const detailTip = document.getElementById('detail-tip');
const detailIconImg = document.getElementById('detail-icon-img');
const usageList = document.getElementById('usage-list');
const decomposeList = document.getElementById('decompose-list');
const obtainList = document.getElementById('obtain-list');
const tipText = document.getElementById('tip-text');

// State
let currentFilter = 'all';
let searchQuery = '';

// Constants
const MIN_HEIGHT = 200;
const MAX_HEIGHT = 800;
const PADDING = 10; // panel margin

// Fixed heights of UI elements (approximate)
const HEADER_HEIGHT = 45;
const SEARCH_HEIGHT = 58;
const FILTERS_HEIGHT = 52;
const STATS_HEIGHT = 30;
const LEGEND_HEIGHT = 35;
const ITEM_HEIGHT = 53;
const DETAIL_HEADER_HEIGHT = 55;

// Send current content height to C#
function updateWindowHeight() {
  // Only resize when panel is visible
  if (panel.classList.contains('hidden')) {
    return;
  }

  requestAnimationFrame(() => {
    let height;

    if (!detailView.classList.contains('hidden')) {
      // Detail view - measure actual content height
      const detailContent = detailView.querySelector('.detail-content');
      const detailHeader = detailView.querySelector('.detail-header');
      const contentHeight = detailContent ? detailContent.scrollHeight : 300;
      const headerHeight = detailHeader ? detailHeader.offsetHeight : DETAIL_HEADER_HEIGHT;
      height = headerHeight + contentHeight + PADDING + 2; // +2 for borders
    } else {
      // List view - calculate based on item count
      const itemCount = list.children.length;
      const listHeight = itemCount * ITEM_HEIGHT;
      height = HEADER_HEIGHT + SEARCH_HEIGHT + FILTERS_HEIGHT + STATS_HEIGHT + listHeight + LEGEND_HEIGHT + PADDING;
    }

    // Cap at MAX_HEIGHT
    if (height > MAX_HEIGHT) {
      height = MAX_HEIGHT;
      if (!detailView.classList.contains('hidden')) {
        // Detail view - set max-height on detail-content
        const detailContent = detailView.querySelector('.detail-content');
        if (detailContent) {
          const availableHeight = MAX_HEIGHT - DETAIL_HEADER_HEIGHT - PADDING;
          detailContent.style.maxHeight = availableHeight + 'px';
        }
      } else {
        // List view - set max-height on list
        const availableListHeight = MAX_HEIGHT - HEADER_HEIGHT - SEARCH_HEIGHT - FILTERS_HEIGHT - STATS_HEIGHT - LEGEND_HEIGHT - PADDING;
        list.style.maxHeight = availableListHeight + 'px';
      }
    } else {
      list.style.maxHeight = '';
      const detailContent = detailView.querySelector('.detail-content');
      if (detailContent) {
        detailContent.style.maxHeight = '';
      }
    }

    height = Math.max(MIN_HEIGHT, height);
    postMessage('resize:' + height);
  });
}

// ========================================
// ITEM RENDERING
// ========================================

function getTagClass(tag) {
  const normalized = tag.toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '');

  if (normalized.includes('nechat')) return 'tag-nechat';
  if (normalized.includes('prodat')) return 'tag-prodat';
  if (normalized.includes('recyklovat')) return 'tag-recyklovat';
  if (normalized.includes('pouzit')) return 'tag-pouzit';
  return '';
}

function render() {
  list.replaceChildren();

  const filtered = items.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchQuery) ||
                          item.category.toLowerCase().includes(searchQuery) ||
                          item.desc.toLowerCase().includes(searchQuery);

    const matchesFilter = currentFilter === 'all' || item.tag === currentFilter;

    return matchesSearch && matchesFilter;
  });

  stats.textContent = 'Zobrazeno ' + filtered.length + ' z ' + items.length + ' itemů';

  if (filtered.length === 0) {
    const empty = document.createElement('li');
    empty.className = 'empty-state';

    const emptyIcon = document.createElement('div');
    emptyIcon.className = 'icon';
    emptyIcon.textContent = String.fromCodePoint(0x1F50D);

    const emptyText = document.createElement('div');
    emptyText.textContent = 'Žádné itemy nenalezeny';

    empty.appendChild(emptyIcon);
    empty.appendChild(emptyText);
    list.appendChild(empty);
    return;
  }

  filtered.forEach(item => {
    const li = document.createElement('li');
    li.className = 'item rarity-' + item.rarity;

    li.addEventListener('click', () => showDetail(item));

    const iconWrapperEl = document.createElement('div');
    iconWrapperEl.className = 'item-icon';
    const iconImg = document.createElement('img');
    iconImg.src = 'images/items/' + item.name + '.webp';
    iconImg.alt = item.name;
    iconImg.onerror = function() { this.style.display = 'none'; };
    iconWrapperEl.appendChild(iconImg);

    const left = document.createElement('div');
    left.className = 'item-left';

    const name = document.createElement('div');
    name.className = 'item-name';
    name.textContent = item.name;

    const meta = document.createElement('div');
    meta.className = 'item-meta';

    const category = document.createElement('span');
    category.className = 'item-category';
    category.textContent = item.category;

    const desc = document.createElement('span');
    desc.className = 'item-desc';
    desc.textContent = item.desc;

    meta.appendChild(category);
    meta.appendChild(desc);
    left.appendChild(name);
    left.appendChild(meta);

    const tag = document.createElement('span');
    tag.className = 'tag ' + getTagClass(item.tag);
    tag.textContent = item.tag;

    li.appendChild(iconWrapperEl);
    li.appendChild(left);
    li.appendChild(tag);
    list.appendChild(li);
  });

  updateWindowHeight();
}

// ========================================
// EVENT HANDLERS
// ========================================

search.addEventListener('input', (e) => {
  searchQuery = e.target.value.toLowerCase();
  render();
});

filterBtns.forEach(btn => {
  btn.addEventListener('click', () => {
    filterBtns.forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    currentFilter = btn.dataset.filter;
    render();
  });
});

// Back button
backBtn.addEventListener('click', () => {
  detailView.classList.add('hidden');
  listView.classList.remove('hidden');
  updateWindowHeight();
});

// Icon drag and click handling
let isDragging = false;
let clickStartTime = 0;

iconWrapper.addEventListener('mousedown', (e) => {
  if (e.button !== 0) return;
  isDragging = false;
  clickStartTime = Date.now();
});

iconWrapper.addEventListener('mousemove', (e) => {
  if (e.buttons !== 1) return;

  // If mouse moved and held for more than 100ms, start drag
  if (!isDragging && Date.now() - clickStartTime > 100) {
    isDragging = true;
    postMessage('startDrag');
  }
});

// Icon click - expand window (only if not dragging)
iconBtn.addEventListener('click', (e) => {
  if (isDragging) {
    isDragging = false;
    return;
  }
  iconWrapper.classList.add('hidden');
  panel.classList.remove('hidden');
  updateWindowHeight();
});

// Collapse button - minimize to icon
collapseBtn.addEventListener('click', (e) => {
  e.stopPropagation();
  postMessage('collapse');
  panel.classList.add('hidden');
  iconWrapper.classList.remove('hidden');
  // Reset to list view when collapsing
  detailView.classList.add('hidden');
  listView.classList.remove('hidden');
});

// Close button - quit app
closeBtn.addEventListener('click', (e) => {
  e.stopPropagation();
  postMessage('quit');
});

// Listen for messages from C# (toggle via Alt+I)
if (window.chrome && window.chrome.webview) {
  window.chrome.webview.addEventListener('message', (e) => {
    if (e.data === 'toggle_expand') {
      iconWrapper.classList.add('hidden');
      panel.classList.remove('hidden');
      updateWindowHeight();
    } else if (e.data === 'toggle_collapse') {
      panel.classList.add('hidden');
      iconWrapper.classList.remove('hidden');
      detailView.classList.add('hidden');
      listView.classList.remove('hidden');
    }
  });
}

// ========================================
// DETAIL VIEW
// ========================================

function createDetailRow(label, value, valueClass) {
  const row = document.createElement('div');
  row.className = 'detail-row';

  const labelSpan = document.createElement('span');
  labelSpan.className = 'label';
  labelSpan.textContent = label;

  const valueSpan = document.createElement('span');
  valueSpan.className = 'value' + (valueClass ? ' ' + valueClass : '');
  valueSpan.textContent = value;

  row.appendChild(labelSpan);
  row.appendChild(valueSpan);
  return row;
}

function fillList(listElement, items) {
  listElement.replaceChildren();
  items.forEach(text => {
    const li = document.createElement('li');
    li.textContent = text;
    listElement.appendChild(li);
  });
}

function showDetail(item) {
  postMessage('showDetail');
  listView.classList.add('hidden');
  detailView.classList.remove('hidden');

  detailIconImg.src = 'images/items/' + item.name + '.webp';
  detailIconImg.alt = item.name;
  detailIconImg.onerror = function() { this.style.display = 'none'; };
  detailIconImg.onload = function() { this.style.display = 'block'; };

  detailName.textContent = item.name;
  detailName.className = 'detail-rarity-' + item.rarity;

  detailCategory.replaceChildren();
  detailCategory.appendChild(createDetailRow('Kategorie:', item.category));

  const rarityNames = {
    legendary: 'Legendární',
    epic: 'Epický',
    rare: 'Vzácný',
    uncommon: 'Neobvyklý',
    common: 'Běžný'
  };
  detailRarity.replaceChildren();
  detailRarity.appendChild(createDetailRow('Vzácnost:', rarityNames[item.rarity] || item.rarity, 'detail-rarity-' + item.rarity));

  detailDesc.textContent = item.desc;

  detailTag.textContent = item.tag;
  detailTag.className = 'tag ' + getTagClass(item.tag);

  detailUsage.classList.add('hidden');
  detailDecompose.classList.add('hidden');
  detailObtain.classList.add('hidden');
  detailTip.classList.add('hidden');

  if (item.usedFor && item.usedFor.length > 0) {
    detailUsage.classList.remove('hidden');
    fillList(usageList, item.usedFor);
  }

  if (item.decomposesTo && item.decomposesTo.length > 0) {
    detailDecompose.classList.remove('hidden');
    fillList(decomposeList, item.decomposesTo);
  }

  if (item.obtainedFrom && item.obtainedFrom.length > 0) {
    detailObtain.classList.remove('hidden');
    fillList(obtainList, item.obtainedFrom);
  }

  if (item.tip) {
    detailTip.classList.remove('hidden');
    tipText.textContent = item.tip;
  }

  updateWindowHeight();
}

// ========================================
// INIT
// ========================================

async function init() {
  try {
    // Load items via fetch
    const response = await fetch('data.json');
    items = await response.json();

    render();
  } catch (error) {
    console.error('Init error:', error);
    const errorDiv = document.createElement('div');
    errorDiv.style.cssText = 'color:red;padding:20px;';
    errorDiv.textContent = 'Error: ' + error.message;
    document.body.appendChild(errorDiv);
  }
}

// Wait for DOM to be ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}
