// app.jsx — main App: routing state + tweaks panel + density / direction switching

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "soil",
  "hero": "kinetic",
  "palette": ["#1a3a2a", "#c9a961", "#e8e2d0"],
  "density": 1.0,
  "dark": false,
  "subBrand": "minerals",
  "sectionOrder": ["intro", "stats", "minerals", "feature", "lands", "visit", "projects", "cta"]
}/*EDITMODE-END*/;

function applyPalette(p) {
  if (!Array.isArray(p) || p.length < 3) return;
  const r = document.documentElement.style;
  r.setProperty('--forest', p[0]);
  r.setProperty('--gold', p[1]);
  r.setProperty('--paper', p[2]);
  // also derive a tinted bg-elevated:
  r.setProperty('--paper-soft', p[2]);
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = React.useState('home');
  const [subBrand, setSubBrand] = React.useState(t.subBrand || 'minerals');

  // sync direction + dark + palette + density to root html element
  React.useEffect(() => {
    const html = document.documentElement;
    html.classList.toggle('dir-bedrock', t.direction === 'bedrock');
    html.classList.toggle('dir-soil', t.direction !== 'bedrock');
    html.classList.toggle('dark', !!t.dark);
    html.style.setProperty('--density-scale', t.density);
    applyPalette(t.palette);
  }, [t.direction, t.dark, t.density, t.palette]);

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

  // simple reveal-on-scroll observer
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [page]);

  const renderPage = () => {
    switch (page) {
      case 'about':    return <AboutPage setPage={setPage} />;
      case 'minerals': return <MineralsPage setPage={setPage} />;
      case 'lands':    return <LandsPage setPage={setPage} />;
      case 'visit':    return <VisitPage setPage={setPage} />;
      case 'projects': return <ProjectsPage setPage={setPage} />;
      case 'insights': return <InsightsPage setPage={setPage} />;
      case 'careers':  return <CareersPage setPage={setPage} />;
      case 'contact':  return <ContactPage />;
      default:         return <Home
        hero={t.hero}
        subBrand={subBrand}
        setSubBrand={setSubBrand}
        setPage={setPage}
        sectionOrder={t.sectionOrder}
      />;
    }
  };

  // Section reorder helper — move section up/down
  const moveSection = (idx, dir) => {
    const order = [...t.sectionOrder];
    const ni = idx + dir;
    if (ni < 0 || ni >= order.length) return;
    [order[idx], order[ni]] = [order[ni], order[idx]];
    setTweak('sectionOrder', order);
  };
  const resetOrder = () => setTweak('sectionOrder', TWEAK_DEFAULTS.sectionOrder);

  return (
    <React.Fragment>
      <Nav page={page} setPage={setPage} subBrand={subBrand} setSubBrand={setSubBrand} />
      {renderPage()}
      <Footer setPage={setPage} />

      <TweaksPanel>
        <TweakSection label="Direction" />
        <TweakRadio label="Type system" value={t.direction}
                    options={['soil', 'bedrock']}
                    onChange={v => setTweak('direction', v)} />

        <TweakSection label="Hero" />
        <TweakRadio label="Layout" value={t.hero}
                    options={['kinetic', 'split', 'editorial']}
                    onChange={v => setTweak('hero', v)} />

        <TweakSection label="Theme" />
        <TweakColor label="Palette" value={t.palette}
                    options={[
                      ['#1a3a2a', '#c9a961', '#e8e2d0'],
                      ['#2a1d12', '#b8541f', '#d9c9a3'],
                      ['#0f1f2e', '#7a8a4a', '#e6e9ec'],
                      ['#1f1f1d', '#8a6d3b', '#f5f2e8'],
                    ]}
                    onChange={v => setTweak('palette', v)} />
        <TweakToggle label="Dark mode" value={t.dark}
                     onChange={v => setTweak('dark', v)} />

        <TweakSection label="Layout" />
        <TweakSlider label="Density" value={t.density}
                     min={0.7} max={1.3} step={0.05}
                     onChange={v => setTweak('density', v)} />

        {page === 'home' && (
          <React.Fragment>
            <TweakSection label="Section order (home)" />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '4px 12px 8px' }}>
              {t.sectionOrder.map((s, i) => (
                <div key={s} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  background: 'rgba(0,0,0,0.04)', borderRadius: 6, padding: '4px 6px 4px 10px', fontSize: 11,
                }}>
                  <span style={{ textTransform: 'capitalize' }}>{i + 1}. {s}</span>
                  <span style={{ display: 'flex', gap: 4 }}>
                    <button onClick={() => moveSection(i, -1)} disabled={i === 0}
                            style={{ background: 'rgba(0,0,0,0.06)', border: 'none', padding: '2px 6px', borderRadius: 4, cursor: i === 0 ? 'not-allowed' : 'pointer', opacity: i === 0 ? 0.4 : 1 }}>↑</button>
                    <button onClick={() => moveSection(i, +1)} disabled={i === t.sectionOrder.length - 1}
                            style={{ background: 'rgba(0,0,0,0.06)', border: 'none', padding: '2px 6px', borderRadius: 4, cursor: i === t.sectionOrder.length - 1 ? 'not-allowed' : 'pointer', opacity: i === t.sectionOrder.length - 1 ? 0.4 : 1 }}>↓</button>
                  </span>
                </div>
              ))}
              <TweakButton label="Reset order" onClick={resetOrder} />
            </div>
          </React.Fragment>
        )}

        <TweakSection label="Navigate" />
        <TweakSelect label="Page" value={page}
                     options={[
                       { value: 'home', label: 'Home' },
                       { value: 'about', label: 'About' },
                       { value: 'minerals', label: 'Minerals' },
                       { value: 'lands', label: 'Lands' },
                       { value: 'visit', label: 'Visit' },
                       { value: 'projects', label: 'Projects' },
                       { value: 'insights', label: 'Insights' },
                       { value: 'careers', label: 'Careers' },
                       { value: 'contact', label: 'Contact' },
                     ]}
                     onChange={setPage} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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