package blog

import (
	"html/template"
	"log"
	"net/http"
	"strings"
)

const pageTpl = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{.Title}}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Inter:wght@300;500;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #05030a;
      --accent: #b574ff;
      --accent-soft: rgba(181, 116, 255, 0.12);
      --text: #f3f0ff;
      --text-dim: #a9a3c4;
      --border: rgba(255, 255, 255, 0.06);
    }
    * { box-sizing: border-box; }
    body {
      margin: 0; min-height: 100vh;
      background: radial-gradient(circle at top, #1a1035 0, #05030a 55%);
      color: var(--text);
      font-family: "Inter", system-ui, sans-serif;
      display: flex; justify-content: center;
    }
    .wrap { position: relative; z-index: 1; width: 100%; max-width: 820px; padding: 32px 20px 40px; }
    header {
      display: flex; justify-content: space-between; align-items: center;
      gap: 24px; padding: 18px 22px; border-radius: 18px;
      border: 1px solid var(--border);
      background: linear-gradient(135deg, rgba(255,255,255,0.02), rgba(0,0,0,0.35));
      backdrop-filter: blur(18px);
    }
    .logo-mark {
      width: 44px; height: 44px; border-radius: 14px;
      border: 1px solid rgba(181,116,255,0.7);
      background: radial-gradient(circle at 20% 0, rgba(255,255,255,0.25), transparent 55%),
                  radial-gradient(circle at 80% 100%, rgba(181,116,255,0.9), transparent 60%);
      display: flex; align-items: center; justify-content: center;
      font-family: "JetBrains Mono", monospace; font-weight: 600; font-size: 20px;
    }
    .logo-mark a { color: inherit; text-decoration: none; }
    nav { display: flex; gap: 16px; align-items: center; }
    nav a { color: var(--text-dim); text-decoration: none; font-size: 13px; text-transform: uppercase; letter-spacing: 0.1em; }
    nav a:hover { color: var(--accent); }
    main { margin-top: 24px; }
    .post-list { list-style: none; padding: 0; margin: 0; }
    .post-list li { padding: 12px 0; border-top: 1px solid var(--border); }
    .post-list li:first-child { border-top: 0; }
    .post-list a { color: var(--text); text-decoration: none; font-size: 16px; }
    .post-list a:hover { color: var(--accent); }
    .article h1 { font-size: 28px; margin: 0 0 4px; }
    .post-date { display: block; font-size: 13px; color: var(--text-dim); margin-bottom: 24px; }
    .post-date-inline { font-size: 12px; color: var(--text-dim); }
    .article p { line-height: 1.7; color: var(--text-dim); }
    .article pre {
      background: rgba(0,0,0,0.5); border: 1px solid var(--border);
      border-radius: 12px; padding: 16px; overflow-x: auto;
    }
    .article code { font-family: "JetBrains Mono", monospace; font-size: 13px; }
    .article a { color: var(--accent); }
    .article img { max-width: 100%; border-radius: 12px; }
    .article blockquote {
      border-left: 3px solid var(--accent); margin: 0; padding: 4px 16px;
      color: var(--text-dim);
    }
    .article h1, .article h2, .article h3 { color: var(--text); }
    .article ul, .article ol { color: var(--text-dim); line-height: 1.7; }
    footer { margin-top: 30px; font-size: 11px; color: var(--text-dim); display: flex; justify-content: space-between; padding: 4px 2px; }
  </style>
</head>
<body>
  <div class="wrap">
    <header>
      <div style="display:flex; gap:14px; align-items:center;">
        <div class="logo-mark"><a href="/blog/">CS</a></div>
        <nav>
          <a href="/">Home</a>
          <a href="/blog/">Blog</a>
        </nav>
      </div>
    </header>
    <main>
      {{if .Post.HTML}}
        <article class="article">
          <h1>{{.Post.Title}}</h1>
          <time class="post-date">{{.Post.Date.Format "January 2, 2006"}}</time>
          {{.Post.HTML | safehtml}}
        </article>
      {{else}}
        <h1>Field Notes</h1>
        {{if .Posts}}
        <ul class="post-list">
          {{range .Posts}}
          <li>
            <a href="/blog/posts/{{.Slug}}">{{.Title}}</a>
            <span class="post-date-inline">{{.Date.Format "Jan 2, 2006"}}</span>
          </li>
          {{end}}
        </ul>
        {{else}}
        <p style="color: var(--text-dim);">No posts yet.</p>
        {{end}}
      {{end}}
    </main>
    <footer>
      <span>Running on self-hosted infrastructure.</span>
      <span>Chaosmith Systems</span>
    </footer>
  </div>
</body>
</html>`

type pageData struct {
	Title      string
	Posts      []Post
	Post       Post
	ActiveSlug string
}

var tmpl *template.Template

func safehtml(s string) template.HTML {
	return template.HTML(s)
}

func init() {
	var err error
	tmpl, err = template.New("blog").Funcs(template.FuncMap{"safehtml": safehtml}).Parse(pageTpl)
	if err != nil {
		panic(err)
	}
}

func render(w http.ResponseWriter, data pageData) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	tmpl.Execute(w, data)
}

func RegisterRoutes(mux *http.ServeMux, contentDir string) error {
	store := NewStore()
	if err := store.Load(contentDir); err != nil {
		log.Printf("blog: warning: could not load posts from %s: %v", contentDir, err)
	}

	mux.HandleFunc("/blog/admin/reload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "POST only", http.StatusMethodNotAllowed)
			return
		}
		if err := store.Load(contentDir); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write([]byte("reloaded\n"))
	})

	mux.HandleFunc("/blog/posts/", func(w http.ResponseWriter, r *http.Request) {
		slug := strings.TrimPrefix(r.URL.Path, "/blog/posts/")
		if slug == "" || strings.Contains(slug, "/") {
			http.NotFound(w, r)
			return
		}
		p, ok := store.Get(slug)
		if !ok {
			http.NotFound(w, r)
			return
		}
		render(w, pageData{
			Title: p.Title + " — Chaosmith Systems",
			Posts: store.All(),
			Post:  p,
		})
	})

	mux.HandleFunc("/blog/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/blog/" {
			http.NotFound(w, r)
			return
		}
		render(w, pageData{
			Title: "Chaosmith Systems — Field Notes",
			Posts: store.All(),
		})
	})

	log.Printf("blog: loaded %d post(s) from %s, mounted at /blog/", store.Count(), contentDir)
	return nil
}
