// App shell — router, tweaks integration, mount

const TWEAK_DEFAULTS = window.__TWEAK_DEFAULTS;

function App() {
  // Route is one of:
  // 'home', 'projects', 'sectors', 'services', 'capability', 'about', 'awards', 'contact', 'sitemap'
  // 'project:<id>', 'sector:<id>'
  const [route, setRoute] = useState('home');
  const [prefill, setPrefill] = useState(null);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweak vars to root
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty('--accent', t.accent);
    r.setProperty('--bronze', t.accent);
    r.setProperty('--bronze-soft', shade(t.accent, 0.45));
    r.setProperty('--bronze-deep', shade(t.accent, -0.2));
    r.setProperty('--density', String(t.density));
    r.setProperty('--display-weight', String(t.displayWeight));
    document.documentElement.setAttribute('dir', t.locale === 'ar' ? 'rtl' : 'ltr');
    document.documentElement.setAttribute('lang', t.locale);
  }, [t.accent, t.density, t.displayWeight, t.locale]);

  const go = (r, payload) => {
    setRoute(r);
    if (r === 'contact' && payload) setPrefill(payload);
    else if (r !== 'contact') setPrefill(null);
    window.scrollTo({ top: 0, behavior: 'instant' });
    window.history.replaceState(null, '', '#' + r);
  };

  // Read initial hash route
  useEffect(() => {
    const h = (window.location.hash || '').replace(/^#/, '');
    if (h) setRoute(h);
  }, []);

  const renderPage = () => {
    if (route.startsWith('project:')) return <PageCase go={go} id={route.split(':')[1]} showMaterials={t.showMaterials} />;
    if (route.startsWith('sector:'))  return <PageSectorDetail go={go} id={route.split(':')[1]} />;
    switch (route) {
      case 'home': return <PageHome go={go} />;
      case 'projects': return <PageProjects go={go} />;
      case 'sectors': return <PageSectorHub go={go} />;
      case 'services': return <PageServices go={go} />;
      case 'capability': return <PageCapability go={go} />;
      case 'about': return <PageAbout go={go} />;
      case 'awards': return <PageAwards go={go} />;
      case 'contact': return <PageContact go={go} prefill={prefill} />;
      case 'sitemap': return <PageSitemap go={go} />;
      default: return <PageHome go={go} />;
    }
  };

  return (
    <div>
      <Nav route={navTopId(route)} go={go} locale={t.locale} setLocale={(l) => setTweak('locale', l)} />
      {renderPage()}
      <Footer go={go} />

      {/* Sticky CTA on mobile */}
      <div className="stickycta">
        <button className="btn btn--lg" onClick={() => go('contact')}>Start a project →</button>
      </div>

      {/* TWEAKS PANEL */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent">
          <TweakColor label="Brand accent" value={t.accent}
            options={['#9A6A3C', '#1F2937', '#446B5A', '#7A1F2B', '#B89668']}
            onChange={(v) => setTweak('accent', v)} />
        </TweakSection>

        <TweakSection label="Type">
          <TweakSlider label="Display weight" value={t.displayWeight} min={400} max={700} step={100}
            onChange={(v) => setTweak('displayWeight', v)} />
        </TweakSection>

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

        <TweakSection label="Locale (preview)">
          <TweakRadio label="Direction" value={t.locale} options={['en','ar']}
            onChange={(v) => setTweak('locale', v)} />
        </TweakSection>

        <TweakSection label="Case study">
          <TweakToggle label="Show materials section" value={t.showMaterials}
            onChange={(v) => setTweak('showMaterials', v)} />
        </TweakSection>

        <TweakSection label="Jump to page">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6, marginTop: 4 }}>
            {[['home','Home'],['projects','Projects'],['project:tattu-dubai','Tattu'],['capability','Capability'],['contact','Start project'],['awards','Awards']].map(([k, l]) => (
              <button key={k} className="chip" style={{ fontSize: 10, padding: '5px 8px', letterSpacing: '0.08em' }} onClick={() => go(k)}>{l}</button>
            ))}
          </div>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function navTopId(route) {
  if (route.startsWith('project:')) return 'projects';
  if (route.startsWith('sector:')) return 'sectors';
  return route;
}

// Mix a hex toward white (amt > 0) or black (amt < 0)
function shade(hex, amt) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  if (amt >= 0) {
    r = Math.round(r + (255 - r) * amt);
    g = Math.round(g + (255 - g) * amt);
    b = Math.round(b + (255 - b) * amt);
  } else {
    r = Math.round(r * (1 + amt));
    g = Math.round(g * (1 + amt));
    b = Math.round(b * (1 + amt));
  }
  return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
}

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