/*******************************************************************************
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 TextBox : public EditPlugin {
        public:
            TextBox() {
                Type = "b33b8ef0-1e54-4d2e-93b5-8e45c0a65b35";
            }

            virtual ~TextBox() = default;

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

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

            // --- Properties ---
        private:
            std::string content;
            std::string fontFamily   = "";
            std::string fontSize     = "";
            std::string fontColor    = "";
            std::string textAlign    = "left";
            std::string fontWeight   = "normal";
            std::string fontStyle    = "normal";
            std::string whiteSpace   = "normal";

            // Dimensions
            std::string width        = "";
            std::string height       = "";

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

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

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

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

        public:

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

                // Font family
                libhtmlpp::HtmlElement ffLabel("label");
                ffLabel.appendChild(libhtmlpp::TextElement("Font Family: "));
                settings.appendChild(ffLabel);
                libhtmlpp::HtmlElement ffInput("input");
                ffInput.setAttribute("type", "text");
                ffInput.setAttribute("name", "font_family");
                ffInput.setAttribute("value", fontFamily.c_str());
                settings.appendChild(ffInput);

                // Font size
                libhtmlpp::HtmlElement fsLabel("label");
                fsLabel.appendChild(libhtmlpp::TextElement("Font Size: "));
                settings.appendChild(fsLabel);
                libhtmlpp::HtmlElement fsInput("input");
                fsInput.setAttribute("type", "text");
                fsInput.setAttribute("name", "font_size");
                fsInput.setAttribute("value", fontSize.c_str());
                settings.appendChild(fsInput);

                // Font color
                libhtmlpp::HtmlElement fcLabel("label");
                fcLabel.appendChild(libhtmlpp::TextElement("Font Color: "));
                settings.appendChild(fcLabel);
                libhtmlpp::HtmlElement fcInput("input");
                fcInput.setAttribute("type", "color");
                fcInput.setAttribute("name", "font_color");
                fcInput.setAttribute("value", fontColor.c_str());
                settings.appendChild(fcInput);

                // Text align
                libhtmlpp::HtmlElement taLabel("label");
                taLabel.appendChild(libhtmlpp::TextElement("Text Align: "));
                settings.appendChild(taLabel);
                libhtmlpp::HtmlElement taSelect("select");
                taSelect.setAttribute("name", "text_align");
                const char* aligns[] = {"left", "center", "right", "justify"};
                for (const char* a : aligns) {
                    libhtmlpp::HtmlElement opt("option");
                    opt.setAttribute("value", a);
                    if (textAlign == a) opt.setAttribute("selected", "selected");
                    opt.appendChild(libhtmlpp::TextElement(a));
                    taSelect.appendChild(opt);
                }
                settings.appendChild(taSelect);

                // Content textarea
                libhtmlpp::HtmlElement cLabel("label");
                cLabel.appendChild(libhtmlpp::TextElement("Content: "));
                settings.appendChild(cLabel);
                libhtmlpp::HtmlElement cArea("textarea");
                cArea.setAttribute("name", "content");
                cArea.setAttribute("rows", "6");
                cArea.setAttribute("cols", "60");
                cArea.appendChild(libhtmlpp::TextElement(content.c_str()));
                settings.appendChild(cArea);
            }

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

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

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

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

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

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

            // --- 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("content", "Content", "richtext");
                addField("width", "Width", "text", "e.g. 100%", "desktop");
                addField("height", "Height", "text", "e.g. auto", "desktop");
                addField("font_family", "Font Family", "text", "e.g. Arial, sans-serif");
                addField("font_size", "Font Size", "text", "e.g. 16px", "desktop");
                addField("font_color", "Font Color (Dark)", "color_var", nullptr, "desktop");
                addField("l_font_color", "Font Color (Light)", "color_var", nullptr, "light");
                addField("text_align", "Text Align", "select", nullptr, "desktop", mkOpts({"left","center","right","justify"}));
                addField("font_weight", "Font Weight", "select", nullptr, "all", mkOpts({"normal","bold","lighter","bolder"}));
                addField("font_style", "Font Style", "select", nullptr, "all", mkOpts({"normal","italic","oblique"}));
                addField("white_space", "Zeilenumbruch", "select", nullptr, "all", mkOpts({"normal","nowrap","pre","pre-wrap","pre-line","break-spaces"}));
                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("font_family", fontFamily.c_str());
                element->SetAttribute("font_size", fontSize.c_str());
                element->SetAttribute("font_color", fontColor.c_str());
                element->SetAttribute("text_align", textAlign.c_str());
                element->SetAttribute("font_weight", fontWeight.c_str());
                element->SetAttribute("font_style", fontStyle.c_str());
                element->SetAttribute("white_space", whiteSpace.c_str());

                // Dimensions
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());

                // Light mode overrides
                element->SetAttribute("l_font_color", l_fontColor.c_str());

                // Mobile overrides
                element->SetAttribute("m_font_size", m_fontSize.c_str());
                element->SetAttribute("m_font_color", m_fontColor.c_str());
                element->SetAttribute("m_text_align", m_textAlign.c_str());
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

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

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

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

                return element;
            }

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

                val = xml_data->GetText();
                if (val) content = val;

                val = xml_data->Attribute("font_family");
                if (val) fontFamily = val;

                val = xml_data->Attribute("font_size");
                if (val) fontSize = val;

                val = xml_data->Attribute("font_color");
                if (val) fontColor = val;

                val = xml_data->Attribute("text_align");
                if (val) textAlign = val;

                val = xml_data->Attribute("font_weight");
                if (val) fontWeight = val;

                val = xml_data->Attribute("font_style");
                if (val) fontStyle = val;

                val = xml_data->Attribute("white_space");
                if (val) whiteSpace = val;

                // Dimensions
                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_font_color");
                if (val) l_fontColor = val;

                // Mobile overrides
                val = xml_data->Attribute("m_font_size");
                if (val) m_fontSize = val;
                val = xml_data->Attribute("m_font_color");
                if (val) m_fontColor = val;
                val = xml_data->Attribute("m_text_align");
                if (val) m_textAlign = val;
                val = xml_data->Attribute("m_width");
                if (val) m_width = val;
                val = xml_data->Attribute("m_height");
                if (val) m_height = val;

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

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

            // --- JSON Properties Helpers ---
            std::string toPropertiesJson() {
                // Use json-c to properly escape HTML content with quotes/brackets
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "font_family", json_object_new_string(fontFamily.c_str()));
                json_object_object_add(obj, "font_size", json_object_new_string(fontSize.c_str()));
                json_object_object_add(obj, "font_color", json_object_new_string(fontColor.c_str()));
                json_object_object_add(obj, "text_align", json_object_new_string(textAlign.c_str()));
                json_object_object_add(obj, "font_weight", json_object_new_string(fontWeight.c_str()));
                json_object_object_add(obj, "font_style", json_object_new_string(fontStyle.c_str()));
                json_object_object_add(obj, "white_space", json_object_new_string(whiteSpace.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, "content", json_object_new_string(content.c_str()));
                json_object_object_add(obj, "l_font_color", json_object_new_string(l_fontColor.c_str()));
                json_object_object_add(obj, "m_font_size", json_object_new_string(m_fontSize.c_str()));
                json_object_object_add(obj, "m_font_color", json_object_new_string(m_fontColor.c_str()));
                json_object_object_add(obj, "m_text_align", json_object_new_string(m_textAlign.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, "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()));
                const char *result = json_object_to_json_string_ext(obj, JSON_C_TO_STRING_NOSLASHESCAPE);
                std::string out(result);
                json_object_put(obj);
                return out;
            }

            void fromPropertiesJson(const std::string &json) {
                // Use json-c to properly parse HTML content with quotes/brackets
                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, "font_family", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) fontFamily = val;
                }
                if (json_object_object_get_ex(obj, "font_size", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) fontSize = val;
                }
                if (json_object_object_get_ex(obj, "font_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) fontColor = val;
                }
                if (json_object_object_get_ex(obj, "text_align", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) textAlign = val;
                }
                if (json_object_object_get_ex(obj, "font_weight", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) fontWeight = val;
                }
                if (json_object_object_get_ex(obj, "font_style", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) fontStyle = val;
                }
                if (json_object_object_get_ex(obj, "white_space", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val && val[0]) whiteSpace = 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, "content", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) content = val; // Allow empty content
                }
                if (json_object_object_get_ex(obj, "l_font_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) l_fontColor = val;
                }
                if (json_object_object_get_ex(obj, "m_font_size", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_fontSize = val;
                }
                if (json_object_object_get_ex(obj, "m_font_color", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_fontColor = val;
                }
                if (json_object_object_get_ex(obj, "m_text_align", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) m_textAlign = 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, "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 box("div");

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

                std::string style = "padding: 8px;";
                if (!width.empty())      style += " width: " + width + ";";
                if (!height.empty())     style += " height: " + height + ";";
                if (!fontFamily.empty()) style += " font-family: " + fontFamily + ";";
                if (!fontSize.empty())   style += " font-size: " + fontSize + ";";
                if (!fontColor.empty())  style += " color: " + fontColor + ";";
                if (!textAlign.empty())  style += " text-align: " + textAlign + ";";
                if (fontWeight != "normal") style += " font-weight: " + fontWeight + ";";
                if (fontStyle != "normal") style += " font-style: " + fontStyle + ";";
                if (whiteSpace != "normal") style += " white-space: " + whiteSpace + ";";
                if (hidden) style += " display: none;";

                box.setAttribute("style", style.c_str());
                box.setAttribute("class", responsiveClass.c_str());

                // Mobile responsive overrides via media query
                std::string mobileCSS;
                if (!m_fontSize.empty()) mobileCSS += " font-size: " + m_fontSize + " !important;";
                if (!m_fontColor.empty()) mobileCSS += " color: " + m_fontColor + " !important;";
                if (!m_textAlign.empty()) mobileCSS += " text-align: " + m_textAlign + " !important;";
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) mobileCSS += " display: block !important;";

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

                // Light mode overrides via prefers-color-scheme
                std::string lightCSS;
                if (!l_fontColor.empty()) {
                    lightCSS += " color: " + l_fontColor + " !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);
                }

                if (!content.empty()) {
                    // Content contains HTML markup from the rich text editor;
                    // parse it into an element tree and append to the box.
                    // Auto-close any unclosed block-level tags before parsing.
                    std::string safeContent = content;
                    {
                        static const char* blockTags[] = {
                            "h1","h2","h3","h4","h5","h6",
                            "p","blockquote","pre","div","ul","ol","li",
                            "strong","em","b","i","a","span","code",nullptr
                        };
                        for (int t = 0; blockTags[t]; ++t) {
                            std::string tag = blockTags[t];
                            std::string openTag = "<" + tag;
                            std::string closeTag = "</" + tag + ">";
                            // Count opens (including with attributes like <h1 class="x">)
                            int opens = 0, closes = 0;
                            size_t pos = 0;
                            while ((pos = safeContent.find(openTag, pos)) != std::string::npos) {
                                size_t after = pos + openTag.size();
                                if (after < safeContent.size() &&
                                    (safeContent[after] == '>' || safeContent[after] == ' '))
                                    ++opens;
                                pos = after;
                            }
                            pos = 0;
                            while ((pos = safeContent.find(closeTag, pos)) != std::string::npos) {
                                ++closes;
                                pos += closeTag.size();
                            }
                            for (int i = closes; i < opens; ++i)
                                safeContent += closeTag;
                        }
                    }
                    try {
                        libhtmlpp::HtmlString htmlBuf("<div>" + safeContent + "</div>");
                        libhtmlpp::Element &parsed = htmlBuf.parse();
                        box.appendChild(parsed);
                    } catch (...) {
                        // Fallback: if parsing fails, insert as plain text
                        libhtmlpp::HtmlElement span("span");
                        span.appendChild(libhtmlpp::TextElement(content.c_str()));
                        box.appendChild(span);
                    }
                }

                el.appendChild(box);
            }

            // --- Element Management (TextBox is a leaf — no children) ---
            bool canHaveChildren() const override { return false; }
            bool haveChilds() override { return false; }

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

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

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