<?php

//$slug = sanitize_title($term->name);

// === Styling setup ===
$layout = get_theme_mod("firefly_thing_layout_$slug", 'list');
$style_key = "{$layout}_{$slug}";

$thumb_width   = get_theme_mod("firefly_thing_thumb_width_$style_key", get_theme_mod("firefly_thing_thumb_width_$slug", 300));
$thumb_height  = get_theme_mod("firefly_thing_thumb_height_$style_key", get_theme_mod("firefly_thing_thumb_height_$slug", 300));
$image_padding = get_theme_mod("firefly_thing_image_padding_$slug", '0px');
$panel_margin  = get_theme_mod("firefly_thing_panel_margin_$slug", '10px');
$panel_border  = get_theme_mod("firefly_thing_border_$slug", '1px');

$panel_margin_top    = get_theme_mod("firefly_panel_margin_top_$slug", '10px');
$panel_margin_bottom = get_theme_mod("firefly_panel_margin_bottom_$slug", '10px');
$panel_padding_top   = get_theme_mod("firefly_panel_padding_top_$slug", '10px');


$text_colour_key       = get_theme_mod("firefly_thing_text_colour_$slug", 'black');
$heading_colour_key       = get_theme_mod("firefly_thing_heading_colour_$slug", 'black');
$background_colour_key = get_theme_mod("firefly_thing_background_colour_$slug", 'white');
$line_colour_key       = get_theme_mod("firefly_thing_line_colour_$slug", 'black');
$panel_colour_key      = get_theme_mod("firefly_thing_panel_colour_$slug", 'white');
$galleryyesorno      = get_theme_mod("firefly_thing_image_display_mode_$slug", 'single');


$heading_colour = match ($heading_colour_key) {
    'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
    'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
    'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
    'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
    'white'   => '#ffffff',
    default   => '#000000',
};


$text_colour = match ($text_colour_key) {
    'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
    'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
    'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
    'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
    'white'   => '#ffffff',
    default   => '#000000',
};

$background_colour = match ($background_colour_key) {
    'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
    'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
    'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
    'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
    'white'   => '#ffffff',
    default   => '#ffffff',
};

$line_colour = match ($line_colour_key) {
    'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
    'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
    'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
    'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
    'white'   => '#ffffff',
    default   => '#000000',
};

$panel_colour = match ($panel_colour_key) {
    'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
    'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
    'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
    'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
    'white'   => '#ffffff',
    default   => '#ffffff',
};

// === Start Container
echo "<div class='thing-container-$slug'>";

$haslinks   = get_theme_mod("firefly_thing_link_to_page_$slug",1);
$post_slug = sanitize_title(get_the_title());


