package vuedocs

import (
	"strings"
	"testing"

	"github.com/PuerkitoBio/goquery"
)

const testReferencePageHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>Vue API Reference</h1>

<h2 id="ref">ref()</h2>
<p>Takes an inner value and returns a reactive and mutable ref object.</p>
<pre><code>function ref<T>(value: T): Ref<T></code></pre>

<h2 id="reactive">reactive()</h2>
<p>Returns a reactive proxy of the object.</p>
<pre><code>function reactive<T extends object>(target: T): T</code></pre>

<h2 id="computed">computed()</h2>
<p>Takes a getter function and returns a readonly reactive ref object.</p>

<h3 id="v-bind">v-bind</h3>
<p>Dynamically binds one or more attributes to an expression.</p>

<h3 id="Transition">Transition</h3>
<p>Provides animated transition effects when elements enter or leave the DOM.</p>
</body>
</html>
`

func TestParseReferencePage(t *testing.T) {
	parser := NewParser()
	ref, err := parser.ParseReferencePage(testReferencePageHTML, "https://vuejs.org/api/")
	if err != nil {
		t.Fatalf("ParseReferencePage failed: %v", err)
	}

	if len(ref.Composition) == 0 {
		t.Error("Expected at least one composition API item")
	}

	if len(ref.Directives) == 0 {
		t.Error("Expected at least one directive")
	}

	if len(ref.Components) == 0 {
		t.Error("Expected at least one component")
	}
}

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

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(testReferencePageHTML))
	if err != nil {
		t.Fatalf("Failed to parse HTML: %v", err)
	}

	compos := parser.extractCompositionAPI(doc, "https://vuejs.org/api/")

	if len(compos) == 0 {
		t.Skip("No composition API items extracted from test HTML")
	}
}

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

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(testReferencePageHTML))
	if err != nil {
		t.Fatalf("Failed to parse HTML: %v", err)
	}

	directives := parser.extractDirectives(doc, "https://vuejs.org/api/")

	found := false
	for _, d := range directives {
		if d.Name == "v-bind" {
			found = true
			break
		}
	}

	if !found {
		t.Error("Expected to find v-bind directive")
	}
}

func TestResolveURL(t *testing.T) {
	tests := []struct {
		base     string
		href     string
		expected string
	}{
		{"https://vuejs.org", "/api/", "https://vuejs.org/api/"},
		{"https://vuejs.org", "https://example.com/page", "https://example.com/page"},
	}

	for _, tt := range tests {
		t.Run(tt.href, func(t *testing.T) {
			got := resolveURL(tt.base, tt.href)
			if got != tt.expected {
				t.Errorf("resolveURL(%q, %q) = %q, want %q", tt.base, tt.href, got, tt.expected)
			}
		})
	}
}
