// ────────────────────────────────────────────────────────────
// site-nav.jsx — Einheitliche globale Navigation + Footer für alle Unterseiten.
// Ersetzt die früher pro Seite kopierten Header.
//
// Exporte:
//   <GlobalNav lang setLang page variant accent />   — sticky top nav (3 Varianten)
//   <SiteFooter lang page maxWidth />                 — einheitlicher Footer
//   useSiteTweaks()                                   — Hook: nav-Variante + accent, persistiert
//   <NavTweaks tweaks setTweaks editMode onClose />   — Tweaks-Panel (Nav-Variante wählen)
//
// Home (index.html) bleibt unangetastet — nutzt diese Nav NICHT.
// ────────────────────────────────────────────────────────────

// Nav-/Footer-Labels ergänzen (COPY lebt in shared.jsx).
COPY.de.navSteckbrief = 'Agent planen';
COPY.en.navSteckbrief = 'Plan your agent';
COPY.de.navStufen = '5 Stufen';
COPY.en.navStufen = '5 stages';
COPY.de.navEvents = 'Events';
COPY.en.navEvents = 'Events';
COPY.de.navBlog = 'Blog';
COPY.en.navBlog = 'Blog';
COPY.de.navAgenten = 'KI-Beratung';
COPY.en.navAgenten = 'AI consulting';
COPY.de.navHome = 'Start';
COPY.en.navHome = 'Start';
COPY.de.menu = 'Menü';
COPY.en.menu = 'Menu';
COPY.de.agentenFooter = 'KI-Beratung';
COPY.en.agentenFooter = 'AI consulting';

const NAV_LINKS = [
  { id: 'steckbrief', key: 'navSteckbrief', href: 'steckbrief.html' },
  { id: 'stufen', key: 'navStufen', href: 'stufen.html' },
  { id: 'events', key: 'navEvents', href: 'events.html' },
  { id: 'blog', key: 'navBlog', href: 'https://kiliansblog.substack.com/', external: true },
];

// ── Coral "K" mark ───────────────────────────────────────────
function KMark({ size = 26, accent = KS.coral }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 5,
      background: accent, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: KSFonts.mono, fontWeight: 700, fontSize: size * 0.5,
      letterSpacing: 0, flexShrink: 0, lineHeight: 1,
    }}>K</span>
  );
}

// ── Wordmark (K + name) ──────────────────────────────────────
function Wordmark({ accent, big = false }) {
  return (
    <a href="index.html" style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      textDecoration: 'none', color: KS.charcoal, whiteSpace: 'nowrap',
    }}>
      <KMark size={big ? 30 : 26} accent={accent} />
      <span style={{
        fontWeight: 700, fontSize: big ? 17 : 15.5, letterSpacing: -0.3, color: KS.charcoal,
      }}>Kilian Springer</span>
    </a>
  );
}

// ── One nav link (desktop) ───────────────────────────────────
function NavLink({ link, active, lang, accent, mono = false }) {
  const t = COPY[lang];
  const [hover, setHover] = React.useState(false);
  const on = active || hover;
  return (
    <a
      href={link.href}
      {...(link.external ? { target: '_blank', rel: 'noreferrer' } : {})}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative',
        textDecoration: 'none',
        color: on ? accent : KS.charcoal,
        fontFamily: mono ? KSFonts.mono : KSFonts.body,
        fontSize: mono ? 11.5 : 14,
        fontWeight: mono ? 500 : 500,
        letterSpacing: mono ? 1 : 0,
        textTransform: mono ? 'uppercase' : 'none',
        padding: '6px 0',
        transition: 'color 160ms ease',
        display: 'inline-flex', alignItems: 'center', gap: 5,
      }}
    >
      {t[link.key]}
      {link.external && <Icon name="arrow-up-right" size={mono ? 11 : 12} style={{ opacity: 0.5 }} />}
      <span style={{
        position: 'absolute', left: 0, right: 0, bottom: -2, height: 2,
        background: accent,
        transformOrigin: 'left',
        transform: `scaleX(${active ? 1 : hover ? 0.6 : 0})`,
        opacity: active ? 1 : hover ? 0.6 : 0,
        transition: 'transform 200ms cubic-bezier(.2,.7,.2,1), opacity 160ms ease',
      }} />
    </a>
  );
}

