"""Displacement Dashboard: the site pages that are mostly words.

Purpose: home, lines index, the Story, About the data, the annual update
guide, the one-pager, search, accessibility and the not-found page. Their
figures come from the same data model as the line and station pages, so a
number on the Story always matches the map. Edit the words here; rerun
update_dashboard.py to publish them.

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

import html
import json
import re
import shutil
from pathlib import Path

import dashboard_html as H

E = html.escape
n = H.n
HERE = Path(__file__).resolve().parent

DTAT_REPORT = "docs/development-trends-along-transit-2025.pdf"
HPP_REPORT = "docs/imagine-2050-housing-policy-plan.pdf"


def _text(fragment: str) -> str:
    """Visible words of an HTML fragment, for the search index."""
    return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", fragment)).strip()


def portal(base, pid, stem, alt, size="lg", small=600, painted="300px", large=1080, subject=None):
    """A half-mile portal: a resident photograph in a circle, from the crops in
    assets/img/photos (<stem>-<small>.jpg and <stem>-<large>.jpg)."""
    a, b = f"assets/img/photos/{stem}-{small}.jpg", f"assets/img/photos/{stem}-{large}.jpg"
    crop = f' data-crop-subject="{subject}"' if subject else ""
    return (f'<figure class="portal portal-{size}" data-photo-story-id="{pid}" data-visual-id="{pid}"><img src="{base}{a}" srcset="{base}{a} {small}w, {base}{b} {large}w" '
            f'sizes="(max-width: 700px) 60vw, {painted}" width="{small}" height="{small}" alt="{H.attr(alt)}" '
            f'loading="lazy" decoding="async" data-photo-asset="public{base}{b}" data-crop-kind="photo"{crop}></figure>')


def share_by_year(model):
    years = model["years"]
    corridor = {y: 0 for y in years}
    for p in model["permits"]:
        corridor[p["year"]] += p["units"]
    return {y: (corridor[y], model["region"]["byYear"][y]) for y in years}


def story_main(model, base, example_figure):
    years = model["years"]
    sby = share_by_year(model)
    first, last = years[0], years[-1]
    top = max(c / r for c, r in sby.values() if r)
    cols = "".join(
        f'<li class="yr" style="--v:{(c / r) / top:.4f}" data-year="{y}"><span class="yr-bar" aria-hidden="true"></span>'
        f'<span class="yr-val">{round(c / r * 100)}%</span><span class="yr-label">{y if (i % 2 == 0) else ""}</span>'
        f'<span class="visually-hidden">{y}: {round(c / r * 100)} percent</span></li>'
        for i, (y, (c, r)) in enumerate(sby.items()))
    rows = "".join(f'<tr><th scope="row">{y}</th><td>{n(c)}</td><td>{n(r)}</td><td>{round(c / r * 100)}%</td></tr>' for y, (c, r) in sby.items())
    share_chart = (
        f'<figure class="years years-share chart-fig" style="--mark:#0054a4" aria-labelledby="share-title" data-visual-id="share-by-year" data-visual-kind="data-graphic">'
        f'<figcaption class="chart-head"><span class="chart-title" id="share-title">Homes near high-frequency transit as a share of the region\'s new multifamily homes, by year</span></figcaption>'
        f'<button class="table-toggle" type="button" aria-controls="share-title-table" aria-expanded="false">Show as table</button>'
        f'<div class="year-plot"><div class="year-axis" aria-hidden="true"><span>{round(top * 100)}%</span><span>{round(top * 50)}%</span><span>0%</span></div><ol class="year-bars" role="list">{cols}</ol></div>'
        f'<table class="data-table" id="share-title-table" hidden><caption>Multifamily homes permitted near high-frequency transit and in the whole region, by year</caption>'
        f'<thead><tr><th scope="col">Year</th><th scope="col">Near high-frequency transit</th><th scope="col">Whole region</th><th scope="col">Share</th></tr></thead><tbody>{rows}</tbody></table>'
        f'<p class="chart-note">Source: Metropolitan Council, Development Trends Along Transit permit data, {first} to {last}.</p></figure>'
    )
    badges = "".join(H.line_badge(l, base) for l in model["lines"])
    lead_line = next(l for l in model["lines"] if l["id"] == "green-line")
    ba = lead_line["beforeAfter"]
    return f"""
