#include "ui/newtab.h"
#include "db/database.h"
#include <stdio.h>
#include <string.h>

// Helper to escape JSON strings (rudimentary)
static char *escape_json(const char *input) {
  if (!input)
    return g_strdup("");
  GString *str = g_string_new("");
  for (const char *p = input; *p; p++) {
    if (*p == '"')
      g_string_append(str, "\\\"");
    else if (*p == '\\')
      g_string_append(str, "\\\\");
    else if (*p == '\n')
      g_string_append(str, "\\n");
    else
      g_string_append_c(str, *p);
  }
  return g_string_free(str, FALSE);
}

char *newtab_get_html(Profile *profile) {
  // Load settings
  char *shortcuts_json = NULL;
  char *bg_image = NULL;
  char *font_color = NULL;

  if (profile && profile->db) {
    shortcuts_json = settings_get(profile->db, "newtab_shortcuts");
    bg_image = settings_get(profile->db, "newtab_bg_image");
    font_color = settings_get(profile->db, "newtab_font_color");
  }

  // Defaults
  if (!shortcuts_json)
    shortcuts_json = g_strdup("[]");
  if (!font_color)
    font_color = g_strdup("#eeeeee");

  // Background style
  char *bg_style = NULL;
  if (bg_image && strlen(bg_image) > 0) {
    // If it's a local path, we prepend file://
    if (g_str_has_prefix(bg_image, "/")) {
      bg_style =
          g_strdup_printf("background-image: url('file://%s');", bg_image);
    } else {
      bg_style = g_strdup_printf("background-image: url('%s');", bg_image);
    }
  } else {
    // Default gradient
    bg_style = g_strdup(
        "background: linear-gradient(135deg, #1a1c2c 0%%, #4a192c 100%%);");
  }

  GString *html = g_string_new("");

  g_string_append_printf(
      html,
      "<!DOCTYPE html>\n"
      "<html>\n"
      "<head>\n"
      "<meta charset='UTF-8'>\n"
      "<title>New Tab</title>\n"
      "<style>\n"
      ":root {\n"
      "  --font-color: %s;\n"
      "}\n"
      "body {\n"
      "  margin: 0;\n"
      "  padding: 0;\n"
      "  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, "
      "sans-serif;\n"
      "  height: 100vh;\n"
      "  width: 100vw;\n"
      "  %s\n"
      "  background-size: cover;\n"
      "  background-position: center;\n"
      "  background-attachment: fixed;\n"
      "  color: var(--font-color);\n"
      "  display: flex;\n"
      "  flex-direction: column;\n"
      "  align-items: center;\n"
      "  justify-content: center;\n"
      "  transition: background 0.3s ease;\n"
      "}\n"
      "/* Overlay for readability if image is bright */\n"
      "body::before {\n"
      "  content: '';\n"
      "  position: absolute;\n"
      "  top: 0; left: 0; right: 0; bottom: 0;\n"
      "  background: rgba(0,0,0,0.4);\n"
      "  z-index: -1;\n"
      "}\n"
      ".container {\n"
      "  width: 100%%;\n"
      "  max-width: 800px;\n"
      "  padding: 20px;\n"
      "  text-align: center;\n"
      "}\n"
      "/* Search Bar */\n"
      ".search-container {\n"
      "  margin-bottom: 40px;\n"
      "}\n"
      ".search-bar {\n"
      "  width: 100%%;\n"
      "  max-width: 600px;\n"
      "  padding: 16px 24px;\n"
      "  font-size: 18px;\n"
      "  border-radius: 30px;\n"
      "  border: 1px solid rgba(255,255,255,0.2);\n"
      "  background: rgba(255, 255, 255, 0.1);\n"
      "  color: white;\n"
      "  backdrop-filter: blur(10px);\n"
      "  box-shadow: 0 4px 15px rgba(0,0,0,0.2);\n"
      "  transition: all 0.3s ease;\n"
      "}\n"
      ".search-bar:focus {\n"
      "  outline: none;\n"
      "  background: rgba(255, 255, 255, 0.2);\n"
      "  box-shadow: 0 6px 20px rgba(0,0,0,0.3);\n"
      "  transform: scale(1.02);\n"
      "}\n"
      ".search-bar::placeholder { color: rgba(255,255,255,0.7); }\n"
      "/* Speed Dial Grid */\n"
      ".shortcuts-grid {\n"
      "  display: grid;\n"
      "  grid-template-columns: repeat(6, 1fr);\n"
      "  gap: 20px;\n"
      "  margin-bottom: 20px;\n"
      "  padding: 20px;\n"
      "}\n"
      ".shortcut-item {\n"
      "  display: flex;\n"
      "  flex-direction: column;\n"
      "  align-items: center;\n"
      "  cursor: pointer;\n"
      "  padding: 15px;\n"
      "  border-radius: 12px;\n"
      "  transition: all 0.2s;\n"
      "  background: rgba(255,255,255,0.1);\n"
      "  backdrop-filter: blur(10px);\n"
      "  position: relative;\n"
      "}\n"
      ".shortcut-item:hover {\n"
      "  background: rgba(255,255,255,0.25);\n"
      "  transform: translateY(-5px);\n"
      "}\n"
      ".shortcut-icon {\n"
      "  width: 48px;\n"
      "  height: 48px;\n"
      "  background: white;\n"
      "  border-radius: 12px;\n"
      "  padding: 8px;\n"
      "  margin-bottom: 10px;\n"
      "  box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n"
      "  object-fit: contain;\n"
      "}\n"
      ".shortcut-label {\n"
      "  font-size: 14px;\n"
      "  font-weight: 500;\n"
      "  text-shadow: 0 1px 2px rgba(0,0,0,0.5);\n"
      "  white-space: nowrap;\n"
      "  overflow: hidden;\n"
      "  text-overflow: ellipsis;\n"
      "  max-width: 100%%;\n"
      "}\n"
      ".add-btn-container {\n"
      "  grid-column: 1 / -1;\n"
      "  display: flex;\n"
      "  justify-content: center;\n"
      "  margin-top: 10px;\n"
      "}\n"
      ".add-btn {\n"
      "  width: 50px;\n"
      "  height: 50px;\n"
      "  border-radius: 50%%;\n"
      "  background: rgba(255,255,255,0.2);\n"
      "  border: 2px solid rgba(255,255,255,0.5);\n"
      "  color: white;\n"
      "  font-size: 30px;\n"
      "  display: flex;\n"
      "  align-items: center;\n"
      "  justify-content: center;\n"
      "  cursor: pointer;\n"
      "  transition: all 0.2s;\n"
      "}\n"
      ".add-btn:hover {\n"
      "  background: rgba(255,255,255,0.4);\n"
      "  transform: scale(1.1);\n"
      "}\n"
      "/* Settings Cog */\n"
      ".settings-btn {\n"
      "  position: fixed;\n"
      "  bottom: 20px;\n"
      "  right: 20px;\n"
      "  width: 40px;\n"
      "  height: 40px;\n"
      "  background: rgba(255,255,255,0.1);\n"
      "  border-radius: 50%%;\n"
      "  display: flex;\n"
      "  align-items: center;\n"
      "  justify-content: center;\n"
      "  cursor: pointer;\n"
      "  color: white;\n"
      "  transition: all 0.2s;\n"
      "}\n"
      ".settings-btn:hover {\n"
      "  background: rgba(255,255,255,0.3);\n"
      "  transform: rotate(45deg);\n"
      "}\n"
      "/* Modal */\n"
      ".modal-overlay {\n"
      "  position: fixed;\n"
      "  top: 0; left: 0; width: 100%%; height: 100%%;\n"
      "  background: rgba(0,0,0,0.6);\n"
      "  display: none;\n"
      "  align-items: center;\n"
      "  justify-content: center;\n"
      "  z-index: 1000;\n"
      "  width: 100%%;\n"
      "}\n"
      ".modal {\n"
      "  background: #2d3436;\n"
      "  padding: 30px;\n"
      "  border-radius: 16px;\n"
      "  width: 350px;\n"
      "  color: #dfe6e9;\n"
      "  box-shadow: 0 10px 25px rgba(0,0,0,0.5);\n"
      "  animation: modalPop 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);\n"
      "}\n"
      "@keyframes modalPop {\n"
      "  from { transform: scale(0.8); opacity: 0; }\n"
      "  to { transform: scale(1); opacity: 1; }\n"
      "}\n"
      ".modal h3 { margin-top: 0; margin-bottom: 20px; color: #fff; }\n"
      ".modal-input {\n"
      "  width: 100%%;\n"
      "  padding: 12px;\n"
      "  margin-bottom: 15px;\n"
      "  border: none;\n"
      "  background: #636e72;\n"
      "  color: white;\n"
      "  border-radius: 6px;\n"
      "  font-size: 14px;\n"
      "}\n"
      ".modal-input:focus { outline: 2px solid #74b9ff; }\n"
      ".modal-buttons {\n"
      "  display: flex;\n"
      "  justify-content: flex-end;\n"
      "  gap: 10px;\n"
      "  margin-top: 20px;\n"
      "}\n"
      ".btn {\n"
      "  padding: 8px 16px;\n"
      "  border: none;\n"
      "  border-radius: 6px;\n"
      "  cursor: pointer;\n"
      "  font-weight: 500;\n"
      "  transition: 0.2s;\n"
      "}\n"
      ".btn-cancel {\n"
      "  background: #636e72;\n"
      "  color: #dfe6e9;\n"
      "}\n"
      ".btn-cancel:hover { background: #b2bec3; color: #2d3436; }\n"
      ".btn-save {\n"
      "  background: #0984e3;\n"
      "  color: white;\n"
      "}\n"
      ".btn:hover { opacity: 0.9; transform: translateY(-1px); }\n"
      "/* Context Menu */\n"
      ".context-menu {\n"
      "  position: absolute;\n"
      "  background: #2d3436;\n"
      "  border-radius: 8px;\n"
      "  box-shadow: 0 4px 15px rgba(0,0,0,0.3);\n"
      "  padding: 5px 0;\n"
      "  display: none;\n"
      "  z-index: 2000;\n"
      "  color: #dfe6e9;\n"
      "  min-width: 120px;\n"
      "}\n"
      ".context-item {\n"
      "  padding: 10px 20px;\n"
      "  cursor: pointer;\n"
      "  font-size: 14px;\n"
      "}\n"
      ".context-item:hover { background: #636e72; }\n"
      "</style>\n"
      "</head>\n"
      "<body>\n"
      "\n"
      "<div class='container'>\n"
      "  <div class='search-container'>\n"
      "    <input type='text' class='search-bar' id='searchBar' "
      "placeholder='Search or enter address' autofocus>\n"
      "  </div>\n"
      "\n"
      "  <div class='shortcuts-grid' id='shortcutsGrid'>\n"
      "    <!-- Shortcuts generated by JS -->\n"
      "  </div>\n"
      "  \n"
      "  <div class='add-btn-container'>\n"
      "    <div class='add-btn' id='addBtn' title='Add Shortcut'>+</div>\n"
      "  </div>\n"
      "</div>\n"
      "\n"
      "<div class='settings-btn' id='settingsBtn'>⚙</div>\n"
      "\n"
      "<!-- Shortcut Modal -->\n"
      "<div class='modal-overlay' id='shortcutModal'>\n"
      "  <div class='modal'>\n"
      "    <h3 id='modalTitle'>Add Shortcut</h3>\n"
      "    <input type='hidden' id='shortcutIndex'>\n"
      "    <input type='text' id='shortcutName' class='modal-input' "
      "placeholder='Name'>\n"
      "    <input type='text' id='shortcutUrl' class='modal-input' "
      "placeholder='URL'>\n"
      "    <div class='modal-buttons'>\n"
      "      <button class='btn btn-cancel' "
      "onclick='closeModal()'>Cancel</button>\n"
      "      <button class='btn btn-save' "
      "onclick='saveShortcut()'>Save</button>\n"
      "    </div>\n"
      "  </div>\n"
      "</div>\n"
      "\n"
      "<!-- Settings Modal -->\n"
      "<div class='modal-overlay' id='settingsModal'>\n"
      "  <div class='modal'>\n"
      "    <h3>Page Settings</h3>\n"
      "    <label style='font-size:14px; display:block; "
      "margin-bottom:5px; color:#b2bec3;'>Background Image</label>\n"
      "    <div style='display:flex; gap:10px; margin-bottom:15px;'>\n"
      "       <button class='btn btn-cancel' onclick='selectBackground()' "
      "style='flex:1;'>Browse...</button>\n"
      "       <button class='btn btn-cancel' "
      "onclick='resetBackground()'>Reset</button>\n"
      "    </div>\n"
      "    \n"
      "    <label style='font-size:14px; display:block; "
      "margin-bottom:5px; color:#b2bec3;'>Font Color</label>\n"
      "    <div style='display:flex; align-items:center; gap:10px; "
      "margin-bottom:20px;'>\n"
      "       <input type='color' id='fontColorPicker' value='%s' "
      "onchange='saveFontColor(this.value)' style='background:none; "
      "border:none; width:40px; height:40px; cursor:pointer;'>\n"
      "       <span id='colorVal'>%s</span>\n"
      "    </div>\n"
      "    \n"
      "    <div class='modal-buttons'>\n"
      "      <button class='btn btn-save' "
      "onclick='closeSettings()'>Done</button>\n"
      "    </div>\n"
      "  </div>\n"
      "</div>\n"
      "\n"
      "<!-- Context Menu -->\n"
      "<div class='context-menu' id='contextMenu'>\n"
      "  <div class='context-item' onclick='editShortcutContext()'>Edit</div>\n"
      "  <div class='context-item' "
      "onclick='removeShortcutContext()'>Remove</div>\n"
      "  <!-- Re-arrange is handled by drag and drop, but could add arrows "
      "here -->\n"
      "</div>\n"
      "\n"
      "<script>\n"
      "let shortcuts = %s;\n"
      "let contextTargetIndex = -1;\n"
      "\n"
      "// Render shortcuts\n"
      "function renderShortcuts() {\n"
      "  const grid = document.getElementById('shortcutsGrid');\n"
      "  grid.innerHTML = '';\n"
      "  \n"
      "  shortcuts.forEach((sc, index) => {\n"
      "    const item = document.createElement('div');\n"
      "    item.className = 'shortcut-item';\n"
      "    item.draggable = true;\n"
      "    item.innerHTML = `\n"
      "      <img "
      "src='https://www.google.com/s2/favicons?domain=${sc.url}&sz=64' "
      "class='shortcut-icon' onerror='this.src=\"about:blank\"'>\n"
      "      <div class='shortcut-label'>${sc.name}</div>\n"
      "    `;\n"
      "    \n"
      "    item.onclick = (e) => {\n"
      "        if(!e.defaultPrevented) window.location.href = sc.url;\n"
      "    };\n"
      "    \n"
      "    item.oncontextmenu = (e) => {\n"
      "      e.preventDefault();\n"
      "      showContextMenu(e, index);\n"
      "    };\n"
      "    \n"
      "    // Drag interactions\n"
      "    item.ondragstart = (e) => e.dataTransfer.setData('text/plain', "
      "index);\n"
      "    item.ondragover = (e) => e.preventDefault();\n"
      "    item.ondrop = (e) => {\n"
      "      e.preventDefault();\n"
      "      const fromIndex = "
      "parseInt(e.dataTransfer.getData('text/plain'));\n"
      "      moveShortcut(fromIndex, index);\n"
      "    };\n"
      "    \n"
      "    grid.appendChild(item);\n"
      "  });\n"
      "}\n"
      "\n"
      "function saveShortcutsToBackend() {\n"
      "  renderShortcuts();\n"
      "  window.webkit.messageHandlers.newtabUpdate.postMessage({ \n"
      "    action: 'save_shortcuts', \n"
      "    data: JSON.stringify(shortcuts)\n"
      "  });\n"
      "}\n"
      "\n"
      "function moveShortcut(from, to) {\n"
      "  const item = shortcuts.splice(from, 1)[0];\n"
      "  shortcuts.splice(to, 0, item);\n"
      "  saveShortcutsToBackend();\n"
      "}\n"
      "\n"
      "// Modal Logic\n"
      "const modal = document.getElementById('shortcutModal');\n"
      "const addBtn = document.getElementById('addBtn');\n"
      "const title = document.getElementById('modalTitle');\n"
      "const nameInput = document.getElementById('shortcutName');\n"
      "const urlInput = document.getElementById('shortcutUrl');\n"
      "const idxInput = document.getElementById('shortcutIndex');\n"
      "\n"
      "addBtn.onclick = () => {\n"
      "  title.innerText = 'Add Shortcut';\n"
      "  nameInput.value = '';\n"
      "  urlInput.value = '';\n"
      "  idxInput.value = '-1';\n"
      "  modal.style.display = 'flex';\n"
      "};\n"
      "\n"
      "function closeModal() {\n"
      "  modal.style.display = 'none';\n"
      "}\n"
      "\n"
      "function saveShortcut() {\n"
      "  const name = nameInput.value.trim();\n"
      "  let url = urlInput.value.trim();\n"
      "  if (!name || !url) return;\n"
      "  if (url.indexOf('://') === -1) url = 'https://' + url;\n"
      "  \n"
      "  const idx = parseInt(idxInput.value);\n"
      "  if (idx === -1) {\n"
      "    if (shortcuts.length >= 18) { alert('Max shortcuts reached (18)'); "
      "return; }\n"
      "    shortcuts.push({name, url});\n"
      "  } else {\n"
      "    shortcuts[idx] = {name, url};\n"
      "  }\n"
      "  \n"
      "  saveShortcutsToBackend();\n"
      "  closeModal();\n"
      "}\n"
      "\n"
      "// Search Bar\n"
      "document.getElementById('searchBar').onkeydown = (e) => {\n"
      "  if (e.key === 'Enter') {\n"
      "    window.location.href = e.target.value;\n"
      "  }\n"
      "};\n"
      "\n"
      "// Context Menu\n"
      "const ctxMenu = document.getElementById('contextMenu');\n"
      "function showContextMenu(e, index) {\n"
      "  contextTargetIndex = index;\n"
      "  ctxMenu.style.display = 'block';\n"
      "  ctxMenu.style.left = e.pageX + 'px';\n"
      "  ctxMenu.style.top = e.pageY + 'px';\n"
      "}\n"
      "document.onclick = () => ctxMenu.style.display = 'none';\n"
      "\n"
      "function removeShortcutContext() {\n"
      "  if (contextTargetIndex === -1) return;\n"
      "  shortcuts.splice(contextTargetIndex, 1);\n"
      "  saveShortcutsToBackend();\n"
      "}\n"
      "function editShortcutContext() {\n"
      "  if (contextTargetIndex === -1) return;\n"
      "  const sc = shortcuts[contextTargetIndex];\n"
      "  title.innerText = 'Edit Shortcut';\n"
      "  nameInput.value = sc.name;\n"
      "  urlInput.value = sc.url;\n"
      "  idxInput.value = contextTargetIndex;\n"
      "  modal.style.display = 'flex';\n"
      "}\n"
      "\n"
      "// Settings Logic\n"
      "const settingsModal = document.getElementById('settingsModal');\n"
      "document.getElementById('settingsBtn').onclick = () => "
      "settingsModal.style.display = 'flex';\n"
      "function closeSettings() { settingsModal.style.display = 'none'; }\n"
      "\n"
      "function saveFontColor(val) {\n"
      "  document.documentElement.style.setProperty('--font-color', val);\n"
      "  document.getElementById('colorVal').innerText = val;\n"
      "  window.webkit.messageHandlers.newtabUpdate.postMessage({ \n"
      "    action: 'save_color', \n"
      "    data: val \n"
      "  });\n"
      "}\n"
      "\n"
      "function selectBackground() {\n"
      "  window.webkit.messageHandlers.newtabUpdate.postMessage({ action: "
      "'select_bg' });\n"
      "}\n"
      "function resetBackground() {\n"
      "   document.body.style.backgroundImage = 'none';\n"
      "   document.body.style.background = 'linear-gradient(135deg, #1a1c2c "
      "0%%, #4a192c 100%%)';\n"
      "   window.webkit.messageHandlers.newtabUpdate.postMessage({ \n"
      "     action: 'save_bg', \n"
      "     data: '' \n"
      "   });\n"
      "}\n"
      "\n"
      "// Initial Render\n"
      "renderShortcuts();\n"
      "</script>\n"
      "</body>\n"
      "</html>",
      font_color, bg_style, font_color, font_color, // For picker Init
      shortcuts_json);

  if (shortcuts_json)
    free(shortcuts_json);
  if (bg_image)
    free(bg_image);
  if (font_color)
    free(font_color);
  if (bg_style)
    g_free(bg_style);

  return g_string_free(html, FALSE);
}
