function Logo({ color = "var(--ink)" }) {
  const isDark = color === '#fff' || color === 'white';
  const textColor = isDark ? '#fff' : 'var(--ink)';
  const mutedColor = isDark ? 'rgba(255,255,255,0.55)' : 'var(--muted)';
  return (
    <div className="en" style={{ display: 'flex', flexDirection: 'column', gap: 3, direction: 'ltr' }}>
      <div style={{
        fontSize: 22, fontWeight: 800,
        color: textColor,
        letterSpacing: '-0.04em',
        lineHeight: 1,
        whiteSpace: 'nowrap',
      }}>
        Lawyer<span style={{ color: 'var(--turquoise)', fontSize: 20 }}>¶</span>t
      </div>
      <div style={{
        fontSize: 9, fontWeight: 500,
        color: mutedColor,
        letterSpacing: '0.08em',
        textTransform: 'uppercase',
        whiteSpace: 'nowrap',
      }}>
        We've Got You Covered
      </div>
    </div>
  );
}

// Mega-menu: shown on hover over "שירותים"
function ServicesMegaMenu() {
  const TAG_COLORS_LOCAL = {
    blue:   { bg: 'var(--blue-50)',   fg: 'var(--blue-600)' },
    purple: { bg: 'var(--purple-50)', fg: 'var(--purple-600)' },
    orange: { bg: 'var(--orange-50)', fg: 'var(--orange)' },
    green:  { bg: '#ECFDF5',          fg: '#059669' },
  };

  const lang = useLang();
  const cols = lang === 'en'
    ? (typeof SERVICE_COLUMNS_EN !== 'undefined' ? SERVICE_COLUMNS_EN : [])
    : (typeof SERVICE_COLUMNS !== 'undefined' ? SERVICE_COLUMNS : []);

  return (
    <div style={{
      position: 'absolute',
      top: '100%',
      right: 0,
      left: 0,
      background: 'white',
      borderTop: '1px solid var(--border)',
      borderBottom: '1px solid var(--border)',
      boxShadow: '0 16px 48px -8px rgba(0,0,0,0.12)',
      zIndex: 100,
      padding: '32px 0 36px',
    }}>
      <div className="container">
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(6, 1fr)',
          gap: '0 24px',
        }}>
          {cols.map((col, i) => {
            const c = col.color ? TAG_COLORS_LOCAL[col.color] : null;
            return (
              <div key={i} style={{
                paddingTop: 0,
                borderRight: i < cols.length - 1 ? '1px solid var(--border-2)' : 'none',
                paddingInlineEnd: i < cols.length - 1 ? 24 : 0,
              }}>
                {/* Category header */}
                <div style={{ marginBottom: 14 }}>
                  {col.tag && c && (
                    <div className="en" style={{
                      display: 'inline-block',
                      fontSize: 9, fontWeight: 700, letterSpacing: '0.08em',
                      color: c.fg, background: c.bg,
                      padding: '2px 7px', borderRadius: 4,
                      marginBottom: 6,
                    }}>{col.tag}</div>
                  )}
                  {col.href ? (
                    <a href={col.href} style={{
                      display: 'block',
                      fontSize: 13, fontWeight: 700,
                      color: col.highlight ? 'var(--turquoise-700)' : 'var(--ink)',
                      letterSpacing: '-0.01em',
                      lineHeight: 1.3,
                      marginBottom: 4,
                      textDecoration: 'none',
                    }}
                    onMouseEnter={e => e.currentTarget.style.color = 'var(--turquoise-700)'}
                    onMouseLeave={e => e.currentTarget.style.color = col.highlight ? 'var(--turquoise-700)' : 'var(--ink)'}
                    >
                      {col.title}
                      <span style={{ fontSize: 11, marginRight: 4, opacity: 0.7 }}>←</span>
                    </a>
                  ) : (
                    <div style={{
                      fontSize: 13, fontWeight: 700,
                      color: 'var(--ink)',
                      letterSpacing: '-0.01em',
                      lineHeight: 1.3,
                      marginBottom: 4,
                    }}>{col.title}</div>
                  )}
                  <div style={{ display: 'flex', gap: 3 }}>
                    {[0,1,2].map(d => (
                      <div key={d} style={{
                        width: 4, height: 4, borderRadius: '50%',
                        background: col.highlight ? 'var(--turquoise)' : 'var(--orange)',
                        opacity: d === 2 ? 0.35 : 1,
                      }} />
                    ))}
                  </div>
                </div>

                {/* Items */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {col.items.map((item, ii) => (
                    <div key={ii} style={{
                      fontSize: 12.5,
                      color: 'var(--muted)',
                      lineHeight: 1.4,
                      paddingBottom: 6,
                      borderBottom: ii < col.items.length - 1 ? '1px solid var(--border-2)' : 'none',
                    }}>{item}</div>
                  ))}
                  {col.extra && col.extra.items.map((item, ii) => (
                    <div key={'x'+ii} style={{
                      fontSize: 12, color: 'var(--muted-2)', lineHeight: 1.4,
                      fontStyle: 'italic',
                    }}>{item}</div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function Header({ onLangSwitch }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuTimer = React.useRef(null);
  const lang = useLang();

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const openMenu  = () => { clearTimeout(menuTimer.current); setMenuOpen(true); };
  const closeMenu = () => { menuTimer.current = setTimeout(() => setMenuOpen(false), 120); };

  // Detect if we're on the homepage to build correct nav hrefs
  const isHome = /Homepage|index\.html|^\/$/.test(window.location.pathname);
  const toHome = (hash = '') => isHome ? (hash || '#') : ('Lawyerit Homepage.html' + hash);

  const navItems = lang === 'en'
    ? [
        { label: 'How We Work', href: toHome('#how') },
        { label: 'About',       href: toHome('#about') },
        { label: 'Articles',    href: 'insights.html' },
        { label: 'Contact',     href: toHome('#contact') },
      ]
    : [
        { label: 'איך אנחנו עובדים', href: toHome('#how') },
        { label: 'אודות',             href: toHome('#about') },
        { label: 'מאמרים',            href: 'insights.html' },
        { label: 'צור קשר',          href: toHome('#contact') },
      ];

  return (
    <header style={{
      position: 'sticky',
      top: 0,
      zIndex: 50,
      background: scrolled ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.6)',
      backdropFilter: 'saturate(180%) blur(14px)',
      WebkitBackdropFilter: 'saturate(180%) blur(14px)',
      borderBottom: scrolled ? '1px solid var(--border)' : '1px solid transparent',
      transition: 'all 0.25s ease',
    }}>
      <div className="container" style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 72,
      }}>
        <a href={toHome()} style={{ display: 'flex', alignItems: 'center' }}>
          <Logo />
        </a>

        <nav style={{ display: 'flex', alignItems: 'center', gap: 36 }} className="desktop-nav">
          {/* Services with mega-menu */}
          <div
            style={{ position: 'relative' }}
            onMouseEnter={openMenu}
            onMouseLeave={closeMenu}
          >
            <a href="#services" style={{
              fontSize: 15, fontWeight: 400,
              color: menuOpen ? 'var(--turquoise-700)' : 'var(--ink-2)',
              transition: 'color 0.2s',
              display: 'flex', alignItems: 'center', gap: 4,
            }}>
              {lang === 'en' ? 'Services' : 'שירותים'}
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none"
                style={{ transform: menuOpen ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>
                <path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </a>
          </div>

          {/* Other nav items */}
          {navItems.map(i => (
            <a key={i.href} href={i.href} style={{
              fontSize: 15, fontWeight: 400,
              color: 'var(--ink-2)',
              transition: 'color 0.2s',
            }}
            onMouseEnter={e => e.target.style.color = 'var(--turquoise-700)'}
            onMouseLeave={e => e.target.style.color = 'var(--ink-2)'}>
              {i.label}
            </a>
          ))}
        </nav>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {/* Language toggle */}
          {onLangSwitch && (
            <div style={{
              display: 'flex', alignItems: 'center',
              border: '1px solid var(--border)',
              borderRadius: 8, overflow: 'hidden',
              fontSize: 13, fontWeight: 500,
            }}>
              {['he','en'].map((l) => (
                <button key={l} onClick={() => onLangSwitch(l)} style={{
                  padding: '6px 10px',
                  background: lang === l ? 'var(--turquoise)' : 'transparent',
                  color: lang === l ? 'white' : 'var(--muted)',
                  border: 'none', cursor: 'pointer',
                  transition: 'all 0.2s',
                  fontFamily: 'var(--font-en)',
                  letterSpacing: '0.04em',
                }}>
                  {l === 'he' ? 'HE' : 'EN'}
                </button>
              ))}
            </div>
          )}
          <a href="https://www.cal.eu/lawyer-it/30min" target="_blank" rel="noopener noreferrer" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 14 }}>
            {lang === 'en' ? 'Book a Call' : 'שיחת היכרות'}
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M10 4L6 8l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
        </div>
      </div>

      {/* Mega-menu panel */}
      {menuOpen && (
        <div onMouseEnter={openMenu} onMouseLeave={closeMenu}>
          <ServicesMegaMenu />
        </div>
      )}

      <style>{`
        @media (max-width: 900px) {
          .desktop-nav { display: none !important; }
        }
      `}</style>
    </header>
  );
}

Object.assign(window, { Header, Logo });
