package astrodocs

import "testing"

const testAstroPageHTML = `
<!DOCTYPE html>
<html>
<head>
  <title>Components | Astro Docs</title>
  <meta name="description" content="Build pages using Astro components.">
</head>
<body>
  <main>
    <h1 id="components">Components</h1>
    <p>Astro components are basic HTML templates.</p>
    <h2 id="props">Props</h2>
    <p>Pass props to customize output.</p>
    <pre class="language-js"><code>const { title } = Astro.props;</code></pre>
  </main>
</body>
</html>
`

func TestParsePage(t *testing.T) {
	parser := NewParser()

	page, err := parser.ParsePage(testAstroPageHTML, "https://docs.astro.build/en/guides/components/")
	if err != nil {
		t.Fatalf("ParsePage failed: %v", err)
	}

	if page.Title != "Components" {
		t.Fatalf("unexpected title: %q", page.Title)
	}
	if page.Description == "" {
		t.Fatal("expected non-empty description")
	}
	if len(page.Sections) < 2 {
		t.Fatalf("expected at least 2 sections, got %d", len(page.Sections))
	}
	if len(page.CodeBlocks) == 0 {
		t.Fatal("expected at least one code block")
	}

	foundJS := false
	for _, block := range page.CodeBlocks {
		if block.Language == "js" {
			foundJS = true
			break
		}
	}
	if !foundJS {
		t.Fatalf("expected at least one js code block, got %+v", page.CodeBlocks)
	}
}

func TestParseSidebar(t *testing.T) {
	parser := NewParser()

	html := `
<nav>
  <a href="/en/guides/components/">Components</a>
  <a href="/en/guides/routing/">Routing</a>
</nav>`

	sections, err := parser.ParseSidebar(html)
	if err != nil {
		t.Fatalf("ParseSidebar failed: %v", err)
	}

	if len(sections) != 2 {
		t.Fatalf("expected 2 sections, got %d", len(sections))
	}
	if sections[0].DocURL != "https://docs.astro.build/en/guides/components/" {
		t.Fatalf("unexpected resolved URL: %q", sections[0].DocURL)
	}
}

func TestResolveURL(t *testing.T) {
	got := resolveURL("https://docs.astro.build", "/en/guides/components/")
	if got != "https://docs.astro.build/en/guides/components/" {
		t.Fatalf("resolveURL returned %q", got)
	}
}
