---
name: "document-to-site"
description: "Turns any long document (handbook, policy pack, supplier code, onboarding or training guide) into a branded, interactive single-file website with summaries, search and quizzes."
---

# Document to site

Turns a dropped-in document into a branded single-page website that people can read on any device, search and test themselves on. The person running this may not be technical. Speak plainly, give one instruction at a time and never assume they know what HTML, JSON or hosting means.

Use whenever someone drops in a document (a staff handbook, policy pack, supplier code, onboarding guide, training manual, product guide, process manual, board or investor pack, terms or member rules) and asks to "turn this into a website", "make this interactive", "make this easy to read", "build a 101 site", "a microsite for this guide", or similar.

## What you produce

1. `index.html`: one self-contained file (styles, scripts, logos, pattern and fonts inside) that any web server can host as it is (a company intranet, a secure internal server or, for non-confidential documents, Netlify Drop), or that can be opened straight from the computer.
2. A short summary in chat: how many sections, anything you were unsure about, and how to publish it safely.

## Step 0: Unpack the bundled files

This skill carries its scripts, styles and references at the end of this file, under "Bundled files". Before Step 1, create a working folder named `document-to-site` and write each bundled file into it at the path shown in its heading, exactly as written (copy the text between the `~~~~` fence lines, without the fences). Then run every command below from inside that folder. Read a reference file from that folder when a step points to it.

## Step 1: Gather what you need

Check what has already been provided. Then ask for anything missing in **one message**, as a short numbered list. Use the AskUserQuestion tool for the choices where it is available.

Required:
1. **The document** (Word, PDF, Markdown or text). If they have not attached it, ask for it first.
2. **Who will read the site** (for example new staff, all employees, suppliers, customers, members, investors, students) and **what they should be able to do after reading it**. This sets the tone, the "what this means for you" points and the quizzes.
3. **Organisation name** as the readers know it.
4. **Their brand guidelines** (PDF or images of the pages). Ask for these explicitly; the site is built from them. If they truly have none, accept their website link plus logo files, and say the result will be less on-brand.
5. **Logo files**: one for light backgrounds and, if they have it, one for dark backgrounds (SVG or transparent PNG). Check the guidelines for both versions before asking.
6. **Who readers should contact** with questions: name, role and email.

Optional (offer sensible defaults; do not block on these):
7. Owner and version label shown on the site (default: taken from the document, e.g. "Version: March 2026").
8. Short "About us" facts to show near the top. Leave out if not given; never invent them.
9. Whether to keep quizzes (default: yes) and the full original wording (default: yes, in a fold-out section).
10. **Who should hear when someone completes it**, and how: by Netlify Forms email notifications, by an email link that opens the reader's own email, or both (default: both, to the contact in item 6). Also the pass mark for each quiz (default: 80%, so 4 out of 5).
11. **Whether the document contains confidential information.** This decides how it should be published (see Step 7). Either way the site is marked private by default, so search engines are asked not to list it.
12. Font files, if their brand fonts are licensed and not on Google Fonts.
13. Language and spelling (default: British English).

## Step 1b: Read the brand guidelines and propose the brand mix

Read the guidelines properly: colour pages, typography, logo usage, graphic elements and any "do and don't" pages. For a PDF, render the relevant pages to images and look at them. Then follow `references/brand.md` to:

- Assign every brand colour a role: `brand`, `dark`, `tint`, `accents`, text and neutrals. The site uses a **mix**: a dark brand band (hero, final round, footer), a light brand tint on alternate sections, and two to four accent colours rotated across the contents groups and sections as bars, rules and markers.
- Pick up the brand's graphic element (pattern, line motif, shape, texture) and recreate it as an SVG or crop it from the guidelines as a PNG, for the dark bands.
- Set fonts, letter spacing for small capitals, and corner rounding from the guidelines.
- Follow the guidelines' own rules: colours that must not sit together, minimum logo sizes, clear space, colours reserved for accents only.

Before building, show the user a short summary of the brand mix in plain English (for example: "Navy for the header bands, sand for alternate sections, coral and teal as accents, your wave pattern behind the header, Poppins for headings") and ask them to confirm or adjust.

## Step 2: Read the document

```bash
python3 scripts/extract_document.py "<document file>" document.md
```

Read `document.md` in full. Map the document's own structure (parts, chapters, schedules, policies, modules, articles) to site sections. Opening material (introduction, how to use this document, definitions) can merge into one first section such as "Welcome and how this guide works". Very short related sections can merge; very long ones can split where the document has a natural break. Group sections into three to six groups that make sense to the reader.

If there are more than 15 sections, show the user the proposed section list and groups before writing all the content, and wait for a yes.

## Step 3: Choose the labels

The site's headings and buttons come from `labels` in `content.json`. Choose words that fit this document and audience. See `references/labels.md` for the full list, the defaults and worked examples for handbooks, supplier codes, onboarding guides, training manuals and product guides. Leave a label out to use the default.

## Step 4: Write the content

Write `content.json` following `references/content-schema.md` exactly. Follow `references/writing-rules.md`. The key rules:

- Every number, deadline, entitlement, price and step must come from the document. Never add facts, figures or advice that are not in it. If the document is unclear, say so in the chat summary; do not guess.
- Plain English for the stated readers. Short sentences. "You" for the reader; "we" for the organisation where the document speaks as the organisation.
- `full_text` carries the document's wording as written (light tidy-up of formatting only, no rewording).
- 6 to 8 quiz questions per section: realistic situations the reader might face, one clearly correct answer drawn from the document and a one-sentence reason.

For long documents, write the JSON in batches (for example five sections at a time) and merge them, so nothing gets cut short. The original wording can usually be split into `full_text` blocks with a short script from `document.md` instead of retyping it.

## Step 5: Write brand.json

Write `brand.json` from the confirmed brand mix, following `references/brand.md`. Put the logos, pattern and any font files next to `brand.json` and reference them by file name.

## Step 6: Build and check

```bash
python3 scripts/build_site.py --content content.json --brand brand.json --out site
```

- Fix every ERROR. Read every WARNING; fix contrast warnings by choosing a stronger shade from the brand palette, and tell the user what you changed.
- Open `site/index.html` in a headless browser at desktop (1440px), laptop (1280px) and mobile (390px) widths, take screenshots and look at them. Check the hero band and pattern, both logos, the contents groups and their accents, one plain and one tinted section, the sections sidebar (open a group, then a section), a quiz, the final round, the progress bar, the completion section (locked, then unlocked by setting every quiz as passed in localStorage) and the footer. Compare against the guidelines: if something would break one of their rules, fix it.
- Check every figure in "Key facts" against `document.md` one more time.

## Step 7: Hand it over

Give the user `site/index.html` as a downloadable file. Then tell them how to publish it, matching what they said about confidentiality.

**If the document contains confidential information**, say this first and plainly: do not publish it on Netlify, because anyone with a Netlify link can usually open the site. Ask them to send `index.html` to their tech team and ask for it to be hosted securely, for example on the intranet or behind the company login. The file needs no special setup: any web server can host it as it is.

**If it is not confidential**, give them these steps, exactly:

1. Log in to Netlify at **app.netlify.com/login** (or create a free account), so the site is saved to your account.
2. Put `index.html` in a new, empty folder on your computer, go to **app.netlify.com/drop** and drag the folder onto the page.
3. After a few seconds Netlify shows a web address ending in netlify.app. That is your site. Share the link with your readers.

If you are not sure whether it is confidential, recommend the tech team route.

**Completion notifications.** Readers' progress is saved in their own browser. When they pass every quiz, an on-screen notification appears and the completion form unlocks. Tell the user how they will hear about completions:

- On Netlify: in Netlify, open the site, click **Forms**, then **Enable form detection**. Drag the same folder in again under **Production deploys** (Netlify only finds the form on the next upload). Then go to **Forms**, then **Submission notifications**, and add an email notification with the address that should receive completions. An address outside their Netlify team has to confirm by email before notifications start. Test it by completing the site once.
- Anywhere else: the **Email my completion** button opens the reader's own email, addressed to the contact, with their name and scores filled in. Their tech team can also connect the form (named `completion`) to their own systems.

To update the site later: run this skill again with the new document (or tell Claude what changed). On Netlify, open the site and drag the new folder into the drag-and-drop area under **Production deploys**. If the tech team hosts it, send them the new file.

## Things to avoid

- Do not invent sections, figures, entitlements, contacts or organisation facts.
- Do not give legal, financial or medical advice in the summaries; describe what the document says.
- Do not hand-write the page HTML. Always build with `scripts/build_site.py` so the design, sidebar and quizzes work.
- Do not include personal data from the document beyond the named contacts the user has confirmed.

## Bundled files

### references/content-schema.md

~~~~
# content.json schema

```json
{
  "lang": "en-GB",
  "private": true,
  "quiz_per_round": 5,
  "organisation": {
    "name": "Acme",
    "document_title": "Supplier Code of Conduct",
    "headline": "Supplier Code 101",
    "intro": "What we expect from our suppliers, in plain English.",
    "version": "Version: October 2026",
    "owner": "Head of Procurement",
    "help_contact": {"name": "Sam Lee", "role": "Head of Procurement", "email": "suppliers@acme.com"},
    "about_title": "About Acme",
    "intro_story": "Optional short paragraph shown above the About facts.",
    "disclaimer": "Optional. Replaces the footer wording for this site only."
  },
  "labels": {
    "contents_title": "Find a standard",
    "doc_noun": "code",
    "section_noun": "standards"
  },
  "completion": {
    "enabled": true,
    "pass_mark": 0.8,
    "notify": "both",
    "email": "suppliers@acme.com",
    "notify_name": "Sam",
    "form_name": "completion"
  },
  "about": [
    {"label": "Founded", "value": "2019"},
    {"label": "Offices", "value": "London, Leeds"}
  ],
  "sections": [
    {
      "id": "gifts-hospitality",
      "group": "Doing business with us",
      "title": "Gifts and hospitality",
      "summary": "One line for the contents card (max ~110 characters).",
      "in_short": "Two or three sentences: the short version of the section.",
      "for_you": [
        "Practical point for the reader, starting with an action or fact.",
        "Another point."
      ],
      "key_facts": [
        {"label": "Gift limit", "value": "£50 per person per year"},
        {"label": "Declare to", "value": "Your Acme contact"}
      ],
      "questions": [
        {"q": "Can I send a gift at Christmas?", "a": "Answer taken from the document."}
      ],
      "full_text": [
        {"h": "Sub-heading as in the document"},
        {"p": "Paragraph as written in the document."},
        {"ul": ["List item", "List item"]}
      ],
      "quiz": [
        {
          "scenario": "A buyer at Acme mentions their birthday. Can you send a £100 hamper?",
          "options": ["No, it is over the gift limit", "Yes", "Yes, if sent to their home", "Only in December"],
          "answer": 0,
          "why": "Gifts are limited to £50 per person per year."
        }
      ]
    }
  ],
  "closing": {
    "title": "Why this matters",
    "body": ["Optional closing paragraph(s)."]
  }
}
```

