<?php
defined('ABSPATH') || exit;

get_header();
?>

<main class="fjord-main fjord-product-page">
  <div class="fjord-product-page__inner">
    <?php do_action('woocommerce_before_single_product'); ?>
    <?php while (have_posts()) : ?>
      <?php the_post(); ?>
      <?php
      global $product;
      if (!$product) {
        $product = wc_get_product(get_the_ID());
      }
      if (!$product) {
        continue;
      }
      $image_ids = array_filter(array_merge([$product->get_image_id()], $product->get_gallery_image_ids()));
      $image_ids = array_values(array_unique($image_ids));
      if (!$image_ids) {
        $image_ids = [0];
      }
      $attribute_groups = [];
      $variation_attribute_names = [];

      if ($product->is_type('variable')) {
        $variation_attributes = $product->get_variation_attributes();
        foreach ($variation_attributes as $attribute_name => $options) {
          $options = array_values(array_filter($options));
          if (!$options) {
            continue;
          }
          $label = wc_attribute_label($attribute_name);
          $display_options = [];
          foreach ($options as $option) {
            $option_label = $option;
            if (taxonomy_exists($attribute_name)) {
              $term = get_term_by('slug', $option, $attribute_name);
              if ($term && !is_wp_error($term)) {
                $option_label = $term->name;
              }
            }
            $display_options[] = [
              'value' => $option,
              'label' => $option_label,
            ];
          }
          $variation_attribute_names[] = $attribute_name;
          $attribute_groups[] = [
            'name' => wc_variation_attribute_name($attribute_name),
            'label' => $label,
            'options' => $display_options,
            'selectable' => true,
          ];
        }
      }

      foreach ($product->get_attributes() as $attribute) {
        if (!$attribute->get_visible()) {
          continue;
        }
        $attr_name = $attribute->get_name();
        if (in_array($attr_name, $variation_attribute_names, true)) {
          continue;
        }
        $label = $attribute->is_taxonomy() ? wc_attribute_label($attr_name) : $attr_name;
        $options = $attribute->is_taxonomy()
          ? wc_get_product_terms($product->get_id(), $attr_name, ['fields' => 'names'])
          : $attribute->get_options();
        $options = array_values(array_filter($options));
        if (!$options) {
          continue;
        }
        $display_options = array_map(function ($option) {
          return [
            'value' => $option,
            'label' => $option,
          ];
        }, $options);
        $attribute_groups[] = [
          'name' => $attr_name,
          'label' => $label,
          'options' => $display_options,
          'selectable' => false,
        ];
      }

      $default_cat = (int) get_option('default_product_cat');
      $category_terms = wc_get_product_terms($product->get_id(), 'product_cat', ['fields' => 'all']);
      if ($category_terms) {
        $category_terms = array_values(array_filter($category_terms, function ($term) use ($default_cat) {
          return !$default_cat || (int) $term->term_id !== $default_cat;
        }));
      }
      $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);
        }
      }
      ?>

      <div class="fjord-product-page__columns">
        <section class="fjord-product-page__media">
          <div class="fjord-product-page__media-stack">
            <?php foreach ($image_ids as $index => $image_id) : ?>
              <figure id="fjord-product-image-<?php echo esc_attr($index); ?>" class="fjord-product-page__media-item<?php echo $index === 0 ? ' is-primary' : ''; ?>">
                <?php
                if ($image_id) {
                  echo wp_get_attachment_image($image_id, 'woocommerce_single', false, ['loading' => 'lazy']);
                } else {
                  echo wc_placeholder_img('woocommerce_single');
                }
                ?>
              </figure>
            <?php endforeach; ?>
            <?php if (count($image_ids) > 1) : ?>
              <div class="fjord-product-page__thumbs-wrap">
                <div class="fjord-product-page__thumbs" data-product-thumbs>
                  <?php foreach ($image_ids as $thumb_index => $thumb_id) : ?>
                    <button class="fjord-product-page__thumb" type="button" data-product-thumb-target="fjord-product-image-<?php echo esc_attr($thumb_index); ?>" aria-label="View image <?php echo esc_attr($thumb_index + 1); ?>">
                      <?php
                      if ($thumb_id) {
                        echo wp_get_attachment_image($thumb_id, 'thumbnail', false, ['loading' => 'lazy']);
                      } else {
                        echo wc_placeholder_img('thumbnail');
                      }
                      ?>
                    </button>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </section>

        <aside class="fjord-product-page__details">
          <div class="fjord-product-page__panel fjord-product-page__panel--main fjord-product-page__panel--primary" data-variation-scope>
            <div class="fjord-product-page__price-row">
              <div class="fjord-product-page__price">
                <?php echo wp_kses_post($product->get_price_html()); ?>
              </div>
            <?php if ($discount_percent) : ?>
              <span class="fjord-product-page__badge"><?php echo esc_html($discount_percent); ?>% OFF</span>
            <?php endif; ?>
            </div>

            <?php
            $shop_id = function_exists('wc_get_page_id') ? wc_get_page_id('shop') : 0;
            $shop_name = $shop_id > 0 ? get_the_title($shop_id) : 'Tienda';
            $shop_link = $shop_id > 0 ? get_permalink($shop_id) : '';
            $breadcrumb_items = [
              [
                'label' => __('Inicio', 'fjord-clone'),
                'url' => home_url('/'),
              ],
            ];
            if ($shop_name) {
              $breadcrumb_items[] = [
                'label' => $shop_name,
                'url' => $shop_link,
              ];
            }
            if (!empty($category_terms)) {
              $primary_term = $category_terms[0];
              $term_link = get_term_link($primary_term);
              if (!is_wp_error($term_link)) {
                $breadcrumb_items[] = [
                  'label' => $primary_term->name,
                  'url' => $term_link,
                ];
              }
            }
            $breadcrumb_items[] = [
              'label' => get_the_title(),
              'url' => '',
            ];
            ?>
            <nav class="fjord-blog-post__breadcrumb" aria-label="Breadcrumb">
              <?php foreach ($breadcrumb_items as $index => $item) : ?>
                <?php if ($index > 0) : ?>
                  <span class="fjord-blog-post__breadcrumb-sep">/</span>
                <?php endif; ?>
                <?php if (!empty($item['url'])) : ?>
                  <a href="<?php echo esc_url($item['url']); ?>">
                    <?php echo esc_html($item['label']); ?>
                  </a>
                <?php else : ?>
                  <span><?php echo esc_html($item['label']); ?></span>
                <?php endif; ?>
              <?php endforeach; ?>
            </nav>

            <div class="fjord-product-page__title">
              <h1><?php the_title(); ?></h1>
              <?php
              $description = $product->get_description();
              if (!$description) {
                $description = $product->get_short_description();
              }
              ?>
              <?php if ($description) : ?>
                <div class="fjord-product-page__desc">
                  <?php echo wp_kses_post($description); ?>
                </div>
              <?php endif; ?>
            </div>

            <?php if ($category_terms) : ?>
              <div class="fjord-product-page__materials fjord-product-page__materials--category">
                <p class="fjord-product-page__label">Categoría</p>
                <p class="fjord-product-page__category"><?php echo esc_html($category_terms[0]->name); ?></p>
              </div>
            <?php endif; ?>

            <?php if ($attribute_groups) : ?>
              <div class="fjord-product-page__variations">
                <?php foreach ($attribute_groups as $group) : ?>
                  <div class="fjord-product-page__materials fjord-product-page__materials--variation">
                    <p class="fjord-product-page__label"><?php echo esc_html($group['label']); ?></p>
                    <div class="fjord-product-page__chips<?php echo $group['selectable'] ? ' fjord-product-page__chips--selectable' : ''; ?>"<?php echo $group['selectable'] ? ' data-variation-group data-attribute-name="' . esc_attr($group['name']) . '"' : ''; ?>>
                      <?php foreach ($group['options'] as $option) : ?>
                        <?php if ($group['selectable']) : ?>
                          <button class="fjord-product-page__chip" type="button" data-variation-value="<?php echo esc_attr($option['value']); ?>">
                            <?php echo esc_html($option['label']); ?>
                          </button>
                        <?php else : ?>
                          <span class="fjord-product-page__chip"><?php echo esc_html($option['label']); ?></span>
                        <?php endif; ?>
                      <?php endforeach; ?>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>

            <div class="fjord-product-page__form">
              <?php if ($product->is_type('simple')) : ?>
                <form class="cart" action="<?php echo esc_url(apply_filters('woocommerce_add_to_cart_form_action', $product->get_permalink())); ?>" method="post" enctype="multipart/form-data">
                  <?php do_action('woocommerce_before_add_to_cart_button'); ?>
                  <div class="fjord-product-page__cta">
                    <div class="fjord-product-page__qty" data-product-qty>
                      <button type="button" class="fjord-product-page__qty-btn" data-qty-change="-1" aria-label="Decrease quantity">-</button>
                      <?php
                      woocommerce_quantity_input([
                        'input_value' => isset($_POST['quantity']) ? wc_stock_amount(wp_unslash($_POST['quantity'])) : 1,
                      ]);
                      ?>
                      <button type="button" class="fjord-product-page__qty-btn" data-qty-change="1" aria-label="Increase quantity">+</button>
                    </div>
                    <button type="submit" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" class="fjord-product-page__add">
                      <?php echo esc_html($product->single_add_to_cart_text()); ?>
                    </button>
                  </div>
                  <?php do_action('woocommerce_after_add_to_cart_button'); ?>
                </form>
              <?php else : ?>
                <?php woocommerce_template_single_add_to_cart(); ?>
              <?php endif; ?>
            </div>
          </div>

          <?php
          $show_shipping_bar = get_post_meta($product->get_id(), '_fjord_show_shipping_bar', true) !== 'no';
          $shipping_items = $show_shipping_bar ? fjord_clone_get_product_shipping_items($product->get_id()) : [];
          if (!empty($shipping_items)) :
          ?>
          <div class="fjord-product-page__panel fjord-product-page__panel--shipping fjord-product-page__panel--secondary">
            <div class="fjord-product-page__shipping">
              <div class="fjord-product-page__shipping-marquee">
                <?php for ($track_index = 0; $track_index < 2; $track_index++) : ?>
                  <div class="fjord-product-page__shipping-track"<?php echo $track_index === 1 ? ' aria-hidden="true"' : ''; ?>>
                    <?php foreach ($shipping_items as $item) : ?>
                      <div class="fjord-product-page__shipping-item">
                        <?php if ($item['icon']) : ?>
                          <svg viewBox="0 0 24 24" aria-hidden="true">
                            <?php echo fjord_clone_get_shipping_icon_svg($item['icon']); ?>
                          </svg>
                        <?php endif; ?>
                        <span><?php echo esc_html($item['text']); ?></span>
                      </div>
                    <?php endforeach; ?>
                  </div>
                <?php endfor; ?>
              </div>
            </div>
          </div>
          <?php endif; ?>

          <div class="fjord-product-page__panel fjord-product-page__panel--accordion fjord-product-page__panel--secondary">
            <details class="fjord-product-page__accordion">
              <summary>Descripción <span class="fjord-product-page__accordion-icon">+</span></summary>
              <div class="fjord-product-page__accordion-body">
                <?php
                $short_description = $product->get_short_description();
                ?>
                <?php if ($short_description) : ?>
                  <?php echo wp_kses_post($short_description); ?>
                <?php elseif ($description) : ?>
                  <?php echo wp_kses_post($description); ?>
                <?php else : ?>
                  <p>Designed with comfort in mind, crafted from premium materials.</p>
                <?php endif; ?>
              </div>
            </details>
          </div>

          <div class="fjord-product-page__panel fjord-product-page__panel--accordion fjord-product-page__panel--secondary">
            <details class="fjord-product-page__accordion">
              <summary>Dimensiones <span class="fjord-product-page__accordion-icon">+</span></summary>
              <div class="fjord-product-page__accordion-body">
            <?php
            $dimension_string = wc_format_dimensions($product->get_dimensions(false));
            $custom_dimensions = get_post_meta($product->get_id(), '_fjord_dimensions_text', true);
            $weight_value = $product->get_weight();
            ?>
            <?php if ($custom_dimensions) : ?>
              <p><?php echo wp_kses_post($custom_dimensions); ?></p>
            <?php else : ?>
              <?php if ($dimension_string) : ?>
                <p><?php echo esc_html($dimension_string); ?></p>
              <?php endif; ?>
              <?php if ($weight_value) : ?>
                <p><?php echo esc_html(wc_format_weight($weight_value)); ?></p>
              <?php endif; ?>
              <?php if (!$dimension_string && !$weight_value) : ?>
                <p><?php echo esc_html__('N/D', 'fjord-clone'); ?></p>
              <?php endif; ?>
            <?php endif; ?>
              </div>
            </details>
          </div>

          <div class="fjord-product-page__panel fjord-product-page__panel--accordion fjord-product-page__panel--secondary">
            <details class="fjord-product-page__accordion">
              <?php
              $shipping_title = get_post_meta($product->get_id(), '_fjord_shipping_returns_title', true);
              $shipping_text = get_post_meta($product->get_id(), '_fjord_shipping_returns_text', true);
              $shipping_title = $shipping_title ?: 'Shipping &amp; Returns';
              $shipping_text = $shipping_text ?: 'Standard delivery in 3-7 business days. Returns accepted within 30 days.';
              ?>
              <summary><?php echo wp_kses_post($shipping_title); ?> <span class="fjord-product-page__accordion-icon">+</span></summary>
              <div class="fjord-product-page__accordion-body">
                <p><?php echo wp_kses_post($shipping_text); ?></p>
              </div>
            </details>
          </div>

          <div class="fjord-product-page__panel fjord-product-page__panel--social fjord-product-page__panel--secondary">
            <div class="fjord-product-page__social">
            <?php
            $pinterest_label = get_post_meta($product->get_id(), '_fjord_social_pinterest_label', true);
            $pinterest_url = get_post_meta($product->get_id(), '_fjord_social_pinterest_url', true);
            $instagram_label = get_post_meta($product->get_id(), '_fjord_social_instagram_label', true);
            $instagram_url = get_post_meta($product->get_id(), '_fjord_social_instagram_url', true);
            $pinterest_label = $pinterest_label ?: 'Pinterest';
            $instagram_label = $instagram_label ?: 'Instagram';
            ?>
              <?php if ($pinterest_url) : ?>
                <a class="fjord-product-page__social-btn" target="_blank" rel="noopener noreferrer" href="<?php echo esc_url($pinterest_url); ?>" aria-label="<?php echo esc_attr($pinterest_label); ?>"><?php echo esc_html($pinterest_label); ?></a>
              <?php else : ?>
                <span class="fjord-product-page__social-btn is-disabled" aria-hidden="true"><?php echo esc_html($pinterest_label); ?></span>
              <?php endif; ?>
              <?php if ($instagram_url) : ?>
                <a class="fjord-product-page__social-btn" target="_blank" rel="noopener noreferrer" href="<?php echo esc_url($instagram_url); ?>" aria-label="<?php echo esc_attr($instagram_label); ?>"><?php echo esc_html($instagram_label); ?></a>
              <?php else : ?>
                <span class="fjord-product-page__social-btn is-disabled" aria-hidden="true"><?php echo esc_html($instagram_label); ?></span>
              <?php endif; ?>
            </div>
          </div>
        </aside>
      </div>

      <section class="fjord-product-page__details-strip">Detalles</section>

      <section class="fjord-product-page__story">
        <?php
        $story1_title = get_post_meta($product->get_id(), '_fjord_story_block_1_title', true) ?: 'Designed for Modern Living';
        $story1_text = get_post_meta($product->get_id(), '_fjord_story_block_1_text', true) ?: 'Our furniture is thoughtfully crafted to blend timeless design with modern function. Every detail is refined for lasting comfort and elegance.';
        $story2_title = get_post_meta($product->get_id(), '_fjord_story_block_2_title', true) ?: 'Quality That Lasts a Lifetime';
        $story2_text = get_post_meta($product->get_id(), '_fjord_story_block_2_text', true) ?: 'We use sustainable materials and expert craftsmanship to ensure every piece stands the test of time, with beauty that only improves with age.';
        ?>
        <div class="fjord-product-page__story-row fjord-product-page__story-row--text-left">
          <div class="fjord-product-page__story-media">
            <?php
            $story_image_one = $image_ids[1] ?? $image_ids[0] ?? 0;
            if ($story_image_one) {
              echo wp_get_attachment_image($story_image_one, 'large', false, ['loading' => 'lazy']);
            } else {
              echo wc_placeholder_img('large');
            }
            ?>
          </div>
          <div class="fjord-product-page__story-card">
            <h3><?php echo wp_kses_post($story1_title); ?></h3>
            <p><?php echo wp_kses_post($story1_text); ?></p>
          </div>
        </div>

        <div class="fjord-product-page__story-row">
          <div class="fjord-product-page__story-card">
            <h3><?php echo wp_kses_post($story2_title); ?></h3>
            <p><?php echo wp_kses_post($story2_text); ?></p>
          </div>
          <div class="fjord-product-page__story-media">
            <?php
            $story_image_two = $image_ids[2] ?? $image_ids[0] ?? 0;
            if ($story_image_two) {
              echo wp_get_attachment_image($story_image_two, 'large', false, ['loading' => 'lazy']);
            } else {
              echo wc_placeholder_img('large');
            }
            ?>
          </div>
        </div>
      </section>

      <?php
      $related_ids = wc_get_related_products($product->get_id(), 4);
      if ($related_ids) :
        $related_query = new WP_Query([
          'post_type' => 'product',
          'post__in' => $related_ids,
          'posts_per_page' => 4,
          'orderby' => 'post__in',
        ]);
        ?>
        <section class="fjord-product-page__related">
            <h4 class="fjord-product-page__related-title">También te puede interesar</h4>
          <div class="fjord-product-page__related-grid">
            <?php while ($related_query->have_posts()) : ?>
              <?php $related_query->the_post(); ?>
              <?php wc_get_template_part('content', 'product'); ?>
            <?php endwhile; ?>
          </div>
        </section>
        <?php wp_reset_postdata(); ?>
      <?php endif; ?>

      <section class="fjord-product-page__social-row">
        <?php
        $fjord_categories = get_terms([
          'taxonomy' => 'product_cat',
          'hide_empty' => false,
          'number' => 4,
          'exclude' => [get_option('default_product_cat')],
        ]);
        if (!is_wp_error($fjord_categories) && !empty($fjord_categories)) :
          foreach ($fjord_categories as $category) :
            $category_link = get_term_link($category);
            if (is_wp_error($category_link)) {
              continue;
            }
            ?>
            <a class="fjord-product-page__social-pill" href="<?php echo esc_url($category_link); ?>" aria-label="<?php echo esc_attr($category->name); ?>">
              <?php echo esc_html($category->name); ?>
            </a>
          <?php
          endforeach;
        endif;
        ?>
      </section>
    <?php endwhile; ?>
    <?php do_action('woocommerce_after_single_product'); ?>
  </div>
</main>

<?php get_footer(); ?>
