package webpub

import (
	"strings"
	"testing"
	"time"

	"hamlog/internal/qso"
)

// The published page carries its own sort script, so a regression there is
// silent: the table still renders, it just sorts wrongly. These pin the two
// things that were actually broken in the field.

func renderSample(t *testing.T) string {
	t.Helper()
	cfg := Config{Columns: []string{"qso_date", "callsign", "freq"}}
	cfg.Normalise()
	qsos := []qso.QSO{
		{Callsign: "8B81SU", QSODate: time.Date(2026, 8, 10, 9, 56, 0, 0, time.UTC)},
		{Callsign: "LZ8NG", QSODate: time.Date(2025, 12, 31, 23, 1, 0, 0, time.UTC)},
	}
	return string(renderHTML(cfg, columnsFor(cfg.Columns), qsos, "F4BPO"))
}

// A third click restores the published order, which is only possible if each row
// remembers where it started.
func TestRowsCarryTheirPublishedIndex(t *testing.T) {
	html := renderSample(t)
	for _, want := range []string{`<tr data-i="0">`, `<tr data-i="1">`} {
		if !strings.Contains(html, want) {
			t.Errorf("published page is missing %s — the reset-to-original click cannot work", want)
		}
	}
}

// parseFloat accepts a numeric PREFIX, so "2026-08-10" became 2026 and every
// date in the same year compared equal: the Date column looked unsortable.
// Callsigns starting with a digit ("8B81SU") hit the same trap. The whole cell
// must match for a numeric comparison to be used.
func TestSortScriptRejectsNumericPrefixes(t *testing.T) {
	html := renderSample(t)
	if !strings.Contains(html, `var NUM=/^[+-]?\d+(\.\d+)?$/;`) {
		t.Error("the anchored numeric test is gone; a bare parseFloat makes dates and 8-prefixed calls sort as equal")
	}
	if strings.Contains(html, "n=!isNaN(nx)&&!isNaN(ny)") {
		t.Error("the old prefix-tolerant numeric detection is back")
	}
}
