import { useState, useEffect } from 'react'
import home from './home-body.html?raw'
import sobreNos from './sobre-nos-body.html?raw'
import contato from './contato-body.html?raw'
import Blog from './Blog.jsx'
import Article from './Article.jsx'
import Eventos from './Eventos.jsx'
import HomeBlogSection from './HomeBlogSection.jsx'
import MapSection from './MapSection.jsx'
import HeroSlideshow from './HeroSlideshow.jsx'
import GoogleReviews from './GoogleReviews.jsx'
import { createRoot } from 'react-dom/client'
import Loader from './Loader.jsx'
import './article.css'

// Divide o HTML da home em torno da seção de blog do Elementor
const BLOG_SPLIT_START = '<div class="elementor-element elementor-element-6e9a689 e-flex e-con-boxed e-con e-parent e-lazyloaded" data-id="6e9a689"'
const BLOG_SPLIT_END = '<div data-elementor-type="footer" data-elementor-id="136"'
const blogStartIdx = home.indexOf(BLOG_SPLIT_START)
const blogEndIdx = home.indexOf(BLOG_SPLIT_END)
const homeTop = blogStartIdx > 0 ? home.slice(0, blogStartIdx) : home
const homeBottom = blogEndIdx > 0 ? home.slice(blogEndIdx) : ''


// ─── BayerlPress API ──────────────────────────────────────────────────────────
const CMS = 'https://cms.bayerl.cloud/api/buenas'

function normalizePost(p) {
  const meta = p.meta ?? {}
  const ts = Number(p.published_at ?? p.created_at)
  const date = isNaN(ts) ? '' : new Date(ts).toLocaleDateString('pt-BR', {
    day: '2-digit', month: '2-digit', year: 'numeric'
  })
  return {
    id: p.id,
    slug: p.slug,
    title: p.title,
    date,
    excerpt: meta.excerpt ?? '',
    image: meta.featured_image ?? '',
    content: p.content?.htmlContent ?? '',
    faq: meta.faq ?? [],
    seo_title: meta.seo_title ?? p.title,
    meta_description: meta.meta_description ?? meta.excerpt ?? '',
  }
}

async function fetchPosts() {
  const res = await fetch(`${CMS}/posts?limit=100`)
  if (!res.ok) throw new Error('Erro ao carregar posts')
  const { data } = await res.json()
  return data.map(normalizePost)
}

async function fetchPost(slug) {
  const res = await fetch(`${CMS}/posts/${slug}`)
  if (!res.ok) return null
  const { data } = await res.json()
  return normalizePost(data)
}

// ─── Tracker ──────────────────────────────────────────────────────────────────
const SESSION_KEY = 'bn_sid'
function getSessionId() {
  let sid = sessionStorage.getItem(SESSION_KEY)
  if (!sid) { sid = Math.random().toString(36).slice(2) + Date.now().toString(36); sessionStorage.setItem(SESSION_KEY, sid) }
  return sid
}
function track(type, extra = {}) {
  fetch('https://cms.bayerl.cloud/track', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      type,
      page: window.location.pathname,
      session_id: getSessionId(),
      data: { tenant: 'buenas', referrer: document.referrer, ...extra },
    }),
  }).catch(() => {})
}

// ─── SEO ──────────────────────────────────────────────────────────────────────
function setSeo({ title, description, image } = {}) {
  if (title) document.title = title
  const setMeta = (name, val) => {
    let el = document.querySelector(`meta[name="${name}"]`) ?? document.querySelector(`meta[property="${name}"]`)
    if (!el) { el = document.createElement('meta'); el.setAttribute(name.startsWith('og:') ? 'property' : 'name', name); document.head.appendChild(el) }
    el.setAttribute('content', val ?? '')
  }
  if (description) { setMeta('description', description); setMeta('og:description', description) }
  if (title) setMeta('og:title', title)
  if (image) setMeta('og:image', image)
}

