// app.jsx — Router + Tweaks for My Lovely Wedding

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "gold",
  "density": "regular",
  "lang": "en",
  "heroImage": "media/hero-3.webp"
}/*EDITMODE-END*/;

function parseHash() {
  const h = window.location.hash.replace(/^#\/?/, '');
  if (!h) return { route: 'home', params: {} };
  const [path, query] = h.split('?');
  const params = {};
  if (query) {
    query.split('&').forEach(kv => {
      const [k, v] = kv.split('=');
      params[k] = decodeURIComponent(v || '');
    });
  }
  const segs = path.split('/').filter(Boolean);
  if (segs[0] === 'wedding' && segs[1]) return { route: 'wedding', id: segs[1], params };
  return { route: segs[0] || 'home', params };
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [{ route, id, params }, setNav] = useState(parseHash());

  useEffect(() => {
    const on = () => setNav(parseHash());
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);

  // scroll to top on route change
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [route, id]);

  // Apply lang + accent + density to root
  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute('data-accent', t.accent);
    root.setAttribute('data-density', t.density);
    root.setAttribute('dir', t.lang === 'ar' ? 'rtl' : 'ltr');
    root.setAttribute('lang', t.lang === 'ar' ? 'ar' : 'en');
  }, [t]);

  const go = (key, extraParams) => {
    if (key === 'styling' || key === 'planning' || key === 'flowers') {
      window.location.hash = `/${key}`;
    } else if (key === 'weddings' && extraParams?.venue) {
      window.location.hash = `/weddings?venue=${extraParams.venue}`;
    } else {
      window.location.hash = `/${key}`;
    }
  };

  const openWedding = (id) => {
    window.location.hash = `/wedding/${id}`;
  };

  let page;
  switch (route) {
    case 'weddings':
      page = <WeddingsIndex lang={t.lang} onOpen={openWedding} initialFilter={params}/>;
      break;
    case 'wedding':
      page = <CaseStudy id={id} lang={t.lang} onBack={()=>go('weddings')} onOpen={openWedding}/>;
      break;
    case 'styling':
    case 'planning':
    case 'flowers':
      page = <ServicePage which={route} lang={t.lang} onNav={go}/>;
      break;
    case 'about':
      page = <About lang={t.lang} onNav={go}/>;
      break;
    case 'journal':
      page = <Journal lang={t.lang} onNav={go}/>;
      break;
    case 'contact':
      page = <Contact lang={t.lang} onNav={go}/>;
      break;
    case 'home':
    default:
      page = <Home lang={t.lang} onNav={go} openWedding={openWedding}/>;
  }

  return (
    <div data-screen-label={route === 'home' ? '01 Home' : route === 'weddings' ? '02 Real Weddings' : route === 'wedding' ? `03 Case Study` : route === 'styling' ? '04 Styling' : route === 'planning' ? '05 Planning' : route === 'flowers' ? '06 Flowers & Stationery' : route === 'about' ? '07 About' : route === 'journal' ? '08 Journal' : route === 'contact' ? '09 Enquire' : route}>
      <Nav route={route} lang={t.lang} onNav={go} onLang={(l)=>setTweak('lang', l)}/>
      {page}
      <Footer lang={t.lang} onNav={go}/>
      <WhatsAppFab lang={t.lang}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand"/>
        <TweakColor
          label="Accent"
          value={t.accent === 'gold' ? '#C9B26B' : t.accent === 'forest' ? '#4F6151' : '#C8907B'}
          options={['#C9B26B', '#4F6151', '#C8907B']}
          onChange={(hex) => setTweak('accent', hex === '#C9B26B' ? 'gold' : hex === '#4F6151' ? 'forest' : 'blush')}
        />
        <TweakRadio
          label="Language"
          value={t.lang}
          options={['en', 'ar']}
          onChange={(v) => setTweak('lang', v)}
        />
        <TweakSection label="Layout"/>
        <TweakRadio
          label="Density"
          value={t.density}
          options={['cozy', 'regular', 'airy']}
          onChange={(v) => setTweak('density', v)}
        />
        <TweakSection label="Pages"/>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 6 }}>
          {[
            ['Home','home'],['Weddings','weddings'],
            ['Styling','styling'],['Planning','planning'],
            ['Flowers','flowers'],['About','about'],
            ['Journal','journal'],['Enquire','contact'],
          ].map(([l, k]) => (
            <button key={k} onClick={()=>go(k)} style={{
              background: route === k ? 'var(--ink)' : 'transparent',
              color: route === k ? 'var(--paper)' : 'var(--ink)',
              border:'1px solid var(--line)',
              borderRadius: 4,
              padding:'8px 10px',
              fontSize: 11,
              letterSpacing:'0.12em',
              textTransform:'uppercase',
              cursor:'pointer',
              fontFamily:'inherit',
            }}>{l}</button>
          ))}
        </div>
        <TweakButton onClick={() => openWedding('waldorf-rak-garden')}>Open a wedding story →</TweakButton>
      </TweaksPanel>
    </div>
  );
}

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