/*******************************************************************************
Copyright (c) 2025, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include <sstream>
#include <iostream>
#include <cstring>

#include <tinyxml2.h>
#include <htmlpp/html.h>

#include "plugin.h"

extern "C" {
    namespace blogi::webedit {

        class Image : public EditPlugin {
        private:
            std::string src;
            std::string alt        = "";
            std::string width      = "100%";
            std::string height     = "auto";
            std::string objectFit  = "cover";
            std::string borderRadius = "0";
            std::string linkUrl    = "";
            std::string mediaId    = "";  // mediadb media UUID
            std::string mediaExt   = "webp"; // file extension for mediadb URL
            int         realWidth  = 0;     // actual pixel width for preview
            int         realHeight = 0;     // actual pixel height for preview

            // Mobile overrides (empty = inherit desktop value)
            std::string m_width    = "";
            std::string m_height   = "";

            // Visibility
            bool hidden = false;
            bool m_hidden = false;

            // Fullscreen
            bool fullscreen = false;

            // Custom CSS
            std::string customCss = "";

        public:
            Image() {
                Type = "e66ebcf3-4h87-6g5h-c6e8-1h78f3d878e6";
            }

            virtual ~Image() = default;

            const std::string getName() const override {
                return "Image";
            }

            const std::string getAuthor() const override {
                return "Jan Koester";
            }

            const std::string getVersion() const override {
                return "1.0";
            }

            void logError(const std::string& message) override {
                std::cerr << "ImagePlugin Error (" << getInstanceId().c_str() << "): " << message << std::endl;
            }

            // --- UI Settings ---
            void Settings(libhttppp::HttpRequest &curreq, libhtmlpp::HtmlElement &settings) override {
                libhtmlpp::HtmlElement title("h3");
                title.appendChild(libhtmlpp::TextElement("Image Settings"));
                settings.appendChild(title);

                // Source URL
                libhtmlpp::HtmlElement srcLabel("label");
                srcLabel.appendChild(libhtmlpp::TextElement("Image URL: "));
                settings.appendChild(srcLabel);
                libhtmlpp::HtmlElement srcInput("input");
                srcInput.setAttribute("type", "text");
                srcInput.setAttribute("name", "src");
                srcInput.setAttribute("value", src.c_str());
                srcInput.setAttribute("placeholder", "/path/to/image.jpg");
                settings.appendChild(srcInput);

                // Alt text
                libhtmlpp::HtmlElement altLabel("label");
                altLabel.appendChild(libhtmlpp::TextElement("Alt Text: "));
                settings.appendChild(altLabel);
                libhtmlpp::HtmlElement altInput("input");
                altInput.setAttribute("type", "text");
                altInput.setAttribute("name", "alt");
                altInput.setAttribute("value", alt.c_str());
                settings.appendChild(altInput);

                // Width
                libhtmlpp::HtmlElement wLabel("label");
                wLabel.appendChild(libhtmlpp::TextElement("Width: "));
                settings.appendChild(wLabel);
                libhtmlpp::HtmlElement wInput("input");
                wInput.setAttribute("type", "text");
                wInput.setAttribute("name", "width");
                wInput.setAttribute("value", width.c_str());
                settings.appendChild(wInput);

                // Height
                libhtmlpp::HtmlElement hLabel("label");
                hLabel.appendChild(libhtmlpp::TextElement("Height: "));
                settings.appendChild(hLabel);
                libhtmlpp::HtmlElement hInput("input");
                hInput.setAttribute("type", "text");
                hInput.setAttribute("name", "height");
                hInput.setAttribute("value", height.c_str());
                settings.appendChild(hInput);

                // Object fit
                libhtmlpp::HtmlElement ofLabel("label");
                ofLabel.appendChild(libhtmlpp::TextElement("Object Fit: "));
                settings.appendChild(ofLabel);
                libhtmlpp::HtmlElement ofSelect("select");
                ofSelect.setAttribute("name", "object_fit");
                const char* fits[] = {"cover", "contain", "fill", "none", "scale-down"};
                for (const char* f : fits) {
                    libhtmlpp::HtmlElement opt("option");
                    opt.setAttribute("value", f);
                    if (objectFit == f) opt.setAttribute("selected", "selected");
                    opt.appendChild(libhtmlpp::TextElement(f));
                    ofSelect.appendChild(opt);
                }
                settings.appendChild(ofSelect);

                // Border radius
                libhtmlpp::HtmlElement brLabel("label");
                brLabel.appendChild(libhtmlpp::TextElement("Border Radius: "));
                settings.appendChild(brLabel);
                libhtmlpp::HtmlElement brInput("input");
                brInput.setAttribute("type", "text");
                brInput.setAttribute("name", "border_radius");
                brInput.setAttribute("value", borderRadius.c_str());
                settings.appendChild(brInput);

                // Link URL
                libhtmlpp::HtmlElement lnkLabel("label");
                lnkLabel.appendChild(libhtmlpp::TextElement("Link URL (optional): "));
                settings.appendChild(lnkLabel);
                libhtmlpp::HtmlElement lnkInput("input");
                lnkInput.setAttribute("type", "text");
                lnkInput.setAttribute("name", "link_url");
                lnkInput.setAttribute("value", linkUrl.c_str());
                settings.appendChild(lnkInput);

                // Media file extension
                libhtmlpp::HtmlElement extLabel("label");
                extLabel.appendChild(libhtmlpp::TextElement("Format: "));
                settings.appendChild(extLabel);
                libhtmlpp::HtmlElement extSelect("select");
                extSelect.setAttribute("name", "media_ext");
                const char* exts[] = {"webp", "png", "jpg", "jpeg", "gif", "avif", "svg"};
                for (const char* e : exts) {
                    libhtmlpp::HtmlElement opt("option");
                    opt.setAttribute("value", e);
                    if (mediaExt == e) opt.setAttribute("selected", "selected");
                    opt.appendChild(libhtmlpp::TextElement(e));
                    extSelect.appendChild(opt);
                }
                settings.appendChild(extSelect);
            }

            // --- JSON API ---
            void JsonApi(json_object *request, json_object *response) override {
                if (request == nullptr) {
                    logError("Invalid JSON request received (nullptr).");
                    return;
                }

                json_object *action_obj = nullptr;
                const char *action = nullptr;

                if (json_object_object_get_ex(request, "action", &action_obj)) {
                    action = json_object_get_string(action_obj);
                }

                if (action == nullptr || action[0] == '\0') {
                    logError("No action specified in JsonApi request.");
                    return;
                }

                if (strcmp(action, "modify_bulk") == 0) {
                    json_object *props_obj = nullptr;
                    if (json_object_object_get_ex(request, "properties", &props_obj)) {
                        const char *json_str = json_object_to_json_string_ext(props_obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                        if (json_str) {
                            fromPropertiesJson(json_str);
                        }
                    }
                } else if (strcmp(action, "read") == 0) {
                    json_object *result_obj = json_object_new_object();
                    json_object_object_add(result_obj, "properties", json_object_new_string(toPropertiesJson().c_str()));
                    if (response) {
                        json_object_object_add(response, "data", result_obj);
                    }
                } else if (strcmp(action, "get_schema") == 0) {
                    if (response) {
                        json_object_object_add(response, "schema", getSchemaJson());
                    }
                }

                if (response != nullptr) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Image"));
                }
            }

            // --- XML Persistence ---
            tinyxml2::XMLElement* toXmlObject(tinyxml2::XMLDocument* doc) override {
                tinyxml2::XMLElement* element = doc->NewElement(getName().c_str());
                element->SetAttribute("instance_id", getInstanceId().c_str());
                element->SetAttribute("type_id", getTypeId().c_str());
                element->SetAttribute("src", src.c_str());
                element->SetAttribute("alt", alt.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());
                element->SetAttribute("object_fit", objectFit.c_str());
                element->SetAttribute("border_radius", borderRadius.c_str());
                element->SetAttribute("link_url", linkUrl.c_str());
                element->SetAttribute("media_id", mediaId.c_str());
                element->SetAttribute("media_ext", mediaExt.c_str());
                element->SetAttribute("real_width", realWidth);
                element->SetAttribute("real_height", realHeight);

                // Mobile overrides
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

                // Visibility
                element->SetAttribute("hidden", hidden ? "true" : "false");
                element->SetAttribute("m_hidden", m_hidden ? "true" : "false");

                // Fullscreen
                element->SetAttribute("fullscreen", fullscreen ? "true" : "false");

                if (!customCss.empty()) {
                    tinyxml2::XMLElement* cssEl = doc->NewElement("CustomCss");
                    cssEl->SetText(customCss.c_str());
                    element->InsertEndChild(cssEl);
                }
                return element;
            }

            void fromXmlObject(tinyxml2::XMLElement* xml_data) override {
                const char* val = nullptr;

                val = xml_data->Attribute("src");           if (val) src = val;
                val = xml_data->Attribute("alt");           if (val) alt = val;
                val = xml_data->Attribute("width");         if (val) width = val;
                val = xml_data->Attribute("height");        if (val) height = val;
                val = xml_data->Attribute("object_fit");    if (val) objectFit = val;
                val = xml_data->Attribute("border_radius"); if (val) borderRadius = val;
                val = xml_data->Attribute("link_url");      if (val) linkUrl = val;
                val = xml_data->Attribute("media_id");      if (val) mediaId = val;
                val = xml_data->Attribute("media_ext");     if (val) mediaExt = val;
                xml_data->QueryIntAttribute("real_width", &realWidth);
                xml_data->QueryIntAttribute("real_height", &realHeight);

                // Mobile overrides
                val = xml_data->Attribute("m_width");       if (val) m_width = val;
                val = xml_data->Attribute("m_height");      if (val) m_height = val;

                // Visibility
                val = xml_data->Attribute("hidden");
                if (val) hidden = (strcmp(val, "true") == 0);
                val = xml_data->Attribute("m_hidden");
                if (val) m_hidden = (strcmp(val, "true") == 0);

                // Fullscreen
                val = xml_data->Attribute("fullscreen");
                if (val) fullscreen = (strcmp(val, "true") == 0);

                tinyxml2::XMLElement* cssEl = xml_data->FirstChildElement("CustomCss");
                if (cssEl) {
                    const char* cssVal = cssEl->GetText();
                    if (cssVal) customCss = cssVal;
                }
            }

            // --- JSON Properties Helpers ---
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "src", json_object_new_string(src.c_str()));
                json_object_object_add(obj, "alt", json_object_new_string(alt.c_str()));
                json_object_object_add(obj, "width", json_object_new_string(width.c_str()));
                json_object_object_add(obj, "height", json_object_new_string(height.c_str()));
                json_object_object_add(obj, "object_fit", json_object_new_string(objectFit.c_str()));
                json_object_object_add(obj, "border_radius", json_object_new_string(borderRadius.c_str()));
                json_object_object_add(obj, "link_url", json_object_new_string(linkUrl.c_str()));
                json_object_object_add(obj, "media_id", json_object_new_string(mediaId.c_str()));
                json_object_object_add(obj, "media_ext", json_object_new_string(mediaExt.c_str()));
                json_object_object_add(obj, "real_width", json_object_new_int(realWidth));
                json_object_object_add(obj, "real_height", json_object_new_int(realHeight));
                json_object_object_add(obj, "m_width", json_object_new_string(m_width.c_str()));
                json_object_object_add(obj, "m_height", json_object_new_string(m_height.c_str()));
                json_object_object_add(obj, "hidden", json_object_new_boolean(hidden));
                json_object_object_add(obj, "m_hidden", json_object_new_boolean(m_hidden));
                json_object_object_add(obj, "fullscreen", json_object_new_boolean(fullscreen));
                json_object_object_add(obj, "custom_css", json_object_new_string(customCss.c_str()));
                std::string result = json_object_to_json_string_ext(obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                json_object_put(obj);
                return result;
            }

            void fromPropertiesJson(const std::string &json) {
                json_object *obj = json_tokener_parse(json.c_str());
                if (!obj) return;

                json_object *val_obj = nullptr;
                const char *val = nullptr;

                if (json_object_object_get_ex(obj, "src", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) src = val;
                }
                if (json_object_object_get_ex(obj, "alt", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) alt = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) height = val;
                }
                if (json_object_object_get_ex(obj, "object_fit", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) objectFit = val;
                }
                if (json_object_object_get_ex(obj, "border_radius", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) borderRadius = val;
                }
                if (json_object_object_get_ex(obj, "link_url", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) linkUrl = val;
                }
                if (json_object_object_get_ex(obj, "media_id", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) mediaId = val;
                }
                if (json_object_object_get_ex(obj, "media_ext", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) mediaExt = val;
                }
                if (json_object_object_get_ex(obj, "real_width", &val_obj)) {
                    realWidth = json_object_get_int(val_obj);
                }
                if (json_object_object_get_ex(obj, "real_height", &val_obj)) {
                    realHeight = json_object_get_int(val_obj);
                }
                if (json_object_object_get_ex(obj, "m_width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_width = val;
                }
                if (json_object_object_get_ex(obj, "m_height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_height = val;
                }
                if (json_object_object_get_ex(obj, "hidden", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        hidden = (s && strcmp(s, "true") == 0);
                    } else {
                        if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        hidden = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        hidden = json_object_get_boolean(val_obj);
                    }
                    }
                }
                if (json_object_object_get_ex(obj, "m_hidden", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        m_hidden = (s && strcmp(s, "true") == 0);
                    } else {
                        if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        m_hidden = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        m_hidden = json_object_get_boolean(val_obj);
                    }
                    }
                }
                if (json_object_object_get_ex(obj, "fullscreen", &val_obj)) {
                    if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        fullscreen = (s && strcmp(s, "true") == 0);
                    } else {
                        if (json_object_is_type(val_obj, json_type_string)) {
                        const char *s = json_object_get_string(val_obj);
                        fullscreen = (s && (strcmp(s, "true") == 0 || strcmp(s, "1") == 0));
                    } else {
                        fullscreen = json_object_get_boolean(val_obj);
                    }
                    }
                }
                if (json_object_object_get_ex(obj, "custom_css", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) customCss = val;
                }

                json_object_put(obj);
            }

            // --- Schema ---
            static json_object* getSchemaJson() {
                json_object *arr = json_object_new_array();
                auto addField = [&](const char *key, const char *label, const char *type,
                                    const char *placeholder = nullptr, const char *target = "all",
                                    json_object *options = nullptr, int min = -1,
                                    json_object *visibleWhen = nullptr) {
                    json_object *f = json_object_new_object();
                    json_object_object_add(f, "key", json_object_new_string(key));
                    json_object_object_add(f, "label", json_object_new_string(label));
                    json_object_object_add(f, "type", json_object_new_string(type));
                    if (placeholder) json_object_object_add(f, "placeholder", json_object_new_string(placeholder));
                    json_object_object_add(f, "target", json_object_new_string(target));
                    if (options) json_object_object_add(f, "options", options);
                    if (min >= 0) json_object_object_add(f, "min", json_object_new_int(min));
                    if (visibleWhen) json_object_object_add(f, "visibleWhen", visibleWhen);
                    json_object_array_add(arr, f);
                };
                auto mkOpts = [](std::initializer_list<const char*> vals) {
                    json_object *a = json_object_new_array();
                    for (auto v : vals) json_object_array_add(a, json_object_new_string(v));
                    return a;
                };
                addField("media_id", "Media (from MediaDB)", "media_browse");
                addField("media_ext", "Format", "select", nullptr, "all", mkOpts({"webp","png","jpg","jpeg","gif","avif","svg"}));
                addField("real_width", "Preview Width (px)", "number", nullptr, "all", nullptr, 0);
                addField("real_height", "Preview Height (px)", "number", nullptr, "all", nullptr, 0);
                addField("src", "Image Path (manual)", "text", "/path/to/image.jpg");
                addField("alt", "Alt Text", "text");
                addField("width", "CSS Width", "text", "100%", "desktop");
                addField("height", "CSS Height", "text", "auto", "desktop");
                addField("object_fit", "Object Fit", "select", nullptr, "all", mkOpts({"cover","contain","fill","none","scale-down"}));
                addField("border_radius", "Border Radius", "text", "0");
                addField("link_url", "Link URL", "text", "/page or https://...");
                addField("fullscreen", "Show in Fullscreen", "checkbox");
                addField("hidden", "Hidden", "checkbox", nullptr, "desktop");
                {
                    json_object *hf = json_object_array_get_idx(arr, json_object_array_length(arr) - 1);
                    json_object_object_add(hf, "default", json_object_new_boolean(false));
                }
                addField("m_hidden", "Hidden (Mobile)", "checkbox", nullptr, "mobile");
                addField("m_width", "Width (Mobile)", "text", "e.g. 100%", "mobile");
                addField("m_height", "Height (Mobile)", "text", "e.g. auto", "mobile");
                addField("custom_css", "Custom CSS", "textarea", ".we-xxx { color: red; }");
                return arr;
            }

            // --- HTML Rendering ---
            void Render(libhtmlpp::HtmlElement &el) const override {
                libhtmlpp::HtmlElement wrapper("div");

                // Unique CSS class for responsive targeting
                std::string responsiveClass = std::string("we-") + getInstanceId().c_str();

                std::string renderSrc = src;
                const std::string &pfx = getPrefix();
                if (!renderSrc.empty() && renderSrc[0] == '/' && !pfx.empty() && pfx != "/") {
                    // Only add prefix if src doesn't already start with it
                    if (renderSrc.length() < pfx.length() || renderSrc.substr(0, pfx.length()) != pfx) {
                        renderSrc = pfx + renderSrc;
                    }
                }

                libhtmlpp::HtmlElement img("img");
                img.setAttribute("src", renderSrc.c_str());
                img.setAttribute("alt", alt.c_str());
                img.setAttribute("class", responsiveClass.c_str());

                // Compute effective width/height, auto-calculating from aspect ratio
                std::string effWidth = width;
                std::string effHeight = height;
                if (realWidth > 0 && realHeight > 0) {
                    // If width is a pixel value and height is auto, compute height
                    if (effHeight == "auto" && !effWidth.empty() && effWidth != "auto") {
                        try {
                            // Check if width is a plain number or ends with "px"
                            std::string wVal = effWidth;
                            bool isPx = false;
                            if (wVal.size() > 2 && wVal.substr(wVal.size()-2) == "px") {
                                wVal = wVal.substr(0, wVal.size()-2);
                                isPx = true;
                            }
                            double w = std::stod(wVal);
                            if (isPx || (w > 0 && wVal.find('%') == std::string::npos
                                && wVal.find("em") == std::string::npos
                                && wVal.find("vw") == std::string::npos
                                && wVal.find("vh") == std::string::npos)) {
                                double h = w * realHeight / realWidth;
                                effHeight = std::to_string(static_cast<int>(h + 0.5)) + "px";
                                if (!isPx && effWidth.find("px") == std::string::npos)
                                    effWidth += "px";
                            }
                        } catch (...) {}
                    }
                    // If height is a pixel value and width is auto, compute width
                    else if (effWidth == "auto" && !effHeight.empty() && effHeight != "auto") {
                        try {
                            std::string hVal = effHeight;
                            bool isPx = false;
                            if (hVal.size() > 2 && hVal.substr(hVal.size()-2) == "px") {
                                hVal = hVal.substr(0, hVal.size()-2);
                                isPx = true;
                            }
                            double h = std::stod(hVal);
                            if (isPx || (h > 0 && hVal.find('%') == std::string::npos
                                && hVal.find("em") == std::string::npos
                                && hVal.find("vw") == std::string::npos
                                && hVal.find("vh") == std::string::npos)) {
                                double w = h * realWidth / realHeight;
                                effWidth = std::to_string(static_cast<int>(w + 0.5)) + "px";
                                if (!isPx && effHeight.find("px") == std::string::npos)
                                    effHeight += "px";
                            }
                        } catch (...) {}
                    }
                }

                std::string style;
                style += "width: " + effWidth + ";";
                style += " height: " + effHeight + ";";
                style += " object-fit: " + objectFit + ";";
                if (borderRadius != "0") {
                    style += " border-radius: " + borderRadius + ";";
                }
                style += " display: block;";
                if (hidden) style += " display: none;";
                img.setAttribute("style", style.c_str());

                // Mobile responsive overrides via media query
                std::string mobileCSS;
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) mobileCSS += " display: block !important;";

                if (!mobileCSS.empty()) {
                    libhtmlpp::HtmlElement styleTag("style");
                    std::string mediaRule = "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } }";
                    styleTag.appendChild(libhtmlpp::TextElement(mediaRule.c_str()));
                    el.appendChild(styleTag);
                }

                if (!customCss.empty()) {
                    libhtmlpp::HtmlElement cssStyle("style");
                    cssStyle.appendChild(libhtmlpp::TextElement(customCss.c_str()));
                    el.appendChild(cssStyle);
                }

                if (!linkUrl.empty()) {
                    libhtmlpp::HtmlElement a("a");
                    a.setAttribute("href", linkUrl.c_str());
                    a.setAttribute("target", "_blank");
                    a.appendChild(img);
                    wrapper.appendChild(a);
                } else if (fullscreen) {
                    // Build original (non-resized) URL by stripping query params
                    std::string origSrc = renderSrc;
                    auto qpos = origSrc.find('?');
                    if (qpos != std::string::npos) origSrc = origSrc.substr(0, qpos);
                    img.setAttribute("data-original", origSrc.c_str());
                    img.setAttribute("style", (style + " cursor: pointer;").c_str());
                    img.setAttribute("onclick",
                        "var o=document.createElement('div');"
                        "o.style.cssText='position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;z-index:99999;cursor:pointer;overflow:auto;';"
                        "var i=document.createElement('img');"
                        "i.src=this.getAttribute('data-original')||this.src;i.alt=this.alt;"
                        "i.style.cssText='max-width:95vw;max-height:95vh;width:auto;height:auto;object-fit:contain;';"
                        "o.appendChild(i);"
                        "o.onclick=function(e){if(e.target===o)document.body.removeChild(o);};"
                        "document.body.appendChild(o);");
                    wrapper.appendChild(img);
                } else {
                    wrapper.appendChild(img);
                }

                el.appendChild(wrapper);
            }

            // --- Element Management (Image is a leaf) ---
            bool canHaveChildren() const override { return false; }
            bool haveChilds() override { return false; }

            void setChildElement(const EditPlugin &) override {
                logError("Image cannot have children.");
            }
            void unsetChildElement(const EditPlugin &) override {
                logError("Image cannot have children.");
            }
            void addNextElement(const EditPlugin &) override {
                logError("Image does not support addNextElement.");
            }
            void remNextElement(const EditPlugin &) override {
                logError("Image does not support remNextElement.");
            }
        };
    };
}

// --- Factory Functions ---
EXPORT blogi::webedit::Image* create() {
    return new blogi::webedit::Image();
}

EXPORT void destroy(blogi::webedit::Image* p) {
    delete p;
}
