<?php

function fjord_clone_enqueue_assets() {
  $style_path = get_stylesheet_directory() . '/style.css';
  $style_version = file_exists($style_path) ? (string) filemtime($style_path) : '1.0';

  wp_enqueue_style(
    'fjord-clone-fonts',
    'https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap',
    [],
    null
  );
  wp_enqueue_style('fjord-clone-style', get_stylesheet_uri(), [], $style_version);
  fjord_clone_add_global_color_styles();
}

add_action('wp_enqueue_scripts', 'fjord_clone_enqueue_assets');
add_action('wp_enqueue_scripts', 'fjord_clone_enqueue_blog_scroll_script');

function fjord_clone_add_global_color_styles() {
  $page_background = get_theme_mod('fjord_page_background_color', '#ffffff');

  $page_background = sanitize_hex_color($page_background) ?: '#ffffff';

  $custom_css = sprintf(
    ':root{--fjord-page-background:%1$s;}',
    esc_html($page_background)
  );

  wp_add_inline_style('fjord-clone-style', $custom_css);
}

function fjord_clone_enqueue_blog_scroll_script() {
  if (!is_page_template('page-blog.php')) {
    return;
  }
  $script_path = __DIR__ . '/js/blog-scroll.js';
  $version = file_exists($script_path) ? filemtime($script_path) : null;
  wp_enqueue_script(
    'fjord-clone-blog-scroll',
    get_template_directory_uri() . '/js/blog-scroll.js',
    [],
    $version,
    true
  );
  wp_localize_script('fjord-clone-blog-scroll', 'fjordBlogScroll', [
    'ajax_url' => admin_url('admin-ajax.php'),
  ]);
}
add_filter('wpcf7_autop_or_not', '__return_false');

function fjord_clone_setup() {
  register_nav_menus([
    'primary' => __('Primary Menu', 'fjord-clone'),
    'footer_pages' => __('Footer Pages Menu', 'fjord-clone'),
    'footer_shop' => __('Footer Shop Menu', 'fjord-clone'),
    'footer_customer' => __('Footer Customer Service Menu', 'fjord-clone'),
  ]);

  add_theme_support('woocommerce');
  add_theme_support('custom-logo');
  add_theme_support('title-tag');
}

add_action('after_setup_theme', 'fjord_clone_setup');
add_action('customize_register', 'fjord_clone_customize_register');
add_filter('customize_return_url', 'fjord_clone_customize_return_url');
add_action('after_switch_theme', 'fjord_clone_after_switch_theme');
add_action('admin_init', 'fjord_clone_set_wc_visibility');
add_action('admin_init', 'fjord_clone_ensure_default_checkout_page');
add_action('admin_init', 'fjord_clone_seed_cf7_forms');

function fjord_clone_customize_return_url() {
  return admin_url('themes.php');
}

