/*******************************************************************************
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> // For JSON property serialization
#include <iostream> // For logError
#include <cstring> // For strcmp

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

#include "plugin.h"

extern "C" {
    namespace blogi::webedit {

        class Container : public EditPlugin {
        private:
            std::string content;
            std::string backgroundColor = "";
            std::string cssClass = "";
            std::string borderRadius = "";
            std::string borderStyle = "";
            std::string opacity = "";
            std::string padding = "";
            std::string margin = "";
            std::string width = "";
            std::string height = "";

            // Background image
            std::string backgroundImage    = "";
            std::string backgroundSize     = "cover";
            std::string backgroundPosition = "center";
            std::string backgroundRepeat   = "no-repeat";

            // Light mode overrides (empty = inherit dark value)
            std::string l_backgroundColor = "";

            // Mobile overrides (empty = inherit desktop value)
            std::string m_backgroundColor = "";
            std::string m_backgroundImage    = "";
            std::string m_backgroundSize     = "";
            std::string m_backgroundPosition = "";
            std::string m_borderRadius = "";
            std::string m_borderStyle = "";
            std::string m_opacity = "";
            std::string m_padding = "";
            std::string m_margin = "";
            std::string m_width = "";
            std::string m_height = "";

            // Vertical alignment
            std::string verticalAlign = "";
            std::string m_verticalAlign = "";

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

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

        public:
            Container() {
                // NOTE: The base EditPlugin constructor handles ID generation.
                // We set the Type ID here, assuming Type is a member of EditPlugin
                Type="a22a7ef9-0d43-4c1d-82b4-7d34b9545a24";
            };

            virtual ~Container() = default;

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

            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 << "ContainerPlugin Error (" << getInstanceId().c_str() << "): " << message << std::endl;
            }

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

            // --- JSON API (Structural & Bulk Operations) ---
            void JsonApi(json_object *request, json_object *response) override {
                // This method handles structural operations (Add/Delete/Move) and bulk property modifications.

                // --- 1. Request Validation (Placeholder) ---
                // NOTE: Assuming external json_object library functions are available.

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

                if (request == nullptr /* || json_object_get_type(request) != json_type_object */) {
                    logError("Invalid JSON request received (nullptr or not object).");
                    return;
                }

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

                // --- 3. Action Dispatcher (Structural Changes) ---

                if (strcmp(action, "add") == 0) {
                    // ADD operation: Create a new plugin and attach it.

                    const char *type_id = nullptr;   // Plugin type to create
                    const char *position = nullptr; // "child" or "next"

                    // Placeholder: Extract type_id and position from request

                    json_object *type_id_obj = nullptr;
                    if (json_object_object_get_ex(request, "type_id", &type_id_obj)) {
                        type_id = json_object_get_string(type_id_obj);
                    }

                    json_object *position_obj = nullptr;
                    if (json_object_object_get_ex(request, "position", &position_obj)) {
                        position = json_object_get_string(position_obj);
                    }

                    if (type_id) {
                        // External Dependency: Assumes a factory is available
                        std::unique_ptr<EditPlugin> new_el=std::make_unique<Container>();
                        if (new_el) {
                            if (position != nullptr && strcmp(position, "child") == 0) {
                                this->setChildElement(*new_el);
                            } else { // Assume "next" or sibling append
                                this->addNextElement(*new_el);
                            }
                        } else {
                            logError("Plugin type not found for ADD action.");
                        }
                    } else {
                        logError("Missing 'type_id' for ADD action.");
                    }

                } else if (strcmp(action, "delete") == 0) {

                    const char *target_id = nullptr;

                    if (target_id) {
                        EditPlugin *el_to_remove = nullptr;

                        // Check if it's the first child
                        if (this->child != nullptr && this->child->getInstanceId() == target_id) {
                            el_to_remove = this->child;
                            this->unsetChildElement(*el_to_remove);
                        } else {
                            // Traverse siblings to find the element *before* target_id
                            EditPlugin *cur = this->child;
                            while(cur != nullptr && cur->nextElement() != nullptr) {
                                if (cur->nextElement()->getInstanceId() == target_id) {
                                    el_to_remove = const_cast<EditPlugin*>(cur->nextElement());
                                    this->remNextElement(*el_to_remove);
                                    break;
                                }
                                cur = const_cast<EditPlugin*>(cur->nextElement());
                            }
                        }

                        if (el_to_remove) {
                            // Placeholder: Send Success response
                        } else {
                            logError("Target ID not found for DELETE action.");
                            // Placeholder: Send Error response
                        }
                    }
                } else 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) {
                    // READ operation: Fetch properties or structural info.
                    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());
                    }
                }

                // --- 4. Final Response Construction ---
                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("Container"));
                }
            }

            // --- 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 *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);
                    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("background_color", "Background Color (Dark)", "color_var", nullptr, "desktop");
                addField("l_background_color", "Background Color (Light)", "color_var", nullptr, "light");
                addField("background_image", "Background Image", "media_browse", "/media/getimage/...", "desktop");
                addField("background_size", "Background Size", "select", nullptr, "desktop", mkOpts({"cover","contain","auto","100% 100%"}));
                addField("background_position", "Background Position", "select", nullptr, "desktop", mkOpts({"center","top","bottom","left","right","top left","top right","bottom left","bottom right"}));
                addField("background_repeat", "Background Repeat", "select", nullptr, "all", mkOpts({"no-repeat","repeat","repeat-x","repeat-y"}));
                addField("width", "Width", "text", "e.g. 100%", "desktop");
                addField("height", "Height", "text", "e.g. auto", "desktop");
                addField("css_class", "CSS Class", "text", "e.g. my-container");
                addField("border_radius", "Border Radius", "text", "e.g. 8px", "desktop");
                addField("border_style", "Border", "text", "e.g. 1px solid #ccc", "desktop");
                addField("opacity", "Opacity", "text", "0.0 - 1.0", "desktop");
                addField("padding", "Padding", "text", "e.g. 10px 20px", "desktop");
                addField("margin", "Margin", "text", "e.g. 10px auto", "desktop");
                addField("vertical_align", "Vertical Align", "select", nullptr, "desktop", mkOpts({"top","center","bottom"}));
                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 { color: red; }");
                return arr;
            }

            // --- XML Persistence (Save/Load State) ---

            /**
             * @brief Serializes the element and its children to an XML object.
             */
            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());

                // Persist properties
                element->SetAttribute("background_color", backgroundColor.c_str());
                element->SetAttribute("css_class", cssClass.c_str());
                element->SetAttribute("border_radius", borderRadius.c_str());
                element->SetAttribute("border_style", borderStyle.c_str());
                element->SetAttribute("opacity", opacity.c_str());
                element->SetAttribute("padding", padding.c_str());
                element->SetAttribute("margin", margin.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());

                // Background image
                element->SetAttribute("background_image", backgroundImage.c_str());
                element->SetAttribute("background_size", backgroundSize.c_str());
                element->SetAttribute("background_position", backgroundPosition.c_str());
                element->SetAttribute("background_repeat", backgroundRepeat.c_str());

                // Light mode overrides
                element->SetAttribute("l_background_color", l_backgroundColor.c_str());

                // Mobile overrides
                element->SetAttribute("m_background_color", m_backgroundColor.c_str());
                element->SetAttribute("m_background_image", m_backgroundImage.c_str());
                element->SetAttribute("m_background_size", m_backgroundSize.c_str());
                element->SetAttribute("m_background_position", m_backgroundPosition.c_str());
                element->SetAttribute("m_border_radius", m_borderRadius.c_str());
                element->SetAttribute("m_border_style", m_borderStyle.c_str());
                element->SetAttribute("m_opacity", m_opacity.c_str());
                element->SetAttribute("m_padding", m_padding.c_str());
                element->SetAttribute("m_margin", m_margin.c_str());
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

                // Vertical alignment
                element->SetAttribute("vertical_align", verticalAlign.c_str());
                element->SetAttribute("m_vertical_align", m_verticalAlign.c_str());

                // Visibility
                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);
                }

                // Add content
                if (!content.empty()) {
                    element->SetText(content.c_str());
                }

                const EditPlugin *cur = child;
                while (cur) {
                    // toXmlObject is non-const but the recursive call is fine
                    element->InsertEndChild(const_cast<EditPlugin*>(cur)->toXmlObject(doc));
                    cur = cur->nextElement(); // Use base class accessor for siblings
                }

                return element;
            }

            void fromXmlObject(tinyxml2::XMLElement* xml_data) override {
                const char* loaded_content = xml_data->GetText();
                if (loaded_content) {
                    content = loaded_content;
                }
                // Load attributes
                const char* loaded_color = xml_data->Attribute("background_color");
                if (loaded_color) backgroundColor = loaded_color;

                const char* loaded_class = xml_data->Attribute("css_class");
                if (loaded_class) cssClass = loaded_class;

                const char* loaded_br = xml_data->Attribute("border_radius");
                if (loaded_br) borderRadius = loaded_br;

                const char* loaded_bs = xml_data->Attribute("border_style");
                if (loaded_bs) borderStyle = loaded_bs;

                const char* loaded_op = xml_data->Attribute("opacity");
                if (loaded_op) opacity = loaded_op;

                const char* loaded_pad = xml_data->Attribute("padding");
                if (loaded_pad) padding = loaded_pad;
                const char* loaded_mar = xml_data->Attribute("margin");
                if (loaded_mar) margin = loaded_mar;
                const char* loaded_w = xml_data->Attribute("width");
                if (loaded_w) width = loaded_w;
                const char* loaded_h = xml_data->Attribute("height");
                if (loaded_h) height = loaded_h;

                // Background image
                const char* loaded_bi = xml_data->Attribute("background_image");
                if (loaded_bi) backgroundImage = loaded_bi;
                const char* loaded_bsz = xml_data->Attribute("background_size");
                if (loaded_bsz) backgroundSize = loaded_bsz;
                const char* loaded_bpos = xml_data->Attribute("background_position");
                if (loaded_bpos) backgroundPosition = loaded_bpos;
                const char* loaded_brep = xml_data->Attribute("background_repeat");
                if (loaded_brep) backgroundRepeat = loaded_brep;

                // Light mode overrides
                const char* loaded_l_bg = xml_data->Attribute("l_background_color");
                if (loaded_l_bg) l_backgroundColor = loaded_l_bg;

                // Mobile overrides
                const char* loaded_m_bg = xml_data->Attribute("m_background_color");
                if (loaded_m_bg) m_backgroundColor = loaded_m_bg;
                const char* loaded_m_bi = xml_data->Attribute("m_background_image");
                if (loaded_m_bi) m_backgroundImage = loaded_m_bi;
                const char* loaded_m_bsz = xml_data->Attribute("m_background_size");
                if (loaded_m_bsz) m_backgroundSize = loaded_m_bsz;
                const char* loaded_m_bpos = xml_data->Attribute("m_background_position");
                if (loaded_m_bpos) m_backgroundPosition = loaded_m_bpos;
                const char* loaded_m_br = xml_data->Attribute("m_border_radius");
                if (loaded_m_br) m_borderRadius = loaded_m_br;
                const char* loaded_m_bs = xml_data->Attribute("m_border_style");
                if (loaded_m_bs) m_borderStyle = loaded_m_bs;
                const char* loaded_m_op = xml_data->Attribute("m_opacity");
                if (loaded_m_op) m_opacity = loaded_m_op;
                const char* loaded_m_pad = xml_data->Attribute("m_padding");
                if (loaded_m_pad) m_padding = loaded_m_pad;
                const char* loaded_m_mar = xml_data->Attribute("m_margin");
                if (loaded_m_mar) m_margin = loaded_m_mar;
                const char* loaded_m_w = xml_data->Attribute("m_width");
                if (loaded_m_w) m_width = loaded_m_w;
                const char* loaded_m_h = xml_data->Attribute("m_height");
                if (loaded_m_h) m_height = loaded_m_h;

                // Vertical alignment
                const char* loaded_va = xml_data->Attribute("vertical_align");
                if (loaded_va) verticalAlign = loaded_va;
                const char* loaded_m_va = xml_data->Attribute("m_vertical_align");
                if (loaded_m_va) m_verticalAlign = loaded_m_va;

                // Visibility
                const char* loaded_hidden = xml_data->Attribute("hidden");
                if (loaded_hidden) hidden = (strcmp(loaded_hidden, "true") == 0);
                const char* loaded_m_hidden = xml_data->Attribute("m_hidden");
                if (loaded_m_hidden) m_hidden = (strcmp(loaded_m_hidden, "true") == 0);

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

                // NOTE: Loading children from XML requires an EditPluginFactory which is not available here.
            }

            // --- JSON API (Modify/Read Properties) ---

            // Serialize properties to JSON for the API/UI (Read operation)
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "background_color", json_object_new_string(backgroundColor.c_str()));
                json_object_object_add(obj, "css_class", json_object_new_string(cssClass.c_str()));
                json_object_object_add(obj, "border_radius", json_object_new_string(borderRadius.c_str()));
                json_object_object_add(obj, "border_style", json_object_new_string(borderStyle.c_str()));
                json_object_object_add(obj, "opacity", json_object_new_string(opacity.c_str()));
                json_object_object_add(obj, "padding", json_object_new_string(padding.c_str()));
                json_object_object_add(obj, "margin", json_object_new_string(margin.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, "background_image", json_object_new_string(backgroundImage.c_str()));
                json_object_object_add(obj, "background_size", json_object_new_string(backgroundSize.c_str()));
                json_object_object_add(obj, "background_position", json_object_new_string(backgroundPosition.c_str()));
                json_object_object_add(obj, "background_repeat", json_object_new_string(backgroundRepeat.c_str()));
                json_object_object_add(obj, "l_background_color", json_object_new_string(l_backgroundColor.c_str()));
                json_object_object_add(obj, "m_background_color", json_object_new_string(m_backgroundColor.c_str()));
                json_object_object_add(obj, "m_background_image", json_object_new_string(m_backgroundImage.c_str()));
                json_object_object_add(obj, "m_background_size", json_object_new_string(m_backgroundSize.c_str()));
                json_object_object_add(obj, "m_background_position", json_object_new_string(m_backgroundPosition.c_str()));
                json_object_object_add(obj, "m_border_radius", json_object_new_string(m_borderRadius.c_str()));
                json_object_object_add(obj, "m_border_style", json_object_new_string(m_borderStyle.c_str()));
                json_object_object_add(obj, "m_opacity", json_object_new_string(m_opacity.c_str()));
                json_object_object_add(obj, "m_padding", json_object_new_string(m_padding.c_str()));
                json_object_object_add(obj, "m_margin", json_object_new_string(m_margin.c_str()));
                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, "vertical_align", json_object_new_string(verticalAlign.c_str()));
                json_object_object_add(obj, "m_vertical_align", json_object_new_string(m_verticalAlign.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, "background_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) backgroundColor = val;
                }
                if (json_object_object_get_ex(obj, "css_class", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) cssClass = val;
                }
                if (json_object_object_get_ex(obj, "border_radius", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) borderRadius = val;
                }
                if (json_object_object_get_ex(obj, "border_style", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) borderStyle = val;
                }
                if (json_object_object_get_ex(obj, "opacity", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) opacity = val;
                }
                if (json_object_object_get_ex(obj, "background_image", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) backgroundImage = val;
                }
                if (json_object_object_get_ex(obj, "background_size", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) backgroundSize = val;
                }
                if (json_object_object_get_ex(obj, "background_position", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) backgroundPosition = val;
                }
                if (json_object_object_get_ex(obj, "background_repeat", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) backgroundRepeat = val;
                }
                if (json_object_object_get_ex(obj, "l_background_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) l_backgroundColor = val;
                }
                if (json_object_object_get_ex(obj, "m_background_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_backgroundColor = val;
                }
                if (json_object_object_get_ex(obj, "m_background_image", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_backgroundImage = val;
                }
                if (json_object_object_get_ex(obj, "m_background_size", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_backgroundSize = val;
                }
                if (json_object_object_get_ex(obj, "m_background_position", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_backgroundPosition = val;
                }
                if (json_object_object_get_ex(obj, "m_border_radius", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_borderRadius = val;
                }
                if (json_object_object_get_ex(obj, "m_border_style", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_borderStyle = val;
                }
                if (json_object_object_get_ex(obj, "m_opacity", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_opacity = val;
                }
                if (json_object_object_get_ex(obj, "padding", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) padding = val;
                }
                if (json_object_object_get_ex(obj, "margin", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) margin = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) height = val;
                }
                if (json_object_object_get_ex(obj, "m_padding", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_padding = val;
                }
                if (json_object_object_get_ex(obj, "m_margin", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_margin = val;
                }
                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, "vertical_align", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) verticalAlign = val;
                }
                if (json_object_object_get_ex(obj, "m_vertical_align", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_verticalAlign = val;
                }
                if (json_object_object_get_ex(obj, "hidden", &val_obj)) {
                    hidden = json_object_get_boolean(val_obj);
                }
                if (json_object_object_get_ex(obj, "m_hidden", &val_obj)) {
                    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 ---

            /**
             * @brief Renders the container element and recursively renders its children.
             */
            void Render(libhtmlpp::HtmlElement &el) const override {
                libhtmlpp::HtmlElement cnt("div");

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

                std::string style = "";
                if (!backgroundColor.empty() && backgroundColor != "none" && backgroundColor != "transparent") {
                    style += " background-color: " + backgroundColor + ";";
                }
                if (!backgroundImage.empty()) {
                    style += " background-image: url('" + backgroundImage + "');";
                    style += " background-size: " + backgroundSize + ";";
                    style += " background-position: " + backgroundPosition + ";";
                    style += " background-repeat: " + backgroundRepeat + ";";
                }
                if (!borderRadius.empty()) {
                    style += " border-radius: " + borderRadius + ";";
                }
                if (!borderStyle.empty()) {
                    style += " border: " + borderStyle + ";";
                }
                if (!opacity.empty()) {
                    style += " opacity: " + opacity + ";";
                }
                if (!padding.empty()) {
                    style += " padding: " + padding + ";";
                }
                if (!margin.empty()) {
                    style += " margin: " + margin + ";";
                }
                if (!width.empty()) {
                    style += " width: " + width + ";";
                }
                if (!height.empty()) {
                    style += " height: " + height + ";";
                }
                if (!verticalAlign.empty()) {
                    style += " display: flex; flex-direction: column;";
                    if (verticalAlign == "top") style += " justify-content: flex-start;";
                    else if (verticalAlign == "center") style += " justify-content: center;";
                    else if (verticalAlign == "bottom") style += " justify-content: flex-end;";
                }
                if (hidden) {
                    style += " display: none;";
                }

                cnt.setAttribute("style", style.c_str());
                std::string cls = responsiveClass;
                if (!cssClass.empty()) {
                    cls = cssClass + " " + responsiveClass;
                }
                cnt.setAttribute("class", cls.c_str());

                // Mobile responsive overrides via media query
                std::string mobileCSS;
                if (!m_backgroundColor.empty() && m_backgroundColor != "none" && m_backgroundColor != "transparent") {
                    mobileCSS += " background-color: " + m_backgroundColor + " !important;";
                } else if (m_backgroundColor == "none" || m_backgroundColor == "transparent") {
                    mobileCSS += " background-color: transparent !important;";
                }
                if (!m_backgroundImage.empty()) {
                    mobileCSS += " background-image: url('" + m_backgroundImage + "') !important;";
                }
                if (!m_backgroundSize.empty()) {
                    mobileCSS += " background-size: " + m_backgroundSize + " !important;";
                }
                if (!m_backgroundPosition.empty()) {
                    mobileCSS += " background-position: " + m_backgroundPosition + " !important;";
                }
                if (!m_borderRadius.empty()) mobileCSS += " border-radius: " + m_borderRadius + " !important;";
                if (!m_borderStyle.empty()) mobileCSS += " border: " + m_borderStyle + " !important;";
                if (!m_opacity.empty()) mobileCSS += " opacity: " + m_opacity + " !important;";
                if (!m_padding.empty()) mobileCSS += " padding: " + m_padding + " !important;";
                if (!m_margin.empty()) mobileCSS += " margin: " + m_margin + " !important;";
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (!m_verticalAlign.empty()) {
                    mobileCSS += " display: flex !important; flex-direction: column !important;";
                    if (m_verticalAlign == "top") mobileCSS += " justify-content: flex-start !important;";
                    else if (m_verticalAlign == "center") mobileCSS += " justify-content: center !important;";
                    else if (m_verticalAlign == "bottom") mobileCSS += " justify-content: flex-end !important;";
                }
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) {
                    if (!m_verticalAlign.empty() || !verticalAlign.empty())
                        mobileCSS += " display: flex !important;";
                    else
                        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);
                }

                // Light mode overrides via prefers-color-scheme
                std::string lightCSS;
                if (!l_backgroundColor.empty() && l_backgroundColor != "none" && l_backgroundColor != "transparent") {
                    lightCSS += " background-color: " + l_backgroundColor + " !important;";
                } else if (l_backgroundColor == "none" || l_backgroundColor == "transparent") {
                    lightCSS += " background-color: transparent !important;";
                }
                if (!lightCSS.empty()) {
                    libhtmlpp::HtmlElement lightStyle("style");
                    std::string lightRule = "@media (prefers-color-scheme: light) { ." + responsiveClass + " {" + lightCSS + " } }";
                    lightStyle.appendChild(libhtmlpp::TextElement(lightRule.c_str()));
                    el.appendChild(lightStyle);
                }

                if (!customCss.empty()) {
                    libhtmlpp::HtmlElement cssStyle("style");
                    // Emit raw — user writes full selectors, e.g. .we-xxx { color: red; }
                    cssStyle.appendChild(libhtmlpp::TextElement(customCss.c_str()));
                    el.appendChild(cssStyle);
                }

                // Placeholder: Add content if any
                if (!content.empty()) {
                    cnt.appendChild(libhtmlpp::TextElement(content.c_str()));
                }

                // Recursively render children
                const EditPlugin *cur = child;
                while (cur) {
                    cur->Render(cnt);
                    cur = cur->nextElement(); // Changed to use the base class's accessor
                }

                el.appendChild(cnt);
            }

            // --- Element Management API (Add/Delete Structural Elements) ---

            bool canHaveChildren() const override { return true; }

            bool haveChilds() override { return child != nullptr; }

            /**
             * @brief Sets the first child element of this container.
             * @param el The EditPlugin element to be set as the first child.
             */
            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());
                }
            }

            /**
             * @brief Adds a new element as a sibling to the last element in the list.
             * @param el The EditPlugin element to be added.
             */
            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::Container* create() {
    return new blogi::webedit::Container();
}

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