<article class="story">
<header class="story-hero">
  <figure class="story-hero-photo" data-photo-story-id="story-hero-green-line" data-visual-id="story-hero-green-line">
    <img src="{base}assets/img/photos/green-line-tower-2555.jpg" srcset="{base}assets/img/photos/green-line-tower-1000.jpg 1000w, {base}assets/img/photos/green-line-tower-1600.jpg 1600w, {base}assets/img/photos/green-line-tower-2555.jpg 2555w" sizes="(max-width: 1240px) 100vw, 1200px" width="2555" height="1702" alt="A Green Line train passes a new glass apartment tower on a clear day" decoding="async" style="object-position: 50% 80%" data-photo-asset="public/metropolitancouncil/assets/img/photos/green-line-tower-2555.jpg" data-crop-kind="photo" data-crop-subject="0.05 0.45 0.9 0.45">
  </figure>
  <div class="story-hero-copy">
    <p class="kicker">The story of the data</p>
    <h1>Development along transit, and who it serves</h1>
    <p class="lede" data-verbatim data-source-copy="metrocouncil-tod-markets-equity">Transit is a significant public investment and it should benefit those who rely on it most.</p>
    <p class="attribution">Metropolitan Council, Transit Oriented Development Guide</p>
  </div>
</header>

<section class="chapter" aria-labelledby="ch-built">
  <h2 id="ch-built"><span class="station-stop" aria-hidden="true"></span>What gets built near transit</h2>
  <p data-source-copy="story-built">Since {first}, the region has permitted {n(model["region"]["corridorUnits"])} multifamily homes within a half mile of a METRO station or a quarter mile of a High Frequency bus route, {round(model["region"]["corridorUnits"] / model["region"]["total"] * 100)} percent of all the multifamily homes it permitted, counting each line before and after it opened. The 2025 report, which counts each line from the year it began tracking it, finds {model["report"]["corridorUnits"]}, or {model["report"]["corridorShare"].rstrip("%")} percent. On the Green Line, the {n(ba["beforeAvg"])} homes permitted in an average year before service began in {ba["split"]} became {n(ba["afterAvg"])} a year after.</p>
  {share_chart}
</section>

<section class="chapter chapter-people" aria-labelledby="ch-stays">
  <h2 id="ch-stays"><span class="station-stop" aria-hidden="true"></span>Who gets to stay</h2>
  <div class="portal-line portal-line-wide">
    {portal(base, "story-people-embrace", "housing-embrace", "Two women embrace outside a yellow house with a carved wooden sculpture behind them", "lg", small=800, painted="380px")}
    {portal(base, "story-people-mural", "mural-neighbors", "A woman and a man stand smiling in front of a bright neighborhood mural", "md", painted="280px")}
    {portal(base, "story-people-bus-stop", "bus-stop-resident", "A woman waits at a neighborhood bus stop beside her house", "sm", painted="220px")}
  </div>
  <p data-verbatim data-source-copy="i2050-anti-displacement-framework">This framework lays the groundwork for understanding who benefits and who is harmed by development, policies, and investments in the region.</p>
  <p data-verbatim data-source-copy="hpp-history">The construction of highways in the region, notably I-94 and I-35, disproportionately and intentionally destroyed cultural connections, communities, and homes.</p>
  <p data-verbatim data-source-copy="i2050-anti-displacement-framework">Displacement can happen before or after development or other community changes occur and can impact an individual's physical and perceived safety in their community.</p>
</section>

