// /tag-extractor/assets/js/app.js

document.addEventListener('DOMContentLoaded', function () {
  const inputText = document.getElementById('inputText');
  const extractTextBtn = document.getElementById('extractTextBtn');
  const uploadForm = document.getElementById('uploadForm');
  const urlForm = document.getElementById('urlForm');

  const resultsSection = document.getElementById('resultsSection');
  const resultsSummary = document.getElementById('resultsSummary');

  const handlesList = document.getElementById('handlesList');
  const hashtagsList = document.getElementById('hashtagsList');
  const linksList = document.getElementById('linksList');
  const emailsList = document.getElementById('emailsList');

  const handlesCount = document.getElementById('handlesCount');
  const hashtagsCount = document.getElementById('hashtagsCount');
  const linksCount = document.getElementById('linksCount');
  const emailsCount = document.getElementById('emailsCount');

  const snippetSection = document.getElementById('snippetSection');
  const htmlFooterOutput = document.getElementById('htmlFooterOutput');
  const hashtagsInlineOutput = document.getElementById('hashtagsInlineOutput');

  function extractFromText(text) {
    // @handles
    const handleRegex = /@([A-Za-z0-9_.]+)/gu;
    const hashtagRegex = /#(\w+)/gu;
    const urlRegex = /https?:\/\/[^\s"<>'"]+/gi;
    const emailRegex = /[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/g;

    function uniqSorted(arr) {
      return Array.from(new Set(arr)).sort((a, b) => a.localeCompare(b));
    }

    const handles = [];
    const hashtags = [];
    const links = [];
    const emails = [];

    let match;
    while ((match = handleRegex.exec(text)) !== null) {
      handles.push(match[0]);
    }
    while ((match = hashtagRegex.exec(text)) !== null) {
      hashtags.push(match[0]);
    }
    while ((match = urlRegex.exec(text)) !== null) {
      links.push(match[0]);
    }
    while ((match = emailRegex.exec(text)) !== null) {
      emails.push(match[0]);
    }

    return {
      handles: uniqSorted(handles),
      hashtags: uniqSorted(hashtags),
      links: uniqSorted(links),
      emails: uniqSorted(emails),
      textLength: text.length
    };
  }

  function buildHtmlFooterSnippet(data) {
    const handles = data.handles || [];
    const hashtags = data.hashtags || [];
    const links = data.links || [];

    const handlesText = handles.length ? handles.join(', ') : '';
    const hashtagsText = hashtags.length ? hashtags.join(' ') : '';
    const linksHtml = links
      .map(link => `        <li><a href="${link}" target="_blank" rel="noopener noreferrer">${link}</a></li>`)
      .join('\n');

    const snippet = `<!-- Article Footer – Generated by Tag Extractor -->
<section class="article-footer-promo">
  <h3>Community &amp; Resources</h3>
  ${handlesText ? `<p><strong>@Handles:</strong> ${handlesText}</p>` : ''}
  ${hashtagsText ? `<p><strong>Hashtags:</strong> ${hashtagsText}</p>` : ''}
  ${links.length ? `<ul>\n${linksHtml}\n  </ul>` : ''}
</section>
<!-- End Article Footer -->`;

    return snippet;
  }

  function buildHashtagInlineSnippet(data) {
    const hashtags = data.hashtags || [];
    if (!hashtags.length) return '';
    return hashtags.join(' ');
  }

  function renderResults(data, sourceLabel) {
    // Show extracted lists
    resultsSection.classList.remove('hidden');

    handlesList.textContent = data.handles.join('\n');
    hashtagsList.textContent = data.hashtags.join('\n');
    linksList.textContent = data.links.join('\n');
    emailsList.textContent = data.emails.join('\n');

    handlesCount.textContent = data.handles.length;
    hashtagsCount.textContent = data.hashtags.length;
    linksCount.textContent = data.links.length;
    emailsCount.textContent = data.emails.length;

    resultsSummary.innerHTML = `
      <p><strong>Source:</strong> ${sourceLabel}</p>
      <p><strong>Text length processed:</strong> ${data.textLength || data.text_length || 0} characters</p>
    `;

    // Build snippets
    const footerSnippet = buildHtmlFooterSnippet(data);
    const hashtagSnippet = buildHashtagInlineSnippet(data);

    htmlFooterOutput.textContent = footerSnippet;
    hashtagsInlineOutput.textContent = hashtagSnippet;

    snippetSection.classList.remove('hidden');
  }

  extractTextBtn.addEventListener('click', function () {
    const text = inputText.value || '';
    if (!text.trim()) {
      alert('Please paste some text first.');
      return;
    }

    const result = extractFromText(text);
    renderResults(result, 'Pasted text');
  });

  // Handle file upload via AJAX
  if (uploadForm) {
    uploadForm.addEventListener('submit', function (e) {
      e.preventDefault();

      const fileInput = document.getElementById('tagfile');
      if (!fileInput.files.length) {
        alert('Please choose a file first.');
        return;
      }

      const formData = new FormData();
      formData.append('mode', 'file');
      formData.append('tagfile', fileInput.files[0]);

      fetch('process.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          if (data.error) {
            alert(data.error);
            return;
          }
          const transformed = {
            handles: data.handles || [],
            hashtags: data.hashtags || [],
            links: data.links || [],
            emails: data.emails || [],
            textLength: data.text_length || 0
          };
          renderResults(transformed, 'Uploaded file');
        })
        .catch(err => {
          console.error(err);
          alert('Error processing file.');
        });
    });
  }

  // Handle URL fetch mode
  if (urlForm) {
    urlForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const urlInput = document.getElementById('source_url');
      const url = urlInput.value.trim();
      if (!url) {
        alert('Please enter a URL.');
        return;
      }

      const formData = new FormData();
      formData.append('mode', 'url');
      formData.append('source_url', url);

      fetch('process.php', {
        method: 'POST',
        body: formData
      })
        .then(res => res.json())
        .then(data => {
          if (data.error) {
            alert(data.error);
            return;
          }
          const transformed = {
            handles: data.handles || [],
            hashtags: data.hashtags || [],
            links: data.links || [],
            emails: data.emails || [],
            textLength: data.text_length || 0
          };
          renderResults(transformed, `Fetched URL: ${url}`);
        })
        .catch(err => {
          console.error(err);
          alert('Error fetching URL.');
        });
    });
  }

  // Copy buttons (works for all result + snippet blocks)
  document.addEventListener('click', function (e) {
    if (e.target.matches('button[data-copy-target]')) {
      const targetId = e.target.getAttribute('data-copy-target');
      const pre = document.getElementById(targetId);
      if (!pre) return;

      const text = pre.textContent;
      if (!text.trim()) {
        alert('Nothing to copy.');
        return;
      }

      navigator.clipboard.writeText(text)
        .then(() => {
          const original = e.target.textContent;
          e.target.textContent = 'Copied!';
          setTimeout(() => {
            e.target.textContent = original;
          }, 1200);
        })
        .catch(() => {
          alert('Copy failed. You can still select and copy manually.');
        });
    }
  });
});
