package com.realnet.OpenAi.Services;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class HtmlBuilder2 {

	// Plugin registry for special sections
	private static final Map<String, Function<Object, String>> SPECIAL_RENDERERS = new HashMap<>();

	static {
		// Menu renderer
		SPECIAL_RENDERERS.put("menu", new Function<Object, String>() {
			public String apply(Object obj) {
				return renderMenu(obj);
			}
		});

		// Actions renderer
		SPECIAL_RENDERERS.put("actions", new Function<Object, String>() {
			public String apply(Object obj) {
				return renderActions(obj);
			}
		});

		// Logo renderer
		SPECIAL_RENDERERS.put("logo", new Function<Object, String>() {
			public String apply(Object obj) {
				return "<div class=\"logo\">" + obj + "</div>";
			}
		});

		SPECIAL_RENDERERS.put("Header Section", new Function<Object, String>() {
			public String apply(Object obj) {
				return renderHeaderSection(obj);
			}
		});

		SPECIAL_RENDERERS.put("Blog Template", new Function<Object, String>() {
		    public String apply(Object obj) {
		        return renderBlogTemplate((Map<String, Object>) obj);
		    }
		});

		// More renderers can be added here dynamically
	}

	public static String buildHtml(Object node) {
		if (node instanceof Map) {
			return renderFromMap((Map<String, Object>) node);
		} else if (node instanceof List) {
			return renderFromList((List<Object>) node);
		} else if (node != null) {
			return String.valueOf(node);
		} else {
			return "";
		}
	}

	private static String renderFromMap(Map<String, Object> node) {
		StringBuilder html = new StringBuilder();

		String type = getString(node, "type", "div");
		String tag = resolveTag(getString(node, "tag", ""), type);

		if (tag.isEmpty()) {
			tag = TYPE_TAG_MAP.getOrDefault(type.toLowerCase(), type);
		}

		html.append("<").append(tag);

		String className = getString(node, "class", "");
		String id = getString(node, "id", "");

		if (!className.isEmpty())
			html.append(" class=\"").append(className).append("\"");
		if (!id.isEmpty())
			html.append(" id=\"").append(id).append("\"");

		// Flat string attributes
		for (Map.Entry<String, Object> entry : node.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (!Arrays.asList("tag", "type", "class", "id", "content", "children").contains(key)
					&& !(value instanceof Map || value instanceof List)) {
				html.append(" ").append(key).append("=\"").append(value).append("\"");
			}
		}

		html.append(">");

		// Standard content
		if (node.containsKey("content")) {
			html.append(node.get("content"));
		}

		// Plugin-based section renderers
		for (Map.Entry<String, Function<Object, String>> plugin : SPECIAL_RENDERERS.entrySet()) {
			if (node.containsKey(plugin.getKey())) {
				html.append(plugin.getValue().apply(node.get(plugin.getKey())));
			}
		}

		// Children
		if (node.containsKey("children")) {
			html.append(buildHtml(node.get("children")));
		}

		html.append("</").append(tag).append(">");
		return html.toString();
	}

	private static String renderFromList(List<Object> list) {
		StringBuilder html = new StringBuilder();
		for (Object obj : list) {
			html.append(buildHtml(obj));
		}
		return html.toString();
	}

	private static final Map<String, String> TYPE_TAG_MAP = new HashMap<>();
	static {
		TYPE_TAG_MAP.put("navbar", "nav");
		TYPE_TAG_MAP.put("footer", "footer");
		TYPE_TAG_MAP.put("article", "article");
		// add more if needed
	}

	private static String getString(Map<String, Object> map, String key, String defaultValue) {
		Object val = map.get(key);
		return (val instanceof String) ? (String) val : defaultValue;
	}

	private static String resolveTag(String tag, String type) {
		if (tag != null && !tag.isEmpty())
			return tag;
		if ("navbar".equalsIgnoreCase(type))
			return "nav";
		return type != null ? type : "div";
	}

	// -------- Renderers for plugins --------

	private static String renderMenu(Object obj) {
		StringBuilder html = new StringBuilder("<ul class=\"main-menu\">");

		List<Object> menu = (List<Object>) obj;
		for (Object item : menu) {
			if (item instanceof String) {
				html.append("<li><a href=\"#\">").append(item).append("</a></li>");
			} else if (item instanceof Map) {
				Map<String, Object> dropdownItem = (Map<String, Object>) item;
				html.append("<li class=\"dropdown\">");
				html.append("<a href=\"#\">").append(dropdownItem.get("title")).append("</a>");

				if (dropdownItem.containsKey("dropdown")) {
					html.append(renderDropdown(dropdownItem.get("dropdown")));
				}

				html.append("</li>");
			}
		}

		html.append("</ul>");
		return html.toString();
	}

	private static String renderDropdown(Object obj) {
		StringBuilder html = new StringBuilder("<div class=\"dropdown-content\"><div class=\"dropdown-columns\">");

		Map<String, Object> dropdown = (Map<String, Object>) obj;
		List<Map<String, Object>> columns = (List<Map<String, Object>>) dropdown.get("columns");

		for (Map<String, Object> column : columns) {
			html.append("<div class=\"column\">");
			html.append("<h4>").append(column.get("title")).append("</h4>");
			html.append("<ul>");

			if (column.containsKey("items")) {
				List<Map<String, Object>> items = (List<Map<String, Object>>) column.get("items");
				for (Map<String, Object> item : items) {
					html.append("<li>");
					html.append("<span class=\"icon\">").append(item.get("icon")).append("</span>");
					html.append("<div class=\"info\">").append("<strong>").append(item.get("title")).append("</strong>")
							.append("<p>").append(item.get("description")).append("</p>").append("</div>");
					html.append("</li>");
				}
			} else if (column.containsKey("blogs")) {
				List<Map<String, Object>> blogs = (List<Map<String, Object>>) column.get("blogs");
				for (Map<String, Object> blog : blogs) {
					html.append("<li><strong>").append(blog.get("title")).append("</strong>");
					html.append("<p>").append(blog.get("description")).append("</p>");
					html.append("<a href=\"#\">").append(blog.get("cta")).append("</a></li>");
				}
				if (column.containsKey("footerLink")) {
					html.append("<div class=\"footer-link\"><a href=\"#\">").append(column.get("footerLink"))
							.append("</a></div>");
				}
			}

			html.append("</ul></div>");
		}

		html.append("</div></div>");
		return html.toString();
	}

	private static String renderActions(Object obj) {
		StringBuilder html = new StringBuilder("<div class=\"navbar-actions\">");

		List<Map<String, Object>> actions = (List<Map<String, Object>>) obj;
		for (Map<String, Object> action : actions) {
			String label = getString(action, "label", "Button");
			String variant = getString(action, "variant", "");
			String btnClass = "join-btn";
			if (!variant.isEmpty())
				btnClass += " " + variant;

			html.append("<button class=\"").append(btnClass).append("\">").append(label).append("</button>");
		}

		html.append("</div>");
		return html.toString();
	}

	private static String renderHeaderSection(Object obj) {
		Map<String, Object> data = (Map<String, Object>) obj;

		StringBuilder html = new StringBuilder();
		String sectionClass = getString(data, "class", "");
		html.append("<section");
		if (!sectionClass.isEmpty()) {
			html.append(" class=\"").append(sectionClass).append("\"");
		}
		html.append(">");

		String heading = getString(data, "heading", "");
		if (!heading.isEmpty()) {
			html.append("<h1>").append(heading).append("</h1>");
		}

		String subheading = getString(data, "subheading", "");
		if (!subheading.isEmpty()) {
			html.append("<p>").append(subheading).append("</p>");
		}

		if (data.containsKey("buttons")) {
			Map<String, Object> buttons = (Map<String, Object>) data.get("buttons");
			String btnClass = getString(buttons, "class", "");
			List<String> items = (List<String>) buttons.get("items");

			html.append("<div");
			if (!btnClass.isEmpty()) {
				html.append(" class=\"").append(btnClass).append("\"");
			}
			html.append(">");
			for (String label : items) {
				html.append("<button>").append(label).append("</button>");
			}
			html.append("</div>");
		}

		html.append("</section>");
		return html.toString();
	}
	
	private static String renderBlogTemplate(Map<String, Object> node) {
	    StringBuilder html = new StringBuilder();
	    html.append("<section class=\"blog-template\">");

	    // Header
	    if (node.containsKey("header")) {
	        Map<String, Object> header = (Map<String, Object>) node.get("header");
	        html.append("<header class=\"blog-header\">")
	            .append("<h1><span class=\"icon\">")
	            .append(getString(header, "icon", "💡"))
	            .append("</span> ")
	            .append(getString(header, "title", "Blog Title"))
	            .append("</h1></header>");
	    }

	    // Navigation
	    if (node.containsKey("navigation")) {
	        List<String> navItems = (List<String>) node.get("navigation");
	        html.append("<nav class=\"blog-nav\"><ul>");
	        for (String item : navItems) {
	            html.append("<li><a href=\"#\">").append(item).append("</a></li>");
	        }
	        html.append("</ul></nav>");
	    }

	    // Layout Columns
	    if (node.containsKey("layout")) {
	        Map<String, Object> layout = (Map<String, Object>) node.get("layout");
	        List<Map<String, Object>> columns = (List<Map<String, Object>>) layout.get("columns");

	        html.append("<div class=\"blog-layout\">");

	        for (Map<String, Object> col : columns) {
	            String type = getString(col, "type", "");

	            if ("main".equalsIgnoreCase(type)) {
	                html.append("<main class=\"main-column\">");
	                List<Map<String, Object>> blocks = (List<Map<String, Object>>) col.get("contentBlocks");
	                for (Map<String, Object> block : blocks) {
	                    html.append("<div class=\"content-block\">")
	                        .append("<h2>").append(getString(block, "heading", "")).append("</h2>")
	                        .append("<p>").append(getString(block, "text", "")).append("</p>")
	                        .append("</div>");
	                }
	                html.append("</main>");
	            }

	            if ("sidebar".equalsIgnoreCase(type)) {
	                html.append("<aside class=\"sidebar-column\">");
	                List<String> widgets = (List<String>) col.get("widgets");
	                for (String widget : widgets) {
	                    String emoji = getWidgetIcon(widget);
	                    html.append("<div class=\"widget\">").append(emoji).append(" ").append(widget).append("</div>");
	                }
	                html.append("</aside>");
	            }
	        }

	        html.append("</div>");
	    }

	    html.append("</section>");
	    return html.toString();
	}
	private static String getWidgetIcon(String widget) {
	    widget = widget.toLowerCase();
	    if (widget.contains("search")) return "🔍";
	    if (widget.contains("recent")) return "📝";
	    if (widget.contains("newsletter")) return "📬";
	    return "📦";
	}



	// ------------- END --------------------
}
