// projects.js
const PROJECT_BASE = "https://chatgpt.com/g";
const MAKE_URL = (id) => `${PROJECT_BASE}/${id}/project`;

const TITLES_KEY = "projectTitles";
const LIST_KEY   = "projects";

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

// ===== Local titles 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 });
}

// ===== Fetch list (server → fallback local) =====
async function fetchList(){
  // از BG می‌گیریم تا به سرور وصل شود
  const res = await new Promise((resolve) => {
    chrome.runtime.sendMessage({ action: 'getProjects' }, (ans) => {
      if (chrome.runtime.lastError) {
        resolve({ ok:false, data:[] });
      } else {
        resolve({ ok: !!ans?.success, data: ans?.data || [] });
      }
    });
  });
  if (res.ok && res.data.length) return res.data;

  // فال‌بک لوکال
  const store = await chrome.storage.local.get({ [LIST_KEY]: [] });
  return store[LIST_KEY] || [];
}

// ===== Edit Title modal =====
function wireBackdropClose(){
  const backdrop = $('editTitleBackdrop');
  backdrop.addEventListener('click', (e)=>{
    if (e.target === backdrop) backdrop.style.display = 'none';
  });
}
function openEditModal(id, currentTitle, onSaved){
  const backdrop  = $('editTitleBackdrop');
  const input     = $('editTitleInput');
  const saveBtn   = $('editTitleSaveBtn');
  const cancelBtn = $('editCancel');

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

  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 onKey = (e)=>{
    if (e.key === 'Enter') onSave();
    if (e.key === 'Escape') close();
  };
  const onCancel = ()=> close();

  function cleanup(){
    saveBtn.removeEventListener('click', onSave);
    cancelBtn.removeEventListener('click', onCancel);
    input.removeEventListener('keydown', onKey);
  }

  saveBtn.addEventListener('click', onSave);
  cancelBtn.addEventListener('click', onCancel);
  input.addEventListener('keydown', onKey);
}

// ===== 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 wireTop(){
  $('refresh').onclick = async ()=>{
    $('refresh').disabled = true;
    try { await loadData(); render(CURRENT_ROWS); }
    finally { $('refresh').disabled = false; }
  };
}

// ===== Load data =====
async function loadData(){
  const ids = await fetchList();
  const titles = await getTitlesMap();
  CURRENT_ROWS = ids.map(id => ({ id, title: titles[id]?.title || "" }));
}

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

  wireBackdropClose();
  wireTop();
  wireSearch();

  await loadData();
  render(CURRENT_ROWS);
}
init();
