// conversations.js
const CHAT_BASE = "https://chatgpt.com";
const MAKE_URL  = (id) => `${CHAT_BASE}/c/${id}`;
const TITLES_KEY = "chatTitles";
const LIST_KEY   = "conversations";

const $ = (id) => document.getElementById(id);

// ===== titles local cache =====
async function getTitlesMap(){
  const s = await chrome.storage.local.get({ [TITLES_KEY]: {} });
  return s[TITLES_KEY] || {};
}
async function setTitle(id, title){
  const map = await getTitlesMap();
  map[id] = { title, ts: Date.now() };
  await chrome.storage.local.set({ [TITLES_KEY]: map });
}
async function getTitle(id){
  const m = await getTitlesMap();
  return m[id]?.title || "";
}

// ===== fetch conversations (server->bg fallback local) =====
async function fetchList(){
  const server = await new Promise((resolve) => {
    chrome.runtime.sendMessage({ action: 'getConversations' }, (res) => {
      if (chrome.runtime.lastError) return resolve({ ok:false, data:[] });
      resolve({ ok: !!res?.success, data: res?.data || [] });
    });
  });
  if (server.ok && server.data.length) return server.data;

  const store = await chrome.storage.local.get({ [LIST_KEY]: [] });
  return store[LIST_KEY] || [];
}

// ===== page modal (already in HTML) helpers =====
function openEditModal(id, currentTitle, onSaved){
  const backdrop = $("editTitleBackdrop");
  const input    = $("editTitleInput");
  const saveBtn  = $("editTitleSaveBtn");
  const cancel   = $("editCancel");

  input.value = currentTitle || "";
  backdrop.style.display = "flex";
  setTimeout(() => { input.focus(); input.select(); }, 0);

  const close = () => { backdrop.style.display = "none"; cleanup(); };
  const onSave = async () => {
    saveBtn.disabled = true;
    await setTitle(id, input.value.trim());
    saveBtn.disabled = false;
    close();
    onSaved?.(input.value.trim());
  };
  const onCancel = () => close();
  const onKey = (e) => {
    if (e.key === "Enter") onSave();
    if (e.key === "Escape") onCancel();
  };
  function cleanup(){
    saveBtn.removeEventListener("click", onSave);
    cancel.removeEventListener("click", onCancel);
    input.removeEventListener("keydown", onKey);
    backdrop.removeEventListener("click", backdropClick);
  }
  function backdropClick(e){
    if (e.target === backdrop) onCancel();
  }

  saveBtn.addEventListener("click", onSave);
  cancel.addEventListener("click", onCancel);
  input.addEventListener("keydown", onKey);
  backdrop.addEventListener("click", backdropClick);
}

// ===== render =====
let CURRENT_ROWS = []; // [{id,title}]
function render(items){
  const list  = $('list');
  const empty = $('empty');
  const count = $('count');

  list.innerHTML = '';
  count.textContent = (items?.length || 0).toLocaleString('fa-IR');

  if (!items || items.length === 0){
    empty.style.display = 'block';
    return;
  }
  empty.style.display = 'none';

  for(const item of items){
    const { id, title } = item;

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

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

    const titleEl = document.createElement('div');
    titleEl.className = 'cid';
    titleEl.textContent = title || id;

    const url = document.createElement('div');
    url.className = 'url';
    url.textContent = MAKE_URL(id);

    left.appendChild(titleEl); left.appendChild(url);

    const actions = document.createElement('div');
    actions.className = 'actions';

    const openBtn = document.createElement('button');
    openBtn.className = 'btn btn-primary';
    openBtn.textContent = 'باز کردن';
    openBtn.onclick = () => chrome.tabs.create({ url: MAKE_URL(id) });

    const copyBtn = document.createElement('button');
    copyBtn.className = 'btn btn-ghost';
    copyBtn.textContent = 'کپی لینک';
    copyBtn.onclick = async () => {
      await navigator.clipboard.writeText(MAKE_URL(id));
      copyBtn.textContent = 'کپی شد ✔';
      setTimeout(()=> copyBtn.textContent='کپی لینک', 1200);
    };

    const editBtn = document.createElement('button');
    editBtn.className = 'btn btn-ghost';
    editBtn.textContent = 'ویرایش عنوان';
    editBtn.onclick = () => {
      openEditModal(id, title, (newTitle)=>{
        titleEl.textContent = newTitle || id;
        const idx = CURRENT_ROWS.findIndex(x => x.id === id);
        if (idx >= 0) CURRENT_ROWS[idx].title = newTitle || "";
      });
    };

    actions.appendChild(openBtn);
    actions.appendChild(copyBtn);
    actions.appendChild(editBtn);

    row.appendChild(left);
    row.appendChild(actions);
    list.appendChild(row);
  }
}

// ===== search =====
function wireSearch(){
  const q = $('q');
  q.addEventListener('input', ()=>{
    const term = q.value.trim().toLowerCase();
    if (!term){ render(CURRENT_ROWS); return; }
    const filtered = CURRENT_ROWS.filter(x =>
      x.id.toLowerCase().includes(term) ||
      (x.title && x.title.toLowerCase().includes(term))
    );
    render(filtered);
  });
}

// ===== top buttons =====
function wireTopButtons(){
  $('openChatGPT').onclick = ()=> chrome.tabs.create({ url: CHAT_BASE });

  $('refresh').onclick = async ()=>{
    $('refresh').disabled = true;
    try { await loadDataAndRender(); } finally { $('refresh').disabled = false; }
  };
}

// ===== load & boot =====
async function loadDataAndRender(){
  const ids = await fetchList();
  const tmap = await getTitlesMap();
  CURRENT_ROWS = ids.map(id => ({ id, title: tmap[id]?.title || "" }));
  render(CURRENT_ROWS);
}

async function init(){
  chrome.storage.local.get(['userInfo','userToken'], ({userInfo, userToken})=>{
    const meta = $('meta');
    if (userToken){
      meta.textContent = `توکن فعال: ${userToken} — کاربر: ${userInfo?.username || '—'}`;
    } else {
      meta.textContent = 'توکن فعالی تنظیم نشده است.';
    }
  });

  wireTopButtons();
  wireSearch();
  await loadDataAndRender();
}

init();
