"use strict";var FindoraWidget=(()=>{var u=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var S=(s,t)=>{for(var e in t)u(s,e,{get:t[e],enumerable:!0})},T=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of k(t))!C.call(s,r)&&r!==e&&u(s,r,{get:()=>t[r],enumerable:!(i=E(t,r))||i.enumerable});return s};var L=s=>T(u({},"__esModule",{value:!0}),s);var H={};S(H,{FindoraWidget:()=>d,default:()=>B});var m={"pt-BR":{searchPlaceholder:"Digite sua pesquisa...",searchSite:"Pesquisar no site",toNavigate:"para navegar",toSelect:"para selecionar",toClose:"para fechar",noResults:"Nenhum resultado encontrado",searchError:"Erro ao realizar a pesquisa. Tente novamente.",loadingText:"Buscando..."},en:{searchPlaceholder:"Type to search...",searchSite:"Search website",toNavigate:"to navigate",toSelect:"to select",toClose:"to close",noResults:"No results found",searchError:"Search error. Please try again.",loadingText:"Searching..."}};function g(s){return m[s]||m["pt-BR"]}function w(){return(typeof navigator<"u"&&(navigator.language||navigator.userLanguage)||"").startsWith("pt")?"pt-BR":"en"}var I=` self.onmessage = async ({ data }) => { const encoder = new TextEncoder(); const hasLeadingZeroBits = (bytes, difficulty) => { const fullBytes = Math.floor(difficulty / 8); const remainingBits = difficulty % 8; for (let index = 0; index < fullBytes; index += 1) { if (bytes[index] !== 0) return false; } return remainingBits === 0 || (bytes[fullBytes] & (0xff << (8 - remainingBits))) === 0; }; for (let proof = 0; proof < Number.MAX_SAFE_INTEGER; proof += 1) { const digest = new Uint8Array( await crypto.subtle.digest('SHA-256', encoder.encode(data.challengeToken + ':' + proof)), ); if (hasLeadingZeroBits(digest, data.difficulty)) { self.postMessage({ proof }); return; } } self.postMessage({ error: 'proof indisponivel' }); }; `,h=class{constructor(t,e=1e4){this.widgetSession=null;this.widgetSessionPromise=null;this.apiUrl=t.replace(/\/$/,""),this.timeout=e}async getConfig(){return await this.getConfigFromEndpoint()}async getConfigFromEndpoint(){let t=new AbortController,e=setTimeout(()=>t.abort(),this.timeout);try{let i=await fetch(`${this.apiUrl}/config`,{method:"GET",signal:t.signal});if(clearTimeout(e),!i.ok)return null;let r=await i.json();if(!r.success)return null;let o=r.result;return o?"result"in o?o.result||null:o:null}catch{return clearTimeout(e),null}}async search(t,e=0,i=10,r){try{let o={query:t.trim(),page:e,limit:i};r&&r.length>0&&(o.excludePageIds=r);let n=await this.fetchWithWidgetSession("/search",o);n.status===401&&(this.widgetSession=null,n=await this.fetchWithWidgetSession("/search",o));let a=await n.json();if(!n.ok)throw new Error(a.error||`HTTP ${n.status}: ${n.statusText}`);if(!a.success)throw new Error(a.error||"Unknown error");let l=a.result?.result||a.result,p=(l?.results||[]).map(c=>({page_id:Number(c.page_id??c.pageId??0),url:String(c.url||""),title:String(c.title||""),featured_image:c.featured_image??c.featuredImage??null,excerpt:String(c.excerpt||""),relevance:Number(c.relevance||0),chunk_id:String(c.chunk_id??c.chunkId??"")})),x=l?.totalCount??l?.totalResults??p.length,y=l?.hasMore??!1;return{results:p,totalResults:x,hasMore:y}}catch(o){throw o instanceof Error?o.name==="AbortError"?new Error("Request timeout"):o:new Error("Unknown error occurred")}}async recordEvent(t){try{let e=await this.ensureWidgetSession();await fetch(`${this.apiUrl}/event`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),keepalive:!0})}catch{}}async fetchWithWidgetSession(t,e){let i=await this.ensureWidgetSession(),r=new AbortController,o=setTimeout(()=>r.abort(),this.timeout);try{return await fetch(`${this.apiUrl}${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(e),signal:r.signal})}finally{clearTimeout(o)}}async ensureWidgetSession(){return this.widgetSession&&this.widgetSession.expiresAt-15e3>Date.now()?this.widgetSession.token:(this.widgetSessionPromise||(this.widgetSessionPromise=this.createWidgetSession().finally(()=>{this.widgetSessionPromise=null})),await this.widgetSessionPromise)}async createWidgetSession(){let t=await fetch(`${this.apiUrl}/widget/challenge`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),e=await t.json();if(!t.ok||!e.success||!e.result)throw new Error(e.error||"Widget challenge unavailable");let i=await this.solveProofOfWork(e.result.challengeToken,e.result.difficulty),r=await fetch(`${this.apiUrl}/widget/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challengeToken:e.result.challengeToken,proof:i})}),o=await r.json();if(!r.ok||!o.success||!o.result)throw new Error(o.error||"Widget session unavailable");let n=Date.parse(o.result.expiresAt);if(!Number.isFinite(n))throw new Error("Widget session expiration is invalid");return this.widgetSession={token:o.result.token,expiresAt:n},o.result.token}async solveProofOfWork(t,e){if(typeof Worker<"u"&&typeof Blob<"u")try{return await this.solveProofOfWorkInWorker(t,e)}catch{}return await this.solveProofOfWorkAsync(t,e)}solveProofOfWorkInWorker(t,e){return new Promise((i,r)=>{let o=URL.createObjectURL(new Blob([I],{type:"text/javascript"})),n=new Worker(o),a=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(o),r(new Error("Widget proof timeout"))},Math.max(this.timeout*3,3e4));n.onmessage=({data:l})=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(o),typeof l.proof=="number"?i(l.proof):r(new Error(l.error||"Widget proof unavailable"))},n.onerror=()=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(o),r(new Error("Widget proof worker failed"))},n.postMessage({challengeToken:t,difficulty:e})})}async solveProofOfWorkAsync(t,e){let i=new TextEncoder;for(let r=0;r0&&r%256===0&&await new Promise(n=>setTimeout(n,0))}throw new Error("Widget proof unavailable")}hasLeadingZeroBits(t,e){let i=Math.floor(e/8),r=e%8;for(let o=0;o{if(!this.state.hasMore||this.state.isLoading||this.isFetchingMore||this.state.results.length===0||!this.resultsEl)return;if(this.resultsEl.scrollTop+this.resultsEl.clientHeight>=this.resultsEl.scrollHeight-W){let i=this.state.page+1;this.isFetchingMore=!0,this.performSearch(this.state.query,i,!0)}};let e=t.language||w();this.translations=g(e),this.config={apiUrl:t.apiUrl||window.location.origin,position:this.isWidgetPosition(t.position)?t.position:v,theme:t.theme||"light",language:e,mode:t.mode||"modal",siteConfig:t.siteConfig,primaryColor:t.primaryColor,placeholder:t.placeholder,siteName:t.siteName},this.apiClient=new h(this.config.apiUrl),this.state={isOpen:!1,results:[],selectedIndex:-1,page:0,hasMore:!1,error:null,isLoading:!1,query:"",totalResults:0}}init(){this.injectStyles(),this.config.mode==="native"&&this.config.siteConfig?this.setupNativeMode():(this.createButton(),this.createModal(),this.attachEventListeners()),this.applyVisualConfig(),this.loadPublicConfig(),window.findoraWidgetInstance=this}setupNativeMode(){let t=this.config.siteConfig,e=document.querySelector(t.inputSelector);if(!e){console.error("[FindoraWidget] Native input not found:",t.inputSelector);return}this.nativeInputEl=e;let i=null;this.nativeInputHandler=o=>{let a=o.target.value.trim();if(i&&clearTimeout(i),a.length<3){this.clearNativeResults();return}i=setTimeout(()=>{this.injectIntoNativeSearch(a)},300)};let r=t.inputEvent==="both"?"input":t.inputEvent;e.addEventListener(r,this.nativeInputHandler),t.inputEvent==="both"&&e.addEventListener("keyup",this.nativeInputHandler)}clearNativeResults(){let t=this.config.siteConfig;if(!t)return;let e=document.querySelector(t.dropdownSelector);e&&(e.innerHTML="",e.classList.remove("active"))}openModalWithQuery(t){this.state.isOpen=!0,this.modalEl?.classList.add("fw-modal-open"),this.inputEl&&(this.inputEl.value=t,this.inputEl.dispatchEvent(new Event("input",{bubbles:!0}))),this.inputEl?.focus();let e=document.getElementById("search-results");e&&e.classList.remove("active")}cleanTitle(t){return t.replace(/\s[-–—|]\s*[^|–—-]{2,120}?(?:\s*(?:Comments|Comentarios|Comentários))\s*$/i,"")}escapeHtml(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}async loadPublicConfig(){let t=await this.apiClient.getConfig();t&&this.applyRuntimeConfig(t)}applyRuntimeConfig(t){this.config.primaryColor=t.widget?.color||this.config.primaryColor,this.config.placeholder=t.widget?.placeholder||this.config.placeholder,this.config.siteName=t.siteName||t.domain?.hostname||this.config.siteName,this.isWidgetPosition(t.widget?.position)&&(this.config.position=t.widget.position),this.isWidgetTheme(t.widget?.theme)&&(this.config.theme=t.widget.theme),this.applyVisualConfig(),this.applyWidgetClasses(),this.inputEl&&(this.inputEl.placeholder=this.getPlaceholder());let e=document.getElementById("fw-site-name");e&&(e.textContent=this.getDisplaySiteName())}applyVisualConfig(){let t=this.config.primaryColor?.trim();!t||!/^#[0-9a-f]{6}$/i.test(t)||(document.documentElement.style.setProperty("--fw-primary",t),document.documentElement.style.setProperty("--fw-primary-strong",t))}isWidgetPosition(t){return t==="bottom-right"||t==="bottom-left"||t==="top-right"||t==="top-left"}isWidgetTheme(t){return t==="light"||t==="dark"}getPositionClass(){return this.config.position===v?"":`fw-${this.config.position}`}getThemeClass(){return this.config.theme==="dark"?"fw-theme-dark":""}applyWidgetClasses(){let t=this.getPositionClass(),e=this.getThemeClass();this.buttonEl&&(this.buttonEl.className=["fw-btn-search",t,e].filter(Boolean).join(" ")),this.modalEl&&(this.modalEl.className=["fw-modal-overlay",this.state.isOpen?"fw-modal-open":"",e].filter(Boolean).join(" "))}showResultsContainer(){this.resultsEl?.classList.add("fw-results","fw-results-container")}hideResultsContainer(){this.resultsEl?.classList.remove("fw-results","fw-results-container")}getDisplaySiteName(){return this.config.siteName?.trim()||window.location.hostname}getPlaceholder(){return this.config.placeholder?.trim()||this.translations.searchPlaceholder}getFallbackImageUrl(){let t=['meta[property="og:image"]','meta[name="twitter:image"]','meta[itemprop="image"]','link[rel~="apple-touch-icon"]','link[rel~="icon"]','link[rel="shortcut icon"]','img[alt*="logo" i]','img[class*="logo" i]','img[src*="logo" i]'];for(let e of t){let i=document.querySelector(e),r=i instanceof HTMLMetaElement?i.content:i instanceof HTMLLinkElement?i.href:i?.currentSrc||i?.src,o=this.resolveImageUrl(r);if(o)return o}return f}resolveImageUrl(t){let e=t?.trim();if(!e)return null;try{return new URL(e,window.location.href).toString()}catch{return null}}getResultImageUrl(t){return this.resolveImageUrl(t)||this.getFallbackImageUrl()}getRelativePath(t){try{let e=new URL(t,window.location.href);return`${e.pathname}${e.search}`||"/"}catch{return t}}getImageErrorFallback(t){return t===f?"":`this.onerror=null;this.src='${f}';`}injectStyles(){let t="fw-widget-styles";if(document.getElementById(t))return;let e=` :root { --fw-bg: oklch(98% 0.006 240); --fw-surface: oklch(100% 0 0); --fw-surface-soft: oklch(96.8% 0.01 250); --fw-fg: oklch(21% 0.035 255); --fw-muted: oklch(52% 0.035 255); --fw-muted-2: oklch(67% 0.025 255); --fw-border: oklch(88% 0.018 255); --fw-primary: oklch(58% 0.18 250); --fw-primary-strong: oklch(51% 0.2 252); --fw-primary-soft: oklch(94% 0.035 250); --fw-highlight: oklch(91% 0.08 84); --fw-overlay: oklch(18% 0.04 255 / 0.52); --fw-shadow: 0 26px 80px oklch(18% 0.035 255 / 0.22), 0 4px 16px oklch(18% 0.035 255 / 0.1); --fw-radius: 22px; --fw-radius-sm: 14px; --fw-modal-width: 42rem; --fw-font-body: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } .fw-modal-overlay { position: fixed; inset: 0; z-index: 99999; display: none; place-items: start center; padding: clamp(20px, 7vh, 76px) 18px 18px; background: var(--fw-overlay); backdrop-filter: blur(18px) saturate(1.15); -webkit-backdrop-filter: blur(18px) saturate(1.15); } .fw-modal-overlay.fw-modal-open { display: grid; animation: fw-overlay-in 160ms ease-out; } .fw-modal-overlay.fw-modal-closing { display: grid; animation: fw-fade-out 160ms ease-out forwards; } @keyframes fw-overlay-in { from { opacity: 0; } to { opacity: 1; } } @keyframes fw-fade-out { from { opacity: 1; } to { opacity: 0; } } @keyframes fw-modal-in { from { opacity: 0; transform: translateY(10px) scale(0.985); } to { opacity: 1; transform: translateY(0) scale(1); } } #searchButton { position: fixed; right: 24px; bottom: 24px; z-index: 99999; } #searchButton.fw-bottom-left { left: 24px; right: auto; } #searchButton.fw-top-right { top: 24px; bottom: auto; } #searchButton.fw-top-left { top: 24px; right: auto; bottom: auto; left: 24px; } .fw-theme-dark { --fw-bg: oklch(16% 0.025 255); --fw-surface: oklch(20% 0.026 255); --fw-surface-soft: oklch(25% 0.03 255); --fw-fg: oklch(95% 0.01 255); --fw-muted: oklch(74% 0.022 255); --fw-muted-2: oklch(62% 0.022 255); --fw-border: oklch(36% 0.028 255); --fw-overlay: oklch(8% 0.03 255 / 0.68); --fw-shadow: 0 26px 80px oklch(0% 0 0 / 0.46), 0 4px 16px oklch(0% 0 0 / 0.22); } .fw-btn-search { appearance: none !important; -webkit-appearance: none !important; width: 64px !important; min-width: 64px !important; height: 64px !important; display: inline-flex !important; align-items: center; justify-content: center; padding: 0 !important; margin: 0 !important; border: 0 !important; border-radius: 999px !important; color: white !important; background: linear-gradient(135deg, var(--fw-primary), var(--fw-primary-strong)) !important; box-shadow: 0 18px 45px oklch(51% 0.2 252 / 0.38), 0 5px 14px oklch(18% 0.035 255 / 0.18) !important; cursor: pointer; line-height: 1 !important; text-transform: none !important; transition: transform 160ms ease, box-shadow 160ms ease, filter 160ms ease !important; will-change: transform; } .fw-btn-search:hover { transform: translateY(-2px); filter: saturate(1.05); box-shadow: 0 22px 52px oklch(51% 0.2 252 / 0.42), 0 8px 18px oklch(18% 0.035 255 / 0.18) !important; } .fw-btn-search .fw-btn-icon { width: 26px; height: 26px; stroke-width: 2.15; } .fw-container { width: min(var(--fw-modal-width), calc(100vw - 36px)); max-height: min(780px, calc(100vh - 110px)); display: flex; flex-direction: column; margin-inline: auto; } .fw-modal-content { position: relative; width: 100%; min-height: 420px; max-height: min(780px, calc(100vh - 110px)); display: flex; flex-direction: column; overflow: hidden; isolation: isolate; font-family: var(--fw-font-body); color: var(--fw-fg); background: var(--fw-surface); border: 1px solid color-mix(in oklch, var(--fw-border), transparent 15%); border-radius: var(--fw-radius); box-shadow: var(--fw-shadow); animation: fw-modal-in 180ms ease-out; } .fw-modal-content::before { content: ''; position: absolute; inset: 0; pointer-events: none; border-radius: inherit; box-shadow: inset 0 1px 0 oklch(100% 0 0 / 0.72); z-index: -1; } .fw-modal-header { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 24px 26px 16px; } .fw-modal-title-group { min-height: 38px; min-width: 0; display: flex; align-items: center; } .fw-modal-site-title { margin: 0; color: var(--fw-fg); font-size: clamp(0.95rem, 1.5vw, 1.15rem); font-weight: 760; line-height: 1.1; letter-spacing: -0.02em; } .fw-modal-subtitle { margin: 7px 0 0; color: var(--fw-muted); font-size: 0.9rem; line-height: 1.4; } .fw-modal-close-mobile { flex: 0 0 auto; display: flex; justify-content: flex-end; padding: 0; } .fw-modal-close-btn, .fw-clear-btn { appearance: none !important; -webkit-appearance: none !important; min-width: 0 !important; margin: 0 !important; border: 0 !important; box-shadow: none !important; text-transform: none !important; will-change: auto !important; } .fw-modal-close-btn { width: 36px !important; height: 36px !important; display: inline-flex !important; align-items: center; justify-content: center; padding: 0 !important; color: var(--fw-muted) !important; background: transparent !important; border-radius: 999px !important; cursor: pointer; line-height: 1 !important; transition: background-color 140ms ease, color 140ms ease !important; transform: none !important; } .fw-modal-close-btn:hover { color: var(--fw-fg) !important; background: var(--fw-surface-soft) !important; box-shadow: none !important; transform: none !important; } .fw-icon-sm { width: 19px; height: 19px; stroke-width: 2.1; } .fw-input-container { padding: 0 26px 16px; border-bottom: 1px solid color-mix(in oklch, var(--fw-border), transparent 35%); } .fw-input-wrapper { position: relative; display: flex; align-items: center; min-height: 54px; background: color-mix(in oklch, var(--fw-surface), var(--fw-surface-soft) 48%); border: 1px solid var(--fw-border); border-radius: var(--fw-radius-sm); box-shadow: 0 9px 28px oklch(18% 0.035 255 / 0.07), inset 0 1px 0 oklch(100% 0 0 / 0.8); transition: border-color 150ms ease, box-shadow 150ms ease; } .fw-input-wrapper:focus-within { border-color: color-mix(in oklch, var(--fw-primary), white 20%); box-shadow: 0 13px 34px oklch(51% 0.2 252 / 0.14), 0 0 0 4px oklch(58% 0.18 250 / 0.14), inset 0 1px 0 oklch(100% 0 0 / 0.85); } .fw-search-icon { position: absolute; left: 19px; top: 50%; width: 22px; height: 22px; color: var(--fw-muted-2); transform: translateY(-50%); pointer-events: none; } .fw-search-input { width: 100% !important; min-height: 52px; padding: 0 54px !important; margin: 0 !important; color: var(--fw-fg) !important; background: transparent !important; border: 0 !important; outline: none !important; box-shadow: none !important; font-family: var(--fw-font-body) !important; font-size: 1rem !important; line-height: 1.4 !important; text-transform: none !important; } .fw-search-input::placeholder { color: var(--fw-muted-2); } .fw-clear-btn { position: absolute; right: 8px; top: 50%; width: 38px !important; height: 38px !important; display: flex !important; align-items: center; justify-content: center; padding: 0 !important; color: var(--fw-muted) !important; background: transparent !important; border-radius: 999px !important; cursor: pointer; line-height: 1 !important; opacity: 0; pointer-events: none; transform: translateY(-50%) !important; transition: opacity 120ms ease, color 120ms ease, background-color 120ms ease !important; } .fw-clear-btn.fw-visible, .fw-clear-btn.is-visible { opacity: 1; pointer-events: auto; } .fw-clear-btn:hover { color: var(--fw-fg) !important; background: var(--fw-surface-soft) !important; box-shadow: none !important; } .fw-clear-btn svg { width: 15px; height: 15px; stroke-width: 2.25; } .fw-modal-body { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 0; } .fw-results-column { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; } .fw-results, .fw-results-container { width: 100%; flex: 1 1 auto; min-height: 240px; max-height: min(56vh, 520px); overflow-y: auto; padding: 16px 18px 18px; scrollbar-width: thin; scrollbar-color: color-mix(in oklch, var(--fw-primary), transparent 46%) transparent; } .fw-results::-webkit-scrollbar { width: 9px; } .fw-results::-webkit-scrollbar-track { background: transparent; } .fw-results::-webkit-scrollbar-thumb { background: color-mix(in oklch, var(--fw-primary), transparent 54%); border: 3px solid transparent; border-radius: 999px; background-clip: content-box; } .fw-loading { display: none; padding: 18px; text-align: center; } .fw-loading.fw-visible { display: block; } .fw-no-results { margin: 10px 0; padding: 18px; color: var(--fw-muted); text-align: center; background: var(--fw-surface-soft); border: 1px solid color-mix(in oklch, var(--fw-border), transparent 28%); border-radius: var(--fw-radius-sm); } .fw-loading-more { margin: 10px 0; padding: 12px; text-align: center; } .fw-spinner { display: inline-block; width: 26px; height: 26px; border: 3px solid color-mix(in oklch, var(--fw-primary), transparent 78%); border-top-color: var(--fw-primary); border-radius: 999px; animation: fw-spin 850ms linear infinite; } @keyframes fw-spin { to { transform: rotate(360deg); } } .fw-result-card { overflow: hidden; margin: 0 0 10px; background: color-mix(in oklch, var(--fw-surface), var(--fw-surface-soft) 18%); border: 1px solid color-mix(in oklch, var(--fw-border), transparent 20%); border-left: 4px solid transparent; border-radius: 16px; box-shadow: 0 8px 26px oklch(18% 0.035 255 / 0.045); transition: border-color 150ms ease, background-color 150ms ease; } .fw-result-card:hover, .fw-result-card.fw-selected { transform: none; background: var(--fw-surface); border-color: color-mix(in oklch, var(--fw-border), transparent 20%); border-left-color: var(--fw-primary); box-shadow: 0 8px 26px oklch(18% 0.035 255 / 0.045); } .fw-result-link { display: block; color: inherit; text-decoration: none; } .fw-result-content { display: grid; grid-template-columns: 94px minmax(0, 1fr); gap: 14px; padding: 12px; } .fw-result-image-container { width: 94px; min-height: 96px; height: auto; align-self: stretch; display: flex; align-items: center; justify-content: center; overflow: hidden; border-radius: 8px; background: transparent; } .fw-result-image { width: 100%; height: 100%; object-fit: cover; object-position: center; border-radius: inherit; box-shadow: none; } .fw-result-info { min-width: 0; display: flex; flex-direction: column; justify-content: center; } .fw-result-title { margin: 0 0 6px; color: var(--fw-fg); font-size: 0.88rem; font-weight: 720; line-height: 1.25; letter-spacing: -0.015em; text-shadow: none; } .fw-result-excerpt { margin: 0; color: var(--fw-muted); font-size: 0.7rem; line-height: 1.45; overflow-wrap: anywhere; } .fw-result-path { margin: 6px 0 0; color: var(--fw-muted-2); font-size: 0.6rem; line-height: 1.25; text-align: right; overflow-wrap: anywhere; } .fw-result-excerpt mark, .fw-result-title mark { color: color-mix(in oklch, var(--fw-primary-strong), black 8%); background: transparent; border-radius: 0; padding: 0; font-weight: 760; } .fw-footer { border-top: 1px solid color-mix(in oklch, var(--fw-border), transparent 35%); background: color-mix(in oklch, var(--fw-surface-soft), white 36%); padding: 12px 18px; color: var(--fw-muted); font-size: 0.8rem; } .fw-footer-content { display: flex; align-items: center; justify-content: center; gap: 16px; flex-wrap: wrap; } .fw-footer-item { display: inline-flex; align-items: center; gap: 5px; } .fw-footer kbd { min-width: 23px; display: inline-flex; align-items: center; justify-content: center; padding: 3px 6px; color: var(--fw-fg); font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.74rem; line-height: 1; background: var(--fw-surface); border: 1px solid var(--fw-border); border-radius: 7px; box-shadow: inset 0 -1px 0 oklch(18% 0.035 255 / 0.08); } .fw-intercept-result { display: flex; align-items: center; padding: 8px; text-decoration: none; color: inherit; border-bottom: 1px solid #eee; } .fw-intercept-result:hover { background-color: #f5f5f5; } .fw-intercept-image { width: 50px; height: 50px; object-fit: contain; margin-right: 10px; flex-shrink: 0; } .fw-intercept-info { flex-grow: 1; min-width: 0; } .fw-intercept-title { font-weight: 600; color: #1f2937; font-size: 0.9rem; margin: 0 0 2px 0; } .fw-intercept-excerpt { font-size: 0.8rem; color: #6b7280; margin: 0; overflow: hidden; text-overflow: clip; white-space: normal; word-wrap: break-word; } .fw-intercept-excerpt mark { font-weight: bold; color: #d35400; background-color: inherit; } @media (max-width: 640px) { .fw-modal-overlay { place-items: stretch; padding: 0; } .fw-container { width: 100%; max-height: 100vh; } .fw-modal-content { min-height: 100vh; max-height: 100vh; border-radius: 0; border: 0; } .fw-modal-header { padding: 20px 18px 14px; } .fw-input-container { padding: 0 18px 14px; } .fw-results, .fw-results-container { min-height: 0; max-height: none; padding: 14px; } .fw-result-content { grid-template-columns: 78px minmax(0, 1fr); gap: 12px; } .fw-result-image-container { width: 78px; min-height: 82px; height: auto; } .fw-footer { display: none; } #searchButton { right: 18px; bottom: 18px; } #searchButton.fw-bottom-left { left: 18px; right: auto; } #searchButton.fw-top-right { top: 18px; right: 18px; bottom: auto; } #searchButton.fw-top-left { top: 18px; right: auto; bottom: auto; left: 18px; } } @media (prefers-reduced-motion: reduce) { .fw-modal-overlay, .fw-modal-content, .fw-btn-search, .fw-result-card, .fw-input-wrapper, .fw-clear-btn, .fw-modal-close-btn { animation: none !important; transition: none !important; } } `,i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}createButton(){this.buttonEl=document.createElement("button"),this.buttonEl.id="searchButton",this.buttonEl.className=["fw-btn-search",this.getPositionClass(),this.getThemeClass()].filter(Boolean).join(" "),this.buttonEl.setAttribute("aria-label","Abrir busca"),this.buttonEl.innerHTML=` `,document.body.appendChild(this.buttonEl)}createModal(){let t=document.createElement("div");t.id="searchModal",t.className=["fw-modal-overlay",this.getThemeClass()].filter(Boolean).join(" "),t.onclick=()=>this.closeModal(),t.innerHTML=`

${this.getDisplaySiteName()}

`,document.body.appendChild(t),this.modalEl=t,this.inputEl=document.getElementById("searchInput"),this.resultsEl=document.getElementById("searchResults"),this.loadingEl=document.getElementById("loadingIndicator")}attachEventListeners(){this.buttonEl?.addEventListener("click",()=>this.openModal()),document.getElementById("fw-close-mobile-btn")?.addEventListener("click",()=>this.closeModal()),this.inputEl?.addEventListener("input",i=>this.handleInput(i)),this.inputEl?.addEventListener("keydown",i=>this.handleKeydown(i)),document.getElementById("clearButton")?.addEventListener("click",()=>this.clearSearch())}openModal(){this.state.isOpen=!0,this.modalEl?.classList.add("fw-modal-open"),this.applyWidgetClasses(),this.inputEl.value="",this.inputEl?.focus(),this.resetState(),this.apiClient.recordEvent({eventType:"open"})}closeModal(){this.state.isOpen=!1,this.modalEl?.classList.remove("fw-modal-open"),this.abortCurrentRequest(),this.resetState()}resetState(){this.state.results=[],this.state.selectedIndex=-1,this.state.page=0,this.state.hasMore=!1,this.state.error=null,this.isFetchingMore=!1,this.seenPageIds.clear(),this.resultsEl&&(this.resultsEl.innerHTML=""),this.hideResultsContainer(),this.loadingEl&&(this.loadingEl.style.display="none"),document.getElementById("clearButton")?.classList.remove("fw-visible")}handleInput(t){let i=t.target.value.trim(),r=document.getElementById("clearButton");if(r&&r.classList.toggle("fw-visible",!!i),this.debounceTimer&&clearTimeout(this.debounceTimer),this.state.query=i,this.state.page=0,this.state.hasMore=!1,this.state.selectedIndex=-1,this.seenPageIds.clear(),i.length<3){this.resultsEl&&(this.resultsEl.innerHTML=""),this.hideResultsContainer();return}this.debounceTimer=setTimeout(()=>{this.performSearch(i,0)},M)}handleKeydown(t){if(this.resultsEl)switch(this.resultElements=this.resultsEl.querySelectorAll(".fw-result-card"),t.key){case"ArrowDown":t.preventDefault(),this.state.selectedIndex=Math.min(this.state.selectedIndex+1,this.resultElements.length-1),this.updateSelection(),this.state.selectedIndex>=0&&this.resultElements[this.state.selectedIndex]&&this.resultElements[this.state.selectedIndex].scrollIntoView({block:"nearest"});break;case"ArrowUp":t.preventDefault(),this.state.selectedIndex=Math.max(this.state.selectedIndex-1,-1),this.updateSelection(),this.state.selectedIndex>=0&&this.resultElements[this.state.selectedIndex]&&this.resultElements[this.state.selectedIndex].scrollIntoView({block:"nearest"});break;case"Enter":if(this.state.selectedIndex>=0&&this.resultElements[this.state.selectedIndex]){let e=this.resultElements[this.state.selectedIndex].querySelector("a"),i=this.state.results[this.state.selectedIndex];e&&i&&(this.apiClient.recordEvent({eventType:"click",query:this.state.query,pageId:i.page_id,resultUrl:i.url}),window.location.href=e.getAttribute("href")||"")}break;case"Escape":this.closeModal();break}}updateSelection(){this.resultElements&&this.resultElements.forEach((t,e)=>{e===this.state.selectedIndex?t.classList.add("fw-selected"):t.classList.remove("fw-selected")})}clearSearch(){this.abortCurrentRequest(),this.inputEl&&(this.inputEl.value=""),this.resultsEl&&(this.resultsEl.innerHTML=""),this.hideResultsContainer(),document.getElementById("clearButton")?.classList.remove("fw-visible"),this.resetState()}abortCurrentRequest(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null)}async performSearch(t,e,i=!1){if(e>0&&this.pendingPage===e)return;this.state.isLoading&&this.abortCurrentRequest(),this.pendingPage=e,this.state.isLoading=!0,this.currentAbortController=new AbortController;let r=null;this.showResultsContainer(),!i&&this.loadingEl&&(this.loadingEl.style.display="block"),i&&this.resultsEl&&(r=document.createElement("div"),r.className="fw-loading-more",r.innerHTML=`
`,this.resultsEl.appendChild(r));try{let o=e>0?Array.from(this.seenPageIds):void 0,{results:n,totalResults:a,hasMore:l}=await this.apiClient.search(t,e,10,o);for(let p of n)this.seenPageIds.add(p.page_id);i?n.length>0&&(this.state.results=[...this.state.results,...n]):this.state.results=n,this.state.totalResults=a,this.state.hasMore=l,this.state.page=e,this.state.error=null,r?.remove(),r=null,this.renderResults(i,n),!i&&this.resultsEl&&this.resultsEl.scrollHeight<=this.resultsEl.clientHeight&&this.state.hasMore&&n.length>0&&!this.isFetchingMore&&(this.isFetchingMore=!0,setTimeout(()=>{this.performSearch(t,e+1,!0)},100))}catch(o){if(o.name==="AbortError")return;if(this.state.error=o instanceof Error?o.message:"Unknown error",!i&&this.resultsEl){this.showResultsContainer();let n=this.escapeHtml(this.state.error||this.translations.searchError);this.resultsEl.innerHTML=`
${n}
`}}finally{this.state.isLoading=!1,this.isFetchingMore=!1,this.pendingPage=-1,this.loadingEl&&(this.loadingEl.style.display="none"),r?.remove(),this.resultsEl?.querySelectorAll(".fw-loading-more").forEach(o=>o.remove()),this.setupScrollListener()}}renderResults(t,e){if(!this.resultsEl)return;if(this.showResultsContainer(),t||(this.resultsEl.innerHTML=""),this.state.results.length===0&&!t){this.resultsEl.innerHTML=`
${this.translations.noResults}
`;return}let r=(t&&e?e:this.state.results).map(o=>{let n=this.getResultImageUrl(o.featured_image),a=this.getImageErrorFallback(n),l=this.getRelativePath(o.url);return` `}).join("");t?this.resultsEl.innerHTML+=r:this.resultsEl.innerHTML=r,this.attachResultClickTracking()}attachResultClickTracking(){if(!this.resultsEl)return;this.resultsEl.querySelectorAll(".fw-result-link").forEach((e,i)=>{e.addEventListener("click",()=>{let r=this.state.results[i];r&&this.apiClient.recordEvent({eventType:"click",query:this.state.query,pageId:r.page_id,resultUrl:r.url})})})}setupScrollListener(){this.resultsEl&&(this.resultsEl.removeEventListener("scroll",this.scrollHandler),this.resultsEl.addEventListener("scroll",this.scrollHandler,{passive:!0}))}async injectIntoNativeSearch(t){let e=this.config.siteConfig;if(!e){console.error("[FindoraWidget] No siteConfig provided for native mode");return}let i=document.querySelector(e.dropdownSelector);if(!i){console.error("[FindoraWidget] Dropdown not found:",e.dropdownSelector);return}try{let{results:r}=await this.apiClient.search(t,0,10);if(e.injectMethod==="replace"&&(i.innerHTML=""),r.length===0){e.clearResultsOnEmpty&&(i.innerHTML="",i.classList.remove("active"));return}let o=document.createDocumentFragment();for(let n of r){let a=document.createElement("a");a.href=n.url,a.className="fw-intercept-result";let l=this.getResultImageUrl(n.featured_image),p=this.getImageErrorFallback(l);a.innerHTML=`
${this.cleanTitle(n.title)}
...${n.excerpt||""}
`,o.appendChild(a)}i.appendChild(o),i.classList.add("active")}catch(r){console.error("[FindoraWidget] Error in native search:",r)}}destroy(){this.nativeInputEl&&this.nativeInputHandler&&(this.nativeInputEl.removeEventListener("input",this.nativeInputHandler),this.nativeInputEl.removeEventListener("keyup",this.nativeInputHandler),this.nativeInputEl=null,this.nativeInputHandler=null),this.buttonEl?.remove(),this.modalEl?.remove(),document.getElementById("fw-widget-styles")?.remove()}};function R(){let s=document.currentScript;if(s)return s;let t=document.querySelectorAll("script[src]");for(let e of t){let i=e.src;if(i.includes("/findora.js")||i.includes("/findora-widget.js"))return e}return null}function P(){let s=R(),t={...window.FindoraWidgetConfig};if(s){if(!t.apiUrl){let e=s.getAttribute("data-api-url");t.apiUrl=e||new URL(s.src).origin}t.position=t.position??(s.getAttribute("data-position")||void 0),t.theme=t.theme??(s.getAttribute("data-theme")||void 0),t.language=t.language??(s.getAttribute("data-language")||void 0),t.primaryColor=t.primaryColor??s.getAttribute("data-color")??void 0,t.placeholder=t.placeholder??s.getAttribute("data-placeholder")??void 0,t.siteName=t.siteName??s.getAttribute("data-site-name")??void 0}return t.apiUrl=t.apiUrl||window.location.origin,t}function b(){let s=P();if(!s){console.warn("[FindoraWidget] Widget not initialized due to missing config");return}new d(s).init(),window.initFindoraWidget=(e={})=>{let i={...s,...e},r=new d(i);return r.init(),r},window.FindoraWidget=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",b):b();var B=d;return L(H);})();