/*******************************************************************************
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 <vector>

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

#include "plugin.h"

extern "C" {
    namespace blogi::webedit {

        class List : public EditPlugin {
        private:
            // List type: "ul" (unordered) or "ol" (ordered)
            std::string listType = "ul";

            // Items stored as pipe-separated text (each item can contain HTML from rich text editor)
            std::vector<std::string> items;

            // Styling
            std::string fontFamily      = "";
            std::string fontSize        = "16px";
            std::string fontColor       = "var(--blogi-text)";
            std::string lineHeight      = "1.6";
            std::string listStyleType   = "";  // disc, circle, square, decimal, etc. (empty = browser default)
            std::string direction       = "vertical"; // "vertical" or "horizontal"
            std::string gap             = "";
            std::string alignItems      = "";
            std::string padding         = "0 0 0 20px";
            std::string margin          = "8px 0";
            std::string width           = "";
            std::string height          = "";

            // Light mode overrides
            std::string l_fontColor     = "";

            // Mobile overrides
            std::string m_fontSize      = "";
            std::string m_padding       = "";
            std::string m_direction     = "";
            std::string m_width         = "";
            std::string m_height        = "";

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

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

            // Helper: join items to a single string for XML storage
            std::string joinItems(const std::string &sep) const {
                std::string result;
                for (size_t i = 0; i < items.size(); ++i) {
                    if (i > 0) result += sep;
                    result += items[i];
                }
                return result;
            }

            // Helper: split string by separator
            static std::vector<std::string> splitItems(const std::string &str, const std::string &sep) {
                std::vector<std::string> result;
                if (str.empty()) return result;
                size_t start = 0;
                size_t pos;
                while ((pos = str.find(sep, start)) != std::string::npos) {
                    result.push_back(str.substr(start, pos - start));
                    start = pos + sep.size();
                }
                result.push_back(str.substr(start));
                return result;
            }

        public:
            List() {
                Type = "a1b2c3d4-list-4e5f-6a7b-8c9d0e1f2a3b";
                items.push_back("Item 1");
                items.push_back("Item 2");
                items.push_back("Item 3");
            }

            virtual ~List() = default;

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

            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 << "ListPlugin 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("List Settings"));
                settings.appendChild(title);
            }

            // --- JSON API ---
            void JsonApi(json_object *request, json_object *response) override {
                if (!request) {
                    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 || 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) {
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object_object_add(response, "plugin_type", json_object_new_string("List"));
                }
            }

            // --- 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("list_type", "List Type", "select", nullptr, "all",
                         mkOpts({"ul", "ol"}));
                addField("list_style_type", "List Style", "select", nullptr, "all",
                         mkOpts({"", "disc", "circle", "square", "decimal", "decimal-leading-zero",
                                 "lower-alpha", "upper-alpha", "lower-roman", "upper-roman", "none"}));
                addField("direction", "Direction", "select", nullptr, "desktop",
                         mkOpts({"vertical", "horizontal"}));
                addField("gap", "Gap", "text", "8px");
                addField("align_items", "Align Items", "select", nullptr, "all",
                         mkOpts({"", "flex-start", "center", "flex-end", "stretch", "baseline"}));
                addField("items", "Items (one per line)", "textarea", "Item 1\nItem 2\nItem 3");
                addField("font_family", "Font Family", "text", "Arial, sans-serif");
                addField("font_size", "Font Size", "text", "16px", "desktop");
                addField("font_color", "Text Color (Dark)", "color_var");
                addField("l_font_color", "Text Color (Light)", "color_var", nullptr, "light");
                addField("line_height", "Line Height", "text", "1.6");
                addField("padding", "Padding", "text", "0 0 0 20px", "desktop");
                addField("margin", "Margin", "text", "8px 0");
                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));
                }
                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("list_type", listType.c_str());
                element->SetAttribute("list_style_type", listStyleType.c_str());
                element->SetAttribute("direction", direction.c_str());
                element->SetAttribute("gap", gap.c_str());
                element->SetAttribute("align_items", alignItems.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("line_height", lineHeight.c_str());
                element->SetAttribute("padding", padding.c_str());
                element->SetAttribute("margin", margin.c_str());
                element->SetAttribute("width", width.c_str());
                element->SetAttribute("height", height.c_str());

                element->SetAttribute("l_font_color", l_fontColor.c_str());

                element->SetAttribute("m_font_size", m_fontSize.c_str());
                element->SetAttribute("m_padding", m_padding.c_str());
                element->SetAttribute("m_direction", m_direction.c_str());
                element->SetAttribute("m_width", m_width.c_str());
                element->SetAttribute("m_height", m_height.c_str());

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

                // Store items as child <Item> elements
                for (const auto &item : items) {
                    tinyxml2::XMLElement *li = doc->NewElement("Item");
                    li->SetText(item.c_str());
                    element->InsertEndChild(li);
                }

                return element;
            }

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

                val = xml_data->Attribute("list_type");       if (val) listType = val;
                val = xml_data->Attribute("list_style_type"); if (val) listStyleType = val;
                val = xml_data->Attribute("direction");       if (val) direction = val;
                val = xml_data->Attribute("gap");              if (val) gap = val;
                val = xml_data->Attribute("align_items");     if (val) alignItems = 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("line_height");     if (val) lineHeight = val;
                val = xml_data->Attribute("padding");         if (val) padding = val;
                val = xml_data->Attribute("margin");          if (val) margin = val;
                val = xml_data->Attribute("width");           if (val) width = val;
                val = xml_data->Attribute("height");          if (val) height = val;

                val = xml_data->Attribute("l_font_color");
                if (val) l_fontColor = val;

                val = xml_data->Attribute("m_font_size");
                if (val) m_fontSize = val;
                val = xml_data->Attribute("m_padding");
                if (val) m_padding = val;
                val = xml_data->Attribute("m_direction");
                if (val) m_direction = val;
                val = xml_data->Attribute("m_width");
                if (val) m_width = val;
                val = xml_data->Attribute("m_height");
                if (val) m_height = val;

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

                // Read items from child <Item> elements
                items.clear();
                for (tinyxml2::XMLElement *li = xml_data->FirstChildElement("Item"); li; li = li->NextSiblingElement("Item")) {
                    const char *text = li->GetText();
                    if (text) items.push_back(text);
                }
            }

            // --- JSON Properties ---
            std::string toPropertiesJson() {
                json_object *obj = json_object_new_object();
                json_object_object_add(obj, "list_type", json_object_new_string(listType.c_str()));
                json_object_object_add(obj, "list_style_type", json_object_new_string(listStyleType.c_str()));
                json_object_object_add(obj, "direction", json_object_new_string(direction.c_str()));
                json_object_object_add(obj, "gap", json_object_new_string(gap.c_str()));
                json_object_object_add(obj, "align_items", json_object_new_string(alignItems.c_str()));
                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, "line_height", json_object_new_string(lineHeight.c_str()));
                json_object_object_add(obj, "padding", json_object_new_string(padding.c_str()));
                json_object_object_add(obj, "margin", json_object_new_string(margin.c_str()));
                json_object_object_add(obj, "width", json_object_new_string(width.c_str()));
                json_object_object_add(obj, "height", json_object_new_string(height.c_str()));
                json_object_object_add(obj, "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_padding", json_object_new_string(m_padding.c_str()));
                json_object_object_add(obj, "m_direction", json_object_new_string(m_direction.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()));

                // Items as newline-separated string for textarea editing
                std::string itemsStr;
                for (size_t i = 0; i < items.size(); ++i) {
                    if (i > 0) itemsStr += "\n";
                    itemsStr += items[i];
                }
                json_object_object_add(obj, "items", json_object_new_string(itemsStr.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, "list_type", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) listType = val;
                }
                if (json_object_object_get_ex(obj, "list_style_type", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) listStyleType = val;
                }
                if (json_object_object_get_ex(obj, "direction", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) direction = val;
                }
                if (json_object_object_get_ex(obj, "gap", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) gap = val;
                }
                if (json_object_object_get_ex(obj, "align_items", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) alignItems = val;
                }
                if (json_object_object_get_ex(obj, "font_family", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) 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, "line_height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val && val[0]) lineHeight = 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, "margin", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) margin = val;
                }
                if (json_object_object_get_ex(obj, "width", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) width = val;
                }
                if (json_object_object_get_ex(obj, "height", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) height = val;
                }
                if (json_object_object_get_ex(obj, "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_padding", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_padding = val;
                }
                if (json_object_object_get_ex(obj, "m_direction", &val_obj)) {
                    val = json_object_get_string(val_obj); if (val) m_direction = 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;
                }

                // Items from newline-separated string
                if (json_object_object_get_ex(obj, "items", &val_obj)) {
                    val = json_object_get_string(val_obj);
                    if (val) {
                        items = splitItems(val, "\n");
                        // Remove empty trailing items
                        while (!items.empty() && items.back().empty())
                            items.pop_back();
                    }
                }

                json_object_put(obj);
            }

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

                std::string tag = (listType == "ol") ? "ol" : "ul";
                libhtmlpp::HtmlElement list(tag.c_str());

                bool horiz = (direction == "horizontal");

                std::string style;
                if (horiz) {
                    style += "display: flex; flex-direction: row; flex-wrap: wrap;";
                    if (!gap.empty()) style += " gap: " + gap + ";";
                    if (!alignItems.empty()) style += " align-items: " + alignItems + ";";
                } else {
                    if (!gap.empty()) style += "display: flex; flex-direction: column; gap: " + gap + ";";
                }
                if (!fontFamily.empty()) style += " font-family: " + fontFamily + ";";
                if (!fontSize.empty())   style += " font-size: " + fontSize + ";";
                if (!fontColor.empty())  style += " color: " + fontColor + ";";
                if (!lineHeight.empty()) style += " line-height: " + lineHeight + ";";
                if (!listStyleType.empty()) style += " list-style-type: " + listStyleType + ";";
                if (!padding.empty())    style += " padding: " + padding + ";";
                if (!margin.empty())     style += " margin: " + margin + ";";
                if (!width.empty())      style += " width: " + width + ";";
                if (!height.empty())     style += " height: " + height + ";";
                if (hidden) style += " display: none;";

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

                for (const auto &item : items) {
                    libhtmlpp::HtmlElement li("li");
                    if (!item.empty()) {
                        try {
                            libhtmlpp::HtmlString htmlBuf("<span>" + item + "</span>");
                            libhtmlpp::Element &parsed = htmlBuf.parse();
                            li.appendChild(parsed);
                        } catch (...) {
                            li.appendChild(libhtmlpp::TextElement(item.c_str()));
                        }
                    }
                    list.appendChild(li);
                }

                // Render child widgets — each child gets its own <li>
                const EditPlugin *cur = child;
                while (cur) {
                    libhtmlpp::HtmlElement li("li");
                    cur->Render(li);
                    list.appendChild(li);
                    cur = cur->nextElement();
                }

                // Mobile responsive overrides
                std::string mobileCSS;
                if (!m_fontSize.empty()) mobileCSS += " font-size: " + m_fontSize + " !important;";
                if (!m_padding.empty())  mobileCSS += " padding: " + m_padding + " !important;";
                if (!m_width.empty()) mobileCSS += " width: " + m_width + " !important;";
                if (!m_height.empty()) mobileCSS += " height: " + m_height + " !important;";
                if (!m_direction.empty()) {
                    if (m_direction == "horizontal")
                        mobileCSS += " flex-direction: row !important;";
                    else
                        mobileCSS += " flex-direction: column !important;";
                }
                if (m_hidden) mobileCSS += " display: none !important;";
                else if (hidden) mobileCSS += " display: flex !important;";

                // Light mode overrides
                std::string lightCSS;
                if (!l_fontColor.empty()) lightCSS += " color: " + l_fontColor + " !important;";

                std::string allMediaCSS;
                if (!mobileCSS.empty()) {
                    allMediaCSS += "@media (max-width: 768px) { ." + responsiveClass + " {" + mobileCSS + " } } ";
                }
                if (!lightCSS.empty()) {
                    allMediaCSS += "@media (prefers-color-scheme: light) { ." + responsiveClass + " {" + lightCSS + " } }";
                }

                if (!allMediaCSS.empty()) {
                    libhtmlpp::HtmlElement styleTag("style");
                    styleTag.appendChild(libhtmlpp::TextElement(allMediaCSS.c_str()));
                    el.appendChild(styleTag);
                }

                if (!customCss.empty()) {
                    libhtmlpp::HtmlElement cssStyle("style");
                    cssStyle.appendChild(libhtmlpp::TextElement(customCss.c_str()));
                    el.appendChild(cssStyle);
                }

                el.appendChild(list);
            }

            // --- Container widget: children become <li> entries ---
            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 {
                if (!child) {
                    setChildElement(el);
                    return;
                }
                EditPlugin *cur = child;
                while (cur->nextElement()) {
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
                cur->setNextEl(const_cast<EditPlugin*>(&el));
            }
            void remNextElement(const EditPlugin &el) override {
                if (child == &el) {
                    unsetChildElement(el);
                    return;
                }
                EditPlugin *cur = child;
                while (cur) {
                    if (cur->nextElement() == &el) {
                        cur->setNextEl(const_cast<EditPlugin*>(el.nextElement()));
                        return;
                    }
                    cur = const_cast<EditPlugin*>(cur->nextElement());
                }
            }
        };
    };
}

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

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