// Hangar Browser Companion — Sidebar JS
// Works with both Chrome (chrome.*) and Firefox (browser.*) APIs.

const api = typeof browser !== 'undefined' ? browser : chrome;

let hangarToken = null;
let hangarPort  = null;
let credentials = [];

// ─── Boot ─────────────────────────────────────────────────────────────────────

async function init() {
  const session = await api.runtime.sendMessage({ type: 'GET_SESSION' });
  if (!session?.token) {
    showConnecting();
    setTimeout(init, 1200);
    return;
  }

  hangarToken = session.token;
  hangarPort  = session.port;

  setStatus(true, session.sectionTitle || 'Session');
  document.getElementById('section-title').textContent = session.sectionTitle || 'Hangar';

  await Promise.all([loadCredentials(), loadChecklists()]);
}

function showConnecting() {
  const list = document.getElementById('credentials-list');
  list.innerHTML = `
    <div class="connecting-state">
      <div class="spinner"></div>
      <span>Waiting for Hangar…</span>
    </div>`;
}

function setStatus(connected, label) {
  const dot  = document.getElementById('status-dot');
  const lbl  = document.getElementById('status-label');
  dot.className  = connected ? 'connected' : '';
  lbl.textContent = connected ? 'Isolated' : 'Connecting…';
}

// ─── Credentials ──────────────────────────────────────────────────────────────

async function loadCredentials() {
  try {
    const res  = await fetch(`http://127.0.0.1:${hangarPort}/session/${hangarToken}/credentials`);
    credentials = await res.json();
    renderCredentials(credentials);
  } catch {
    credentials = [];
    renderCredentials([]);
  }
}

function renderCredentials(creds) {
  const list    = document.getElementById('credentials-list');
  const fillAll = document.getElementById('btn-fill-all');

  list.innerHTML = '';

  if (!creds.length) {
    fillAll.disabled = true;
    list.innerHTML = `
      <div class="empty-state">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
        </svg>
        <span>No key-value credentials<br>in this section</span>
      </div>`;
    return;
  }

  fillAll.disabled = false;
  for (const cred of creds) {
    list.appendChild(buildCredRow(cred));
  }
}

function buildCredRow(cred) {
  const row = el('div', 'credential-row');

  const info  = el('div', 'credential-info');
  const label = el('div', 'credential-label', cred.label);
  const val   = el('div', 'credential-value');
  val.textContent    = cred.isSensitive ? '••••••••••' : (cred.value || '(empty)');
  val.dataset.shown  = 'false';
  label.title = 'Click to copy key';
  val.title   = 'Click to copy value';
  label.addEventListener('click', () => copyText(label, cred.label));
  val.addEventListener('click', () => copyText(val, cred.value || ''));
  info.append(label, val);

  const actions = el('div', 'credential-actions');

  if (cred.isSensitive) {
    const eyeBtn = iconBtn(eyeSVG(), 'Reveal');
    eyeBtn.addEventListener('click', () => {
      const shown = val.dataset.shown === 'true';
      val.textContent    = shown ? '••••••••••' : (cred.value || '(empty)');
      val.dataset.shown  = shown ? 'false' : 'true';
      eyeBtn.innerHTML   = shown ? eyeSVG() : eyeSlashSVG();
    });
    actions.appendChild(eyeBtn);
  }

  const copyBtn = iconBtn(copySVG(), 'Copy to clipboard');
  copyBtn.addEventListener('click', async () => {
    await navigator.clipboard.writeText(cred.value);
    copyBtn.innerHTML = checkSVG();
    copyBtn.classList.add('success');
    setTimeout(() => { copyBtn.innerHTML = copySVG(); copyBtn.classList.remove('success'); }, 1500);
  });
  actions.appendChild(copyBtn);

  const fillBtn = iconBtn(arrowSVG(), 'Fill into page');
  fillBtn.classList.add('fill-btn');
  fillBtn.addEventListener('click', () => {
    api.runtime.sendMessage({ type: 'FILL_FIELD', label: cred.label, value: cred.value });
  });
  actions.appendChild(fillBtn);

  row.append(info, actions);
  return row;
}

async function copyText(node, text) {
  await navigator.clipboard.writeText(text);
  const original = node.textContent;
  node.textContent = 'Copied';
  node.classList.add('success');
  setTimeout(() => {
    node.textContent = original;
    node.classList.remove('success');
  }, 900);
}