<section class="chapter" aria-labelledby="ch-measure">
  <h2 id="ch-measure"><span class="station-stop" aria-hidden="true"></span>What the Displacement Analysis measures</h2>
  {portal(base, "story-construction", "station-construction", "A new light rail station shelter stands finished beside a construction fence", "md", small=600, painted="260px", large=1080)}
  <p data-source-copy="story-measure">The analysis follows households moving into and out of the areas around each station and along each corridor, every year from 2006 to 2025, and sets them against similar control corridors that have no frequent transit. Results arrive as aggregated, de-identified tables; no one's record is ever shown.</p>
  <ol class="phase-line" role="list" aria-label="Transit project phases the analysis uses">
    <li><span class="phase-stop" aria-hidden="true"></span><span class="phase-name">Pre-development</span></li>
    <li><span class="phase-stop" aria-hidden="true"></span><span class="phase-name">Planning</span></li>
    <li><span class="phase-stop" aria-hidden="true"></span><span class="phase-name">Construction</span></li>
    <li><span class="phase-stop" aria-hidden="true"></span><span class="phase-name">Operation</span></li>
  </ol>
  <ul class="question-list" role="list">
    <li data-verbatim data-source-copy="rfp-research-questions">During which project phase(s) is displacement occurring, and how do trends differ across phases?</li>
    <li data-verbatim data-source-copy="rfp-research-questions">Are people near transit corridors displaying the same kinds of movement we see in control corridors without access to frequent transit?</li>
    <li data-verbatim data-source-copy="rfp-research-questions">Is there anything in this data that can help us identify whether movement is voluntary or forced displacement?</li>
  </ul>
</section>

<section class="chapter" aria-labelledby="ch-reads">
  <h2 id="ch-reads"><span class="station-stop" aria-hidden="true"></span>How a finding will read</h2>
  <p data-source-copy="story-reads">Each station and corridor gets the same comparison: who moved out, who moved in, and whether the two groups differ. Until the Twin Cities results arrive, the example below uses the Utah findings the Council included with its request.</p>
  {example_figure(base)}
</section>

<section class="chapter chapter-end" aria-labelledby="ch-yours">
  <h2 id="ch-yours"><span class="station-stop" aria-hidden="true"></span>Read your line</h2>
  <div class="badge-row">{badges}</div>
  <p class="actions" data-control-group="actions"><a class="button" href="{base}">Open the map</a> <a class="button button-quiet" href="{base}one-pager/">Print the one-pager</a></p>
</section>
</article>
"""


def about_main(model, base, example_figure):
    years = model["years"]
    rows = [
        ("Permitted homes", "Development Trends Along Transit residential permits, from the Council's Building Permit Survey", f"{years[0]} to {years[-1]}", "Metropolitan Council, ArcGIS service DevelopmentTrendsAlongTransit"),
        ("Transitway alignments and corridors", "DTAT alignments and half-mile corridor areas", "2025 report", "Metropolitan Council, ArcGIS service DevelopmentTrendsAlongTransit"),
        ("Stations and opening years", "Existing and planned transitway stations, with completion year and project phase", "Current", "Metropolitan Council, ArcGIS service Transportation_Transit"),
        ("High Frequency Network", "Local routes with frequent all-day service", "Current", "Metropolitan Council, ArcGIS service DevelopmentTrendsAlongTransit"),
        ("Cities and townships", "Municipal boundaries in the seven-county region", "Current", "Metropolitan Council, ArcGIS service AdministrativeDemographic"),
        ("Counties", "The seven metro counties", "2020 Census geography", "U.S. Census Bureau, TIGERweb"),
        ("Household movement", "Displacement Analysis results by station area and corridor", "2006 to 2025", "Analysis team, delivered in Month Two of the dashboard contract"),
    ]
    trs = "".join(f"<tr><th scope=\"row\">{E(a)}</th><td>{E(b)}</td><td>{E(c)}</td><td>{E(d)}</td></tr>" for a, b, c, d in rows)
    fields = [
        ("geography_type", "station_area, corridor, region or control_corridor"),
        ("geography_id", "matches the station and line ids in data/dashboard.json"),
        ("year", "2006 to 2025"),
        ("direction", "in, out or stayed"),
        ("income_band", "under 30%, 30 to 50%, 50 to 80%, or over 80% of area median income"),
        ("race_ethnicity", "the Analysis team's categories"),
        ("households", "count, suppressed below the Analysis team's minimum cell size"),
        ("project_phase", "pre-development, planning, construction or operation for that line and year"),
    ]
    frows = "".join(f"<tr><th scope=\"row\"><code>{E(a)}</code></th><td>{E(b)}</td></tr>" for a, b in fields)
    return f"""
