"""Fixes of 15 Nov 2026: guest theme flag, desktop hero contacts, dynamic claim copy."""
import copy, json, re, datetime as dt
from pathlib import Path
import pytest

import generator

TODAY = dt.date(2026, 11, 15)
HERE = Path(__file__).resolve().parents[1]
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
CSS = (HERE / "shared/page.css").read_text()
TOPBAR_CSS = (HERE / "shared/topbar.css").read_text()
TOPBAR_JS = (HERE / "shared/topbar.js").read_text()


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


def unclaimed(ato=None, **over):
    a = copy.deepcopy(ato or PAID)
    a["status"] = "unclaimed"
    a.update(over)
    return a


# ---- Fix 1: guest themes (flag; locked default preserved) ----
def test_guest_theme_locked_by_default(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID))
    assert re.search(r"<html[^>]*data-guest-theme-choice", html) is None
    assert 'H.dataset.pal=night?"black":"white"' in html
    assert 'H.setAttribute("data-guest-theme","1")' in html
    assert "data-guest-theme-choice" in html  # script still honours the preview query
    assert 'id="ato-theme-tokens"' in html
    # All four palettes are inlined so a later flag-on switch can reach them.
    assert "html[data-theme=night][data-pal=purple]" in html
    assert "html[data-theme=night][data-pal=black]" in html
    assert "html[data-theme=day][data-pal=white]" in html
    assert "html[data-theme=day][data-pal=beige]" in html


def test_guest_theme_choice_flag_bakes_attribute_and_keeps_auto(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID), guest_theme_choice=True)
    assert 'data-guest-theme-choice="1"' in html
    assert 't==="auto"||t==="sun"' in html
    assert 'localStorage.getItem("wm-theme")' in html
    assert "NAMED" in html and "amethyst" in html and "champagne" in html


def test_topbar_hides_guest_theme_button_unless_flag_is_on():
    assert 'html[data-preview-view="guest"]:not([data-guest-theme-choice="1"]) #tb-theme' in TOPBAR_CSS
    assert 'html[data-guest-theme="1"]:not([data-guest-theme-choice="1"]) .sheet' in TOPBAR_CSS
    # Refresh stays hidden for every guest, flag or not.
    assert 'html[data-preview-view="guest"] #ato-tb-refresh { display: none !important; }' in TOPBAR_CSS
    assert "function guestThemeChoiceOn()" in TOPBAR_JS
    assert 'data-v", "auto"' in TOPBAR_JS
    assert 'localStorage.setItem("wm-theme", "auto")' in TOPBAR_JS
    # Locked guests still must not write storage.
    assert "function mayPersistTheme()" in TOPBAR_JS


# ---- Fix 2: desktop hero contacts stay visible ----
def test_hero_contacts_are_not_hidden_from_820px():
    assert not re.search(r"@media\s*\(min-width:\s*820px\)\s*\{\s*\.ob-hcontact\s*\{\s*display:\s*none", CSS)
    assert "@media (max-width:819px){ .ob-about-sec .ob-cbtn{display:none} }" in CSS
    assert ".ob-hero .ob-hcontact" in CSS


def test_generated_page_keeps_hero_and_about_contacts(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID))
    assert 'class="ob-hcontact' in html
    assert "ob-actions3 ob-cbtn" in html
    hero = html.split('class="ob-card ob-hero"', 1)[1].split("</section>", 1)[0]
    assert ">Call<" in hero and ">Email<" in hero and ">Website<" in hero
    about = html.split("About the ATO", 1)[1].split("</section>", 1)[0]
    assert ">Call<" in about and ">Email<" in about and ">Website<" in about


# ---- Fix 3: dynamic claim copy ----
def test_claim_copy_when_all_contacts_present(tmp_path):
    a = unclaimed()
    m = generator.page_model(copy.deepcopy(a), TODAY)
    assert m["claim_copy"] == "Claim this page to manage your details and reply to reviews"
    html = render(tmp_path, a)
    assert "Claim this page to manage your details and reply to reviews" in html
    assert "add your phone, email, website" not in html
    assert "Until then, pilots can't contact you from here." not in html
    assert "Is this your school?" in html
    assert 'class="ob-claim-step"' in html


def test_claim_copy_asks_only_for_missing_phone():
    a = unclaimed()
    a["contact"] = {"phone": None, "email": "hello@example.invalid", "web": "example.invalid"}
    copy_txt = generator.page_model(a, TODAY)["claim_copy"]
    assert copy_txt == "Claim this page to add your phone."
    assert "email" not in copy_txt and "website" not in copy_txt
    assert "Until then" not in copy_txt


def test_claim_copy_lists_missing_email_and_website():
    a = unclaimed()
    a["contact"] = {"phone": "+27 00 000 0000", "email": "", "web": None}
    copy_txt = generator.page_model(a, TODAY)["claim_copy"]
    assert copy_txt == "Claim this page to add your email and website."
    assert "phone" not in copy_txt
    assert "Until then" not in copy_txt


def test_claim_copy_all_contacts_missing_keeps_until_then():
    a = unclaimed()
    a["contact"] = {"phone": None, "email": None, "web": None}
    a["about"] = ""
    a["courses"] = []
    copy_txt = generator.page_model(a, TODAY)["claim_copy"]
    assert copy_txt.startswith("Claim this page to add your phone, email, website")
    assert "about text" in copy_txt and "courses" in copy_txt
    assert copy_txt.endswith("Until then, pilots can't contact you from here.")


def test_claim_copy_complete_contacts_ignore_missing_about():
    a = unclaimed()
    a["about"] = ""
    assert generator.page_model(a, TODAY)["claim_copy"] == (
        "Claim this page to manage your details and reply to reviews"
    )


def test_claimed_page_has_no_claim_step(tmp_path):
    html = render(tmp_path, copy.deepcopy(PAID))  # paid / claimed
    assert 'class="ob-claim-step"' not in html
    assert "Claim this page to manage your details" not in html


def test_no_reviews_yet_copy_is_unchanged(tmp_path):
    a = unclaimed()
    a.pop("rating", None)
    a["top_reviews"] = []
    a["visible_reviews"] = 0
    html = render(tmp_path, a)
    assert "No reviews yet" in html