// === Loop
while ($query->have_posts()) {
    $query->the_post();


  
    $post_id = get_the_ID();
    
$link = esc_url(site_url("/$post_id/$slug/$post_slug"));
$onclick = $haslinks ? "onclick=\"window.location.href='$link'\"" : '';

     
/* draft? */
$is_draft    = get_post_status() === 'draft';
$draft_class = $is_draft ? ' firefly-draft' : '';

echo '<div class="thing-panel-' . esc_attr( $slug ) . $draft_class . '">';



    // Admin Tools
    if (current_user_can('manage_options')) {
        $template_file = get_stylesheet_directory() . "/firefly-admin-thing.php";
        if (file_exists($template_file)) include $template_file;
    }





    if ($galleryyesorno == "single") {

        // === Single Image ===
$gallery_images = get_post_meta(get_the_ID(), 'thing_gallery', true);
$thumbnail_id   = get_post_thumbnail_id();
$image_id       = null;

// Prefer thumbnail if available
if ($thumbnail_id) {
    $image_id = $thumbnail_id;
} elseif (is_array($gallery_images) && !empty($gallery_images)) {
    $image_id = $gallery_images[0];
}

if ($image_id) {
    if ($haslinks == 1) {
        echo "<a href='$link'>";
    }

    echo '<div class="firefly-gallery-wrapper" style="width:' . esc_attr($thumb_width) . 'px;height:' . esc_attr($thumb_height) . 'px;">';
 $alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );

echo wp_get_attachment_image( $image_id, 'medium', false, [
    'style'   => 'width:100%;height:100%;object-fit:cover;',
    'loading' => 'lazy',
    'alt'     => $alt !== '' ? $alt : get_the_title(),   // fallback = post title
     'title'   => $title !== '' ? $alt : get_the_title(),
] );
    echo '</div>';

    if ($haslinks == 1) {
        echo "</a>";
    }
}




    }
    else
    {
    // Image
 $gallery_images = get_post_meta(get_the_ID(), 'thing_gallery', true);
$thumbnail_id = get_post_thumbnail_id();

// Combine all images (featured first if exists)
$all_images = [];
if ($thumbnail_id) {
    $all_images[] = $thumbnail_id;
}
if (is_array($gallery_images)) {
    foreach ($gallery_images as $image_id) {
        if ($image_id != $thumbnail_id) {
            $all_images[] = $image_id;
        }
    }
}

// Display image gallery or fallback
if (!empty($all_images)) {
    echo '<div class="firefly-gallery-wrapper" style="width:' . esc_attr($thumb_width) . 'px;height:' . esc_attr($thumb_height) . 'px;">';





        if ($haslinks == 1) {
            echo "<a href='$link'>";
        }


    foreach ($all_images as $index => $image_id) {
        $opacity = $index === 0 ? '1' : '0';
        echo '<div class="firefly-gallery-image" style="opacity:' . $opacity . ';transition:opacity 0.5s ease;">';
        echo wp_get_attachment_image($image_id, 'medium', false, [
            'style' => 'width:100%;height:100%;object-fit:cover;',
            'loading' => 'lazy',
        ]);
        echo '</div>';
    }

    echo '</div>';

    echo '
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const gallery = document.querySelectorAll(".firefly-gallery-wrapper");
        gallery.forEach(wrapper => {
            const images = wrapper.querySelectorAll(".firefly-gallery-image");
            if (images.length <= 1) return;

            let currentIndex = 0;
            let nextIndex = 1;

            function cycleImages() {
                images[currentIndex].style.opacity = "0";
                images[nextIndex].style.opacity = "1";
                currentIndex = nextIndex;
                nextIndex = (nextIndex + 1) % images.length;
                wrapper.dataset.timeoutId = setTimeout(cycleImages, 3000);
            }

            wrapper.dataset.timeoutId = setTimeout(cycleImages, 3000);

            wrapper.addEventListener("mouseenter", () => {
                clearTimeout(wrapper.dataset.timeoutId);
            });

            wrapper.addEventListener("mouseleave", () => {
                wrapper.dataset.timeoutId = setTimeout(cycleImages, 3000);
            });
        });
    });
    </script>
    ';
} else {
    echo '<div class="thing-image-' . esc_attr($slug) . '" style="width:' . esc_attr($thumb_width) . 'px;height:' . esc_attr($thumb_height) . 'px;">';
    echo get_the_post_thumbnail(get_the_ID(), 'medium', [
        'style' => 'width:100%;height:100%;object-fit:cover;display:block;',
    ]);
    echo '</div>';
}
    if ($haslinks == 1) {
        echo "</a>";
    }
    }





        $post_id = get_the_ID();
    $is_sold = get_post_meta( $post_id, 'sold', true );



// === Overlay Text (only show if not empty) ===
$overlay_text  = get_post_meta($post_id, 'firefly_overlay_text', true);
$overlay_style = get_post_meta($post_id, 'firefly_overlay_style', true); // e.g., 'red', '#ff0000', 'rgb(255,0,0)'

// Fallback if empty
$bg_colour = $overlay_style ? $overlay_style : 'green';
$text_colour = '#fff'; // keep white text by default

if ($overlay_text) {
    // If SOLD is shown, add extra top margin to separate the two banners
    $extra_top = $is_sold ? '20px' : '0';

    echo '<div class="firefly-overlay"
              style="color:' . esc_attr($text_colour) . ';
                     font-weight:bold;
                     background-color:' . esc_attr($bg_colour) . ';
                     text-align:center;
                     font-size:18px;
                     line-height:1.4;
                     margin-top:' . esc_attr($extra_top) . ';
                     z-index:9998;">
              <div style="padding:8px 5px;">' . esc_html($overlay_text) . '</div>
          </div>';
}



      if ( $is_sold ) {
        echo '<div style="color:white;font-weight:bold;background-color:red;padding:10px;text-align:center;font-size:60px;margin-top:-80px;z-index:9999;"><div style="padding-top:10px;padding-bottom:10px;">SOLD!</div></div>';
      }


    $is_soldout = get_post_meta( $post_id, 'soldout', true );

      if ( $is_soldout ) {
        echo '<div style="color:white;font-weight:bold;background-color:red;padding:10px;text-align:center;margin-top:-50px;z-index:9999;">SOLD OUT!</div>';
      }




      

// === Overlay Text (only show if not empty) ===
$overlay_text  = get_post_meta( $post_id, 'firefly_overlay_text', true );
$overlay_style = get_post_meta( $post_id, 'firefly_overlay_style', true );

// map styles to colors
$style_colors = [
    'green' => ['bg' => '#28a745', 'color' => '#fff'],
    'red'   => ['bg' => '#dc3545', 'color' => '#fff'],
    'blue'  => ['bg' => '#007bff', 'color' => '#fff'],
    'purple'  => ['bg' => '#d0f549ff', 'color' => '#fff'],
];