function fjord_clone_customize_register($wp_customize) {
  $wp_customize->add_section('fjord_header', [
    'title' => __('Header', 'fjord-clone'),
    'priority' => 29,
  ]);

  $wp_customize->add_setting('fjord_header_logo_image', [
    'sanitize_callback' => 'fjord_clone_sanitize_image',
  ]);
  $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'fjord_header_logo_image', [
    'label' => __('Header logo', 'fjord-clone'),
    'section' => 'fjord_header',
  ]));

  $wp_customize->add_setting('fjord_header_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $header_menu_choices = ['' => __('Primary menu', 'fjord-clone')];
  foreach (wp_get_nav_menus() as $menu) {
    $header_menu_choices[$menu->term_id] = $menu->name;
  }
  $wp_customize->add_control('fjord_header_menu', [
    'label' => __('Header menu', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'select',
    'choices' => $header_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_mobile_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $mobile_menu_choices = ['' => __('Use header menu', 'fjord-clone')];
  foreach (wp_get_nav_menus() as $menu) {
    $mobile_menu_choices[$menu->term_id] = $menu->name;
  }
  $wp_customize->add_control('fjord_mobile_menu', [
    'label' => __('Mobile menu', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'select',
    'choices' => $mobile_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_cart_label', [
    'default' => 'Cart',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_cart_label', [
    'label' => __('Cart label', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_topbar_enabled', [
    'default' => 1,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_topbar_enabled', [
    'label' => __('Show topbar on home', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'checkbox',
  ]);

  $wp_customize->add_setting('fjord_topbar_messages', [
    'default' => 'Save 20% on your first order',
    'sanitize_callback' => 'sanitize_textarea_field',
  ]);
  $wp_customize->add_control('fjord_topbar_messages', [
    'label' => __('Topbar messages (separate entries with | )', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'textarea',
  ]);

  $wp_customize->add_setting('fjord_header_background_color', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_header_background_color', [
    'label' => __('Header background color', 'fjord-clone'),
    'section' => 'fjord_header',
  ]));

  $wp_customize->add_setting('fjord_header_search_enabled', [
    'default' => 1,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_header_search_enabled', [
    'label' => __('Mostrar botón de búsqueda', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'checkbox',
  ]);

  $wp_customize->add_setting('fjord_header_search_placeholder', [
    'default' => 'Search...',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_header_search_placeholder', [
    'label' => __('Placeholder del buscador', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_header_logo_width', [
    'default' => 90,
    'sanitize_callback' => 'fjord_clone_sanitize_positive_integer',
  ]);
  $wp_customize->add_control('fjord_header_logo_width', [
    'label' => __('Header logo width (px)', 'fjord-clone'),
    'section' => 'fjord_header',
    'type' => 'number',
    'input_attrs' => [
      'min' => 40,
      'max' => 400,
      'step' => 1,
    ],
  ]);

  $wp_customize->add_section('fjord_global_colors', [
    'title' => __('Colores de la web', 'fjord-clone'),
    'description' => __('Colores base para todas las paginas. Los colores configurados dentro de un bloque individual tienen prioridad.', 'fjord-clone'),
    'priority' => 30,
  ]);

  $wp_customize->add_setting('fjord_page_background_color', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_page_background_color', [
    'label' => __('Color de fondo de las paginas', 'fjord-clone'),
    'section' => 'fjord_global_colors',
  ]));

  $wp_customize->add_section('fjord_footer', [
    'title' => __('Footer', 'fjord-clone'),
    'priority' => 31,
  ]);

  $wp_customize->add_setting('fjord_footer_logo_text', [
    'default' => 'Estudio Páchel',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_logo_text', [
    'label' => __('Footer Logo Text', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_logo_image_enabled', [
    'default' => 0,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_footer_logo_image_enabled', [
    'label' => __('Mostrar logo de imagen', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'checkbox',
  ]);

  $wp_customize->add_setting('fjord_footer_logo_image', [
    'sanitize_callback' => 'fjord_clone_sanitize_image',
  ]);
  $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'fjord_footer_logo_image', [
    'label' => __('Footer logo image', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_logo_image_width', [
    'default' => 150,
    'sanitize_callback' => 'fjord_clone_sanitize_positive_integer',
  ]);
  $wp_customize->add_control('fjord_footer_logo_image_width', [
    'label' => __('Footer logo image width (px)', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'number',
    'input_attrs' => [
      'min' => 40,
      'max' => 400,
      'step' => 1,
    ],
  ]);

  $wp_customize->add_setting('fjord_footer_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $footer_menu_choices = ['' => __('Primary menu', 'fjord-clone')];
  foreach (wp_get_nav_menus() as $menu) {
    $footer_menu_choices[$menu->term_id] = $menu->name;
  }
  $wp_customize->add_control('fjord_footer_menu', [
    'label' => __('Footer menu', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'select',
    'choices' => $footer_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_footer_pages_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $wp_customize->add_control('fjord_footer_pages_menu', [
    'label' => __('Pages column menu', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'select',
    'choices' => $footer_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_footer_shop_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $wp_customize->add_control('fjord_footer_shop_menu', [
    'label' => __('Shop column menu', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'select',
    'choices' => $footer_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_footer_customer_menu', [
    'sanitize_callback' => 'absint',
  ]);
  $wp_customize->add_control('fjord_footer_customer_menu', [
    'label' => __('Customer Service column menu', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'select',
    'choices' => $footer_menu_choices,
  ]);

  $wp_customize->add_setting('fjord_footer_meta_text', [
    'default' => 'Web diseñada por Estudio Páchel',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_meta_text', [
    'label' => __('Footer Meta Text', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_meta_link', [
    'default' => 'https://estudiopachel.com',
    'sanitize_callback' => 'esc_url_raw',
  ]);
  $wp_customize->add_control('fjord_footer_meta_link', [
    'label' => __('Footer Meta Link (URL)', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'url',
  ]);

  $wp_customize->add_setting('fjord_footer_pages_section_title', [
    'default' => 'Pages',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_pages_section_title', [
    'label' => __('Pages column title', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_shop_section_title', [
    'default' => 'Shop',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_shop_section_title', [
    'label' => __('Shop column title', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_customer_section_title', [
    'default' => 'Customer Service',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_customer_section_title', [
    'label' => __('Customer Services column title', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_newsletter_title', [
    'default' => 'Join our newsletter and get 20% off your first purchase',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_newsletter_title', [
    'label' => __('Newsletter Title', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_brand_description', [
    'default' => 'Scandinavian furniture, meticulously handcrafted to bring warmth and elegance into your home.',
    'sanitize_callback' => 'sanitize_textarea_field',
  ]);
  $wp_customize->add_control('fjord_footer_brand_description', [
    'label' => __('Footer brand description', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'textarea',
  ]);

  $wp_customize->add_setting('fjord_footer_brand_background_color', [
    'default' => '#0f1012',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_brand_background_color', [
    'label' => __('Footer brand background color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_brand_text_color', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_brand_text_color', [
    'label' => __('Footer brand text color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_newsletter_background_color', [
    'default' => '#121314',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_newsletter_background_color', [
    'label' => __('Footer newsletter background color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_newsletter_text_color', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_newsletter_text_color', [
    'label' => __('Footer newsletter text color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_text_color', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_text_color', [
    'label' => __('Footer text color (links, meta, description)', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_newsletter_button_text', [
    'default' => 'Subscribe',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_newsletter_button_text', [
    'label' => __('Newsletter button text', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_newsletter_button_background', [
    'default' => '#ffffff',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_newsletter_button_background', [
    'label' => __('Newsletter button background', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_newsletter_button_text_color', [
    'default' => '#0e1011',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_newsletter_button_text_color', [
    'label' => __('Newsletter button text color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_setting('fjord_footer_newsletter_shortcode', [
    'default' => '[contact-form-7 id="3b78303" title="Newsletter"]',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_footer_newsletter_shortcode', [
    'label' => __('Newsletter Form Shortcode', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_footer_newsletter_enabled', [
    'default' => 1,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_footer_newsletter_enabled', [
    'label' => __('Mostrar bloque newsletter del footer', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'checkbox',
  ]);

  $wp_customize->add_setting('fjord_footer_newsletter_form_enabled', [
    'default' => 1,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_footer_newsletter_form_enabled', [
    'label' => __('Mostrar formulario', 'fjord-clone'),
    'section' => 'fjord_footer',
    'type' => 'checkbox',
  ]);

  $wp_customize->add_setting('fjord_footer_background_color', [
    'default' => '#f6f6f6',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_footer_background_color', [
    'label' => __('Footer background color', 'fjord-clone'),
    'section' => 'fjord_footer',
  ]));

  $wp_customize->add_section('fjord_blog', [
    'title' => __('Blog Page', 'fjord-clone'),
    'priority' => 33,
  ]);

  $wp_customize->add_setting('fjord_blog_title', [
    'default' => 'Blog',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_blog_title', [
    'label' => __('Blog page title', 'fjord-clone'),
    'section' => 'fjord_blog',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_blog_lead', [
    'default' => 'Explore photography tips, behind-the-scenes insights, and creative inspiration from my projects and personal work.',
    'sanitize_callback' => 'sanitize_textarea_field',
  ]);
  $wp_customize->add_control('fjord_blog_lead', [
    'label' => __('Blog lead text', 'fjord-clone'),
    'section' => 'fjord_blog',
    'type' => 'textarea',
  ]);
  $wp_customize->add_setting('fjord_blog_background_color', [
    'default' => '#f6f6f6',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_blog_background_color', [
    'label' => __('Blog intro background color', 'fjord-clone'),
    'section' => 'fjord_blog',
  ]));
  $wp_customize->add_setting('fjord_blog_text_color', [
    'default' => '#0e1011',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_blog_text_color', [
    'label' => __('Blog intro text color', 'fjord-clone'),
    'section' => 'fjord_blog',
  ]));
  $wp_customize->add_setting('fjord_blog_paragraph_color', [
    'default' => '#0e1011',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  $wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'fjord_blog_paragraph_color', [
    'label' => __('Blog lead paragraph color', 'fjord-clone'),
    'section' => 'fjord_blog',
  ]));

  $wp_customize->add_section('fjord_shop', [
    'title' => __('Shop Page', 'fjord-clone'),
    'priority' => 34,
  ]);

  $wp_customize->add_setting('fjord_shop_title', [
    'default' => 'Shop',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_shop_title', [
    'label' => __('Shop page title', 'fjord-clone'),
    'section' => 'fjord_shop',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_shop_lead', [
    'default' => 'Explore our Dark Collection, where deep hues and refined finishes bring an air of sophistication and drama to any room.',
    'sanitize_callback' => 'sanitize_textarea_field',
  ]);
  $wp_customize->add_control('fjord_shop_lead', [
    'label' => __('Shop lead text', 'fjord-clone'),
    'section' => 'fjord_shop',
    'type' => 'textarea',
  ]);

  $wp_customize->add_section('fjord_moving_bar', [
    'title' => __('Barra movimiento', 'fjord-clone'),
    'panel' => 'woocommerce',
    'priority' => 120,
  ]);

  $wp_customize->add_setting('fjord_global_shipping_bar_enabled', [
    'default' => 0,
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  $wp_customize->add_control('fjord_global_shipping_bar_enabled', [
    'label' => __('Usar texto global en productos', 'fjord-clone'),
    'description' => __('Si un producto tiene textos propios en Avanzado, esos textos tienen prioridad.', 'fjord-clone'),
    'section' => 'fjord_moving_bar',
    'type' => 'checkbox',
  ]);

  $shipping_icon_choices = fjord_clone_shipping_icon_choices();
  $default_global_shipping_items = [
    ['icon' => 'truck', 'text' => __('Envío gratis desde 500 €', 'fjord-clone')],
    ['icon' => 'globe', 'text' => __('Envío a todo el mundo', 'fjord-clone')],
    ['icon' => 'shield', 'text' => __('Devoluciones sin costo', 'fjord-clone')],
    ['icon' => 'package', 'text' => __('Entregas rápidas', 'fjord-clone')],
  ];
  foreach ($default_global_shipping_items as $index => $default_global_shipping_item) {
    $item_number = $index + 1;
    $wp_customize->add_setting("fjord_global_shipping_bar_icon_{$item_number}", [
      'default' => $default_global_shipping_item['icon'],
      'sanitize_callback' => 'sanitize_key',
    ]);
    $wp_customize->add_control("fjord_global_shipping_bar_icon_{$item_number}", [
      'label' => sprintf(__('Icono barra %d', 'fjord-clone'), $item_number),
      'section' => 'fjord_moving_bar',
      'type' => 'select',
      'choices' => $shipping_icon_choices,
    ]);

    $wp_customize->add_setting("fjord_global_shipping_bar_text_{$item_number}", [
      'default' => $default_global_shipping_item['text'],
      'sanitize_callback' => 'sanitize_text_field',
    ]);
    $wp_customize->add_control("fjord_global_shipping_bar_text_{$item_number}", [
      'label' => sprintf(__('Texto barra %d', 'fjord-clone'), $item_number),
      'section' => 'fjord_moving_bar',
      'type' => 'text',
    ]);
  }

  $wp_customize->add_section('fjord_contact', [
    'title' => __('Contact Page', 'fjord-clone'),
    'priority' => 32,
  ]);

  $wp_customize->add_setting('fjord_contact_title', [
    'default' => "Let's Talk",
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_contact_title', [
    'label' => __('Contact Title', 'fjord-clone'),
    'section' => 'fjord_contact',
    'type' => 'text',
  ]);

  $wp_customize->add_setting('fjord_contact_form_shortcode', [
    'default' => '',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  $wp_customize->add_control('fjord_contact_form_shortcode', [
    'label' => __('Contact Form Shortcode', 'fjord-clone'),
    'section' => 'fjord_contact',
    'type' => 'text',
  ]);
}

function fjord_clone_after_switch_theme() {
  update_option('fjord_wc_visibility_set', 'no');
  update_option('fjord_checkout_default_set', 'no');
  fjord_clone_remove_demo_categories();
}

function fjord_clone_ensure_default_checkout_page() {
  if (get_option('fjord_checkout_default_set') === 'yes') {
    return;
  }
  if (!class_exists('WooCommerce')) {
    return;
  }

  $checkout_id = (int) get_option('woocommerce_checkout_page_id');
  if (!$checkout_id && function_exists('wc_create_page')) {
    $created_id = wc_create_page('checkout', 'woocommerce_checkout_page_id', __('Checkout', 'woocommerce'));
    if (!is_wp_error($created_id)) {
      $checkout_id = (int) $created_id;
    }
  }

  if ($checkout_id > 0) {
    $checkout_post = get_post($checkout_id);
    if ($checkout_post && $checkout_post->post_type === 'page') {
      $content = (string) $checkout_post->post_content;
      if (strpos($content, '[woocommerce_checkout]') === false) {
        wp_update_post([
          'ID' => $checkout_id,
          'post_content' => '[woocommerce_checkout]',
        ]);
      }
    }
  }

  update_option('fjord_checkout_default_set', 'yes');
}

function fjord_clone_set_wc_visibility() {
  if (!class_exists('WooCommerce')) {
    return;
  }
  if (get_option('fjord_wc_visibility_set') === 'yes') {
    return;
  }
  update_option('woocommerce_coming_soon', 'no');
  update_option('woocommerce_coming_soon_type', 'live');
  update_option('fjord_wc_visibility_set', 'yes');
}

function fjord_clone_seed_cf7_forms() {
  if (!class_exists('WPCF7_ContactForm')) {
    return;
  }
  if (get_option('fjord_cf7_seeded') === 'yes') {
    return;
  }

  $contact_title = 'Formulario de contacto 1';
  $newsletter_title = 'Newsletter';
  $site_host = wp_parse_url(home_url(), PHP_URL_HOST);
  $sender = '[your-site-name] <wordpress@' . $site_host . '>';

  $contact_form = get_page_by_title($contact_title, OBJECT, 'wpcf7_contact_form');
  $contact_id = $contact_form ? (int) $contact_form->ID : 0;
  if (!$contact_id) {
    $contact_id = wp_insert_post([
      'post_title' => $contact_title,
      'post_status' => 'publish',
      'post_type' => 'wpcf7_contact_form',
    ]);
  }
  if ($contact_id && !is_wp_error($contact_id)) {
    $contact_form_markup = "<div class=\"fjord-contact__row\">\n  [text* full-name class:fjord-contact__input placeholder \"Your Name\"]\n  [email* email class:fjord-contact__input placeholder \"Your Email\"]\n</div>\n[textarea* message class:fjord-contact__input class:fjord-contact__textarea placeholder \"Your Message\"]\n[submit class:fjord-contact__submit \"Enviar\"]\n";
    wp_update_post([
      'ID' => $contact_id,
      'post_content' => $contact_form_markup,
    ]);
    update_post_meta($contact_id, '_form', $contact_form_markup);
    update_post_meta($contact_id, '_mail', [
      'subject' => '[your-site-name] Contacto',
      'sender' => $sender,
      'body' => "Nombre: [full-name]\nEmail: [email]\nMensaje:\n[message]\n",
      'recipient' => get_option('admin_email'),
      'additional_headers' => "Reply-To: [email]\n",
      'attachments' => '',
      'use_html' => false,
      'exclude_blank' => false,
    ]);
  }

  $newsletter_form = get_page_by_title($newsletter_title, OBJECT, 'wpcf7_contact_form');
  $newsletter_id = $newsletter_form ? (int) $newsletter_form->ID : 0;
  if (!$newsletter_id) {
    $newsletter_id = wp_insert_post([
      'post_title' => $newsletter_title,
      'post_status' => 'publish',
      'post_type' => 'wpcf7_contact_form',
    ]);
  }
  if ($newsletter_id && !is_wp_error($newsletter_id)) {
    $newsletter_markup = "[email* newsletter-email class:fjord-footer__input placeholder \"name@email.com\"]\n[submit class:fjord-footer__submit \"Subscribe\"]\n";
    wp_update_post([
      'ID' => $newsletter_id,
      'post_content' => $newsletter_markup,
    ]);
    update_post_meta($newsletter_id, '_form', $newsletter_markup);
    update_post_meta($newsletter_id, '_mail', [
      'subject' => '[your-site-name] Newsletter',
      'sender' => $sender,
      'body' => "Email: [newsletter-email]\n",
      'recipient' => get_option('admin_email'),
      'additional_headers' => "Reply-To: [newsletter-email]\n",
      'attachments' => '',
      'use_html' => false,
      'exclude_blank' => false,
    ]);
    set_theme_mod('fjord_footer_newsletter_shortcode', '[contact-form-7 id="' . $newsletter_id . '" title="' . $newsletter_title . '"]');
  }

  update_option('fjord_cf7_seeded', 'yes');
}

function fjord_clone_seed_pages_and_menu() {
  if (get_option('fjord_content_seeded') === 'yes') {
    return;
  }

  $pages = [
    'home' => [
      'title' => 'Home',
      'slug' => 'home',
      'template' => '',
    ],
    'collections' => [
      'title' => 'Collections',
      'slug' => 'collections',
      'template' => '',
    ],
    'about' => [
      'title' => 'About',
      'slug' => 'about',
      'template' => 'page-about.php',
    ],
    'blog' => [
      'title' => 'Blog',
      'slug' => 'blog',
      'template' => 'page-blog.php',
    ],
    'contacto' => [
      'title' => 'Contacto',
      'slug' => 'contacto',
      'template' => 'page-contacto.php',
    ],
    'faq' => [
      'title' => 'FAQ',
      'slug' => 'faq',
      'template' => 'page-faq.php',
    ],
    'carrito' => [
      'title' => 'Carrito',
      'slug' => 'carrito',
      'template' => 'page-carrito.php',
    ],
  ];

  $page_ids = [];
  foreach ($pages as $key => $page) {
    $existing = get_page_by_title($page['title']);
    if ($existing) {
      $page_ids[$key] = $existing->ID;
      continue;
    }

    $page_id = wp_insert_post([
      'post_title' => $page['title'],
      'post_name' => $page['slug'],
      'post_status' => 'publish',
      'post_type' => 'page',
    ]);

    if ($page_id && !is_wp_error($page_id)) {
      if (!empty($page['template'])) {
        update_post_meta($page_id, '_wp_page_template', $page['template']);
      }
      $page_ids[$key] = $page_id;
    }
  }

  if (function_exists('wc_create_page')) {
    $shop_id = wc_create_page('shop', 'woocommerce_shop_page_id', __('Shop', 'woocommerce'));
    $cart_id = wc_create_page('cart', 'woocommerce_cart_page_id', __('Cart', 'woocommerce'));
    $checkout_id = wc_create_page('checkout', 'woocommerce_checkout_page_id', __('Checkout', 'woocommerce'));
    $account_id = wc_create_page('my-account', 'woocommerce_myaccount_page_id', __('My account', 'woocommerce'));
    if ($shop_id) {
      $page_ids['shop'] = $shop_id;
    }
    if ($cart_id) {
      $page_ids['cart'] = $cart_id;
    }
    if ($checkout_id) {
      $page_ids['checkout'] = $checkout_id;
    }
    if ($account_id) {
      $page_ids['account'] = $account_id;
    }

    if ($checkout_id) {
      wp_update_post([
        'ID' => $checkout_id,
        'post_content' => '[woocommerce_checkout]',
      ]);
    }
  }

  if (!empty($page_ids['home'])) {
    update_option('show_on_front', 'page');
    update_option('page_on_front', (int) $page_ids['home']);
  }
  if (!empty($page_ids['blog'])) {
    update_option('page_for_posts', (int) $page_ids['blog']);
  }

  $menu_name = 'Primary';
  $menu = wp_get_nav_menu_object($menu_name);
  if (!$menu) {
    $menu_id = wp_create_nav_menu($menu_name);
  } else {
    $menu_id = (int) $menu->term_id;
  }

  if ($menu_id) {
    $existing_items = wp_get_nav_menu_items($menu_id);
    if (!empty($existing_items)) {
      foreach ($existing_items as $existing_item) {
        wp_delete_post((int) $existing_item->ID, true);
      }
    }

    $menu_items = [
      ['label' => 'Home', 'page_key' => 'home'],
      ['label' => 'Tienda', 'page_key' => 'shop'],
      ['label' => 'Blog', 'page_key' => 'blog'],
      ['label' => 'About', 'page_key' => 'about'],
      ['label' => 'Contacto', 'page_key' => 'contacto'],
    ];

    foreach ($menu_items as $item) {
      $page_id = isset($page_ids[$item['page_key']]) ? (int) $page_ids[$item['page_key']] : 0;
      $url = $page_id ? get_permalink($page_id) : home_url('/');
      wp_update_nav_menu_item($menu_id, 0, [
        'menu-item-title' => $item['label'],
        'menu-item-url' => $url,
        'menu-item-status' => 'publish',
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type',
        'menu-item-object-id' => $page_id,
      ]);
    }

    $locations = get_theme_mod('nav_menu_locations', []);
    $locations['primary'] = $menu_id;
    set_theme_mod('nav_menu_locations', $locations);
  }

  update_option('fjord_content_seeded', 'yes');
}

add_action('admin_menu', 'fjord_clone_register_plugins_page');
add_action('admin_notices', 'fjord_clone_plugins_admin_notice');
add_action('admin_init', 'fjord_clone_maybe_dismiss_plugins_notice');

function fjord_clone_required_plugins() {
  return [
    [
      'name' => 'Contact Form 7',
      'slug' => 'contact-form-7',
      'file' => 'contact-form-7/wp-contact-form-7.php',
      'required' => true,
    ],
    [
      'name' => 'Flamingo',
      'slug' => 'flamingo',
      'file' => 'flamingo/flamingo.php',
      'required' => true,
    ],
    [
      'name' => 'WooCommerce',
      'slug' => 'woocommerce',
      'file' => 'woocommerce/woocommerce.php',
      'required' => true,
    ],
  ];
}

function fjord_clone_register_plugins_page() {
  add_submenu_page(
    'themes.php',
    __('Theme Setup', 'fjord-clone'),
    __('Theme Setup', 'fjord-clone'),
    'manage_options',
    'fjord-theme-setup',
    'fjord_clone_plugins_page'
  );
}

function fjord_clone_plugins_admin_notice() {
  if (!current_user_can('install_plugins')) {
    return;
  }
  $user_id = get_current_user_id();
  if ($user_id && get_user_meta($user_id, 'fjord_clone_plugins_notice_dismissed', true) === 'yes') {
    return;
  }
  $plugins = fjord_clone_required_plugins();
  $missing = [];
  foreach ($plugins as $plugin) {
    $file = $plugin['file'];
    if (!file_exists(WP_PLUGIN_DIR . '/' . $file) || !is_plugin_active($file)) {
      if ($plugin['required']) {
        $missing[] = $plugin['name'];
      }
    }
  }
  if (!$missing) {
    return;
  }
  $url = admin_url('themes.php?page=fjord-theme-setup');
  $dismiss_url = wp_nonce_url(
    add_query_arg(['fjord_dismiss_plugins_notice' => '1']),
    'fjord_dismiss_plugins_notice'
  );
  echo '<div class="notice notice-warning is-dismissible fjord-clone-dismissible-notice" data-dismiss-url="' . esc_url($dismiss_url) . '"><p>';
  echo esc_html__('El tema Zapatería requiere plugins para funcionar correctamente.', 'fjord-clone');
  echo ' <a href="' . esc_url($url) . '">' . esc_html__('Abrir Theme Setup', 'fjord-clone') . '</a>';
  echo '</p></div>';
  echo "<script>
  document.addEventListener('click', function(event) {
    var button = event.target.closest('.fjord-clone-dismissible-notice .notice-dismiss');
    if (!button) {
      return;
    }
    var notice = button.closest('.fjord-clone-dismissible-notice');
    if (!notice) {
      return;
    }
    var dismissUrl = notice.getAttribute('data-dismiss-url');
    if (dismissUrl) {
      window.location.href = dismissUrl;
    }
  });
  </script>";
}

function fjord_clone_maybe_dismiss_plugins_notice() {
  if (!is_admin() || !current_user_can('install_plugins')) {
    return;
  }
  if (empty($_GET['fjord_dismiss_plugins_notice'])) {
    return;
  }
  check_admin_referer('fjord_dismiss_plugins_notice');
  $user_id = get_current_user_id();
  if ($user_id) {
    update_user_meta($user_id, 'fjord_clone_plugins_notice_dismissed', 'yes');
  }
}

function fjord_clone_plugin_action_link($plugin) {
  $file = $plugin['file'];
  $installed = file_exists(WP_PLUGIN_DIR . '/' . $file);
  $active = $installed && is_plugin_active($file);
  if ($active) {
    return '<span>' . esc_html__('Activo', 'fjord-clone') . '</span>';
  }
  if (!$installed) {
    $url = wp_nonce_url(
      self_admin_url('update.php?action=install-plugin&plugin=' . $plugin['slug']),
      'install-plugin_' . $plugin['slug']
    );
    return '<a class="button" href="' . esc_url($url) . '">' . esc_html__('Instalar', 'fjord-clone') . '</a>';
  }
  $url = wp_nonce_url(
    self_admin_url('plugins.php?action=activate&plugin=' . urlencode($file)),
    'activate-plugin_' . $file
  );
  return '<a class="button button-primary" href="' . esc_url($url) . '">' . esc_html__('Activar', 'fjord-clone') . '</a>';
}

function fjord_clone_plugins_page() {
  if (!current_user_can('install_plugins')) {
    return;
  }
  $plugins = fjord_clone_required_plugins();
  echo '<div class="wrap"><h1>' . esc_html__('Theme Setup', 'fjord-clone') . '</h1>';
  echo '<p>' . esc_html__('Instala y activa los plugins necesarios.', 'fjord-clone') . '</p>';
  echo '<table class="widefat striped"><thead><tr><th>' . esc_html__('Plugin', 'fjord-clone') . '</th><th>' . esc_html__('Estado', 'fjord-clone') . '</th></tr></thead><tbody>';
  foreach ($plugins as $plugin) {
    echo '<tr><td>' . esc_html($plugin['name']) . '</td><td>' . fjord_clone_plugin_action_link($plugin) . '</td></tr>';
  }
  echo '</tbody></table></div>';
}

add_filter('ocdi/import_files', 'fjord_clone_import_files');

function fjord_clone_import_files() {
  $base = get_stylesheet_directory() . '/demo-content';
  $content = $base . '/demo-content.xml';
  $widgets = $base . '/widgets.wie';
  $customizer = $base . '/customizer.dat';

  if (!file_exists($content)) {
    return [];
  }

  $files = [
    [
      'import_file_name' => 'Fjord Demo',
      'local_import_file' => $content,
    ],
  ];

  if (file_exists($widgets)) {
    $files[0]['local_import_widget_file'] = $widgets;
  }
  if (file_exists($customizer)) {
    $files[0]['local_import_customizer_file'] = $customizer;
  }

  return $files;
}

add_action('ocdi/after_import', 'fjord_clone_remove_demo_categories');
function fjord_clone_remove_demo_categories() {
  if (!function_exists('get_terms')) {
    return;
  }

  $taxonomies = [
    'category' => (int) get_option('default_category'),
    'product_cat' => (int) get_option('default_product_cat'),
  ];

  foreach ($taxonomies as $taxonomy => $default_term_id) {
    if (!taxonomy_exists($taxonomy)) {
      continue;
    }

    $term_ids = get_terms([
      'taxonomy' => $taxonomy,
      'hide_empty' => false,
      'fields' => 'ids',
    ]);

    if (is_wp_error($term_ids) || !$term_ids) {
      continue;
    }

    foreach ($term_ids as $term_id) {
      if ($default_term_id && (int) $term_id === $default_term_id) {
        continue;
      }
      wp_delete_term((int) $term_id, $taxonomy);
    }
  }
}

add_filter('wpcf7_form_elements', 'fjord_clone_contact_form_submit_text', 20, 2);
function fjord_clone_contact_form_submit_text($content, $form = null) {
  $content = preg_replace_callback(
    '/(<input[^>]+class="[^"]*fjord-contact__submit[^"]*"[^>]+value=")[^"]*(")/i',
    function ($matches) {
      return $matches[1] . 'Enviar' . $matches[2];
    },
    $content
  );
  $content = preg_replace_callback(
    "/(<input[^>]+class='[^']*fjord-contact__submit[^']*'[^>]+value=')[^']*(')/i",
    function ($matches) {
      return $matches[1] . 'Enviar' . $matches[2];
    },
    $content
  );
  return $content;
}

add_action('login_enqueue_scripts', 'fjord_clone_login_branding');
add_filter('login_headerurl', 'fjord_clone_login_header_url');
add_filter('login_headertext', 'fjord_clone_login_header_text');

function fjord_clone_login_branding() {
  $logo_id = get_theme_mod('custom_logo');
  $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'full') : '';
  $logo_css = $logo_url ? "background-image:url('{$logo_url}');" : '';
  ?>
  <style>
    body.login {
      background: #f6f6f6;
      font-family: "DM Sans", Arial, sans-serif;
    }
    #login h1 a {
      <?php echo esc_html($logo_css); ?>
      background-size: contain;
      width: 180px;
      height: 60px;
    }
    .login #backtoblog a,
    .login #nav a {
      color: rgba(14, 16, 17, 0.7);
    }
    .login form {
      border-radius: 12px;
      box-shadow: none;
      border: 1px solid rgba(14, 16, 17, 0.06);
    }
    .login .button-primary {
      background: #0e1011;
      border: none;
      border-radius: 999px;
      text-shadow: none;
      box-shadow: none;
    }
  </style>
  <?php
}

function fjord_clone_login_header_url() {
  return home_url('/');
}

function fjord_clone_login_header_text() {
  return get_bloginfo('name');
}

function fjord_clone_shop_per_page($per_page) {
  return 20;
}

add_filter('loop_shop_per_page', 'fjord_clone_shop_per_page', 20);

function fjord_clone_latest_products_first($query) {
  if (is_admin() || !$query->is_main_query()) {
    return;
  }

  if (function_exists('is_shop') && function_exists('is_product_taxonomy') && (is_shop() || is_product_taxonomy())) {
    $query->set('orderby', 'date');
    $query->set('order', 'DESC');
  }
}

add_action('pre_get_posts', 'fjord_clone_latest_products_first');

function fjord_clone_load_more_products() {
  if (!function_exists('WC')) {
    wp_send_json_error();
  }

  $page = isset($_POST['page']) ? max(1, (int) $_POST['page']) : 1;
  $query_vars = isset($_POST['query_vars']) ? json_decode(wp_unslash($_POST['query_vars']), true) : [];
  if (!is_array($query_vars)) {
    $query_vars = [];
  }

  $query_vars['paged'] = $page;
  $query_vars['posts_per_page'] = 20;
  $query_vars['post_type'] = 'product';

  $product_query = new WP_Query($query_vars);

  ob_start();
  if ($product_query->have_posts()) {
    while ($product_query->have_posts()) {
      $product_query->the_post();
      wc_get_template_part('content', 'product');
    }
  }
  wp_reset_postdata();
  $html = ob_get_clean();

  wp_send_json_success([
    'html' => $html,
    'max' => (int) $product_query->max_num_pages,
  ]);
}

function fjord_clone_blog_card_markup() {
  ob_start();
  ?>
  <article <?php post_class('fjord-blog-card'); ?>>
    <a class="fjord-blog-card__link" href="<?php the_permalink(); ?>">
      <div class="fjord-blog-card__media">
        <?php if (has_post_thumbnail()) : ?>
          <?php the_post_thumbnail('large'); ?>
        <?php else : ?>
          <div class="fjord-blog-card__placeholder"></div>
        <?php endif; ?>
      </div>
      <div class="fjord-blog-card__footer">
        <span class="fjord-blog-card__footer-title"><?php the_title(); ?></span>
        <span class="fjord-blog-card__read"><?php esc_html_e('Leer', 'fjord-clone'); ?></span>
      </div>
    </a>
  </article>
  <?php
  return ob_get_clean();
}

add_action('wp_ajax_fjord_load_more_blog', 'fjord_clone_load_more_blog_posts');
add_action('wp_ajax_nopriv_fjord_load_more_blog', 'fjord_clone_load_more_blog_posts');
function fjord_clone_load_more_blog_posts() {
  $page = max(1, isset($_POST['page']) ? (int) $_POST['page'] : 1);
  $exclude = [];
  if (!empty($_POST['exclude'])) {
    $exclude = array_filter(array_map('absint', explode(',', wp_unslash($_POST['exclude']))));
  }

  $blog_query = new WP_Query([
    'post_type' => 'post',
    'paged' => $page,
    'posts_per_page' => 8,
    'post_status' => 'publish',
    'post__not_in' => $exclude,
  ]);

  if (!$blog_query->have_posts()) {
    wp_send_json_success([
      'html' => '',
      'total' => $blog_query->max_num_pages,
    ]);
  }

  ob_start();
  while ($blog_query->have_posts()) {
    $blog_query->the_post();
    echo fjord_clone_blog_card_markup();
  }
  $html = ob_get_clean();
  wp_reset_postdata();

  wp_send_json_success([
    'html' => $html,
    'total' => $blog_query->max_num_pages,
  ]);
}

function fjord_clone_shipping_icon_choices() {
  return [
    '' => __('Sin icono', 'fjord-clone'),
    'truck' => __('Camión', 'fjord-clone'),
    'globe' => __('Mundo', 'fjord-clone'),
    'shield' => __('Escudo', 'fjord-clone'),
    'package' => __('Caja', 'fjord-clone'),
    'clock' => __('Reloj', 'fjord-clone'),
    'star' => __('Estrella', 'fjord-clone'),
    'tag' => __('Etiqueta', 'fjord-clone'),
    'support' => __('Soporte', 'fjord-clone'),
  ];
}

function fjord_clone_shipping_icon_paths() {
  return [
    'truck' => '<path d="M3 12h12l4 4v4h-4a2 2 0 0 1-4 0H9a2 2 0 0 1-4 0H3v-8Zm2 6a1 1 0 1 0 2 0H5Zm10 0a1 1 0 1 0 2 0h-2ZM15 6h4l2 4h-6V6Z" fill="currentColor"></path>',
    'globe' => '<path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2Zm7.9 9h-3.06a14.7 14.7 0 0 0-1.2-5 8.05 8.05 0 0 1 4.26 5ZM12 4.1A12.9 12.9 0 0 1 13.6 11h-3.2A12.9 12.9 0 0 1 12 4.1ZM4.1 11a8.05 8.05 0 0 1 4.26-5 14.7 14.7 0 0 0-1.2 5ZM9.4 13h5.2A12.9 12.9 0 0 1 12 19.9 12.9 12.9 0 0 1 9.4 13Zm6.34 6a14.7 14.7 0 0 0 1.2-5h3.06a8.05 8.05 0 0 1-4.26 5Zm-11.8-5h3.06a14.7 14.7 0 0 0 1.2 5 8.05 8.05 0 0 1-4.26-5Z" fill="currentColor"></path>',
    'shield' => '<path d="M12 4a8 8 0 1 0 8 8h2A10 10 0 1 1 12 2v2Zm7 8-3 3-3-3h2V8h2v4h2Z" fill="currentColor"></path>',
    'package' => '<path d="M3 7h18v10H3z" fill="currentColor"></path><path d="M12 3.5l9 4V17l-9 4-9-4V7.5z" fill="none" stroke="currentColor" stroke-width="1.2"></path><path d="M12 3.5v17" fill="none" stroke="currentColor" stroke-width="1.2"></path>',
    'clock' => '<circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="1.5" fill="none"></circle><path d="M12 7v5l3 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"></path>',
    'star' => '<path d="M12 3.25 13.78 8.4 19.5 8.93 14.65 12.99 16.18 18.6 12 15.8 7.82 18.6 9.35 12.99 4.5 8.93 10.22 8.4z" fill="currentColor"></path>',
    'tag' => '<path d="M4 6.5a1.5 1.5 0 0 1 1.5-1.5h5.17a1.5 1.5 0 0 1 1.06.44l6.83 6.84a1.5 1.5 0 0 1 0 2.12l-5.5 5.5a1.5 1.5 0 0 1-2.12 0L4.44 9.45A1.5 1.5 0 0 1 4 8.5z" fill="currentColor"></path><circle cx="8" cy="8" r="1.2" fill="currentColor"></circle>',
    'support' => '<path d="M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zm7 16a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm3.5-6.5H8.5V7h7z" fill="currentColor"></path>',
  ];
}
function fjord_clone_get_shipping_icon_svg($key) {
  $paths = fjord_clone_shipping_icon_paths();
  return isset($paths[$key]) ? $paths[$key] : '';
}

function fjord_clone_get_product_shipping_items($product_id) {
  $default_items = [
    [
      'icon' => 'truck',
      'text' => __('Envío gratis desde 500 €', 'fjord-clone'),
    ],
    [
      'icon' => 'globe',
      'text' => __('Envío a todo el mundo', 'fjord-clone'),
    ],
    [
      'icon' => 'shield',
      'text' => __('Devoluciones sin costo', 'fjord-clone'),
    ],
    [
      'icon' => 'package',
      'text' => __('Entregas rápidas', 'fjord-clone'),
    ],
  ];

  $has_product_shipping_text = false;
  foreach (range(1, 4) as $i) {
    $custom_text = get_post_meta($product_id, "_fjord_shipping_text_{$i}", true);
    if (trim((string) $custom_text) !== '') {
      $has_product_shipping_text = true;
      break;
    }
  }

  $global_bar_enabled = (bool) get_theme_mod('fjord_global_shipping_bar_enabled', 0);
  if (!$has_product_shipping_text && $global_bar_enabled) {
    $global_items = [];
    foreach ($default_items as $index => $default) {
      $i = $index + 1;
      $global_icon = get_theme_mod("fjord_global_shipping_bar_icon_{$i}", $default['icon']);
      $global_text = trim(preg_replace('/\s+/', ' ', (string) get_theme_mod("fjord_global_shipping_bar_text_{$i}", $default['text'])));
      if ($global_text === '') {
        continue;
      }
      $global_items[] = [
        'icon' => sanitize_key($global_icon),
        'text' => $global_text,
      ];
    }

    $legacy_global_text = trim(preg_replace('/\s+/', ' ', (string) get_theme_mod('fjord_global_shipping_bar_text', '')));
    if (!$global_items && $legacy_global_text !== '') {
      $global_items[] = [
        'icon' => '',
        'text' => $legacy_global_text,
      ];
    }

    if ($global_items) {
      return $global_items;
    }
  }

  $items = [];
  foreach ($default_items as $index => $default) {
    $i = $index + 1;
    $custom_icon = get_post_meta($product_id, "_fjord_shipping_icon_{$i}", true);
    $custom_text = get_post_meta($product_id, "_fjord_shipping_text_{$i}", true);
    $icon = $custom_icon !== '' ? sanitize_key($custom_icon) : $default['icon'];
    $text = trim($custom_text !== '' ? $custom_text : $default['text']);
    if ($text === '') {
      continue;
    }
    $items[] = [
      'icon' => $icon,
      'text' => $text,
    ];
  }
  return $items;
}

add_action('wp_ajax_fjord_load_more_products', 'fjord_clone_load_more_products');
add_action('wp_ajax_nopriv_fjord_load_more_products', 'fjord_clone_load_more_products');

function fjord_clone_update_cart_item() {
  if (!function_exists('WC')) {
    wp_send_json_error();
  }

  check_ajax_referer('fjord-cart', 'nonce');

  $cart_item_key = isset($_POST['cart_item_key']) ? sanitize_text_field(wp_unslash($_POST['cart_item_key'])) : '';
  $quantity = isset($_POST['quantity']) ? (int) $_POST['quantity'] : 0;

  if (!$cart_item_key) {
    wp_send_json_error();
  }

  if ($quantity <= 0) {
    WC()->cart->remove_cart_item($cart_item_key);
  } else {
    WC()->cart->set_quantity($cart_item_key, $quantity, true);
  }

  WC()->cart->calculate_totals();

  ob_start();
  woocommerce_mini_cart();
  $mini_cart = ob_get_clean();

  wp_send_json_success([
    'fragments' => [
      'div.widget_shopping_cart_content' => $mini_cart,
    ],
    'count' => WC()->cart->get_cart_contents_count(),
  ]);
}

add_action('wp_ajax_fjord_update_cart_item', 'fjord_clone_update_cart_item');
add_action('wp_ajax_nopriv_fjord_update_cart_item', 'fjord_clone_update_cart_item');

function fjord_clone_add_to_cart_redirect($url) {
  $product_id = isset($_REQUEST['add-to-cart']) ? absint($_REQUEST['add-to-cart']) : 0;
  if ($product_id) {
    $url = get_permalink($product_id);
  } else {
    $referer = wp_get_referer();
    if ($referer) {
      $url = $referer;
    }
  }
  $url = $url ? remove_query_arg(['add-to-cart', 'added-to-cart', 'quantity'], $url) : home_url('/');
  return add_query_arg('fjord-cart', '1', $url);
}

add_filter('woocommerce_add_to_cart_redirect', 'fjord_clone_add_to_cart_redirect');

function fjord_clone_render_favorites_carousel() {
  ob_start();
  ?>
  <div class="fjord-carousel" data-carousel>
    <button class="fjord-carousel__control fjord-carousel__control--prev" type="button" aria-label="Previous">
      <img src="https://framerusercontent.com/images/6tTbkXggWgQCAJ4DO2QEdXXmgM.svg" alt="">
    </button>
    <div class="fjord-carousel__track">
      <?php
      $favorite_products = [];
      if (function_exists('wc_get_products')) {
        $favorite_products = wc_get_products([
          'status' => 'publish',
          'featured' => true,
          'limit' => 12,
        ]);
        if (!$favorite_products) {
          $favorite_products = wc_get_products([
            'status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC',
            'limit' => 12,
          ]);
        }
      }
      ?>
      <?php if ($favorite_products) : ?>
        <?php foreach ($favorite_products as $product) : ?>
          <?php
          $product_id = $product->get_id();
          $product_name = $product->get_name();
          $discount_percent = null;
          if ($product->is_on_sale()) {
            $regular_price = (float) $product->get_regular_price();
            $sale_price = (float) $product->get_sale_price();
            if ($regular_price > 0 && $sale_price > 0 && $sale_price < $regular_price) {
              $discount_percent = (int) round((($regular_price - $sale_price) / $regular_price) * 100);
            }
          }
          ?>
          <article class="fjord-product">
            <div class="fjord-product__badge"><?php echo esc_html($product_name); ?></div>
            <?php if ($discount_percent) : ?>
              <span class="fjord-product__discount"><?php echo esc_html($discount_percent); ?>% OFF</span>
            <?php endif; ?>
            <div class="fjord-product__image">
              <a href="<?php echo esc_url(get_permalink($product_id)); ?>">
                <?php echo $product->get_image('woocommerce_single', ['alt' => $product_name]); ?>
              </a>
            </div>
            <div class="fjord-product__cta">
              <span><?php echo wp_kses_post($product->get_price_html()); ?></span>
              <a class="fjord-product__cta-link" href="<?php echo esc_url(get_permalink($product_id)); ?>">Ver</a>
            </div>
          </article>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
    <button class="fjord-carousel__control fjord-carousel__control--next" type="button" aria-label="Next">
      <img src="https://framerusercontent.com/images/11KSGbIZoRSg4pjdnUoif6MKHI.svg" alt="">
    </button>
  </div>
  <?php
  return ob_get_clean();
}

function fjord_clone_render_favorites_section($args = []) {
  $favorites_title = isset($args['favorites_title']) ? $args['favorites_title'] : 'Our Favorites';
  $pill_background = isset($args['pill_background']) ? $args['pill_background'] : '';
  $pill_text_color = isset($args['pill_text_color']) ? $args['pill_text_color'] : '';
  $pill_border_color = isset($args['pill_border_color']) ? $args['pill_border_color'] : '';

  $styles = [];
  $background = sanitize_hex_color($pill_background);
  if ($background) {
    $styles[] = 'background:' . $background;
  }
  $text_color = sanitize_hex_color($pill_text_color);
  if ($text_color) {
    $styles[] = 'color:' . $text_color;
  }
  $border_color = sanitize_hex_color($pill_border_color);
  if ($border_color) {
    $styles[] = 'border-color:' . $border_color;
  }
  $style_attr = $styles ? ' style="' . esc_attr(implode(';', $styles)) . '"' : '';

  ob_start();
  ?>
  <section class="fjord-favorites">
    <div class="fjord-favorites__pill"<?php echo $style_attr; ?>>
      <h2><?php echo esc_html($favorites_title); ?></h2>
    </div>
    <?php echo fjord_clone_render_favorites_carousel(); ?>
  </section>
  <?php
  return ob_get_clean();
}

function fjord_clone_register_blocks() {
  register_block_type(__DIR__ . '/blocks/hero');
  register_block_type(__DIR__ . '/blocks/info-bar');
  register_block_type(__DIR__ . '/blocks/info-item');
  register_block_type(__DIR__ . '/blocks/favorites');
  register_block_type(__DIR__ . '/blocks/section-pill');
  register_block_type(__DIR__ . '/blocks/slider-2-home');
  register_block_type(__DIR__ . '/blocks/collections-grid');
  register_block_type(__DIR__ . '/blocks/about-section');
  register_block_type(__DIR__ . '/blocks/about-pill');
  register_block_type(__DIR__ . '/blocks/about-mission');
  register_block_type(__DIR__ . '/blocks/about-team');
  register_block_type(__DIR__ . '/blocks/about-hero');
  register_block_type(__DIR__ . '/blocks/about-text-marquee');
  wp_register_script(
    'fjord-clone-faq-pills',
    get_template_directory_uri() . '/blocks/faq-pills/index.js',
    ['wp-blocks', 'wp-element', 'wp-editor', 'wp-components'],
    filemtime(__DIR__ . '/blocks/faq-pills/index.js')
  );
  register_block_type(__DIR__ . '/blocks/contact-hero');
  register_block_type(__DIR__ . '/blocks/faq-hero');
  register_block_type(__DIR__ . '/blocks/faq-pills');
  register_block_type(__DIR__ . '/blocks/faq-hero');
  register_block_type(__DIR__ . '/blocks/steps-six');
}

// Home popup settings
function fjord_clone_admin_popup_settings_init() {
  register_setting('fjord_home_popup_group', 'fjord_home_popup_enabled', [
    'type' => 'boolean',
    'sanitize_callback' => 'fjord_clone_sanitize_checkbox',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_title', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_subtitle', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_button', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_note', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_delay', [
    'type' => 'integer',
    'sanitize_callback' => 'absint',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_pages', [
    'sanitize_callback' => 'fjord_clone_sanitize_pages',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_type', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_behavior', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_repeat_minutes', [
    'type' => 'integer',
    'sanitize_callback' => 'absint',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_newsletter_shortcode', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_newsletter_coupon', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_discount_pct', [
    'type' => 'integer',
    'sanitize_callback' => 'absint',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_notice_text', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_text_field',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_button_background', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
  register_setting('fjord_home_popup_group', 'fjord_home_popup_button_text', [
    'type' => 'string',
    'sanitize_callback' => 'sanitize_hex_color',
  ]);
}

function fjord_clone_sanitize_checkbox($value) {
  return $value ? 1 : 0;
}

function fjord_clone_sanitize_positive_integer($value) {
  $number = absint($value);
  return $number > 0 ? $number : 0;
}

function fjord_clone_sanitize_image($value) {
  if (!$value) {
    return '';
  }
  if (is_numeric($value)) {
    return absint($value);
  }
  return esc_url_raw($value);
}

add_filter('wpcf7_form_elements', 'fjord_clone_customize_footer_newsletter_button');
function fjord_clone_customize_footer_newsletter_button($html) {
  $button_text = get_theme_mod('fjord_footer_newsletter_button_text', 'Subscribe');
  if (!$button_text) {
    return $html;
  }
  return preg_replace_callback(
    '/(<input\\b[^>]*\\btype=(["\\\'])submit\\2[^>]*\\bvalue=)(["\\\'])([^"\\\']*)(["\\\'])/i',
    static function ($matches) use ($button_text) {
      return $matches[1] . $matches[3] . esc_attr($button_text) . $matches[5];
    },
    $html,
    1
  );
}

function fjord_clone_sanitize_pages($value) {
  if (!is_array($value)) {
    return [];
  }
  $allowed = ['front', 'shop', 'product', 'post'];
  return array_values(array_intersect($allowed, $value));
}

add_action('woocommerce_product_options_advanced', 'fjord_clone_add_shipping_returns_field');
function fjord_clone_add_shipping_returns_field() {
  $shipping_icon_choices = fjord_clone_shipping_icon_choices();
  woocommerce_wp_checkbox([
    'id' => '_fjord_show_shipping_bar',
    'label' => __('Mostrar barra de beneficios', 'fjord-clone'),
    'description' => __('Muestra u oculta la barra con devoluciones, entregas rápidas y envío gratis en la ficha del producto.', 'fjord-clone'),
    'desc_tip' => true,
    'value' => get_post_meta(get_the_ID(), '_fjord_show_shipping_bar', true) === 'no' ? 'no' : 'yes',
  ]);
  for ($i = 1; $i <= 4; $i++) {
    woocommerce_wp_select([
      'id' => "_fjord_shipping_icon_{$i}",
      'label' => sprintf(__('Icono envío %d', 'fjord-clone'), $i),
      'options' => $shipping_icon_choices,
      'desc_tip' => true,
    ]);
    woocommerce_wp_text_input([
      'id' => "_fjord_shipping_text_{$i}",
      'label' => sprintf(__('Texto envío %d', 'fjord-clone'), $i),
      'desc_tip' => true,
    ]);
  }
  woocommerce_wp_textarea_input([
    'id' => '_fjord_shipping_returns_text',
    'label' => __('Envíos y devoluciones', 'fjord-clone'),
    'description' => __('Texto que reemplaza la nota de envío estándar en la ficha del producto.', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_shipping_returns_title',
    'label' => __('Shipping & Returns title', 'fjord-clone'),
    'description' => __('Título que aparece encima del texto de envíos y devoluciones.', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_textarea_input([
    'id' => '_fjord_dimensions_text',
    'label' => __('Dimensiones (texto)', 'fjord-clone'),
    'description' => __('Texto libre para reemplazar los campos numéricos de dimensiones.', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_social_pinterest_label',
    'label' => __('Texto botón Pinterest', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_social_pinterest_url',
    'label' => __('URL Pinterest', 'fjord-clone'),
    'type' => 'url',
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_social_instagram_label',
    'label' => __('Texto botón Instagram', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_social_instagram_url',
    'label' => __('URL Instagram', 'fjord-clone'),
    'type' => 'url',
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_story_block_1_title',
    'label' => __('Título bloque 1', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_textarea_input([
    'id' => '_fjord_story_block_1_text',
    'label' => __('Texto bloque 1', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_text_input([
    'id' => '_fjord_story_block_2_title',
    'label' => __('Título bloque 2', 'fjord-clone'),
    'desc_tip' => true,
  ]);
  woocommerce_wp_textarea_input([
    'id' => '_fjord_story_block_2_text',
    'label' => __('Texto bloque 2', 'fjord-clone'),
    'desc_tip' => true,
  ]);
}

add_action('woocommerce_process_product_meta', 'fjord_clone_save_shipping_returns_field');
function fjord_clone_save_shipping_returns_field($post_id) {
  update_post_meta(
    $post_id,
    '_fjord_show_shipping_bar',
    isset($_POST['_fjord_show_shipping_bar']) ? 'yes' : 'no'
  );

  if (!isset($_POST['_fjord_shipping_returns_text'])) {
    return;
  }
  update_post_meta(
    $post_id,
    '_fjord_shipping_returns_text',
    sanitize_textarea_field(wp_unslash($_POST['_fjord_shipping_returns_text']))
  );
  if (isset($_POST['_fjord_shipping_returns_title'])) {
    update_post_meta(
      $post_id,
      '_fjord_shipping_returns_title',
      sanitize_text_field(wp_unslash($_POST['_fjord_shipping_returns_title']))
    );
  }
  for ($i = 1; $i <= 4; $i++) {
    if (isset($_POST["_fjord_shipping_icon_{$i}"])) {
      update_post_meta(
        $post_id,
        "_fjord_shipping_icon_{$i}",
        sanitize_key(wp_unslash($_POST["_fjord_shipping_icon_{$i}"]))
      );
    }
    if (isset($_POST["_fjord_shipping_text_{$i}"])) {
      update_post_meta(
        $post_id,
        "_fjord_shipping_text_{$i}",
        sanitize_text_field(wp_unslash($_POST["_fjord_shipping_text_{$i}"]))
      );
    }
  }
  if (isset($_POST['_fjord_dimensions_text'])) {
    update_post_meta(
      $post_id,
      '_fjord_dimensions_text',
      sanitize_textarea_field(wp_unslash($_POST['_fjord_dimensions_text']))
    );
  }
  if (isset($_POST['_fjord_social_pinterest_label'])) {
    update_post_meta($post_id, '_fjord_social_pinterest_label', sanitize_text_field(wp_unslash($_POST['_fjord_social_pinterest_label'])));
  }
  if (isset($_POST['_fjord_social_pinterest_url'])) {
    update_post_meta($post_id, '_fjord_social_pinterest_url', esc_url_raw(wp_unslash($_POST['_fjord_social_pinterest_url'])));
  }
  if (isset($_POST['_fjord_social_instagram_label'])) {
    update_post_meta($post_id, '_fjord_social_instagram_label', sanitize_text_field(wp_unslash($_POST['_fjord_social_instagram_label'])));
  }
  if (isset($_POST['_fjord_social_instagram_url'])) {
    update_post_meta($post_id, '_fjord_social_instagram_url', esc_url_raw(wp_unslash($_POST['_fjord_social_instagram_url'])));
  }
  if (isset($_POST['_fjord_story_block_1_title'])) {
    update_post_meta($post_id, '_fjord_story_block_1_title', sanitize_text_field(wp_unslash($_POST['_fjord_story_block_1_title'])));
  }
  if (isset($_POST['_fjord_story_block_1_text'])) {
    update_post_meta($post_id, '_fjord_story_block_1_text', sanitize_textarea_field(wp_unslash($_POST['_fjord_story_block_1_text'])));
  }
  if (isset($_POST['_fjord_story_block_2_title'])) {
    update_post_meta($post_id, '_fjord_story_block_2_title', sanitize_text_field(wp_unslash($_POST['_fjord_story_block_2_title'])));
  }
 if (isset($_POST['_fjord_story_block_2_text'])) {
    update_post_meta($post_id, '_fjord_story_block_2_text', sanitize_textarea_field(wp_unslash($_POST['_fjord_story_block_2_text'])));
  }
}

function fjord_clone_home_popup_menu() {
  add_menu_page(
    'Home Popup',
    'Home Popup',
    'manage_options',
    'fjord-home-popup',
    'fjord_clone_render_home_popup_settings',
    'dashicons-feedback',
    70
  );
}

function fjord_clone_render_home_popup_settings() {
  ?>
  <div class="wrap">
    <h1>Nordie Home Popup</h1>
    <form method="post" action="options.php">
      <?php
      settings_fields('fjord_home_popup_group');
      do_settings_sections('fjord_home_popup_group');
      $enabled = get_option('fjord_home_popup_enabled', false);
      $title = get_option('fjord_home_popup_title', 'Enter your email and unlock 20% OFF');
      $subtitle = get_option('fjord_home_popup_subtitle', 'Home is more stylish with Nordie. Use code'); // maybe note
      $button = get_option('fjord_home_popup_button', 'Get code');
      $note = get_option('fjord_home_popup_note', 'Discount applies to first purchase only.');
      ?>
      <table class="form-table">
        <tr>
          <th><label for="fjord_home_popup_enabled">Enable popup</label></th>
          <td><input type="checkbox" id="fjord_home_popup_enabled" name="fjord_home_popup_enabled" value="1" <?php checked($enabled, 1); ?>></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_delay">Delay (segundos)</label></th>
          <td><input type="number" id="fjord_home_popup_delay" name="fjord_home_popup_delay" value="<?php echo esc_attr(get_option('fjord_home_popup_delay', 2)); ?>" class="small-text" min="0"></td>
        </tr>
        <tr>
          <th>Páginas</th>
          <td>
            <?php
            $pages = get_option('fjord_home_popup_pages', ['front']);
            $presets = [
              'front' => 'Home',
              'shop' => 'Tienda',
              'product' => 'Producto',
              'post' => 'Entradas',
            ];
            foreach ($presets as $key => $label) :
              ?>
              <label><input type="checkbox" name="fjord_home_popup_pages[]" value="<?php echo esc_attr($key); ?>" <?php checked(in_array($key, (array) $pages), true); ?>> <?php echo esc_html($label); ?></label><br>
            <?php endforeach; ?>
          </td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_title">Headline</label></th>
          <td><input type="text" id="fjord_home_popup_title" name="fjord_home_popup_title" value="<?php echo esc_attr($title); ?>" class="regular-text"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_subtitle">Subtitle</label></th>
          <td><input type="text" id="fjord_home_popup_subtitle" name="fjord_home_popup_subtitle" value="<?php echo esc_attr($subtitle); ?>" class="regular-text"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_button">Button text</label></th>
          <td><input type="text" id="fjord_home_popup_button" name="fjord_home_popup_button" value="<?php echo esc_attr($button); ?>" class="regular-text"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_note">Disclaimer / note</label></th>
          <td><input type="text" id="fjord_home_popup_note" name="fjord_home_popup_note" value="<?php echo esc_attr($note); ?>" class="regular-text"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_button_background">Color botón (fondo)</label></th>
          <td><input type="color" id="fjord_home_popup_button_background" name="fjord_home_popup_button_background" value="<?php echo esc_attr(get_option('fjord_home_popup_button_background', '#191919')); ?>"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_button_text">Color botón (texto)</label></th>
          <td><input type="color" id="fjord_home_popup_button_text" name="fjord_home_popup_button_text" value="<?php echo esc_attr(get_option('fjord_home_popup_button_text', '#ffffff')); ?>"></td>
        </tr>
        <tr data-type-option="newsletter">
          <th><label for="fjord_home_popup_newsletter_shortcode">Shortcode newsletter</label></th>
          <td><input type="text" id="fjord_home_popup_newsletter_shortcode" name="fjord_home_popup_newsletter_shortcode" value="<?php echo esc_attr(get_option('fjord_home_popup_newsletter_shortcode', '')); ?>" class="regular-text" placeholder="[contact-form-7 id=&quot;1&quot; title=&quot;Newsletter&quot;]"></td>
        </tr>
        <tr data-type-option="newsletter">
          <th><label for="fjord_home_popup_newsletter_coupon">Código tras suscripción</label></th>
          <td><input type="text" id="fjord_home_popup_newsletter_coupon" name="fjord_home_popup_newsletter_coupon" value="<?php echo esc_attr(get_option('fjord_home_popup_newsletter_coupon', 'WELCOME20')); ?>" class="regular-text"></td>
        </tr>
        <tr data-type-option="discount">
          <th><label for="fjord_home_popup_discount_pct">% de descuento</label></th>
          <td><input type="number" id="fjord_home_popup_discount_pct" name="fjord_home_popup_discount_pct" value="<?php echo esc_attr(get_option('fjord_home_popup_discount_pct', 20)); ?>" class="small-text" min="0" max="100"> %</td>
        </tr>
        <tr data-type-option="notice">
          <th><label for="fjord_home_popup_notice_text">Texto aviso</label></th>
          <td><input type="text" id="fjord_home_popup_notice_text" name="fjord_home_popup_notice_text" value="<?php echo esc_attr(get_option('fjord_home_popup_notice_text', 'Anuncio puntual.')); ?>" class="regular-text"></td>
        </tr>
        <tr>
          <th><label for="fjord_home_popup_type">Tipo de popup</label></th>
          <td>
            <select id="fjord_home_popup_type" name="fjord_home_popup_type">
              <?php
              $types = [
                'discount' => 'Código de descuento',
                'newsletter' => 'Newsletter',
                'notice' => 'Aviso personalizado',
              ];
              $current_type = get_option('fjord_home_popup_type', 'discount');
              foreach ($types as $value => $label) :
                ?>
                <option value="<?php echo esc_attr($value); ?>" <?php selected($current_type, $value); ?>><?php echo esc_html($label); ?></option>
              <?php endforeach; ?>
            </select>
          </td>
        </tr>
        <tr>
          <th>Frecuencia</th>
          <td>
            <label><input type="radio" name="fjord_home_popup_behavior" value="once" <?php checked(get_option('fjord_home_popup_behavior', 'once'), 'once'); ?>> Una vez</label><br>
            <label><input type="radio" name="fjord_home_popup_behavior" value="repeat" <?php checked(get_option('fjord_home_popup_behavior', 'once'), 'repeat'); ?>> Repetir cada</label>
            <input type="number" name="fjord_home_popup_repeat_minutes" value="<?php echo esc_attr(get_option('fjord_home_popup_repeat_minutes', 1440)); ?>" class="small-text" min="5"> minutos
            <br>
            <label><input type="radio" name="fjord_home_popup_behavior" value="repeat_always" <?php checked(get_option('fjord_home_popup_behavior', 'once'), 'repeat_always'); ?>> Repetir siempre</label>
          </td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>
  </div>
  <script>
    (function () {
      const select = document.getElementById("fjord_home_popup_type");
      const rows = document.querySelectorAll("[data-type-option]");
      if (!select) {
        return;
      }
      const update = () => {
        const value = select.value;
        rows.forEach((row) => {
          row.style.display = row.dataset.typeOption === value ? "table-row" : "none";
        });
      };
      document.addEventListener("DOMContentLoaded", update);
      select.addEventListener("change", update);
      update();
    })();
  </script>
  <?php
}

function fjord_clone_home_popup_is_allowed() {
  $pages = get_option('fjord_home_popup_pages', ['front']);
  if (!is_array($pages) || empty($pages)) {
    $pages = ['front'];
  }
  if (in_array('front', $pages, true) && is_front_page()) {
    return true;
  }
  if (in_array('shop', $pages, true) && (is_shop() || is_post_type_archive('product'))) {
    return true;
  }
  if (in_array('product', $pages, true) && is_singular('product')) {
    return true;
  }
  if (in_array('post', $pages, true) && is_singular('post')) {
    return true;
  }
  return false;
}

function fjord_clone_enqueue_home_popup_scripts() {
  if (!get_option('fjord_home_popup_enabled')) {
    return;
  }
  if (!fjord_clone_home_popup_is_allowed()) {
    return;
  }
  wp_enqueue_script(
    'fjord-home-popup',
    get_template_directory_uri() . '/js/home-popup.js',
    ['jquery'],
    filemtime(__DIR__ . '/js/home-popup.js'),
    true
  );
  wp_enqueue_style(
    'fjord-home-popup-style',
    get_template_directory_uri() . '/css/home-popup.css',
    [],
    filemtime(__DIR__ . '/css/home-popup.css')
  );
}

function fjord_clone_render_home_popup() {
  if (!fjord_clone_home_popup_is_allowed()) {
    return;
  }
  if (!get_option('fjord_home_popup_enabled')) {
    return;
  }
  $title = get_option('fjord_home_popup_title', 'Enter your email and get 20% OFF');
  $subtitle = get_option('fjord_home_popup_subtitle', 'Subscribe & unlock style.');
  $button = get_option('fjord_home_popup_button', 'Get price');
  $note = get_option('fjord_home_popup_note', '*Offer valid on first purchase.');
  $newsletter_shortcode = get_option('fjord_home_popup_newsletter_shortcode', '');
  $newsletter_coupon = get_option('fjord_home_popup_newsletter_coupon', '');
  $discount_pct = max(0, get_option('fjord_home_popup_discount_pct', 20));
  $promotion_value = get_option('fjord_home_popup_promotion_value', '40% OFF promocional');
  $notice_text = get_option('fjord_home_popup_notice_text', 'Aviso personalizado.');
  $button_background = get_option('fjord_home_popup_button_background', '#191919');
  $button_text = get_option('fjord_home_popup_button_text', '#ffffff');
  ?>
  <?php
  $delay = max(0, get_option('fjord_home_popup_delay', 2));
  $pages = get_option('fjord_home_popup_pages', ['front']);
  if (empty($pages)) {
    $pages = ['front'];
  }
  $behavior = get_option('fjord_home_popup_behavior', 'once');
  $repeat = max(5, get_option('fjord_home_popup_repeat_minutes', 1440));
  $type = get_option('fjord_home_popup_type', 'discount');
  ?>
  <?php
  $admin_bypass = current_user_can('manage_options') ? 'true' : 'false';
  ?>
  <div
    class="fjord-home-popup"
    role="dialog"
    aria-modal="true"
    data-delay="<?php echo esc_attr($delay); ?>"
    data-pages="<?php echo esc_attr(implode(',', $pages)); ?>"
    data-behavior="<?php echo esc_attr($behavior); ?>"
    data-repeat-minutes="<?php echo esc_attr($repeat); ?>"
    data-popup-type="<?php echo esc_attr($type); ?>"
    data-admin-bypass="<?php echo esc_attr($admin_bypass); ?>"
    data-newsletter-coupon="<?php echo esc_attr($newsletter_coupon); ?>"
    style="--fjord-popup-button-bg: <?php echo esc_attr($button_background); ?>; --fjord-popup-button-text: <?php echo esc_attr($button_text); ?>;"
  >
    <div class="fjord-home-popup__overlay"></div>
    <div class="fjord-home-popup__card fjord-home-popup__card--<?php echo esc_attr($type); ?>">
      <button class="fjord-home-popup__close" type="button" aria-label="Close">×</button>
      <p class="fjord-home-popup__subtitle"><?php echo esc_html($subtitle); ?></p>
      <h2 class="fjord-home-popup__title"><?php echo esc_html($title); ?></h2>

      <?php if ('discount' === $type) : ?>
        <p class="fjord-home-popup__discount"><?php echo esc_html($discount_pct); ?>% OFF</p>
      <?php elseif ('newsletter' === $type) : ?>
        <div class="fjord-home-popup__newsletter">
          <div class="fjord-home-popup__newsletter-body">
            <?php
            if ($newsletter_shortcode) {
              echo do_shortcode($newsletter_shortcode);
            } else {
              ?>
              <input type="email" class="fjord-home-popup__input" placeholder="Tu email">
              <?php
            }
            ?>
          </div>
          <?php if ($newsletter_coupon) : ?>
            <div class="fjord-home-popup__newsletter-success" role="status">
              <p class="fjord-home-popup__newsletter-success-label">Gracias por suscribirte</p>
              <p class="fjord-home-popup__newsletter-success-code"><?php echo esc_html($newsletter_coupon); ?></p>
              <p class="fjord-home-popup__newsletter-success-note">Copia el código y úsalo en tu próxima compra.</p>
            </div>
          <?php endif; ?>
        </div>
      <?php elseif ('notice' === $type) : ?>
        <p class="fjord-home-popup__notice"><?php echo esc_html($notice_text); ?></p>
      <?php endif; ?>

      <button class="fjord-home-popup__button" type="button"><?php echo esc_html($button); ?></button>
      <p class="fjord-home-popup__note"><?php echo esc_html($note); ?></p>
    </div>
  </div>
  <?php
}

add_action('admin_menu', 'fjord_clone_home_popup_menu');
add_action('admin_init', 'fjord_clone_admin_popup_settings_init');
add_action('wp_enqueue_scripts', 'fjord_clone_enqueue_home_popup_scripts');
add_action('wp_footer', 'fjord_clone_render_home_popup');

function fjord_clone_trim_front_page_content($content) {
  if (!is_front_page() && !is_home()) {
    return $content;
  }

  $pattern = '/(<p[^>]*>(?:\s|&nbsp;|\x{00a0})*<\/p>\s*)+$/iu';
  $trimmed = @preg_replace($pattern, '', $content);
  return ($trimmed === null || $trimmed === false) ? $content : $trimmed;
}

add_filter('the_content', 'fjord_clone_trim_front_page_content', 12);

function fjord_clone_remove_home_template_part($content) {
  if (!is_front_page() && !is_home()) {
    return $content;
  }

  if (stripos($content, 'wp:template-part') === false) {
    return $content;
  }

  $blocks = parse_blocks($content);
  $filtered = array_filter($blocks, function ($block) {
    if (empty($block['blockName'])) {
      return true;
    }
    if ($block['blockName'] === 'core/template-part' && isset($block['attrs']['slug'])) {
      $slug = strtolower($block['attrs']['slug']);
      return $slug !== 'home';
    }
    return true;
  });

  return serialize_blocks(array_values($filtered));
}

add_filter('the_content', 'fjord_clone_remove_home_template_part', 11);

add_action('init', 'fjord_clone_register_blocks');

function fjord_clone_force_cart_template($template, $template_name, $template_path) {
  if ($template_name === 'cart/cart.php') {
    $forced = get_stylesheet_directory() . '/woocommerce/cart/cart.php';
    if (file_exists($forced)) {
      return $forced;
    }
  }
  return $template;
}

add_filter('woocommerce_locate_template', 'fjord_clone_force_cart_template', 10, 3);

function fjord_clone_force_cart_template_include($template) {
  if (!fjord_clone_is_cart_target()) {
    return $template;
  }

  $cart_template = get_stylesheet_directory() . '/page-carrito.php';
  if (file_exists($cart_template)) {
    return $cart_template;
  }

  return $template;
}

add_filter('template_include', 'fjord_clone_force_cart_template_include', 99);

function fjord_clone_is_cart_target() {
  if (function_exists('is_cart') && is_cart()) {
    return true;
  }
  if (function_exists('wc_get_page_id')) {
    $cart_page_id = wc_get_page_id('cart');
    if ($cart_page_id > 0 && is_page($cart_page_id)) {
      return true;
    }
  }
  if (is_page('carrito')) {
    return true;
  }
  if (is_page_template('page-carrito.php')) {
    return true;
  }
  return false;
}

function fjord_clone_render_cart_template() {
  if (!function_exists('WC')) {
    return '';
  }
  if (function_exists('wc_load_cart')) {
    wc_load_cart();
  }
  ob_start();
  $template_path = get_stylesheet_directory() . '/woocommerce/cart/cart.php';
  if (file_exists($template_path)) {
    include $template_path;
  } else {
    echo do_shortcode('[woocommerce_cart]');
  }
  return ob_get_clean();
}

function fjord_clone_force_cart_shortcode($content) {
  if (!fjord_clone_is_cart_target()) {
    return $content;
  }

  return fjord_clone_render_cart_template();
}

add_filter('the_content', 'fjord_clone_force_cart_shortcode', 9);

function fjord_clone_force_cart_page_render() {
  if (!fjord_clone_is_cart_target()) {
    return;
  }

  if (is_admin() || (defined('REST_REQUEST') && REST_REQUEST)) {
    return;
  }

  if (function_exists('wc_load_cart')) {
    wc_load_cart();
  }

  get_header();
  echo '<main class="fjord-main">';
  echo fjord_clone_render_cart_template();
  echo '</main>';
  get_footer();
  exit;
}

add_action('template_redirect', 'fjord_clone_force_cart_page_render', 9);

function fjord_clone_render_hero_block() {
  $fallback = function () {
    ob_start();
    get_template_part('template-parts/hero-static');
    return ob_get_clean();
  };

  if (!function_exists('parse_blocks')) {
    return $fallback();
  }

  $post_id = get_queried_object_id();
  if (!$post_id) {
    return $fallback();
  }

  $content = get_post_field('post_content', $post_id);
  if (!$content) {
    return $fallback();
  }

  $blocks = parse_blocks($content);
  $queue = $blocks;
  while ($queue) {
    $block = array_shift($queue);
    if (!empty($block['blockName']) && $block['blockName'] === 'fjord/hero') {
      return render_block($block);
    }
    if (!empty($block['innerBlocks'])) {
      $queue = array_merge($queue, $block['innerBlocks']);
    }
  }

  return $fallback();
}
