<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>MultiSearch Tag Explorer</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
        Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
      margin: 0; padding: 2rem;
      background: linear-gradient(145deg, #eef2f7, #ffffff);
      color: #2c3e50; min-height: 100vh;
      display: flex; flex-direction: column; align-items: center;
      -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;
      text-rendering: optimizeLegibility;
    }
    h1 {
      font-size: 2rem;
      margin-bottom: 1rem;
      color: #1a1a1a;
      text-align: center;
      line-height: 1.2;
    }
    form#searchForm {
      display: flex;
      max-width: 420px;
      width: 100%;
      margin: 1rem auto 2rem auto;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      border-radius: 8px;
      overflow: hidden;
      background: #fff;
    }
    #searchBox {
      flex-grow: 1;
      padding: 0.6rem 1rem;
      font-size: 1rem;
      border: none;
      outline: none;
    }
    #searchBox::placeholder {
      color: #999;
    }
    button[type="submit"] {
      background: #1a73e8;
      border: none;
      color: #fff;
      font-size: 1rem;
      padding: 0 1.2rem;
      cursor: pointer;
      transition: background-color 0.3s ease;
      user-select: none;
    }
    button[type="submit"]:hover,
    button[type="submit"]:focus {
      background: #155ab6;
      outline: none;
    }
    #searchResults {
      max-width: 420px;
      width: 100%;
      color: #2c3e50;
    }
    #searchResults a {
      font-weight: 600;
      color: #1a73e8;
      text-decoration: none;
    }
    #searchResults a:hover,
    #searchResults a:focus {
      text-decoration: underline;
      outline: none;
    }
    #searchResults div.result-item {
      margin-bottom: 1rem;
      background: #fff;
      padding: 0.75rem 1rem;
      border-radius: 6px;
      box-shadow: 0 1px 4px rgba(0,0,0,0.07);
    }
    #searchResults p.description {
      margin: 0.25rem 0 0.5rem 0;
      color: #444;
      font-size: 0.9rem;
      line-height: 1.3;
    }
    #searchResults div.tags {
      display: flex;
      flex-wrap: wrap;
      gap: 0.4rem;
    }
    #searchResults div.tags a {
      background: #e8f0fe;
      color: #1a73e8;
      padding: 0.15rem 0.6rem;
      font-size: 0.85rem;
      border-radius: 12px;
      text-decoration: none;
      user-select: none;
      white-space: nowrap;
      transition: background-color 0.3s ease;
    }
    #searchResults div.tags a:hover,
    #searchResults div.tags a:focus {
      background-color: #c3dafd;
      outline: none;
    }
    @media (max-width: 480px) {
      body {
        padding: 1rem;
      }
      h1 {
        font-size: 1.5rem;
      }
      form#searchForm {
        max-width: 100%;
      }
      #searchResults {
        max-width: 100%;
      }
    }
  </style>
