package web

import (
	"strings"
	"testing"
)

// Native "Megosztás…" button in the share modal (v0.165.1). Renders the ADMIN launcher template with
// sharing enabled and asserts the Web Share API wiring: hidden-by-default button, feature-detect
// reveal, a title/text/url-only payload (never a QR file), and the non-cancel fallback to copy.

func renderAdminLauncherModal(t *testing.T) string {
	t.Helper()
	return renderBackupPage(t, "launcher", map[string]interface{}{
		"Page": "launcher", "Title": "Indítópult", "Domain": "demo-felhom.eu",
		"Version":          "test",
		"ShareEnabled":     true,
		"ShareURL":         "https://felhom.demo-felhom.eu/s/REDACTED-TOKEN",
		"SharePasswordSet": false,
	})
}

// Group A — markup + payload shape.
// COMPANION red-proof (REPORT): drop the `style="display:none"` from the button (reveal it in markup)
// → the hidden-by-default assertion FAILS.
func TestShareModal_NativeShareButton(t *testing.T) {
	html := renderAdminLauncherModal(t)

	if !strings.Contains(html, `id="share-native-btn"`) {
		t.Error("the native share button must be present in the modal")
	}
	// Hidden by default in the markup — JS only ever reveals it.
	if !strings.Contains(html, `id="share-native-btn" class="btn btn-outline" style="display:none"`) {
		t.Error("the native share button must be display:none in the initial markup")
	}
	// Feature-detect reveal in the IIFE.
	if !strings.Contains(html, "if(navigator.share)") {
		t.Error("missing navigator.share feature-detect reveal")
	}
	// Payload carries title/text/url and NOTHING else — no files key.
	for _, k := range []string{"title:'Indítópult", "text:'Az otthoni alkalmazások egy helyen.'", "url:inp.value"} {
		if !strings.Contains(html, k) {
			t.Errorf("nativeShare payload missing %q", k)
		}
	}
	if strings.Contains(html, "files:") {
		t.Error("nativeShare must NOT attach files (the QR) to the share payload")
	}
	// The universal fallback is not demoted.
	if !strings.Contains(html, "Link másolása") {
		t.Error("the copy button (universal fallback) must remain")
	}
}

// Group B — fallback wiring.
// COMPANION red-proof (REPORT): swap the catch to swallow all errors (drop the copyShareLink() call)
// → the fallback-presence assertion FAILS.
func TestShareModal_NativeShareFallback(t *testing.T) {
	html := renderAdminLauncherModal(t)
	if !strings.Contains(html, "AbortError") {
		t.Error("a user-cancel (AbortError) must be silently ignored")
	}
	if !strings.Contains(html, "copyShareLink();") {
		t.Error("a non-abort rejection must fall back to copyShareLink()")
	}
}