The example values are illustrations only. Every value in a real site comes from the user's document or from the user.

## Field notes

- `organisation.name` and `organisation.document_title` are required. `headline` defaults to the document title.
- `labels`: optional. See `labels.md`. Leave out any label to use the default.
- `completion`: optional; on by default whenever there are quizzes. `pass_mark` is the share of each quiz a reader must get right (0.8 = 4 out of 5). `notify` is `"both"` (Netlify form and email button), `"netlify"` (form only) or `"email"` (email button only). `email` and `notify_name` default to the help contact. `form_name` is the name the form shows under in Netlify. Set `"enabled": false` to remove the progress bar and completion step.
- `sections`: required. (Older files that use `company`, `handbook_title`, `policy_owner` and `chapters` still work.)
- `id`: short, lowercase, hyphens. Auto-generated from the title if missing.
- `number`: optional. Defaults to 01, 02, 03 in order.
- `group`: optional. Sections with the same group appear together under that heading in the contents and the sidebar, and each group takes the next brand accent colour. Keep sections of one group next to each other. The contents grid is three columns wide, so size groups in threes (3, 6, 9...) where the subject matter allows, and avoid groups of one.
- `answer`: the index (starting at 0) of the correct option. Options are shuffled on screen, so write them in any order. Use 3 or 4 options.
- `full_text` blocks: `{"h": ...}` sub-heading, `{"p": ...}` paragraph, `{"ul": [...]}` bullets, `{"ol": [...]}` numbered list. A plain string is treated as a paragraph.
- `private`: `true` adds a "noindex" tag so search engines do not list the site. Use `false` for public guides.
- Leave out any optional section rather than filling it with invented content.
~~~~

### references/brand.md

~~~~
# brand.json: turning brand guidelines into the site's brand mix

The site is designed to use a **mix** of the brand, not one colour on white:

| Where | Role | What it uses |
|---|---|---|
| Hero, final round, footer | Dark brand band | `dark`, with the brand `pattern` faded behind it and `logo_on_dark` in the footer |
| Alternate sections, quiz feedback | Light brand tint | `tint` |
| Contents groups and their sections | Rotating accents | `accents` (one per group, in order): bars on the contents cards, group markers, the "In short" rule, key fact cards, tick markers, quiz header bar, the line under each section number |
| Buttons, links, section numbers | Main brand colour | `brand` |
| Who-to-ask card, focus rings | First accent | `accents[0]` |

Accents are only ever used for fills, bars and lines, never for body text, so light or bright accents are safe.

## Example

```json
{
  "colors": {
    "brand": "#223643",
    "dark": "#1C2D37",
    "tint": "#F0EBE5",
    "accents": ["#88B6CD", "#223643"],
    "background": "#FAFAFA",
    "surface": "#FFFFFF",
    "text": "#1B1B19",
    "heading": "#1C2D37",
    "muted": "#48565E",
    "line": "#E4E0D9",
    "on_dark_muted": "#C8D2D8"
  },
  "fonts": {
    "heading": "'Hedvig Letters Serif', Georgia, serif",
    "body": "'Rethink Sans', system-ui, sans-serif",
    "google_fonts_url": "https://fonts.googleapis.com/css2?family=Hedvig+Letters+Serif&family=Rethink+Sans:wght@400;600;700&display=swap",
    "heading_weight": 400,
    "eyebrow_spacing": "0.22em"
  },
  "font_css": null,
  "radius": "4px",
  "logo": "logo.svg",
  "logo_on_dark": "logo-white.svg",
  "pattern": "pattern.svg",
  "pattern_opacity": 0.9,
  "stripe": false
}
```

## Choosing each value from the guidelines

| Field | How to choose it |
|---|---|
| `brand` | The main brand colour, dark enough to read on the background (buttons and links use it). If the main colour is light or bright (yellow, lime, pale blue), put it in `accents` and use the darkest brand colour here. |
| `dark` | The brand's darkest colour (navy, charcoal, deep green). Used for big bands with white text. Must give at least 4.5:1 contrast with white. |
| `tint` | The brand's lightest warm or neutral colour (sand, cream, pale grey), or a very light version of an accent. Alternate sections sit on it. |
| `accents` | Two to four secondary brand colours. Order them by how prominent the guidelines want them: the first appears most. Respect any guideline that says a colour is "accent only" or "use sparingly". |
| `background` / `surface` | Page colour and card colour, usually the brand's white or off-white, and pure white. |
| `text`, `heading`, `muted`, `line` | Body text, headings, secondary text and borders. Use the brand's neutrals. `muted` must still read on both `background` and `tint`. |
| `on_dark_muted` | Optional. Secondary text colour on the dark bands. Defaults to a softened white. |
| `fonts` | Heading and body font stacks with safe fallbacks. `heading_weight` from the guidelines (often 400 for serif display faces). `eyebrow_spacing` is the letter spacing for small capitals labels if the guidelines specify one. |
| `google_fonts_url` | If the brand fonts are on Google Fonts, the stylesheet link. |
| `font_css` | If the user uploaded licensed font files, write a small CSS file with one `@font-face` per file (relative `url(...)` to each font file). The build embeds the files so nothing is fetched at load. Use the family names from that CSS in `fonts.heading` / `fonts.body`. Remind the user to check their font licence allows web embedding. |
| `radius` | Corner rounding: `0px` to `4px` for sharp, formal brands; `10px` to `16px` for soft, friendly ones. Match buttons or cards in the guidelines. |
| `logo` | The logo for light backgrounds (top bar). |
| `logo_on_dark` | The white or reversed logo for the dark footer. If none exists, leave it out and the company name is set in the heading font instead. Never recolour a logo the guidelines say must not be recoloured. |
| `pattern` | The brand's graphic element for the dark bands: a pattern, line motif, shape or texture. Recreate simple ones as an SVG (best), or crop from the guidelines as a PNG at least 1600px wide. Leave out if the brand has none. |
| `pattern_opacity` | How strongly the pattern shows (0 to 1). Keep it subtle: it must never compete with the heading. Start around 0.3 for busy patterns and 0.9 for already faint line motifs. |
| `stripe` | `true` shows a thin band of brand and accent colours under the top bar. Turn off if the guidelines keep colour blocks apart or the brand is very restrained. |

## Checks the build makes

The build warns if text would be hard to read (body text on background and tint, white on the dark band, link colour on the background). Fix warnings by picking a stronger shade from the guidelines, not by inventing a new colour. If the guidelines leave no compliant option, tell the user which pairing falls short.

## When the guidelines are thin

If the user only has a logo and a website, take the main colour, a dark and a light from the site, show the user the proposed mix, and ask them to confirm before building.
~~~~

### references/labels.md

~~~~
# Labels

Every heading, button and line of fixed text on the site can be changed through `labels` in `content.json`. Leave a label out to use the default.

| Label | Default | Where it shows |
|---|---|---|
| `contents_eyebrow` | Contents | Small label above the contents, and the top bar link |
| `contents_title` | Find a section | Contents heading |
| `contents_sub` | Each section starts with the short version, then what it means for you, the key facts, common questions, the full wording and a quick quiz. | Under the contents heading |
| `for_you` | What this means for you | Section sub-heading |
| `key_facts` | Key facts | Section sub-heading |
| `questions` | Questions people ask | Section sub-heading |
| `full_text` | The full wording | Section sub-heading |
| `full_text_open` | Read the full wording | Fold-out button |
| `quiz` | Test yourself | Quiz label |
| `final_eyebrow` | Final round | Final quiz label, top bar and sidebar link |
| `final_title` | Which section covers it? | Final quiz heading |
| `final_sub` | One situation from each section, in random order. Pick the section that covers it. | Under the final quiz heading |
| `help_title` | Who to ask | Contact card label |
| `help_text` | {name} can help with any question about this {doc_noun}. | Contact card text |
| `help_line` | Not sure how this applies to you? Ask {contact}. | Line at the end of each section |
| `section_noun` | sections | Count in the hero ("30 sections") |
| `doc_noun` | document | Used in `help_text` |
| `search` | Search | Search box placeholder |
| `nav_title` | Sections | Sidebar heading and phone button |
| `back` | Back to contents | Link at the end of each section |
| `owner` | Owner | Label before the owner in the hero |
| `section_singular` | section | Used in completion messages ("every section") |
| `progress` | {done} of {total} {section_noun} complete | Progress text in the sidebar and completion section |
| `complete_eyebrow` | Completion | Small label above the completion section |
| `complete_title` | Finish and confirm | Completion heading, sidebar button and notification button |
| `complete_locked` | Pass the quiz in every {section_singular} to finish. You need {pass} or more in each. Your progress is saved in this browser. | Shown until every quiz is passed |
| `complete_done` | You have completed the {doc}. Send your completion so {notify_name} has a record. | Shown once complete |
| `complete_toast` | You've completed every {section_singular}. Send your completion to finish. | On-screen notification |
| `form_name_label`, `form_email_label`, `form_team_label` | Your name / Your email / Team (optional) | Completion form fields |
| `form_submit` | Send my completion | Form button |
| `form_sent` | Thank you. Your completion has been sent. | After sending |
| `form_failed` | This page could not send it automatically. Please use the email button instead. | If the form cannot send (not on Netlify) |
| `email_button` | Email my completion | Email link button |
| `disclaimer` | This site summarises the {doc} from {org} in plain English. It does not replace or change the original. If anything here differs from the original document, the original applies. | Footer |

`{name}`, `{contact}`, `{doc_noun}`, `{doc}`, `{org}`, `{done}`, `{total}`, `{section_noun}`, `{section_singular}`, `{pass}` and `{notify_name}` are filled in automatically.

## Examples

**Staff handbook**
```json
{"contents_title": "Find a policy", "full_text": "The full policy", "final_title": "Which policy covers it?",
 "final_sub": "One situation from each chapter, in random order. Pick the policy that covers it.",
 "section_noun": "chapters", "doc_noun": "handbook", "search": "Search the handbook",
 "disclaimer": "This guide summarises the {org} {doc} in plain English. It does not change your contract or any policy. If anything here differs from the handbook itself, the handbook applies."}
```

**Supplier code of conduct** (readers: suppliers)
```json
{"contents_title": "Find a standard", "for_you": "What we expect from you", "full_text": "The full standard",
 "final_title": "Which standard covers it?", "doc_noun": "code", "section_noun": "standards",
 "help_line": "Questions about how this applies to your business? Ask {contact}."}
```

**Onboarding guide** (readers: new joiners)
```json
{"contents_title": "Your first weeks", "for_you": "What to do", "key_facts": "Good to know",
 "final_title": "Where would you find it?", "doc_noun": "guide", "section_noun": "topics"}
```

**Training manual** (readers: learners)
```json
{"contents_title": "Modules", "for_you": "What you need to know", "quiz": "Check your understanding",
 "final_title": "Which module covers it?", "doc_noun": "manual", "section_noun": "modules", "nav_title": "Modules"}
```

