import '../../styles/panel.css';
import { getServerUrl, setServerUrl, fetchSessions, checkServerHealth } from '../../lib/config';
import { getChatHistory } from '../../lib/api';

const $ = (s) => document.querySelector(s);
const $$ = (s) => document.querySelectorAll(s);

const $serverStatus = $('#server-status');
const $sessionCount = $('#session-count');
const $errorCount = $('#error-count');
const $sessionsList = $('#sessions-list');
const $btnDashboard = $('#btn-dashboard');
const $serverUrl = $('#server-url');
const $btnSaveUrl = $('#btn-save-url');
const $chatOffline = $('#chat-offline');
const $chatArea = $('#chat-area');
const $chatFeed = $('#chat-feed');
const $btnInject = $('#btn-inject-session');
const $injectStatus = $('#inject-status');
const $toggleAutoInject = $('#toggle-auto-inject');

let serverOnline = false;
let lastMessageCount = -1;
let pollInterval = null;

function dot(color) {
  return `<span class="dot dot-${color}"></span>`;
}

function renderSessions(sessions) {
  if (sessions.length === 0) {
    $sessionsList.innerHTML = '';
    return;
  }
  $sessionsList.innerHTML = `
    <div class="status-card" style="margin-top:12px">
      <div style="font-size:11px;color:var(--text-secondary);margin-bottom:8px;text-transform:uppercase;letter-spacing:0.5px">
        Connected tabs
      </div>
      ${sessions.map((s) => `
        <div class="status-row">
          <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px" title="${s.url}">
            ${s.title || s.url || s.id}
          </span>
          <span style="font-size:10px;color:var(--text-secondary);font-family:var(--font-mono)">
            ${s.id.slice(0, 8)}
          </span>
        </div>
      `).join('')}
    </div>
  `;
}

