package templates

import (
	"bytes"
	"context"
	"strings"
	"testing"
)

// TestLoginPage_RendersAuthLayoutStructure verifies that LoginPage wraps output
// in the AuthLayout shell with all required structural CSS classes and assets
// (AUTH-UI-01).
func TestLoginPage_RendersAuthLayoutStructure(t *testing.T) {
	var buf bytes.Buffer
	err := LoginPage(LoginForm{Email: "a@b.com"}, LoginErrors{}, "tok", EmptyAuthProviderButtons()).Render(context.Background(), &buf)
	if err != nil {
		t.Fatalf("LoginPage.Render: %v", err)
	}
	body := buf.String()

	for _, want := range []string{
		"login-screen",
		"auth-card-shell",
		"brand-logo",
		`src="/static/logo_dark.png"`,
		"Sign in to Xtablo",
		`class="auth-body"`,
		`class="divider-pill"`,
	} {
		if !strings.Contains(body, want) {
			t.Errorf("LoginPage body missing %q", want)
		}
	}
}

// TestLoginPage_HTMXFormAttributes verifies that LoginFormFragment renders the
// HTMX swap attributes, CSRF field, and signup navigation link (AUTH-UI-01,
// D-19, D-20).
func TestLoginPage_HTMXFormAttributes(t *testing.T) {
	var buf bytes.Buffer
	err := LoginFormFragment(LoginForm{}, LoginErrors{}, "tok").Render(context.Background(), &buf)
	if err != nil {
		t.Fatalf("LoginFormFragment.Render: %v", err)
	}
	body := buf.String()

	for _, want := range []string{
		`hx-post="/login"`,
		`hx-target="#login-form"`,
		`hx-swap="outerHTML"`,
		`id="login-form"`,
		`class="login-form"`,
		`name="_csrf"`,
		`href="/signup"`,
	} {
		if !strings.Contains(body, want) {
			t.Errorf("LoginFormFragment body missing %q", want)
		}
	}

	// Signup copy — templ HTML-encodes apostrophes as &#39; so check both forms.
	if !strings.Contains(body, "Don&#39;t have an account") && !strings.Contains(body, "Don't have an account") {
		t.Errorf("LoginFormFragment body missing signup copy; body: %s", body)
	}
}

// TestLoginPage_DoesNotEchoPassword verifies the password input field does not
// carry a pre-populated value attribute in the rendered HTML (security parity
// with signup, T-2-01). LoginForm intentionally has no Password field so the
// value can never round-trip; this test asserts the password input has no
// value= attribute.
func TestLoginPage_DoesNotEchoPassword(t *testing.T) {
	var buf bytes.Buffer
	// LoginForm has no Password field by design — only Email round-trips.
	err := LoginPage(LoginForm{Email: "a@b.com"}, LoginErrors{}, "tok", EmptyAuthProviderButtons()).Render(context.Background(), &buf)
	if err != nil {
		t.Fatalf("LoginPage.Render: %v", err)
	}
	body := buf.String()
	// The password input must not carry a value= attribute.
	// Find the password input block and check it has no value="..." attribute.
	pwIdx := strings.Index(body, `name="password"`)
	if pwIdx == -1 {
		t.Fatal("LoginPage missing password input")
	}
	// Look in the vicinity of the password input for value="..." (within 200 chars).
	vicinity := body[max(0, pwIdx-100) : min(len(body), pwIdx+200)]
	// Acceptable: no value= at all, or value="" (empty string).
	if strings.Contains(vicinity, `value="`) {
		// Only an empty value is acceptable — any non-empty value would echo.
		// Extract the value content to verify it is empty.
		vidx := strings.Index(vicinity, `value="`)
		after := vicinity[vidx+len(`value="`):]
		end := strings.Index(after, `"`)
		if end > 0 && after[:end] != "" {
			t.Errorf("LoginPage password input has non-empty value= attribute: %q", after[:end])
		}
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
