
(()=>{
  if (window.__PULSE_CANDIDATE_TYPE_CONTENT__) return;
  window.__PULSE_CANDIDATE_TYPE_CONTENT__ = true;

  let mt = new Map();
  let ht = new Map();
  let bt = true;
  const wt = 'alphaFinderUserTypeCache';
  const yt = 36e5;
  const xt = '[data-testid="chat-list"]';
  const AUTH_KEY = "pulsarAuth";
  const LEFT_RAIL_SELECTOR = '[class*="styles_item_left_left__"]';

  const TYPE_BG = {
    1: 'linear-gradient(180deg, rgba(171, 32, 56, .96) 0%, rgba(196, 53, 78, .92) 100%)',
    2: 'linear-gradient(180deg, rgba(72, 166, 255, .98) 0%, rgba(104, 191, 255, .92) 100%)',
    3: 'linear-gradient(180deg, rgba(44, 233, 185, .96) 0%, rgba(86, 242, 202, .92) 100%)'
  };

  const getLeftRail = (row) => {
    if (!row) return null;
    return row.querySelector(LEFT_RAIL_SELECTOR);
  };

  const clearRailStyle = (rail) => {
    if (!rail) return;
    rail.style.background = '';
    rail.style.backgroundImage = '';
    rail.style.backgroundColor = '';
  };

  const applyRailStyle = (rail, type) => {
    if (!rail) return;
    rail.style.background = TYPE_BG[type] || TYPE_BG[2];
    rail.style.backgroundImage = TYPE_BG[type] || TYPE_BG[2];
  };

  const clearAllRows = () => {
    try {
      document.querySelectorAll(`${xt} [data-testid], [data-testid]`).forEach((row) => {
        clearRailStyle(getLeftRail(row));
      });
    } catch {}
  };

  const _t = () => {
    const out = {};
    ht.forEach((n, e) => {
      if (n && n.type !== undefined) {
        out[e] = {
          type: n.type,
          manExternalID: n.manExternalID || null,
          womanExternalID: n.womanExternalID || null,
          cachedAt: n.cachedAt || Date.now()
        };
      }
    });
    try { chrome.storage.local.set({ [wt]: out }); } catch {}
  };

  try {
    chrome.storage.local.get([wt, 'enableChatTypeCheck', AUTH_KEY], (res) => {
      try {
        if (res && res[wt] && typeof res[wt] === 'object') {
          Object.entries(res[wt]).forEach(([k, v]) => {
            if (v && v.type !== undefined) ht.set(k, v);
          });
        }
        const isAuthed = !!(res && res[AUTH_KEY] && res[AUTH_KEY].authenticated && res[AUTH_KEY].token);
        if (typeof res?.enableChatTypeCheck !== 'undefined') bt = isAuthed && res.enableChatTypeCheck === true;
        else bt = isAuthed;
      } catch {}
      kt();
    });
  } catch {}

  try {
    chrome.storage.onChanged.addListener((changes, area) => {
      if (area !== 'local') return;
      if (changes[wt] && changes[wt].newValue && typeof changes[wt].newValue === 'object') {
        ht = new Map();
        Object.entries(changes[wt].newValue).forEach(([k, v]) => {
          if (v && v.type !== undefined) ht.set(k, v);
        });
      }
      if (changes.enableChatTypeCheck || changes[AUTH_KEY]) {
        chrome.storage.local.get(['enableChatTypeCheck', AUTH_KEY], (res) => {
          const isAuthed = !!(res && res[AUTH_KEY] && res[AUTH_KEY].authenticated && res[AUTH_KEY].token);
          bt = !!isAuthed && res.enableChatTypeCheck === true;
          if (!bt) clearAllRows();
          new Set([...mt.keys(), ...ht.keys()]).forEach((chatUid) => vt(chatUid, mt.get(chatUid) || null));
        });
        return;
      }
      new Set([...mt.keys(), ...ht.keys()]).forEach((chatUid) => vt(chatUid, mt.get(chatUid) || null));
    });
  } catch {}

  const vt = (t, n) => {
    const i = document.querySelector(xt);
    const r = i ? i.querySelector(`[data-testid="${t}"]`) : document.querySelector(`[data-testid="${t}"]`);
    if (!r) return false;
    const rail = getLeftRail(r);
    if (!rail) return false;
    const s = ht.get(t);
    if (bt && s && s.type) {
      const type = [1,2,3].includes(Number(s.type)) ? Number(s.type) : 2;
      applyRailStyle(rail, type);
    } else {
      clearRailStyle(rail);
    }
    return true;
  };

  const At = async (manExternalID, womanExternalID, chatUid) => {
    if (!bt) return;
    try {
      const cached = ht.get(chatUid);
      if (cached) {
        const age = cached.cachedAt ? Date.now() - cached.cachedAt : 3600001;
        if (cached.manExternalID === manExternalID && cached.womanExternalID === womanExternalID && age < yt) {
          const limits = mt.get(chatUid) || null;
          vt(chatUid, limits);
          return;
        }
        if (age >= yt) {
          ht.delete(chatUid);
          _t();
        }
      }
      const token = (() => {
        try { return localStorage.getItem('token'); } catch { return null; }
      })();
      if (!token) return;
      const res = await fetch('https://alpha.date/api/config/type/check', {
        method: 'POST',
        headers: {
          Authorization: 'Bearer ' + token,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ manExternalID, womanExternalID })
      });
      if (!res.ok) return;
      const json = await res.json();
      if (json.status && json.result && json.result.type !== undefined) {
        ht.set(chatUid, {
          type: json.result.type,
          manExternalID,
          womanExternalID,
          cachedAt: Date.now()
        });
        _t();
        vt(chatUid, mt.get(chatUid) || null);
      }
    } catch {}
  };

  const kt = () => {
    let seen = new Set();
    let timer = null;
    const apply = () => {
      const next = new Set();
      mt.forEach((limits, chatUid) => {
        next.add(chatUid);
        vt(chatUid, limits);
      });
      ht.forEach((_, chatUid) => {
        next.add(chatUid);
        vt(chatUid, mt.get(chatUid) || null);
      });
      seen = next;
    };
    const obs = new MutationObserver(() => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        timer = null;
        apply();
      }, 400);
    });
    apply();
    setTimeout(apply, 500);
    setTimeout(apply, 1000);
    setTimeout(apply, 2000);
    obs.observe(document.body, { childList: true, subtree: true });
    return obs;
  };

  const processLastMessages = async (arr) => {
    if (!bt) return;
    const need = [];
    arr.forEach((t) => {
      if (!t || !t.chat_uid) return;
      let manExternalID = null;
      let womanExternalID = null;
      if (t.is_male === 0) {
        womanExternalID = t.sender_external_id;
        manExternalID = t.recipient_external_id;
      } else if (t.is_male === 1) {
        manExternalID = t.sender_external_id;
        womanExternalID = t.recipient_external_id;
      }
      if (manExternalID && womanExternalID) {
        const cached = ht.get(t.chat_uid);
        const age = cached?.cachedAt ? Date.now() - cached.cachedAt : 3600001;
        if (!(cached && cached.manExternalID === manExternalID && cached.womanExternalID === womanExternalID && age < yt)) {
          need.push({ manExternalID, womanExternalID, chatUid: t.chat_uid });
        }
      }
    });
    for (const item of need) {
      await At(item.manExternalID, item.womanExternalID, item.chatUid);
    }
  };

  window.addEventListener('message', (e) => {
    try {
      const d = e?.data;
      if (!d) return;

      if (d.type === 'LAST_MESSAGE_DATA' && Array.isArray(d.lastMessages)) {
        processLastMessages(d.lastMessages);
        return;
      }

      if (d.source !== 'alpha-finder-chat-limits') return;
      if (d.type === 'LAST_MESSAGES' && Array.isArray(d.payload)) {
        processLastMessages(d.payload);
        return;
      }
      if (d.type === 'LIMITS_MAP' && d.payload && typeof d.payload === 'object') {
        mt = new Map(Object.entries(d.payload));
        new Set([...mt.keys(), ...ht.keys()]).forEach((chatUid) => vt(chatUid, mt.get(chatUid) || null));
      }
    } catch {}
  });
})();
