<?php
/**
 * Kumo Foundation Theme Header
 * Production-ready version for Kumo Development
 *
 * FIX (mobile nav):
 * - Aligns JS class toggles with your CSS:
 *     .hamburger.active
 *     .main-header .navigation.active
 * - Keeps aria-expanded + aria-hidden in sync
 * - Closes menu on link click + Escape + outside click
 *
 * @package KumoFoundation
 * @version 1.4
 * @since 1.0.0
 */

// Prevent direct file access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>
<!doctype html>
<html <?php language_attributes(); ?> class="no-js">
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">

	<?php if ( is_singular() && pings_open() ) : ?>
		<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
	<?php endif; ?>

	<!-- Font: Inter Tight (optimized loading with font-display) -->
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">

	<?php
	/**
	 * Optional per-site head snippets from Customizer
	 * Sanitized in customizer.php
	 */
	if ( function_exists( 'kumo_foundation_get_head_snippets' ) ) {
		$snippets = kumo_foundation_get_head_snippets();
		if ( ! empty( $snippets ) ) {
			echo $snippets . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
	}

	/**
	 * JSON-LD Schema (ACF Options)
	 * For structured data (SEO)
	 */
	if ( function_exists( 'get_field' ) ) {
		$schema_jsonld = get_field( 'site_schema_jsonld', 'option' );
		if ( ! empty( $schema_jsonld ) ) :
			?>
			<script type="application/ld+json">
				<?php echo $schema_jsonld; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			</script>
		<?php endif;
	}

	wp_head();
	?>
</head>

<body <?php body_class(); ?>>
<?php wp_body_open(); ?>

<!-- Skip to Main Content Link (Accessibility) -->
<a class="skip-link screen-reader-text" href="#main">
	<?php esc_html_e( 'Skip to content', 'kumo-foundation' ); ?>
</a>

<?php
/**
 * ============================================================================
 * CTA DATA
 * ============================================================================
 */
$cta_label   = get_theme_mod( 'cta_label', '' );
$cta_url     = get_theme_mod( 'cta_url', '' );
$cta_new_tab = get_theme_mod( 'cta_new_tab', false );
$cta_target  = $cta_new_tab ? '_blank' : '_self';
$cta_rel     = $cta_new_tab ? 'noopener noreferrer' : '';

if ( ( empty( $cta_label ) || empty( $cta_url ) ) && function_exists( 'get_field' ) ) {
	$link = get_field( 'header_cta', 'option' );
	if ( is_array( $link ) && ! empty( $link ) ) {
		$cta_url    = isset( $link['url'] ) ? $link['url'] : '';
		$cta_label  = isset( $link['title'] ) ? $link['title'] : '';
		$cta_target = isset( $link['target'] ) ? $link['target'] : '_self';
		$cta_rel    = ( '_blank' === $cta_target ) ? 'noopener noreferrer' : '';
	}
}

/**
 * ============================================================================
 * PHONE NUMBER DATA
 * ============================================================================
 */
$hide_call = function_exists( 'get_field' ) ? (int) get_field( 'header_callus_button_hide', 'option' ) : 0;
$phone     = get_theme_mod( 'site_phone', '' );

if ( empty( $phone ) && function_exists( 'get_field' ) ) {
	$phone = get_field( 'header_defaultphone_number', 'option' );
}

$call_text = function_exists( 'get_field' ) ? get_field( 'header_callus_text', 'option' ) : '';
if ( empty( $call_text ) ) {
	$call_text = __( 'Call Us', 'kumo-foundation' );
}

$phone_clean = ! empty( $phone ) ? preg_replace( '/[^0-9+]/', '', (string) $phone ) : '';

/**
 * ============================================================================
 * LOGO DATA
 * ============================================================================
 */
$logo_url  = home_url( '/' );
$site_name = get_bloginfo( 'name' );
$logo_html = '';

if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) {
	$logo_html = get_custom_logo();
} elseif ( function_exists( 'get_field' ) ) {
	$logo_image = get_field( 'logo', 'option' );

	if ( ! empty( $logo_image ) ) {
		$logo_src = is_array( $logo_image ) ? ( $logo_image['url'] ?? '' ) : $logo_image;
		$logo_alt = is_array( $logo_image ) ? ( $logo_image['alt'] ?? $site_name . ' ' . __( 'Logo', 'kumo-foundation' ) ) : $site_name . ' ' . __( 'Logo', 'kumo-foundation' );

		if ( ! empty( $logo_src ) ) {
			$logo_html = sprintf(
				'<img class="kumo-logo" src="%s" alt="%s" width="200" height="48" loading="eager">',
				esc_url( $logo_src ),
				esc_attr( $logo_alt )
			);
		}
	}
}

