// =============================================================
// LoFi Wireframe Primitives — ZVK Steinmetz
// =============================================================

const { useState, useEffect, useRef } = React;
// Greyscale, annotation-heavy. No brand. Communicates structure,
// not visual design. Each module labelled. Placeholder text
// as pure horizontal lines (TextLines) and grey boxes (Box).
// =============================================================

const wfColors = {
  paper: '#FBFBFA',
  ink: '#1F1F1F',
  mute: '#6A6A6A',
  line: '#C9C9C5',
  fill: '#E8E6E2',
  fillDark: '#D4D1CC',
  accent: '#2C2C2C', // annotation ink
  annotBg: '#FFF6D5' // sticky-note yellow for annotations
};

// ---------- WFLink — hash-router link wrapper ------------------
function WFLink({ to, children, style, title }) {
  if (!to) return <span style={style}>{children}</span>;
  return (
    <a href={'#' + to} title={title}
       style={{ color: 'inherit', textDecoration: 'inherit', cursor: 'pointer', display: 'inline-block', ...style }}>
      {children}
    </a>
  );
}

// Map of nav label → route
const NAV_ROUTES = {
  'Leistungen':            '/leistungen/betriebliche-rentenbeihilfe',
  'Unsere Leistungen':     '/leistungen/betriebliche-rentenbeihilfe',
  'Service':               '/service',
  'Über die ZVK':          '/ueber-uns',
  'Kontakt':               '/service/kontakt',
  'Für Betriebe':          '/fuer-betriebe',
  'Für Versicherte':       '/fuer-versicherte',
  'Für Rentner':           '/fuer-rentner',
  'Für Hinterbliebene':    '/fuer-hinterbliebene',
  'Betriebe':              '/fuer-betriebe',
  'Versicherte':           '/fuer-versicherte',
  'Rentner':               '/fuer-rentner',
  'Hinterbliebene':        '/fuer-hinterbliebene',
};

// ---------- Frame ----------------------------------------------
// Browser-chrome artboard. Drop-in contents are the page itself.
// ---------------------------------------------------------------
function WFFrame({ label, path, width = 1280, children, note }) {
  return (
    <div style={{
      width: width,
      background: wfColors.paper,
      border: `1px solid ${wfColors.line}`,
      boxShadow: '0 1px 0 rgba(0,0,0,.03)',
      fontFamily: 'Panton, system-ui, sans-serif',
      color: wfColors.ink,
      position: 'relative'
    }}>
      {/* chrome */}
      <div style={{
        borderBottom: `1px solid ${wfColors.line}`,
        padding: '10px 14px',
        display: 'flex',
        alignItems: 'center',
        gap: 10,
        background: '#F3F1ED'
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#D4D1CC' }}></span>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#D4D1CC' }}></span>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#D4D1CC' }}></span>
        </div>
        <div style={{
          flex: 1,
          background: wfColors.paper,
          border: `1px solid ${wfColors.line}`,
          borderRadius: 999,
          padding: '4px 12px',
          fontSize: 12,
          fontFamily: 'ui-monospace, Menlo, monospace',
          color: wfColors.mute
        }}>
          zvk-steinmetz.de{path}
        </div>
        <div style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: wfColors.mute }}>
          {label}
        </div>
      </div>
      {children}
      {note &&
      <div style={{
        position: 'absolute',
        top: -8,
        right: -8,
        background: wfColors.annotBg,
        border: `1px solid ${wfColors.line}`,
        padding: '6px 10px',
        fontSize: 11,
        fontFamily: 'ui-monospace, Menlo, monospace',
        maxWidth: 220,
        boxShadow: '0 2px 8px rgba(0,0,0,.06)'
      }}>{note}</div>
      }
    </div>);

}