**Product or customer guide** (readers: customers)
```json
{"contents_title": "Find a topic", "for_you": "How it works for you", "questions": "Common questions",
 "final_title": "Which topic covers it?", "doc_noun": "guide", "section_noun": "topics",
 "help_title": "Need help?", "help_text": "{name} can help with any question about this {doc_noun}."}
```

Remove the quiz from a section by leaving its `quiz` list empty. With no quizzes anywhere, the final round is left out.
~~~~

### references/writing-rules.md

~~~~
# Writing rules

Write for the readers the user named. Picture one of them reading on a phone: they want to know what applies to them, what they need to do, and who to ask.

## Accuracy
- Every figure, time limit, price, entitlement and step comes from the document. Quote numbers exactly ("28 days", "within 14 days", "£250").
- If the document says "may", do not turn it into "will".
- If something is unclear or contradictory in the document, keep the summary neutral and list the point in your chat summary for the user to check.
- Do not add commentary, outside facts or advice the document does not give.

## Style
- Plain English for the stated audience. Short sentences. Active voice.
- "You" for the reader. "We" for the organisation where the document speaks as the organisation; otherwise use its name.
- No jargon unless the readers would already use it; if a term is needed, explain it in the same sentence.
- No em dashes. Use commas, colons or full stops.
- Avoid filler such as "it's important to note", "in summary", "navigate", "ensure that", "robust".
- British spelling unless the user asks otherwise.

## Each section
- `summary`: one line, what the section covers.
- `in_short`: two or three sentences that a reader could stop after and still know the essentials.
- `for_you`: 3 to 6 practical points for the reader. Lead with the action or fact.
- `key_facts`: 2 to 6 label/value pairs for the hard facts (numbers, deadlines, who approves, where to go). Skip if the section has none.
- `questions`: 2 to 4 questions the readers would actually ask, answered from the document.
- `quiz`: 6 to 8 everyday situations the readers could face. One correct answer, plausible wrong answers, a one-sentence reason that points back to the document. No trick questions, no "all of the above".

## Sensitive sections
Where a section deals with complaints, wrongdoing, discipline, health, family or bereavement, keep the tone calm and supportive, make clear who to contact, and keep quiz situations everyday and respectful. Never make light of harm, harassment or loss.
~~~~

### scripts/extract_document.py

~~~~
#!/usr/bin/env python3
"""Turn a document file (.docx, .pdf, .md, .txt) into plain markdown text so Claude can read it.

Usage: python3 extract_document.py <document file> <output .md>

Tries pandoc first, then python-docx / pdfplumber / pdftotext. Prints a list of
likely section headings so the section split can be checked.
"""
import os, re, shutil, subprocess, sys


def via_pandoc(src):
    if not shutil.which('pandoc'):
        return None
    try:
        return subprocess.run(['pandoc', src, '-t', 'gfm', '--wrap=none'], capture_output=True, text=True, check=True).stdout
    except Exception:
        return None


def docx_text(src):
    try:
        import docx  # python-docx
    except ImportError:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'python-docx', '--break-system-packages'])
        import docx
    d = docx.Document(src)
    out = []
    for p in d.paragraphs:
        t = p.text.strip()
        if not t:
            continue
        style = (p.style.name or '').lower()
        m = re.search(r'heading\s*(\d)', style)
        if m:
            out.append('#' * int(m.group(1)) + ' ' + t)
        elif 'list' in style:
            out.append('- ' + t)
        else:
            out.append(t)
    return '\n\n'.join(out)


def pdf_text(src):
    if shutil.which('pdftotext'):
        r = subprocess.run(['pdftotext', '-layout', src, '-'], capture_output=True, text=True)
        if r.returncode == 0 and r.stdout.strip():
            return r.stdout
    try:
        import pdfplumber
    except ImportError:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'pdfplumber', '--break-system-packages'])
        import pdfplumber
    with pdfplumber.open(src) as pdf:
        return '\n\n'.join((pg.extract_text() or '') for pg in pdf.pages)


def main():
    if len(sys.argv) != 3:
        print(__doc__); sys.exit(1)
    src, dst = sys.argv[1], sys.argv[2]
    ext = os.path.splitext(src)[1].lower()
    if ext in ('.md', '.txt'):
        text = open(src, encoding='utf-8', errors='ignore').read()
    elif ext == '.pdf':
        text = pdf_text(src)
    elif ext in ('.docx', '.doc', '.odt', '.rtf'):
        text = via_pandoc(src) or (docx_text(src) if ext == '.docx' else None)
    else:
        text = via_pandoc(src)
    if not text or len(text.strip()) < 200:
        print('Could not read enough text from the file. If it is a scanned PDF, ask for a Word version.')
        sys.exit(2)
    open(dst, 'w', encoding='utf-8').write(text)
    words = len(text.split())
    print(f'Wrote {dst}: about {words:,} words')
    heads = [l.strip() for l in text.splitlines()
             if re.match(r'^(#{1,3} |schedule \d+|part \d+|section \d+|\d{1,2}\.?\s+[A-Z])', l.strip(), re.I)]
    print('Likely headings (first 60):')
    for h in heads[:60]:
        print('  ', h[:100])


if __name__ == '__main__':
    main()
~~~~

### scripts/build_site.py

~~~~
#!/usr/bin/env python3
"""Build a single-file interactive website from any long document: content.json + brand.json.

Usage:
  python3 build_site.py --content content.json --brand brand.json --out ./site

Writes ./site/index.html (everything inlined, logos and pattern embedded) ready to
drag onto Netlify Drop or any static host. Prints warnings for missing content
and colour contrast problems. Exits non-zero on errors that would break the site.

The design uses a mix of the brand's colours: a dark brand band for the hero,
final round and footer, a light brand tint for alternate sections, and the
accent colours rotated across contents groups and chapters as bars, rules and
markers. Accents are only used for fills and lines, never for body text.
"""
import argparse, base64, html, json, mimetypes, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
ASSETS = os.path.join(HERE, '..', 'assets')

DEFAULT_BRAND = {
    "colors": {"brand": "#1F3A5F", "dark": None, "tint": None, "accent": "#E8A33D", "accents": None,
                "background": "#FAFAF7", "surface": "#FFFFFF", "text": "#1E1E1E", "heading": None,
                "muted": "#5F6368", "line": "#E3E1DC", "link": None, "on_dark_muted": None,
                "good": "#1E7B4A", "bad": "#B3261E"},
    "fonts": {"heading": "Georgia, serif", "body": "system-ui, -apple-system, 'Segoe UI', sans-serif",
               "google_fonts_url": None, "heading_weight": 700, "eyebrow_spacing": "0.14em"},
    "radius": "10px",
    "logo": None,
    "logo_on_dark": None,
    "pattern": None,
    "pattern_opacity": 0.35,
    "font_css": None,
    "stripe": True,
}

DEFAULT_LABELS = {
    "contents_eyebrow": "Contents",
    "contents_title": "Find a section",
    "contents_sub": "Each section starts with the short version, then what it means for you, the key facts, common questions, the full wording and a quick quiz.",
    "for_you": "What this means for you",
    "key_facts": "Key facts",
    "questions": "Questions people ask",
    "full_text": "The full wording",
    "full_text_open": "Read the full wording",
    "quiz": "Test yourself",
    "final_eyebrow": "Final round",
    "final_title": "Which section covers it?",
    "final_sub": "One situation from each section, in random order. Pick the section that covers it.",
    "help_title": "Who to ask",
    "help_text": "{name} can help with any question about this {doc_noun}.",
    "help_line": "Not sure how this applies to you? Ask {contact}.",
    "section_noun": "sections",
    "doc_noun": "document",
    "search": "Search",
    "nav_title": "Sections",
    "back": "Back to contents",
    "owner": "Owner",
    "progress": "{done} of {total} {section_noun} complete",
    "progress_short": "Your progress",
    "complete_eyebrow": "Completion",
    "complete_title": "Finish and confirm",
    "complete_locked": "Pass the quiz in every {section_singular} to finish. You need {pass} or more in each. Your progress is saved in this browser.",
    "complete_done": "You have completed the {doc}. Send your completion so {notify_name} has a record.",
    "complete_toast": "You've completed every {section_singular}. Send your completion to finish.",
    "form_name_label": "Your name",
    "form_email_label": "Your email",
    "form_team_label": "Team (optional)",
    "form_submit": "Send my completion",
    "form_sent": "Thank you. Your completion has been sent.",
    "form_failed": "This page could not send it automatically. Please use the email button instead.",
    "email_button": "Email my completion",
    "section_singular": "section",
    "disclaimer": "This site summarises the {doc} from {org} in plain English. It does not replace or change the original. If anything here differs from the original document, the original applies.",
}

errors, warnings = [], []
esc = lambda s: html.escape(str(s or ''), quote=True)


# ---------- colour helpers ----------
def hex_rgb(h):
    h = h.strip().lstrip('#')
    if len(h) == 3:
        h = ''.join(c * 2 for c in h)
    if not re.fullmatch(r'[0-9a-fA-F]{6}', h):
        raise ValueError(h)
    return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))

def rgb_hex(t):
    return '#' + ''.join(f'{max(0, min(255, round(c * 255))):02X}' for c in t)

def mix(a, b, t):
    """Blend colour a towards b by t (0..1)."""
    ra, rb = hex_rgb(a), hex_rgb(b)
    return rgb_hex(tuple(x + (y - x) * t for x, y in zip(ra, rb)))

def lum(h):
    def ch(c):
        return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
    r, g, b = (ch(c) for c in hex_rgb(h))
    return 0.2126 * r + 0.7152 * g + 0.0722 * b

def contrast(a, b):
    la, lb = sorted((lum(a), lum(b)), reverse=True)
    return (la + 0.05) / (lb + 0.05)


def merge(base, over):
    out = dict(base)
    for k, v in (over or {}).items():
        if isinstance(v, dict) and isinstance(base.get(k), dict):
            out[k] = merge(base[k], v)
        elif v is not None:
            out[k] = v
    return out


def slugify(s):
    return re.sub(r'[^a-z0-9]+', '-', str(s).lower()).strip('-') or 'section'


def data_uri(path, base_dir, label):
    if not path:
        return None
    if str(path).startswith('data:'):
        return path
    p = path if os.path.isabs(path) else os.path.join(base_dir, path)
    if not os.path.exists(p):
        warnings.append(f'{label} not found at {p}; leaving it out.')
        return None
    mime = mimetypes.guess_type(p)[0] or 'image/png'
    return f'data:{mime};base64,' + base64.b64encode(open(p, 'rb').read()).decode()


# ---------- rendering ----------
def render_blocks(blocks):
    out = []
    for b in blocks or []:
        if isinstance(b, str):
            out.append(f'<p>{esc(b)}</p>')
        elif 'h' in b:
            out.append(f'<h4>{esc(b["h"])}</h4>')
        elif 'p' in b:
            out.append(f'<p>{esc(b["p"])}</p>')
        elif 'ul' in b:
            out.append('<ul>' + ''.join(f'<li>{esc(i)}</li>' for i in b['ul']) + '</ul>')
        elif 'ol' in b:
            out.append('<ol>' + ''.join(f'<li>{esc(i)}</li>' for i in b['ol']) + '</ol>')
    return '\n'.join(out)


