import { useEffect } from 'react'
import { Outlet } from 'react-router-dom'
import { Footer } from './Footer'
import { Header } from './Header'

export function Layout() {
  useEffect(() => {
    if (typeof window === 'undefined') return

    if (document.getElementById('mailerlite-universal')) return

    const script = document.createElement('script')
    script.id = 'mailerlite-universal'
    script.innerHTML = `
      (function(m,a,i,l,e,r){
        m['MailerLiteObject']=e;
        function f(){
          var c={a:arguments,q:[]};
          var r=this.push(c);
          return "number"!=typeof r?r:f.bind(c.q);
        }
        f.q=f.q||[];
        m[e]=m[e]||f.bind(f.q);
        m[e].q=m[e].q||f.q;
        r=a.createElement(i);
        var _=a.getElementsByTagName(i)[0];
        r.async=1;
        r.src=l+'?v'+(~~(new Date().getTime()/1000000));
        _.parentNode.insertBefore(r,_);
      })(window, document, 'script', 'https://static.mailerlite.com/js/universal.js', 'ml');
      window.ml_account = ml('accounts', '1778010', 'x2d3d9f8n1', 'load');
    `

    document.body.appendChild(script)

    return () => {
      script.remove()
    }
  }, [])

  return (
    <div className="bg-[#fdfdfd] antialiased relative" style={{ fontFamily: 'var(--font-inter)' }}>
      <div className="relative z-10">
        <Header />
        <main>
          <Outlet />
        </main>
        <Footer />
      </div>
    </div>
  )
}
