(function(){
/* global React, ReactDOM, Router, useRouter, TopNav, Footer, Home, ServicesHub, GutterInstallation, ProductsHub, SeamlessAluminum, About, Contact, BlogIndex, BlogPost, GutterGuide, Icon */
const { useState, useEffect } = React;

const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variant": "field",
  "fonts": "fraunces-inter",
  "cta": "solid",
  "density": "default",
  "accent": "default"
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweaks] = useState(TWEAKS_DEFAULTS);

  // Apply tweaks to :root
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-variant', tweaks.variant);
    if (tweaks.fonts && tweaks.fonts !== 'fraunces-inter') r.setAttribute('data-fonts', tweaks.fonts);
    else r.removeAttribute('data-fonts');
    if (tweaks.cta && tweaks.cta !== 'solid') r.setAttribute('data-cta', tweaks.cta);
    else r.removeAttribute('data-cta');
    if (tweaks.density && tweaks.density !== 'default') r.setAttribute('data-density', tweaks.density);
    else r.removeAttribute('data-density');
    if (tweaks.accent && tweaks.accent !== 'default') r.setAttribute('data-accent', tweaks.accent);
    else r.removeAttribute('data-accent');
  }, [tweaks]);

  const set = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*'); } catch {}
  };

  return (
    <Router>
      <TopNav/>
      <main data-screen-label="App">
        <Route />
      </main>
      <Footer/>
    </Router>
  );
}

function Route() {
  const { path } = useRouter();
  const p = path.replace(/\/+$/, '') || '/';

  let content;
  if (p === '/' || p === '') content = <Home/>;
  else if (p === '/about') content = <About/>;
  else if (p === '/contact') content = <Contact/>;
  else if (p === '/services') content = <ServicesHub/>;
  else if (p === '/services/gutter-installation') content = <GutterInstallation/>;
  else if (p.startsWith('/services/')) content = <ServiceStub slug={p.split('/').pop()}/>;
  else if (p === '/products') content = <ProductsHub/>;
  else if (p === '/products/seamless-aluminum-gutters') content = <SeamlessAluminum/>;
  // Other product slugs fall through to ProductStub:
  //   copper-gutters, galvanized-steel-gutters, k-style-gutters, half-round-gutters, box-gutters,
  //   corrugated-round-downspouts, box-square-downspouts, rain-chains, leader-heads, gutter-guards
  else if (p.startsWith('/products/')) content = <ProductStub slug={p.split('/').pop()}/>;
  else if (p === '/gutter-guide') content = <GutterGuide/>;
  else if (p === '/blog') content = <BlogIndex/>;
  else if (p.startsWith('/blog/')) content = <BlogPost slug={p.split('/').pop()}/>;
  else if (p === '/service-areas' || p.startsWith('/service-areas')) content = <ServiceAreaStub slug={p.split('/').pop()}/>;
  else content = <NotFound path={p}/>;

  return <div data-screen-label={p}>{content}</div>;
}

function ServiceStub({ slug }) {
  const nice = slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  return <Stub title={nice} kind="service" back="/services"/>;
}
function ProductStub({ slug }) {
  const nice = slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  return <Stub title={nice} kind="product" back="/products"/>;
}
function ServiceAreaStub({ slug }) {
  const nice = slug && slug !== 'service-areas' ? slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) : 'All service areas';
  return <Stub title={nice} kind="service area" back="/service-areas"/>;
}
function Stub({ title, kind, back }) {
  return (
    <section style={{ padding: '72px 0 120px' }}>
      <div className="wrap-n" style={{ textAlign: 'center' }}>
        <div className="tag" style={{ marginBottom: 18 }}>{kind} page — stub</div>
        <h1>{title}</h1>
        <p className="muted" style={{ maxWidth: 520, margin: '22px auto 0', fontSize: 17 }}>
          This {kind} page follows the same template as the fully designed example in this prototype. It would include: intro · what's included · process · options · pricing factors · FAQ · CTA · related links · schema.
        </p>
        <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center' }}>
          <a href={'#' + back} className="btn btn-secondary">← Back to hub</a>
          <a href="#/gutter-guide" className="btn btn-primary">Get a free quote</a>
        </div>
      </div>
    </section>
  );
}
function NotFound({ path }) {
  return (
    <section style={{ padding: '120px 0' }}>
      <div className="wrap-n" style={{ textAlign: 'center' }}>
        <h1>404 — Not found</h1>
        <p className="muted" style={{ marginTop: 16 }}>Couldn't find "{path}".</p>
        <a href="#/" className="btn btn-primary" style={{ marginTop: 24 }}>Back home</a>
      </div>
    </section>
  );
}

