/*******************************************************************************
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 CustomHtml : public EditPlugin {
        public:
            CustomHtml() {
                Type = "a12c3d4e-5f67-8901-abcd-ef2345678901";
            }

            virtual ~CustomHtml() = default;

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

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

            // --- Properties ---
        private:
            std::string htmlContent;
            std::string jsContent;
            std::string cssContent;
            std::string width = "";
            std::string height = "";

            // Visibility
            bool hidden = false;
            bool m_hidden = false;
            std::string m_width = "";
            std::string m_height = "";

        public:

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

                // HTML Content
                libhtmlpp::HtmlElement htmlLabel("label");
                htmlLabel.appendChild(libhtmlpp::TextElement("HTML Content: "));
                settings.appendChild(htmlLabel);
                libhtmlpp::HtmlElement htmlArea("textarea");
                htmlArea.setAttribute("name", "html_content");
                htmlArea.setAttribute("rows", "10");
                htmlArea.setAttribute("cols", "60");
                htmlArea.appendChild(libhtmlpp::TextElement(htmlContent.c_str()));
                settings.appendChild(htmlArea);

                // JavaScript Content
                libhtmlpp::HtmlElement jsLabel("label");
                jsLabel.appendChild(libhtmlpp::TextElement("JavaScript: "));
                settings.appendChild(jsLabel);
                libhtmlpp::HtmlElement jsArea("textarea");
                jsArea.setAttribute("name", "js_content");
                jsArea.setAttribute("rows", "8");
                jsArea.setAttribute("cols", "60");
                jsArea.appendChild(libhtmlpp::TextElement(jsContent.c_str()));
                settings.appendChild(jsArea);

                // CSS Content
                libhtmlpp::HtmlElement cssLabel("label");
                cssLabel.appendChild(libhtmlpp::TextElement("CSS: "));
                settings.appendChild(cssLabel);
                libhtmlpp::HtmlElement cssArea("textarea");
                cssArea.setAttribute("name", "css_content");
                cssArea.setAttribute("rows", "6");
                cssArea.setAttribute("cols", "60");
                cssArea.appendChild(libhtmlpp::TextElement(cssContent.c_str()));
                settings.appendChild(cssArea);
            }

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

            // --- 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 *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));
                    json_object_array_add(arr, f);
                };
                addField("html_content", "HTML Content", "textarea", "<div>Your custom HTML here</div>");
                addField("css_content", "CSS", "textarea", "color: red; font-size: 16px;");
                addField("js_content", "JavaScript", "textarea", "console.log(\"Hello from widget\");");
                addField("width", "Width", "text", "e.g. 100%", "desktop");
                addField("height", "Height", "text", "e.g. auto", "desktop");
                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));
                }
                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());

                // Visibility
                element->SetAttribute("hidden", hidden ? "true" : "false");
                element->SetAttribute("m_hidden", m_hidden ? "true" : "false");
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

                // Store content in nested CDATA elements to preserve special characters
                if (!htmlContent.empty()) {
                    tinyxml2::XMLElement* htmlEl = doc->NewElement("HtmlContent");
                    htmlEl->SetText(htmlContent.c_str());
                    element->InsertEndChild(htmlEl);
                }
                if (!jsContent.empty()) {
                    tinyxml2::XMLElement* jsEl = doc->NewElement("JsContent");
                    jsEl->SetText(jsContent.c_str());
                    element->InsertEndChild(jsEl);
                }
                if (!cssContent.empty()) {
                    tinyxml2::XMLElement* cssEl = doc->NewElement("CssContent");
                    cssEl->SetText(cssContent.c_str());
                    element->InsertEndChild(cssEl);
                }

                return element;
            }

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

                // 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);
                val = xml_data->Attribute("width");
                if (val) width = val;
                val = xml_data->Attribute("height");
                if (val) height = val;
                val = xml_data->Attribute("m_width");
                if (val) m_width = val;
                val = xml_data->Attribute("m_height");
                if (val) m_height = val;

                // Read nested content elements
                tinyxml2::XMLElement* htmlEl = xml_data->FirstChildElement("HtmlContent");
                if (htmlEl) {
                    val = htmlEl->GetText();
                    if (val) htmlContent = val;
                }
                tinyxml2::XMLElement* jsEl = xml_data->FirstChildElement("JsContent");
                if (jsEl) {
                    val = jsEl->GetText();
                    if (val) jsContent = val;
                }
                tinyxml2::XMLElement* cssEl = xml_data->FirstChildElement("CssContent");
                if (cssEl) {
                    val = cssEl->GetText();
                    if (val) cssContent = val;
                }
            }

            // --- JSON Properties Helpers ---
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "html_content", json_object_new_string(htmlContent.c_str()));
                json_object_object_add(obj, "js_content", json_object_new_string(jsContent.c_str()));
                json_object_object_add(obj, "css_content", json_object_new_string(cssContent.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, "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));
                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) {
                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, "html_content", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) htmlContent = val;
                }
                if (json_object_object_get_ex(obj, "js_content", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) jsContent = val;
                }
                if (json_object_object_get_ex(obj, "css_content", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) cssContent = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) height = val;
                }
                if (json_object_object_get_ex(obj, "m_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)) {
                    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);
                    }
                }

                json_object_put(obj);
            }

            // --- HTML Rendering ---
            void Render(libhtmlpp::HtmlElement &el) const override {
                // Unique CSS class for targeting
                std::string responsiveClass = std::string("we-") + getInstanceId().c_str();

                // Inject custom CSS if provided
                if (!cssContent.empty()) {
                    libhtmlpp::HtmlElement styleTag("style");
                    // Scope the CSS within the responsive class
                    std::string scopedCSS = "." + responsiveClass + " { " + cssContent + " }";
                    styleTag.appendChild(libhtmlpp::TextElement(scopedCSS.c_str()));
                    el.appendChild(styleTag);
                }

                // Mobile visibility override
                if (m_hidden || hidden) {
                    libhtmlpp::HtmlElement mobileStyle("style");
                    std::string mobileCSS;
                    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;";
                    std::string mediaRule = "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } }";
                    mobileStyle.appendChild(libhtmlpp::TextElement(mediaRule.c_str()));
                    el.appendChild(mobileStyle);
                } else if (!m_width.empty() || !m_height.empty()) {
                    libhtmlpp::HtmlElement mobileStyle("style");
                    std::string mobileCSS;
                    if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                    if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                    std::string mediaRule = "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } }";
                    mobileStyle.appendChild(libhtmlpp::TextElement(mediaRule.c_str()));
                    el.appendChild(mobileStyle);
                }

                // Wrapper div
                libhtmlpp::HtmlElement wrapper("div");
                std::string style;
                if (hidden) style += "display: none;";
                if (!width.empty()) style += " width: " + width + ";";
                if (!height.empty()) style += " height: " + height + ";";
                if (!style.empty()) wrapper.setAttribute("style", style.c_str());
                wrapper.setAttribute("class", responsiveClass.c_str());

                // Inject custom HTML
                if (!htmlContent.empty()) {
                    try {
                        libhtmlpp::HtmlString htmlBuf("<span>" + htmlContent + "</span>");
                        libhtmlpp::Element &parsed = htmlBuf.parse();
                        wrapper.appendChild(parsed);
                    } catch (...) {
                        // Fallback: insert as plain text
                        libhtmlpp::HtmlElement span("span");
                        span.appendChild(libhtmlpp::TextElement(htmlContent.c_str()));
                        wrapper.appendChild(span);
                    }
                }

                el.appendChild(wrapper);

                // Inject custom JavaScript at the end
                if (!jsContent.empty()) {
                    libhtmlpp::HtmlElement scriptTag("script");
                    // Wrap in an IIFE scoped to this widget instance
                    std::string wrappedJs = "(function() {\n"
                        "var widget = document.querySelector('." + responsiveClass + "');\n"
                        + jsContent +
                        "\n})();";
                    scriptTag.appendChild(libhtmlpp::TextElement(wrappedJs.c_str()));
                    el.appendChild(scriptTag);
                }
            }

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

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

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

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