// /linkstorm/script.js

// ===== Link sharing (from original version) =====
function getLink() {
  return document.getElementById('shareLink').value;
}

function shareTo(platform) {
  const link = encodeURIComponent(getLink());
  let shareURL = "";
  switch (platform) {
    case 'facebook':
      shareURL = `https://www.facebook.com/sharer/sharer.php?u=${link}`;
      break;
    case 'twitter':
      shareURL = `https://twitter.com/intent/tweet?url=${link}`;
      break;
    case 'linkedin':
      shareURL = `https://www.linkedin.com/sharing/share-offsite/?url=${link}`;
      break;
    case 'reddit':
      shareURL = `https://www.reddit.com/submit?url=${link}`;
      break;
  }
  window.open(shareURL, '_blank');
}

function autoShare() {
  ['facebook', 'twitter', 'linkedin', 'reddit'].forEach(shareTo);
}

// Use saved tokens (localStorage) and API functions from api.js
function shareLoggedIn() {
  const link = getLink();
  const fbToken = localStorage.getItem("facebook_token");
  const twToken = localStorage.getItem("twitter_token");
  const lnToken = localStorage.getItem("linkedin_token");

  if (fbToken) postToFacebookAPI(link, fbToken);
  if (twToken) postToTwitterAPI(link, twToken);
  if (lnToken) postToLinkedInAPI(link, lnToken);

  if (!fbToken && !twToken && !lnToken) {
    alert("No tokens saved! Please add them in settings.");
  }
}

