<?php

if (!defined('ABSPATH')) { exit; }

$cpt = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::POST_TYPE : 'aieo_competition';

$pid = isset($attributes['competitionId']) ? (int) $attributes['competitionId'] : 0;
if ($pid <= 0 && isset($block) && is_object($block) && !empty($block->context['postId'])) {
    $ctx = (int) $block->context['postId'];
    if ($ctx > 0 && get_post_type($ctx) === $cpt) { $pid = $ctx; }
}
if ($pid <= 0 && function_exists('is_singular') && is_singular($cpt)) {
    $pid = (int) get_queried_object_id();
}
if ($pid <= 0 || get_post_type($pid) !== $cpt) {
    return; 
}

$name  = get_the_title($pid);
$desc  = (string) get_post_meta($pid, '_aieo_comp_short_desc', true);
$gf_id = (int) get_post_meta($pid, '_aieo_comp_gf_form_id', true);
$img_d = (int) get_post_meta($pid, '_aieo_comp_image_desktop', true);
$img_m = (int) get_post_meta($pid, '_aieo_comp_image_mobile', true);
$links = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::share_links($pid) : array();

$state      = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::schedule_state($pid) : 'live';
$is_manager = current_user_can('edit_post', $pid) || current_user_can('manage_options');
$start_disp = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::fmt_dt(get_post_meta($pid, AIEO_Competition_CPT::META_START, true)) : '';
$end_disp   = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::fmt_dt(get_post_meta($pid, AIEO_Competition_CPT::META_END, true)) : '';

$announce_raw  = class_exists('AIEO_Competition_CPT') ? (string) get_post_meta($pid, AIEO_Competition_CPT::META_ANNOUNCE_AT, true) : '';
$announce_disp = ($announce_raw !== '' && class_exists('AIEO_Competition_CPT')) ? AIEO_Competition_CPT::fmt_dt($announce_raw) : '';
$winners_html  = class_exists('AIEO_Competition_CPT') ? (string) get_post_meta($pid, AIEO_Competition_CPT::META_WINNERS_ANNOUNCE, true) : '';
$winners       = ($state === 'ended' && class_exists('AIEO_Competition_Participants')) ? AIEO_Competition_Participants::get_winners($pid) : array();

$hero = '';
if ($img_d && $img_m) {
    $hero .= '<img class="aieo-competition__img aieo-competition__img--mobile" src="' . esc_url((string) wp_get_attachment_image_url($img_m, 'large')) . '" alt="' . esc_attr($name) . '" loading="eager">';
    $hero .= '<img class="aieo-competition__img aieo-competition__img--desktop" src="' . esc_url((string) wp_get_attachment_image_url($img_d, 'full')) . '" alt="' . esc_attr($name) . '" loading="eager">';
} elseif ($img_d || $img_m) {
    $one  = $img_d ?: $img_m;
    $size = $img_d ? 'full' : 'large';
    $hero .= '<img class="aieo-competition__img aieo-competition__img--single" src="' . esc_url((string) wp_get_attachment_image_url($one, $size)) . '" alt="' . esc_attr($name) . '" loading="eager">';
}

$wrapper = function_exists('get_block_wrapper_attributes')
    ? get_block_wrapper_attributes(array('class' => 'aieo-competition'))
    : 'class="aieo-competition"';

echo '<section ' . $wrapper . '>'; 

if ($hero !== '') {
    echo '<div class="aieo-competition__hero">' . $hero . '</div>'; 
}

echo '<div class="aieo-competition__body">';
echo '<h1 class="aieo-competition__title">' . esc_html($name) . '</h1>';
if ($desc !== '') {
    echo '<div class="aieo-competition__desc">' . wp_kses_post(wpautop($desc)) . '</div>';
}

if ($start_disp !== '' || $end_disp !== '') {
    echo '<div class="aieo-competition__schedule">';
    if ($start_disp !== '') {
        echo '<span class="aieo-competition__sched-item"><strong>' . esc_html__('Starts:', 'ai-eshop-optimizer') . '</strong> ' . esc_html($start_disp) . '</span>';
    }
    if ($end_disp !== '') {
        $end_label = ($state === 'ended') ? esc_html__('Ended:', 'ai-eshop-optimizer') : esc_html__('Ends:', 'ai-eshop-optimizer');
        echo '<span class="aieo-competition__sched-item"><strong>' . $end_label . '</strong> ' . esc_html($end_disp) . '</span>';
    }
    echo '</div>';
}