// ─── Checklists ───────────────────────────────────────────────────────────────

async function loadChecklists() {
  try {
    const res    = await fetch(`http://127.0.0.1:${hangarPort}/session/${hangarToken}/checklists`);
    const lists  = await res.json();
    renderChecklists(lists);
  } catch {
    renderChecklists([]);
  }
}

function renderChecklists(lists) {
  const section  = document.getElementById('checklists-section');
  const divider  = document.getElementById('checklist-divider');
  const container = document.getElementById('checklists-list');

  if (!lists.length) {
    section.style.display = 'none';
    divider.style.display  = 'none';
    return;
  }

  section.style.display = 'flex';
  divider.style.display  = 'block';
  container.innerHTML   = '';

  for (const cl of lists) {
    container.appendChild(buildChecklistCard(cl));
  }
}

function buildChecklistCard(cl) {
  const card    = el('div', 'checklist-card');
  const header  = el('div', 'checklist-card-header');
  const chevron = el('span', 'checklist-chevron', '▾');
  const title   = el('span', 'checklist-title', cl.title);

  const checked = cl.entries.filter(e => e.checked).length;
  const count   = el('span', 'checklist-count', `${checked}/${cl.entries.length}`);

  header.append(chevron, title, count);
  card.appendChild(header);

  const entries = el('div', 'checklist-entries');
  for (const entry of cl.entries) {
    entries.appendChild(buildEntryRow(entry, cl.id, count, cl.entries));
  }
  card.appendChild(entries);

  // Collapse/expand
  header.addEventListener('click', () => {
    const collapsed = chevron.classList.toggle('collapsed');
    entries.style.display = collapsed ? 'none' : '';
  });

  return card;
}

function buildEntryRow(entry, clID, countEl, allEntries) {
  const row      = el('div', 'checklist-entry');
  const checkbox = el('div', 'entry-checkbox' + (entry.checked ? ' checked' : ''));
  const label    = el('span', 'entry-label' + (entry.checked ? ' checked' : ''), entry.title);

  row.append(checkbox, label);

  row.addEventListener('click', async () => {
    entry.checked = !entry.checked;
    checkbox.className = 'entry-checkbox' + (entry.checked ? ' checked' : '');
    label.className    = 'entry-label'    + (entry.checked ? ' checked' : '');

    // Update count badge
    const done = allEntries.filter(e => e.checked).length;
    countEl.textContent = `${done}/${allEntries.length}`;

    // Notify Hangar
    try {
      await fetch(
        `http://127.0.0.1:${hangarPort}/session/${hangarToken}/checklist/${clID}/toggle/${entry.id}`,
        { method: 'POST' }
      );
    } catch { /* offline — UI already updated optimistically */ }
  });

  return row;
}

// ─── Capture buttons ──────────────────────────────────────────────────────────

document.getElementById('btn-voice').addEventListener('click', () => {
  fetch(`http://127.0.0.1:${hangarPort}/session/${hangarToken}/capture`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ type: 'voice' })
  }).catch(() => {});
});

document.getElementById('btn-text').addEventListener('click', () => {
  fetch(`http://127.0.0.1:${hangarPort}/session/${hangarToken}/capture`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ type: 'text' })
  }).catch(() => {});
});

document.getElementById('btn-fill-all').addEventListener('click', () => {
  api.runtime.sendMessage({ type: 'FILL_ALL', credentials });
});

// ─── Utility ──────────────────────────────────────────────────────────────────

function el(tag, className, text) {
  const node = document.createElement(tag);
  if (className) node.className = className;
  if (text !== undefined) node.textContent = text;
  return node;
}

function iconBtn(svgContent, title) {
  const btn = document.createElement('button');
  btn.className = 'icon-btn';
  btn.title = title;
  btn.innerHTML = svgContent;
  return btn;
}

const svgAttrs = 'width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';

function eyeSVG() {
  return `<svg ${svgAttrs}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`;
}
function eyeSlashSVG() {
  return `<svg ${svgAttrs}><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`;
}
function copySVG() {
  return `<svg ${svgAttrs}><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`;
}
function checkSVG() {
  return `<svg ${svgAttrs}><polyline points="20 6 9 17 4 12"/></svg>`;
}
function arrowSVG() {
  return `<svg ${svgAttrs}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>`;
}

// ─── Start ────────────────────────────────────────────────────────────────────

init();
