/* =====================================================================
   Footer + App bootstrap v2
   ===================================================================== */
const { useRef: useRefFt } = React;
const BootSplash = window.BootSplash; // ported from src/Loaders.jsx via mwt-v2/loaders.jsx
const Marquee = window.Marquee; // mwt-v2/marquee.jsx

function Footer() {
  const ref = useRefFt(null); useReveal(ref);
  const site = window.MWT_SITE || {};
  const contact = site.contact || {};
  const footer = site.footer || {};
  const email = contact.email || 'hello@midwest.tech';
  const phone = contact.phone || '+14055550142';
  const phoneHref = contact.phoneHref || 'tel:+14055550142';
  const location = contact.location || 'Oklahoma City, OK';
  const socials = Array.isArray(contact.socials)
    ? contact.socials.filter(url => typeof url === 'string' && /^https?:\/\//i.test(url))
    : [];
  const footerDescription = footer.description || "Oklahoma's website studio. We build custom websites for service businesses, retailers, real estate agents, and anyone who needs more than a template — and we wire in AI agents that work for your customers around the clock. Based in OKC. Serving clients nationwide.";
  const copyrightLine = footer.copyrightLine || '© 2026 Midwest Technologies · All systems operational';
  const versionLine = footer.versionLine || 'v26.04.1 · 35.47°N 97.52°W';
  const socialCol = socials.length
    ? [{
        t:'Social',
        l:socials.map(url => {
          let label = url;
          try { label = new URL(url).hostname.replace(/^www\./, '').toUpperCase(); } catch (_) { /* keep URL */ }
          return [label, url];
        })
      }]
    : [];
  const cols = [
    { t:'Studio',  l:[['Work','#work'],['Services','#services'],['SEO','#seo'],['Contact','#contact']] },
    { t:'Build',   l:[['One-page sites','#services'],['Listings','#work'],['Marketing sites','#work'],['Custom dashboards','#work'],['AI helpers','#contact']] },
    { t:'Contact', l:[[email,`mailto:${email}`],[phone,phoneHref],[location,'#contact'],['Start a project','#contact']] },
    ...socialCol,
  ];
  return (
    <footer ref={ref} className="mw-reveal" style={{ borderTop:'1px solid var(--border)',
      padding:'clamp(48px,7vh,72px) clamp(20px,4vw,32px) 28px',
      background:'var(--bg-elev-1)' }}>
      <div style={{ maxWidth:1440, margin:'0 auto',
        display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))', gap:40 }}>
        {/* Brand column */}
        <div style={{ gridColumn:'span 2', minWidth:0 }} className="mw-footer-about">
          <Logo size={36}/>
          <p style={{ marginTop:16, maxWidth:380, fontSize:13, lineHeight:1.6, color:'var(--fg-3)',textWrap:'pretty' }}>
            {footerDescription}
          </p>
          <div style={{ display:'flex', gap:10, marginTop:20, flexWrap:'wrap' }}>
            <MagButton size="sm" variant="ghost" href="#contact"
              onClick={() => window['mwtTrack'] && window['mwtTrack']('select_content', {
                content_type: 'cta',
                content_id: 'footer_free_quote',
                cta_label: 'Free quote',
                page_section: 'footer',
                page_path: typeof window !== 'undefined' ? window.location.pathname : '',
              })}
            >Free quote</MagButton>
            <MagButton size="sm" variant="ghost" href={`mailto:${email}`} noArrow
              onClick={() => window['mwtTrack'] && window['mwtTrack']('email_click', {
                email,
                page_section: 'footer_brand',
                page_path: typeof window !== 'undefined' ? window.location.pathname : '',
              })}
            >{email}</MagButton>
          </div>
        </div>
        {/* Nav columns */}
        {cols.map(col => (
          <div key={col.t} style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.18em', color:'var(--fg-4)', marginBottom:2 }}>— {col.t.toUpperCase()}</div>
            {col.l.map(([l,h], idx) => (
              <a key={`${col.t}-${l}-${idx}`} href={h}
                onClick={() => {
                  if (!window['mwtTrack']) return;
                  if (typeof h === 'string' && h.indexOf('mailto:') === 0) {
                    window['mwtTrack']('email_click', {
                      email: h.slice(7),
                      page_section: 'footer_nav',
                      page_path: typeof window !== 'undefined' ? window.location.pathname : '',
                    });
                  } else if (typeof h === 'string' && h.indexOf('tel:') === 0) {
                    window['mwtTrack']('phone_call_click', {
                      phone_number: h.slice(4),
                      page_section: 'footer_nav',
                      page_path: typeof window !== 'undefined' ? window.location.pathname : '',
                    });
                  } else if (typeof h === 'string' && /^https?:\/\//i.test(h)) {
                    try {
                      var domain = new URL(h).hostname;
                      if (domain && domain !== window.location.host) {
                        window['mwtTrack']('outbound_link', {
                          link_url: h,
                          link_domain: domain,
                          page_path: window.location.pathname,
                        });
                      }
                    } catch (_) { /* noop */ }
                  }
                }}
                style={{ color:'var(--fg-2)', textDecoration:'none', fontSize:13, lineHeight:1.5, transition:'color .15s' }}
                onMouseEnter={e=>e.currentTarget.style.color='var(--accent)'}
                onMouseLeave={e=>e.currentTarget.style.color='var(--fg-2)'}>{l}</a>
            ))}
          </div>
        ))}
      </div>
      {/* Bottom bar */}
      <div style={{ maxWidth:1440, margin:'40px auto 0', paddingTop:18, borderTop:'1px solid var(--border)',
        display:'flex', justifyContent:'space-between', gap:16, flexWrap:'wrap',
        fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--fg-4)' }}>
        <span>{copyrightLine}</span>
        <span>{versionLine}</span>
      </div>
    </footer>
  );
}

/* =====================================================================
   App bootstrap — TOD logic, component mount
   ===================================================================== */
const { useState: useStApp, useEffect: useEfApp } = React;

function todFromHour(h) {
  if (h >= 5 && h < 8)  return 'sunrise';
  if (h >= 8 && h < 17) return 'day';
  if (h >= 17 && h < 20) return 'sunset';
  return 'night';
}

// BootSplash is provided globally by mwt-v2/loaders.jsx (ported from src/Loaders.jsx).
// The v1 splash — circular logo + progress ring + stage labels — is the canonical one.

function App() {
  const [booted, setBooted] = useStApp(false);
  const [auto, setAuto] = useStApp(true);
  const [tod, setTod] = useStApp(() => todFromHour(new Date().getHours()));
  const [tweaks, setTweak] = useTweaks(window.MWT_TWEAK_DEFAULTS);

  useEfApp(() => {
    if (!auto) return;
    const tick = () => setTod(todFromHour(new Date().getHours()));
    tick();
    // Honor prefers-reduced-motion: skip the every-minute auto-cycle so
    // the page state doesn't shift under users who've asked for less motion.
    const rm =
      typeof window !== 'undefined' && window.matchMedia
        ? window.matchMedia('(prefers-reduced-motion: reduce)')
        : null;
    if (rm && rm.matches) return;
    const t = setInterval(tick, 60000);
    return () => clearInterval(t);
  }, [auto]);

  useEfApp(() => {
    document.documentElement.setAttribute('data-tod', tod);
  }, [tod]);

  useEfApp(() => {
    document.documentElement.setAttribute('data-moon-pos', tweaks.moonPosition);
  }, [tweaks.moonPosition]);

  return (
    <>
      {!booted && <BootSplash onDone={() => setBooted(true)}/>}
      <Nav tod={tod} setTod={setTod} auto={auto} setAuto={setAuto}/>
      <main>
        <Hero tod={tod}/>
        <Marquee/>
        <Services/>
        <Projects/>
        <SEOIntelligence/>
        <Contact/>
      </main>
      <Footer/>
      <MwtTweaks tweaks={tweaks} setTweak={setTweak}/>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