if ( empty( $logo_html ) ) {
	$logo_html = sprintf( '<span class="site-name">%s</span>', esc_html( $site_name ) );
}

/**
 * ============================================================================
 * NAV IDS (used by JS)
 * ============================================================================
 */
$nav_id        = 'site-navigation';
$toggle_id     = 'kumo-nav-toggle';
?>

<header class="main-header" role="banner" itemscope itemtype="https://schema.org/WPHeader">
	<div class="mh-wrap">
		<div class="container">
			<div class="kumo-headerInner kumo-header-grid">

				<!-- Mobile Hamburger Menu Toggle -->
				<button
					id="<?php echo esc_attr( $toggle_id ); ?>"
					class="hamburger"
					type="button"
					aria-label="<?php esc_attr_e( 'Toggle navigation menu', 'kumo-foundation' ); ?>"
					aria-expanded="false"
					aria-controls="<?php echo esc_attr( $nav_id ); ?>"
				>
					<span></span>
					<span></span>
					<span></span>
				</button>

				<!-- Brand / Logo -->
				<a
					class="brand-logo kumo-brand"
					href="<?php echo esc_url( $logo_url ); ?>"
					aria-label="<?php echo esc_attr( sprintf( __( '%s - Home', 'kumo-foundation' ), $site_name ) ); ?>"
					itemprop="url"
				>
					<?php echo $logo_html; // escaped above ?>
				</a>

				<!-- Primary Navigation -->
				<nav
					class="navigation kumo-nav"
					id="<?php echo esc_attr( $nav_id ); ?>"
					aria-label="<?php esc_attr_e( 'Primary navigation', 'kumo-foundation' ); ?>"
					aria-hidden="true"
					itemscope
					itemtype="https://schema.org/SiteNavigationElement"
				>
					<?php
					if ( has_nav_menu( 'main-menu' ) ) {
						wp_nav_menu( array(
							'theme_location' => 'main-menu',
							'container'      => false,
							'menu_id'        => 'primary-menu',
							'menu_class'     => 'menu kumo-menu',
							'fallback_cb'    => false,
							'depth'          => 2,
							'items_wrap'     => '<ul id="%1$s" class="%2$s" role="menubar">%3$s</ul>',
						) );
					} else {
						echo '<ul id="primary-menu" class="menu kumo-menu" role="menubar">';
						echo '<li><a href="' . esc_url( home_url( '/' ) ) . '">' . esc_html__( 'Home', 'kumo-foundation' ) . '</a></li>';
						echo '<li><a href="' . esc_url( home_url( '/about' ) ) . '">' . esc_html__( 'About', 'kumo-foundation' ) . '</a></li>';
						echo '<li><a href="' . esc_url( home_url( '/services' ) ) . '">' . esc_html__( 'Services', 'kumo-foundation' ) . '</a></li>';
						echo '<li><a href="' . esc_url( home_url( '/contact' ) ) . '">' . esc_html__( 'Contact', 'kumo-foundation' ) . '</a></li>';
						echo '</ul>';
					}
					?>

					<!-- Mobile CTA INSIDE nav (matches your CSS .mob-cta borders/spacing) -->
					<div class="mob-cta">
						<?php if ( ! empty( $cta_label ) && ! empty( $cta_url ) ) : ?>
							<a
								class="header-cta kumo-btn kumo-btnAqua"
								href="<?php echo esc_url( $cta_url ); ?>"
								target="<?php echo esc_attr( $cta_target ); ?>"
								<?php if ( ! empty( $cta_rel ) ) : ?>
									rel="<?php echo esc_attr( $cta_rel ); ?>"
								<?php endif; ?>
							>
								<?php echo esc_html( $cta_label ); ?>
							</a>
						<?php elseif ( 1 !== $hide_call && ! empty( $phone_clean ) ) : ?>
							<a
								class="header-cta kumo-btn kumo-btnAqua"
								href="tel:<?php echo esc_attr( $phone_clean ); ?>"
								aria-label="<?php echo esc_attr( sprintf( __( 'Call us at %s', 'kumo-foundation' ), $phone ) ); ?>"
							>
								<?php echo esc_html( $call_text ); ?>
							</a>
						<?php endif; ?>
					</div>
				</nav>

				<!-- Desktop CTA or Phone -->
				<div class="kumo-headerCta">
					<?php if ( ! empty( $cta_label ) && ! empty( $cta_url ) ) : ?>
						<a
							class="header-cta kumo-btn kumo-btnAqua"
							href="<?php echo esc_url( $cta_url ); ?>"
							target="<?php echo esc_attr( $cta_target ); ?>"
							<?php if ( ! empty( $cta_rel ) ) : ?>
								rel="<?php echo esc_attr( $cta_rel ); ?>"
							<?php endif; ?>
						>
							<?php echo esc_html( $cta_label ); ?>
						</a>
					<?php elseif ( 1 !== $hide_call && ! empty( $phone_clean ) ) : ?>
						<div class="mobile-phone-number" itemprop="contactPoint" itemscope itemtype="https://schema.org/ContactPoint">
							<meta itemprop="contactType" content="customer service">
							<a
								href="tel:<?php echo esc_attr( $phone_clean ); ?>"
								itemprop="telephone"
								aria-label="<?php echo esc_attr( sprintf( __( 'Call us at %s', 'kumo-foundation' ), $phone ) ); ?>"
							>
								<?php if ( ! empty( $call_text ) ) : ?>
									<span class="call-label"><?php echo esc_html( $call_text ); ?></span>
								<?php endif; ?>
								<span class="phonecall">
									<i class="icon-Phone_light" aria-hidden="true"></i>
									<?php echo esc_html( $phone ); ?>
								</span>
							</a>
						</div>
					<?php endif; ?>
				</div>

			</div><!-- .kumo-headerInner -->
		</div><!-- .container -->
	</div><!-- .mh-wrap -->
