const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "#10b981",
  "darkAccent": "#059669",
  "showMarquee": true,
  "fontFamily": "Plus Jakarta Sans"
}/*EDITMODE-END*/;

const VALID_PAGES = ['home','gmc','shopping','insider','preapproved','about','contact','cases','pricing','blog','services','partner'];
const parsePath = () => {
  const p = window.location.pathname.replace(/^\/|\/$/g, '');
  if (!p) return { page: 'home', slug: null };
  const parts = p.split('/');
  if (parts[0] === 'blog' && parts[1]) return { page: 'blog', slug: parts[1] };
  return { page: VALID_PAGES.includes(parts[0]) ? parts[0] : 'home', slug: null };
};
const pageToPath = (p, slug) => {
  if (p === 'home') return '/';
  if (p === 'blog' && slug) return '/blog/' + slug;
  return '/' + p;
};

const App = () => {
  const initial = parsePath();
  const [page, setPage] = React.useState(initial.page);
  const [blogSlug, setBlogSlug] = React.useState(initial.slug);
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const [showTweaks, setShowTweaks] = React.useState(false);

  const navigate = (p, opts) => {
    const slug = (opts && opts.slug) || null;
    setPage(p);
    setBlogSlug(slug);
    const path = pageToPath(p, slug);
    if (window.location.pathname !== path) window.history.pushState({ page: p, slug }, '', path);
    if (window.__applyPageSEO) window.__applyPageSEO(p);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  React.useEffect(() => {
    if (window.__applyPageSEO) window.__applyPageSEO(page);
    const onPop = () => { const s = parsePath(); setPage(s.page); setBlogSlug(s.slug); if (window.__applyPageSEO) window.__applyPageSEO(s.page); };
    window.addEventListener('popstate', onPop);
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setShowTweaks(true);
      if (e.data?.type === '__deactivate_edit_mode') setShowTweaks(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => { window.removeEventListener('message', handler); window.removeEventListener('popstate', onPop); };
  }, []);

  const updateTweak = (key, val) => {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
    if (key === 'accentColor') document.documentElement.style.setProperty('--green', val);
    if (key === 'darkAccent') document.documentElement.style.setProperty('--green-dark', val);
    if (key === 'fontFamily') document.body.style.fontFamily = `'${val}', sans-serif`;
  };

  const pages = { home: HomePage, gmc: GMCPage, shopping: ShoppingPage, insider: InsiderPage, preapproved: PreApprovedPage, about: AboutPage, contact: ContactPage, cases: CasesPage, pricing: PricingPage, blog: BlogPage, services: typeof ServicesPage !== 'undefined' ? ServicesPage : HomePage, partner: PartnerPage };
  const PageComponent = pages[page] || HomePage;

  return (
    <>
      <Nav currentPage={page} navigate={navigate} />
      <PageComponent navigate={navigate} tweaks={tweaks} blogSlug={blogSlug} />
      <Footer navigate={navigate} />

      {showTweaks && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, width: 290, background: 'white', borderRadius: 20, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', border: '1px solid #e2e8f0', zIndex: 9999, overflow: 'hidden' }}>
          <div style={{ background: 'linear-gradient(135deg,#059669,#10b981)', padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ color: 'white', fontWeight: 800, fontSize: 14 }}>✦ Tweaks</span>
            <button onClick={() => setShowTweaks(false)} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.8)', cursor: 'pointer', fontSize: 16 }}>✕</button>
          </div>
          <div style={{ padding: '16px 18px 20px' }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: '#94a3b8', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>Accent Color</div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
              {[['#10b981','#059669','Emerald'],['#3b82f6','#2563eb','Blue'],['#8b5cf6','#7c3aed','Purple'],['#f59e0b','#d97706','Amber']].map(([light,dark,name]) => (
                <div key={name} onClick={() => { updateTweak('accentColor',light); updateTweak('darkAccent',dark); }} title={name}
                  style={{ width: 30, height: 30, borderRadius: '50%', background: light, cursor: 'pointer', border: tweaks.accentColor===light ? '3px solid #0f172a' : '3px solid transparent', boxShadow: tweaks.accentColor===light ? '0 0 0 2px white inset' : 'none', transition: 'border 0.15s' }} />
              ))}
            </div>
            <div style={{ fontSize: 11, fontWeight: 800, color: '#94a3b8', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>Font</div>
            <select value={tweaks.fontFamily} onChange={e => updateTweak('fontFamily', e.target.value)}
              style={{ width: '100%', padding: '9px 12px', border: '1.5px solid #e2e8f0', borderRadius: 9, fontSize: 13, fontFamily: 'Plus Jakarta Sans,sans-serif', outline: 'none', marginBottom: 18, cursor: 'pointer', background: 'white' }}>
              {['Plus Jakarta Sans','Inter','DM Sans','Sora','Outfit'].map(f => <option key={f}>{f}</option>)}
            </select>
            <div style={{ fontSize: 11, fontWeight: 800, color: '#94a3b8', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>Marquee Ticker</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
              <div onClick={() => updateTweak('showMarquee', !tweaks.showMarquee)}
                style={{ width: 42, height: 24, borderRadius: 12, background: tweaks.showMarquee ? '#10b981' : '#e2e8f0', position: 'relative', cursor: 'pointer', transition: 'background 0.2s' }}>
                <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'white', position: 'absolute', top: 3, left: tweaks.showMarquee ? 21 : 3, transition: 'left 0.2s', boxShadow: '0 1px 4px rgba(0,0,0,0.2)' }} />
              </div>
              <span style={{ fontSize: 13, color: '#475569' }}>{tweaks.showMarquee ? 'Visible' : 'Hidden'}</span>
            </div>
            <div style={{ fontSize: 11, fontWeight: 800, color: '#94a3b8', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10 }}>Navigate</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {[['home','Home'],['gmc','GMC'],['shopping','Shopping'],['about','About'],['cases','Results'],['pricing','Pricing'],['blog','Blog'],['contact','Contact']].map(([p,label]) => (
                <button key={p} onClick={() => navigate(p)}
                  style={{ fontSize: 12, fontWeight: 600, padding: '5px 12px', borderRadius: 50, border: '1.5px solid', borderColor: page===p ? '#10b981' : '#e2e8f0', background: page===p ? '#ecfdf5' : 'white', color: page===p ? '#065f46' : '#64748b', cursor: 'pointer', fontFamily: 'Plus Jakarta Sans,sans-serif', transition: 'all 0.15s' }}>{label}</button>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
};

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