// ── CTA button ───────────────────────────────────────────────
function NavCta({ lang, accent, outlined = false }) {
  const t = COPY[lang];
  const [hover, setHover] = React.useState(false);
  const base = {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    padding: '11px 18px', fontSize: 13.5, fontWeight: 600,
    textDecoration: 'none', borderRadius: 6, whiteSpace: 'nowrap',
    transition: 'all 160ms ease', cursor: 'pointer',
    lineHeight: 1,
  };
  const style = outlined
    ? {
        ...base,
        background: hover ? accent : 'transparent',
        color: hover ? '#fff' : KS.charcoal,
        border: `1.5px solid ${hover ? accent : KS.borderStrong}`,
      }
    : {
        ...base,
        background: accent, color: '#fff', border: `1.5px solid ${accent}`,
        filter: hover ? 'brightness(0.93)' : 'none',
        boxShadow: hover ? '0 6px 18px -8px rgba(255,100,79,0.7)' : 'none',
      };
  return (
    <a
      href="beratung.html"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={style}
    >
      <span style={{ width: 6, height: 6, borderRadius: 3, background: outlined ? accent : 'rgba(255,255,255,0.9)', display: 'inline-block' }} />
      {t.navAgenten}
    </a>
  );
}

// ── Hamburger button ─────────────────────────────────────────
function Burger({ open, onClick, accent }) {
  return (
    <button
      onClick={onClick}
      aria-label="Menu"
      aria-expanded={open}
      style={{
        width: 42, height: 42, border: `1px solid ${KS.borderStrong}`,
        background: '#fff', borderRadius: 8, cursor: 'pointer',
        display: 'inline-flex', flexDirection: 'column', gap: 4,
        alignItems: 'center', justifyContent: 'center', padding: 0,
      }}
    >
      {[0, 1, 2].map(i => (
        <span key={i} style={{ width: 18, height: 2, background: KS.charcoal, borderRadius: 2, display: 'block' }} />
      ))}
    </button>
  );
}

