"""Premium layout for paid schools and the Edit Premium kit (MT, 20 Nov 2026).
- A paid or gifted school with its own content gets the premium layout live, with no flag; empty sections are not drawn.
- Free, unclaimed, verified-unpaid and lapsed pages stay the free page. Lapsed pages carry only a 'renew' kit.
- The edit kit is inert (<template>), content only, and ships only on paid, gifted and lapsed pages."""
import copy, json, re, sys, datetime as dt
from pathlib import Path
import pytest

HERE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(HERE))
import generator  # noqa: E402

TODAY = dt.date(2026, 11, 20)
LIVE = json.loads((HERE / "data/ato/example-premium-academy.json").read_text())
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
FREE = json.loads((HERE / "data/ato/example-air-school.json").read_text())
LAPSED = json.loads((HERE / "data/ato/example-lapsed-school.json").read_text())
CSS = (HERE / "shared/page.css").read_text()
JS = (HERE / "shared/page.js").read_text()


def render(tmp_path, ato, **kw):
    d = tmp_path / "data"; d.mkdir(parents=True, exist_ok=True)
    (d / "a.json").write_text(json.dumps(ato))
    generator.build(d, tmp_path / "out", "pearl", TODAY, **kw)
    return (tmp_path / "out" / ato["slug"] / "index.html").read_text()


def kit(html):
    m = re.search(r'<template id="ob-edit-kit"[^>]*>(.*?)</template>', html, re.S)
    return m and m.group(1)


def test_a_paid_school_with_its_own_content_is_live_without_a_flag(tmp_path):
    h = render(tmp_path, copy.deepcopy(LIVE))
    assert '<html lang="en" data-theme="day" data-pal="white" data-premium="live">' in h
    assert "data-design-pending" not in h and "Sample details" not in h
    for needle in ('class="pa-about"', 'class="pr-zone"', 'id="pc-contact"', "R165,000", "Book a trial flight"):
        assert needle in h, needle
    assert "pr-news" not in h and "pr-jobs" not in h                  # nothing filled, nothing drawn


def test_free_lapsed_and_paid_without_content_keep_the_free_page(tmp_path):
    for i, ato in enumerate((FREE, LAPSED, PAID)):
        h = render(tmp_path / str(i), copy.deepcopy(ato))
        assert "data-premium" not in h and not re.search(r'class="(pa-|pc-|pr-)', h)
    lapsed = copy.deepcopy(LAPSED); lapsed["premium"] = LIVE["premium"]; lapsed["profile"] = LIVE["profile"]
    h = render(tmp_path / "l", lapsed)
    assert "data-premium" not in h and "R165,000" not in h            # lapsed: saved content stays hidden


def test_free_page_carries_no_kit_and_is_unchanged_by_this_work(tmp_path):
    h = render(tmp_path, copy.deepcopy(FREE))
    assert "ob-edit-kit" not in h and "ek-" not in h


def test_the_kit_is_inert_and_lists_every_editable_and_locked_section(tmp_path):
    h = render(tmp_path, copy.deepcopy(LIVE))
    k = kit(h)
    assert k and h.count('id="ob-edit-kit"') == 1 and "<form method=\"dialog\"" in k and "action=" not in k
    keys = re.findall(r'class="ek-slot" data-ek="([a-z]+)"', k)
    assert keys == ["announcement", "about", "fees", "fleet", "jobs", "link", "contact"]
    assert re.findall(r'data-ek-lock="([a-z]+)"', k) == ["record", "courses", "reviews"]
    filled = set(re.findall(r'class="ek-slot" data-ek="([a-z]+)" data-filled', k))
    assert filled == {"about", "fees", "fleet", "link", "contact"}
    assert "Content only. The layout, fonts and colours stay the same on every school page." in k
    assert "Goes live as soon as you save. Go Around checks every change." in k
    for c in ("Private Licence (A)", "Night rating"):
        assert f"<option>{c}</option>" in k                            # fees use the school's own SACAA course names