if ( $overlay_text ) {
    $style = $style_colors[ $overlay_style ] ?? $style_colors['green'];

    // If SOLD is shown, add extra margin so they don't overlap
    $margin_top = $is_sold ? '20px' : '-80px';

}





// === Overlay Text (only show if not empty) ===
$overlay_text = (string) get_post_meta($post_id, 'firefly_overlay_text', true);
$overlay_hex  = (string) get_post_meta($post_id, 'firefly_overlay_style', true);

// Normalise to a valid 6-digit HEX with a leading '#'
if (preg_match('/^#?[0-9A-Fa-f]{6}$/', $overlay_hex)) {
  $bg_hex = '#' . strtoupper(ltrim($overlay_hex, '#'));
} else {
  // Fallback if nothing valid is saved
  $bg_hex = '#003366'; // deep blue works well with white text
}


    // Info Block
    echo '<div class="thing-info">';
    echo '<div class="thing-name">' ;
    
        if ($haslinks == 1) {
        echo "<a href='$link'>";
    }

    
    echo  esc_html(get_the_title()) ;

        if ($haslinks == 1) {
        echo "</a>";
    }

    
    echo '</div>';


    

$firefly_thing_excerpt_length      = get_theme_mod("firefly_thing_excerpt_length_$slug", 0);

if ($firefly_thing_excerpt_length > 0) {

    // Get description (use excerpt if set, fallback to content)
    $raw_description = get_the_excerpt();
    if (empty($raw_description)) {
        $raw_description = strip_tags(get_the_content()); // fallback to full content, no HTML
    }

    // Count total words
    $words = preg_split('/\s+/', trim($raw_description));
    $word_count = count($words);

    // Trim to limit
    $trimmed = implode(' ', array_slice($words, 0, $firefly_thing_excerpt_length));

    // Add ellipsis if it's longer than allowed
    if ($word_count > $firefly_thing_excerpt_length) {
        $trimmed .= '...';
    }

    // Output
    echo '<div class="thing-description">';
    echo esc_html($trimmed);
    echo '</div>';
}

 $price_output = '';
$other_fields_output = [];

foreach ($list_fields as $field_raw) {
    $is_checkbox = str_starts_with($field_raw, '*');
    $field = ltrim($field_raw, '*');
      //  $key = sanitize_key($field);
          
      //  $key = str_replace(" ", "", $field);
       //     $key = str_replace("/", "", $key);
      //      $key = str_replace('"', "", $key);
      //      $key = str_replace("'", "", $key);
       //     $key = strtolower($key);

$key = thing_meta_key( $field );

    $val = get_post_meta(get_the_ID(), $key, true);

    if ($val !== '') {
        $output = $is_checkbox ? ($val ? '✅' : '❌') : esc_html($val);

        if (strtolower($field) === 'price') {
              $price_output = '<div class="thing-price">';
                                                            
                                            
                                    if ($haslinks == 1) {
                                        $price_output .= "<a href='$link' style='color:white;'>";
                                    }



                                    
                                    $price_output .= '$' . str_replace("$", "", $output) ;
                                    
                                      if ($haslinks == 1) {
                                        $price_output .= "</a>";
                                    }

                            $price_output .=    '</div>';
        } else {
            $other_fields_output[] = '<div class="thing-field">' . esc_html($field) . ': ' . $output . '</div>';
        }
    }
}

// Output all non-price fields
foreach ($other_fields_output as $field_html) {
    echo $field_html;
}

// Output price at the end
echo $price_output;


   

    echo '</div>'; // .thing-info
    echo '</div>'; // .thing-panel
}

wp_reset_postdata();
echo "</div>"; // .thing-container



$text_align = get_theme_mod("firefly_thing_text_align_$slug", 'left');

$thing_heading_font_size = get_theme_mod("firefly_thing_heading_size_$slug", '36px');

$thing_description_font_size = get_theme_mod("firefly_thing_description_font_size_$slug", '18px');




$thing_heading_font_family = get_theme_mod("firefly_thing_heading_font_$slug", '18px');
$thing_description_font_family = get_theme_mod("firefly_thing_description_font_$slug", '18px');

$thing_custom_fields_font_size = get_theme_mod("firefly_thing_custom_fields_font_size_$slug", '18px');
$thing_headng_padding_top = get_theme_mod("firefly_panel_heading_padding_top_$slug", '18px');
$thing_headng_padding_bottom = get_theme_mod("firefly_panel_heading_padding_bottom_$slug", '18px');
$thing_description_padding_bottom = get_theme_mod("firefly_panel_description_padding_bottom_$slug", '18px');
$firefly_panel_padding_leftright = get_theme_mod("firefly_panel_padding_leftright_$slug", '10px');

