"""Displacement Dashboard: HTML building blocks.

Purpose: small functions that turn the data model into accessible, static HTML
(charts are plain HTML and CSS, so every figure reads with scripting off and
has a table beside it). Pages are assembled in update_dashboard.py.

Owner: Metropolitan Council, Metro Transit TOD Office (built by Stoa).
"""
from __future__ import annotations

import html
import math

E = html.escape


def n(x) -> str:
    """Whole number with thousands separators."""
    return f"{int(round(x)):,}"


def pct(x, digits=0) -> str:
    return f"{x * 100:.{digits}f} percent"


def attr(s) -> str:
    return html.escape(str(s), quote=True)


def chart_color(hex_color: str) -> str:
    """A version of a line color that reaches 3:1 against white for chart marks,
    keeping its hue (light lines such as Gold, Orange and D Line darken)."""
    r, g, b = (int(hex_color[i:i + 2], 16) / 255 for i in (1, 3, 5))

    def lum(c):
        c = [x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
        return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]

    rgb = [r, g, b]
    for _ in range(40):
        if (1.05) / (lum(rgb) + 0.05) >= 3.0:
            break
        rgb = [x * 0.93 for x in rgb]
    return "#" + "".join(f"{int(round(x * 255)):02x}" for x in rgb)


def text_on(hex_color: str) -> str:
    """Near-black or white label for text set inside a filled badge."""
    r, g, b = (int(hex_color[i:i + 2], 16) / 255 for i in (1, 3, 5))
    c = [x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in (r, g, b)]
    L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
    return "#13202f" if (L + 0.05) / 0.05 > 1.05 / (L + 0.05) else "#ffffff"


def line_badge(line, base, tag="a", extra_class="", current=False) -> str:
    planned = " is-planned" if line["status"] == "planned" else ""
    href = f'{base}lines/{line["id"]}/'
    style = f'--line:{line["color"]};--line-ink:{text_on(line["color"])};--line-mark:{chart_color(line["color"])}'
    cur = ' aria-current="page"' if current else ""
    inner = f'<span class="badge-swatch" aria-hidden="true"></span><span class="badge-name">{E(line["name"])}</span>'
    if tag == "a":
        return f'<a class="line-badge{planned} {extra_class}" href="{href}" style="{style}" data-line="{line["id"]}"{cur}>{inner}</a>'
    return f'<span class="line-badge{planned} {extra_class}" style="{style}">{inner}</span>'


def status_text(line) -> str:
    if line["status"] == "planned":
        phase = (line.get("phase") or "planning").lower()
        return f"Planned, in {phase}"
    if line.get("opened"):
        return f"In service since {line['opened']}"
    return "In service"


def year_chart(series: dict, years, title_id: str, caption: str, color: str, opened=None, note=None, table_label="Year") -> str:
    """Columns for one series over the DTAT years, with the service year marked
    and a table twin. `series` maps year -> value."""
    top = max([series[y] for y in years] + [1])
    step = 10 ** max(0, int(math.log10(top)) - (0 if top / 10 ** int(math.log10(top)) >= 3 else 1)) if top >= 10 else 1
    nice = math.ceil(top / step) * step
    bars = []
    for i, y in enumerate(years):
        v = series[y]
        side = "after" if (opened and y >= opened) else ("before" if opened else "")
        label = f"{y}: {n(v)} homes"
        bars.append(
            f'<li class="yr {side}" style="--v:{v / nice:.4f}" data-year="{y}" data-value="{int(v)}">'
            f'<span class="yr-bar" aria-hidden="true"></span>'
            f'<span class="yr-val">{n(v)}</span>'
            f'<span class="yr-label">{y if (i % 2 == 0 or len(years) <= 10) else ""}</span>'
            f'<span class="visually-hidden">{E(label)}</span></li>'
        )
    mark = ""
    if opened and years[0] < opened <= years[-1]:
        idx = years.index(opened)
        mark = f'<div class="service-mark{" is-late" if idx / len(years) > 0.55 else ""}" style="--at:{idx};--count:{len(years)}"><span>Service began {opened}</span></div>'
    rows = "".join(f"<tr><th scope=\"row\">{y}</th><td>{n(series[y])}</td></tr>" for y in years)
    table = (f'<table class="data-table" id="{title_id}-table" hidden><caption>{E(caption)}</caption>'
             f'<thead><tr><th scope="col">{E(table_label)}</th><th scope="col">Homes permitted</th></tr></thead><tbody>{rows}</tbody></table>')
    note_html = f'<p class="chart-note">{note}</p>' if note else ""
    return (
        f'<figure class="years chart-fig" style="--mark:{color}" aria-labelledby="{title_id}" data-visual-id="years-chart" data-visual-kind="data-graphic">'
        f'<figcaption class="chart-head"><span class="chart-title" id="{title_id}">{E(caption)}</span></figcaption>'
        f'<button class="table-toggle" type="button" aria-controls="{title_id}-table" aria-expanded="false">Show as table</button>'
        f'<div class="year-plot" data-max="{nice}">'
        f'<div class="year-axis" aria-hidden="true"><span>{n(nice)}</span><span>{n(nice / 2)}</span><span>0</span></div>'
        f'<ol class="year-bars" role="list">{"".join(bars)}</ol>{mark}</div>'
        f'{note_html}{table}</figure>'
    )