def render_facts(facts):
    if not facts:
        return ''
    return '<dl class="facts">' + ''.join(
        f'<div><dt>{esc(f["label"])}</dt><dd>{esc(f["value"])}</dd></div>' for f in facts) + '</dl>'


def render_chapter(c, help_line, alt, L):
    parts = [f'<section class="chapter{" alt" if alt else ""}" id="{c["id"]}" style="--acc:{c["_acc"]}"><div class="wrap narrow">',
             f'<div class="chapter-head"><span class="num">{esc(c["number"])}</span><div>'
             + (f'<span class="chip">{esc(c["group"])}</span>' if c.get('group') else '') +
             f'<h2>{esc(c["title"])}</h2></div></div>']
    if c.get('in_short'):
        parts.append(f'<p class="in-short">{esc(c["in_short"])}</p>')
    if c.get('for_you'):
        parts.append(f'<h3>{esc(L["for_you"])}</h3><ul class="you">' +
                     ''.join(f'<li>{esc(x)}</li>' for x in c['for_you']) + '</ul>')
    if c.get('key_facts'):
        parts.append(f'<h3>{esc(L["key_facts"])}</h3>' + render_facts(c['key_facts']))
    if c.get('questions'):
        parts.append(f'<h3>{esc(L["questions"])}</h3>' + ''.join(
            f'<details><summary>{esc(q["q"])}</summary><div class="inner"><p>{esc(q["a"])}</p></div></details>'
            for q in c['questions']))
    if c.get('full_text'):
        parts.append(f'<h3>{esc(L["full_text"])}</h3><details class="fulltext"><summary>{esc(L["full_text_open"])}</summary>'
                     f'<div class="inner">{render_blocks(c["full_text"])}</div></details>')
    if help_line:
        parts.append(f'<p class="help-line">{help_line}</p>')
    if c.get('quiz'):
        parts.append(f'<div class="quiz" id="quiz-{c["id"]}" data-label="{esc(L["quiz"])}"></div>')
    parts.append(f'<a class="back" href="#contents">{esc(L["back"])}</a></div></section>')
    return '\n'.join(parts)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--content', required=True)
    ap.add_argument('--brand', required=True)
    ap.add_argument('--out', required=True)
    a = ap.parse_args()

    content = json.load(open(a.content))
    brand = merge(DEFAULT_BRAND, json.load(open(a.brand)))
    brand_dir = os.path.dirname(os.path.abspath(a.brand))
    col = brand['colors']

    accents = col.get('accents') or [col['accent']]
    col['accents'] = None
    for k, v in list(col.items()):
        if v is None:
            continue
        try:
            hex_rgb(v)
        except Exception:
            errors.append(f'Colour "{k}" is not a valid hex value: {v}')
    for v in accents:
        try:
            hex_rgb(v)
        except Exception:
            errors.append(f'Accent colour is not a valid hex value: {v}')
    if errors:
        print('ERRORS:'); [print(' -', e) for e in errors]; sys.exit(1)

    col['heading'] = col.get('heading') or col['text']
    col['link'] = col.get('link') or col['brand']
    col['dark'] = col.get('dark') or (col['brand'] if lum(col['brand']) < 0.08 else mix(col['brand'], '#000000', 0.55))
    col['tint'] = col.get('tint') or mix(accents[0], col['background'], 0.88)
    col['on_brand'] = '#FFFFFF' if contrast(col['brand'], '#FFFFFF') >= contrast(col['brand'], '#111111') else '#111111'
    col['on_dark'] = '#FFFFFF' if contrast(col['dark'], '#FFFFFF') >= contrast(col['dark'], '#111111') else '#111111'
    col['on_dark_muted'] = col.get('on_dark_muted') or mix(col['on_dark'], col['dark'], 0.25)
    col['tint_line'] = mix(col['tint'], col['text'], 0.1)
    col['accent'] = accents[0]
    # the brightest accent that reads on the dark band, for eyebrows and numbers there
    dark_ok = [x for x in accents if contrast(x, col['dark']) >= 3] or [col['on_dark']]
    col['accent_on_dark'] = max(dark_ok, key=lambda x: contrast(x, col['dark']))

    checks = [('text', 'background', 4.5), ('text', 'surface', 4.5), ('text', 'tint', 4.5),
              ('muted', 'background', 4.5), ('muted', 'tint', 4.5), ('heading', 'background', 3.0),
              ('link', 'background', 4.5), ('on_dark', 'dark', 4.5), ('on_dark_muted', 'dark', 4.5)]
    for fg, bg, need in checks:
        r = contrast(col[fg], col[bg])
        if r < need:
            warnings.append(f'Contrast {fg} on {bg} is {r:.1f}:1 (needs {need}:1). Pick a stronger shade from the brand palette.')
    if contrast(col['brand'], col['background']) < 3:
        warnings.append(f'Brand colour {col["brand"]} is faint on the background; use a darker brand shade as "brand" and keep the light one in "accents".')

    co = content.get('organisation') or content.get('company') or {}
    co['doc_title'] = co.get('document_title') or co.get('handbook_title')
    if not co.get('name'):
        errors.append('organisation.name is missing')
    if not co.get('doc_title'):
        errors.append('organisation.document_title is missing')
    L = dict(DEFAULT_LABELS, **(content.get('labels') or {}))
    chapters = content.get('sections') or content.get('chapters') or []
    if not chapters:
        errors.append('No sections found in content.json')

    seen = set()
    for i, c in enumerate(chapters, 1):
        c['number'] = c.get('number') or f'{i:02d}'
        c['id'] = slugify(c.get('id') or c.get('title', f'chapter-{i}'))
        while c['id'] in seen:
            c['id'] += '-x'
        seen.add(c['id'])
        if not c.get('title'):
            errors.append(f'Section {i} has no title')
        if not c.get('summary'):
            warnings.append(f'Section "{c.get("title")}" has no one-line summary')
        if not c.get('full_text'):
            warnings.append(f'Section "{c.get("title")}" has no full wording')
        q = c.get('quiz') or []
        if len(q) < 5:
            warnings.append(f'Section "{c.get("title")}" has {len(q)} quiz questions (aim for 6 to 8)')
        for j, item in enumerate(q, 1):
            if not isinstance(item.get('answer'), int) or not (0 <= item['answer'] < len(item.get('options', []))):
                errors.append(f'Section "{c.get("title")}" quiz {j}: answer index is invalid')
    if errors:
        print('ERRORS:'); [print(' -', e) for e in errors]
        sys.exit(1)

    # one accent per contents group, rotating through the brand accents
    groups, order = {}, []
    for c in chapters:
        g = c.get('group') or ''
        if g not in groups:
            groups[g] = []; order.append(g)
        groups[g].append(c)
    for gi, g in enumerate(order):
        for c in groups[g]:
            c['_acc'] = accents[gi % len(accents)]

    help_ = co.get('help_contact') or {}
    help_line = ''
    if help_.get('name'):
        contact = esc(help_['name']) + (f', {esc(help_["role"])}' if help_.get('role') else '')
        if help_.get('email'):
            contact += f' (<a href="mailto:{esc(help_["email"])}">{esc(help_["email"])}</a>)'
        help_line = esc(L['help_line']).replace('{contact}', contact)

    toc_html = []
    for gi, g in enumerate(order):
        acc = accents[gi % len(accents)]
        toc_html.append(f'<div class="toc-group" style="--acc:{acc}">')
        if g:
            toc_html.append(f'<p class="group-title"><span class="dot"></span>{esc(g)}</p>')
        toc_html.append('<div class="toc">' + ''.join(
            f'<a href="#{c["id"]}"><span class="num">{esc(c["number"])}</span><strong>{esc(c["title"])}</strong>'
            f'<small>{esc(c.get("summary"))}</small><span class="status" data-status="{c["id"]}">'
            f'{"Quiz not taken yet" if c.get("quiz") else ""}</span></a>' for c in groups[g]) + '</div></div>')

    comp_cfg = dict({"enabled": True, "pass_mark": 0.8, "notify": "both", "form_name": "completion", "email": None, "notify_name": None},
                    **(content.get('completion') or {}))
    quiz_count = sum(1 for c in chapters if c.get('quiz'))
    completion_on = bool(comp_cfg['enabled']) and quiz_count > 0
    comp_email = comp_cfg['email'] or help_.get('email') or ''
    notify_name = comp_cfg['notify_name'] or (help_.get('name', '').split()[0] if help_.get('name') else co['name'])
    use_form = comp_cfg['notify'] in ('both', 'netlify')
    use_email = comp_cfg['notify'] in ('both', 'email') and comp_email
    per = int(content.get('quiz_per_round', 5))
    import math
    pass_n = max(1, math.ceil(per * float(comp_cfg['pass_mark'])))
    def fill(t):
        return (t.replace('{section_noun}', L['section_noun']).replace('{section_singular}', L['section_singular'])
                 .replace('{doc}', co['doc_title']).replace('{notify_name}', notify_name).replace('{pass}', f'{pass_n}/{per}'))
    complete_html = ''
    progress_html = ''
    if completion_on:
        fname = esc(comp_cfg['form_name'])
        form = ''
        if use_form:
            form = (f'<form class="comp-form" name="{fname}" method="POST" data-netlify="true" netlify-honeypot="bot-field" id="comp-form">'
                    f'<input type="hidden" name="form-name" value="{fname}">'
                    '<p class="hp"><label>Leave this empty <input name="bot-field"></label></p>'
                    f'<input type="hidden" name="document" value="{esc(co["name"] + " " + co["doc_title"])}">'
                    '<input type="hidden" name="result" id="comp-result"><input type="hidden" name="completed_at" id="comp-date">'
                    f'<label><span>{esc(L["form_name_label"])}</span><input name="name" required autocomplete="name"></label>'
                    f'<label><span>{esc(L["form_email_label"])}</span><input name="email" type="email" required autocomplete="email"></label>'
                    f'<label><span>{esc(L["form_team_label"])}</span><input name="team" autocomplete="organization-title"></label>'
                    f'<div class="comp-actions"><button class="btn" type="submit">{esc(L["form_submit"])}</button>'
                    + (f'<a class="btn ghost" id="comp-mail" href="#">{esc(L["email_button"])}</a>' if use_email else '') +
                    '</div><p class="comp-status" id="comp-status" role="status"></p></form>')
        elif use_email:
            form = (f'<div class="comp-form"><label><span>{esc(L["form_name_label"])}</span><input id="comp-name-only" autocomplete="name"></label>'
                    f'<div class="comp-actions"><a class="btn" id="comp-mail" href="#">{esc(L["email_button"])}</a></div></div>')
        complete_html = (f'<section class="block tint complete" id="complete"><div class="wrap narrow">'
                         f'<p class="eyebrow">{esc(L["complete_eyebrow"])}</p><h2>{esc(L["complete_title"])}</h2>'
                         f'<div class="comp-progress"><div class="bar"><span class="fill" data-progress-fill></span></div><p class="count" data-progress-text></p></div>'
                         f'<p class="comp-locked">{esc(fill(L["complete_locked"]))}</p>'
                         f'<div class="comp-open"><p>{esc(fill(L["complete_done"]))}</p>{form}</div>'
                         '</div></section>')
        progress_html = '<div class="progress-top" aria-hidden="true"><span class="fill" data-progress-fill></span></div>'

    side = [f'<nav class="sidenav" id="sidenav" aria-label="{esc(L["nav_title"])}"><div class="side-head"><p class="side-title">{esc(L["nav_title"])}</p><button type="button" class="nav-close" id="nav-close" aria-label="Close sections"></button></div>']
    for gi, g in enumerate(order):
        acc = accents[gi % len(accents)]
        side.append(f'<div class="side-group" style="--acc:{acc}">')
        if g:
            side.append(f'<button type="button" class="side-group-title" aria-expanded="false"><span class="dot"></span><span class="gname">{esc(g)}</span><span class="count">{len(groups[g])}</span><span class="chev" aria-hidden="true"></span></button>')
        side.append('<ul>' + ''.join(f'<li><a href="#{c["id"]}" data-nav="{c["id"]}"><span>{esc(c["number"])}</span>{esc(c["title"])}</a></li>' for c in groups[g]) + '</ul></div>')
    side.append('<div class="side-links">')
    if any(c.get('quiz') for c in chapters) and len(chapters) > 1:
        side.append(f'<a class="side-final" href="#final" data-nav="final">{esc(L["final_eyebrow"])}</a>')
    if completion_on:
        side.append(f'<a class="side-final side-complete" href="#complete" data-nav="complete">{esc(L["complete_title"])}</a>')
    side.append('</div>')
    if completion_on:
        side.append(f'<div class="side-progress"><div class="bar"><span class="fill" data-progress-fill></span></div><p data-progress-text></p></div>')
    side.append('</nav><button class="nav-toggle" id="nav-toggle" type="button" aria-controls="sidenav" aria-expanded="false">' + esc(L['nav_title']) + '</button><div class="nav-scrim" id="nav-scrim"></div>')
    side_html = ''.join(side)

    about = content.get('about') or []
    about_html = ''
    if about or co.get('intro_story'):
        about_html = ('<section class="block tint"><div class="wrap narrow">'
                      f'<h2>{esc(co.get("about_title") or "About us")}</h2>'
                      + (f'<p>{esc(co["intro_story"])}</p>' if co.get('intro_story') else '')
                      + render_facts(about) + '</div></section>')

    help_html = ''
    if help_.get('name'):
        btn = f'<a class="btn" href="mailto:{esc(help_["email"])}">Email {esc(help_["name"].split()[0])}</a>' if help_.get('email') else ''
        help_html = ('<div class="wrap narrow help-wrap"><div class="card help"><div class="who">'
                     f'<p class="eyebrow">{esc(L["help_title"])}</p><p style="margin:0">'
                     + esc(L['help_text'].replace('{doc_noun}', L['doc_noun'])).replace('{name}', esc(help_['name']) + (', ' + esc(help_['role']) if help_.get('role') else '')) + '</p>'
                     + f'</div>{btn}</div></div>')

    closing = content.get('closing') or {}
    closing_html = ''
    if closing.get('body'):
        closing_html = (f'<section class="block"><div class="wrap narrow"><h2>{esc(closing.get("title") or "Why this matters")}</h2>'
                        + ''.join(f'<p>{esc(p)}</p>' for p in (closing['body'] if isinstance(closing['body'], list) else [closing['body']]))
                        + '</div></section>')

    owner = co.get('owner') or co.get('policy_owner')
    meta = [m for m in (co.get('version'), owner and f'{L["owner"]}: {owner}',
                        f'{len(chapters)} {L["section_noun"]}') if m]
    disclaimer = co.get('disclaimer') or L['disclaimer'].replace('{org}', co['name']).replace('{doc}', co['doc_title'])

    logo = data_uri(brand.get('logo'), brand_dir, 'Logo')
    logo_dark = data_uri(brand.get('logo_on_dark'), brand_dir, 'Logo for dark backgrounds')
    pattern = data_uri(brand.get('pattern'), brand_dir, 'Pattern')
    logo_tag = f'<img src="{logo}" alt="{esc(co["name"])}">' if logo else f'<span>{esc(co["name"])}</span>'
    logo_dark_tag = (f'<img src="{logo_dark}" alt="{esc(co["name"])}">' if logo_dark
                     else f'<span class="name-on-dark">{esc(co["name"])}</span>')

    f = brand['fonts']
    font_css = ''
    if brand.get('font_css'):
        fp = brand['font_css'] if os.path.isabs(brand['font_css']) else os.path.join(brand_dir, brand['font_css'])
        if os.path.exists(fp):
            font_css = open(fp).read()
            # inline any font files the CSS points to by relative path
            def _inline(m):
                u = m.group(1).strip('\'"')
                if u.startswith('data:') or u.startswith('http'):
                    return m.group(0)
                d = data_uri(u, os.path.dirname(fp), 'Font file')
                return f'url("{d}")' if d else m.group(0)
            font_css = re.sub(r'url\(([^)]+)\)', _inline, font_css)
        else:
            warnings.append(f'Font CSS not found at {fp}')
    font_link = (f'<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>'
                 f'<link rel="stylesheet" href="{esc(f["google_fonts_url"])}">') if f.get('google_fonts_url') else ''
    varname = {'background': 'bg', 'text': 'ink'}
    root = (':root{' + ''.join(f'--{varname.get(k, k).replace("_", "-")}:{v};' for k, v in col.items() if v)
            + f'--font-heading:{f["heading"]};--font-body:{f["body"]};--heading-weight:{f.get("heading_weight", 700)};'
            f'--eyebrow-spacing:{f.get("eyebrow_spacing", "0.14em")};--radius:{brand["radius"]};'
            f'--pattern:{("url(" + chr(34) + pattern + chr(34) + ")") if pattern else "none"};'
            f'--pattern-opacity:{brand.get("pattern_opacity", 0.35)};}}')

    data = {'slug': slugify(co['name'] + '-' + co['doc_title']), 'perRound': int(content.get('quiz_per_round', 5)),
            'completion': ({'passMark': float(comp_cfg['pass_mark']), 'email': comp_email if use_email else '',
                            'subject': f'Completed: {co["name"]} {co["doc_title"]}', 'docName': f'{co["name"]} {co["doc_title"]}',
                            'progress': L['progress'].replace('{section_noun}', L['section_noun']),
                            'toast': fill(L['complete_toast']), 'sent': L['form_sent'], 'failed': L['form_failed'],
                            'toastButton': L['complete_title']} if completion_on else None),
            'chapters': [{'id': c['id'], 'number': c['number'], 'title': c['title'], 'summary': c.get('summary', ''),
                          'quiz': c.get('quiz') or []} for c in chapters]}
    data_json = json.dumps(data, ensure_ascii=False).replace('</', '<\\/')

    css = open(os.path.join(ASSETS, 'site.css')).read()
    js = open(os.path.join(ASSETS, 'site.js')).read()
    title = f'{co["name"]} {co["doc_title"]}'
    has_final = any(c.get('quiz') for c in chapters) and len(chapters) > 1
    stripe = ''.join(f'<span style="background:{x}"></span>' for x in [col['brand']] + accents)

    page = f'''<!DOCTYPE html>
<html lang="{esc(content.get("lang", "en-GB"))}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{esc(title)}</title>
<meta name="description" content="{esc(co.get("intro"))}">
<meta name="robots" content="{"noindex" if content.get("private", True) else "index"}">
{font_link}
<style>{font_css}
{root}
{css}</style>
</head>
<body>
<header class="topbar"><div class="wrap">
<a class="logo" href="#top">{logo_tag}</a>
<nav><a class="hide-sm" href="#contents">{esc(L['contents_eyebrow'])}</a>{f'<a class="hide-sm" href="#final">{esc(L["final_eyebrow"])}</a>' if has_final else ''}
<div class="search"><input id="search" type="search" placeholder="{esc(L['search'])}" aria-label="{esc(L['search'])}"><div class="search-results" id="search-results"></div></div></nav>
</div>{('<div class="stripe" aria-hidden="true">' + stripe + '</div>') if brand.get('stripe') and len(accents) > 1 else ''}{progress_html}</header>
{side_html}
<main id="top">
<section class="hero dark"><div class="pattern" aria-hidden="true"></div><div class="wrap narrow">
<span class="eyebrow">{esc(co["name"])} · {esc(co["doc_title"])}</span>
<h1>{esc(co.get("headline") or co["doc_title"])}</h1>
<p class="lead">{esc(co.get("intro"))}</p>
<div class="meta">{''.join(f'<span class="pill">{esc(m)}</span>' for m in meta)}</div>
</div></section>
{help_html}
{about_html}
<section class="block" id="contents"><div class="wrap"><p class="eyebrow">{esc(L['contents_eyebrow'])}</p><h2>{esc(L['contents_title'])}</h2>
<p class="sub">{esc(L['contents_sub'])}</p>
{''.join(toc_html)}</div></section>
{''.join(render_chapter(c, help_line, i % 2 == 0, L) for i, c in enumerate(chapters))}
{('<section class="block dark final" id="final"><div class="pattern" aria-hidden="true"></div><div class="wrap narrow"><p class="eyebrow">' + esc(L['final_eyebrow']) + '</p><h2>' + esc(L['final_title']) + '</h2><p class="sub">' + esc(L['final_sub']) + '</p><div class="quiz" id="quiz-final" data-label="' + esc(L['final_eyebrow']) + '"></div></div></section>') if has_final else ''}
{complete_html}
{closing_html}
</main>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<footer class="dark"><div class="wrap narrow"><div class="foot-logo">{logo_dark_tag}</div><p>{esc(disclaimer)}</p><p>{esc(co.get("version") or "")}</p></div></footer>
<script>window.HB={data_json};</script>
<script>{js}</script>
</body>
</html>'''

    os.makedirs(a.out, exist_ok=True)
    out = os.path.join(a.out, 'index.html')
    open(out, 'w', encoding='utf-8').write(page)
    print(f'Built {out} ({len(page) // 1024} KB, {len(chapters)} sections, {len(accents)} accent colour(s))')
    if warnings:
        print('WARNINGS:'); [print(' -', w) for w in warnings]


