1import{j as e}from"./ui-DP3MGJ7H.js";import{a as u,L as J}from"./vendor-C9YJUoHc.js";import{H as ne,F as le}from"./Footer-CAqpfTjo.js";import{S as ke}from"./SEOHead-DZVQE-ak.js";import{c as W,a as A,B as T,t as _,u as pe}from"./index-DtiPzfAm.js";import{C as S,a as M,b as R,d as k}from"./card-LxZ6mji4.js";import{B as D}from"./badge-CNTX1T8j.js";import{T as Ae,a as Pe,b as z,c as $}from"./tabs-Bqx34tgC.js";import{D as Te,a as Ee,b as Ie,c as Le}from"./dialog-C9CFprcX.js";import{a as ge,u as De,S as Me}from"./useSeoSubscription-BwkZYI-u.js";import{S as fe,a as je,b as Ne,c as ve,d as ee}from"./select-Bous7QvT.js";import{T as Re,R as Ue,L as qe,C as Fe,X as Oe,Y as ze,a as $e}from"./charts-OmThYDam.js";import{aN as G,a as Be,d as We,b8 as Ve,n as O,a5 as X,G as Y,Y as He,B as F,t as te,y as ye,a2 as Je,I as se,ar as Ke,X as Ge,ae as Xe,m as oe,b9 as ae,c as be,S as Q,e as Ye,ba as K,A as V,bb as ce,a$ as we,aj as de,T as Z,b6 as Ze,o as re}from"./icons-BkqQ-mD_.js";import{I as q}from"./input-BLR1AQtN.js";import{S as _e}from"./switch-NGcpuYzE.js";import{L as U}from"./label-nVUzcUau.js";import{m as Qe}from"./animations-HcY6UNf9.js";import{Y as es}from"./useSupabaseQuery-BexCR7yQ.js";import"./AdSlot-DH0pRZkq.js";import"./query-DEUgYzHT.js";import"./supabase-C_AT-Fx3.js";import"./useComposition-BJVfCnNp.js";const ss={light:"",dark:".dark"},Se=u.createContext(null);function as(){const s=u.useContext(Se);if(!s)throw new Error("useChart must be used within a <ChartContainer />");return s}function rs({id:s,className:i,children:n,config:a,...g}){const d=u.useId(),f=`chart-${s||d.replace(/:/g,"")}`;return e.jsx(Se.Provider,{value:{config:a},children:e.jsxs("div",{"data-slot":"chart","data-chart":f,className:W("[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",i),...g,children:[e.jsx(ts,{id:f,config:a}),e.jsx(Ue,{children:n})]})})}const ts=({id:s,config:i})=>{const n=Object.entries(i).filter(([,a])=>a.theme||a.color);return n.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(ss).map(([a,g])=>` 2${g} [data-chart=${s}] { 3${n.map(([d,f])=>{const N=f.theme?.[a]||f.color;return N?` --color-${d}: ${N};`:null}).join(` 4`)} 5} 6`).join(` 7`)}}):null},is=Re;function ns({active:s,payload:i,className:n,indicator:a="dot",hideLabel:g=!1,hideIndicator:d=!1,label:f,labelFormatter:N,labelClassName:l,formatter:r,color:t,nameKey:c,labelKey:C}){const{config:v}=as(),m=u.useMemo(()=>{if(g||!i?.length)return null;const[x]=i,y=`${C||x?.dataKey||x?.name||"value"}`,L=me(v,x,y),h=!C&&typeof f=="string"?v[f]?.label||f:L?.label;return N?e.jsx("div",{className:W("font-medium",l),children:N(h,i)}):h?e.jsx("div",{className:W("font-medium",l),children:h}):null},[f,N,i,g,l,v,C]);if(!s||!i?.length)return null;const w=i.length===1&&a!=="dot";return e.jsxs("div",{className:W("border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",n),children:[w?null:m,e.jsx("div",{className:"grid gap-1.5",children:i.filter(x=>x.type!=="none").map((x,y)=>{const L=`${c||x.name||x.dataKey||"value"}`,h=me(v,x,L),j=t||x.payload.fill||x.color;return e.jsx("div",{className:W("[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",a==="dot"&&"items-center"),children:r&&x?.value!==void 0&&x.name?r(x.value,x.name,x,y,x.payload):e.jsxs(e.Fragment,{children:[h?.icon?e.jsx(h.icon,{}):!d&&e.jsx("div",{className:W("shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",{"h-2.5 w-2.5":a==="dot","w-1":a==="line","w-0 border-[1.5px] border-dashed bg-transparent":a==="dashed","my-0.5":w&&a==="dashed"}),style:{"--color-bg":j,"--color-border":j}}),e.jsxs("div",{className:W("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[w?m:null,e.jsx("span",{className:"text-muted-foreground",children:h?.label||x.name})]}),x.value&&e.jsx("span",{className:"text-foreground font-mono font-medium tabular-nums",children:x.value.toLocaleStr
7ing()})]})]})},x.dataKey)})})]})}function me(s,i,n){if(typeof i!="object"||i===null)return;const a="payload"in i&&typeof i.payload=="object"&&i.payload!==null?i.payload:void 0;let g=n;return n in i&&typeof i[n]=="string"?g=i[n]:a&&n in a&&typeof a[n]=="string"&&(g=a[n]),g in s?s[g]:s[n]}const ls={score:{label:"Score SEO",color:"hsl(var(--primary))"}};function os({userId:s}){const[i,n]=u.useState([]),[a,g]=u.useState("all"),[d,f]=u.useState([]),[N,l]=u.useState(!0);u.useEffect(()=>{r()},[s]),u.useEffect(()=>{t()},[a,s]);const r=async()=>{const{data:m}=await A.from("monitored_urls").select("id, url, label, is_competitor").eq("is_active",!0).order("created_at");m&&n(m)},t=async()=>{l(!0);try{let m=A.from("seo_analyses").select("url, score, created_at").order("created_at",{ascending:!0}).limit(100);if(a!=="all"){const x=i.find(y=>y.id===a);x&&(m=m.eq("url",x.url))}const{data:w}=await m;w&&f(w.map(x=>({date:new Date(x.created_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"short"}),score:x.score,url:x.url})))}finally{l(!1)}},c=d.length>=2?d[d.length-1].score-d[0].score:0,C=c>0?Be:c<0?We:Ve,v=c>0?"text-green-500":c<0?"text-red-500":"text-muted-foreground";return e.jsxs(S,{className:"max-w-5xl mx-auto mb-8",children:[e.jsx(M,{children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(G,{className:"h-5 w-5 text-primary"}),"Evolução do Score SEO"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[i.length>0&&e.jsxs(fe,{value:a,onValueChange:g,children:[e.jsx(je,{className:"w-[200px]",children:e.jsx(Ne,{placeholder:"Filtrar URL"})}),e.jsxs(ve,{children:[e.jsx(ee,{value:"all",children:"Todos os sites"}),i.map(m=>e.jsx(ee,{value:m.id,children:m.label||new URL(m.url).hostname},m.id))]})]}),d.length>=2&&e.jsxs(D,{variant:"secondary",className:`gap-1 ${v}`,children:[e.jsx(C,{className:"h-3 w-3"}),c>0?"+":"",c," pts"]})]})]})}),e.jsx(k,{children:N?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(O,{className:"h-5 w-5 animate-spin mr-2"}),"Carregando dados..."]}):d.length<2?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(G,{className:"h-10 w-10 mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:"São necessárias pelo menos 2 análises para mostrar a evolução."}),e.jsx("p",{className:"text-xs mt-1",children:"Analise seu site periodicamente para acompanhar o progresso."})]}):e.jsx(rs,{config:ls,className:"h-[300px] w-full",children:e.jsxs(qe,{data:d,margin:{top:5,right:20,bottom:5,left:0},children:[e.jsx(Fe,{strokeDasharray:"3 3",className:"stroke-border"}),e.jsx(Oe,{dataKey:"date",className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(ze,{domain:[0,100],className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(is,{content:e.jsx(ns,{})}),e.jsx($e,{type:"monotone",dataKey:"score",stroke:"hsl(var(--primary))",strokeWidth:2,dot:{r:4,fill:"hsl(var(--primary))"},activeDot:{r:6}})]})})})]})}function xe(s){if(!s)return null;const i=new Date(s);return i.setDate(i.getDate()+7),i.toLocaleDateString("pt-BR",{day:"2-digit",month:"short"})}function ue({item:s,onToggle:i,onRemove:n}){return e.jsxs(Qe.div,{className:"flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent/5 transition-colors",initial:{opacity:0,y:5},animate:{opacity:1,y:0},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[s.last_score!==void 0&&s.last_score!==null?e.jsx(ge,{score:s.last_score}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:s.label||(()=>{try{return new URL(s.url).hostname}catch{return s.url}})()}),!s.is_active&&e.jsx(D,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Pausado"})]}),e.jsx("span",{className:"text-xs text-muted-foreground truncate block",children:s.url})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.last_checked_at&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1 hidden sm:flex",children:[e.jsx(te,{className:"h-3 w-3"}),new Date(s.last_checked_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"short"})]}),s.is_active&&xe(s.last_checked_at)&&e.jsxs("span",{className:"text-xs text-primary/70 flex items-center gap-1 hidden md:flex",children:[e.jsx(ye,{className:"h-3 w-3"}),"Próx: ",xe(s.last_checked_at)]}),e.jsx(_e,{checked:s.is_active,onCheckedChange:a=>i(s.id,a)}),e.jsx(T,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>n(s.id),children:e.jsx(Je,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function cs({userId:s}){const[i,n]=u.useState([]),[a,g]=u.useState(!0),[d,f]=u.useState(""),[N,l]=u.useState(""),[r,t]=u.useState(!1),[c,C]=u.useState(!1);u.useEffect(()=>
7{v()},[s]);const v=async()=>{g(!0);try{const{data:h}=await A.from("monitored_urls").select("*").order("created_at");if(h){const j=await Promise.all(h.map(async p=>{const{data:P}=await A.from("seo_analyses").select("score").eq("url",p.url).order("created_at",{ascending:!1}).limit(1).single();return{...p,last_score:P?.score}}));n(j)}}finally{g(!1)}},m=async()=>{if(d.trim()){C(!0);try{let h=d.trim();h.startsWith("http")||(h=`https://${h}`);const{error:j}=await A.from("monitored_urls").insert({user_id:s,url:h,label:N.trim()||null,is_competitor:r});if(j){j.code==="23505"?_.error("Esta URL já está sendo monitorada."):_.error("Erro ao adicionar URL.");return}_.success("URL adicionada ao monitoramento!"),f(""),l(""),t(!1),v()}finally{C(!1)}}},w=async h=>{const{error:j}=await A.from("monitored_urls").delete().eq("id",h);j||(_.success("URL removida."),n(p=>p.filter(P=>P.id!==h)))},x=async(h,j)=>{await A.from("monitored_urls").update({is_active:j}).eq("id",h),n(p=>p.map(P=>P.id===h?{...P,is_active:j}:P))},y=i.filter(h=>!h.is_competitor),L=i.filter(h=>h.is_competitor);return e.jsxs(S,{className:"max-w-5xl mx-auto mb-8",children:[e.jsx(M,{children:e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(X,{className:"h-5 w-5 text-primary"}),"Monitoramento Periódico"]})}),e.jsxs(k,{children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/5 border border-primary/10 mb-6 space-y-2",children:[e.jsx("p",{className:"text-sm text-foreground font-medium",children:"Como funciona o monitoramento?"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Adicione URLs dos seus sites e de concorrentes para acompanhar o SEO automaticamente."}),e.jsxs("li",{children:[e.jsx("strong",{children:"Varredura semanal:"})," o sistema re-analisa cada URL ativa a cada 7 dias e registra o score."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Alertas por email:"})," você recebe uma notificação quando o score muda significativamente (⥠3 pontos)."]}),e.jsx("li",{children:'Marque URLs como "Concorrente" para comparar seu desempenho com a concorrência.'})]})]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-card/50 mb-6 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Y,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(q,{value:d,onChange:h=>f(h.target.value),placeholder:"https://seusite.com.br",className:"pl-9",disabled:c})]}),e.jsx(q,{value:N,onChange:h=>l(h.target.value),placeholder:"Apelido (opcional)",className:"w-40",disabled:c})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_e,{id:"competitor",checked:r,onCheckedChange:t}),e.jsx(U,{htmlFor:"competitor",className:"text-sm text-muted-foreground",children:"à um concorrente"})]}),e.jsxs(T,{size:"sm",onClick:m,disabled:c||!d.trim(),children:[c?e.jsx(O,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(He,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]})]}),a?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground py-6 justify-center",children:[e.jsx(O,{className:"h-4 w-4 animate-spin"}),"Carregando..."]}):i.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(F,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Nenhuma URL monitorada ainda. Adicione seu primeiro site acima."})]}):e.jsxs("div",{className:"space-y-6",children:[y.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[e.jsx(Y,{className:"h-4 w-4 text-primary"}),"Meus Sites (",y.length,")"]}),e.jsx("div",{className:"space-y-2",children:y.map(h=>e.jsx(ue,{item:h,onToggle:x,onRemove:w},h.id))})]}),L.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-semibold text-foreground mb-3 flex items-center gap-2",children:[e.jsx(X,{className:"h-4 w-4 text-destructive"}),"Concorrentes (",L.length,")"]}),e.jsx("div",{className:"space-y-2",children:L.map(h=>e.jsx(ue,{item:h,onToggle:x,onRemove:w},h.id))})]})]})]})]})}const ds="BI-NT6iQ6ZIx262R4wNcuJPacT2IG1dw_QRxUhPTdBKqTWNlRMztxxuKPo0y22zyNef6GQYD6fndUmXZctvadR4";function ms(s){const i="=".repeat((4-s.length%4)%4),n=(s+i).replace(/-/g,"+").replace(/_/g,"/"),a=atob(n);return Uint8Array.from(a,g=>g.charCodeAt(0))}function he(s){return btoa(String.fromCharCode(...new Uint8Array(s))
7)}function xs(){const s=typeof window<"u"&&"Notification"in window&&"serviceWorker"in navigator&&"PushManager"in window,[i,n]=u.useState(s?Notification.permission:"denied"),[a,g]=u.useState(!1),[d,f]=u.useState(!1);u.useEffect(()=>{s&&(n(Notification.permission),navigator.serviceWorker.ready.then(t=>t.pushManager.getSubscription()).then(t=>g(!!t)).catch(()=>{}))},[s]);const N=u.useCallback(async()=>{if(!s)return _.error("Notificações push não são suportadas neste navegador."),!1;f(!0);try{const{data:{session:t}}=await A.auth.getSession(),c=t?.user?.id;if(!c)return _.error("Faça login para ativar as notificações push."),!1;await navigator.serviceWorker.register("/sw.js");const C=await navigator.serviceWorker.ready,v=await C.pushManager.getSubscription();v&&(await v.unsubscribe(),console.info("[WebPush] Unsubscribed stale push subscription before re-subscribing."));const m=await C.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ms(ds)}),w=m.getKey("p256dh"),x=m.getKey("auth");if(!w||!x)return _.error("Não foi possÃvel extrair as chaves da inscrição push."),!1;const{error:y}=await A.from("push_subscriptions").upsert({user_id:c,endpoint:m.endpoint,p256dh:he(w),auth_key:he(x),user_agent:navigator.userAgent.
7substring(0,200)},{onConflict:"user_id,endpoint"});return y?(_.error(`Erro ao salvar inscrição: ${y.message}`),console.error("[WebPush] upsert error:",y.message,y.details),!1):(n("granted"),g(!0),!0)}catch(t){return t?.name==="NotAllowedError"?_.error("Permissão de notificação negada pelo navegador."):_.error(`Erro ao ativar push: ${t?.message??"desconhecido"}`),console.error("[WebPush] subscribe error:",t),n(Notification.permission),!1}finally{f(!1)}},[s]),l=u.useCallback(async()=>{if(s){f(!0);try{const c=await(await navigator.serviceWorker.ready).pushManager.getSubscription();c&&(await A.from("push_subscriptions").delete().eq("endpoint",c.endpoint),await c.unsubscribe(),g(!1))}finally{f(!1)}}},[s]),r=u.useCallback(async()=>{if(!s){_.error("Notificações não são suportadas neste navegador.");return}if(Notification.permission!=="granted"){_.error("Ative as notificações primeiro antes de testar.");return}try{await(await navigator.serviceWorker.ready).showNotification("RankTop SEO â Teste â",{body:"Notificacoes push estao funcionando! Voce sera alertado sobre quedas de score SEO.",icon:"/logo-ranktop.png",badge:"/logo-ranktop.png",tag:"seo-push-test",requireInteraction:!0,silent:!1}),_.success("Notificação de teste enviada â verifique o centro de notificações do Windows/Mac se não aparecer na tela.")}catch(t){_.error(`Erro no teste: ${t?.message??"desconhecido"}`),console.error("[WebPush] testNotification error:",t)}},[s]);return{isSupported:s,permission:i,isSubscribed:a,loading:d,subscribe:N,unsubscribe:l,testNotification:r}}const us=["E-commerce","SaaS / Tecnologia","Saúde","Educação","Serviços Profissionais","Imobiliário","Alimentação","Varejo","Indústria","Outro"],hs={free:"Gratuito",starter:"Starter",pro:"Pro",agency:"Agency"};function ps({subscription:s,planType:i="free"}){const{user:n}=pe(),{isSupported:a,permission:g,isSubscribed:d,loading:f,subscribe:N,unsubscribe:l,testNotification:r}=xs(),[t,c]=u.useState({name:null,email:null,phone:null,company:null,website:null,industry:null,city:null}),[C,v]=u.useState(!0),[m,w]=u.useState(!1),[x,y]=u.useState(!1);u.useEffect(()=>{n&&L()},[n]);async function L(){v(!0);try{const p="https://upmjyulgvnxqkbcvtsai.supabase.co",H=(await A.auth.getSession()).data.session?.access_token;if(!H){c(b=>({...b,email:n.email||null})),v(!1);return}const o=await fetch(`${p}/rest/v1/users?id=eq.${n.id}&select=name,email,phone,company,website,industry,city`,{headers:{Authorization:`Bearer ${H}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVwbWp5dWxndm54cWtiY3Z0c2FpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njc3MjUzODUsImV4cCI6MjA4MzMwMTM4NX0.wj2QH-oN2MCj9sVAWrgN0xdVqlKWbv58Tx8crkCKEeA",Accept:"application/json"}});if(o.ok){const b=await o.json();if(Array.isArray(b)&&b.length>0){const E=b[0];c({...E,email:E.email||n.email||null})}else c(E=>({...E,email:n.email||null,name:n.user_metadata?.name||null}))}else console.error("Profile load failed:",o.status),c(b=>({...b,email:n.email||null}))}catch(p){console.error("Error loading profile:",p),c(P=>({...P,email:n.email||null}))}finally{v(!1)}}async function h(){if(n){w(!0);try{const p={name:t.name,phone:t.phone,company:t.company,website:t.website,industry:t.industry,city:t.city,updated_at:new Date().toISOString()},P="https://upmjyulgvnxqkbcvtsai.supabase.co",o=(await A.auth.getSession()).data.session?.access_token;if(!o)throw new Error("Sessão expirada. Faça login novamente.");const b=await fetch(`${P}/rest/v1/users?id=eq.${n.id}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVwbWp5dWxndm54cWtiY3Z0c2FpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njc3MjUzODUsImV4cCI6MjA4MzMwMTM4NX0.wj2QH-oN2MCj9sVAWrgN0xdVqlKWbv58Tx8crkCKEeA",Prefer:"return=representation"},body:JSON.stringify(p)});if(!b.ok){const I=await b.text();throw console.error("Profile update failed:",b.status,I),new Error(`Erro ao salvar: ${b.status}`)}const E=await b.json();if(console.log("Profile updated successfully:",E),Array.isArray(E)&&E.length>0){const I=E[0];c({name:I.name,email:I.email||n.email||null,phone:I.phone,company:I.company,website:I.website,industry:I.industry,city:I.city})}_.success("Perfil atualizado com sucesso!"),y(!1)}catch(p){console.error("Profile save error:",p),_.error(p.message||"Erro ao salvar perfil")}finally{w(!1)}}}if(C)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(O,{className:"h-8 w-8 animate-spin text-primary"})});const j=({label:p,value:P})=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:p}),e.jsx("p",{className:"text-sm font-medium",children:P||e.jsx("span",{className:"text-muted-foreground italic",children:"Não informado"})})]});
7return e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[e.jsxs(S,{children:[e.jsxs(M,{className:"flex flex-row items-center justify-between",children:[e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(se,{className:"h-5 w-5"}),"Meu Perfil"]}),x?e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>y(!1),children:[e.jsx(Ge,{className:"h-4 w-4 mr-1"})," Cancelar"]}):e.jsxs(T,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[e.jsx(Ke,{className:"h-4 w-4 mr-1"})," Editar"]})]}),e.jsx(k,{children:x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"name",children:"Nome"}),e.jsx(q,{id:"name",value:t.name||"",onChange:p=>c({...t,name:p.target.value}),placeholder:"Seu nome"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"email",children:"Email"}),e.jsx(q,{id:"email",value:t.email||"",disabled:!0,className:"bg-muted"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"O email é vinculado à sua conta e não pode ser alterado aqui."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"phone",children:"Telefone"}),e.jsx(q,{id:"phone",value:t.phone||"",onChange:p=>c({...t,phone:p.target.value}),placeholder:"(00) 00000-0000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"company",children:"Empresa"}),e.jsx(q,{id:"company",value:t.company||"",onChange:p=>c({...t,company:p.target.value}),placeholder:"Nome da empresa"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"website",children:"Site"}),e.jsx(q,{id:"website",value:t.website||"",onChange:p=>c({...t,website:p.target.value}),placeholder:"https://seusite.com.br"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"city",children:"Cidade"}),e.jsx(q,{id:"city",value:t.city||"",onChange:p=>c({...t,city:p.target.value}),placeholder:"Sua cidade"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{htmlFor:"industry",children:"Segmento"}),e.jsxs(fe,{value:t.industry||"",onValueChange:p=>c({...t,industry:p}),children:[e.jsx(je,{children:e.jsx(Ne,{placeholder:"Selecione o segmento"})}),e.jsx(ve,{children:us.map(p=>e.jsx(ee,{value:p,children:p},p))})]})]}),e.jsxs(T,{onClick:h,disabled:m,className:"w-full sm:w-auto",children:[m?e.jsx(O,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Salvar Perfil"]})]}):e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(j,{label:"Nome",value:t.name}),e.jsx(j,{label:"Email",value:t.email}),e.jsx(j,{label:"Telefone",value:t.phone}),e.jsx(j,{label:"Empresa",value:t.company}),e.jsx(j,{label:"Site",value:t.website}),e.jsx(j,{label:"Cidade",value:t.city}),e.jsx(j,{label:"Segmento",value:t.industry})]})})]}),a&&e.jsxs(S,{children:[e.jsx(M,{children:e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(F,{className:"h-5 w-5"}),"Notificações Push"]})}),e.jsxs(k,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Receba alertas no navegador quando o score SEO do seu site mudar â mesmo com a aba fechada."}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[d?e.jsx(F,{className:"h-5 w-5 text-primary"}):e.jsx(oe,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Notificações ativas":"Notificações desativadas"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g==="denied"?"Permissão bloqueada no navegador â habilite nas configurações do site.":d?"Você receberá alertas quando o score cair abaixo do limite.":"Ative para ser notificado imediatamente sobre quedas de score."})]})]}),g!=="denied"&&e.jsx(T,{size:"sm",variant:d?"outline":"default",disabled:f,onClick:async()=>{d?(await l(),_.success("Notificações desativadas.")):await N()&&_.success("Notificações ativadas com sucesso!")},children:f?e.jsx(O,{className:"h-4 w-4 animate-spin"}):d?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-1"})," Desativar"]}):e.jsxs(e.Fragment,{children:[e.jsx(F,{className:"h-4 w-4 mr-1"})," Ativar"]})})]}),d&&g==="granted"&&e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-dashed bg-muted/30 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Testar notificação"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Dispara uma notificação local para confirmar que está funcionando."})]}),e.jsxs(T,{size:"sm",variant:"secondary",onClick:r,children:[e.jsx(F,{className:"h-3.5 w-3.5 mr-1"}),"Testar"]})]})]})]}),e.jsxs(S,{children:[e.jsx(M,{children:e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(ae,{className:"h-5 w-5"}
7),"Minha Assinatura"]})}),e.jsx(k,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plano Atual"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{variant:i!=="free"?"default":"secondary",children:hs[i]||i}),s?.status&&e.jsx(D,{variant:s.status==="active"?"default":"destructive",className:"text-xs",children:s.status==="active"?"Ativo":s.status==="cancelled"?"Cancelado":s.status==="expired"?"Expirado":"Pendente"})]})]}),s&&s.plan_type!=="free"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"InÃcio da Assinatura"}),e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(ye,{className:"h-3.5 w-3.5"}),new Date(s.started_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"long",year:"numeric"})]})]}),s.expires_at&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Expira em"}),e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(te,{className:"h-3.5 w-3.5"}),new Date(s.expires_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"long",year:"numeric"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Limites do Plano"}),e.jsxs("p",{className:"text-sm",children:[s.max_analyses_per_day," análises/dia · ",s.max_monitored_urls," URLs monitoradas"]})]})]}),(!s||s.plan_type==="free")&&e.jsx("div",{className:"sm:col-span-2 p-4 rounded-lg border border-dashed bg-muted/30 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Você está no plano gratuito. Faça upgrade para desbloquear mais recursos."})})]})})]})]})}function B({icon:s,text:i}){return e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-muted/50 border mb-6",children:[e.jsx(Ze,{className:"h-5 w-5 text-primary shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i})]})}function gs({planType:s,checkoutLoading:i,onCheckout:n}){const{data:a,isLoading:g}=es("diagnostico-seo"),[d,f]=u.useState("monthly");if(u.useEffect(()=>{new URLSearchParams(window.location.search).get("billing")==="annual"&&f("annual")},[]),g)return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[1,2,3,4].map(r=>e.jsx(S,{className:"h-64 animate-pulse bg-muted"},r))});if(!a||a.length===0)return e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Nenhum plano disponÃvel."});const N=r=>r.features?Array.isArray(r.features)?r.features:[]:[],l=r=>({Gratuito:"free",Starter:"starter",Pro:"pro",Agency:"agency"})[r]||r.toLowerCase();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx("button",{onClick:()=>f("monthly"),className:`px-5 py-2 rounded-full text-sm font-medium transition-colors ${d==="monthly"?"bg-primary text-primary-foreground":"border text-muted-foreground hover:text-foreground"}`,children:"Mensal"}),e.jsxs("button",{onClick:()=>f("annual"),className:`px-5 py-2 rounded-full text-sm font-medium transition-colors flex items-center gap-2 ${d==="annual"?"bg-primary text-primary-foreground":"border text-muted-foreground hover:text-foreground"}`,children:["Anual",e.jsx("span",{className:"text-xs font-bold bg-green-500 text-white px-2 py-0.5 rounded-full",children:"-30%"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:a.map(r=>{const t=l(r.name),c=t===s,C=N(r),v=`${t}_annual`,m=!!r.price_annual,w=d==="annual"&&m?v:t;return e.jsxs(S,{className:`relative ${c?"ring-2 ring-primary":""} ${r.is_highlighted?"border-primary":""}`,children:[r.is_highlighted&&r.highlight_label&&e.jsx("div",{className:"absolute -top-3 left-1/2 -translate-x-1/2",children:e.jsx(D,{className:"bg-primary text-primary-foreground",children:r.highlight_label})}),c&&e.jsx("div",{className:"absolute -top-3 right-4",children:e.jsx(D,{variant:"secondary",children:"Atual"})}),e.jsxs(M,{className:"text-center pb-2",children:[e.jsx(R,{className:"text-lg",children:r.name}),e.jsx("div",{className:"text-3xl font-bold",children:d==="annual"&&m?e.jsxs(e.Fragment,{children:[r.price_annual,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:r.price_annual_period||"/ano"})]}):e.jsxs(e.Fragment,{children:[r.price,r.price_period&&e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:r.price_period})]})}),d==="annual"&&m&&r.annual_savings&&e.jsx("span",{className:"text-xs text-green-600 font-semibold",children:r.annual_savings})]}),e.jsxs(k,{className:"space-y-3",children:[e.jsx("ul",{className:"space-y-2 text-sm",children:C.map((x,y)=>e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(re,{className:"h-4 w-4 text-primary shrink-0"}),String(x)]},y))}),c?e.jsx(T,{variant:"outline",className:"w-full",disabled:!0,children:"Plano Atual"}):r.plan_type==="subscription"&&t!=="free"?e.jsxs(e.Fragment,{children:[(t==="starter"||t==="pro")&&s==="free"&&e.jsx("div",{className:"text-center text-xs font-semibold text-green-600 bg-green-50 border border-green-200 rounded-md py-1.5 px-2 mb-2",children:"ð 7 dias grátis â cancele antes de ser cobrado"}),e.jsx(T,{className:"w-full",variant:r.is_highlighted?"default":"outline",onClick:()=>n(w),disabled:i===w,children:i===w?e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):e.jsx(e.Fragment,{children:d==="annual"&&m?`Assinar ${r.name} Anual`:r.cta_text||`Assinar ${r.name}`})})]}):e.jsx(T,{variant:"ghost",className:"w-full",disabled:!0,children:"â"})]})]},r.id)})})]})}function fs({analysisId:s,open:i,onClose:n}){const[a,g]=u.useState(null),[d,f]=u.useState(!1);u.useEffect(()=>{s&&i&&N(s)},[s,i]);async function N(l){f(!0),g(null);try{const{data:r,error:t}=await A.from("seo_analyses").select("id, url, score, created_at, crawl_data, technical_checks, issues, recommendations, keywords").eq("id",l).maybeSingle();if(console.log("[AnalysisDialog] Query result:",{id:l,data:r?"loaded":"null",error:t}),!r&&!t){console.warn("[AnalysisDialog] Proxy returned null, trying direct Supabase...");const c=`https://upmjyulgvnxqkbcvtsai.supabase.co/rest/v1/seo_analyses?id=eq.${l}&select=id,url,score,created_at,crawl_data,technical_checks,issues,recommendations,keywords`,C=await fetch(c,{headers:{apikey:"sb_publishable_ZceRWhZBUnJpoa6cIP6CPQ_yIKUk8h9",Authorization:`Bearer ${(await A.auth.getSession()).data.session?.access_token}`}});if(C.ok){const v=await C.json();if(v.length>0){const m=v[0];g({...m,technical_checks:Array.isArray(m.technical_checks)?m.technical_checks:[],issues:Array.isArray(m.issues)?m.issues:[],recommendations:Array.isArray(m.recommendations)?m.recommendations:[],keywords:Array.isArray(m.keywords)?m.keywords:[],crawl_data:m.crawl_data||{}}),f(!1);return}}_.error("Análise não encontrada"),f(!1);return}if(t)throw t;if(!r){_.error("Análise não encontrada");return}g({id:r.id,url:r.url,score:r.score,created_at:r.created_at,technical_checks:Array.isArray(r.technical_checks)?r.technical_checks:[],issues:Array.isArray(r.issues)?r.issues:[],recommendations:Array.isArray(r.recommendations)?r.recommendations:[],keywords:Array.isArray(r.keywords)?r.keywords:[],crawl_data:r.crawl_data||{}})}catch(r){console.error("[AnalysisDialog] Error loading analysis:",r),_.error("Erro ao carregar análise")}finally{f(!1)}}return e.jsx(Te,{open:i,onOpenChange:l=>!l&&n(),children:e.jsxs(Ee,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Ie,{children:e.jsxs(Le,{className:"flex items-center gap-2",children:[e.jsx(K,{className:"h-5 w-5"}),"Detalhes da Análise"]})}),d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(O,{className:"h-8 w-8 animate-spin text-primary"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-6",children:[e.jsx(Me,{score:a.score,size:"lg"}),e.jsxs("div",{className:"space-y-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-sm font-medium text-foreground break-all",children:a.url}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(a.created_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit"})})]})]}),a.technical_checks.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"Verificações Técnicas"}),e.jsx("div",{className:"grid gap-2",children:a.technical_checks.map((l,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded border",children:[l.passed?e.jsx(re,{className:"h-4 w-4 text-green-500 shrink-0"}):e.jsx(Z,{className:"h-4 w-4 text-destructive shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:l.label||l.name}),(l.details||l.detail)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:l.details||l.detail})]})]},r))})]}),a.issues.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-3 text-destructive",children:["Problemas Encontrados (",a.issues.length,")"]}),e.jsx("ul",{className:"space-y-2",children:a.issues.map((l,r)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm p-2 rounded bg-destructive/5 border border-destructive/10",children:[e.jsx(Z,{className:"h-4 w-4 text-destructive shrink-0 mt-0.5"}),e.jsx("span",{children:typeof l=="string"?l:l.message||l.description||JSON.stringify(l)})]},r))})]}),a.recommendations.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-3 text-primary",children:["Recomendações (",a.recommendations.length,")"]}),e.jsx("ul",{className:"space-y-2",children:a.recommendations.map((l,r)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm p-2 rounded bg-primary/5 border border-primary/10",children:[e.jsx(re,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsx("span",{children:typeof l=="string"?l:l.message||l.description||JSON.stringify(l)})]},r))})]}),a.keywords.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"Palavras-chave Sugeridas"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.keywords.map((l,r)=>e.jsx(D,{variant:"secondary",children:typeof l=="string"?l:l.keyword||l.term||JSON.stringify(l)},r))})]}),a.crawl_data&&Object.keys(a.crawl_data).length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"Dados do Crawl"}),(a.crawl_data.detectedPlatform||a.crawl_data.detectedRenderType)&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[a.crawl_data.detectedPlatform&&a.crawl_data.detectedPlatform!=="Desconhecido"&&e.jsxs(D,{variant:"secondary",className:"gap-1",children:[e.jsx(Y,{className:"h-3 w-3"}),a.crawl_data.detectedPlatform]}),a.crawl_data.detectedRenderType&&a.crawl_data.detectedRenderType!=="Desconhecido"&&e.jsx(D,{variant:"outline",className:"gap-1",children:a.crawl_data.detectedRenderType}),a.crawl_data.isHttps!==void 0&&e.jsxs(D,{variant:a.crawl_data.isHttps?"secondary":"destructive",className:"gap-1",children:[e.jsx(be,{className:"h-3 w-3"}),a.crawl_data.isHttps?"HTTPS â":"Sem HTTPS"]}),a.crawl_data.hreflangLangs?.length>0&&e.jsxs(D,{variant:"outline",className:"gap-1 text-xs",children:["Idiomas: ",a.crawl_data.hreflangLangs.join(", ")
7]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[a.crawl_data.wordCount!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:a.crawl_data.wordCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Palavras"})]}),a.crawl_data.loadTimeMs!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsxs("p",{className:"text-lg font-bold text-foreground",children:[a.crawl_data.loadTimeMs,"ms"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tempo de Resposta"})]}),a.crawl_data.totalImages!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:a.crawl_data.totalImages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Imagens"})]}),a.crawl_data.imagesWithoutAlt!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsx("p",{className:"text-lg font-bold text-destructive",children:a.crawl_data.imagesWithoutAlt}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sem Alt"})]}),a.crawl_data.totalLinks!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:a.crawl_data.totalLinks}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Links"})]}),a.crawl_data.h1Count!=null&&e.jsxs("div",{className:"p-3 rounded-lg border text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:a.crawl_data.h1Count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tags H1"})]})]})]}),e.jsx("div",{className:"pt-4 border-t flex justify-end",children:e.jsx(T,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(J,{href:`/analise/${a.id}`,children:[e.jsx(we,{className:"h-4 w-4 mr-1"}),"Ver relatório completo"]})})})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Análise não encontrada."})]})})}function Os(){const{user:s}=pe(),{subscription:i,planType:n,features:a,isSubscriber:g,canUseAlerts:d,createCheckout:f}=De(),[N,l]=u.useState([]),[r,t]=u.useState([]),[c,C]=u.useState([]),[v,m]=u.useState(!0),[w,x]=u.useState(null),[y,L]=u.useState(null),[h,j]=u.useState("overview");u.useEffect(()=>{s&&p()},[s]);async function p(){m(!0);try{const{data:o}=await A.from("monitored_urls").select("*").eq("user_id",s.id).order("created_at",{ascending:!0});if(o){const E=await Promise.all(o.map(async I=>{const{data:ie}=await A.from("seo_analyses").select("score").eq("monitored_url_id",I.id).order("created_at",{ascending:!1}).limit(2),{count:Ce}=await A.from("seo_analyses").select("id",{count:"exact",head:!0}).eq("monitored_url_id",I.id);return{...I,alert_threshold:I.alert_threshold??50,latest_score:ie?.[0]?.score??null,previous_score:ie?.[1]?.score??null,analyses_count:Ce??0}}));l(E)}if(d){const{data:E}=await A.from("seo_alerts").select("*").eq("user_id",s.id).order("sent_at",{ascending:!1}).limit(10);E&&t(E)}const{data:b}=await A.from("seo_analyses").select("id, url, score, created_at").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(50);b&&C(b)}catch(o){console.error("Dashboard load error:",o)}finally{m(!1)}}async function P(o){x(o);try{const b=await f(o);b.init_point&&(window.location.href=b.init_point)}catch(b){_.error(b.message||"Erro ao criar checkout")}finally{x(null)}}if(!s)return e.jsxs(e.Fragment,{children:[e.jsx(ne,{}),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(S,{className:"max-w-md w-full mx-4",children:e.jsxs(k,{className:"pt-6 text-center space-y-4",children:[e.jsx(be,{className:"h-12 w-12 mx-auto text-muted-foreground"}),e.jsx("h2",{className:"text-xl font-bold",children:"Acesso Restrito"}),e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o Dashboard SEO."}),e.jsx(T,{asChild:!0,children:e.jsx(J,{href:"/login",children:"Fazer Login"})})]})})}),e.jsx(le,{})]});const H=N.filter(o=>o.latest_score!==null).length>0?Math.round(N.filter(o=>o.latest_score!==null).reduce((o,b)=>o+(b.latest_score||0),0)/N.filter(o=>o.latest_score!==null).length):null;return N.filter(o=>o.latest_score!==null&&o.latest_score>=(o.alert_threshold||50)).length,N.filter(o=>o.latest_score!==null&&o.latest_score<(o.alert_threshold||50)).length,s.email&&s.user_metadata?.name,e.jsxs(e.Fragment,{children:[e.jsx(ke,{title:"Dashboard SEO | RankTop",description:"Painel consolidado com visão geral dos seus sites monitorados, scores e tendências SEO."}),e.jsx(ne,{}),e.jsx("main",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"container py-8 space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:"Dashboard SEO"}),e.jsx("p",{className:"text-muted-foreground",children:"Gerencie seus sites, acompanhe scores e otimize resultados"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(D,{variant:g?"default":"secondary",className:"gap-1",children:[e.jsx(ae,{className:"h-3 w-3"}),"Plano ",a.label]}),e.jsx(T,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(J,{href:"/diagnostico-seo",children:[e.jsx(Q,{className:"h-4 w-4 mr-1"}),"Nova Análise"]})})]})]}),e.jsxs(Ae,{value:h,onValueChange:j,className:"space-y-6",children:[e.jsxs(Pe,{className:"flex flex-wrap h-auto gap-1",children:[e.jsx(z,{value:"overview",children:"Visão Geral"}),e.jsx(z,{value:"history",children:"Histórico"}),e.jsx(z,{value:"evolution",children:"Evolução"}),e.jsx(z,{value:"monitoring",children:"Monitoramento"}),d&&e.jsx(z,{value:"alerts",children:"Alertas"}),e.jsx(z,{value:"plans",children:"Planos"}),e.jsx(z,{value:"profile",children:"Meu Perfil"})]}),e.jsxs($,{value:"overview",className:"space-y-6",children:[e.jsx(B,{icon:X,text:"Resumo do seu perfil SEO com métricas-chave e links rápidos para cada recurso."}),v?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(O,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(S,{children:e.jsx(k,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Ye,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:H??"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Score médio"})]})]})})}),e.jsx(S,{children:e.jsx(k,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Q,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total de análises"})]})]})})}),e.jsx(S,{children:e.jsx(k,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Y,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:N.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sites monitorados"})]})]})})}),e.jsx(S,{children:e.jsx(k,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(ae,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plano ativo"})]})]})})})]}),e.jsx("h3",{className:"font-semibold text-lg",children:"Ações Rápidas"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(S,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:()=>j("history"),children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(K,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Ver Histórico"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length," análises realizadas"]})]}),e.jsx(V,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsx(S,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:()=>j("evolution"),children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(G,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Evolução de Score"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tendência ao longo do tempo"})]}),e.jsx(V,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsx(S,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:()=>j("monitoring"),children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(ce,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Gerenciar Monitoramento"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.length," sites ativos"]})]}),e.jsx(V,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsx(J,{href:"/diagnostico-seo",children:e.jsx(S,{className:"hover:shadow-md transition-shadow group cursor-pointer",children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(Q,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Nova Análise"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Analise um site agora"})]}),e.jsx(we,{className:"h-4 w-4 text-muted-foreground"})]})})}),e.jsx(S,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:()=>j("profile"),children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(se,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Meu Perfil"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Dados e assinatura"})]}),e.jsx(V,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsx(S,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:()=>j("plans"),children:e.jsxs(k,{className:"pt-6 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 group-hover:bg-primary/20 transition-colors",children:e.jsx(de,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Planos"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gerencie sua assinatura"})]}),e.jsx(V,{className:"h-4 w-4 text-muted-foreground"})]})})]}),d&&r.length>0&&e.jsxs(S,{children:[e.jsx(M,{className:"pb-3",children:e.jsxs(R,{className:"text-base flex items-center gap-2",children:[e.jsx(F,{className:"h-4 w-4"})," Ãltimos Alertas"]})}),e.jsxs(k,{children:[e.jsx("div",{className:"space-y-2",children:r.slice(0,3).map(o=>e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsx(Z,{className:"h-4 w-4 text-destructive shrink-0"}),e.jsx("span",{className:"truncate flex-1",children:o.url}),e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[o.old_score," â ",o.new_score]})]},o.id))}),e.jsxs(T,{variant:"link",size:"sm",className:"mt-2 p-0",onClick:()=>j("alerts"),children:["Ver todos os alertas ",e.jsx(V,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsxs($,{value:"history",className:"space-y-4",children:[e.jsx(B,{icon:K,text:"Consulte o relatório completo de cada análise já realizada. Clique em um item para ver todos os detalhes."}),e.jsxs(S,{children:[e.jsx(M,{children:e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(K,{className:"h-5 w-5"}),"Histórico de Análises"]})}),e.jsx(k,{children:c.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(K,{className:"h-12 w-12 mx-auto text-muted-foreground
7/30 mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"Nenhuma análise realizada ainda."}),e.jsx(T,{variant:"outline",size:"sm",className:"mt-3",asChild:!0,children:e.jsx(J,{href:"/diagnostico-seo",children:"Fazer primeira análise"})})]}):e.jsx("div",{className:"grid gap-2",children:c.map(o=>e.jsxs("button",{onClick:()=>L(o.id),className:"flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent/5 transition-colors w-full text-left",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(ge,{score:o.score}),e.jsx("span",{className:"text-sm text-foreground truncate",children:o.url})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground shrink-0",children:[e.jsx(te,{className:"h-3 w-3"}),new Date(o.created_at).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}),e.jsx(X,{className:"h-3 w-3 ml-1"})]})]},o.id))})})]})]}),e.jsxs($,{value:"evolution",children:[e.jsx(B,{icon:G,text:"Acompanhe a tendência do score SEO dos seus sites ao longo do tempo. O gráfico mostra a evolução a cada análise."}),s&&e.jsx(os,{userId:s.id})]}),e.jsxs($,{value:"monitoring",children:[e.jsx(B,{icon:ce,text:"Gerencie seus sites e concorrentes para monitoramento automático semanal. Você receberá alertas por email quando o score mudar significativamente."}),s&&e.jsx(cs,{userId:s.id})]}),d&&e.jsxs($,{value:"alerts",className:"space-y-4",children:[e.jsx(B,{icon:F,text:"Notificações automáticas enviadas por email quando o score de um site monitorado cai abaixo do limite configurado."}),e.jsxs(S,{children:[e.jsx(M,{children:e.jsxs(R,{className:"flex items-center gap-2",children:[e.jsx(F,{className:"h-5 w-5"}),"Histórico de Alertas"]})}),e.jsx(k,{children:r.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"Nenhum alerta enviado ainda. Os alertas são disparados quando o score de um site monitorado cai abaixo do threshold configurado."}):e.jsx("div",{className:"space-y-3",children:r.map(o=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/50",children:[e.jsx(Z,{className:"h-5 w-5 text-destructive shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.url}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Score caiu de ",o.old_score," â ",o.new_score," (limite: ",o.threshold,")"]})]}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:new Date(o.sent_at).toLocaleDateString("pt-BR")})]},o.id))})})]})]}),e.jsxs($,{value:"plans",className:"space-y-6",children:[e.jsx(B,{icon:de,text:"Compare os planos disponÃveis e faça upgrade para desbloquear recursos avançados como alertas, exportação PDF e mais."}),e.jsx(gs,{planType:n,checkoutLoading:w,onCheckout:P})]}),e.jsxs($,{value:"profile",forceMount:!0,className:"data-[state=inactive]:hidden",children:[e.jsx(B,{icon:se,text:"Seus dados pessoais e informações da assinatura ativa. Mantenha seu perfil atualizado para receber relatórios personalizados."}),e.jsx(ps,{subscription:i,planType:n})]})]})]})}),e.jsx(le,{}),e.jsx(fs,{analysisId:y,open:!!y,onClose:()=>L(null)})]})}export{Os as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.