<section class="page-head">
  <h1>About the Data</h1>
  <p class="lede">What the dashboard shows today, what the Displacement Analysis adds, and how each number is counted.</p>
</section>
{H.band(base, "about-corridor", "b-line-red-lanes", 1000, 1920, "An aerial view of a city corridor with red bus-only lanes running toward downtown Minneapolis", "0.1 0.25 0.8 0.55")}
<div class="prose-grid">
<section aria-labelledby="def"><h2 id="def"><span class="station-stop" aria-hidden="true"></span>What displacement means here</h2>
<p data-verbatim data-source-copy="i2050-anti-displacement-framework">Though displacement is, ultimately, defined by residents, it can mean a physical and involuntary, often violent, loss of one's home, community, or access to resources. It can be an economic, social, or cultural change, removal, or the loss of sense of belonging in one's community.</p>
<p class="attribution">Metropolitan Council, Imagine 2050 Anti-displacement Framework</p>
</section>
<section aria-labelledby="sources"><h2 id="sources"><span class="station-stop" aria-hidden="true"></span>Sources</h2>
<div class="table-wrap"><table class="data-table is-visible"><caption>Data behind the dashboard</caption><thead><tr><th scope="col">Layer</th><th scope="col">What it is</th><th scope="col">Years</th><th scope="col">Publisher</th></tr></thead><tbody>{trs}</tbody></table></div>
<p>Documents: <a href="{base}{DTAT_REPORT}">Development Trends Along Transit, 2025 Report</a> (PDF) and the <a href="{base}{HPP_REPORT}">Imagine 2050 Housing Policy Plan</a> (PDF, accessible version).</p>
</section>
<section aria-labelledby="counting"><h2 id="counting"><span class="station-stop" aria-hidden="true"></span>How the homes are counted</h2>
<ul>
<li>Homes are the units on residential building permits for townhomes, duplexes to fourplexes, apartment buildings of five or more homes and accessory dwelling units. Single-family detached houses are not part of this permit layer.</li>
<li>A permit belongs to a line when it sits inside that line's half-mile corridor, as drawn for Development Trends Along Transit, in every year from 2009, before and after the line opened. The report's own layer marks a permit for a line only from the year it began tracking that line, so a line's totals here can be higher than the report's. The regional total differs the same way: {n(model["region"]["corridorUnits"])} homes here, {model["report"]["corridorUnits"]} in the report. Corridors overlap downtown and where lines cross, so one permit can count toward more than one line.</li>
<li>The High Frequency Network counts the permits the Council's layer marks as near a high-frequency local route.</li>
<li>On a station page, each permit counts toward the nearest station on that line, so a line's stations add up to the line's total.</li>
<li>Planned lines show what is being permitted along their future corridors, before service.</li>
<li data-verbatim data-source-copy="hfn-layer-description">The High Frequency Network consists of all or parts of transit routes with service every 15 minutes (or better) on weekdays from 6:00 AM to 7:00 PM and Saturdays from 9:00 AM to 6:00 PM.</li>
</ul>
</section>
<section aria-labelledby="analysis"><h2 id="analysis"><span class="station-stop" aria-hidden="true"></span>What the Displacement Analysis adds</h2>
<p data-source-copy="about-analysis">The Analysis team delivers aggregated, de-identified household movement for every station area and corridor, the region and the control corridors, 2006 to 2025. The dashboard never receives individual Data Axle records. Its tables load through one file layout:</p>
<div class="table-wrap"><table class="data-table is-visible"><caption>Analysis table layout (schema/analysis-v1.json)</caption><thead><tr><th scope="col">Field</th><th scope="col">Values</th></tr></thead><tbody>{frows}</tbody></table></div>
</section>
<section aria-labelledby="reads"><h2 id="reads"><span class="station-stop" aria-hidden="true"></span>How a finding will read</h2>
{example_figure(base)}
</section>
<section aria-labelledby="downloads"><h2 id="downloads"><span class="station-stop" aria-hidden="true"></span>Downloads</h2>
<ul class="download-list" role="list">
<li><a href="{base}downloads/homes-permitted-by-station.csv">Homes permitted by station and year</a> <span class="muted">CSV</span></li>
<li><a href="{base}downloads/homes-permitted-by-line.csv">Homes permitted by line and year</a> <span class="muted">CSV</span></li>
<li><a href="{base}downloads/permits-in-corridors.csv">Every permit inside a corridor</a> <span class="muted">CSV</span></li>
<li><a href="{base}data/geo/lines.geojson">Line alignments</a> <span class="muted">GeoJSON</span></li>
<li><a href="{base}data/geo/stations.geojson">Stations with totals</a> <span class="muted">GeoJSON</span></li>
<li><a href="{base}data/geo/areas.geojson">Half-mile corridor areas</a> <span class="muted">GeoJSON</span></li>
</ul>
</section>
<section aria-labelledby="contact"><h2 id="contact"><span class="station-stop" aria-hidden="true"></span>Questions</h2>
<p>For questions about the data or the analysis, write to the Metro Transit TOD Office at <a href="mailto:TOD@metrotransit.org">TOD@metrotransit.org</a>.</p>
</section>
</div>
"""


def update_main(model, base):
    steps = [
        ("Get the year's layers", f'<p>Run <code>python3 update_dashboard.py --fetch</code> to pull the permits, stations, alignments and corridor areas from the Council\'s ArcGIS services, or export the same layers from ArcGIS Pro as GeoJSON into <code>inputs/</code>.</p>'),
        ("Add the Analysis team's tables", '<p>Save their CSV files in <code>inputs/analysis/</code>. The column layout is in <code>schema/analysis-v1.json</code>; the script stops with a plain message if a column or a station id does not match.</p>'),
        ("Update the report figures", '<p>The Development Trends Along Transit figures quoted on the Story and the line pages sit at the top of <code>update_dashboard.py</code> under <code>DTAT_FACTS</code> and <code>DTAT_LINE_FACTS</code>. Copy the new report\'s numbers there.</p>'),
        ("Run the update", f'<p>Run <code>python3 update_dashboard.py</code>. It rebuilds every line and station page, the downloads and the search index, and prints a summary: {len(model["lines"])} lines and {sum(len(l["stations"]) for l in model["lines"])} stations today.</p>'),
        ("Review before publishing", '<p>Open the rebuilt site from the <code>site/</code> folder and check three things against last year: the region total on the map, one line you know well, and the Story\'s figures.</p>'),
        ("Publish", '<p>Copy the <code>site/</code> folder to the web server or Azure storage. Keep last year\'s folder; publishing it again is the rollback.</p>'),
    ]
    items = "".join(f'<li class="step"><span class="step-stop" aria-hidden="true"></span><div><h2>{E(t)}</h2>{b.replace("<p>", f'<p data-source-copy="update-step-{i + 1}">', 1)}</div></li>' for i, (t, b) in enumerate(steps))
    files = [("update_dashboard.py", "the update script"), ("dashboard_data.py", "reads and counts the layers"),
             ("dashboard_html.py", "the charts and the line strip"), ("site_pages.py", "the words on each page"), ("analysis-v1.json", "the Analysis table layout")]
    flist = "".join(f'<li><a href="{base}annual-update/files/{f}">{E(f)}</a> <span class="muted">{E(d)}</span></li>' for f, d in files)
    return f"""