if __name__ == '__main__':
    main()
~~~~

### assets/site.css

~~~~
/* Document site styles. Brand values arrive as CSS variables set in :root by build_site.py.
   Colour roles: --brand (buttons, links, numbers), --dark (hero, final round, footer),
   --tint (alternate sections), --acc (rotating accent per group: bars, rules, markers only). */
*,*::before,*::after{box-sizing:border-box}
html{scroll-behavior:smooth;scroll-padding-top:84px}
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--font-body);font-size:17px;line-height:1.65;-webkit-font-smoothing:antialiased}
h1,h2,h3,h4{font-family:var(--font-heading);color:var(--heading);line-height:1.18;margin:0 0 .5em;font-weight:var(--heading-weight);letter-spacing:-.01em}
h1{font-size:clamp(2.4rem,5.4vw,4rem);letter-spacing:-.02em}
h2{font-size:clamp(1.7rem,3.4vw,2.4rem)}
h3{font-size:1.2rem}
p{margin:0 0 1em}
a{color:var(--link)}
:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
.wrap{max-width:1040px;margin:0 auto;padding:0 24px}
.narrow{max-width:780px}
.eyebrow{display:inline-block;font-size:.76rem;font-weight:700;letter-spacing:var(--eyebrow-spacing);text-transform:uppercase;color:var(--brand);margin:0 0 12px}
.sub{color:var(--muted);max-width:640px}