function escapeHtml(text) {
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function formatText(text) {
  let html = text
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  html = html
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')
    .replace(/^### (.+)$/gm, '<h4>$1</h4>')
    .replace(/^## (.+)$/gm, '<h3>$1</h3>')
    .replace(/^# (.+)$/gm, '<h2>$1</h2>')
    .replace(/^\s*[-*] (.+)$/gm, '<div class="chat-bullet">• $1</div>')
    .replace(/^\s*(\d+)[.)] (.+)$/gm, '<div class="chat-step"><span class="chat-step-num">$1</span> $2</div>')
    .replace(/\n/g, '<br/>');
  html = html
    .replace(/<br\/>\s*<br\/>/g, '<br/>')
    .replace(/<br\/>\s*(<h[234]|<div class="chat-)/g, '$1')
    .replace(/(<\/h[234]|<\/div>)\s*<br\/>/g, '$1');
  return html;
}

function renderContent(text) {
  const parts = [];
  const codeBlockRegex = /(```[\s\S]*?```)/g;
  let match;
  let lastIndex = 0;
  while ((match = codeBlockRegex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      parts.push({ type: 'text', content: text.slice(lastIndex, match.index) });
    }
    const full = match[1];
    const firstNewline = full.indexOf('\n');
    const lang = firstNewline > -1 ? full.slice(3, firstNewline).trim() : '';
    const code = firstNewline > -1 ? full.slice(firstNewline + 1, -3) : full.slice(3, -3);
    parts.push({ type: 'code', lang, content: code });
    lastIndex = match.index + full.length;
  }
  if (lastIndex < text.length) {
    parts.push({ type: 'text', content: text.slice(lastIndex) });
  }
  return parts;
}

function createMessageEl(msg) {
  const el = document.createElement('div');
  el.className = `chat-msg ${msg.role}`;

  if (msg.role === 'system') {
    el.innerHTML = `<div class="chat-system-dot"></div><div class="chat-system-text">${escapeHtml(msg.content)}</div>`;
    return el;
  }

  const isUser = msg.role === 'user';
  const avatar = isUser ? '★' : '◆';
  const label = isUser ? 'CDT' : 'GEN';

  let displayContent = msg.content;
  let parsedToolCalls = null;
  let parsedSegments = null;

  try {
    const parsed = JSON.parse(msg.content);
    if (parsed && Array.isArray(parsed.segments)) {
      parsedSegments = parsed.segments;
      displayContent = parsed.content || '';
    } else if (parsed && Array.isArray(parsed.tool_calls)) {
      parsedToolCalls = parsed.tool_calls;
      displayContent = parsed.content || '';
    }
  } catch {}

  const cleanContent = displayContent.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');

  let bodyHtml = '';
  if (parsedSegments) {
    bodyHtml = parsedSegments.map((seg) => {
      if (seg.type === 'text' && seg.content) {
        const c = seg.content.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');
        if (!c) return '';
        return renderContent(c).map((p) => {
          if (p.type === 'code') {
            return `<div class="chat-code-block"><div class="chat-code-header"><span class="chat-code-lang">${p.lang || ''}</span><button class="chat-copy-btn" data-code="${encodeURIComponent(p.content)}">Copy</button></div><pre><code>${escapeHtml(p.content)}</code></pre></div>`;
          }
          return `<span>${formatText(p.content)}</span>`;
        }).join('');
      }
      if (seg.type === 'tool') {
        const name = seg.call?.name || 'tool';
        const icon = { terminal: '⌨', crush_run: '⚡', read_file: '📄', list_files: '📁', search_files: '🔍', web_fetch: '🌐' }[name] || '🔧';
        const done = seg.result;
        const isErr = done && done.is_error;
        const preview = (() => {
          try {
            const args = typeof seg.call.args === 'string' ? JSON.parse(seg.call.args) : seg.call.args;
            return args.command || args.task || args.path || args.url || JSON.stringify(args).slice(0, 60);
          } catch { return ''; }
        })();
        const resultText = done ? (done.content || '').slice(0, 500) : '';
        return `<div class="chat-tool ${done ? 'done' : 'running'} ${isErr ? 'error' : ''}"><div class="chat-tool-header"><span class="chat-tool-icon">${icon}</span><span>${name}</span>${done ? `<span class="chat-tool-status ${isErr ? 'err' : 'ok'}">${isErr ? '✗' : '✓'}</span>` : '<span class="chat-dots"><span></span><span></span><span></span></span>'}</div>${preview ? `<div class="chat-tool-args">${escapeHtml(preview)}</div>` : ''}${resultText ? `<pre class="chat-tool-result">${escapeHtml(resultText)}</pre>` : ''}</div>`;
      }
      return '';
    }).join('');
  } else {
    if (cleanContent) {
      bodyHtml = renderContent(cleanContent).map((p) => {
        if (p.type === 'code') {
          return `<div class="chat-code-block"><div class="chat-code-header"><span class="chat-code-lang">${p.lang || ''}</span><button class="chat-copy-btn" data-code="${encodeURIComponent(p.content)}">Copy</button></div><pre><code>${escapeHtml(p.content)}</code></pre></div>`;
        }
        return `<span>${formatText(p.content)}</span>`;
      }).join('');
    }
    if (parsedToolCalls && parsedToolCalls.length > 0) {
      bodyHtml = parsedToolCalls.map((tc) => {
        const name = tc.name || 'tool';
        const icon = { terminal: '⌨', crush_run: '⚡', read_file: '📄', web_fetch: '🌐' }[name] || '🔧';
        return `<div class="chat-tool done"><div class="chat-tool-header"><span class="chat-tool-icon">${icon}</span><span>${name}</span><span class="chat-tool-status ok">✓</span></div></div>`;
      }).join('') + bodyHtml;
    }
  }

  if (!bodyHtml) bodyHtml = '<span class="chat-dots"><span></span><span></span><span></span></span>';

  el.innerHTML = `
    <div class="chat-avatar ${isUser ? 'user' : 'ai'}">${avatar}</div>
    <div class="chat-body">
      <div class="chat-header"><span class="chat-badge" style="color:${isUser ? '#FFD740' : '#FF9100'};border-color:${isUser ? '#FFD740' : '#FF9100'}">${label}</span></div>
      <div class="chat-content">${bodyHtml}</div>
    </div>
  `;
  return el;
}

function scrollToBottom() {
  requestAnimationFrame(() => {
    $chatFeed.scrollTop = $chatFeed.scrollHeight;
  });
}

function switchTab(tabName) {
  $$('.tab').forEach((t) => t.classList.toggle('active', t.dataset.tab === tabName));
  $$('.tab-content').forEach((s) => s.classList.toggle('active', s.id === `tab-${tabName}`));
  if (tabName === 'chat' && serverOnline) {
    pollStudio();
  }
}

function updateChatVisibility() {
  if (serverOnline) {
    $chatOffline.style.display = 'none';
    $chatArea.style.display = 'flex';
  } else {
    $chatOffline.style.display = 'flex';
    $chatArea.style.display = 'none';
  }
}

async function pollStudio() {
  try {
    const data = await getChatHistory();
    const msgs = data.messages || [];
    if (msgs.length !== lastMessageCount) {
      lastMessageCount = msgs.length;
      $chatFeed.innerHTML = '';
      msgs.forEach((msg) => {
        $chatFeed.appendChild(createMessageEl(msg));
      });
      scrollToBottom();
    }
  } catch {}
}

function injectSessionScript() {
  $injectStatus.style.display = 'block';
  $injectStatus.className = 'inject-status';
  $injectStatus.textContent = 'Injection en cours…';

  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (!tabs || !tabs[0]) {
      $injectStatus.textContent = 'Erreur: aucun onglet actif';
      $injectStatus.classList.add('inject-error');
      return;
    }
    const tabId = tabs[0].id;

    chrome.scripting.executeScript({
      target: { tabId },
      func: () => {
        if (window.__muyueExtension) {
          return 'already_injected';
        }
        window.__muyueExtension = true;
        return 'fresh_inject';
      },
    }, (results) => {
      if (chrome.runtime.lastError) {
        $injectStatus.textContent = 'Erreur: ' + chrome.runtime.lastError.message;
        $injectStatus.classList.add('inject-error');
        return;
      }

      const status = results?.[0]?.result;

      if (status === 'already_injected') {
        $injectStatus.textContent = '✓ Script déjà injecté dans cette page';
        $injectStatus.classList.add('inject-success');
      } else {
        chrome.tabs.reload(tabId, {}, () => {
          $injectStatus.textContent = '✓ Page rechargée avec le script de session';
          $injectStatus.classList.add('inject-success');
        });
      }

      setTimeout(() => {
        $injectStatus.style.display = 'none';
      }, 3000);
    });
  });
}

async function loadAutoInjectSetting() {
  const result = await chrome.storage.local.get('muyue_auto_inject');
  $toggleAutoInject.checked = !!result.muyue_auto_inject;
}

async function saveAutoInjectSetting(enabled) {
  await chrome.storage.local.set({ muyue_auto_inject: enabled });
}

$$('.tab').forEach((tab) => {
  tab.addEventListener('click', () => switchTab(tab.dataset.tab));
});

$chatFeed.addEventListener('click', (e) => {
  const btn = e.target.closest('.chat-copy-btn');
  if (btn) {
    navigator.clipboard.writeText(decodeURIComponent(btn.dataset.code));
    const orig = btn.textContent;
    btn.textContent = 'Copied!';
    setTimeout(() => { btn.textContent = orig; }, 1200);
  }
});

$btnInject.addEventListener('click', injectSessionScript);

$toggleAutoInject.addEventListener('change', () => {
  saveAutoInjectSetting($toggleAutoInject.checked);
});

$btnSaveUrl.addEventListener('click', async () => {
  const url = $serverUrl.value.trim().replace(/\/$/, '');
  if (url) {
    await setServerUrl(url);
    refresh();
  }
});

async function refresh() {
  const url = await getServerUrl();
  $serverUrl.value = url;
  $btnDashboard.href = url;

  try {
    const sessions = await fetchSessions();
    serverOnline = true;
    $serverStatus.innerHTML = `${dot('green')} Online`;
    $sessionCount.textContent = sessions.length;
    renderSessions(sessions);
  } catch {
    serverOnline = false;
    $serverStatus.innerHTML = `${dot('red')} Offline`;
    $sessionCount.textContent = '—';
    $sessionsList.innerHTML = '';
  }

  updateChatVisibility();

  chrome.runtime.sendMessage({ type: 'get_state' }, (state) => {
    if (chrome.runtime.lastError || !state) return;
    $errorCount.textContent = state.errorCount || 0;
  });
}

loadAutoInjectSetting();
refresh();

if (pollInterval) clearInterval(pollInterval);
pollInterval = setInterval(() => {
  refresh();
  if (serverOnline) pollStudio();
}, 3000);
