/*******************************************************************************
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 Popup : public EditPlugin {
        private:
            // Button properties
            std::string buttonLabel      = "Open";
            std::string buttonBgColor    = "var(--blogi-accent)";
            std::string buttonTextColor  = "var(--blogi-text)";
            std::string buttonFontSize   = "16px";
            std::string buttonFontWeight = "normal";
            std::string buttonPadding    = "10px 20px";
            std::string buttonBorderRadius = "4px";

            // Light mode button overrides
            std::string l_buttonBgColor   = "";
            std::string l_buttonTextColor = "";

            // Mobile button overrides
            std::string m_buttonFontSize   = "";
            std::string m_buttonPadding    = "";

            // Popup overlay properties
            std::string overlayBgColor   = "rgba(0,0,0,0.6)";
            std::string popupBgColor     = "var(--blogi-bg)";
            std::string popupTextColor   = "var(--blogi-text)";
            std::string popupWidth       = "600px";
            std::string popupMaxHeight   = "80vh";
            std::string popupPadding     = "24px";
            std::string popupBorderRadius = "8px";

            // Light mode popup overrides
            std::string l_popupBgColor   = "";
            std::string l_popupTextColor = "";

            // Mobile popup overrides
            std::string m_popupWidth     = "95vw";

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

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

        public:
            Popup() {
                Type = "c44bde81-7a23-4f0e-b6d1-9e83a5cf67b2";
            }

            virtual ~Popup() = default;

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

            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 << "PopupPlugin 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("Popup Settings"));
                settings.appendChild(title);

                // Button Label
                libhtmlpp::HtmlElement lblLabel("label");
                lblLabel.appendChild(libhtmlpp::TextElement("Button Label: "));
                settings.appendChild(lblLabel);
                libhtmlpp::HtmlElement lblInput("input");
                lblInput.setAttribute("type", "text");
                lblInput.setAttribute("name", "button_label");
                lblInput.setAttribute("value", buttonLabel.c_str());
                settings.appendChild(lblInput);

                // Popup Width
                libhtmlpp::HtmlElement pwLabel("label");
                pwLabel.appendChild(libhtmlpp::TextElement("Popup Width: "));
                settings.appendChild(pwLabel);
                libhtmlpp::HtmlElement pwInput("input");
                pwInput.setAttribute("type", "text");
                pwInput.setAttribute("name", "popup_width");
                pwInput.setAttribute("value", popupWidth.c_str());
                settings.appendChild(pwInput);
            }

            // --- 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("Popup"));
                }
            }

            // --- 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,
                                    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 (visibleWhen) json_object_object_add(f, "visibleWhen", visibleWhen);
                    json_object_array_add(arr, f);
                };

                // Button settings
                addField("button_label", "Button Label", "text", "Open");
                addField("button_bg_color", "Button Background (Dark)", "color_var");
                addField("l_button_bg_color", "Button Background (Light)", "color_var", nullptr, "light");
                addField("button_text_color", "Button Text Color (Dark)", "color_var");
                addField("l_button_text_color", "Button Text Color (Light)", "color_var", nullptr, "light");
                addField("button_font_size", "Button Font Size", "text", "16px", "desktop");
                addField("button_font_weight", "Button Font Weight", "text", "normal");
                addField("button_padding", "Button Padding", "text", "10px 20px", "desktop");
                addField("button_border_radius", "Button Border Radius", "text", "4px");

                // Popup settings
                addField("overlay_bg_color", "Overlay Background", "text", "rgba(0,0,0,0.6)");
                addField("popup_bg_color", "Popup Background (Dark)", "color_var");
                addField("l_popup_bg_color", "Popup Background (Light)", "color_var", nullptr, "light");
                addField("popup_text_color", "Popup Text Color (Dark)", "color_var");
                addField("l_popup_text_color", "Popup Text Color (Light)", "color_var", nullptr, "light");
                addField("popup_width", "Popup Width", "text", "600px", "desktop");
                addField("popup_max_height", "Popup Max Height", "text", "80vh");
                addField("popup_padding", "Popup Padding", "text", "24px");
                addField("popup_border_radius", "Popup Border Radius", "text", "8px");

                // Visibility
                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("custom_css", "Custom CSS", "textarea", ".we-xxx { ... }");

                return arr;
            }

            // --- 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("button_label", buttonLabel.c_str());
                element->SetAttribute("button_bg_color", buttonBgColor.c_str());
                element->SetAttribute("button_text_color", buttonTextColor.c_str());
                element->SetAttribute("button_font_size", buttonFontSize.c_str());
                element->SetAttribute("button_font_weight", buttonFontWeight.c_str());
                element->SetAttribute("button_padding", buttonPadding.c_str());
                element->SetAttribute("button_border_radius", buttonBorderRadius.c_str());

                element->SetAttribute("l_button_bg_color", l_buttonBgColor.c_str());
                element->SetAttribute("l_button_text_color", l_buttonTextColor.c_str());
                element->SetAttribute("m_button_font_size", m_buttonFontSize.c_str());
                element->SetAttribute("m_button_padding", m_buttonPadding.c_str());

                element->SetAttribute("overlay_bg_color", overlayBgColor.c_str());
                element->SetAttribute("popup_bg_color", popupBgColor.c_str());
                element->SetAttribute("popup_text_color", popupTextColor.c_str());
                element->SetAttribute("popup_width", popupWidth.c_str());
                element->SetAttribute("popup_max_height", popupMaxHeight.c_str());
                element->SetAttribute("popup_padding", popupPadding.c_str());
                element->SetAttribute("popup_border_radius", popupBorderRadius.c_str());

                element->SetAttribute("l_popup_bg_color", l_popupBgColor.c_str());
                element->SetAttribute("l_popup_text_color", l_popupTextColor.c_str());
                element->SetAttribute("m_popup_width", m_popupWidth.c_str());

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

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

                // Serialize child widgets
                EditPlugin *cur = child;
                while (cur) {
                    tinyxml2::XMLElement *childXml = cur->toXmlObject(doc);
                    if (childXml) element->InsertEndChild(childXml);
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }

                return element;
            }

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

                val = xml_data->Attribute("button_label");          if (val) buttonLabel = val;
                val = xml_data->Attribute("button_bg_color");       if (val) buttonBgColor = val;
                val = xml_data->Attribute("button_text_color");     if (val) buttonTextColor = val;
                val = xml_data->Attribute("button_font_size");      if (val) buttonFontSize = val;
                val = xml_data->Attribute("button_font_weight");    if (val) buttonFontWeight = val;
                val = xml_data->Attribute("button_padding");        if (val) buttonPadding = val;
                val = xml_data->Attribute("button_border_radius");  if (val) buttonBorderRadius = val;

                val = xml_data->Attribute("l_button_bg_color");     if (val) l_buttonBgColor = val;
                val = xml_data->Attribute("l_button_text_color");   if (val) l_buttonTextColor = val;
                val = xml_data->Attribute("m_button_font_size");    if (val) m_buttonFontSize = val;
                val = xml_data->Attribute("m_button_padding");      if (val) m_buttonPadding = val;

                val = xml_data->Attribute("overlay_bg_color");      if (val) overlayBgColor = val;
                val = xml_data->Attribute("popup_bg_color");        if (val) popupBgColor = val;
                val = xml_data->Attribute("popup_text_color");      if (val) popupTextColor = val;
                val = xml_data->Attribute("popup_width");           if (val) popupWidth = val;
                val = xml_data->Attribute("popup_max_height");      if (val) popupMaxHeight = val;
                val = xml_data->Attribute("popup_padding");         if (val) popupPadding = val;
                val = xml_data->Attribute("popup_border_radius");   if (val) popupBorderRadius = val;

                val = xml_data->Attribute("l_popup_bg_color");      if (val) l_popupBgColor = val;
                val = xml_data->Attribute("l_popup_text_color");    if (val) l_popupTextColor = val;
                val = xml_data->Attribute("m_popup_width");         if (val) m_popupWidth = val;

                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);

                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, "button_label", json_object_new_string(buttonLabel.c_str()));
                json_object_object_add(obj, "button_bg_color", json_object_new_string(buttonBgColor.c_str()));
                json_object_object_add(obj, "button_text_color", json_object_new_string(buttonTextColor.c_str()));
                json_object_object_add(obj, "button_font_size", json_object_new_string(buttonFontSize.c_str()));
                json_object_object_add(obj, "button_font_weight", json_object_new_string(buttonFontWeight.c_str()));
                json_object_object_add(obj, "button_padding", json_object_new_string(buttonPadding.c_str()));
                json_object_object_add(obj, "button_border_radius", json_object_new_string(buttonBorderRadius.c_str()));

                json_object_object_add(obj, "l_button_bg_color", json_object_new_string(l_buttonBgColor.c_str()));
                json_object_object_add(obj, "l_button_text_color", json_object_new_string(l_buttonTextColor.c_str()));
                json_object_object_add(obj, "m_button_font_size", json_object_new_string(m_buttonFontSize.c_str()));
                json_object_object_add(obj, "m_button_padding", json_object_new_string(m_buttonPadding.c_str()));

                json_object_object_add(obj, "overlay_bg_color", json_object_new_string(overlayBgColor.c_str()));
                json_object_object_add(obj, "popup_bg_color", json_object_new_string(popupBgColor.c_str()));
                json_object_object_add(obj, "popup_text_color", json_object_new_string(popupTextColor.c_str()));
                json_object_object_add(obj, "popup_width", json_object_new_string(popupWidth.c_str()));
                json_object_object_add(obj, "popup_max_height", json_object_new_string(popupMaxHeight.c_str()));
                json_object_object_add(obj, "popup_padding", json_object_new_string(popupPadding.c_str()));
                json_object_object_add(obj, "popup_border_radius", json_object_new_string(popupBorderRadius.c_str()));

                json_object_object_add(obj, "l_popup_bg_color", json_object_new_string(l_popupBgColor.c_str()));
                json_object_object_add(obj, "l_popup_text_color", json_object_new_string(l_popupTextColor.c_str()));
                json_object_object_add(obj, "m_popup_width", json_object_new_string(m_popupWidth.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, "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, "button_label", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonLabel = val;
                }
                if (json_object_object_get_ex(obj, "button_bg_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonBgColor = val;
                }
                if (json_object_object_get_ex(obj, "button_text_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonTextColor = val;
                }
                if (json_object_object_get_ex(obj, "button_font_size", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonFontSize = val;
                }
                if (json_object_object_get_ex(obj, "button_font_weight", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonFontWeight = val;
                }
                if (json_object_object_get_ex(obj, "button_padding", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonPadding = val;
                }
                if (json_object_object_get_ex(obj, "button_border_radius", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) buttonBorderRadius = val;
                }
                if (json_object_object_get_ex(obj, "l_button_bg_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) l_buttonBgColor = val;
                }
                if (json_object_object_get_ex(obj, "l_button_text_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) l_buttonTextColor = val;
                }
                if (json_object_object_get_ex(obj, "m_button_font_size", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_buttonFontSize = val;
                }
                if (json_object_object_get_ex(obj, "m_button_padding", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_buttonPadding = val;
                }
                if (json_object_object_get_ex(obj, "overlay_bg_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) overlayBgColor = val;
                }
                if (json_object_object_get_ex(obj, "popup_bg_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupBgColor = val;
                }
                if (json_object_object_get_ex(obj, "popup_text_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupTextColor = val;
                }
                if (json_object_object_get_ex(obj, "popup_width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupWidth = val;
                }
                if (json_object_object_get_ex(obj, "popup_max_height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupMaxHeight = val;
                }
                if (json_object_object_get_ex(obj, "popup_padding", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupPadding = val;
                }
                if (json_object_object_get_ex(obj, "popup_border_radius", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) popupBorderRadius = val;
                }
                if (json_object_object_get_ex(obj, "l_popup_bg_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) l_popupBgColor = val;
                }
                if (json_object_object_get_ex(obj, "l_popup_text_color", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) l_popupTextColor = val;
                }
                if (json_object_object_get_ex(obj, "m_popup_width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_popupWidth = 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 || 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 || strcmp(s, "1") == 0));
                    } else {
                        m_hidden = 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);
            }

            // --- HTML Rendering ---
            void Render(libhtmlpp::HtmlElement &el) const override {
                std::string instanceId(getInstanceId().c_str());
                std::string responsiveClass = std::string("we-") + instanceId;
                std::string overlayId = "popup-overlay-" + instanceId;
                std::string popupId   = "popup-content-" + instanceId;

                // --- Trigger Button ---
                libhtmlpp::HtmlElement btn("button");
                btn.setAttribute("type", "button");

                auto validCss = [](const std::string &v) {
                    return !v.empty() && v != "none";
                };

                std::string btnStyle;
                if (validCss(buttonBgColor))    btnStyle += "background-color: " + buttonBgColor + ";";
                else                            btnStyle += "background-color: transparent;";
                if (validCss(buttonTextColor))   btnStyle += " color: " + buttonTextColor + ";";
                if (validCss(buttonFontSize))    btnStyle += " font-size: " + buttonFontSize + ";";
                if (validCss(buttonFontWeight))  btnStyle += " font-weight: " + buttonFontWeight + ";";
                if (validCss(buttonPadding))     btnStyle += " padding: " + buttonPadding + ";";
                if (validCss(buttonBorderRadius)) btnStyle += " border-radius: " + buttonBorderRadius + ";";
                btnStyle += " border: none; cursor: pointer;";
                if (hidden) btnStyle += " display: none;";
                btn.setAttribute("style", btnStyle.c_str());
                btn.setAttribute("class", (responsiveClass + "-btn").c_str());

                std::string openJs = "document.getElementById('" + overlayId + "').style.display='flex';";
                btn.setAttribute("onclick", openJs.c_str());
                btn.appendChild(libhtmlpp::TextElement(buttonLabel.c_str()));

                el.appendChild(btn);

                // --- Overlay + Popup Dialog ---
                libhtmlpp::HtmlElement overlay("div");
                overlay.setAttribute("id", overlayId.c_str());

                std::string overlayStyle;
                overlayStyle += "display: none; position: fixed; top: 0; left: 0;";
                overlayStyle += " width: 100%; height: 100%; z-index: 9999;";
                overlayStyle += " justify-content: center; align-items: center;";
                if (validCss(overlayBgColor)) overlayStyle += " background: " + overlayBgColor + ";";
                overlay.setAttribute("style", overlayStyle.c_str());

                // Close on overlay click
                std::string closeJs = "if(event.target===this)this.style.display='none';";
                overlay.setAttribute("onclick", closeJs.c_str());

                // Popup content box
                libhtmlpp::HtmlElement popup("div");
                popup.setAttribute("id", popupId.c_str());
                popup.setAttribute("class", (responsiveClass + "-dialog").c_str());

                std::string popupStyle;
                popupStyle += "position: relative;";
                if (validCss(popupBgColor))    popupStyle += " background: " + popupBgColor + ";";
                if (validCss(popupTextColor))  popupStyle += " color: " + popupTextColor + ";";
                if (validCss(popupWidth))      popupStyle += " width: " + popupWidth + ";";
                if (validCss(popupMaxHeight))  popupStyle += " max-height: " + popupMaxHeight + ";";
                if (validCss(popupPadding))    popupStyle += " padding: " + popupPadding + ";";
                if (validCss(popupBorderRadius)) popupStyle += " border-radius: " + popupBorderRadius + ";";
                popupStyle += " overflow-y: auto; box-shadow: 0 8px 32px rgba(0,0,0,0.3);";
                popup.setAttribute("style", popupStyle.c_str());

                // Close button (X) top-right
                libhtmlpp::HtmlElement closeBtn("button");
                closeBtn.setAttribute("type", "button");
                closeBtn.setAttribute("style",
                    "position: absolute; top: 8px; right: 12px;"
                    " background: none; border: none; font-size: 24px;"
                    " cursor: pointer; color: inherit; line-height: 1;");
                std::string closeBtnJs = "document.getElementById('" + overlayId + "').style.display='none';";
                closeBtn.setAttribute("onclick", closeBtnJs.c_str());
                closeBtn.appendChild(libhtmlpp::TextElement("\xC3\x97")); // UTF-8 multiplication sign as X
                popup.appendChild(closeBtn);

                // Render child widgets into popup
                const EditPlugin *cur = child;
                while (cur) {
                    cur->Render(popup);
                    cur = cur->nextElement();
                }

                overlay.appendChild(popup);
                el.appendChild(overlay);

                // --- Responsive & Light mode CSS ---
                std::string mediaCSS;

                // Mobile button overrides
                std::string mobileBtnCSS;
                if (validCss(m_buttonFontSize)) mobileBtnCSS += " font-size: " + m_buttonFontSize + " !important;";
                if (validCss(m_buttonPadding))  mobileBtnCSS += " padding: " + m_buttonPadding + " !important;";
                if (m_hidden) mobileBtnCSS += " display: none !important;";
                else if (hidden) mobileBtnCSS += " display: inline-block !important;";

                // Mobile popup overrides
                std::string mobilePopupCSS;
                if (validCss(m_popupWidth)) mobilePopupCSS += " width: " + m_popupWidth + " !important;";

                if (!mobileBtnCSS.empty() || !mobilePopupCSS.empty()) {
                    mediaCSS += "@media (max-width: 768px) {";
                    if (!mobileBtnCSS.empty())
                        mediaCSS += " ." + responsiveClass + "-btn {" + mobileBtnCSS + " }";
                    if (!mobilePopupCSS.empty())
                        mediaCSS += " ." + responsiveClass + "-dialog {" + mobilePopupCSS + " }";
                    mediaCSS += " } ";
                }

                // Light mode overrides
                std::string lightBtnCSS;
                if (validCss(l_buttonBgColor))   lightBtnCSS += " background-color: " + l_buttonBgColor + " !important;";
                if (validCss(l_buttonTextColor))  lightBtnCSS += " color: " + l_buttonTextColor + " !important;";

                std::string lightPopupCSS;
                if (validCss(l_popupBgColor))   lightPopupCSS += " background: " + l_popupBgColor + " !important;";
                if (validCss(l_popupTextColor)) lightPopupCSS += " color: " + l_popupTextColor + " !important;";

                if (!lightBtnCSS.empty() || !lightPopupCSS.empty()) {
                    mediaCSS += "@media (prefers-color-scheme: light) {";
                    if (!lightBtnCSS.empty())
                        mediaCSS += " ." + responsiveClass + "-btn {" + lightBtnCSS + " }";
                    if (!lightPopupCSS.empty())
                        mediaCSS += " ." + responsiveClass + "-dialog {" + lightPopupCSS + " }";
                    mediaCSS += " }";
                }

                // Escape key listener
                mediaCSS += " "; // spacer before script

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

                // Escape key to close
                std::string escScript =
                    "document.addEventListener('keydown',function(e){"
                    "if(e.key==='Escape'){"
                    "var o=document.getElementById('" + overlayId + "');"
                    "if(o)o.style.display='none';"
                    "}});";
                libhtmlpp::HtmlElement script("script");
                script.appendChild(libhtmlpp::TextElement(escScript.c_str()));
                el.appendChild(script);

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

            // --- Element Management (Popup is a container) ---
            bool canHaveChildren() const override { return true; }
            bool haveChilds() override { return child != nullptr; }

            void setChildElement(const EditPlugin &el) override {
                child = const_cast<EditPlugin*>(&el);
            }

            void unsetChildElement(const EditPlugin &el) override {
                if (child == &el) {
                    child = const_cast<EditPlugin*>(el.nextElement());
                }
            }

            void addNextElement(const EditPlugin &el) override {
                EditPlugin *newEl = const_cast<EditPlugin*>(&el);

                if (!child) {
                    setChildElement(el);
                    return;
                }

                EditPlugin *cur = child;
                while (cur->nextElement() != nullptr) {
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
                cur->setNextEl(newEl);
            }

            void remNextElement(const EditPlugin &el) override {
                if (!child) return;

                if (child == &el) {
                    unsetChildElement(el);
                    return;
                }

                EditPlugin *cur = child;
                while (cur->nextElement() != nullptr) {
                    if (cur->nextElement() == &el) {
                        cur->setNextEl(const_cast<EditPlugin*>(el.nextElement()));
                        return;
                    }
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
            }
        };
    };
}

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

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