def strip(line, base, current_id=None, heading_level=2, title=None, compact=False) -> str:
    """The line strip: stations in ride order, each carrying its permitted
    homes as a bar above the stop. A list of links; line-strip.js adds arrow
    keys and map highlighting."""
    stops = line["stations"]
    if not stops:
        return ""
    top = max([s["total"] for s in stops] + [1])
    title = title or f"Ride the {line['name']}"
    hid = f"strip-{line['id']}"
    items = []
    for s in stops:
        cur = s["id"] == current_id
        href = f'{base}lines/{line["id"]}/{s["id"]}/'
        cur_attr = ' aria-current="page"' if cur else ""
        items.append(
            f'<li class="stop{" is-current" if cur else ""}" style="--v:{s["total"] / top:.4f}" data-station="{s["id"]}" '
            f'data-lon="{s["lon"]}" data-lat="{s["lat"]}" data-total="{s["total"]}">'
            f'<a class="stop-link" href="{href}"{cur_attr}>'
            f'<span class="stop-bar" aria-hidden="true"></span>'
            f'<span class="stop-value">{n(s["total"])}<span class="visually-hidden"> homes</span></span>'
            f'<span class="stop-dot" aria-hidden="true"></span>'
            f'<span class="stop-name">{E(s["name"])}</span></a></li>'
        )
    rows = "".join(f'<tr><th scope="row"><a href="{base}lines/{line["id"]}/{s["id"]}/">{E(s["name"])}</a></th><td>{E(s["city"] or "")}</td><td>{n(s["total"])}</td></tr>' for s in stops)
    first, last = stops[0]["name"], stops[-1]["name"]
    return (
        f'<section class="strip{" is-compact" if compact else ""}{" is-planned" if line["status"] == "planned" else ""}" aria-labelledby="{hid}" data-visual-id="line-strip" data-visual-kind="diagram" '
        f'style="--line:{line["color"]};--line-mark:{chart_color(line["color"])};--count:{len(stops)}" data-line="{line["id"]}">'
        f'<div class="strip-head"><h{heading_level} class="strip-title" id="{hid}"><span class="station-stop" aria-hidden="true"></span>{E(title)}</h{heading_level}>'
        f'<p class="strip-note">Multifamily homes permitted 2009 to 2024, counted at the nearest {E(line["name"])} station. {E(first)} to {E(last)}.</p>'
        f'<button class="table-toggle" type="button" aria-controls="{hid}-table" aria-expanded="false">Show as table</button></div>'
        f'<div class="strip-track"><ol class="strip-stops" role="list" aria-label="{attr(line["name"])} stations in order, {attr(first)} to {attr(last)}">{"".join(items)}</ol></div>'
        f'<table class="data-table" id="{hid}-table" hidden><caption>{E(line["name"])} stations in order, multifamily homes permitted 2009 to 2024</caption>'
        f'<thead><tr><th scope="col">Station</th><th scope="col">City</th><th scope="col">Homes permitted</th></tr></thead><tbody>{rows}</tbody></table>'
        f'</section>'
    )


def ranked_lines(lines, base, years_label="2009 to 2024") -> str:
    """Ranked horizontal bars, one per line, as links (region view)."""
    shown = [l for l in lines if l["total"] > 0]
    shown.sort(key=lambda l: -l["total"])
    top = max(l["total"] for l in shown)
    rows = []
    for l in shown:
        rows.append(
            f'<li class="rank" style="--v:{l["total"] / top:.4f};--line:{l["color"]};--line-mark:{chart_color(l["color"])}" data-line="{l["id"]}">'
            f'<a class="rank-link" href="{base}lines/{l["id"]}/" data-line="{l["id"]}">'
            f'<span class="rank-name"><span class="badge-swatch{" is-planned" if l["status"] == "planned" else ""}" aria-hidden="true"></span>{E(l["name"])}</span>'
            f'<span class="rank-track" aria-hidden="true"><span class="rank-bar"></span></span>'
            f'<span class="rank-value">{n(l["total"])}</span></a></li>'
        )
    table_rows = "".join(f'<tr><th scope="row">{E(l["name"])}</th><td>{E(l["modeLabel"])}</td><td>{n(l["total"])}</td></tr>' for l in shown)
    return (
        f'<figure class="ranked chart-fig" aria-labelledby="ranked-title" data-visual-id="ranked-lines" data-visual-kind="data-graphic">'
        f'<figcaption class="chart-head"><span class="chart-title" id="ranked-title">Multifamily homes permitted near each line, {years_label}</span></figcaption>'
        f'<button class="table-toggle" type="button" aria-controls="ranked-table" aria-expanded="false">Show as table</button>'
        f'<ol class="rank-list" role="list">{"".join(rows)}</ol>'
        f'<p class="chart-note">Corridors overlap downtown and where lines cross, so a home can count toward more than one line.</p>'
        f'<table class="data-table" id="ranked-table" hidden><caption>Multifamily homes permitted near each line, {years_label}</caption>'
        f'<thead><tr><th scope="col">Line</th><th scope="col">Mode</th><th scope="col">Homes permitted</th></tr></thead><tbody>{table_rows}</tbody></table>'
        f'</figure>'
    )