function TweaksPanel({ tweaks, set }) {
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 100,
      width: 320, background: 'var(--color-surface)',
      border: '1px solid var(--color-border)', borderRadius: 16,
      boxShadow: 'var(--shadow-lg)', overflow: 'hidden',
      fontFamily: 'var(--font-body)',
    }}>
      <div style={{
        padding: '16px 20px', borderBottom: '1px solid var(--color-border)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'var(--color-primary)', color: '#F8F4EC',
      }}>
        <strong style={{ fontSize: 14, letterSpacing: '.04em' }}>Tweaks</strong>
        <span style={{ fontSize: 11, opacity: .7 }}>design controls</span>
      </div>
      <div style={{ padding: 18, display: 'grid', gap: 16 }}>
        <TweakRow label="Variant">
          <Segmented value={tweaks.variant} onChange={(v) => set('variant', v)}
            options={[['field', 'Field'], ['coastline', 'Coastline']]}/>
        </TweakRow>
        <TweakRow label="Typography">
          <Segmented value={tweaks.fonts} onChange={(v) => set('fonts', v)}
            options={[['fraunces-inter','Fraunces / Inter'],['fraunces-jakarta','Fraunces / Jakarta'],['dmserif-dmsans','DM Serif / DM Sans'],['outfit-inter','Outfit / Inter']]}
            stack/>
        </TweakRow>
        <TweakRow label="CTA style">
          <Segmented value={tweaks.cta} onChange={(v) => set('cta', v)}
            options={[['solid', 'Solid'], ['outline', 'Outline'], ['pill', 'Pill']]}/>
        </TweakRow>
        <TweakRow label="Density">
          <Segmented value={tweaks.density} onChange={(v) => set('density', v)}
            options={[['compact', 'Compact'], ['default', 'Default'], ['roomy', 'Roomy']]}/>
        </TweakRow>
        <TweakRow label="Accent intensity">
          <Segmented value={tweaks.accent} onChange={(v) => set('accent', v)}
            options={[['low', 'Low'], ['default', 'Med'], ['high', 'High']]}/>
        </TweakRow>
      </div>
    </div>
  );
}
function TweakRow({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--color-text-muted)', marginBottom: 8 }}>{label}</div>
      {children}
    </div>
  );
}
function Segmented({ value, onChange, options, stack }) {
  return (
    <div style={{
      display: stack ? 'grid' : 'flex',
      gridTemplateColumns: stack ? '1fr 1fr' : undefined,
      gap: 4, background: 'var(--color-bg)', borderRadius: 8, padding: 3,
      border: '1px solid var(--color-border)',
    }}>
      {options.map(([v, label]) => (
        <button key={v} onClick={() => onChange(v)}
          style={{
            padding: '7px 10px', borderRadius: 6, fontSize: 12, fontWeight: 500,
            background: value === v ? 'var(--color-surface)' : 'transparent',
            color: value === v ? 'var(--color-primary)' : 'var(--color-text-muted)',
            boxShadow: value === v ? 'var(--shadow-sm)' : 'none',
            flex: stack ? undefined : 1, cursor: 'pointer', whiteSpace: 'nowrap',
          }}>{label}</button>
      ))}
    </div>
  );
}

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

})();