</header>

<script>
(function () {
  var toggle = document.getElementById('<?php echo esc_js( $toggle_id ); ?>');
  var nav = document.getElementById('<?php echo esc_js( $nav_id ); ?>');
  if (!toggle || !nav) return;

  function isOpen() {
    return nav.classList.contains('active');
  }

  function openNav() {
    toggle.classList.add('active');     // matches your CSS: .hamburger.active
    nav.classList.add('active');        // matches your CSS: .navigation.active
    toggle.setAttribute('aria-expanded', 'true');
    nav.setAttribute('aria-hidden', 'false');
  }

  function closeNav() {
    toggle.classList.remove('active');
    nav.classList.remove('active');
    toggle.setAttribute('aria-expanded', 'false');
    nav.setAttribute('aria-hidden', 'true');
  }

  toggle.addEventListener('click', function (e) {
    e.preventDefault();
    if (isOpen()) closeNav();
    else openNav();
  });

  // Close on Escape
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && isOpen()) closeNav();
  });

  // Close when a nav link is clicked (mobile UX)
  nav.addEventListener('click', function (e) {
    var t = e.target;
    if (!t) return;
    if (t.tagName && t.tagName.toLowerCase() === 'a' && isOpen()) closeNav();
  });

  // Close if user taps outside nav when open
  document.addEventListener('click', function (e) {
    if (!isOpen()) return;
    var target = e.target;
    if (!target) return;
    if (nav.contains(target) || toggle.contains(target)) return;
    closeNav();
  });

  // Safety: if viewport grows to desktop, ensure nav is not stuck "open"
  window.addEventListener('resize', function () {
    if (window.innerWidth >= 992 && isOpen()) closeNav();
  });
})();
</script>

<div id="wrapper">
	<main id="main" class="site-main" role="main" itemprop="mainContentOfPage">