def tenure_bar(tenure: dict, title_id: str) -> str:
    """Tall segmented bar: homes by tenure (own, rent, not reported)."""
    parts = [("rent", "Rental", tenure.get("rent", 0)), ("own", "Ownership", tenure.get("own", 0) + tenure.get("co-op", 0)),
             ("unknown", "Not reported", tenure.get("unknown", 0) + tenure.get("other", 0))]
    total = sum(p[2] for p in parts) or 1
    blocks = []
    for key, label, v in parts:
        if v <= 0:
            continue
        share = v / total
        txt = f"{round(share * 100)}%" if share >= 0.12 else ""
        blocks.append(f'<span class="seg seg-{key}" style="--w:{share:.4f}" role="img" aria-label="{attr(label)}: {n(v)} homes, {round(share * 100)} percent">{txt}</span>')
    legend = "".join(f'<li><span class="seg-key seg-{k}" aria-hidden="true"></span>{E(lab)}</li>' for k, lab, v in parts if v > 0)
    rows = "".join(f'<tr><th scope="row">{E(lab)}</th><td>{n(v)}</td><td>{round(v / total * 100)}%</td></tr>' for k, lab, v in parts if v > 0)
    return (
        f'<figure class="tenure chart-fig" aria-labelledby="{title_id}" data-visual-id="tenure-bar" data-visual-kind="data-graphic">'
        f'<figcaption class="chart-head"><span class="chart-title" id="{title_id}">Rental or ownership, as reported on the permit</span></figcaption>'
        f'<button class="table-toggle" type="button" aria-controls="{title_id}-table" aria-expanded="false">Show as table</button>'
        f'<div class="seg-bar">{"".join(blocks)}</div><ul class="seg-legend" role="list">{legend}</ul>'
        f'<table class="data-table" id="{title_id}-table" hidden><caption>Rental or ownership, as reported on the permit</caption>'
        f'<thead><tr><th scope="col">Tenure</th><th scope="col">Homes</th><th scope="col">Share</th></tr></thead><tbody>{rows}</tbody></table></figure>'
    )


def analysis_pending(scope_name: str, base: str) -> str:
    return (
        f'<section class="analysis-pending" aria-labelledby="who-moved">'
        f'<h2 id="who-moved"><span class="station-stop" aria-hidden="true"></span>Who moved in and out</h2>'
        f'<p data-source-copy="analysis-pending">Household movement for {E(scope_name)} comes from the Displacement Analysis: households moving in and out each year from 2006 to 2025, '
        f'by income as a share of area median income and by race and ethnicity, compared with control corridors that have no frequent transit. '
        f'It appears here when the Analysis team delivers its station-area results.</p>'
        f'<p><a class="text-link" href="{base}about-the-data/#how-a-finding-reads">How a finding will read</a></p>'
        f'</section>'
    )


def band(base, pid, stem, small, large, alt, subject, caption=""):
    """A wide Council photograph across the measure (assets/img/photos/<stem>-<small|large>.jpg).
    `subject` is the normalized x y w h box the crop keeps."""
    a, b = f"assets/img/photos/{stem}-{small}.jpg", f"assets/img/photos/{stem}-{large}.jpg"
    cap = f"<figcaption>{E(caption)}</figcaption>" if caption else ""
    return (f'<figure class="page-band" data-photo-story-id="{pid}" data-visual-id="{pid}"><img src="{base}{b}" '
            f'srcset="{base}{a} {small}w, {base}{b} {large}w" sizes="(max-width: 1240px) 100vw, 1200px" '
            f'alt="{attr(alt)}" loading="lazy" decoding="async" data-photo-asset="public{base}{b}" data-crop-kind="photo" data-crop-subject="{subject}">{cap}</figure>')
