Dooky / Aither Comps

// ==UserScript==
// @name         Aither Comps
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Add "Create comp" button next to copy button in description block
// @author       Dooky
// @match        https://aither.cc/torrents/*
// @match        https://aither.cc/forums/topics/forum/57/create
// @match        https://aither.cc/forums/topics/forum/58/create
// @exclude      https://aither.cc/torrents/similar/*
// @exclude      https://aither.cc/torrents/moderation
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_openInTab

// @updateURL https://openuserjs.org/meta/Dooky/Aither_Comps.meta.js
// @downloadURL https://openuserjs.org/install/Dooky/Aither_Comps.user.js
// @license MIT
// ==/UserScript==

(function () {
  'use strict';

  function extractTMDBId() {
    const tmdbLinks = document.querySelectorAll('a[href*="themoviedb.org"]');
    for (const link of tmdbLinks) {
      const match = link.href.match(/themoviedb\.org\/(movie|tv)\/(\d+)/);
      if (match) {
        return {
          type: match[1],
          id: match[2]
        };
      }
    }
    return null;
  }

  function getTitleElement() {
    return document.querySelector('h1.torrent__name') ||
      document.querySelector('h1') ||
      document.querySelector('.torrent-title h1');
  }

  function extractTitleAndYear() {
    const titleElement = getTitleElement();
    if (!titleElement) return {
      title: null,
      year: null
    };

    let fullTitle = (titleElement.innerText || titleElement.textContent || '').trim();

    let year = null;
    const yearMatchParen = fullTitle.match(/\s\((\d{4})\)/);
    const yearMatchStandalone = fullTitle.match(/\b(19|20)\d{2}\b/);

    if (yearMatchParen) {
      year = yearMatchParen[1];
      const yearIndex = fullTitle.indexOf(`(${year})`);
      let title = fullTitle.substring(0, yearIndex).trim();
      title = title.replace(/[-\s]+$/, '').trim();
      return {
        title,
        year
      };
    }
    else if (yearMatchStandalone) {
      year = yearMatchStandalone[0];
      const yearIndex = yearMatchStandalone.index;
      let title = fullTitle.substring(0, yearIndex).trim();
      title = title.replace(/\s+$/, '').trim();
      return {
        title,
        year
      };
    }

    const words = fullTitle.split(/\s+/);
    let titleWords = [];

    for (let i = 0; i < words.length; i++) {
      const word = words[i];

      if (/^(19|20)\d{2}$/.test(word)) {
        year = word;
        break;
      }

      if (/^\d{3,4}p$/i.test(word)) {
        break;
      }

      if (/^(UHD|HD|SD|WEB-DL|WEBRip|BluRay|Blu-ray|REMUX|DV|HDR|HDR10|HDR10\+|HEVC|H\.264|H\.265|x264|x265|AAC|AC3|DTS|TrueHD|Atmos|DD|DDP)$/i.test(word)) {
        break;
      }

      titleWords.push(word);
    }

    let title = titleWords.join(' ').trim();
    return {
      title,
      year
    };
  }

  function extractSeasonEpisode() {
    const titleElement = getTitleElement();
    if (!titleElement) return null;

    const fullTitle = (titleElement.innerText || titleElement.textContent || '').trim();
    const match = fullTitle.match(/S(\d+)E(\d+)/i);
    if (match) {
      const season = match[1].padStart(2, '0');
      const episode = match[2].padStart(2, '0');
      return `S${season}E${episode}`;
    }
    return null;
  }

  function extractResolution() {
    const titleElement = getTitleElement();
    if (!titleElement) return null;

    const fullTitle = (titleElement.innerText || titleElement.textContent || '').trim();
    let match = fullTitle.match(/\b(\d{3,4}p)\b/i);
    if (match) {
      return match[1].toLowerCase();
    }

    if (fullTitle.match(/\b4K\b/i)) {
      return '2160p';
    }

    const mediainfoEl = document.querySelector('.torrent-mediainfo-dump pre code[x-ref="mediainfo"]') ||
      document.querySelector('.torrent-mediainfo-dump pre.decoda-code code') ||
      document.querySelector('.torrent-mediainfo-dump code');
    if (mediainfoEl) {
      const mediainfoText = mediainfoEl.innerText || mediainfoEl.textContent || '';
      const widthMatch = mediainfoText.match(/Width\s*[:\-]\s*(\d+)/i);
      if (widthMatch) {
        const width = parseInt(widthMatch[1]);
        if (width >= 1920) return '1080p';
        if (width >= 1280) return '720p';
        if (width >= 3840) return '2160p';
      }
    }

    return null;
  }

  function extractMediainfo() {
    const mediainfoEl = document.querySelector('.torrent-mediainfo-dump pre code[x-ref="mediainfo"]') ||
      document.querySelector('.torrent-mediainfo-dump pre.decoda-code code') ||
      document.querySelector('.torrent-mediainfo-dump code') ||
      document.querySelector('.torrent-mediainfo-dump pre') ||
      document.querySelector('pre code');

    if (!mediainfoEl) return {
      text: null,
      completeName: null
    };

    const mediainfoText = mediainfoEl.innerText || mediainfoEl.textContent || '';
    if (!mediainfoText) return {
      text: null,
      completeName: null
    };

    const completeNameMatch = mediainfoText.match(/Complete name\s*[:\-]\s*(.+)/i);
    const completeName = completeNameMatch ? completeNameMatch[1].trim() : null;

    return {
      text: mediainfoText.trim(),
      completeName: completeName
    };
  }

  function detectTorrentType() {
    const tmdbData = extractTMDBId();
    if (tmdbData && tmdbData.type) {
      return tmdbData.type;
    }

    if (extractSeasonEpisode()) return 'tv';

    const tvIcon = document.querySelector("i.fa-tv, i.torrent-icon[title*='TV'], i.torrent-icon[title*='Show']");
    if (tvIcon) return 'tv';

    const movieIcon = document.querySelector("i.fa-film, i.fa-movie, i.torrent-icon[title*='Movie']");
    if (movieIcon) return 'movie';

    const url = window.location.href.toLowerCase();
    if (url.includes('/tv') || url.includes('/series')) return 'tv';
    if (url.includes('/movie') || url.includes('/film')) return 'movie';

    return 'movie';
  }

  function getDescriptionSection() {
    return document.querySelector('.panel__body.bbcode-rendered') ||
      document.querySelector('.bbcode-rendered') ||
      document.querySelector('section.panelV2 .panel__body') ||
      document.querySelector('.panel__body');
  }

  function findCopyButton() {
    const descriptionSection = getDescriptionSection();
    if (!descriptionSection) return null;

    const buttons = descriptionSection.querySelectorAll('button, a.button, .button');
    for (const button of buttons) {
      const text = (button.innerText || button.textContent || '').toLowerCase();
      if (text.includes('copy')) {
        return button;
      }
    }

    const parentSection = descriptionSection.closest('section, .panel, .panelV2');
    if (parentSection) {
      const parentButtons = parentSection.querySelectorAll('button, a.button, .button');
      for (const button of parentButtons) {
        const text = (button.innerText || button.textContent || '').toLowerCase();
        if (text.includes('copy') && !button.closest('.torrentModToolkit')) {
          return button;
        }
      }
    }

    return null;
  }

  function getRawBBCodeFromDescription() {
    const descriptionSection = getDescriptionSection();
    if (!descriptionSection) return null;

    const copyButton = findCopyButton();
    if (!copyButton) return null;

    const rawBBCode = copyButton.getAttribute('data-bbcode') ||
      copyButton.getAttribute('data-content') ||
      copyButton.getAttribute('data-copy') ||
      copyButton.getAttribute('data-clipboard-text') ||
      copyButton.getAttribute('data-text');

    if (rawBBCode) return rawBBCode;

    const onclick = copyButton.getAttribute('onclick');
    if (onclick) {
      const match = onclick.match(/["']([^"']*\[comparison[^"']*)["']/);
      if (match) return match[1];
    }

    const renderedBBCode = descriptionSection.querySelector('.bbcode-rendered') || descriptionSection;
    const rawFromData = renderedBBCode.getAttribute('data-bbcode') ||
      renderedBBCode.getAttribute('data-content') ||
      renderedBBCode.getAttribute('data-raw') ||
      renderedBBCode.getAttribute('data-original');

    if (rawFromData && rawFromData.includes('[')) return rawFromData;

    const parentSection = descriptionSection.closest('section, .panel, .panelV2');
    if (parentSection) {
      const allTextareas = parentSection.querySelectorAll('textarea');
      for (const textarea of allTextareas) {
        const value = textarea.value || '';
        if (value && value.includes('[comparison')) return value;
      }

      const preElements = parentSection.querySelectorAll('pre, code');
      for (const pre of preElements) {
        const text = pre.textContent || pre.innerText || '';
        if (text && text.includes('[comparison')) return text;
      }
    }

    const copyTargetId = copyButton.getAttribute('data-clipboard-target') ||
      copyButton.getAttribute('data-target') ||
      copyButton.getAttribute('for') ||
      copyButton.getAttribute('data-copy-target');

    if (copyTargetId) {
      const targetElement = copyTargetId.startsWith('#') || copyTargetId.startsWith('.') ?
        document.querySelector(copyTargetId) :
        document.getElementById(copyTargetId) ||
        document.querySelector(`.${copyTargetId}`) ||
        document.querySelector(copyTargetId);

      if (targetElement) {
        const targetValue = targetElement.value ||
          targetElement.textContent ||
          targetElement.innerText ||
          targetElement.getAttribute('data-content') ||
          '';
        if (targetValue && targetValue.includes('[')) return targetValue;
      }
    }

    const buttonParent = copyButton.parentElement;
    if (buttonParent) {
      const siblings = Array.from(buttonParent.children);
      for (const sibling of siblings) {
        if (sibling !== copyButton && (sibling.tagName === 'PRE' || sibling.tagName === 'CODE' || sibling.tagName === 'TEXTAREA')) {
          const siblingText = sibling.textContent || sibling.innerText || sibling.value || '';
          if (siblingText && siblingText.includes('[comparison')) return siblingText;
        }
      }
    }

    const alpineData = descriptionSection.closest('[x-data], [data-alpine]');
    if (alpineData && window.Alpine && alpineData._x_dataStack) {
      const data = alpineData._x_dataStack[0];
      if (data && data.content) return data.content;
    }

    let interceptedBBCode = null;
    let interceptActive = true;

    const copyHandler = (e) => {
      if (interceptActive) {
        e.preventDefault();
        e.stopImmediatePropagation();

        let textToCapture = '';

        if (e.clipboardData) {
          const selection = window.getSelection();
          if (selection && selection.rangeCount > 0) {
            textToCapture = selection.toString();
          }

          if (!textToCapture) {
            const target = e.target;
            if (target) {
              if (target.value) {
                textToCapture = target.value;
              }
              else if (target.textContent) {
                textToCapture = target.textContent;
              }
              else if (target.innerText) {
                textToCapture = target.innerText;
              }
            }
          }

          if (textToCapture && textToCapture.includes('[comparison')) {
            interceptedBBCode = textToCapture;
          }

          e.clipboardData.setData('text/plain', '');
          return false;
        }
      }
    };

    document.addEventListener('copy', copyHandler, true);

    const originalWriteText = navigator.clipboard?.writeText;
    if (navigator.clipboard && originalWriteText) {
      navigator.clipboard.writeText = function (text) {
        if (interceptActive) {
          if (text && typeof text === 'string' && text.includes('[comparison')) {
            interceptedBBCode = text;
          }
          return Promise.resolve();
        }
        return originalWriteText.call(this, text);
      };
    }

    const originalExecCommand = document.execCommand;
    document.execCommand = function (command, showUI, value) {
      if (interceptActive && command === 'copy') {
        if (value && typeof value === 'string' && value.includes('[comparison')) {
          interceptedBBCode = value;
        }
        else {
          const selection = window.getSelection();
          if (selection && selection.toString().includes('[comparison')) {
            interceptedBBCode = selection.toString();
          }
        }
        return false;
      }
      return originalExecCommand.call(document, command, showUI, value);
    };

    try {
      copyButton.click();
    }
    catch (e) {}

    setTimeout(() => {
      interceptActive = false;
      document.removeEventListener('copy', copyHandler, true);
      if (navigator.clipboard && originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
      document.execCommand = originalExecCommand;
    }, 300);

    if (interceptedBBCode) {
      interceptActive = false;
      document.removeEventListener('copy', copyHandler, true);
      if (navigator.clipboard && originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
      document.execCommand = originalExecCommand;
      return interceptedBBCode;
    }

    return null;
  }

  function getDescriptionFromAudits() {
    const auditsTable = document.querySelector('.data-table-wrapper table.data-table');
    if (!auditsTable) return null;

    const rows = auditsTable.querySelectorAll('tbody tr');

    for (const row of rows) {
      const modCell = row.querySelector('td:last-child');
      if (!modCell) continue;

      const listItems = modCell.querySelectorAll('li');

      for (const li of listItems) {
        const text = li.textContent || li.innerText || '';
        const html = li.innerHTML || '';
        const lowerText = text.toLowerCase();
        const lowerHtml = html.toLowerCase();

        if (lowerText.includes('description:') || lowerHtml.includes('description:')) {
          const descriptionHTML = html;
          const arrowPatterns = ['→', '&rarr;', '&rarr'];
          let afterArrow = '';

          for (const arrow of arrowPatterns) {
            if (descriptionHTML.includes(arrow)) {
              const parts = descriptionHTML.split(arrow);
              if (parts.length > 1) {
                afterArrow = parts.slice(1).join(arrow).trim();
                break;
              }
            }
          }

          if (!afterArrow) {
            const descIndex = descriptionHTML.toLowerCase().indexOf('description:');
            if (descIndex !== -1) {
              const afterDesc = descriptionHTML.substring(descIndex + 'description:'.length);
              for (const arrow of arrowPatterns) {
                if (afterDesc.includes(arrow)) {
                  const arrowIndex = afterDesc.indexOf(arrow);
                  afterArrow = afterDesc.substring(arrowIndex + arrow.length).trim();
                  break;
                }
              }
              if (!afterArrow && afterDesc.includes('null')) {
                const nullIndex = afterDesc.indexOf('null');
                afterArrow = afterDesc.substring(nullIndex + 'null'.length).trim();
                afterArrow = afterArrow.replace(/^[\s→→&rarr;]+/, '').trim();
              }
            }
          }

          if (afterArrow) {
            afterArrow = afterArrow
              .replace(/&amp;/g, '&')
              .replace(/&lt;/g, '<')
              .replace(/&gt;/g, '>')
              .replace(/&quot;/g, '"')
              .replace(/&#39;/g, "'")
              .replace(/&nbsp;/g, ' ')
              .replace(/&rarr;/g, '→');
            return afterArrow;
          }
        }
      }
    }

    return null;
  }

  function extractComparisonTags() {
    let descriptionHTML = getRawBBCodeFromDescription();

    if (!descriptionHTML) {
      descriptionHTML = getDescriptionFromAudits();
    }

    if (!descriptionHTML) {
      const descriptionSection = getDescriptionSection();
      if (descriptionSection) {
        descriptionHTML = descriptionSection.innerHTML || descriptionSection.textContent || '';
      }
    }

    if (!descriptionHTML) return null;

    let decodedHTML = descriptionHTML
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&nbsp;/g, ' ')
      .replace(/&rarr;/g, '→');

    let comparisonMatch = decodedHTML.match(/\[comparison\s*=\s*([^\]]*)\]([\s\S]*?)\[\/comparison\]/i);
    if (!comparisonMatch) {
      comparisonMatch = descriptionHTML.match(/\[comparison\s*=\s*([^\]]*)\]([\s\S]*?)\[\/comparison\]/i);
    }
    if (!comparisonMatch) {
      comparisonMatch = descriptionHTML.match(/&lt;comparison\s*=\s*([^&]*&gt;)([\s\S]*?)&lt;\/comparison&gt;/i);
      if (comparisonMatch) {
        comparisonMatch[1] = comparisonMatch[1].replace(/&gt;$/, '');
        comparisonMatch[2] = comparisonMatch[2].replace(/&lt;/g, '<').replace(/&gt;/g, '>');
      }
    }

    if (comparisonMatch) {
      const content = comparisonMatch[2].trim();
      return {
        fullTag: `[comparison=${comparisonMatch[1]}]${content}[/comparison]`,
        params: comparisonMatch[1],
        content: content
      };
    }

    let comparisonMatchNoParams = decodedHTML.match(/\[comparison\]([\s\S]*?)\[\/comparison\]/i);
    if (!comparisonMatchNoParams) {
      comparisonMatchNoParams = descriptionHTML.match(/\[comparison\]([\s\S]*?)\[\/comparison\]/i);
    }

    if (comparisonMatchNoParams) {
      const content = comparisonMatchNoParams[1].trim();
      return {
        fullTag: `[comparison]${content}[/comparison]`,
        params: '',
        content: content
      };
    }

    return null;
  }

  function extractComparisonLinks() {
    let descriptionHTML = getRawBBCodeFromDescription();

    if (!descriptionHTML) {
      descriptionHTML = getDescriptionFromAudits();
    }

    if (!descriptionHTML) {
      const descriptionSection = getDescriptionSection();
      if (descriptionSection) {
        descriptionHTML = descriptionSection.innerHTML || descriptionSection.textContent || '';
      }
    }

    if (!descriptionHTML) {
      return {
        compPics: null,
        slowPics: null
      };
    }

    const decodedHTML = descriptionHTML
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&nbsp;/g, ' ')
      .replace(/&rarr;/g, '→');

    let compPicsLink = null;

    let compPicsMatch = decodedHTML.match(/\[url\s*=\s*([^\]]*comp\.pics[^\]]*)\]([^\[]*)\[\/url\]/i);
    if (compPicsMatch) {
      compPicsLink = compPicsMatch[1].trim().replace(/^["']|["']$/g, '');
    }
    else {
      compPicsMatch = descriptionHTML.match(/\[url\s*=\s*([^\]]*comp\.pics[^\]]*)\]([^\[]*)\[\/url\]/i);
      if (compPicsMatch) {
        compPicsLink = compPicsMatch[1].trim().replace(/^["']|["']$/g, '');
      }
      else {
        const plainUrlMatch = decodedHTML.match(/(https?:\/\/[^\s\[\]]*comp\.pics[^\s\[\]]*)/i);
        if (plainUrlMatch) {
          compPicsLink = plainUrlMatch[1].trim().replace(/^["']|["']$/g, '');
        }
      }
    }

    let slowPicsLink = null;

    let slowPicsMatch = decodedHTML.match(/\[url\s*=\s*([^\]]*slow\.pics[^\]]*)\]([^\[]*)\[\/url\]/i);
    if (slowPicsMatch) {
      slowPicsLink = slowPicsMatch[1].trim().replace(/^["']|["']$/g, '');
    }
    else {
      slowPicsMatch = descriptionHTML.match(/\[url\s*=\s*([^\]]*slow\.pics[^\]]*)\]([^\[]*)\[\/url\]/i);
      if (slowPicsMatch) {
        slowPicsLink = slowPicsMatch[1].trim().replace(/^["']|["']$/g, '');
      }
      else {
        const plainUrlMatch = decodedHTML.match(/(https?:\/\/[^\s\[\]]*slow\.pics[^\s\[\]]*)/i);
        if (plainUrlMatch) {
          slowPicsLink = plainUrlMatch[1].trim().replace(/^["']|["']$/g, '');
        }
      }
    }

    return {
      compPics: compPicsLink,
      slowPics: slowPicsLink
    };
  }

  function getSourcesString() {
    const comparison = extractComparisonTags();
    if (comparison && comparison.params) {
      const sources = comparison.params.split(',').map(s => s.trim()).filter(s => s);
      if (sources.length > 0) {
        return sources.join(' Vs. ');
      }
    }
    return 'Source Vs. Source';
  }

  function buildComparisonTitle() {
    const tmdbData = extractTMDBId();
    const {
      title,
      year
    } = extractTitleAndYear();
    const seasonEpisode = extractSeasonEpisode();
    const resolution = extractResolution();
    const sources = getSourcesString();

    let compTitle = '';

    if (tmdbData) {
      compTitle += `[${tmdbData.type}/${tmdbData.id}] `;
    }
    else {
      const torrentType = detectTorrentType();
      compTitle += `[${torrentType}/] `;
    }

    if (title) {
      compTitle += title;
      if (year) {
        compTitle += ` (${year})`;
      }
    }

    if (seasonEpisode) {
      compTitle += ` - ${seasonEpisode}`;
    }

    if (resolution) {
      compTitle += ` - ${resolution}`;
    }

    compTitle += ` - ${sources}`;

    return compTitle.trim();
  }

  function buildPostContent() {
    const {
      title,
      year
    } = extractTitleAndYear();
    const seasonEpisode = extractSeasonEpisode();
    const resolution = extractResolution();
    const sources = getSourcesString();

    let titleLine = '';
    if (title) {
      titleLine += title;
      if (year) {
        titleLine += ` (${year})`;
      }
    }
    if (seasonEpisode) {
      titleLine += ` - ${seasonEpisode}`;
    }
    if (resolution) {
      titleLine += ` - ${resolution}`;
    }
    titleLine += ` - ${sources}`;

    let postContent = `[u]${titleLine}[/u]\n\n`;

    const comparison = extractComparisonTags();
    if (comparison && comparison.fullTag) {
      postContent += `${comparison.fullTag}\n\n`;
    }
    else if (comparison && comparison.content && comparison.content.trim()) {
      const params = comparison.params ? `=${comparison.params}` : '';
      postContent += `[comparison${params}]\n${comparison.content.trim()}\n[/comparison]\n\n`;
    }
    else {
      postContent += `[comparison=]\n[/comparison]\n\n`;
    }

    const links = extractComparisonLinks();
    if (links.compPics) {
      postContent += `[url=${links.compPics}]${titleLine} | comps pics[/url]\n\n`;
    }

    if (links.slowPics) {
      postContent += `[url=${links.slowPics}]${titleLine} | SlowPoke Pics[/url]\n\n`;
    }

    const mediainfo = extractMediainfo();
    if (mediainfo.text) {
      const spoilerTitle = mediainfo.completeName || 'Mediainfo';
      postContent += `[spoiler=${spoilerTitle}][code]${mediainfo.text}[/code][/spoiler]\n\n`;
    }

    return postContent.trim();
  }

  function addCreateCompButton() {
    if (document.getElementById('create-comp-btn')) {
      return;
    }

    const copyButton = findCopyButton();
    if (!copyButton) {
      return;
    }

    const createCompBtn = document.createElement('button');
    createCompBtn.id = 'create-comp-btn';
    createCompBtn.textContent = 'Create comp';
    createCompBtn.style.marginLeft = '8px';
    createCompBtn.style.padding = '4px 12px';
    createCompBtn.style.cursor = 'pointer';
    createCompBtn.style.backgroundColor = '#2d6cd3';
    createCompBtn.style.color = 'white';
    createCompBtn.style.border = 'none';
    createCompBtn.style.borderRadius = '4px';
    createCompBtn.style.fontSize = '13px';

    createCompBtn.addEventListener('mouseenter', () => {
      createCompBtn.style.backgroundColor = '#2563eb';
    });
    createCompBtn.addEventListener('mouseleave', () => {
      createCompBtn.style.backgroundColor = '#2d6cd3';
    });

    createCompBtn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();

      const compTitle = buildComparisonTitle();
      const postContent = buildPostContent();

      const torrentType = detectTorrentType();
      const forumUrl = torrentType === 'tv' ?
        'https://aither.cc/forums/topics/forum/58/create' :
        'https://aither.cc/forums/topics/forum/57/create';

      GM_setValue('aither_comp_title', compTitle);
      GM_setValue('aither_comp_content', postContent);

      setTimeout(() => {
        GM_openInTab(forumUrl, {
          active: true,
          insert: true
        });
      }, 100);
    });

    if (copyButton.parentNode) {
      copyButton.parentNode.insertBefore(createCompBtn, copyButton.nextSibling);
    }
    else {
      copyButton.after(createCompBtn);
    }
  }

  function fillPostContent() {
    const storedContent = GM_getValue('aither_comp_content', null);
    if (!storedContent) return;

    let filled = false;

    const attemptFill = () => {
      if (filled) return;

      const contentTextarea = document.querySelector('textarea#bbcode-content') ||
        document.querySelector('textarea[name="content"]') ||
        document.querySelector('textarea.bbcode-input__input') ||
        document.querySelector('form textarea');

      if (contentTextarea) {
        if (!contentTextarea.value || contentTextarea.value.trim() === '') {
          contentTextarea.focus();
          contentTextarea.value = storedContent;

          const events = [
            new Event('input', {
              bubbles: true,
              cancelable: true
            }),
            new Event('change', {
              bubbles: true,
              cancelable: true
            })
          ];

          events.forEach(evt => contentTextarea.dispatchEvent(evt));

          if (contentTextarea.hasAttribute('wire:model')) {
            setTimeout(() => {
              contentTextarea.value = storedContent;
              contentTextarea.dispatchEvent(new Event('input', {
                bubbles: true
              }));
            }, 100);
          }

          filled = true;
          GM_setValue('aither_comp_content', null);
        }
      }
    };

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(attemptFill, 200);
      });
    }
    else {
      setTimeout(attemptFill, 200);
    }

    const delays = [500, 1000, 2000, 3000];
    delays.forEach(delay => {
      setTimeout(attemptFill, delay);
    });

    const observer = new MutationObserver(() => {
      if (!filled) {
        attemptFill();
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });

    setTimeout(() => {
      observer.disconnect();
    }, 5000);
  }

  function fillTitleField() {
    const storedTitle = GM_getValue('aither_comp_title', null);
    if (!storedTitle) return;

    let filled = false;

    const attemptFill = () => {
      if (filled) return;

      const titleInput = document.querySelector('input#input-thread-title') ||
        document.querySelector('input.form__text[name="title"]') ||
        document.querySelector('input[name="title"]') ||
        document.querySelector('input[name="topic_title"]') ||
        document.querySelector('input#title') ||
        document.querySelector('form[method="post"] input[type="text"]:first-of-type');

      if (titleInput) {
        const currentValue = titleInput.value || '';
        if (!currentValue.trim()) {
          titleInput.focus();
          titleInput.value = storedTitle;

          const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
          if (descriptor && descriptor.set) {
            descriptor.set.call(titleInput, storedTitle);
          }

          const events = [
            new Event('focus', {
              bubbles: true
            }),
            new Event('input', {
              bubbles: true,
              cancelable: true
            }),
            new InputEvent('input', {
              bubbles: true,
              cancelable: true,
              inputType: 'insertText',
              data: storedTitle
            }),
            new Event('change', {
              bubbles: true,
              cancelable: true
            }),
            new Event('blur', {
              bubbles: true
            })
          ];

          events.forEach(evt => titleInput.dispatchEvent(evt));

          setTimeout(() => {
            if (titleInput.value === storedTitle) {
              filled = true;
              GM_setValue('aither_comp_title', null);
            }
          }, 500);
        }
        else {
          if (currentValue === storedTitle) {
            filled = true;
            GM_setValue('aither_comp_title', null);
          }
        }
      }
    };

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(attemptFill, 100);
      });
    }
    else {
      setTimeout(attemptFill, 100);
    }

    const delays = [300, 500, 800, 1200, 2000, 3000, 5000];
    delays.forEach(delay => {
      setTimeout(attemptFill, delay);
    });

    const observer = new MutationObserver(() => {
      if (!filled) {
        attemptFill();
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['value']
    });

    const formObserver = new MutationObserver(() => {
      if (!filled && document.querySelector('form')) {
        setTimeout(attemptFill, 200);
      }
    });

    formObserver.observe(document.body, {
      childList: true,
      subtree: true
    });

    setTimeout(() => {
      observer.disconnect();
      formObserver.disconnect();
    }, 10000);
  }

  const isTorrentPage = /\/torrents\/\d+/.test(window.location.pathname);
  const isForumCreatePage = window.location.href.includes('/forums/topics/forum/57/create') ||
    window.location.href.includes('/forums/topics/forum/58/create');

  if (isForumCreatePage) {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        fillTitleField();
        fillPostContent();
      });
    }
    else {
      fillTitleField();
      fillPostContent();
    }
  }
  else if (isTorrentPage) {
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(addCreateCompButton, 500);
      });
    }
    else {
      setTimeout(addCreateCompButton, 500);
    }

    setTimeout(addCreateCompButton, 1500);
    setTimeout(addCreateCompButton, 3000);
  }
})();