// ─── Páginas HTML capturadas ──────────────────────────────────────────────────
const CAPTURED = {
  '/': [home, 'Home - Buenas Carnes e Pasta'],
  '/sobre-nos/': [sobreNos, 'Sobre nós - Buenas'],
  '/contato/': [contato, 'Contato - Buenas'],
}
const withSlash = (p) => (p.endsWith('/') ? p : p + '/')

// ─── App ──────────────────────────────────────────────────────────────────────
export default function App() {
  const raw = window.location.pathname
  const p = withSlash(raw)
  const [posts, setPosts] = useState([])
  const [post, setPost] = useState(null)
  const [loading, setLoading] = useState(false)

  // Detecta se é uma rota de artigo (não é capturada nem blog/eventos)
  const staticPaths = ['/', '/sobre-nos/', '/eventos/', '/blog/', '/contato/']
  const isArticle = !staticPaths.includes(p) && !p.startsWith('/wp-')

  useEffect(() => {
    track('pageview')
  }, [])

  // GoogleReviews — injeta via DOM no lugar do widget TrustIndex morto (elementor-9082ab4)
  useEffect(() => {
    if (p !== '/' && p !== '') return
    const trustindex = document.querySelector('.elementor-element-9082ab4')
    if (!trustindex || trustindex.querySelector('.gr-section')) return
    const wrapper = document.createElement('div')
    trustindex.replaceWith(wrapper)
    const root = createRoot(wrapper)
    root.render(<GoogleReviews />)
    return () => root.unmount()
  }, [p])

  // Hamburger toggle — Elementor JS não roda em dangerouslySetInnerHTML
  useEffect(() => {
    const init = () => {
      const toggle = document.querySelector('.elementor-menu-toggle')
      const dropdown = document.querySelector('.elementor-nav-menu--dropdown-tablet .elementor-nav-menu--dropdown')
      if (!toggle || !dropdown) return
      dropdown.style.display = 'none'
      const onClick = () => {
        const open = toggle.classList.toggle('elementor-active')
        toggle.setAttribute('aria-expanded', open)
        dropdown.style.display = open ? 'block' : 'none'
      }
      toggle.addEventListener('click', onClick)
      return () => toggle.removeEventListener('click', onClick)
    }
    // Aguarda o DOM do dangerouslySetInnerHTML renderizar
    const frame = requestAnimationFrame(init)
    return () => cancelAnimationFrame(frame)
  }, [p])

  useEffect(() => {
    if (p === '/blog/' || isArticle) {
      setLoading(true)
      fetchPosts().then(data => { setPosts(data); setLoading(false) }).catch(() => setLoading(false))
    }
    if (isArticle) {
      const slug = p.replace(/^\/|\/$/g, '')
      fetchPost(slug).then(data => {
        if (data) {
          setPost(data)
          setSeo({ title: `${data.seo_title} - Buenas`, description: data.meta_description, image: data.image })
        }
      })
    }
  }, [p])

  // Páginas HTML capturadas do WordPress
  const cap = CAPTURED[raw] || CAPTURED[p]
  if (cap) {
    setSeo({ title: cap[1] })
    // Home: injeta seção de blog dinâmica no lugar do Elementor estático
    if (raw === '/' || raw === '') {
      return (
        <>
          <div dangerouslySetInnerHTML={{ __html: homeTop }} />
          <HeroSlideshow />
          <MapSection />
          <HomeBlogSection />
          <div dangerouslySetInnerHTML={{ __html: homeBottom }} />
        </>
      )
    }
    return <div dangerouslySetInnerHTML={{ __html: cap[0] }} />
  }

  if (p === '/eventos/') {
    setSeo({ title: 'Eventos - Buenas' })
    return <Eventos />
  }

  if (p === '/blog/') {
    setSeo({ title: 'Blog - Buenas Carnes e Pasta', description: 'Histórias, cortes e sabores da Buenas Carnes & Pasta' })
    return loading
      ? <Loader />
      : <Blog articles={posts} />
  }

  if (isArticle) {
    if (!post || loading) return <Loader />
    return <Article article={post} all={posts} />
  }

  setSeo({ title: 'Buenas Carnes e Pasta' })
  return <div dangerouslySetInnerHTML={{ __html: home }} />
}