/* Dark brand bands */
.dark{position:relative;background:var(--dark);color:var(--on-dark);overflow:hidden}
.dark h1,.dark h2,.dark h3{color:var(--on-dark)}
.dark .eyebrow{color:var(--accent-on-dark)}
.dark .sub,.dark .lead{color:var(--on-dark-muted)}
.dark a{color:var(--on-dark)}
.dark .wrap{position:relative;z-index:1}
.pattern{position:absolute;inset:0;background-image:var(--pattern);background-size:cover;background-position:center;opacity:var(--pattern-opacity);pointer-events:none;
  -webkit-mask-image:linear-gradient(to bottom,#000 0%,rgba(0,0,0,.35) 70%,transparent 100%);mask-image:linear-gradient(to bottom,#000 0%,rgba(0,0,0,.35) 70%,transparent 100%)}

/* Top bar */
.topbar{position:sticky;top:0;z-index:20;background:var(--bg);border-bottom:1px solid var(--line)}
.topbar .wrap{display:flex;align-items:center;gap:20px;height:66px}
.topbar .logo img{height:30px;width:auto;display:block}
.topbar .logo span{font-family:var(--font-heading);font-weight:700;font-size:1.15rem;color:var(--heading)}
.topbar nav{margin-left:auto;display:flex;gap:18px;align-items:center}
.topbar nav a{text-decoration:none;color:var(--ink);font-size:.95rem}
.topbar nav a:hover{color:var(--brand)}
.stripe{display:flex;height:3px}
.stripe span{flex:1}
.search{position:relative}
.search input{width:220px;padding:8px 12px;border:1px solid var(--line);border-radius:var(--radius);background:var(--surface);color:var(--ink);font:inherit;font-size:.95rem}
.search-results{position:absolute;right:0;top:44px;width:min(420px,90vw);background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);box-shadow:0 12px 32px rgba(0,0,0,.14);max-height:60vh;overflow:auto;display:none}
.search-results.open{display:block}
.search-results a{display:block;padding:12px 16px;text-decoration:none;color:var(--ink);border-bottom:1px solid var(--line)}
.search-results a:last-child{border-bottom:0}
.search-results a:hover{background:var(--tint)}
.search-results a strong{display:block;color:var(--heading)}
.search-results a small{color:var(--muted)}
.search-results .none{padding:12px 16px;color:var(--muted)}

/* Hero */
.hero{padding:104px 0 120px;text-align:center}
.hero .lead{font-size:1.2rem;max-width:640px;margin:0 auto 30px}
.meta{display:flex;flex-wrap:wrap;justify-content:center;gap:10px}
.pill{display:inline-block;padding:5px 14px;border-radius:999px;font-size:.85rem;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.18);color:var(--on-dark)}

/* Who to ask: card lifted over the hero edge */
.help-wrap{position:relative;z-index:2;margin-top:-52px}
.card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:24px 28px}
.help{display:flex;gap:20px;align-items:center;flex-wrap:wrap;box-shadow:0 16px 40px rgba(0,0,0,.10);border-top:4px solid var(--accent)}
.help .who{flex:1;min-width:220px}
.help .eyebrow{margin-bottom:6px}
.btn{display:inline-block;padding:11px 20px;border-radius:var(--radius);background:var(--brand);color:var(--on-brand);text-decoration:none;border:0;cursor:pointer;font:inherit;font-weight:600}
.btn:hover{filter:brightness(1.08)}
.dark .btn{background:var(--on-dark);color:var(--dark)}

section.block{padding:72px 0}
section.block.tint{background:var(--tint)}
.facts{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin:0}
.facts div{background:var(--surface);border:1px solid var(--line);border-top:3px solid var(--acc,var(--accent));border-radius:var(--radius);padding:14px 16px}
.facts dt{font-size:.74rem;text-transform:uppercase;letter-spacing:var(--eyebrow-spacing);color:var(--muted);margin-bottom:4px}
.facts dd{margin:0;font-weight:600;color:var(--heading);line-height:1.45}

/* Contents */
.toc-group{margin-top:34px}
.group-title{display:flex;align-items:center;gap:10px;margin:0 0 12px;font-size:.8rem;font-weight:700;text-transform:uppercase;letter-spacing:var(--eyebrow-spacing);color:var(--heading)}
.group-title .dot{width:22px;height:6px;border-radius:3px;background:var(--acc)}
.toc{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
.toc a{position:relative;display:flex;flex-direction:column;gap:4px;padding:18px 18px 14px;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);text-decoration:none;color:var(--ink);overflow:hidden;transition:border-color .15s,transform .15s,box-shadow .15s}
.toc a::before{content:"";position:absolute;left:0;top:0;bottom:0;width:4px;background:var(--acc)}
.toc a:hover{border-color:var(--acc);transform:translateY(-2px);box-shadow:0 10px 24px rgba(0,0,0,.08)}
.toc .num{font-family:var(--font-heading);color:var(--brand);font-weight:var(--heading-weight);font-size:.95rem}
.toc strong{color:var(--heading);font-size:1.03rem;line-height:1.35}
.toc small{color:var(--muted);line-height:1.45;font-size:.85rem}
.toc .status{margin-top:auto;padding-top:8px;font-size:.78rem;color:var(--muted)}
.toc .status.done{color:var(--good);font-weight:600}

/* Chapter */
.chapter{padding:84px 0;position:relative}
.chapter.alt{background:var(--tint)}
.chapter.alt .facts div,.chapter.alt details,.chapter.alt .quiz{background:var(--surface)}
.chapter.alt ul.you li{border-color:var(--tint-line)}
.chapter-head{display:flex;gap:20px;align-items:flex-start;margin-bottom:8px}
.chapter-head .num{flex:none;display:flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:var(--radius);background:var(--dark);color:var(--on-dark);font-family:var(--font-heading);font-size:1.6rem;font-weight:var(--heading-weight);line-height:1;box-shadow:inset 0 -4px 0 var(--acc)}
.chip{display:inline-block;font-size:.72rem;font-weight:700;letter-spacing:var(--eyebrow-spacing);text-transform:uppercase;color:var(--muted);margin:2px 0 6px}
.chip::before{content:"";display:inline-block;width:14px;height:4px;border-radius:2px;background:var(--acc);margin-right:8px;vertical-align:middle}
.chapter-head h2{margin:0}
.in-short{font-size:1.15rem;color:var(--ink);border-left:4px solid var(--acc);padding:6px 0 6px 20px;margin:28px 0 36px}
.chapter h3{margin-top:38px}
ul.you{padding:0;list-style:none;margin:0}
ul.you li{position:relative;padding:10px 0 10px 36px;border-bottom:1px solid var(--line)}
ul.you li::before{content:"";position:absolute;left:0;top:13px;width:22px;height:22px;border-radius:50%;background:var(--acc);opacity:.35}
ul.you li::after{content:"";position:absolute;left:7px;top:19px;width:9px;height:5px;border-left:2px solid var(--dark);border-bottom:2px solid var(--dark);transform:rotate(-45deg)}
details{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);margin:10px 0}
details[open]{border-color:var(--acc)}
details summary{cursor:pointer;padding:14px 18px;font-weight:600;color:var(--heading);list-style:none;display:flex;justify-content:space-between;gap:12px}
details summary::-webkit-details-marker{display:none}
details summary::after{content:"+";font-size:1.3rem;line-height:1;color:var(--brand)}
details[open] summary::after{content:"−"}
details .inner{padding:0 18px 16px}
details.fulltext .inner{max-height:70vh;overflow:auto;font-size:.95rem}
details.fulltext h4{font-size:1rem;margin:20px 0 6px}
.help-line{margin-top:24px;color:var(--muted)}
.back{display:inline-block;margin-top:28px;font-size:.9rem;color:var(--muted)}

/* Quiz */
.quiz{margin-top:44px;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:28px;position:relative;overflow:hidden}
.quiz::before{content:"";position:absolute;left:0;right:0;top:0;height:4px;background:var(--acc,var(--accent))}
.quiz .q-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;color:var(--muted);font-size:.8rem;font-weight:700;letter-spacing:var(--eyebrow-spacing);text-transform:uppercase}
.quiz .scenario{font-size:1.08rem;font-weight:600;color:var(--heading);margin:8px 0 18px}
.quiz .opts{display:grid;gap:10px}
.quiz .opt{text-align:left;padding:13px 16px;border:1.5px solid var(--line);border-radius:var(--radius);background:var(--bg);color:var(--ink);font:inherit;cursor:pointer}
.quiz .opt:hover:not([disabled]){border-color:var(--brand)}
.quiz .opt.right{border-color:var(--good);background:color-mix(in srgb,var(--good) 10%,var(--bg))}
.quiz .opt.wrong{border-color:var(--bad);background:color-mix(in srgb,var(--bad) 8%,var(--bg))}
.quiz .why{margin-top:16px;padding:14px 16px;border-radius:var(--radius);background:var(--tint);border:1px solid var(--line);color:var(--ink)}
.quiz .why strong{display:block;margin-bottom:4px;color:var(--heading)}
.quiz .why a{color:var(--link)}
.quiz .actions{margin-top:18px;display:flex;gap:10px;flex-wrap:wrap}
.quiz .result{text-align:center;padding:12px 0}
.quiz .result .score{font-family:var(--font-heading);font-size:2.8rem;color:var(--brand);font-weight:var(--heading-weight)}
.final{padding:96px 0}
.final .quiz{--acc:var(--accent);color:var(--ink)}
.final .quiz .btn{background:var(--brand);color:var(--on-brand)}

footer{padding:56px 0 64px;font-size:.9rem;text-align:center}
footer p{color:var(--on-dark-muted)}
.foot-logo{margin-bottom:18px}
.foot-logo img{height:30px;width:auto}
.name-on-dark{font-family:var(--font-heading);font-size:1.3rem;color:var(--on-dark)}

