<?php
namespace NeoRename\NeoRenameAltText; if (!defined("ABSPATH")) { die("neoWP direct access not allowed"); }

\NeoRename\NeoGlobal\add_action_hook("neo_init", function () {
    $render_setting_callback = function () {
        ?>
        <neo-setting-neo-rename id="neo-rename-alt-text--settings">
            <div slot="left">
                <h3><?php \NeoRename\NeoGlobal\echo_neo__("Generate Alt-Texts", "Alt-Texte generieren") ?></h3>
                <p><?php \NeoRename\NeoGlobal\echo_neo__("Automatically generate missing alt texts from image titles to enhance SEO.", "Fehlende Alt-Texte automatisch aus dem Bildtitel generieren, um SEO zu verbessern.") ?></p>
            </div>
            <div slot="right">
                <?php \NeoRename\NeoGlobal\echo_switch_for_option("neo_rename_alt_text__generation_enabled", \NeoRename\NeoGlobal\neo__("Alt-Texts", "Alt-Texte")) ?> 
            </div>
        </neo-setting-neo-rename><?php
    };
    \NeoRename\NeoGlobal\call_interface_func_implemented('\NeoRename\NeoSettings\interface_add_neo_setting_20260326')("neo-rename-alt-text", $render_setting_callback);
});

function get_generated_alt_text($media_id) {
    return get_post($media_id)?->post_title;
}

\NeoRename\NeoGlobal\frontend_image_hook_register_callback(function ($get_attr, $set_attr, $image_file_path) {
    if (!\NeoRename\NeoGlobal\option__neo_rename_alt_text__generation_enabled()) { return; }
    $existing_alt = $get_attr("alt") ?: "";
    $filename = basename($image_file_path); $filename_no_ext = pathinfo($filename, PATHINFO_FILENAME);
    $normalize = function ($s) { return str_replace(["-", "_", ".", " "], "", strtolower($s)); };
    if (!(trim($existing_alt) === "" || $normalize($existing_alt) === $normalize($filename) || $normalize($existing_alt) === $normalize($filename_no_ext))) { return; }
    $img_post_id = attachment_url_to_postid(str_replace(\NeoRename\NeoGlobal\uploads_dir(), \NeoRename\NeoGlobal\uploads_url(), $image_file_path));
    if (!$img_post_id) { return; }
    $title = get_generated_alt_text($img_post_id);
    if (!($title && trim($title))) { return; }
    $set_attr("alt", $title);
});

\NeoRename\NeoGlobal\add_action_hook("attachment_submitbox_misc_actions:11", function () {
    $post_for_info = get_post();
    if (!$post_for_info) { return; }
    if (!\NeoRename\NeoGlobal\option__neo_rename_alt_text__generation_enabled()) { return; }
    $generated_title = get_generated_alt_text($post_for_info->ID);
    if (!($generated_title && trim($generated_title))) { return; }
    ?>
    <?php \NeoRename\NeoGlobal\backend_page_script_tag_start(["type" => "module"]); ?>
        import { observeOnce, addEventListenerWithInitialCall } from "<?php echo esc_url(\NeoRename\NeoGlobal\plugin_url()) ?>/_global--observer.js";
        import { neo__ } from "<?php echo esc_url(\NeoRename\NeoGlobal\plugin_url()) ?>/_global--translation.js";

        observeOnce("#attachment_alt", (attachmentAltTextAreaNode) => {
            attachmentAltTextAreaNode.setAttribute("placeholder", <?php echo \NeoRename\NeoGlobal\php_to_js_object($generated_title) /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?>); /* phpcs:ignore -> The WP Plugin Checker warning can be ignored here because php_to_js_object() produces safely escaped JavaScript output. */
            const explainerTextNode = document.createElement("p"); explainerTextNode.style.marginTop = "0"; explainerTextNode.innerHTML = neo__("💡 neoRename generates the alt text automatically from the image title.", "💡 neoRename generiert den Alt-Text automatisch aus dem Bild-Titel.") + " <a href=\"#\" class=\"neo-rename-alt-text--apply-link\">" + neo__("Apply", "Übernehmen") + "</a>"; attachmentAltTextAreaNode.parentNode.insertBefore(explainerTextNode, attachmentAltTextAreaNode.nextSibling);
            const applyLinkNode = explainerTextNode.querySelector(".neo-rename-alt-text--apply-link"); applyLinkNode.addEventListener("click", (event) => { event.preventDefault(); if (attachmentAltTextAreaNode.value !== "") { return; } attachmentAltTextAreaNode.value = attachmentAltTextAreaNode.getAttribute("placeholder") || ""; attachmentAltTextAreaNode.dispatchEvent(new Event("input", { bubbles: true })); });
            addEventListenerWithInitialCall(attachmentAltTextAreaNode, "input", () => { explainerTextNode.style.display = attachmentAltTextAreaNode.value === "" ? "block" : "none"; });
        });
    <?php \NeoRename\NeoGlobal\backend_page_script_tag_end(); ?><?php
});