<section class="page-head page-head-portal">
  {portal(base, "update-apartments", "bus-stop-apartments", "A Metro Transit bus stop sign in front of new apartment buildings", "sm", small=600, painted="200px", large=1200, subject="0.2 0.15 0.6 0.7")}
  <h1>The Annual Update</h1>
  <p class="lede" data-source-copy="update-lede">Once a year, after the new Development Trends Along Transit data and any new Displacement Analysis tables arrive, one script rebuilds the dashboard. It needs Python 3.9 or later, which ships with ArcGIS Pro, and nothing else.</p>
</section>
<section class="update-steps" aria-label="The update, step by step"><ol class="steps" role="list">{items}</ol></section>
<section class="update-files" aria-labelledby="files"><h2 id="files"><span class="station-stop" aria-hidden="true"></span>The files</h2>
<ul class="download-list" role="list">{flist}</ul>
<p data-source-copy="update-files">The site itself is plain HTML, CSS and JavaScript with one open-source map library (MapLibre GL JS, BSD license). There is no database, no server software to patch and no subscription.</p>
</section>
<section class="update-files update-change" aria-labelledby="source-change"><h2 id="source-change"><span class="station-stop" aria-hidden="true"></span>When a source changes</h2>
<p data-source-copy="update-source-change">Before it writes anything, the script checks that each layer still has the fields it reads. If the Council renames one, the script stops, leaves the site as it was and names the layer and the field. Add the new name to <code>FIELD_RENAMES</code> at the top of <code>dashboard_data.py</code> and run the update again; nothing else in the code changes.</p>
<pre class="code-sample"><code>FIELD_RENAMES = {{"PERMIT_YEAR": "YEAR"}}</code></pre>
<p data-source-copy="update-owners">The TOD team runs the update each year, with help from Council IS and IS-GIS staff when a layer moves or a service address changes. The layer addresses sit in <code>SERVICES</code> and <code>LAYERS</code> in the same file.</p>
</section>
"""


def one_pager_main(model, base):
    r = model["region"]
    gl = next(l for l in model["lines"] if l["id"] == "green-line")
    ba = gl["beforeAfter"]
    return f"""