def test_lapsed_kit_only_offers_renewal(tmp_path):
    k = kit(render(tmp_path, copy.deepcopy(LAPSED)))
    assert "Premium has ended" in k and "Renew Premium" in k and "ek-sheet" not in k and "ek-edit" not in k


def test_preview_flag_still_draws_sample_content_hidden(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID), premium_preview=True)
    assert h.count('data-design-pending="premium-extras" hidden') == 5 and "data-premium=" not in h


@pytest.mark.parametrize("bad", [
    {"price": [{"title": "PPL", "amount_cents": 0, "updated": "2026-11-01"}]},
    {"fleet": [{"title": "C172", "count": 0}]},
    {"link": [{"title": "Book", "url": "javascript:alert(1)"}]},
    {"announcement": [{"title": "Hi"}]},
    {"posters": []},
    {"intake": [{"title": "PPL", "date": "next week"}]},
])
def test_malformed_premium_content_stops_the_build(bad):
    a = copy.deepcopy(LIVE); a["premium"] = bad
    with pytest.raises(ValueError):
        generator.check(a)


def test_kit_css_is_clean_and_motion_is_transform_and_opacity():
    mine = CSS.split("Edit Premium (20 Nov 2026)", 1)[1]
    assert "!important" not in mine and "prefers-reduced-motion" in mine
    for prop in re.findall(r"transition:([^;}]+)", mine):
        for part in prop.split(","):
            assert part.strip().split()[0] in ("transform", "opacity", "outline-color", "background-color", "none"), prop


def test_kit_js_starts_only_for_allowed_viewers_and_never_saves_by_itself():
    assert 'addEventListener("ga:can-edit"' in JS and 'Q.get("preview-edit") === "1"' in JS
    assert '"ga:edit-save"' in JS and "fetch(" not in JS.split("Edit Premium (MT, 20 Nov)", 1)[1]
    assert 'role !== "admin"' in JS                                      # only Super Admin sees Hide section


def test_edit_sheet_uses_our_own_day_picker_and_24_hour_lists_never_native_date_or_time():
    """MT, 20 Nov: no browser date or time fields; next intake reads "12 Jan 2027", today or later; hours in SA 24-hour style."""
    import re
    from pathlib import Path
    root = Path(__file__).resolve().parents[1]
    kit = (root / "template/parts/edit_kit.j2").read_text()
    assert not re.search(r'type="(date|time|month|datetime-local|week)"', kit)
    assert 'row("Next intake", "intake", kind="date", wide=True)' in kit
    assert 'data-cal="date" data-min="now" data-max="+3"' in kit and 'type="hidden" name="{{ name }}"' in kit
    assert '<span class="ek-tsel"><select' in kit and "range(5, 24)" in kit and '("00", "30")' in kit
    js = (root / "shared/page.js").read_text()
    assert 'querySelectorAll("select").forEach(function (i) { i.disabled = c.checked; })' in js
    assert 'new CustomEvent("ga:cal-sync")' in js
    css = (root / "shared/page.css").read_text()
    assert 'input[type="date"]' not in css and 'input[type="time"]' not in css
    assert "'JetBrains Mono'" in css.split(".ek-f .ek-hours select{", 1)[1].split("}", 1)[0]


def test_built_sheet_has_the_picker_and_hours(tmp_path):
    import re
    from pathlib import Path
    import subprocess, sys
    root = Path(__file__).resolve().parents[1]
    subprocess.run([sys.executable, "generator.py", "--today", "2026-11-20", "--out", str(tmp_path)], cwd=root, check=True, capture_output=True)
    h = (tmp_path / "example-premium-academy/index.html").read_text()
    assert h.count('data-cal="date"') == 1 and 'name="intake"' in h
    assert h.count('<span class="ek-tsel"><select') == 14
    assert re.search(r'<select name="open-6" aria-label="Sun opens" disabled>', h)
    assert "<option selected>08:00</option>" in h and "<option>23:00</option>" in h and "23:30" not in h
    assert not re.search(r'type="(date|time|month)"', h)
    free = (tmp_path / "example-air-school/index.html").read_text()
    assert "ek-tsel" not in free and 'data-cal="date"' not in free
