import { convertFile } from '../services/markdown.js';
import { appState } from '../state/app-state.js';

const win = window.__TAURI__.window.getCurrentWindow();
const titlebarTitle = document.getElementById('titlebar-title');
const content = document.querySelector('#content');

function resolveRelativePath(currentFile, href) {
  const sep = currentFile.includes('\\') ? '\\' : '/';
  const dir = currentFile.split(sep).slice(0, -1).join(sep);
  const parts = [...dir.split(sep), ...href.split('/')];
  const resolved = [];
  for (const part of parts) {
    if (part === '..') resolved.pop();
    else if (part !== '.') resolved.push(part);
  }
  return resolved.join(sep);
}

function wireLinks(filePath, mode, sidebarEl) {
  content.querySelectorAll('a[href]').forEach(a => {
    const href = a.getAttribute('href');
    if (!href || href.startsWith('#')) return;

    if (/^https?:\/\//.test(href)) {
      a.setAttribute('target', '_blank');
      a.setAttribute('rel', 'noopener noreferrer');
      return;
    }

    a.addEventListener('click', async e => {
      e.preventDefault();
      const resolved = resolveRelativePath(filePath, href);
      await loadPage(resolved, mode, sidebarEl);
    });
  });
}

function addCopyButtons() {
  content.querySelectorAll('pre').forEach(pre => {
    if (pre.parentElement?.classList.contains('code-block')) return;

    const wrapper = document.createElement('div');
    wrapper.className = 'code-block';
    pre.parentNode.insertBefore(wrapper, pre);
    wrapper.appendChild(pre);

    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'copy-code-btn';
    btn.textContent = 'Copier';
    btn.addEventListener('click', async () => {
      const code = (pre.querySelector('code') ?? pre).textContent;
      try {
        await navigator.clipboard.writeText(code);
        btn.textContent = 'Copié !';
        btn.classList.add('copied');
      } catch {
        btn.textContent = 'Erreur';
      }
      setTimeout(() => {
        btn.textContent = 'Copier';
        btn.classList.remove('copied');
      }, 1500);
    });
    wrapper.appendChild(btn);
  });
}

export async function loadPage(filePath, mode, sidebarEl) {
  try {
    const html = await convertFile(filePath);
    appState.currentFile = filePath;
    content.innerHTML = html;
    addCopyButtons();

    const basename = filePath.split('/').pop().split('\\').pop();
    const title = basename.replace(/\.md$/i, '');
    await win.setTitle(title);
    titlebarTitle.textContent = title;

    if (mode === 'dir' || mode === 'file') {
      sidebarEl.querySelectorAll('a').forEach(a => {
        a.classList.toggle('active', a.dataset.path === filePath);
      });
      const active = sidebarEl.querySelector('a[data-path].active');
      if (active) {
        let el = active.parentElement;
        while (el && el !== sidebarEl) {
          if (el.tagName === 'DETAILS') el.open = true;
          el = el.parentElement;
        }
      }
    }

    wireLinks(filePath, mode, sidebarEl);
  } catch (err) {
    content.innerHTML = `<p class="error">Impossible de charger le fichier : ${err}</p>`;
  }
}