// ---------- Nav chrome — zweistufig (IA v1) -----------------------
// Zeile 1: Logo + Primärnavigation (Leistungen · Service · Über die ZVK · Kontakt)
// Zeile 2: Sekundärnavigation (Für Betriebe · Für Versicherte · Für Rentner)
function WFNav({ active, activePersona }) {
  const [openMenu, setOpenMenu] = useState(null);
  const navRef = useRef(null);

  const personas = [
    { label: 'Betriebe',    to: '/fuer-betriebe',    matches: ['Betriebe', 'Für Betriebe'] },
    { label: 'Versicherte', to: '/fuer-versicherte', matches: ['Versicherte', 'Für Versicherte'] },
    { label: 'Rentner',     to: '/fuer-rentner',     matches: ['Rentner', 'Für Rentner'] },
  ];

  const mainItems = [
    { label: 'Leistungen', to: '/leistungen/betriebliche-rentenbeihilfe', submenu: [
      { label: 'Betriebliche Rentenbeihilfe', to: '/leistungen/betriebliche-rentenbeihilfe' },
      { label: 'Zusatzrente ZukunftStein',    to: '/leistungen/zukunftstein' },
      { label: 'Vergleich beider Produkte',   to: '/leistungen/vergleich' },
    ]},
    { label: 'Service', to: '/service', submenu: [
      { label: 'Service-Übersicht', to: '/service' },
      { label: 'Meldeportal',       to: '/service/meldeportal' },
      { label: 'FAQ / ZVK A–Z',     to: '/service/haeufige-fragen' },
      { label: 'Downloads',         to: '/service/downloads' },
      { label: 'Kontakt',           to: '/service/kontakt' },
    ]},
    { label: 'Über die ZVK', to: '/ueber-uns' },
    { label: 'Kontakt',      to: '/service/kontakt' },
  ];

  // Close menu when clicking outside
  useEffect(() => {
    if (!openMenu) return;
    const onDoc = (e) => {
      if (navRef.current && !navRef.current.contains(e.target)) setOpenMenu(null);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [openMenu]);

  return (
    <div ref={navRef} style={{ borderBottom: `1px solid ${wfColors.line}` }}>
      {/* Zeile 1: Logo + Primärnav */}
      <div style={{
        padding: '14px 28px',
        display: 'flex',
        alignItems: 'center',
        gap: 28,
        borderBottom: `1px solid ${wfColors.line}`
      }}>
        <WFLink to="/" title="Zur Startseite">
          <div style={{
            width: 110,
            height: 28,
            border: `1px dashed ${wfColors.line}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 11,
            color: wfColors.mute,
            fontFamily: 'ui-monospace, Menlo, monospace'
          }}>[ Logo ]</div>
        </WFLink>
        <div style={{ display: 'flex', gap: 26, flex: 1, fontSize: 13 }}>
          {mainItems.map((item) => {
            const isActive = active === item.label;
            const baseStyle = {
              color: isActive ? wfColors.ink : wfColors.mute,
              borderBottom: isActive ? `2px solid ${wfColors.ink}` : 'none',
              paddingBottom: 2,
              fontWeight: isActive ? 700 : 400,
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
            };
            if (!item.submenu) {
              return <WFLink key={item.label} to={item.to} style={baseStyle}>{item.label}</WFLink>;
            }
            const open = openMenu === item.label;
            return (
              <div key={item.label} style={{ position: 'relative' }}>
                <button
                  onClick={(e) => { e.stopPropagation(); setOpenMenu(open ? null : item.label); }}
                  style={{
                    ...baseStyle,
                    font: 'inherit',
                    border: 0,
                    background: 'transparent',
                    padding: 0,
                    paddingBottom: 2,
                    cursor: 'pointer',
                    color: baseStyle.color,
                    fontWeight: baseStyle.fontWeight,
                    borderBottom: baseStyle.borderBottom,
                  }}
                  aria-expanded={open}
                  aria-haspopup="true"
                >
                  {item.label}
                  <span style={{ fontSize: 9, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>▾</span>
                </button>
                {open && (
                  <div style={{
                    position: 'absolute',
                    top: 'calc(100% + 10px)',
                    left: -10,
                    background: wfColors.paper,
                    border: `1px solid ${wfColors.line}`,
                    boxShadow: '0 6px 18px rgba(0,0,0,0.08)',
                    minWidth: 240,
                    padding: '6px 0',
                    zIndex: 20,
                  }}>
                    {item.submenu.map((s) => (
                      <WFLink key={s.to} to={s.to}
                        style={{
                          display: 'block',
                          padding: '10px 16px',
                          fontSize: 12,
                          color: wfColors.ink,
                          fontWeight: 400,
                        }}>
                        {s.label}
                      </WFLink>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
        <div style={{ fontSize: 11, color: wfColors.mute }}>🔍 Suche</div>
      </div>
      {/* Zeile 2: Sekundärnav Zielgruppen */}
      <div style={{
        display: 'flex',
        alignItems: 'stretch',
        padding: '0 28px',
        background: wfColors.fill
      }}>
        <div style={{
          padding: '9px 18px 9px 0',
          fontSize: 11,
          letterSpacing: '.1em',
          textTransform: 'uppercase',
          color: wfColors.mute,
          display: 'flex',
          alignItems: 'center'
        }}>Die ZVK für</div>
        {personas.map((p, idx) => {
          const isActive = p.matches.includes(activePersona) || p.matches.includes(active);
          return (
            <WFLink key={p.label} to={p.to} style={{
              padding: '9px 18px',
              fontSize: 11,
              fontWeight: 700,
              letterSpacing: '.06em',
              color: isActive ? wfColors.ink : wfColors.mute,
              background: isActive ? wfColors.paper : 'transparent',
              borderLeft: idx === 0 ? `1px solid ${wfColors.line}` : 'none',
              borderRight: `1px solid ${wfColors.line}`,
              borderBottom: isActive ? `2px solid ${wfColors.ink}` : 'none',
            }}>{p.label}</WFLink>);
        })}
      </div>
    </div>);
}

// ---------- Nav chrome V2 (zweistufig — analog Bucerius) --------
// Zeile 1: Logo links + Utility rechts (Kontakt, Suche)
// Zeile 2: Zielgruppen-Leiste rechts (dunkle Chips, analog Bucerius-Rot)
// Zeile 3: Haupt-Navigation (Startseite · Unsere Leistungen · Über die ZVK · Service)
function WFNavV2({ active, activePersona }) {
  const personas = ['Betriebe', 'Versicherte', 'Rentner', 'Hinterbliebene'];
  const mainItems = ['Unsere Leistungen', 'Über die ZVK', 'Service'];
  return (
    <div style={{ borderBottom: `1px solid ${wfColors.line}` }}>

      {/* ── Zeile 1: Logo + Utility ── */}
      <div style={{
        padding: '10px 28px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: `1px solid ${wfColors.line}`
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <div style={{
            width: 40,
            height: 40,
            border: `1px dashed ${wfColors.line}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 10,
            color: wfColors.mute,
            fontFamily: 'ui-monospace, Menlo, monospace'
          }}>[ ☰ ]</div>
        </div>
        <div style={{
          width: 110,
          height: 22,
          border: `1px dashed ${wfColors.line}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 10,
          color: wfColors.mute,
          fontFamily: 'ui-monospace, Menlo, monospace'
        }}>[ Logo ]</div>
        <div style={{ flex: 1 }}></div>
        <div style={{ display: 'flex', gap: 20, fontSize: 11, color: wfColors.mute, alignItems: 'center' }}>
          <span>🔍 Suche</span>
          <span style={{
            padding: '5px 14px',
            border: `1px solid ${wfColors.ink}`,
            fontSize: 11,
            fontWeight: 700,
            color: wfColors.ink
          }}>Kontakt</span>
        </div>
      </div>

      {/* ── Zeile 2: Zielgruppen-Chips (analog Bucerius-Leiste) ── */}
      <div style={{
        display: 'flex',
        justifyContent: 'flex-end',
        alignItems: 'stretch',
        padding: '0 28px',
        background: wfColors.fill,
        borderBottom: `1px solid ${wfColors.line}`
      }}>
        <div style={{
          padding: '9px 20px 9px 0',
          fontSize: 11,
          fontWeight: 400,
          letterSpacing: '.1em',
          textTransform: 'uppercase',
          color: wfColors.mute,
          marginRight: 8,
          display: 'flex',
          alignItems: 'center'
        }}>DIE ZVK FÜR</div>
        {personas.map((p, idx) => {
          const isActive = activePersona === p;
          return (
            <div key={p} style={{
              padding: '9px 20px',
              fontSize: 11,
              fontWeight: 700,
              letterSpacing: '.1em',
              textTransform: 'uppercase',
              background: 'transparent',
              color: wfColors.mute,
              borderLeft: idx === 0 ? `1px solid ${wfColors.line}` : 'none',
              borderRight: `1px solid ${wfColors.line}`,
              cursor: 'pointer'
            }}>{p}</div>);

        })}
      </div>

      {/* ── Zeile 3: Haupt-Navigation ── */}
      <div style={{
        padding: '0 28px',
        display: 'flex',
        alignItems: 'stretch',
        gap: 0
      }}>
        {mainItems.map((i) => {
          const isActive = active === i;
          return (
            <div key={i} style={{
              padding: '14px 22px',
              fontSize: 13,
              color: isActive ? wfColors.ink : wfColors.mute,
              fontWeight: isActive ? 700 : 400,
              borderBottom: isActive ? `2px solid ${wfColors.ink}` : '2px solid transparent',
              cursor: 'pointer'
            }}>{i}</div>);

        })}
      </div>
    </div>);

}

// ---------- Module — dashed container with label chip ----------
function WFModule({ label, req, children, tight }) {
  return (
    <div style={{
      border: `1px dashed ${wfColors.line}`,
      margin: '14px 0',
      position: 'relative',
      padding: tight ? 14 : 22
    }}>
      <div style={{
        position: 'absolute',
        top: -10,
        left: 12,
        background: wfColors.paper,
        padding: '0 8px',
        fontSize: 10,
        letterSpacing: '.14em',
        textTransform: 'uppercase',
        color: wfColors.mute,
        fontFamily: 'ui-monospace, Menlo, monospace'
      }}>
        {label}{req && <span style={{ color: '#B89868', marginLeft: 8 }}>{req}</span>}
      </div>
      {children}
    </div>);

}

// ---------- Box — greyscale placeholder block -------------------
function WFBox({ w = '100%', h = 120, label, kind = 'fill', children, style = {} }) {
  const fills = {
    fill: wfColors.fill,
    line: 'transparent',
    dark: wfColors.fillDark
  };
  const isImg = kind === 'image';
  return (
    <div style={{
      width: w,
      height: h,
      background: isImg ? 'transparent' : fills[kind] || wfColors.fill,
      border: `1px solid ${wfColors.line}`,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: 12,
      color: wfColors.mute,
      fontFamily: 'ui-monospace, Menlo, monospace',
      position: 'relative',
      overflow: 'hidden',
      ...style
    }}>
      {isImg &&
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} preserveAspectRatio="none">
          <line x1="0" y1="0" x2="100%" y2="100%" stroke={wfColors.line} strokeWidth="1"></line>
          <line x1="100%" y1="0" x2="0" y2="100%" stroke={wfColors.line} strokeWidth="1"></line>
        </svg>
      }
      {children || label && <span style={{ position: 'relative', zIndex: 1 }}>{label}</span>}
    </div>);

}

// ---------- TextLines — horizontal line placeholders ------------
function WFLines({ count = 3, widths, gap = 8, height = 9 }) {
  const defaults = ['100%', '92%', '78%', '85%', '70%'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap }}>
      {Array.from({ length: count }).map((_, i) =>
      <div key={i} style={{
        height,
        background: wfColors.fill,
        width: widths ? widths[i] || '80%' : defaults[i % defaults.length]
      }}></div>
      )}
    </div>);

}

// ---------- Heading placeholder ---------------------------------
function WFHeading({ level = 1, width = '60%', children }) {
  const heights = { 1: 28, 2: 22, 3: 16 };
  if (children) {
    const sizes = { 1: 28, 2: 22, 3: 18 };
    return <div style={{ fontSize: sizes[level], fontWeight: 700, lineHeight: 1.2, marginBottom: 8 }}>{children}</div>;
  }
  return <div style={{ height: heights[level], background: wfColors.fillDark, width, marginBottom: 10 }}></div>;
}

// ---------- CTA button placeholder ------------------------------
function WFButton({ label = 'CTA', kind = 'primary', w = 160 }) {
  return (
    <div style={{
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '10px 18px',
      minWidth: w,
      border: `1px solid ${wfColors.ink}`,
      background: kind === 'primary' ? wfColors.ink : 'transparent',
      color: kind === 'primary' ? wfColors.paper : wfColors.ink,
      fontSize: 12,
      fontWeight: 700,
      textTransform: 'uppercase',
      letterSpacing: '.06em'
    }}>{label}</div>);

}

// ---------- Annotation -----------------------------------------
function WFAnnot({ children, style = {} }) {
  return (
    <div style={{
      fontSize: 11,
      fontFamily: 'ui-monospace, Menlo, monospace',
      color: wfColors.mute,
      padding: '4px 0',
      ...style
    }}>↪ {children}</div>);

}

// ---------- Req-tag (F-xx, C-xx) -------------------------------
function WFReq({ children }) {
  return (
    <span style={{
      display: 'inline-block',
      padding: '1px 6px',
      border: `1px solid ${wfColors.line}`,
      fontSize: 9,
      letterSpacing: '.1em',
      color: wfColors.mute,
      fontFamily: 'ui-monospace, Menlo, monospace',
      marginLeft: 6,
      verticalAlign: 'middle'
    }}>{children}</span>);

}

// ---------- Footer ----------------------------------------------
function WFFooter() {
  const cols = [
    { h: 'Zielgruppen', items: [
      ['Für Betriebe',       '/fuer-betriebe'],
      ['Für Versicherte',    '/fuer-versicherte'],
      ['Für Rentner',        '/fuer-rentner'],
      ['Für Hinterbliebene', '/fuer-hinterbliebene'],
    ]},
    { h: 'Leistungen', items: [
      ['Betriebliche Rentenbeihilfe', '/leistungen/betriebliche-rentenbeihilfe'],
      ['Zusatzrente ZukunftStein',    '/leistungen/zukunftstein'],
      ['Vergleich',                    '/leistungen/vergleich'],
    ]},
    { h: 'Service', items: [
      ['Meldeportal',           '/service/meldeportal'],
      ['Formulare',             '/service/downloads'],
      ['Häufige Fragen / A–Z',  '/service/haeufige-fragen'],
      ['Downloads',             '/service/downloads'],
      ['Kontakt',               '/service/kontakt'],
    ]},
    { h: 'Über uns', items: [
      ['Team',                  '/ueber-uns'],
      ['Zahlen',                '/ueber-uns'],
      ['Aufsicht',              '/ueber-uns'],
      ['Aktuelles (V1 inaktiv)', null],
      ['Partner (BBW · BIV · IG BAU)', '/ueber-uns'],
    ]},
    { h: 'Rechtliches', items: [
      ['Impressum',         null],
      ['Datenschutz',       null],
      ['AVB',               null],
      ['Barrierefreiheit',  null],
      ['Aufsicht (BaFin)',  null],
    ]},
  ];

  return (
    <div style={{
      background: '#F3F1ED',
      borderTop: `1px solid ${wfColors.line}`,
      padding: '24px 28px 18px',
      display: 'grid',
      gridTemplateColumns: 'repeat(5, 1fr)',
      gap: 24,
      fontSize: 11,
      color: wfColors.mute
    }}>
      {cols.map((c) =>
      <div key={c.h}>
          <div style={{ fontWeight: 700, color: wfColors.ink, marginBottom: 8, fontSize: 11, letterSpacing: '.08em', textTransform: 'uppercase' }}>{c.h}</div>
          {c.items.map(([label, to]) =>
            <div key={label} style={{ lineHeight: 1.9 }}>
              <WFLink to={to}>{label}</WFLink>
            </div>
          )}
        </div>
      )}
    </div>);

}

// ---------- Persona tile pattern --------------------------------
function WFPersonaTile({ title, sub, cta, to, ctaTo }) {
  return (
    <WFLink to={to} style={{ display: 'block' }}>
      <div style={{
        border: `1px solid ${wfColors.line}`,
        padding: 18,
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
        background: wfColors.paper
      }}>
        <WFBox kind="image" h={120} label="Persona-Bild" />
        <div style={{ fontSize: 16, fontWeight: 700 }}>{title}</div>
        <div style={{ fontSize: 11, color: wfColors.mute }}>{sub}</div>
        <WFLines count={2} widths={['100%', '70%']} />
        <div style={{ marginTop: 4, fontSize: 11, textDecoration: 'underline' }}>→ {cta}</div>
      </div>
    </WFLink>);

}

// ---------- Service tile ----------------------------------------
function WFServiceTile({ icon = '▢', title, ext, to }) {
  return (
    <WFLink to={to} style={{ display: 'block' }}>
      <div style={{
        border: `1px solid ${wfColors.line}`,
        padding: 14,
        display: 'flex',
        flexDirection: 'column',
        gap: 6,
        minHeight: 96
      }}>
        <div style={{ fontSize: 18, color: wfColors.mute }}>{icon}{ext && <span style={{ fontSize: 10, marginLeft: 6, fontFamily: 'ui-monospace,Menlo,monospace' }}>↗ extern</span>}</div>
        <div style={{ fontSize: 13, fontWeight: 700, marginTop: 'auto' }}>{title}</div>
      </div>
    </WFLink>);

}

Object.assign(window, {
  wfColors, NAV_ROUTES, WFLink,
  WFFrame, WFNav, WFNavV2, WFModule, WFBox, WFLines, WFHeading, WFButton,
  WFAnnot, WFReq, WFFooter, WFPersonaTile, WFServiceTile
});