// ── Mobile full-screen overlay (charcoal) ────────────────────
function MobileOverlay({ open, onClose, lang, setLang, page, accent }) {
  const t = COPY[lang];
  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: KS.charcoal,
        display: 'flex', flexDirection: 'column',
        padding: '20px 24px 32px',
        opacity: open ? 1 : 0,
        pointerEvents: open ? 'auto' : 'none',
        transform: open ? 'translateY(0)' : 'translateY(-8px)',
        transition: 'opacity 220ms ease, transform 260ms cubic-bezier(.2,.7,.2,1)',
      }}
      aria-hidden={!open}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <a href="index.html" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <KMark size={28} accent={accent} />
          <span style={{ fontWeight: 700, fontSize: 16, color: KS.offwhite, letterSpacing: -0.3 }}>Kilian Springer</span>
        </a>
        <button onClick={onClose} aria-label="Close" style={{
          width: 42, height: 42, border: '1px solid rgba(248,247,246,0.24)', background: 'transparent',
          color: KS.offwhite, borderRadius: 8, cursor: 'pointer', fontSize: 22, lineHeight: 1,
        }}>×</button>
      </div>

      <nav style={{ marginTop: 48, display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
        {NAV_LINKS.map((link, i) => {
          const active = link.id === page;
          return (
            <a
              key={link.id}
              href={link.href}
              {...(link.external ? { target: '_blank', rel: 'noreferrer' } : {})}
              onClick={onClose}
              style={{
                display: 'flex', alignItems: 'baseline', gap: 14,
                textDecoration: 'none',
                color: active ? accent : KS.offwhite,
                fontSize: 38, fontWeight: 700, letterSpacing: -1.2,
                padding: '12px 0', borderBottom: '1px solid rgba(248,247,246,0.1)',
              }}
            >
              <span style={{ fontFamily: KSFonts.mono, fontSize: 12, fontWeight: 500, color: active ? accent : 'rgba(248,247,246,0.4)', letterSpacing: 1 }}>0{i + 1}</span>
              {t[link.key]}
              {link.external && <Icon name="arrow-up-right" size={20} style={{ opacity: 0.5 }} />}
            </a>
          );
        })}
      </nav>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginTop: 24 }}>
        <a href="beratung.html" onClick={onClose} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          background: accent, color: '#fff', padding: '15px 22px', borderRadius: 8,
          fontSize: 15, fontWeight: 600, textDecoration: 'none', flex: 1, justifyContent: 'center',
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.9)' }} />
          {t.navAgenten}
        </a>
        <div style={{ display: 'inline-flex', padding: 3, border: '1px solid rgba(248,247,246,0.2)', borderRadius: 999 }}>
          {['de', 'en'].map(code => {
            const active = lang === code;
            return (
              <button key={code} onClick={() => setLang(code)} style={{
                background: active ? KS.offwhite : 'transparent',
                color: active ? KS.charcoal : KS.offwhite,
                border: 'none', padding: '8px 14px', fontFamily: KSFonts.mono, fontSize: 12,
                letterSpacing: 0.5, textTransform: 'uppercase', cursor: 'pointer', borderRadius: 999,
              }}>{code}</button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── GlobalNav ────────────────────────────────────────────────
function GlobalNav({ lang, setLang, page, variant = 'rule', accent = KS.coral }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const [mobile, setMobile] = React.useState(() => (typeof window !== 'undefined' ? window.innerWidth < 880 : false));

  React.useEffect(() => {
    const h = () => setMobile(window.innerWidth < 880);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  React.useEffect(() => {
    const h = () => setScrolled(window.scrollY > 8);
    h();
    window.addEventListener('scroll', h, { passive: true });
    return () => window.removeEventListener('scroll', h);
  }, []);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  // close overlay if resized to desktop
  React.useEffect(() => { if (!mobile) setOpen(false); }, [mobile]);

  const isPill = variant === 'pill';
  const isMono = variant === 'mono';

  // scrolled surface
  const solidBg = 'rgba(248,247,246,0.82)';
  const blur = 'saturate(180%) blur(12px)';

  // ── MOBILE ──
  if (mobile) {
    return (
      <>
        <header style={{
          position: 'sticky', top: 0, zIndex: 100,
          background: scrolled ? solidBg : 'transparent',
          backdropFilter: scrolled ? blur : 'none',
          WebkitBackdropFilter: scrolled ? blur : 'none',
          borderBottom: `1px solid ${scrolled ? KS.border : 'transparent'}`,
          transition: 'background 220ms ease, border-color 220ms ease',
          padding: '12px 18px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <Wordmark accent={accent} />
          <Burger open={open} onClick={() => setOpen(true)} accent={accent} />
        </header>
        <MobileOverlay open={open} onClose={() => setOpen(false)} lang={lang} setLang={setLang} page={page} accent={accent} />
      </>
    );
  }

  // ── DESKTOP: PILL (floating) ──
  if (isPill) {
    return (
      <div style={{
        position: 'sticky', top: 0, zIndex: 100,
        padding: scrolled ? '10px 20px' : '18px 20px',
        transition: 'padding 240ms ease',
        pointerEvents: 'none',
      }}>
        <nav style={{
          pointerEvents: 'auto',
          maxWidth: 1140, margin: '0 auto',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24,
          padding: '10px 12px 10px 20px',
          background: 'rgba(255,255,255,0.9)',
          backdropFilter: blur, WebkitBackdropFilter: blur,
          border: `1px solid ${KS.border}`,
          borderRadius: 999,
          boxShadow: scrolled ? '0 12px 32px -16px rgba(73,70,72,0.4)' : '0 4px 16px -10px rgba(73,70,72,0.25)',
          transition: 'box-shadow 240ms ease',
        }}>
          <Wordmark accent={accent} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 26 }}>
            {NAV_LINKS.map(link => (
              <NavLink key={link.id} link={link} active={link.id === page} lang={lang} accent={accent} />
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <LangToggle lang={lang} setLang={setLang} />
            <NavCta lang={lang} accent={accent} />
          </div>
        </nav>
      </div>
    );
  }

  // ── DESKTOP: MONO (editorial / technical) ──
  if (isMono) {
    return (
      <header style={{
        position: 'sticky', top: 0, zIndex: 100,
        background: scrolled ? solidBg : 'transparent',
        backdropFilter: scrolled ? blur : 'none',
        WebkitBackdropFilter: scrolled ? blur : 'none',
        borderBottom: `1px solid ${scrolled ? KS.border : 'transparent'}`,
        transition: 'background 220ms ease, border-color 220ms ease',
      }}>
        <div style={{ height: 3, background: accent }} />
        <div style={{
          maxWidth: 1180, margin: '0 auto',
          padding: '16px 32px',
          display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 24,
        }}>
          <Wordmark accent={accent} big />
          <nav style={{ display: 'flex', alignItems: 'center', gap: 30, justifySelf: 'center' }}>
            {NAV_LINKS.map(link => (
              <NavLink key={link.id} link={link} active={link.id === page} lang={lang} accent={accent} mono />
            ))}
          </nav>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, justifySelf: 'end' }}>
            <LangToggle lang={lang} setLang={setLang} />
            <NavCta lang={lang} accent={accent} outlined />
          </div>
        </div>
      </header>
    );
  }

  // ── DESKTOP: RULE (refined default) ──
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: scrolled ? solidBg : 'transparent',
      backdropFilter: scrolled ? blur : 'none',
      WebkitBackdropFilter: scrolled ? blur : 'none',
      borderBottom: `1px solid ${scrolled ? KS.border : 'transparent'}`,
      transition: 'background 220ms ease, border-color 220ms ease',
    }}>
      <div style={{
        maxWidth: 1180, margin: '0 auto',
        padding: '15px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32,
      }}>
        <Wordmark accent={accent} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 30 }}>
          <nav style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
            {NAV_LINKS.map(link => (
              <NavLink key={link.id} link={link} active={link.id === page} lang={lang} accent={accent} />
            ))}
          </nav>
          <div style={{ width: 1, height: 22, background: KS.border }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <LangToggle lang={lang} setLang={setLang} />
            <NavCta lang={lang} accent={accent} />
          </div>
        </div>
      </div>
    </header>
  );
}

// ── SiteFooter ───────────────────────────────────────────────
function SiteFooter({ lang, page, maxWidth = 1180 }) {
  const t = COPY[lang];
  const links = [
    { id: 'home', label: t.about, href: 'index.html' },
    { id: 'steckbrief', label: t.navSteckbrief, href: 'steckbrief.html' },
    { id: 'stufen', label: t.navStufen, href: 'stufen.html' },
    { id: 'events', label: t.navEvents, href: 'events.html' },
    { id: 'agenten', label: t.agentenFooter, href: 'beratung.html' },
    { id: 'downloads', label: t.downloadsNav, href: 'downloads.html' },
    { id: 'impressum', label: t.imprint, href: 'impressum.html' },
    { id: 'datenschutz', label: t.privacy, href: 'datenschutz.html' },
  ];
  return (
    <footer style={{
      borderTop: `1px solid ${KS.border}`, marginTop: 120,
      maxWidth, margin: '120px auto 0',
      padding: '32px 32px 40px',
      fontFamily: KSFonts.mono, fontSize: 10.5, letterSpacing: 0.5, textTransform: 'uppercase',
      color: KS.muted,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 14,
    }}>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
        <KMark size={18} accent={KS.coral} />
        <span>© 2026 · kilian-springer.com</span>
      </div>
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        {links.map(l => (
          <a key={l.id} href={l.href} style={{
            color: l.id === page ? KS.coral : 'inherit', textDecoration: 'none',
          }}>{l.label}</a>
        ))}
      </div>
    </footer>
  );
}

// ── Tweaks: nav variant + accent (persisted, host edit-mode) ──
const SITE_TWEAK_KEY = 'ks-site-tweaks-v2';
const SITE_TWEAK_DEFAULTS = { nav: 'pill', accent: KS.coral };

function useSiteTweaks() {
  const [tweaks, setTweaksState] = React.useState(() => {
    let base = { ...SITE_TWEAK_DEFAULTS };
    try {
      const s = JSON.parse(localStorage.getItem(SITE_TWEAK_KEY) || 'null');
      if (s && typeof s === 'object') base = { ...base, ...s };
    } catch (e) {}
    return base;
  });
  const [editMode, setEditMode] = React.useState(false);

  const setTweaks = React.useCallback((next) => {
    setTweaksState(prev => {
      const merged = typeof next === 'function' ? next(prev) : next;
      try { localStorage.setItem(SITE_TWEAK_KEY, JSON.stringify(merged)); } catch (e) {}
      return merged;
    });
  }, []);

  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data;
      if (!d || typeof d !== 'object') return;
      if (d.type === '__activate_edit_mode') setEditMode(true);
      else if (d.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  return { tweaks, setTweaks, editMode };
}

function NavTweaks({ tweaks, setTweaks, editMode, onClose }) {
  if (!editMode) return null;
  const set = (k, v) => {
    setTweaks(prev => ({ ...prev, [k]: v }));
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };
  const navOptions = [
    ['rule', 'Linie'],
    ['pill', 'Pille'],
    ['mono', 'Mono'],
  ];
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 1000, width: 260,
      background: '#fff', border: `1px solid ${KS.borderStrong}`,
      boxShadow: '0 20px 60px -20px rgba(0,0,0,0.25)',
      fontFamily: KSFonts.body, color: KS.charcoal,
    }}>
      <div style={{
        padding: '10px 14px', borderBottom: `1px solid ${KS.border}`, background: KS.offwhite,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div style={{ fontFamily: KSFonts.mono, fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase' }}>Tweaks</div>
        {onClose && <button onClick={onClose} style={{ background: 'none', border: 0, cursor: 'pointer', fontSize: 14, color: KS.muted }}>×</button>}
      </div>
      <div style={{ padding: 14, display: 'grid', gap: 16 }}>
        <div>
          <div style={{ fontFamily: KSFonts.mono, fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: KS.muted, marginBottom: 6 }}>Navigation</div>
          <div style={{ display: 'inline-flex', border: `1px solid ${KS.border}`, borderRadius: 6, overflow: 'hidden' }}>
            {navOptions.map(([v, l]) => {
              const active = tweaks.nav === v;
              return (
                <button key={v} onClick={() => set('nav', v)} style={{
                  background: active ? KS.charcoal : '#fff', color: active ? KS.offwhite : KS.charcoal,
                  border: 0, padding: '7px 14px', fontFamily: KSFonts.mono, fontSize: 11,
                  letterSpacing: 0.5, textTransform: 'uppercase', cursor: 'pointer',
                }}>{l}</button>
              );
            })}
          </div>
        </div>
        <div>
          <div style={{ fontFamily: KSFonts.mono, fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: KS.muted, marginBottom: 6 }}>Akzentfarbe</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[KS.coral, KS.deepRed, KS.forest, KS.charcoal].map(c => (
              <button key={c} onClick={() => set('accent', c)} aria-label={c} style={{
                width: 24, height: 24, borderRadius: 12, background: c,
                border: tweaks.accent === c ? `2px solid ${KS.black}` : `1px solid ${KS.border}`,
                cursor: 'pointer', padding: 0,
              }} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  GlobalNav, SiteFooter, KMark, useSiteTweaks, NavTweaks, NAV_LINKS,
});
