/*******************************************************************************
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 Section : 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 maxWidth = "";
            std::string minHeight = "";
            std::string width = "";
            std::string height = "";

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

            // Mobile overrides (empty = inherit desktop value)
            std::string m_backgroundColor = "";
            std::string m_borderRadius = "";
            std::string m_borderStyle = "";
            std::string m_opacity = "";
            std::string m_padding = "";
            std::string m_margin = "";
            std::string m_maxWidth = "";
            std::string m_minHeight = "";
            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:
            Section() {
                Type = "be6ba833-c0be-4906-b97a-78045302d1d2";
            }

            ~Section() override = default;

            // --- Identity ---
            const std::string getName() const override { return "Section"; }
            const std::string getAuthor() const override { return "Jan Koester"; }
            const std::string getVersion() const override { return "0.1"; }

            void logError(const std::string& message) override {
                std::cerr << "[Section] " << message << std::endl;
            }

            // --- Settings UI ---
            void Settings(libhttppp::HttpRequest &curreq, libhtmlpp::HtmlElement &settings) override {
                // No server-side settings panel needed
            }

            // --- JSON API ---
            void JsonApi(json_object *request, json_object *response) override {
                if (!request || !response) return;

                json_object *action_obj = nullptr;
                if (!json_object_object_get_ex(request, "action", &action_obj)) return;
                const char *action = json_object_get_string(action_obj);
                if (!action) return;

                // --- 1. Add Child Element ---
                if (strcmp(action, "add") == 0) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Section"));
                }
                // --- 2. Delete Child Element ---
                else if (strcmp(action, "delete") == 0) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Section"));
                }
                // --- 3. Modify Properties (Bulk) ---
                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_get_string(props_obj);
                        if (json_str) {
                            fromPropertiesJson(json_str);
                        }
                    }
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("Section"));
                }
                // --- 4. Read Properties ---
                else if (strcmp(action, "read") == 0) {
                    json_object *result_obj = json_object_new_object();
                    json_object_object_add(result_obj, "plugin_type", json_object_new_string("Section"));
                    json_object_object_add(result_obj, "instance_id", json_object_new_string(getInstanceId().c_str()));
                    json_object_object_add(result_obj, "type_id", json_object_new_string(getTypeId().c_str()));
                    json_object_object_add(result_obj, "properties", json_object_new_string(toPropertiesJson().c_str()));
                    if (response) {
                        json_object_object_add(response, "data", result_obj);
                    }
                }
                // --- 5. Get Schema ---
                else if (strcmp(action, "get_schema") == 0) {
                    if (response) {
                        json_object_object_add(response, "schema", getSchemaJson());
                    }
                }

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

            // --- 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("css_class", "CSS Class", "text", "e.g. hero-section");
                addField("padding", "Padding", "text", "e.g. 40px 20px", "desktop");
                addField("margin", "Margin", "text", "e.g. 0 auto", "desktop");
                addField("max_width", "Max Width", "text", "e.g. 1200px", "desktop");
                addField("min_height", "Min Height", "text", "e.g. 400px", "desktop");
                addField("width", "Width", "text", "e.g. 100%", "desktop");
                addField("height", "Height", "text", "e.g. auto", "desktop");
                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("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 ---

            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("max_width", maxWidth.c_str());
                element->SetAttribute("min_height", minHeight.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.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_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_max_width", m_maxWidth.c_str());
                element->SetAttribute("m_min_height", m_minHeight.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);
                }

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

                // Serialize children
                const EditPlugin *cur = child;
                while (cur) {
                    element->InsertEndChild(const_cast<EditPlugin*>(cur)->toXmlObject(doc));
                    cur = cur->nextElement();
                }

                return element;
            }

            void fromXmlObject(tinyxml2::XMLElement* xml_data) override {
                const char* loaded_content = xml_data->GetText();
                if (loaded_content) {
                    content = loaded_content;
                }

                const char* val = nullptr;

                val = xml_data->Attribute("background_color");
                if (val) backgroundColor = val;
                val = xml_data->Attribute("css_class");
                if (val) cssClass = val;
                val = xml_data->Attribute("border_radius");
                if (val) borderRadius = val;
                val = xml_data->Attribute("border_style");
                if (val) borderStyle = val;
                val = xml_data->Attribute("opacity");
                if (val) opacity = val;
                val = xml_data->Attribute("padding");
                if (val) padding = val;
                val = xml_data->Attribute("margin");
                if (val) margin = val;
                val = xml_data->Attribute("max_width");
                if (val) maxWidth = val;
                val = xml_data->Attribute("min_height");
                if (val) minHeight = val;
                val = xml_data->Attribute("width");
                if (val) width = val;
                val = xml_data->Attribute("height");
                if (val) height = val;

                // Light mode overrides
                val = xml_data->Attribute("l_background_color");
                if (val) l_backgroundColor = val;

                // Mobile overrides
                val = xml_data->Attribute("m_background_color");
                if (val) m_backgroundColor = val;
                val = xml_data->Attribute("m_border_radius");
                if (val) m_borderRadius = val;
                val = xml_data->Attribute("m_border_style");
                if (val) m_borderStyle = val;
                val = xml_data->Attribute("m_opacity");
                if (val) m_opacity = val;
                val = xml_data->Attribute("m_padding");
                if (val) m_padding = val;
                val = xml_data->Attribute("m_margin");
                if (val) m_margin = val;
                val = xml_data->Attribute("m_max_width");
                if (val) m_maxWidth = val;
                val = xml_data->Attribute("m_min_height");
                if (val) m_minHeight = val;
                val = xml_data->Attribute("m_width");
                if (val) m_width = val;
                val = xml_data->Attribute("m_height");
                if (val) m_height = val;

                // Vertical alignment
                val = xml_data->Attribute("vertical_align");
                if (val) verticalAlign = val;
                val = xml_data->Attribute("m_vertical_align");
                if (val) m_verticalAlign = val;

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

            // --- JSON Properties ---

            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, "max_width", json_object_new_string(maxWidth.c_str()));
                json_object_object_add(obj, "min_height", json_object_new_string(minHeight.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, "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_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_max_width", json_object_new_string(m_maxWidth.c_str()));
                json_object_object_add(obj, "m_min_height", json_object_new_string(m_minHeight.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, "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, "max_width", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) maxWidth = val;
                }
                if (json_object_object_get_ex(obj, "min_height", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) minHeight = 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, "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_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, "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_max_width", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_maxWidth = val;
                }
                if (json_object_object_get_ex(obj, "m_min_height", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_minHeight = 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 ---

            void Render(libhtmlpp::HtmlElement &el) const override {
                libhtmlpp::HtmlElement sect("section");

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

                // Anchor ID so buttons can scroll to this section
                sect.setAttribute("id", responsiveClass.c_str());

                std::string style = "";
                if (!backgroundColor.empty() && backgroundColor != "none" && backgroundColor != "transparent") {
                    style += " background-color: " + backgroundColor + ";";
                }
                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 (!maxWidth.empty()) {
                    style += " max-width: " + maxWidth + ";";
                }
                if (!minHeight.empty()) {
                    style += " min-height: " + minHeight + ";";
                }
                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;";
                }

                sect.setAttribute("style", style.c_str());
                std::string cls = responsiveClass;
                if (!cssClass.empty()) {
                    cls = cssClass + " " + responsiveClass;
                }
                sect.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_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_maxWidth.empty()) mobileCSS += " max-width: " + m_maxWidth + " !important;";
                if (!m_minHeight.empty()) mobileCSS += " min-height: " + m_minHeight + " !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");
                    cssStyle.appendChild(libhtmlpp::TextElement(customCss.c_str()));
                    el.appendChild(cssStyle);
                }

                // Content text
                if (!content.empty()) {
                    sect.appendChild(libhtmlpp::TextElement(content.c_str()));
                }

                // Recursively render children
                const EditPlugin *cur = child;
                while (cur) {
                    cur->Render(sect);
                    cur = cur->nextElement();
                }

                el.appendChild(sect);
            }

            // --- Element Management ---

            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::Section* create() {
    return new blogi::webedit::Section();
}

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