// App shell: theme system, router, nav, footer.
const { useState, useEffect, useMemo, useCallback, useRef, createContext, useContext } = React;

// ---------- Theme presets ----------
const FONT_PRESETS = {
  'editorial': {
    label: 'Editorial',
    display: "'Fraunces', 'Tiempos', Georgia, serif",
    sans: "'Inter Tight', 'Inter', system-ui, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  },
  'industrial': {
    label: 'Industrial',
    display: "'Space Grotesk', 'Inter Tight', sans-serif",
    sans: "'Inter Tight', 'Inter', system-ui, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  },
  'classic': {
    label: 'Classic',
    display: "'Instrument Serif', 'EB Garamond', Georgia, serif",
    sans: "'DM Sans', system-ui, sans-serif",
    mono: "'IBM Plex Mono', ui-monospace, monospace",
  },
  'utility': {
    label: 'Utility',
    display: "'JetBrains Mono', ui-monospace, monospace",
    sans: "'Inter Tight', system-ui, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  },
};

// Curated brand palettes — name : [primary, accent, ink, bg]
const BRAND_PALETTES = [
  { id: 'rubin',      label: 'Rubin',      colors: ['#8D1D2C', '#FFB000', '#14110d', '#faf7f2'] },
  { id: 'navy',       label: 'Granat',     colors: ['#0d52a1', '#FF7514', '#14110d', '#faf7f2'] },
  { id: 'mech',       label: 'Mech',       colors: ['#2F4538', '#E5BE01', '#14110d', '#faf7f2'] },
  { id: 'ink',        label: 'Tusz',       colors: ['#14110d', '#F44611', '#14110d', '#faf7f2'] },
];

const HERO_VARIANTS = [
  { id: 'palette-strip', label: 'Paleta RAL' },
  { id: 'split-image',   label: 'Foto split' },
  { id: 'manifesto',     label: 'Manifest' },
  { id: 'product-led',   label: 'Produktowy' },
];

const CARD_STYLES = [
  { id: 'flat',     label: 'Płaski' },
  { id: 'soft',     label: 'Miękki' },
  { id: 'sharp',    label: 'Ostry' },
];

// ---------- Theme context ----------
const ThemeCtx = createContext(null);
const useTheme = () => useContext(ThemeCtx);

function applyThemeToScope(el, t) {
  if (!el) return;
  const palette = BRAND_PALETTES.find(p => p.id === t.palette) || BRAND_PALETTES[0];
  el.style.setProperty('--brand', palette.colors[0]);
  el.style.setProperty('--accent', palette.colors[1]);

  const fonts = FONT_PRESETS[t.fontPreset] || FONT_PRESETS.editorial;
  el.style.setProperty('--font-display', fonts.display);
  el.style.setProperty('--font-sans', fonts.sans);
  el.style.setProperty('--font-mono', fonts.mono);

  el.style.setProperty('--density', String(t.density));

  // Card styles
  if (t.cardStyle === 'flat') {
    el.style.setProperty('--card-radius', '14px');
    el.style.setProperty('--card-shadow', 'none');
    el.style.setProperty('--card-border', '1px solid var(--line)');
  } else if (t.cardStyle === 'sharp') {
    el.style.setProperty('--card-radius', '0px');
    el.style.setProperty('--card-shadow', 'none');
    el.style.setProperty('--card-border', '1px solid var(--ink)');
  } else {
    el.style.setProperty('--card-radius', '22px');
    el.style.setProperty('--card-shadow', 'var(--sh-1)');
    el.style.setProperty('--card-border', '1px solid var(--line)');
  }

  el.dataset.theme = t.dark ? 'dark' : 'light';
  el.dataset.heroVariant = t.heroVariant;
}

function ThemeProvider({ children, defaults, scopeRef }) {
  const [theme, setTheme] = useState(defaults);
  const setKey = (k, v) => setTheme(t => ({ ...t, [k]: v }));

  useEffect(() => {
    applyThemeToScope(scopeRef.current, theme);
  }, [theme]);

  return (
    <ThemeCtx.Provider value={{ theme, setKey, setTheme }}>
      {children}
    </ThemeCtx.Provider>
  );
}

// ---------- Router (hash-based, scoped per app instance) ----------
const RouterCtx = createContext(null);
const useRouter = () => useContext(RouterCtx);

function RouterProvider({ children, scopeId }) {
  const [path, setPath] = useState('/');
  const navigate = useCallback((p) => {
    setPath(p);
    // Update hash for shareable deep-links — only on the "main" app
    if (scopeId === 'main') {
      try {
        history.replaceState(null, '', '#' + p);
      } catch (e) {}
    }
  }, [scopeId]);

  // Read hash on mount for the main app
  useEffect(() => {
    if (scopeId !== 'main') return;
    const h = window.location.hash.slice(1);
    if (h && h.startsWith('/')) setPath(h);
    const onHash = () => {
      const h = window.location.hash.slice(1);
      if (h && h.startsWith('/')) setPath(h);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [scopeId]);

  return (
    <RouterCtx.Provider value={{ path, navigate }}>
      {children}
    </RouterCtx.Provider>
  );
}

function Link({ to, children, className = '', ...rest }) {
  const { navigate, path } = useRouter();
  const active = path === to || (to !== '/' && path.startsWith(to));
  const onClick = (e) => {
    e.preventDefault();
    navigate(to);
    // Scroll the closest scrollable parent (or window) to top
    requestAnimationFrame(() => {
      const wrap = document.querySelector('.fl-app-scroll');
      if (wrap) wrap.scrollTop = 0;
      else window.scrollTo({ top: 0 });
    });
  };
  return (
    <a href={'#' + to} onClick={onClick} className={className}
       aria-current={active ? 'page' : undefined} {...rest}>
      {children}
    </a>
  );
}

// ---------- Nav ----------
function Nav() {
  const [menuOpen, setMenuOpen] = useState(false);
  return (
    <header className="fl-nav">
      <div className="container fl-nav__inner">
        <Link to="/" className="fl-logo" aria-label="Farby i Lakiery — strona główna">
          <span className="fl-logo__mark" aria-hidden="true"></span>
          <span>
            Pałyszka <em style={{ fontStyle: 'italic', fontWeight: 380 }}>&amp;</em> Kaczka
            <small>Farby i lakiery · od 1990</small>
          </span>
        </Link>

        <nav className="fl-nav__links" aria-label="Główna nawigacja">
          {NAV_ITEMS.map(it => (
            <Link key={it.id} to={it.href} className="fl-nav__link">{it.label}</Link>
          ))}
        </nav>

        <div className="fl-nav__right">
          <a className="fl-nav__phone" href="tel:+48446335625">
            <Icon name="phone" size={14} stroke={1.8}/> 44 633 56 25
          </a>
          <Link to="/kontakt" className="fl-nav__cta">
            Zamów próbnik <Icon name="arrow-right" size={14}/>
          </Link>
          <button className="fl-nav__menu-btn" aria-label="Menu" onClick={() => setMenuOpen(o => !o)}>
            <Icon name={menuOpen ? 'x' : 'menu'}/>
          </button>
        </div>
      </div>
      {menuOpen && (
        <div className="container" style={{ paddingBlock: 'var(--space-4)', borderTop: 'var(--hairline)' }}>
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {NAV_ITEMS.map(it => (
              <Link key={it.id} to={it.href} className="fl-nav__link" onClick={() => setMenuOpen(false)}
                    style={{ padding: '12px 14px' }}>
                {it.label}
              </Link>
            ))}
          </nav>
        </div>
      )}
    </header>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="fl-foot">
      <div className="container">
        <div className="fl-foot__grid">
          <div>
            <div className="fl-foot__brand">
              Wszystkie<br/>kolory <em>świata</em>.
            </div>
            <p style={{ marginTop: 24, maxWidth: '38ch', lineHeight: 1.55, color: 'rgba(255,255,255,0.7)', fontSize: 14 }}>
              Pałyszka &amp; Kaczka. Dystrybutor farb i lakierów dla Bełchatowa, Radomska
              i okolic. Od 1990 roku — trzy oddziały, tysiące zrealizowanych projektów.
            </p>
            <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
              <a href="#" aria-label="Facebook" style={{
                width: 38, height: 38, borderRadius: 999, border: '1px solid rgba(255,255,255,0.15)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
              }}><Icon name="facebook" size={16}/></a>
              <a href="#" aria-label="Instagram" style={{
                width: 38, height: 38, borderRadius: 999, border: '1px solid rgba(255,255,255,0.15)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
              }}><Icon name="instagram" size={16}/></a>
            </div>
          </div>
          <div>
            <h4>Oferta</h4>
            <ul>
              <li><Link to="/katalog">Farby dekoracyjne</Link></li>
              <li><Link to="/katalog">Farby przemysłowe</Link></li>
              <li><Link to="/katalog">Tynki strukturalne</Link></li>
              <li><Link to="/katalog">Akcesoria malarskie</Link></li>
              <li><Link to="/kalkulator">Kalkulator zużycia</Link></li>
            </ul>
          </div>
          <div>
            <h4>Firma</h4>
            <ul>
              <li><Link to="/o-firmie">O firmie</Link></li>
              <li><Link to="/galeria">Galeria salonów</Link></li>
              <li><Link to="/kontakt">Kontakt</Link></li>
              <li><a href="#">Współpraca B2B</a></li>
              <li><a href="#">Pracuj z nami</a></li>
            </ul>
          </div>
          <div>
            <h4>Punkty</h4>
            <ul>
              {BRANCHES.map(b => (
                <li key={b.id}>
                  <strong style={{ color: '#fff', fontSize: 14, display: 'block' }}>{b.name}</strong>
                  <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>{b.address}</span>
                </li>
              ))}
            </ul>
            <h4 style={{ marginTop: 28 }}>Prawo</h4>
            <ul>
              <li><Link to="/cookies">Polityka cookies</Link></li>
              <li><Link to="/rodo">RODO</Link></li>
            </ul>
          </div>
        </div>
        <div className="fl-foot__bottom">
          <span>© 1990–2026 F.H.U. Andrzej Pałyszka &amp; Stanisław Kaczka Sp.j.</span>
          <span style={{ fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>
            NIP 769-00-12-345 · KRS 0000123456
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---------- App ----------
function App({ scopeId = 'main' }) {
  const { path } = useRouter();
  const Page = useMemo(() => routePage(path), [path]);

  return (
    <div className="fl-app">
      <Nav />
      <main>
        <Page key={path} />
      </main>
      <Footer />
    </div>
  );
}

function routePage(path) {
  if (path === '/' || path === '') return PageHome;
  if (path.startsWith('/katalog')) return PageCatalog;
  if (path.startsWith('/kalkulator')) return PageCalculator;
  if (path.startsWith('/galeria')) return PageGallery;
  if (path.startsWith('/o-firmie')) return PageAbout;
  if (path.startsWith('/kontakt')) return PageContact;
  if (path.startsWith('/cookies')) return PageCookies;
  if (path.startsWith('/rodo')) return PageGDPR;
  return PageNotFound;
}

Object.assign(window, {
  ThemeProvider, useTheme, RouterProvider, useRouter, Link,
  Nav, Footer, App, applyThemeToScope,
  BRAND_PALETTES, FONT_PRESETS, HERO_VARIANTS, CARD_STYLES,
});