@media (max-width:900px){.toc{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media (max-width:720px){
  body{font-size:16px}
  .toc{grid-template-columns:minmax(0,1fr)}
  .topbar nav a.hide-sm{display:none}
  .search input{width:150px}
  .hero{padding:64px 0 96px}
  .chapter{padding:60px 0}
  .chapter-head .num{width:52px;height:52px;font-size:1.3rem}
}
@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}.toc a{transition:none}}
@media print{
  .topbar,.quiz,.search,.back,.pattern,.final{display:none}
  .dark{background:none;color:var(--ink)}
  .dark h1,.dark h2{color:var(--heading)}
  details{border:0}
  details .inner{max-height:none;overflow:visible}
  .chapter{page-break-before:always;background:none}
}

/* Sidebar navigation: fixed in the left margin on wide screens, a drawer on smaller ones */
.sidenav{position:fixed;z-index:15;top:92px;right:max(16px,calc((100vw - 780px)/2 - 262px));width:232px;max-height:calc(100vh - 112px);overflow:auto;padding:14px 14px 16px;background:var(--bg);border:1px solid var(--line);border-radius:var(--radius);box-shadow:0 10px 30px rgba(0,0,0,.08);
  opacity:0;visibility:hidden;transform:translateX(8px);transition:opacity .2s,transform .2s,visibility .2s;scrollbar-width:none}
.sidenav::-webkit-scrollbar{display:none}
body.nav-on .sidenav{opacity:1;visibility:visible;transform:none}
body.nav-on.nav-collapsed .sidenav{opacity:0;visibility:hidden;transform:translateX(8px)}
body.nav-on.nav-collapsed .nav-toggle{display:block}
.side-head{display:flex;align-items:center;justify-content:space-between;margin:0 0 8px}
.side-title{font-size:.72rem;font-weight:700;letter-spacing:var(--eyebrow-spacing);text-transform:uppercase;color:var(--muted);margin:0}
.nav-close{position:relative;width:30px;height:30px;border:1px solid var(--line);border-radius:50%;background:var(--surface);cursor:pointer;flex:none}
.nav-close::before,.nav-close::after{content:"";position:absolute;left:50%;top:50%;width:12px;height:1.5px;background:var(--heading);transform:translate(-50%,-50%) rotate(45deg)}
.nav-close::after{transform:translate(-50%,-50%) rotate(-45deg)}
.nav-close:hover{border-color:var(--heading)}
.side-group{margin-bottom:6px}
.side-group:not(.open) ul{display:none}
.side-group.open{margin-bottom:14px}
.side-group-title{display:flex;align-items:flex-start;gap:8px;width:100%;padding:6px 0;border:0;background:none;cursor:pointer;text-align:left;font:inherit;font-size:.72rem;font-weight:700;letter-spacing:var(--eyebrow-spacing);text-transform:uppercase;color:var(--muted);line-height:1.5}
.side-group-title .dot{flex:none;margin-top:.5em}
.side-group-title .gname{flex:1}
.side-group-title .chev{flex:none;width:7px;height:7px;margin:.35em 2px 0 0;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(45deg);transition:transform .15s}
.side-group.open .side-group-title .chev{transform:rotate(-135deg);margin-top:.6em}
.side-group-title:hover,.side-group.open .side-group-title{color:var(--heading)}
.side-group-title .count{font-weight:600;letter-spacing:0;opacity:.6}
.side-group-title .dot{width:14px;height:4px;border-radius:2px;background:var(--acc)}
.sidenav ul{list-style:none;margin:2px 0 0;padding:0;border-left:1px solid var(--line)}
.sidenav li a{display:flex;gap:8px;padding:4px 10px;margin-left:-1px;border-left:2px solid transparent;font-size:.84rem;line-height:1.35;color:var(--muted);text-decoration:none}
.sidenav li a span{flex:none;width:20px;font-variant-numeric:tabular-nums;opacity:.7}
.sidenav li a:hover{color:var(--heading)}
.sidenav li a.active{color:var(--heading);font-weight:600;border-left-color:var(--acc);background:linear-gradient(to right,color-mix(in srgb,var(--acc) 14%,transparent),transparent)}
.side-final{display:inline-block;margin-top:4px;padding:6px 12px;border-radius:var(--radius);background:var(--dark);color:var(--on-dark);font-size:.82rem;font-weight:600;text-decoration:none}
.side-final.active{box-shadow:inset 0 -3px 0 var(--accent)}
.nav-toggle{display:none;position:fixed;z-index:25;right:16px;bottom:16px;padding:11px 18px;border:0;border-radius:999px;background:var(--dark);color:var(--on-dark);font:inherit;font-weight:600;font-size:.9rem;box-shadow:0 8px 24px rgba(0,0,0,.2);cursor:pointer}
.nav-scrim{display:none}
@media (max-width:1319px){
  .sidenav{left:auto;right:0;top:0;bottom:0;max-height:none;width:min(300px,84vw);padding:24px 18px;background:var(--bg);box-shadow:-8px 0 32px rgba(0,0,0,.18);z-index:30;transform:translateX(100%);opacity:1;visibility:hidden}
  body.nav-on .sidenav{transform:translateX(100%);visibility:hidden}
  body.nav-open .sidenav,body.nav-on.nav-open .sidenav{transform:none;visibility:visible}
  body.nav-on .nav-toggle{display:block}
  body.nav-open .nav-scrim{display:block;position:fixed;inset:0;z-index:28;background:rgba(0,0,0,.35)}
}
@media print{.sidenav,.nav-toggle,.nav-scrim{display:none}}

/* Progress and completion */
.progress-top{height:3px;background:var(--line)}
.progress-top .fill,.comp-progress .fill,.side-progress .fill{display:block;height:100%;width:0;background:var(--accent);transition:width .4s}
.comp-progress{margin:6px 0 22px}
.comp-progress .bar,.side-progress .bar{height:8px;border-radius:999px;background:var(--surface);border:1px solid var(--line);overflow:hidden}
.comp-progress .fill{background:var(--brand)}
.comp-progress .count{margin:8px 0 0;font-weight:600;color:var(--heading)}
.side-progress{margin-top:16px}
.side-progress .bar{height:6px}
.side-progress p{margin:6px 0 0;font-size:.78rem;color:var(--muted)}
.side-links{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}
.side-links .side-final{margin-top:0}
.side-complete{background:var(--brand);color:var(--on-brand)}
.complete .comp-open{display:none}
body.is-complete .complete .comp-open{display:block}
body.is-complete .complete .comp-locked{display:none}
.comp-locked{color:var(--muted)}
.comp-form{display:grid;gap:14px;margin-top:18px;background:var(--surface);border:1px solid var(--line);border-top:4px solid var(--accent);border-radius:var(--radius);padding:24px}
.comp-form label{display:grid;gap:6px;font-weight:600;color:var(--heading);font-size:.92rem}
.comp-form input{padding:11px 12px;border:1px solid var(--line);border-radius:var(--radius);font:inherit;font-weight:400;background:var(--bg);color:var(--ink)}
.comp-form .hp{position:absolute;left:-9999px}
.comp-actions{display:flex;gap:10px;flex-wrap:wrap}
.btn.ghost{background:transparent;color:var(--brand);border:1.5px solid var(--brand)}
.btn.pulse{box-shadow:0 0 0 4px color-mix(in srgb,var(--accent) 45%,transparent)}
.comp-status{margin:0;font-weight:600}
.comp-status.good{color:var(--good)}
.comp-status.bad{color:var(--bad)}
.toast{position:fixed;z-index:40;left:50%;bottom:24px;width:min(520px,calc(100vw - 32px));display:flex;align-items:center;gap:14px;
  padding:16px 48px 16px 20px;background:var(--dark);color:var(--on-dark);border-radius:var(--radius);box-shadow:0 18px 44px rgba(0,0,0,.28);border-top:4px solid var(--accent);transform:translate(-50%,calc(100% + 48px));visibility:hidden;transition:transform .35s,visibility .35s}
.toast.show{transform:translate(-50%,0);visibility:visible}
.toast p{margin:0;flex:1;font-weight:600;line-height:1.4}
.toast .btn{background:var(--on-dark);color:var(--dark);white-space:nowrap}
.toast-close{position:absolute;top:8px;right:8px;width:26px;height:26px;border:0;background:none;cursor:pointer}
.toast-close::before,.toast-close::after{content:"";position:absolute;left:50%;top:50%;width:12px;height:1.5px;background:var(--on-dark);transform:translate(-50%,-50%) rotate(45deg)}
.toast-close::after{transform:translate(-50%,-50%) rotate(-45deg)}
@media (max-width:560px){.toast{flex-direction:column;align-items:flex-start}}
@media print{.toast,.progress-top,.complete{display:none}}
~~~~

### assets/site.js