<article class="one-pager" aria-labelledby="op-title">
  <header class="op-head">
    <img class="op-logo" src="{base}assets/img/metropolitan-council-logo-128.png" width="184" height="128" alt="Metropolitan Council">
    <div><p class="kicker">Displacement Dashboard</p><h1 id="op-title">What is changing along transit, station by station</h1></div>
  </header>
  <p class="op-lede">The Displacement Dashboard reads change along every METRO line and High Frequency bus route, station by station, so residents, partner cities and Council staff can see where development is arriving and who is moving in and out around it.</p>
  <ul class="op-figures" role="list">
    <li><span class="fact-figure">{n(r["corridorUnits"])}</span><span class="fact-label">multifamily homes permitted near high-frequency transit, {model["years"][0]} to {model["years"][-1]}</span></li>
    <li><span class="fact-figure">{round(r["corridorUnits"] / r["total"] * 100)}%</span><span class="fact-label">of the region's multifamily homes in those years, counting each line before and after it opened</span></li>
    <li><span class="fact-figure">{n(ba["beforeAvg"])} to {n(ba["afterAvg"])}</span><span class="fact-label">homes permitted a year near the Green Line, before and since service began in {ba["split"]}</span></li>
  </ul>
  <figure class="op-map" data-visual-id="one-pager-map" data-visual-kind="map"><img src="{base}assets/img/one-pager-map.png" width="1600" height="1013" alt="Map of the METRO lines and High Frequency bus routes with the half-mile areas around their stations and the homes permitted near them" loading="lazy" data-crop-kind="graphic"><figcaption class="op-map-cap">METRO lines in service (solid) and planned (dashed), the half mile around their stations, and multifamily homes permitted from 2009 to 2024 <span class="op-map-src">Sources: Metropolitan Council; U.S. Census Bureau</span></figcaption></figure>
  <section class="op-cols">
    <div><h2>What the analysis will show</h2><p>Households moving into and out of each station area and corridor every year from 2006 to 2025, by income and by race and ethnicity, set against control corridors without frequent transit.</p></div>
    <div><h2>How to use it</h2><p>Pick a line on the map, then a station. Every chart has a table, and every figure can be downloaded.</p></div>
  </section>
  <footer class="op-foot"><p>Metro Transit TOD Office · <a href="mailto:TOD@metrotransit.org">TOD@metrotransit.org</a></p></footer>