// ===== Everything else waits for DOM ready =====
document.addEventListener('DOMContentLoaded', () => {
  // --- Auth elements ---
  const authEmail = document.getElementById('authEmail');
  const authPassword = document.getElementById('authPassword');
  const authLoginBtn = document.getElementById('authLoginBtn');
  const authRegisterBtn = document.getElementById('authRegisterBtn');
  const authLogoutBtn = document.getElementById('authLogoutBtn');
  const authStatus = document.getElementById('authStatus');
  const authUserLabel = document.getElementById('authUserLabel');
  const authLoggedOut = document.getElementById('authLoggedOut');
  const authLoggedIn = document.getElementById('authLoggedIn');

  // Tag extractor elements
  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 saveLoadSection = document.getElementById('saveLoadSection');
  const snippetSection = document.getElementById('snippetSection');

  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 htmlFooterOutput = document.getElementById('htmlFooterOutput');
  const hashtagsInlineOutput = document.getElementById('hashtagsInlineOutput');
  const templateSelect = document.getElementById('templateSelect');

  const setNameInput = document.getElementById('setName');
  const saveSetBtn = document.getElementById('saveSetBtn');
  const saveStatus = document.getElementById('saveStatus');
  const savedSetsSelect = document.getElementById('savedSetsSelect');
  const loadSetBtn = document.getElementById('loadSetBtn');
  const loadStatus = document.getElementById('loadStatus');

  let currentExtraction = null;
  let currentSourceType = 'paste';
  let currentSourceLabel = '';
  let currentArticleText = '';

  // ===== Auth helpers =====
  function updateAuthUI(user) {
    if (user && user.id) {
      authLoggedOut.classList.add('hidden');
      authLoggedIn.classList.remove('hidden');
      authUserLabel.textContent = `Logged in as ${user.email}`;
      authStatus.textContent = '';
      loadSavedSets(); // load this user's sets
      saveLoadSection.classList.remove('hidden');
    } else {
      authLoggedOut.classList.remove('hidden');
      authLoggedIn.classList.add('hidden');
      authUserLabel.textContent = '';
      savedSetsSelect.innerHTML = '<option value="">-- Select a saved set --</option>';
      saveLoadSection.classList.add('hidden');
    }
  }

  function fetchMe() {
    fetch('auth.php?action=me')
      .then(res => res.json())
      .then(data => {
        updateAuthUI(data.user || null);
      })
      .catch(() => {});
  }

  fetchMe();

  if (authLoginBtn) {
    authLoginBtn.addEventListener('click', () => {
      const email = authEmail.value.trim();
      const password = authPassword.value;
      if (!email || !password) {
        authStatus.textContent = 'Enter email and password.';
        return;
      }
      const formData = new FormData();
      formData.append('action', 'login');
      formData.append('email', email);
      formData.append('password', password);
      fetch('auth.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
          if (data.error) {
            authStatus.textContent = data.error;
          } else {
            authStatus.textContent = 'Logged in.';
            updateAuthUI(data.user);
          }
        })
        .catch(() => { authStatus.textContent = 'Login error.'; });
    });
  }

  if (authRegisterBtn) {
    authRegisterBtn.addEventListener('click', () => {
      const email = authEmail.value.trim();
      const password = authPassword.value;
      if (!email || !password) {
        authStatus.textContent = 'Enter email and password.';
        return;
      }
      const formData = new FormData();
      formData.append('action', 'register');
      formData.append('email', email);
      formData.append('password', password);
      fetch('auth.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(data => {
          if (data.error) {
            authStatus.textContent = data.error;
          } else {
            authStatus.textContent = 'Registered & logged in.';
            updateAuthUI(data.user);
          }
        })
        .catch(() => { authStatus.textContent = 'Register error.'; });
    });
  }

  if (authLogoutBtn) {
    authLogoutBtn.addEventListener('click', () => {
      const formData = new FormData();
      formData.append('action', 'logout');
      fetch('auth.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(() => {
          updateAuthUI(null);
        })
        .catch(() => {});
    });
  }

  // ===== Tag extractor (front-end mode for pasted text) =====
  function extractFromText(text) {
    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 m;
    while ((m = handleRegex.exec(text)) !== null) handles.push(m[0]);
    while ((m = hashtagRegex.exec(text)) !== null) hashtags.push(m[0]);
    while ((m = urlRegex.exec(text)) !== null) links.push(m[0]);
    while ((m = emailRegex.exec(text)) !== null) emails.push(m[0]);

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

  function buildSnippet(data, templateKey) {
    const handles = data.handles || [];
    const hashtags = data.hashtags || [];
    const links = data.links || [];

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

    if (templateKey === 'studio_footer') {
      return `<!-- Studio1Live Promo Footer -->
<section class="article-footer-promo">
  <h3>Support the Studio1Live Family</h3>
  ${handlesInline ? `<p><strong>Shoutouts:</strong> ${handlesInline}</p>` : ''}
  ${hashtagsInline ? `<p><strong>Tags:</strong> ${hashtagsInline}</p>` : ''}
  ${links.length ? `<ul>\n${linksHtml}\n  </ul>` : ''}
</section>`;
    }

    if (templateKey === 'youtube_shoutout') {
      return `# Shoutouts & Links

Shoutouts:
${handlesInline || '(none)'}

Links:
${links.length ? links.join('\n') : '(none)'}

Hashtags:
${hashtagsInline || '(none)'}`;
    }
if (templateKey === 'full_article') {
  const articleContent = (data.articleText && data.articleText.trim())
    ? data.articleText
    : 'PASTE YOUR ARTICLE CONTENT HERE';

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Your Article Title Here</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- SEO: edit me -->
  <meta name="description" content="Short description of this article.">
  <link rel="stylesheet" href="article.css">
</head>
<body>
  <main class="ls-main">
    <article class="ls-article">
${articleContent}
    </article>

    <footer class="ls-footer">
      ${handlesInline ? `<p><strong>Shoutouts:</strong> ${handlesInline}</p>` : ''}
      ${hashtagsInline ? `<p><strong>Tags:</strong> ${hashtagsInline}</p>` : ''}
      ${links.length ? `<ul>
${linksHtml}
      </ul>` : ''}
    </footer>
  </main>
</body>
</html>`;
}

    // default simple_footer
    return `<!-- Article Footer – Generated by LinkStorm Tag Extractor -->
<section class="article-footer">
  ${handlesInline ? `<p><strong>@Handles:</strong> ${handlesInline}</p>` : ''}
  ${hashtagsInline ? `<p><strong>#Hashtags:</strong> ${hashtagsInline}</p>` : ''}
  ${links.length ? `<ul>\n${linksHtml}\n  </ul>` : ''}
</section>`;
  }

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

  function renderResults(data, sourceLabel) {
    currentExtraction = data;

    resultsSection.classList.remove('hidden');
    snippetSection.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>
    `;

    const tpl = templateSelect.value || 'simple_footer';
    htmlFooterOutput.textContent = buildSnippet(data, tpl);
    hashtagsInlineOutput.textContent = buildHashtagInlineSnippet(data);
  }

  if (templateSelect) {
    templateSelect.addEventListener('change', () => {
      if (!currentExtraction) return;
      const tpl = templateSelect.value || 'simple_footer';
      htmlFooterOutput.textContent = buildSnippet(currentExtraction, tpl);
      hashtagsInlineOutput.textContent = buildHashtagInlineSnippet(currentExtraction);
    });
  }

  // Pasted text
 if (extractTextBtn) {
  extractTextBtn.addEventListener('click', () => {
    const text = inputText.value || '';
    if (!text.trim()) {
      alert('Paste some text first.');
      return;
    }
    currentSourceType = 'paste';
    currentSourceLabel = 'Pasted text';
    currentArticleText = text;              // ← store full article here
    const result = extractFromText(text);
    result.articleText = text;              // ← also store inside result
    renderResults(result, currentSourceLabel);
  });
}

  // Upload
  if (uploadForm) {
    uploadForm.addEventListener('submit', e => {
      e.preventDefault();
      const fileInput = document.getElementById('tagfile');
      if (!fileInput.files.length) {
        alert('Choose a file first.');
        return;
      }
      const formData = new FormData();
      formData.append('mode', 'file');
      formData.append('tagfile', fileInput.files[0]);
      currentSourceType = 'file';
      currentSourceLabel = fileInput.files[0].name;
      fetch('process.php', { method: 'POST', body: formData })
        .then(r => r.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,
  articleText: '' // file mode: no full article text
};
          renderResults(transformed, `Uploaded file: ${currentSourceLabel}`);
        })
        .catch(() => alert('Error processing file.'));
    });
  }

  // URL
  if (urlForm) {
    urlForm.addEventListener('submit', e => {
      e.preventDefault();
      const urlInput = document.getElementById('source_url');
      const url = urlInput.value.trim();
      if (!url) {
        alert('Enter a URL.');
        return;
      }
      const formData = new FormData();
      formData.append('mode', 'url');
      formData.append('source_url', url);
      currentSourceType = 'url';
      currentSourceLabel = url;
      fetch('process.php', { method: 'POST', body: formData })
        .then(r => r.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,
  articleText: '' // url mode: no full article text
};
          renderResults(transformed, `Fetched URL: ${url}`);
        })
        .catch(() => alert('Error fetching URL.'));
    });
  }

  // Save current extraction (requires login)
  if (saveSetBtn) {
    saveSetBtn.addEventListener('click', () => {
      if (!currentExtraction) {
        alert('Extract tags first.');
        return;
      }
      const name = setNameInput.value.trim();
      if (!name) {
        alert('Enter a name for this tag set.');
        return;
      }
      saveStatus.textContent = 'Saving...';
      const payload = {
        name,
        source_type: currentSourceType,
        source_label: currentSourceLabel,
        handles: currentExtraction.handles || [],
        hashtags: currentExtraction.hashtags || [],
        links: currentExtraction.links || [],
        emails: currentExtraction.emails || []
      };
      fetch('save_set.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
        .then(r => r.json())
        .then(data => {
          if (data.error) { saveStatus.textContent = data.error; return; }
          saveStatus.textContent = 'Saved (ID: ' + data.set_id + ')';
          setNameInput.value = '';
          loadSavedSets();
        })
        .catch(() => { saveStatus.textContent = 'Error saving set.'; });
    });
  }

  // Load saved sets for current user
  function loadSavedSets() {
    fetch('list_sets.php')
      .then(r => r.json())
      .then(data => {
        if (data.error) {
          console.warn(data.error);
          return;
        }
        const sets = data.sets || [];
        savedSetsSelect.innerHTML = '<option value="">-- Select a saved set --</option>';
        sets.forEach(s => {
          const opt = document.createElement('option');
          opt.value = s.id;
          opt.textContent = `${s.name} (${s.source_type})`;
          savedSetsSelect.appendChild(opt);
        });
      })
      .catch(() => {});
  }

  if (loadSetBtn) {
    loadSetBtn.addEventListener('click', () => {
      const id = savedSetsSelect.value;
      if (!id) {
        alert('Choose a set first.');
        return;
      }
      loadStatus.textContent = 'Loading...';
      fetch('list_sets.php?id=' + encodeURIComponent(id))
        .then(r => r.json())
        .then(data => {
          if (data.error) { loadStatus.textContent = data.error; return; }
          currentSourceType = data.source_type || 'paste';
          currentSourceLabel = data.source_label || ('Saved Set #' + data.id);
          const extraction = {
            handles: data.handles || [],
            hashtags: data.hashtags || [],
            links: data.links || [],
            emails: data.emails || [],
            textLength: 0
          };
          renderResults(extraction, currentSourceLabel);
          loadStatus.textContent = 'Loaded.';
        })
        .catch(() => { loadStatus.textContent = 'Error loading set.'; });
    });
  }

  // Copy buttons for any snippet / result box
  document.addEventListener('click', e => {
    if (e.target.matches('button[data-copy-target]')) {
      const targetId = e.target.getAttribute('data-copy-target');
      const el = document.getElementById(targetId);
      if (!el) return;
      const text = el.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. Select text manually.'));
    }
  });
});
