/*******************************************************************************
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 Grid : public EditPlugin {
        private:
            std::string columns       = "1fr 1fr";      // CSS grid-template-columns
            std::string rows          = "auto";          // CSS grid-template-rows
            std::string gap           = "10px";          // CSS gap
            std::string backgroundColor = "";
            std::string padding       = "10px";
            std::string cssClass      = "";
            std::string borderRadius  = "";
            std::string borderStyle   = "";
            std::string opacity       = "";
            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_columns       = "";
            std::string m_rows          = "";
            std::string m_gap           = "";
            std::string m_padding       = "";
            std::string m_backgroundColor = "";
            std::string m_borderRadius  = "";
            std::string m_borderStyle   = "";
            std::string m_opacity       = "";
            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:
            Grid() {
                Type = "c44c9af1-2f65-4e3f-a4c6-9f56d1b656c4";
            }

            virtual ~Grid() = default;

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

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

                // Columns
                libhtmlpp::HtmlElement colLabel("label");
                colLabel.appendChild(libhtmlpp::TextElement("Columns (CSS grid-template-columns): "));
                settings.appendChild(colLabel);
                libhtmlpp::HtmlElement colInput("input");
                colInput.setAttribute("type", "text");
                colInput.setAttribute("name", "columns");
                colInput.setAttribute("value", columns.c_str());
                colInput.setAttribute("placeholder", "e.g. 1fr 1fr 1fr");
                settings.appendChild(colInput);

                // Rows
                libhtmlpp::HtmlElement rowLabel("label");
                rowLabel.appendChild(libhtmlpp::TextElement("Rows (CSS grid-template-rows): "));
                settings.appendChild(rowLabel);
                libhtmlpp::HtmlElement rowInput("input");
                rowInput.setAttribute("type", "text");
                rowInput.setAttribute("name", "rows");
                rowInput.setAttribute("value", rows.c_str());
                rowInput.setAttribute("placeholder", "e.g. auto auto");
                settings.appendChild(rowInput);

                // Gap
                libhtmlpp::HtmlElement gapLabel("label");
                gapLabel.appendChild(libhtmlpp::TextElement("Gap: "));
                settings.appendChild(gapLabel);
                libhtmlpp::HtmlElement gapInput("input");
                gapInput.setAttribute("type", "text");
                gapInput.setAttribute("name", "gap");
                gapInput.setAttribute("value", gap.c_str());
                settings.appendChild(gapInput);

                // Background color
                libhtmlpp::HtmlElement bgLabel("label");
                bgLabel.appendChild(libhtmlpp::TextElement("Background Color: "));
                settings.appendChild(bgLabel);
                libhtmlpp::HtmlElement bgInput("input");
                bgInput.setAttribute("type", "color");
                bgInput.setAttribute("name", "background_color");
                bgInput.setAttribute("value", backgroundColor.c_str());
                settings.appendChild(bgInput);
            }

            // --- 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, "add") == 0) {
                    json_object *type_id_obj = nullptr;
                    const char *type_id = nullptr;
                    if (json_object_object_get_ex(request, "type_id", &type_id_obj)) {
                        type_id = json_object_get_string(type_id_obj);
                    }
                    if (type_id) {
                        std::unique_ptr<EditPlugin> new_el = std::make_unique<Grid>();
                        if (new_el) {
                            this->addNextElement(*new_el);
                        }
                    }
                } else if (strcmp(action, "delete") == 0) {
                    // Delete child logic
                    const char *target_id = nullptr;
                    json_object *tid_obj = nullptr;
                    if (json_object_object_get_ex(request, "target_id", &tid_obj)) {
                        target_id = json_object_get_string(tid_obj);
                    }
                    if (target_id && child) {
                        if (child->getInstanceId() == target_id) {
                            unsetChildElement(*child);
                        }
                    }
                } 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) {
                    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("Grid"));
                }
            }

            // --- 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("columns", "Columns", "text", "e.g. 1fr 1fr 1fr", "desktop");
                addField("rows", "Rows", "text", "e.g. auto auto", "desktop");
                addField("gap", "Gap", "text", "10px", "desktop");
                addField("background_color", "Background Color (Dark)", "color_var", nullptr, "desktop");
                addField("l_background_color", "Background Color (Light)", "color_var", nullptr, "light");
                addField("padding", "Padding", "text", "10px", "desktop");
                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-grid");
                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());
                element->SetAttribute("columns", columns.c_str());
                element->SetAttribute("rows", rows.c_str());
                element->SetAttribute("gap", gap.c_str());
                element->SetAttribute("background_color", backgroundColor.c_str());
                element->SetAttribute("padding", padding.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("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_columns", m_columns.c_str());
                element->SetAttribute("m_rows", m_rows.c_str());
                element->SetAttribute("m_gap", m_gap.c_str());
                element->SetAttribute("m_padding", m_padding.c_str());
                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_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);
                }

                // 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* val = nullptr;

                val = xml_data->Attribute("columns");
                if (val) columns = val;

                val = xml_data->Attribute("rows");
                if (val) rows = val;

                val = xml_data->Attribute("gap");
                if (val) gap = val;

                val = xml_data->Attribute("background_color");
                if (val) backgroundColor = val;

                val = xml_data->Attribute("padding");
                if (val) padding = 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("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_columns");
                if (val) m_columns = val;
                val = xml_data->Attribute("m_rows");
                if (val) m_rows = val;
                val = xml_data->Attribute("m_gap");
                if (val) m_gap = val;
                val = xml_data->Attribute("m_padding");
                if (val) m_padding = val;
                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_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
                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, "columns", json_object_new_string(columns.c_str()));
                json_object_object_add(obj, "rows", json_object_new_string(rows.c_str()));
                json_object_object_add(obj, "gap", json_object_new_string(gap.c_str()));
                json_object_object_add(obj, "background_color", json_object_new_string(backgroundColor.c_str()));
                json_object_object_add(obj, "padding", json_object_new_string(padding.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, "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_columns", json_object_new_string(m_columns.c_str()));
                json_object_object_add(obj, "m_rows", json_object_new_string(m_rows.c_str()));
                json_object_object_add(obj, "m_gap", json_object_new_string(m_gap.c_str()));
                json_object_object_add(obj, "m_padding", json_object_new_string(m_padding.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_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, "columns", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) columns = val;
                }
                if (json_object_object_get_ex(obj, "rows", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) rows = val;
                }
                if (json_object_object_get_ex(obj, "gap", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) gap = val;
                }
                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, "padding", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) padding = 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, "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_columns", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_columns = val;
                }
                if (json_object_object_get_ex(obj, "m_rows", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_rows = val;
                }
                if (json_object_object_get_ex(obj, "m_gap", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_gap = 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_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_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)) {
                    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 {
                libhtmlpp::HtmlElement grid("div");

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

                std::string style = "display: grid; box-sizing: border-box; min-width: 0;";
                style += " grid-template-columns: " + columns + ";";
                style += " grid-template-rows: " + rows + ";";
                style += " gap: " + gap + ";";
                style += " padding: " + padding + ";";
                if (!width.empty()) {
                    style += " width: " + width + ";";
                }
                if (!height.empty()) {
                    style += " height: " + height + ";";
                }
                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 (!verticalAlign.empty()) {
                    if (verticalAlign == "top") style += " align-items: start;";
                    else if (verticalAlign == "center") style += " align-items: center;";
                    else if (verticalAlign == "bottom") style += " align-items: end;";
                }
                if (hidden) {
                    style += " display: none;";
                }

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

                // Mobile responsive overrides via media query
                std::string mobileCSS;
                if (!m_columns.empty()) mobileCSS += " grid-template-columns: " + m_columns + " !important;";
                if (!m_rows.empty()) mobileCSS += " grid-template-rows: " + m_rows + " !important;";
                if (!m_gap.empty()) mobileCSS += " gap: " + m_gap + " !important;";
                if (!m_padding.empty()) mobileCSS += " padding: " + m_padding + " !important;";
                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_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (!m_verticalAlign.empty()) {
                    if (m_verticalAlign == "top") mobileCSS += " align-items: start !important;";
                    else if (m_verticalAlign == "center") mobileCSS += " align-items: center !important;";
                    else if (m_verticalAlign == "bottom") mobileCSS += " align-items: end !important;";
                }
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) mobileCSS += " display: grid !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);
                }

                // Render children into grid cells
                const EditPlugin *cur = child;
                while (cur) {
                    libhtmlpp::HtmlElement cell("div");
                    cell.setAttribute("style", "min-width: 0; box-sizing: border-box;");
                    cur->Render(cell);
                    grid.appendChild(cell);
                    cur = cur->nextElement();
                }

                el.appendChild(grid);
            }

            // --- Element Management (Grid can have children) ---
            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::Grid* create() {
    return new blogi::webedit::Grid();
}

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