~~~~
/* Document site behaviour: quizzes, final round, search, progress. Data comes from window.HB. */
(function () {
  var HB = window.HB;
  var KEY = 'hb:' + HB.slug;
  var store = {};
  try { store = JSON.parse(localStorage.getItem(KEY) || '{}'); } catch (e) { store = {}; }
  function save() { try { localStorage.setItem(KEY, JSON.stringify(store)); } catch (e) {} }

  function shuffle(a) { a = a.slice(); for (var i = a.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var t = a[i]; a[i] = a[j]; a[j] = t; } return a; }
  function el(tag, cls, text) { var e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }

  function updateStatus(id) {
    if (window.HBProgress) window.HBProgress();
    var s = document.querySelector('[data-status="' + id + '"]');
    if (!s) return;
    var r = store[id];
    if (r) { s.textContent = 'Quiz: best ' + r.best + '/' + r.of; s.classList.add('done'); }
    else { s.textContent = 'Quiz not taken yet'; s.classList.remove('done'); }
  }

  /* Generic quiz runner. items: [{scenario, options, answer, why, reveal?}] */
  function runQuiz(box, id, pool, perRound) {
    var round, idx, score;
    function start() {
      round = shuffle(pool).slice(0, Math.min(perRound, pool.length));
      idx = 0; score = 0; show();
    }
    function show() {
      box.innerHTML = '';
      if (idx >= round.length) return finish();
      var item = round[idx];
      var top = el('div', 'q-top');
      top.appendChild(el('span', null, box.getAttribute('data-label') || 'Test yourself'));
      top.appendChild(el('span', null, 'Question ' + (idx + 1) + ' of ' + round.length));
      box.appendChild(top);
      box.appendChild(el('p', 'scenario', item.scenario));
      var opts = el('div', 'opts');
      var order = shuffle(item.options.map(function (o, i) { return { text: o, i: i }; }));
      order.forEach(function (o) {
        var b = el('button', 'opt', o.text);
        b.type = 'button';
        b.addEventListener('click', function () {
          var right = o.i === item.answer;
          if (right) score++;
          Array.prototype.forEach.call(opts.children, function (c, k) {
            c.disabled = true;
            if (order[k].i === item.answer) c.classList.add('right');
          });
          if (!right) b.classList.add('wrong');
          var why = el('div', 'why');
          why.appendChild(el('strong', null, right ? 'Correct.' : 'Not quite.'));
          why.appendChild(el('span', null, item.why || ''));
          if (item.reveal) { why.appendChild(el('div', null, '')); why.lastChild.innerHTML = item.reveal; }
          box.appendChild(why);
          var act = el('div', 'actions');
          var next = el('button', 'btn', idx + 1 < round.length ? 'Next question' : 'See your score');
          next.type = 'button';
          next.addEventListener('click', function () { idx++; show(); box.scrollIntoView({ block: 'nearest' }); });
          act.appendChild(next);
          box.appendChild(act);
          next.focus();
        });
        opts.appendChild(b);
      });
      box.appendChild(opts);
    }
    function finish() {
      var prev = store[id];
      if (!prev || score > prev.best) { store[id] = { best: score, of: round.length }; save(); }
      updateStatus(id);
      var r = el('div', 'result');
      r.appendChild(el('div', 'score', score + '/' + round.length));
      r.appendChild(el('p', null, score === round.length ? 'Full marks.' : 'Try again for a fresh set of questions.'));
      var act = el('div', 'actions');
      act.style.justifyContent = 'center';
      var again = el('button', 'btn', 'New set of questions');
      again.type = 'button';
      again.addEventListener('click', start);
      act.appendChild(again);
      r.appendChild(act);
      box.appendChild(r);
    }
    start();
  }

  HB.chapters.forEach(function (c) {
    updateStatus(c.id);
    var box = document.getElementById('quiz-' + c.id);
    if (box && c.quiz && c.quiz.length) runQuiz(box, c.id, c.quiz, HB.perRound);
  });

  /* Final round: one question per chapter, reveals which policy it came from */
  var finalBox = document.getElementById('quiz-final');
  if (finalBox) {
    var pool = [];
    HB.chapters.forEach(function (c) {
      if (!c.quiz || !c.quiz.length) return;
      var q = c.quiz[Math.floor(Math.random() * c.quiz.length)];
      var others = shuffle(HB.chapters.filter(function (o) { return o.id !== c.id; })).slice(0, 3);
      var options = [c.title].concat(others.map(function (o) { return o.title; }));
      pool.push({ scenario: q.scenario, options: options, answer: 0,
        why: 'This is covered in "' + c.title + '".',
        reveal: '<a href="#' + c.id + '">Go to ' + c.number + ' ' + c.title.replace(/</g, '&lt;') + '</a>' });
    });
    if (pool.length >= 2) runQuiz(finalBox, '_final', pool, Math.min(10, pool.length));
    else finalBox.closest('section').style.display = 'none';
  }

  /* Search */
  var input = document.getElementById('search');
  var results = document.getElementById('search-results');
  if (input) {
    var index = HB.chapters.map(function (c) {
      var node = document.getElementById(c.id);
      return { c: c, text: (node ? node.textContent : c.title).toLowerCase() };
    });
    input.addEventListener('input', function () {
      var q = input.value.trim().toLowerCase();
      results.innerHTML = '';
      if (q.length < 2) { results.classList.remove('open'); return; }
      var hits = index.filter(function (x) { return x.text.indexOf(q) !== -1; });
      if (!hits.length) results.appendChild(el('div', 'none', 'Nothing found. Try another word.'));
      hits.slice(0, 12).forEach(function (h) {
        var a = el('a'); a.href = '#' + h.c.id;
        a.appendChild(el('strong', null, h.c.number + '  ' + h.c.title));
        a.appendChild(el('small', null, h.c.summary));
        a.addEventListener('click', function () { results.classList.remove('open'); input.value = ''; });
        results.appendChild(a);
      });
      results.classList.add('open');
    });
    document.addEventListener('click', function (e) { if (!e.target.closest('.search')) results.classList.remove('open'); });
    input.addEventListener('keydown', function (e) { if (e.key === 'Escape') { results.classList.remove('open'); input.blur(); } });
  }

  /* Open every fold-out when printing */
  window.addEventListener('beforeprint', function () { document.querySelectorAll('details').forEach(function (d) { d.setAttribute('open', ''); }); });
})();

/* Sidebar navigation: show after the hero, highlight the section in view, drawer on small screens */
(function () {
  var nav = document.getElementById('sidenav');
  if (!nav) return;
  var body = document.body, toggle = document.getElementById('nav-toggle'), scrim = document.getElementById('nav-scrim');
  var links = {};
  nav.querySelectorAll('[data-nav]').forEach(function (a) { links[a.getAttribute('data-nav')] = a; });
  var first = document.querySelector('.chapter');
  function onScroll() {
    var show = first && first.getBoundingClientRect().top < window.innerHeight * 0.5;
    body.classList.toggle('nav-on', !!show);
  }
  window.addEventListener('scroll', onScroll, { passive: true }); onScroll();
  var current = null;
  var io = new IntersectionObserver(function (entries) {
    entries.forEach(function (e) {
      if (!e.isIntersecting) return;
      var id = e.target.id;
      if (current === id) return;
      if (current && links[current]) links[current].classList.remove('active');
      current = id;
      var a = links[id];
      if (a) {
        a.classList.add('active');
        var grp = a.closest('.side-group');
        nav.querySelectorAll('.side-group.open').forEach(function (x) { if (x !== grp) x.classList.remove('open'); });
        if (grp) { grp.classList.add('open'); grp.querySelector('.side-group-title') && grp.querySelector('.side-group-title').setAttribute('aria-expanded', 'true'); }
        var r = a.getBoundingClientRect(), nr = nav.getBoundingClientRect();
        if (r.top < nr.top + 40 || r.bottom > nr.bottom - 40) nav.scrollTop += r.top - nr.top - nr.height / 3;
      }
    });
  }, { rootMargin: '-35% 0px -60% 0px' });
  Object.keys(links).forEach(function (id) { var s = document.getElementById(id); if (s) io.observe(s); });
  var closeBtn = document.getElementById('nav-close');
  var drawerMode = window.matchMedia('(max-width:1319px)');
  function setOpen(o) { body.classList.toggle('nav-open', o); toggle.setAttribute('aria-expanded', o ? 'true' : 'false'); }
  toggle.addEventListener('click', function () {
    if (drawerMode.matches) setOpen(!body.classList.contains('nav-open'));
    else body.classList.remove('nav-collapsed');
  });
  closeBtn.addEventListener('click', function () {
    if (drawerMode.matches) setOpen(false);
    else body.classList.add('nav-collapsed');
  });
  scrim.addEventListener('click', function () { setOpen(false); });
  // group titles open and close their list; only chapter links scroll
  nav.querySelectorAll('.side-group-title').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var grp = btn.closest('.side-group'), willOpen = !grp.classList.contains('open');
      nav.querySelectorAll('.side-group.open').forEach(function (x) { x.classList.remove('open'); x.querySelector('.side-group-title').setAttribute('aria-expanded', 'false'); });
      if (willOpen) { grp.classList.add('open'); btn.setAttribute('aria-expanded', 'true'); }
    });
  });
  nav.addEventListener('click', function (e) { if (e.target.closest('a[data-nav]')) setOpen(false); });
  document.addEventListener('keydown', function (e) { if (e.key === 'Escape') setOpen(false); });
})();

/* Progress, completion notification, completion form (Netlify Forms) and email link */
(function () {
  var HB = window.HB, C = HB.completion;
  if (!C) return;
  var KEY = 'hb:' + HB.slug, DONE_KEY = KEY + ':done';
  var quizChapters = HB.chapters.filter(function (c) { return c.quiz && c.quiz.length; });
  function store() { try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch (e) { return {}; } }
  function passed(r) { return r && r.of && r.best / r.of >= C.passMark - 1e-9; }
  function state() {
    var st = store(), done = quizChapters.filter(function (c) { return passed(st[c.id]); });
    return { st: st, done: done.length, total: quizChapters.length };
  }
  var toast = document.getElementById('toast');
  function showToast() {
    toast.innerHTML = '';
    var p = document.createElement('p'); p.textContent = C.toast; toast.appendChild(p);
    var a = document.createElement('a'); a.href = '#complete'; a.className = 'btn'; a.textContent = C.toastButton; toast.appendChild(a);
    var x = document.createElement('button'); x.type = 'button'; x.className = 'toast-close'; x.setAttribute('aria-label', 'Close');
    x.addEventListener('click', function () { toast.classList.remove('show'); }); toast.appendChild(x);
    a.addEventListener('click', function () { toast.classList.remove('show'); });
    toast.classList.add('show');
  }
  function render() {
    var s = state(), pct = s.total ? Math.round(100 * s.done / s.total) : 0;
    document.querySelectorAll('[data-progress-fill]').forEach(function (f) { f.style.width = pct + '%'; });
    document.querySelectorAll('[data-progress-text]').forEach(function (t) { t.textContent = C.progress.replace('{done}', s.done).replace('{total}', s.total); });
    var complete = s.done === s.total && s.total > 0;
    document.body.classList.toggle('is-complete', complete);
    var announced = false; try { announced = localStorage.getItem(DONE_KEY) === '1'; } catch (e) {}
    if (complete && !announced) { try { localStorage.setItem(DONE_KEY, '1'); } catch (e) {} showToast(); }
    return s;
  }
  window.HBProgress = function () { setTimeout(render, 0); };
  render();

  function resultText() {
    var s = state();
    var lines = quizChapters.map(function (c) { var r = s.st[c.id]; return c.number + ' ' + c.title + ': ' + (r ? r.best + '/' + r.of : 'not taken'); });
    return s.done + ' of ' + s.total + ' passed\n' + lines.join('\n');
  }
  var mail = document.getElementById('comp-mail');
  if (mail) {
    mail.addEventListener('click', function (e) {
      e.preventDefault();
      var nameEl = document.querySelector('#comp-form [name=name]') || document.getElementById('comp-name-only');
      var name = nameEl && nameEl.value ? nameEl.value : '';
      var body = 'I have completed the ' + C.docName + '.\n\nName: ' + name + '\nDate: ' + new Date().toLocaleDateString('en-GB') + '\n\n' + resultText();
      window.location.href = 'mailto:' + C.email + '?subject=' + encodeURIComponent(C.subject) + '&body=' + encodeURIComponent(body);
    });
  }
  var form = document.getElementById('comp-form'), status = document.getElementById('comp-status');
  if (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      document.getElementById('comp-result').value = resultText();
      document.getElementById('comp-date').value = new Date().toISOString();
      var btn = form.querySelector('button[type=submit]'); btn.disabled = true;
      function fail() { status.textContent = C.failed; status.className = 'comp-status bad'; btn.disabled = false; if (mail) mail.classList.add('pulse'); }
      if (location.protocol === 'file:') { fail(); return; }
      fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(new FormData(form)).toString() })
        .then(function (r) {
          if (!r.ok) throw new Error(r.status);
          status.textContent = C.sent; status.className = 'comp-status good';
          form.querySelectorAll('input,button').forEach(function (x) { x.disabled = true; });
        })
        .catch(fail);
    });
  }
})();
~~~~