package com.swoosh.microblog.data

import com.swoosh.microblog.data.model.LinkPreview

/**
 * Builds a responsive HTML preview from post content.
 * Used to show "how it will look on the blog" before publishing.
 */
object PreviewHtmlBuilder {

    /**
     * Generates a complete HTML document from post content, optional image URL,
     * and optional link preview data. The output uses a Ghost-like responsive
     * styling with dark mode support.
     */
    fun build(
        text: String,
        imageUrl: String? = null,
        linkPreview: LinkPreview? = null
    ): String {
        val contentHtml = buildContentHtml(text, imageUrl, linkPreview)
        return wrapInTemplate(contentHtml)
    }

    /**
     * Wraps existing HTML content (e.g. from the Ghost API html field) in
     * the preview template. Use this for published posts that already have
     * rendered HTML.
     */
    fun wrapExistingHtml(html: String): String {
        return wrapInTemplate(html)
    }

    internal fun buildContentHtml(
        text: String,
        imageUrl: String?,
        linkPreview: LinkPreview?
    ): String {
        val sb = StringBuilder()

        // Convert text to HTML paragraphs
        if (text.isNotBlank()) {
            val paragraphs = text.split("\n\n")
            for (paragraph in paragraphs) {
                val trimmed = paragraph.trim()
                if (trimmed.isNotEmpty()) {
                    val escaped = escapeHtml(trimmed)
                    // Convert single newlines within a paragraph to <br>
                    val withBreaks = escaped.replace("\n", "<br>")
                    sb.append("<p>$withBreaks</p>\n")
                }
            }
        }

        // Add feature image
        if (!imageUrl.isNullOrBlank()) {
            sb.append("<figure class=\"kg-card kg-image-card\">\n")
            sb.append("  <img src=\"${escapeHtml(imageUrl)}\" alt=\"Post image\" />\n")
            sb.append("</figure>\n")
        }

        // Add bookmark card for link preview
        if (linkPreview != null) {
            sb.append(buildBookmarkCard(linkPreview))
        }

        return sb.toString()
    }

    internal fun buildBookmarkCard(linkPreview: LinkPreview): String {
        val sb = StringBuilder()
        sb.append("<div class=\"bookmark-card\">\n")

        if (!linkPreview.imageUrl.isNullOrBlank()) {
            sb.append("  <img class=\"bookmark-image\" src=\"${escapeHtml(linkPreview.imageUrl)}\" alt=\"\" />\n")
        }

        sb.append("  <div class=\"bookmark-content\">\n")

        val title = linkPreview.title
        if (!title.isNullOrBlank()) {
            sb.append("    <div class=\"bookmark-title\">${escapeHtml(title)}</div>\n")
        }

        val description = linkPreview.description
        if (!description.isNullOrBlank()) {
            sb.append("    <div class=\"bookmark-description\">${escapeHtml(description)}</div>\n")
        }

        sb.append("    <div class=\"bookmark-url\">${escapeHtml(linkPreview.url)}</div>\n")
        sb.append("  </div>\n")
        sb.append("</div>\n")

        return sb.toString()
    }

    internal fun escapeHtml(value: String): String {
        return value
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\"", "&quot;")
            .replace("'", "&#39;")
    }

    internal fun wrapInTemplate(content: String): String {
        return """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
  padding: 20px 16px;
  line-height: 1.7;
  max-width: 600px;
  margin: 0 auto;
  color: #1a1a1a;
  background: #ffffff;
  font-size: 17px;
}
p {
  margin: 0 0 1.2em 0;
}
figure {
  margin: 1.5em 0;
  padding: 0;
}
img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  display: block;
}
.bookmark-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  margin: 1.5em 0;
  background: #fafafa;
}
.bookmark-card .bookmark-image {
  width: 100%;
  max-height: 200px;
  object-fit: cover;
  border-radius: 0;
}
.bookmark-content {
  padding: 14px 16px;
}
.bookmark-title {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.4;
  margin-bottom: 4px;
  color: #1a1a1a;
}
.bookmark-description {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.bookmark-url {
  font-size: 13px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
@media (prefers-color-scheme: dark) {
  body {
    background: #1a1a2e;
    color: #e0e0e0;
  }
  .bookmark-card {
    border-color: #333;
    background: #222244;
  }
  .bookmark-title {
    color: #e0e0e0;
  }
  .bookmark-description {
    color: #aaa;
  }
  .bookmark-url {
    color: #888;
  }
}
</style>
</head>
<body>
$content
</body>
</html>"""
    }
}