</article>
<p class="op-actions no-print"><button class="button" type="button" data-print>Print this page</button> <a class="button button-quiet" href="{base}one-pager/displacement-dashboard-one-pager.pdf">Download the PDF</a></p>
"""


def search_starts(base):
    """Four places a reader often starts from, as stops on one line."""
    d = json.loads((Path(__file__).resolve().parents[3] / "public" / "metropolitancouncil" / "data" / "dashboard.json").read_text())
    picks = [("green-line", "snelling"), ("blue-line", "lake-street-midtown-station"), ("b-line", "e-lake-st-and-chicago-ave"), ("c-line", "brooklyn-center-transit-center")]
    items = []
    for lid, sid in picks:
        line = next((l for l in d["lines"] if l["id"] == lid), None)
        st = next((x for x in (line or {}).get("stations", []) if x["id"] == sid), None)
        if line and st:
            items.append(f'<li><a href="{base}lines/{lid}/{sid}/"><span class="try-name">{E(st["name"])}</span><span class="try-line">{E(line["name"])}</span></a></li>')
    return f'<nav class="try-stops" aria-label="Places to start"><p class="kicker">Places to start</p><ol role="list">{"".join(items)}</ol></nav>' if items else ""


def search_main(base):
    return f"""
<section class="page-head">
  <h1>Search the dashboard</h1>
  <form class="search-page-form" role="search" aria-label="Search results" action="{base}search/" method="get">
    <label for="search-q">Search stations, lines, cities and documents</label>
    <div class="search-row"><input id="search-q" name="q" type="search" autocomplete="off"><button type="submit">Search</button></div>
  </form>
</section>
<p class="search-count" id="search-count"></p>
<div class="search-results" data-results>
  <noscript><p>Search needs JavaScript here. Every line and station is listed on <a href="{base}lines/">All lines</a>, and the sources are on <a href="{base}about-the-data/">About the data</a>.</p></noscript>
</div>
<p class="search-empty" id="search-empty-copy" data-empty-copy="Nothing on the map matches that yet. Try a station name, a street or a city, such as Snelling or Bloomington." hidden></p>
<div class="visually-hidden" role="status" aria-live="polite" aria-atomic="true" data-answer-announcer></div>
{search_starts(base)}
"""


def accessibility_main(base):
    return f"""
<section class="page-head page-head-portal">
  {portal(base, "access-rider", "platform-rider", "A woman in a wheelchair on a light rail platform beside a METRO train", "sm", small=600, painted="220px", large=1200, subject="0.2 0.03 0.75 0.95")}
  <h1>Accessibility</h1>
  <p class="lede">The dashboard is built to WCAG 2.2 AA, which includes the WCAG 2.1 AA level the Council requires for public web content.</p>
</section>
<div class="prose">
<ul>
<li>Every map view has a list or a table with the same numbers, and every chart has a "Show as table" button.</li>
<li>The line strip works from the keyboard: Tab to it, use the arrow keys to move between stations, Home and End for the ends of the line, and Enter to open a station.</li>
<li>Line colors always come with the line's name, and planned lines are drawn dashed, so color is never the only cue.</li>
<li>Motion is off when your device asks for reduced motion.</li>
<li>The pages work without JavaScript, apart from the map itself.</li>
</ul>
<p>If something does not work for you, write to the Metro Transit TOD Office at <a href="mailto:TOD@metrotransit.org">TOD@metrotransit.org</a> with the page and what happened.</p>
</div>
"""


def not_found_main(base):
    return f"""
