// content-save-button.js
(function () {
  if (window.__chatgpt_save_btn_injected__) return;
  window.__chatgpt_save_btn_injected__ = true;

  const POS_KEY = "gpt_save_btn_pos";
  const CHAT_RE = /\/c\/([a-z0-9\-]+)/i;

  // ---------- utils ----------
  const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
  const loadPos = () => { try { return JSON.parse(localStorage.getItem(POS_KEY) || "null"); } catch { return null; } };
  const savePos = (style) => {
    try {
      const vw = window.innerWidth, vh = window.innerHeight;
      const b = parseFloat(style.bottom || "24");
      const r = parseFloat(style.right  || "24");
      localStorage.setItem(POS_KEY, JSON.stringify({
        bottomPct: clamp((b / vh) * 100, 0, 100),
        rightPct:  clamp((r / vw) * 100, 0, 100),
      }));
    } catch {}
  };
  const applyPos = (btn) => {
    const pos = loadPos();
    if (pos && typeof pos.bottomPct === "number" && typeof pos.rightPct === "number") {
      btn.style.bottom = `${pos.bottomPct}vh`;
      const vw = window.innerWidth;
      btn.style.right = `${(pos.rightPct / 100) * vw}px`;
    } else {
      btn.style.bottom = "24px";
      btn.style.right  = "24px";
    }
  };

  // ---------- styles for modal ----------
  const STYLE_ID = "gpt-save-title-style";
  if (!document.getElementById(STYLE_ID)) {
    const style = document.createElement("style");
    style.id = STYLE_ID;
    style.textContent = `
      .sbm-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;z-index:2147483647;align-items:center;justify-content:center}
      .sbm-modal{width:min(520px,calc(100vw - 32px));box-sizing:border-box;border-radius:14px;background:#0b1215;color:#d6f4f1;
                 box-shadow:0 20px 60px rgba(0,0,0,.35);padding:16px;font-family:inherit;direction:rtl}
      .sbm-modal h3{margin:0 0 10px 0;font-size:15px}
      .sbm-modal .sbm-desc{font-size:12px;color:#89c9c4;margin-bottom:10px}
      .sbm-input{width:100%;padding:10px 12px;border-radius:10px;border:1px solid #134e4a;background:#0e1a1d;
                 color:#e6fffb;caret-color:#e6fffb;outline:none}
      .sbm-input::placeholder{color:#6aa9a3}
      .sbm-row{display:flex;gap:8px;justify-content:flex-end;margin-top:12px}
      .sbm-btn{border:none;border-radius:10px;padding:8px 12px;cursor:pointer;font-weight:600}
      .sbm-primary{background:#0d6efd;color:#fff}
      .sbm-ghost{background:#0f172a;color:#e2f7f4;border:1px solid #134e4a}
      .sbm-btn:disabled{opacity:.6;cursor:not-allowed}
    `;
    document.head.appendChild(style);
  }

  // ---------- build modal once ----------
  const backdrop = document.createElement("div");
  backdrop.className = "sbm-backdrop";
  const box = document.createElement("div");
  box.className = "sbm-modal";
  box.innerHTML = `
    <h3>ذخیره عنوان چت</h3>
    <div class="sbm-desc">عنوان فقط در افزونه‌ی شما ذخیره می‌شود و به سرور ChatGPT ارسال نمی‌گردد.</div>
    <input id="sbmInput" class="sbm-input" placeholder="مثل: برنامه‌ریزی سفر تابستان">
    <div class="sbm-row">
      <button id="sbmCancel" class="sbm-btn sbm-ghost">انصراف</button>
      <button id="sbmSave"   class="sbm-btn sbm-primary">ذخیره</button>
    </div>
  `;
  backdrop.appendChild(box);
  document.documentElement.appendChild(backdrop);
  const inputEl  = () => document.getElementById("sbmInput");
  const cancelEl = () => document.getElementById("sbmCancel");
  const saveEl   = () => document.getElementById("sbmSave");

  function openSaveTitle(conversationId) {
    const input = inputEl();
    backdrop.style.display = "flex";
    input.value = "";
    setTimeout(() => { input.focus(); }, 0);

    const close = () => { backdrop.style.display = "none"; cleanup(); };
    const onCancel = () => close();
    const onSave = async () => {
      const title = input.value.trim();
      try {
        saveEl().disabled = true;
        const st = await chrome.storage.local.get({ chatTitles: {} });
        st.chatTitles[conversationId] = { title, ts: Date.now() };
        await chrome.storage.local.set({ chatTitles: st.chatTitles });
      } finally {
        saveEl().disabled = false;
        close();
      }
    };
    const onKey = (e) => {
      if (e.key === "Enter") onSave();
      if (e.key === "Escape") onCancel();
    };
    function cleanup() {
      cancelEl().removeEventListener("click", onCancel);
      saveEl().removeEventListener("click", onSave);
      input.removeEventListener("keydown", onKey);
    }
    cancelEl().addEventListener("click", onCancel);
    saveEl().addEventListener("click", onSave);
    input.addEventListener("keydown", onKey);
  }

  // ---------- floating button (built but attach after permission) ----------
  const btn = document.createElement("button");
  btn.textContent = "ذخیره لینک چت";
  Object.assign(btn.style, {
    position: "fixed",
    zIndex: "2147483647",
    padding: "10px 14px",
    borderRadius: "9999px",
    border: "none",
    fontWeight: "700",
    cursor: "grab",
    boxShadow: "0 6px 20px rgba(0,0,0,.18)",
    background: "#0d6efd",
    color: "#fff",
    fontFamily: "inherit",
    userSelect: "none",
    display: "none",
  });
  applyPos(btn);

  // drag
  let dragging = false, startX = 0, startY = 0, startRight = 0, startBottom = 0, moved = false;
  const onPointerDown = (e) => {
    dragging = true; moved = false; btn.style.cursor = "grabbing";
    const vw = window.innerWidth, vh = window.innerHeight;
    const rect = btn.getBoundingClientRect();
    startRight  = vw - rect.right;
    startBottom = vh - rect.bottom;
    startX = e.clientX ?? (e.touches ? e.touches[0].clientX : 0);
    startY = e.clientY ?? (e.touches ? e.touches[0].clientY : 0);
    e.preventDefault();
  };
  const onPointerMove = (e) => {
    if (!dragging) return;
    const clientX = e.clientX ?? (e.touches ? e.touches[0].clientX : 0);
    const clientY = e.clientY ?? (e.touches ? e.touches[0].clientY : 0);
    const dx = clientX - startX, dy = clientY - startY;
    if (Math.abs(dx) + Math.abs(dy) > 2) moved = true;
    const vw = window.innerWidth, vh = window.innerHeight;
    const rect = btn.getBoundingClientRect();
    const newRight  = clamp(startRight  - dx, 8, vw - rect.width  - 8);
    const newBottom = clamp(startBottom - dy, 8, vh - rect.height - 8);
    btn.style.right  = `${newRight}px`;
    btn.style.bottom = `${newBottom}px`;
  };
  const onPointerUp = () => { if (!dragging) return; dragging = false; btn.style.cursor = "grab"; savePos(btn.style); };
  btn.addEventListener("mousedown", onPointerDown);
  btn.addEventListener("touchstart", onPointerDown, { passive: false });
  window.addEventListener("mousemove", onPointerMove, { passive: false });
  window.addEventListener("touchmove", onPointerMove, { passive: false });
  window.addEventListener("mouseup", onPointerUp);
  window.addEventListener("touchend", onPointerUp);

  // click
  btn.addEventListener("click", (e) => {
    if (moved) { e.preventDefault(); return; }
    const m  = location.pathname.match(CHAT_RE);
    const id = m ? m[1] : null;

    btn.disabled = true; btn.textContent = "در حال ذخیره…";
    chrome.runtime.sendMessage(
      { action: "saveCurrentChat", conversationId: id, chatUrl: location.href },
      (res) => {
        btn.disabled = false;
        if (chrome.runtime.lastError || !res?.success) {
          btn.textContent = "ذخیره لینک چت";
          toast("ذخیره لینک ناموفق بود");
          return;
        }
        if (id) openSaveTitle(id);
        btn.textContent = "ذخیره شد ✔";
        setTimeout(() => (btn.textContent = "ذخیره لینک چت"), 1500);
      }
    );
  });

  // keep in viewport
  window.addEventListener("resize", () => {
    const rect = btn.getBoundingClientRect();
    const vw = window.innerWidth, vh = window.innerHeight;
    const newR = clamp(vw - rect.right, 8, vw - rect.width  - 8);
    const newB = clamp(vh - rect.bottom, 8, vh - rect.height - 8);
    btn.style.right  = `${newR}px`;
    btn.style.bottom = `${newB}px`;
    savePos(btn.style);
  });

  // ---------- permission & live toggle ----------
  let attached = false;
  function attachBtn() {
    if (attached) return;
    document.documentElement.appendChild(btn);
    attached = true;
    syncByUrl();
  }
  function detachBtn() {
    if (!attached) return;
    try { btn.remove(); } catch {}
    attached = false;
  }

  function syncByUrl() {
    if (!attached) return;
    const onConversation = CHAT_RE.test(location.pathname);
    btn.style.display = onConversation ? "block" : "none";
  }

  // ❶ فقط وقتی showSaveButton=true باشد اینجکت/نمایش بده
  function ensureBySetting() {
    chrome.storage.local.get({ showSaveButton: true }, (cfg) => {
      if (cfg.showSaveButton) {
        attachBtn();
        syncByUrl();
      } else {
        detachBtn();
      }
    });
  }

  // ❷ تغییر زندهٔ تنظیم
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === "local" && changes.showSaveButton) {
      if (changes.showSaveButton.newValue === true) {
        attachBtn();
        syncByUrl();
      } else {
        detachBtn();
      }
    }
  });

  // ❸ واکنش به تغییر URL در SPA
  let lastHref = location.href;
  setInterval(() => {
    if (location.href !== lastHref) {
      lastHref = location.href;
      syncByUrl();
    }
  }, 500);

  // start
  ensureBySetting();

  function toast(msg) {
    const t = document.createElement("div");
    t.textContent = msg;
    Object.assign(t.style, {
      position: "fixed",
      bottom: "16px",
      right: "16px",
      background: "#10b981",
      color: "#052e2b",
      padding: "10px 14px",
      borderRadius: "10px",
      boxShadow: "0 6px 20px rgba(0,0,0,.2)",
      zIndex: "2147483647",
      fontSize: "13px",
      fontFamily: "inherit",
    });
    document.documentElement.appendChild(t);
    setTimeout(() => t.remove(), 2000);
  }
})();
