#!/bin/bash
# world_detail_generator.sh - Erzeugt die komplexe Detailseite für eine einzelne Welt

generate_world_detail_page() {
    local current_world_key="$1"
    
    local detail_page_file="${WEB_ROOT_PATH}/world_${current_world_key}.html"
    local current_minetest_world_path="${MINETESTMAPPER_WORLD_DATA_BASE_PATH}${current_world_key}" 
    local world_mt_file="${current_minetest_world_path}/world.mt"
    local web_conf_file="${current_minetest_world_path}/web.conf"
    if [ ! -f "$world_mt_file" ] || [ ! -f "$web_conf_file" ]; then log_message "[${current_world_key}] FEHLER: world.mt oder web.conf fehlt."; return 1; fi

    log_message "[${current_world_key}] Starte Generierung der Detailseite..."

    # --- DATEN SAMMELN ---
    
    local gdal_zoom_levels; gdal_zoom_levels=$(get_config_value_from_file "$web_conf_file" "GDAL2TILES_ZOOM_LEVELS" "$DEFAULT_GDAL2TILES_ZOOM_LEVELS")
    local min_zoom_val; min_zoom_val=$(echo "$gdal_zoom_levels" | cut -d- -f1)
    local max_zoom_val; max_zoom_val=$(echo "$gdal_zoom_levels" | cut -d- -f2)
    if [ -z "$max_zoom_val" ]; then max_zoom_val="$min_zoom_val"; fi
    
    local resolutions_array=""
    local num_zooms=$((max_zoom_val - min_zoom_val + 1))
    for (( i=0; i<num_zooms; i++ )); do
        local current_zoom_level=$((min_zoom_val + i))
        local res=$((2**(max_zoom_val - current_zoom_level)))
        resolutions_array+="${res},"
    done
    resolutions_array="[${resolutions_array%,}]"
    
    local tiles_subdir_name; tiles_subdir_name=$(get_config_value_from_file "$web_conf_file" "TILES_SUBDIR_NAME" "$DEFAULT_TILES_SUBDIR_NAME")
    local web_tiles_rel_path="${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/${tiles_subdir_name}"

    local map_background_color; map_background_color=$(get_config_value_from_file "$web_conf_file" "MM_OPT_BGCOLOR" "$DEFAULT_MM_OPT_BGCOLOR")

    local WORLD_DISPLAY_NAME_PAGE; WORLD_DISPLAY_NAME_PAGE=$(get_config_value_from_file "$web_conf_file" "WORLD_DISPLAY_NAME")
    if [ -z "$WORLD_DISPLAY_NAME_PAGE" ]; then
        WORLD_DISPLAY_NAME_PAGE=$(get_config_value_from_file "$world_mt_file" "world_name" "Welt ${current_world_key}")
    fi

    local SERVER_ADDRESS_PAGE; SERVER_ADDRESS_PAGE=$(get_config_value_from_file "$web_conf_file" "SERVER_ADDRESS" "$DEFAULT_SERVER_ADDRESS")
    local SERVER_PORT_PAGE; SERVER_PORT_PAGE=$(get_config_value_from_file "$web_conf_file" "SERVER_PORT" "$DEFAULT_SERVER_PORT")
    local SERVER_ACCESS_INFO_PAGE; SERVER_ACCESS_INFO_PAGE=$(get_config_value_from_file "$web_conf_file" "SERVER_ACCESS_INFO" "$DEFAULT_SERVER_ACCESS_INFO")

    unset ADMIN_NAME ADMIN_SKIN_URL ADMIN_EMAIL ADMIN_DISCORD ADMIN_MATRIX ADMIN_STEAM ADMIN_TEAMSPEAK ADMIN_MUMBLE WORLD_LONG_DESCRIPTION WORLD_GAME_RULES
    source "$web_conf_file"
    local WORLD_LONG_DESCRIPTION_PAGE="${WORLD_LONG_DESCRIPTION:-$DEFAULT_WORLD_LONG_DESCRIPTION}"
    local WORLD_GAME_RULES_PAGE="${WORLD_GAME_RULES:-}"
    
    local MT_GAMEID="$DEFAULT_GAMEID"; local MT_ENABLE_DAMAGE="false"; local MT_CREATIVE_MODE="false"
    declare -A parsed_mod_packs; declare -a parsed_standalone_mods
    while IFS='=' read -r key value || [ -n "$key" ]; do
        key=$(echo "$key"|xargs); value=$(echo "$value"|xargs)
        case "$key" in
            gameid) MT_GAMEID="$value" ;;
            enable_damage) MT_ENABLE_DAMAGE="$value" ;;
            creative_mode) MT_CREATIVE_MODE="$value" ;;
            load_mod_*) local mod_id="${key#load_mod_}"; mod_id=$(echo "$mod_id"|xargs)
                if [[ "$value" =~ ^mods/([^/]+)/.+ ]]; then local pack_n="${BASH_REMATCH[1]}"; parsed_mod_packs["$pack_n"]="${parsed_mod_packs[$pack_n]} ${mod_id}";
                elif [[ "$value" =~ ^mods/([^/]+)$ ]]; then parsed_standalone_mods+=("$mod_id");
                elif [ -n "$value" ]; then parsed_standalone_mods+=("$mod_id"); fi ;;
        esac;
    done < "$world_mt_file"
    
    local MODS_HTML=""
    if [ ${#parsed_mod_packs[@]} -gt 0 ] || [ ${#parsed_standalone_mods[@]} -gt 0 ]; then
        MODS_HTML+="<ul class='mod-list'>"
        local sorted_pack_names=(); if [ ${#parsed_mod_packs[@]} -gt 0 ]; then mapfile -t sorted_pack_names < <(printf '%s\n' "${!parsed_mod_packs[@]}" | sort); fi
        for pack_name in "${sorted_pack_names[@]}"; do
            MODS_HTML+="<li>+ <a href='https://content.luanti.org/packages/?q=${pack_name}' target='_blank' rel='noopener noreferrer'>${pack_name}</a><ul>"
            local mods_in_pack_str="${parsed_mod_packs[$pack_name]}"
            local sorted_mods_in_pack=(); if [ -n "$mods_in_pack_str" ]; then mapfile -t sorted_mods_in_pack < <(echo "$mods_in_pack_str" | tr ' ' '\n' | grep -v '^\s*$' | sort); fi
            for mod_in_pack in "${sorted_mods_in_pack[@]}"; do
                [ -n "$mod_in_pack" ] && MODS_HTML+="<li>- <a href='https://content.luanti.org/packages/?q=${mod_in_pack}' target='_blank' rel='noopener noreferrer'>${mod_in_pack}</a></li>"
            done
            MODS_HTML+="</ul></li>"
        done
        local sorted_standalone_mods=(); if [ ${#parsed_standalone_mods[@]} -gt 0 ]; then mapfile -t sorted_standalone_mods < <(printf '%s\n' "${parsed_standalone_mods[@]}" | sort); fi
        for solo_mod in "${sorted_standalone_mods[@]}"; do
            [ -n "$solo_mod" ] && MODS_HTML+="<li>- <a href='https://content.luanti.org/packages/?q=${solo_mod}' target='_blank' rel='noopener noreferrer'>${solo_mod}</a></li>"
        done
        MODS_HTML+="</ul>"
    else
        MODS_HTML="<p>Keine Mod-Informationen in world.mt gefunden.</p>"
    fi
    
    local ARCHIVE_HTML=""; local available_archive_dates_js_array="[]"; local -a available_archive_dates_bash=();
    local CURRENT_ARCHIVE_SUBDIR_NAME=$(get_config_value_from_file "$web_conf_file" "ARCHIVE_SUBDIR_NAME" "$DEFAULT_ARCHIVE_SUBDIR_NAME")
    local archive_scan_base_path="${WEB_ROOT_PATH}/${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/${CURRENT_ARCHIVE_SUBDIR_NAME}";
    if [ -d "$archive_scan_base_path" ]; then
        shopt -s nullglob;
        for y_d in "${archive_scan_base_path}"/*/; do
            if [ -d "$y_d" ]; then
                local y=$(basename "$y_d");
                for m_d in "${y_d}"*/; do
                    if [ -d "$m_d" ]; then
                        local m=$(basename "$m_d");
                        for d_f in "${m_d}"*.png; do
                            if [ -f "$d_f" ]; then
                                local d=$(basename "$d_f" .png);
                                if [[ "$y" =~ ^[0-9]{4}$ && "$m" =~ ^[0-9]{2}$ && "$d" =~ ^[0-9]{2}$ ]]; then
                                    available_archive_dates_bash+=("${y}-${m}-${d}");
                                fi;
                            fi;
                        done;
                    fi;
                done;
            fi;
        done;
        shopt -u nullglob;
    fi;
    if [ ${#available_archive_dates_bash[@]} -gt 0 ]; then
        local sorted_dates_str; sorted_dates_str=$(printf '%s\n' "${available_archive_dates_bash[@]}" | sort -r);
        local js_dates_temp_array=(); if [ -n "$sorted_dates_str" ]; then mapfile -t js_dates_temp_array < <(echo "$sorted_dates_str"); fi;
        local js_array_content="";
        if [ ${#js_dates_temp_array[@]} -gt 0 ]; then
            for date_str_loop in "${js_dates_temp_array[@]}"; do
                if [ -n "$date_str_loop" ]; then js_array_content+="\"${date_str_loop}\","; fi;
            done;
            js_array_content=${js_array_content%,};
        fi;
        available_archive_dates_js_array="[${js_array_content}]";
    fi
    local temp_archive_html_file; temp_archive_html_file=$(mktemp)
    local archive_world_rel_to_webroot="/${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/${CURRENT_ARCHIVE_SUBDIR_NAME}"
    render_template "${TEMPLATE_DIR_PATH}/world_detail_archiv.template" "$temp_archive_html_file" \
        "current_world_key" "$current_world_key" \
        "available_archive_dates_js_array" "$available_archive_dates_js_array" \
        "archive_world_rel_to_webroot" "$archive_world_rel_to_webroot" \
        "CACHE_BUSTER" "$CACHE_BUSTER"
    ARCHIVE_HTML=$(<"$temp_archive_html_file")
    rm "$temp_archive_html_file"

    local ADMIN_BOXES_HTML=""
    local num_admins=${#ADMIN_NAME[@]}
    if [ $num_admins -eq 0 ]; then
        ADMIN_BOXES_HTML="<div class='admin-box'><div class='admin-contact-block'><img src='/${SITE_OWNER_ADMIN_SKIN_URL:-$DEFAULT_PLAYER_SKIN_URL}?v=${CACHE_BUSTER}' alt='Admin Skin' class='admin-skin-icon'><div class='admin-text-details'><p><strong class='admin-player-name'>${SITE_OWNER_NAME}</strong></p><div class='contact-links'><a href='mailto:${SITE_OWNER_EMAIL}' class='contact-button' data-title='E-Mail: ${SITE_OWNER_EMAIL}'>Email</a></div></div></div></div>"
    else
        for i in "${!ADMIN_NAME[@]}"; do
            local name="${ADMIN_NAME[$i]}"; local skin_url="${ADMIN_SKIN_URL[$i]:-$DEFAULT_PLAYER_SKIN_URL}"; local email="${ADMIN_EMAIL[$i]}"; local discord="${ADMIN_DISCORD[$i]}"; local matrix="${ADMIN_MATRIX[$i]}"; local steam="${ADMIN_STEAM[$i]}"; local teamspeak="${ADMIN_TEAMSPEAK[$i]}"; local mumble="${ADMIN_MUMBLE[$i]}"
            local contact_links_html=""
            [ -n "$email" ]      && contact_links_html+="<a href='mailto:${email}' class='contact-button' data-title='E-Mail: ${email}'>Email</a>"
            [ -n "$discord" ]    && contact_links_html+="<a href='https://discordapp.com/users/${discord}' target='_blank' rel='noopener noreferrer' class='contact-button' data-title='Discord: ${discord}'>Discord</a>"
            [ -n "$matrix" ]     && contact_links_html+="<a href='https://matrix.to/#/${matrix}' target='_blank' rel='noopener noreferrer' class='contact-button' data-title='Matrix: ${matrix}'>Matrix</a>"
            [ -n "$steam" ]      && contact_links_html+="<a href='${steam}' target='_blank' rel='noopener noreferrer' class='contact-button' data-title='Steam Profil'>Steam</a>"
            [ -n "$teamspeak" ]  && contact_links_html+="<a href='ts3server://${teamspeak}' class='contact-button' data-title='Teamspeak: ${teamspeak}'>Teamspeak</a>"
            [ -n "$mumble" ]     && contact_links_html+="<a href='mumble://${mumble}' class='contact-button' data-title='Mumble: ${mumble}'>Mumble</a>"
            ADMIN_BOXES_HTML+="<div class='admin-box'><div class='admin-contact-block'><img src='/${skin_url}?v=${CACHE_BUSTER}' alt='Admin Skin ${name}' class='admin-skin-icon' onerror=\"this.onerror=null;this.src='/${DEFAULT_PLAYER_SKIN_URL}?v=${CACHE_BUSTER}';\"><div class='admin-text-details'><p><strong class='admin-player-name'>${name}</strong></p></div></div>"; if [ -n "$contact_links_html" ]; then ADMIN_BOXES_HTML+="<div class='contact-links'>${contact_links_html}</div>"; fi; ADMIN_BOXES_HTML+="</div>"
        done
    fi

    local web_unknown_nodes_rel_path="${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/unknown_nodes.txt"
    local unknown_nodes_abs_path="${WEB_ROOT_PATH}/${web_unknown_nodes_rel_path}"
    local map_sub_info_link=""
    if [ -f "$unknown_nodes_abs_path" ]; then
        map_sub_info_link="<span class='map-file-link'><a href='/${web_unknown_nodes_rel_path}?v=${CACHE_BUSTER}' target='_blank'>Fehlende Map-Nodes</a></span>"
    else
        map_sub_info_link="<span class='map-file-link'>&nbsp;</span>"
    fi

    local creative_text="Aus"; local creative_text_class="offline"; if [ "$MT_CREATIVE_MODE" = "true" ]; then creative_text="An"; creative_text_class="online"; fi
    local damage_text="Aus"; local damage_text_class="online"; if [ "$MT_ENABLE_DAMAGE" = "true" ]; then damage_text="An"; damage_text_class="offline"; fi
    
    # --- TEMPLATES RENDERN ---
    local temp_radar_file; temp_radar_file=$(mktemp)
    render_template "${TEMPLATE_DIR_PATH}/world_detail_radar.template" "$temp_radar_file" \
        "current_world_key" "$current_world_key" \
        "map_sub_info_link" "$map_sub_info_link" \
        "web_last_update_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/last_update.txt" \
        "CACHE_BUSTER" "$CACHE_BUSTER" \
        "ARCHIVE_HTML" "$ARCHIVE_HTML" \
        "RESOLUTIONS_JS_ARRAY" "$resolutions_array" \
        "web_tiles_rel_path" "$web_tiles_rel_path" \
        "web_map_info_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/map_info.txt" \
        "map_background_color" "$map_background_color" \
        "DEFAULT_PLAYER_SKIN_URL" "$DEFAULT_PLAYER_SKIN_URL"
    local WORLD_RADAR_HTML; WORLD_RADAR_HTML=$(<"$temp_radar_file")
    rm "$temp_radar_file"

    local temp_playerlist_file; temp_playerlist_file=$(mktemp)
    render_template "${TEMPLATE_DIR_PATH}/world_detail_playerlist.template" "$temp_playerlist_file" \
        "current_world_key" "$current_world_key" \
        "DEFAULT_PLAYER_SKIN_URL" "$DEFAULT_PLAYER_SKIN_URL" \
        "CACHE_BUSTER" "$CACHE_BUSTER"
    local WORLD_PLAYERLIST_HTML; WORLD_PLAYERLIST_HTML=$(<"$temp_playerlist_file")
    rm "$temp_playerlist_file"

    local temp_body_file; temp_body_file=$(mktemp)
    render_template "${TEMPLATE_DIR_PATH}/world_detail_page.template" "$temp_body_file" \
        "WORLD_DISPLAY_NAME_PAGE" "$WORLD_DISPLAY_NAME_PAGE" \
        "current_world_key" "$current_world_key" \
        "STATUS_TEXT_FALLBACK_PAGE" "$DEFAULT_SERVER_STATUS_TEXT_FALLBACK" \
        "MT_GAMEID" "$MT_GAMEID" \
        "creative_text_class" "$creative_text_class" \
        "creative_text" "$creative_text" \
        "damage_text_class" "$damage_text_class" \
        "damage_text" "$damage_text" \
        "SERVER_ADDRESS_PAGE" "$SERVER_ADDRESS_PAGE" \
        "SERVER_PORT_PAGE" "$SERVER_PORT_PAGE" \
        "SERVER_ACCESS_INFO_PAGE" "$SERVER_ACCESS_INFO_PAGE" \
        "ADMIN_BOXES_HTML" "$ADMIN_BOXES_HTML" \
        "WORLD_LONG_DESCRIPTION_PAGE" "$WORLD_LONG_DESCRIPTION_PAGE" \
        "WORLD_GAME_RULES_PAGE" "$WORLD_GAME_RULES_PAGE" \
        "MODS_HTML" "$MODS_HTML" \
        "WORLD_RADAR_HTML" "$WORLD_RADAR_HTML" \
        "WORLD_PLAYERLIST_HTML" "$WORLD_PLAYERLIST_HTML" \
        "web_online_status_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/online_status.txt" \
        "web_last_update_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/last_update.txt" \
        "web_players_txt_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/players.txt" \
        "web_weather_txt_rel_path" "${WEB_MAPS_BASE_SUBDIR}/${current_world_key}/weather.txt" \
        "CACHE_BUSTER" "$CACHE_BUSTER"

    {
        generate_html_header "Welt: ${WORLD_DISPLAY_NAME_PAGE}" "."
        cat "$temp_body_file"
        generate_html_footer
    } > "$detail_page_file"
    rm "$temp_body_file"
    
    log_message "[${current_world_key}] Detailseite erstellt."
}