$show_form = ($state === 'live') || $is_manager;

if ($is_manager && $state !== 'live') {
    $note = ($state === 'before')
        ? __('Preview (shop manager): this competition hasn’t started — visitors see the “coming soon” notice.', 'ai-eshop-optimizer')
        : __('Preview (shop manager): this competition has ended — visitors see the “ended” message.', 'ai-eshop-optimizer');
    echo '<p class="aieo-competition__admin-note">' . esc_html($note) . '</p>';
}

$comp_settings = (array) get_option('aieo_competitions_settings', array());
if (!$is_manager && $state === 'before') {
    $soon = (isset($comp_settings['msg_soon']) && $comp_settings['msg_soon'] !== '')
        ? (string) $comp_settings['msg_soon']
        : ($start_disp !== ''
            ? __('This competition opens on %s. Check back soon!', 'ai-eshop-optimizer')
            : __('This competition hasn’t started yet. Check back soon!', 'ai-eshop-optimizer'));
    if (strpos($soon, '%s') !== false) {
        $soon = $start_disp !== '' ? sprintf($soon, $start_disp) : trim(str_replace('%s', '', $soon));
    }
    echo '<div class="aieo-competition__notice aieo-competition__notice--soon">' . esc_html($soon) . '</div>';
} elseif (!$is_manager && $state === 'ended') {
    $ended = (isset($comp_settings['msg_ended']) && $comp_settings['msg_ended'] !== '')
        ? (string) $comp_settings['msg_ended']
        : __('This competition has ended. Thank you to everyone who entered!', 'ai-eshop-optimizer');
    echo '<div class="aieo-competition__notice aieo-competition__notice--ended">' . esc_html($ended) . '</div>';
}

if ($show_form) {
    if ($gf_id > 0 && class_exists('GFForms')) {
        echo '<div class="aieo-competition__form">' . do_shortcode('[gravityform id="' . $gf_id . '" title="false" description="false" ajax="true"]') . '</div>'; 
    } elseif ($gf_id > 0) {
        echo '<p class="aieo-competition__form-missing">' . esc_html__('Entry form unavailable (Gravity Forms is inactive).', 'ai-eshop-optimizer') . '</p>';
    }
}

if (!empty($winners)) {
    echo '<div class="aieo-competition__winners">';
    echo '<h2 class="aieo-competition__winners-title">' . esc_html__('🏆 Winners', 'ai-eshop-optimizer') . '</h2>';
    echo '<ul class="aieo-competition__winners-list">';
    foreach ($winners as $w) {
        echo '<li class="aieo-competition__winner">' . esc_html(AIEO_Competition_CPT::winner_public_name($w)) . '</li>';
    }
    echo '</ul>';
    if ($winners_html !== '') {
        echo '<div class="aieo-competition__announcement">' . wp_kses_post(wpautop($winners_html)) . '</div>'; 
    }
    echo '</div>';
} elseif ($announce_disp !== '') {
    $atext = (isset($comp_settings['msg_announce']) && $comp_settings['msg_announce'] !== '')
        ? (string) $comp_settings['msg_announce']
        : __('🏆 The winners will be announced on %s.', 'ai-eshop-optimizer');
    $atext = (strpos($atext, '%s') !== false) ? sprintf($atext, $announce_disp) : trim($atext . ' ' . $announce_disp);
    echo '<div class="aieo-competition__notice aieo-competition__notice--announce">' . esc_html($atext) . '</div>';
}

$share = ($state === 'ended') ? array() : array_filter(array(
    'facebook'  => isset($links['facebook'])  ? $links['facebook']  : '',
    'tiktok'    => isset($links['tiktok'])     ? $links['tiktok']     : '',
    'instagram' => isset($links['instagram'])  ? $links['instagram']  : '',
));
if (!empty($share)) {
    echo '<div class="aieo-competition__share">';
    echo '<span class="aieo-competition__share-label">' . esc_html__('Share:', 'ai-eshop-optimizer') . '</span>';
    foreach ($share as $net => $url) {
        echo '<a class="aieo-competition__share-btn aieo-competition__share-btn--' . esc_attr($net) . '" href="' . esc_url($url) . '" target="_blank" rel="noopener nofollow">' . esc_html(ucfirst($net)) . '</a>';
    }
    echo '</div>';
}

echo '</div>'; 
echo '</section>';