<section class="page-head not-found">
  <p class="kicker">Page not found</p>
  <h1>This stop is not on the line</h1>
  <ol class="station-stop-route" role="list" aria-label="Where to go instead">
    <li><a href="{base}">Map</a></li>
    <li><a href="{base}lines/">Lines</a></li>
    <li class="is-missing"><span>This page</span></li>
  </ol>
  <p class="lede">The page may have moved when the dashboard was updated. Start from the map, or find a station by name.</p>
  <p class="actions" data-control-group="actions"><a class="button" href="{base}">Back to the map</a> <a class="button button-quiet" href="{base}lines/">All Lines and Stations</a></p>
</section>
"""


def write_site_pages(model, site: Path, base, chrome, page, write, home_main, lines_index_main, example_figure):
    css_map = f'\n<link rel="stylesheet" href="{base}assets/vendor/maplibre-gl-6.15.0/maplibre-gl.css">'
    pages = []

    def add(rel, title, desc, main, **kw):
        write(site, rel, page(base, title, desc, main, chrome=chrome, rel=rel, **kw))
        url = base + (rel[:-len("index.html")] if rel.endswith("index.html") else rel)
        pages.append((kw.get("search_title") or title.split(" · ")[0], url, _text(main)[:1200]))

    kw_home = dict(body_class="page-home", scripts=("line-strip.js", "dashboard.mjs"), head_extra=css_map, embed=True)
    add("index.html", "Displacement Dashboard · Metropolitan Council", "Change along every METRO line and High Frequency bus route, station by station: homes permitted since 2009 and, with the Displacement Analysis, who moved in and out.", home_main(model, base), **kw_home)
    pages[-1] = ("Map: change along transit", base, pages[-1][2])
    add("lines/index.html", "Lines and Stations · Displacement Dashboard", "Every METRO line and the High Frequency bus network, with homes permitted near each since 2009.", lines_index_main(model, base), body_class="page-lines")
    add("story/index.html", "The Story · Displacement Dashboard", "New development along the region's transit lines, and who it serves: the story of the Displacement Dashboard's data.", story_main(model, base, example_figure), body_class="page-story")
    add("about-the-data/index.html", "About the Data · Displacement Dashboard", "Sources, definitions, how homes are counted and what the Displacement Analysis adds.", about_main(model, base, example_figure), body_class="page-about", crumb=None)
    add("annual-update/index.html", "The Annual Update · Displacement Dashboard", "One documented script rebuilds the dashboard each year.", update_main(model, base), body_class="page-update")
    add("one-pager/index.html", "One-Pager · Displacement Dashboard", "A printable summary of the Displacement Dashboard.", one_pager_main(model, base), body_class="page-one-pager")
    add("accessibility/index.html", "Accessibility · Displacement Dashboard", "How the dashboard works with assistive technology, the keyboard and reduced motion.", accessibility_main(base), body_class="page-accessibility")
    write(site, "search/index.html", page(base, "Search · Displacement Dashboard", "Search stations, lines, cities and documents.", search_main(base), chrome=chrome, body_class="page-search", scripts=("answer-announcer.js", "search-page.js"), rel="search/index.html"))
    write(site, "404.html", page(base, "Page Not Found · Displacement Dashboard", "This page is not on the dashboard.", not_found_main(base), chrome=chrome, body_class="page-404", rel="404.html"))
    pages.append(("Contact the TOD Office", f"{base}about-the-data/#contact", "Questions about the data or the analysis: get in touch with the Metro Transit TOD Office by email, TOD@metrotransit.org. Contact, help, questions."))
    # the update files offered for download are the real ones
    files = site / "annual-update" / "files"
    files.mkdir(parents=True, exist_ok=True)
    for f in ("update_dashboard.py", "dashboard_data.py", "dashboard_html.py", "site_pages.py"):
        shutil.copyfile(HERE / f, files / f)
    shutil.copyfile(HERE / "schema" / "analysis-v1.json", files / "analysis-v1.json")
    return pages