$panel_padding_bottom = get_theme_mod("firefly_panel_padding_bottom_$slug", '10px');
$thing_heading_weight = get_theme_mod("firefly_thing_heading_weight_$slug", '10px');

$firefly_container_padding_top = get_theme_mod("firefly_container_padding_top_$slug", '10px');
$firefly_container_padding_bottom = get_theme_mod("firefly_container_padding_bottom_$slug", '10px');
$align_price_bottom = get_theme_mod("firefly_align_price_bottom_$slug") ? true : false;



// === Output CSS
echo "
<style>


.firefly-overlay {
  display: inline-block;    /* shrink-wrap to content */
  width: 100%;              /* span full card width */
  margin-bottom: 0px;      /* consistent gap before heading */
}


.thing-container-$slug {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 30px;
    padding: 20px;
    background: {$background_colour};

        margin-top:{$panel_margin_top};
    margin-bottom:{$panel_margin_bottom};
    padding-top:{$firefly_container_padding_top};
    padding-bottom:{$firefly_container_padding_bottom};

}

.thing-panel-$slug {
    background: {$panel_colour};
    border: {$panel_border} solid {$line_colour};

    border-radius: 10px;
    overflow: hidden;
    width: 300px;
    text-align: {$text_align};
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: box-shadow 0.3s ease;
    display: flex;
    flex-direction: column;
    padding-bottom:{$panel_padding_bottom};
}

.thing-panel-$slug:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.thing-image-$slug {
    width: {$thumb_width}px;
    height: {$thumb_height}px;
    overflow: hidden;
    position: relative;
    display: block;
}




.thing-image-$slug img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.thing-name {
    font-family:{$thing_heading_font_family};
    font-size: {$thing_heading_font_size};
    font-weight: 600;
    color: {$heading_colour};
    line-height: 1.4;
    margin-top: {$thing_headng_padding_top};
     margin-bottom: {$thing_headng_padding_bottom};
     font-weight:{$thing_heading_weight};

}

.thing-name a {
   color: {$heading_colour} !important;
}
.thing-info {
    font-family:{$thing_description_font_family};
    padding-left:{$firefly_panel_padding_leftright};
    padding-right:{$firefly_panel_padding_leftright};
    display: flex;
    flex-direction: column;
    gap: 6px;
    font-family: 'Segoe UI', sans-serif;
  
}




.thing-field {
   font-family:{$thing_description_font_family};
         font-size: {$thing_custom_fields_font_size};
     color: {$text_colour};
    line-height: 1.3;
}

.thing-description {
   font-family:{$thing_description_font_family};
    font-size: {$thing_description_font_size};
     color: {$text_colour};
    line-height: 1.3;
      margin-bottom: {$thing_description_padding_bottom};
}

.thing-price {
    font-size: 1.3rem;
    font-weight: 600;
    color: white;
    background: #0079c1;
    padding: 10px 18px;
    display: inline-block;
    margin-top: 10px;
    border-radius: 4px;
    width: fit-content;
}

.thing-link,
.thing-link:hover,
.thing-link:visited,
.thing-link:active {
    text-decoration: none !important;
}

.thing-link * {
    text-decoration: none !important;
}

.thing-link .thing-name {
    text-decoration: none !important;
}


.firefly-gallery-wrapper {
    position: relative;
    width: <?php echo esc_attr($thumb_width); ?>px;
    height: <?php echo esc_attr($thumb_height); ?>px;
    overflow: hidden;
    line-height: 0;
    background-color: #f0f0f0; /* optional: helps catch uninitialized blank space */
}

.firefly-gallery-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.firefly-gallery-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    object-position: center center;
}



        .firefly-draft          { filter: grayscale(1);  }
.firefly-draft img      { filter: grayscale(1);  }

.firefly-draft .thing-name,
.firefly-draft .thing-field,
.firefly-draft .thing-description {
    color:#777 !important;
    text-decoration:line-through;
}

@media (max-width: 768px) {
    .thing-panel-$slug {
        flex-direction: column;
        margin-left: 15px;
        margin-right: 15px;
    
    }

    .firefly-gallery-layout {
        flex-direction: column;
        align-items: center;
    }

    .firefly-gallery-wrapper {
        width: 100%;
        aspect-ratio: {$thumb_width}/{$thumb_height};
        margin-bottom: 15px;
}

.firefly-thing-info {
        margin-left: 15px !important;
        margin-right: 15px !important;
        display:block;
    }
}



";



if ($align_price_bottom) {
    echo "

.thing-panel-$slug {
    display: flex;
    flex-direction: column;
}

.thing-info {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}

.thing-price {
    margin-top: auto;
}

";
}

echo "

</style>
";
?>