</head>
<body>
  <h1>MultiSearch Tag Explorer</h1>
  <form id="searchForm" role="search" aria-label="Wikipedia search form">
    <input
      id="searchBox"
      type="search"
      name="q"
      placeholder="Search…"
      aria-label="Search Wikipedia"
      autocomplete="off"
      spellcheck="false"
      required
    />
    <button type="submit" aria-label="Submit search">Go</button>
  </form>
  <div id="searchResults" role="region" aria-live="polite" aria-atomic="true"></div>
  <script>
    const searchForm = document.getElementById('searchForm');
    const searchBox = document.getElementById('searchBox');
    const resultsDiv = document.getElementById('searchResults');
    const language = 'en';
    const defaultFallback = 'Technology';
    function decodeHTML(html) {
      const txt = document.createElement('textarea');
      txt.innerHTML = html;
      return txt.value;
    }
    function escapeHTML(str) {
      return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    }
    function extractTags(title) {
      const parts = title.split(/[^0-9\p{L}]+/u);
      return parts.filter(w => w.length > 1);
    }
    async function getLiveStartingTag() {
      const url = `https://${language}.wikipedia.org/w/api.php?action=query&list=recentchanges&rcnamespace=0&rclimit=5&rcprop=title|timestamp&rctype=edit&format=json&origin=*`;
      try {
        const res = await fetch(url);
        if (!res.ok) throw new Error();
        const data = await res.json();
        const changes = data.query?.recentchanges || [];
        for (let change of changes) {
          const fullTitle = decodeHTML(change.title).trim();
          if (fullTitle.length > 0 && !fullTitle.includes(':')) {
            return fullTitle; 
          }
        }
        return defaultFallback;
      } catch (e) {
        console.error("");
        return defaultFallback;
      }
    }
    function updateURLQuery(query) {
      const newUrl = new URL(window.location);
      if (query) {
        newUrl.searchParams.set('q', query);
      } else {
        newUrl.searchParams.delete('q');
      }
      history.pushState(null, '', newUrl);
    }
    function updateTitle(query) {
      if (query) {
        document.title = `${query}`;
      } else {
        document.title = '';
      }
    }
    async function performSearch(query) {
      updateTitle(query);
      resultsDiv.textContent = '';
      window.scrollTo({ top: 0, behavior: 'smooth' });
      const apiUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(query)}&format=json&origin=*`;
      try {
        const res = await fetch(apiUrl);
        if (!res.ok) throw new Error('Network error');
        const data = await res.json();
        if (!data.query || data.query.search.length === 0) {
          if (query.toLowerCase() !== defaultFallback.toLowerCase()) {
            console.warn(`"${query}" "${defaultFallback}"...`);
            searchBox.value = defaultFallback;
            updateURLQuery(defaultFallback);
            performSearch(defaultFallback);
          } else {
            resultsDiv.textContent = '';
          }
          return;
        }
        resultsDiv.innerHTML = data.query.search
          .map(item => {
            const cleanTitle = decodeHTML(item.title);
            const rawSnippet = item.snippet.replace(/<\/?span[^>]*>/g, '');
            const cleanSnippet = decodeHTML(rawSnippet);
            const tags = extractTags(cleanTitle);
            const safeTitle = escapeHTML(cleanTitle);
            const safeSnippet = escapeHTML(cleanSnippet);
            const tagsHtml = tags.map(tag => {
              const encodedTag = encodeURIComponent(tag);
              return `<a href="?q=${encodedTag}" class="tag-link" aria-label="Search for tag ${tag}">${escapeHTML(tag)}</a>`;
            }).join(' ');
            const secondaryEngines = [
              { id: 'gg', name: 'Google', url: `https://www.google.com/search?q=${encodeURIComponent(cleanTitle)}` },
              { id: 'yh', name: 'Yahoo', url: `https://search.yahoo.com/search?p=${encodeURIComponent(cleanTitle)}` },
              { id: 'bg', name: 'Bing', url: `https://www.bing.com/search?q=${encodeURIComponent(cleanTitle)}` },
              { id: 'yd', name: 'Yandex', url: `https://yandex.com/search/?text=${encodeURIComponent(cleanTitle)}` },
              { id: 'bd', name: 'Baidu', url: `https://www.baidu.com/s?wd=${encodeURIComponent(cleanTitle)}` },
              { id: 'dd', name: 'DuckGo', url: `https://duckduckgo.com/?q=${encodeURIComponent(cleanTitle)}` }
            ];
            const shuffled = secondaryEngines.sort(() => 0.5 - Math.random());
            const randomThree = shuffled.slice(0, 3);
            const dynamicEnginesHtml = randomThree.map(engine => {
              return `<a href="${engine.url}" target="_blank" class="future-link ${engine.id}">${engine.name}</a>`;
            }).join('');
            return `<div class="result-item">
              <a href="?q=${encodeURIComponent(cleanTitle)}" class="tag-link result-title" style="font-size: 1.2em; font-weight: bold; text-decoration: none;">${safeTitle}</a>
              <div class="search-engines-wrapper">
                <style>
                  .future-search-container {
                    display: flex !important;
                    flex-wrap: wrap !important;
                    gap: 12px 18px;
                    justify-content: flex-start !important;
                    width: 100% !important;
                    margin-top: 12px;
                    margin-bottom: 8px;
                  }
                  .future-link {
                    position: relative;
                    display: inline-flex !important;
                    align-items: center;
                    flex-shrink: 0 !important;
                    font-size: 0.72rem;
                    font-weight: 500;
                    text-decoration: none;
                    text-transform: uppercase;
                    letter-spacing: 1.5px;
                    color: #94a3b8;
                    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
                    padding-bottom: 4px;
                    transition: color 0.25s ease;
                  }
                  .future-link::after {
                    content: '';
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    width: 0;
                    height: 1px;
                    transition: width 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
                  }
                  .future-link:hover::after {
                    width: 100%;
                  }
                  .future-link.wp:hover { color: #000000; }
                  .future-link.wp::after { background: #000000; }
                  .future-link.gg:hover { color: #4285F4; }
                  .future-link.gg::after { background: #4285F4; box-shadow: 0 0 4px #4285F4; }
                  .future-link.yh:hover { color: #a855f7; }
                  .future-link.yh::after { background: #a855f7; box-shadow: 0 0 4px #a855f7; }
                  .future-link.bg:hover { color: #00A4EF; }
                  .future-link.bg::after { background: #00A4EF; box-shadow: 0 0 4px #00A4EF; }
                  .future-link.yd:hover { color: #ef4444; }
                  .future-link.yd::after { background: #ef4444; box-shadow: 0 0 4px #ef4444; }
                  .future-link.bd:hover { color: #3b82f6; }
                  .future-link.bd::after { background: #3b82f6; box-shadow: 0 0 4px #3b82f6; }
                  .future-link.dd:hover { color: #f97316; }
                  .future-link.dd::after { background: #f97316; box-shadow: 0 0 4px #f97316; }
                  .future-link:active {
                    opacity: 0.5;
                  }
                </style>
                <div class="future-search-container">
                  <a href="https://en.wikipedia.org/wiki/${encodeURIComponent(cleanTitle)}" target="_blank" class="future-link wp">Wiki</a>
                  ${dynamicEnginesHtml}
                </div>
              </div>
              <p class="description">${safeSnippet}...</p>
              <div class="tags" aria-label="Tags">${tagsHtml}</div>
            </div>`;
          })
          .join('');
      } catch (e) {
        resultsDiv.textContent = '';
        console.error(e);
      }
    }
    searchForm.addEventListener('submit', e => {
      e.preventDefault();
      const query = searchBox.value.trim();
      if (query.length === 0) {
        resultsDiv.textContent = '';
        updateURLQuery('');
        updateTitle('');
        return;
      }
      updateURLQuery(query);
      performSearch(query);
    });
    resultsDiv.addEventListener('click', e => {
      if (e.target.classList.contains('tag-link')) {
        e.preventDefault();
        const urlParams = new URLSearchParams(e.target.search);
        const tagQuery = urlParams.get('q');
        if (tagQuery) {
          searchBox.value = tagQuery;
          updateURLQuery(tagQuery);
          performSearch(tagQuery);
        }
      }
    });
    window.addEventListener('popstate', () => {
      const urlParams = new URLSearchParams(window.location.search);
      const q = urlParams.get('q') || '';
      searchBox.value = q;
      if (q) {
        performSearch(q);
      } else {
        resultsDiv.textContent = '';
        updateTitle('');
      }
    });
    window.addEventListener('DOMContentLoaded', async () => {
      const urlParams = new URLSearchParams(window.location.search);
      const q = urlParams.get('q');
      if (q) {
        searchBox.value = q;
        performSearch(q);
      } else {
        resultsDiv.textContent = '';
        const liveExpression = await getLiveStartingTag();
        searchBox.value = liveExpression;
        performSearch(liveExpression);
      }
    });
  </script>
  <footer style="margin-top: 0; padding: 1rem; text-align: center; color: #888; font-size: 0.9rem; user-select: none; background-color: #f9f9f9; border-top: 1px solid #eee;">
  <div style="margin-bottom: 0.5rem;">
    &copy; aéPiot - MultiSearch Tag Explorer. All rights reserved.
  </div>
  <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 0.3rem; font-size: 0.85rem;">
    <a href="https://headlines-world.com/" target="_self" style="color: #555; text-decoration: none; transition: color 0.3s;">Headlines World</a>
    <a href="https://aepiot.com/" target="_self" style="color: #555; text-decoration: none; transition: color 0.3s;">aéPiot.com</a>
    <a href="https://aepiot.ro/" target="_self" style="color: #555; text-decoration: none; transition: color 0.3s;">aéPiot.ro</a>
    <a href="https://allgraph.ro/" target="_self" style="color: #555; text-decoration: none; transition: color 0.3s;">allGraph</a>
  </div>
  </footer>
  <script>
    (function() {
        const linkSettings = [
            ["band, orchestra, choir, voice, piano, instrumental, genre, digital, teacher", "https://www.sheetmusicplus.com/en/explore?aff_id=541503&q=%s", 3],
            ["music, sheet music", "https://www.sheetmusicplus.com?aff_id=541503", 1]
        ];
        const randomSettings = [
            ["https://www.sheetmusicplus.com?aff_id=541503", 1],
            ["https://www.sheetmusicplus.com/en/explore?aff_id=541503&q=%s", 10]
        ];
        const blueWords = linkSettings.flatMap(([wordsString]) => 
            wordsString.split(',').map(w => w.trim().toLowerCase())
        );
        const injectStyles = () => {
            if (document.getElementById('combined-dynamic-styles')) return;
            const style = document.createElement('style');
            style.id = 'combined-dynamic-styles';
            style.innerHTML = `
            .dynamic-link { 
                color: #4f46e5 !important; 
                font-weight: 700 !important; 
                font-size: 1.1em !important;
                text-decoration: none !important; 
                background: rgba(79, 70, 229, 0.05) !important;
                border: 1px solid rgba(79, 70, 229, 0.3) !important;
                padding: 2px 6px !important;
                border-radius: 6px !important;
                box-shadow: 0 2px 4px rgba(79, 70, 229, 0.08) !important;
                transition: all 0.2s ease; 
                cursor: help !important; 
                display: inline-block;
            }
            .dynamic-link:hover { 
                background: rgba(79, 70, 229, 0.12) !important;
                border-color: #4f46e5 !important;
                box-shadow: 0 4px 8px rgba(79, 70, 229, 0.15) !important;
                transform: translateY(-1px);
            }
            .random-link { 
                color: #059669 !important; 
                font-weight: 700 !important; 
                font-size: 1.1em !important;
                text-decoration: none !important; 
                background: rgba(5, 150, 105, 0.05) !important;
                border: 1px solid rgba(5, 150, 105, 0.3) !important;
                padding: 2px 6px !important; 
                border-radius: 6px !important; 
                box-shadow: 0 2px 4px rgba(5, 150, 105, 0.08) !important; 
                transition: all 0.2s ease; 
                cursor: help !important; 
                display: inline-block;
            }
            .random-link:hover { 
                background: rgba(5, 150, 105, 0.12) !important; 
                border-color: #059669 !important; 
                box-shadow: 0 4px 8px rgba(5, 150, 105, 0.15) !important; 
                transform: translateY(-1px); 
            }
            .premium-tooltip { position: fixed; z-index: 2147483647; background: rgba(255, 255, 255, 0.98); backdrop-filter: blur(8px); border: 1px solid #d1d5db; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); padding: 18px 22px; border-radius: 18px; font-family: sans-serif; pointer-events: none; display: none; width: calc(100% - 40px); max-width: 320px; opacity: 0; transform: translateY(15px) scale(0.95); transition: opacity 0.2s ease, transform 0.2s ease; box-sizing: border-box; color: #000; }
            .t-label { font-size: 11px; font-weight: 800; text-transform: uppercase; color: #4338ca; letter-spacing: 1.2px; display: block; margin-bottom: 6px; }
            .t-title { font-size: 20px; font-weight: 800; color: #000000; display: block; margin-bottom: 2px; }
            .t-source { font-size: 12px; color: #4f46e5; font-weight: 700; display: block; margin-bottom: 12px; }
            .t-desc { font-size: 14px; color: #1f2937; border-top: 1px solid #f3f4f6; padding-top: 12px; line-height: 1.5; }
            @media (max-width: 768px) { .premium-tooltip { left: 20px !important; right: 20px !important; bottom: 30px !important; top: auto !important; max-width: none; width: auto; } }
        `;
            document.head.appendChild(style);
        };
        let tooltip;
        const createTooltip = () => {
            if (document.querySelector('.premium-tooltip')) { tooltip = document.querySelector('.premium-tooltip'); return; }
            tooltip = document.createElement('div');
            tooltip.className = 'premium-tooltip';
            document.body.appendChild(tooltip);
        };
        const getDomain = (url) => {
            try { return new URL(url.replace('%s', 'search')).hostname.replace('www.', ''); } catch(e) { return "External Link"; }
        };
        function shuffle(array) {
            for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; }
            return array;
        }
        let isProcessing = false;
        function processAllLinks() {
            if (isProcessing) return;
            isProcessing = true;
            linkSettings.forEach(([wordsString, urlPattern, limit]) => {
                const wordsArray = wordsString.split(',').map(c => c.trim());
                const domain = getDomain(urlPattern);
                wordsArray.forEach(word => {
                    const instances = [];
                    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
                    let node;
                    while(node = walker.nextNode()) {
                        const parent = node.parentElement;
                        if (!parent || parent.closest('.dynamic-link') || parent.closest('.random-link') || ['SCRIPT', 'STYLE', 'A', 'FOOTER', 'NAV', 'HEADER', 'BUTTON', 'INPUT', 'TEXTAREA', 'H1', 'H2', 'H3'].includes(parent.tagName)) continue;
                        const regex = new RegExp(`\\b(${word})\\b`, "gi");
                        if (regex.test(node.nodeValue)) { instances.push({ node, regex }); }
                    }
                    const shuffledInstances = shuffle(instances);
                    let count = 0;
                    shuffledInstances.forEach(item => {
                        if (count < limit && item.node.parentNode) {
                            const span = document.createElement('span');
                            span.innerHTML = item.node.nodeValue.replace(item.regex, (match) => {
                                if (count < limit) { count++; return `<a href="${urlPattern.includes('%s') ? urlPattern.replace('%s', encodeURIComponent(match)) : urlPattern}" target="_blank" class="dynamic-link" data-t="${match}" data-d="${domain}" data-type="indigo">${match}</a>`; }
                                return match;
                            });
                            if (span.innerHTML !== item.node.nodeValue) { item.node.parentNode.replaceChild(span, item.node); }
                        }
                    });
                });
            });
            const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
       let node; 
       let textNodes = [];
       while(node = walker.nextNode()) {
       const parent = node.parentElement;
    if (!parent || 
        parent.closest('.dynamic-link') || 
        parent.closest('.random-link') || 
        parent.closest('#mw-footer, .mw-footer, footer, #footer, .catlinks, #catlinks') || 
        parent.closest('h1, h2, h3, H1, H2, H3') ||
        ['SCRIPT', 'STYLE', 'A', 'FOOTER', 'NAV', 'HEADER', 'BUTTON', 'INPUT', 'TEXTAREA'].includes(parent.tagName)) {
        continue;
    }
    if (node.nodeValue.trim().length > 0) {
        textNodes.push(node);
        }
    }
            textNodes.sort(() => Math.random() - 0.5);
            randomSettings.forEach(([urlPattern, limit]) => {
                let appliedCount = 0; const domain = getDomain(urlPattern);
                for (let i = 0; i < textNodes.length && appliedCount < limit; i++) {
                    let targetNode = textNodes[i]; if (!targetNode.parentNode) continue;
                    const words = targetNode.nodeValue.match(/[a-zA-Z]{3,12}/g);
                    if (words && words.length > 0) {
                        const picked = words[Math.floor(Math.random() * words.length)];
                        const regex = new RegExp(`\\b(${picked})\\b`, "i");
                        const span = document.createElement('span');
                        span.innerHTML = targetNode.nodeValue.replace(regex, `<a href="${urlPattern.includes('%s') ? urlPattern.replace('%s', encodeURIComponent(picked)) : urlPattern}" target="_blank" class="random-link" data-t="${picked}" data-d="${domain}" data-type="emerald">${picked}</a>`);
                        if (span.innerHTML !== targetNode.nodeValue) { targetNode.parentNode.replaceChild(span, targetNode); appliedCount++; textNodes.splice(i, 1); i--; }
                    }
                }
            });
            setTimeout(() => { isProcessing = false; }, 50);
        }
        const showTooltip = (link) => {
            const { t, d, type } = link.dataset;
            if (type === 'emerald') {
                tooltip.innerHTML = `<span class="t-label" style="color: #059669;">Discovery Mode</span><span class="t-title">${t}</span><span class="t-source" style="color: #059669;">Resource: ${d}</span><div class="t-desc">Explore more about "<b>${t}</b>".</div>`;
            } else {
                tooltip.innerHTML = `<span class="t-label">Quick Insight</span><span class="t-title">${t}</span><span class="t-source">Resource: ${d}</span><div class="t-desc">Discover more about "<b>${t}</b>".</div>`;
            }
            tooltip.style.display = 'block';
            if (window.innerWidth > 768) { setTimeout(() => { tooltip.style.opacity = '1'; tooltip.style.transform = 'translateY(0) scale(1)'; }, 10); } else { tooltip.classList.add('active'); tooltip.style.opacity = '1'; }
        };
        const hideTooltip = () => {
            if (!tooltip) return; tooltip.style.opacity = '0';
            if (window.innerWidth > 768) { tooltip.style.transform = 'translateY(15px) scale(0.95)'; } else { tooltip.classList.remove('active'); }
            setTimeout(() => { if(tooltip && tooltip.style.opacity === '0') tooltip.style.display = 'none'; }, 200);
        };
        document.addEventListener('mouseover', (e) => { const link = e.target.closest('.dynamic-link, .random-link'); if (link) showTooltip(link); });
        document.addEventListener('mousemove', (e) => { if (window.innerWidth > 768 && tooltip && tooltip.style.display === 'block') { let x = e.clientX + 20; let y = e.clientY + 20; if (x + tooltip.offsetWidth > window.innerWidth) x = e.clientX - tooltip.offsetWidth - 20; if (y + tooltip.offsetHeight > window.innerHeight) y = e.clientY - tooltip.offsetHeight - 20; tooltip.style.left = x + 'px'; tooltip.style.top = y + 'px'; } });
        document.addEventListener('mouseout', (e) => { if (e.target.closest('.dynamic-link, .random-link')) hideTooltip(); });
        function init() {
            injectStyles(); createTooltip(); processAllLinks();
            const observer = new MutationObserver((mutations) => {
                let shouldProcess = false;
                for (let mutation of mutations) {
                    if (mutation.target.closest && (mutation.target.closest('.premium-tooltip') || mutation.target.closest('.dynamic-link') || mutation.target.closest('.random-link'))) continue;
                    shouldProcess = true; break;
                }
                if (shouldProcess && !isProcessing) { clearTimeout(window.dynamicLinkTimeout); window.dynamicLinkTimeout = setTimeout(processAllLinks, 500); }
            });
            observer.observe(document.body, { childList: true, subtree: true });
        }
        if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); }
    })();
    </script>
</body>
</html>