# -*- coding: utf-8 -*-
"""Builds paygo-app-design.html from the FigCraft SVG exports."""
import os
import re

ROOT = ("C:/Users/User/Documents/dev/coordenadas-content-system/Brands/PayWise"
        "/05_projects/paygo-app-design")
ASSETS = os.path.join(ROOT, "assets")

FONT_STACK = "Poppins, system-ui, -apple-system, 'Segoe UI', sans-serif"


def inline(name, cls="", prefix=None):
    """Read an exported SVG, make it fluid, and namespace its internal ids."""
    p = prefix or re.sub(r"[^a-z0-9]+", "-", name.lower())
    src = open(os.path.join(ASSETS, name + ".svg"), encoding="utf-8").read()

    ids = set(re.findall(r'id="([^"]+)"', src))
    for i in sorted(ids, key=len, reverse=True):
        src = src.replace(f'id="{i}"', f'id="{p}-{i}"')
        src = src.replace(f"url(#{i})", f"url(#{p}-{i})")
        src = src.replace(f'href="#{i}"', f'href="#{p}-{i}"')

    src = src.replace('font-family="Poppins"', f'font-family="{FONT_STACK}"')

    # rewrite the whole opening tag so no attribute is duplicated
    m = re.match(r"<svg([^>]*)>", src)
    attrs = m.group(1)
    w = re.search(r'width="([\d.]+)"', attrs).group(1)
    h = re.search(r'height="([\d.]+)"', attrs).group(1)
    vb = re.search(r'viewBox="([^"]+)"', attrs)
    vb = vb.group(1) if vb else f"0 0 {w} {h}"
    tag = (f'<svg class="{cls}" viewBox="{vb}" width="{w}" height="{h}" '
           f'preserveAspectRatio="xMidYMid meet" fill="none" role="img" '
           f'aria-hidden="true" xmlns="http://www.w3.org/2000/svg">')
    return tag + src[m.end():]


# --------------------------------------------------------------------------
LOCKUPS = [("lockup-white", "Primary · on white"),
           ("lockup-blue", "On PayWise blue"),
           ("lockup-dark", "Reverse · on dark"),
           ("lockup-green", "Reverse · on green")]

SWATCHES = ["pay-blue", "go-green", "blue-mid", "blue-deep", "blue-darkest",
            "green-mid", "green-dark", "ink", "muted", "line", "surface-soft",
            "tint", "tint-line", "error", "error-soft", "on-green"]

TILES = [("spec-buttons", "Buttons"), ("spec-inputs", "Inputs & controls"),
         ("spec-surfaces", "Surfaces"), ("spec-txn-rows", "Transaction rows"),
         ("spec-bars", "Bars"), ("spec-icons", "Icon set")]

NAVS = [("nav-home", "Bottom nav / Home"),
        ("nav-transactions", "Bottom nav / Transactions"),
        ("nav-settings", "Bottom nav / Settings")]

MERCHANT = [
    ("M-0", "M-0 · Idle", "Standby screen saver",
     "Customer-facing ambient state; double-tap to wake into amount entry."),
    ("M-1", "M-1 · Home", "Instant amount entry",
     "No login. Prominent keypad, then Tap &amp; Pay, QR, or payment link."),
    ("M-2", "M-2 · QR", "Dynamic QR presentation",
     "Business-account QR for open camera scanning; supports a secondary customer screen."),
    ("M-3a", "M-3a · Outcome", "Payment successful",
     "Colour, chime and receipt actions resolve the moment hands-free."),
    ("M-3b", "M-3b · Outcome", "Payment declined",
     "Unambiguous failure state with a clear reason and fast retry."),
    ("M-4", "M-4 · History", "Transaction history",
     "Searchable log, status badges, and re-issuable receipts."),
    ("M-5", "M-5 · Settings", "Device profile &amp; settings",
     "Read-only business info, audio toggle, fee allocation and key pairing."),
    ("M-6", "M-6 · Provisioning", "Pair new device key",
     "One-time binding generated from the PayWise portal; daily use stays login-free."),
]

CUSTOMER = [
    ("C-1", "C-1 · Onboarding", "Express registration",
     "Minimal setup — enough for receipts and future one-tap checkout."),
    ("C-2", "C-2 · Checkout", "Biometric authorization",
     "Saved tokenized cards plus Touch ID — no PIN, no OTP at the terminal."),
    ("C-3", "C-3 · Receipt", "Receipt &amp; notes",
     "Automatic receipt capture plus optional text or voice notes."),
    ("C-4", "C-4 · Log", "Customer payment log",
     "Every PayGo transaction across merchants, with receipts in one place."),
]

SWATCH_META = {
    "pay-blue": ("Pay Blue", "#1B92CE"), "go-green": ("Go Green", "#69CE57"),
    "blue-mid": ("Blue Mid", "#1A6CA8"), "blue-deep": ("Blue Deep", "#195A9E"),
    "blue-darkest": ("Blue Darkest", "#04507F"),
    "green-mid": ("Green Mid", "#5FAD4A"), "green-dark": ("Green Dark", "#4E893B"),
    "ink": ("Ink", "#141414"), "muted": ("Muted", "#5B6B7C"),
    "line": ("Line", "#DDE4EC"), "surface-soft": ("Surface Soft", "#F4F6F9"),
    "tint": ("Tint", "#EEF7FC"), "tint-line": ("Tint Line", "#C9E4F2"),
    "error": ("Error", "#B3261E"), "error-soft": ("Error Soft", "#FBECEA"),
    "on-green": ("On Green", "#06283F"),
}


def screen_card(code, kicker, title, desc):
    return f"""      <article class="screen-card" id="screen-{code}">
        <div class="screen-meta">
          <span class="kicker">{kicker}</span>
          <h3>{title}</h3>
          <p>{desc}</p>
        </div>
        <div class="phone">
          <div class="phone-screen">
{inline("screen-" + code, "screen-svg", "s" + code.lower().replace('-', ''))}
          </div>
        </div>
      </article>
"""


def build():
    css = open(os.path.join(os.path.dirname(__file__), "paygo.css"),
               encoding="utf-8").read()

    # the exported lockup and tile artwork already carries its own label,
    # so no figcaption here
    lockups = "\n".join(
        f'      <figure class="lockup" aria-label="{lab}">'
        f'{inline(n, "fluid", n)}</figure>' for n, lab in LOCKUPS)

    swatches = "\n".join(
        f'      <figure class="swatch-fig">{inline("swatch-" + s, "fluid", "sw" + s)}'
        f'<figcaption><span>{SWATCH_META[s][0]}</span>'
        f'<code>{SWATCH_META[s][1]}</code></figcaption></figure>'
        for s in SWATCHES)

    tiles = "\n".join(
        f'      <figure class="tile" aria-label="{lab}">'
        f'{inline(n, "fluid", n)}</figure>' for n, lab in TILES)

    navs = "\n".join(
        f'      <figure class="nav-fig">{inline(n, "fluid", n)}'
        f'<figcaption>{lab}</figcaption></figure>' for n, lab in NAVS)

    merchant = "".join(screen_card(*s) for s in MERCHANT)
    customer = "".join(screen_card(*s) for s in CUSTOMER)

    wordmark = inline("paygo-wordmark", "brand-svg", "wm")
    wordmark_hero = inline("paygo-wordmark", "hero-wordmark", "wmh")

    html = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PayGo — App Design &amp; Screen System</title>
<meta name="description" content="Screen system and visual language for PayWise's lightweight point-of-sale app. Every screen exported from the PayGo FigCraft source file.">
<meta name="color-scheme" content="light">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&amp;display=swap" rel="stylesheet">
<style>
{css}
</style>
</head>
<body>

<header class="site-header">
  <div class="header-inner">
    <a class="brand-mark" href="#top" aria-label="PayGo">{wordmark}</a>
    <nav class="nav" aria-label="Page sections">
      <a href="#brand">Brand</a>
      <a href="#merchant">Merchant app</a>
      <a href="#customer">Customer app</a>
    </nav>
  </div>
</header>

<main id="top">
  <section class="hero">
    <div class="rings" aria-hidden="true">
      <svg class="ring-a" width="280" height="280" viewBox="0 0 280 280"><circle cx="140" cy="140" r="120" fill="none" stroke="currentColor" stroke-width="20"/></svg>
      <svg class="ring-b" width="260" height="260" viewBox="0 0 260 260"><circle cx="130" cy="130" r="110" fill="none" stroke="currentColor" stroke-width="22"/><circle cx="130" cy="130" r="70" fill="currentColor" opacity=".35"/></svg>
      <svg class="ring-c" width="180" height="180" viewBox="0 0 180 180"><circle cx="90" cy="90" r="70" fill="none" stroke="currentColor" stroke-width="18"/></svg>
    </div>
    <div class="hero-inner">
      <h1>PayGo. Pay and go your way.</h1>
      <p>Screen system and visual language for PayWise's lightweight point-of-sale app. Merchant flows built for busy counters; customer flows built for a checkout that finishes in seconds.</p>
      <span class="tagline">
        <svg class="icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M5.5 8.5a8 8 0 0 0 0 7M9.2 6a12 12 0 0 0 0 12M12.9 3.8a15.4 15.4 0 0 0 0 16.4M17.5 7v10"/></svg>
        Tap, scan, link — no login at the counter
      </span>
      <p class="source-note">Every screen and spec below is exported straight from <strong>PayGo App Design.figcraft</strong> — 390 × 844 artboards, auto-layout, Poppins, 24 variables and 26 styles.</p>
    </div>
  </section>

  <section class="section" id="brand">
    <div class="section-head">
      <div>
        <span class="eyebrow">Brand system</span>
        <h2>One wordmark, inverted.</h2>
        <p>PayGo keeps the PayWise letterforms but flips the colour split: <strong>Pay</strong> in blue, <strong>Go</strong> in green — so “Go” reads like a green light. The artwork below is the official PayGo vector.</p>
      </div>
    </div>

    <div class="lockup-grid">
{lockups}
    </div>

    <h3 class="sub-head">Colour</h3>
    <p class="sub-copy">Large blue buttons use <strong>Blue Deep #195A9E</strong> (not the lighter Pay Blue) and green buttons use dark text on <strong>Go Green</strong>, for AA contrast.</p>
    <div class="swatch-grid">
{swatches}
    </div>

    <h3 class="sub-head">Type</h3>
    <p class="sub-copy">Poppins throughout — no display faces, no decorative weights. Weights in use: Regular, Medium, SemiBold, Bold, ExtraBold.</p>
    <div class="scroll-x">
{inline("type-scale", "type-scale", "ts")}
    </div>

    <h3 class="sub-head">Components</h3>
    <p class="sub-copy">The atoms every screen is assembled from. Bottom navigation is a real component in three states — the merchant screens use instances, so editing the component updates every screen.</p>
    <div class="tile-grid">
{tiles}
    </div>
    <div class="nav-grid">
{navs}
    </div>

    <div class="note">
      <strong>Colour decision:</strong> the attached merchant spec proposed <code>#0A52C6</code> and <code>#00C853</code>. That would break brand consistency, so this design uses the PayWise palette above. The wordmark keeps its official vector colours, <code>#1E64A7</code> and <code>#5CA032</code>.
    </div>
  </section>

  <hr class="divider">

  <section class="section" id="merchant">
    <div class="section-head">
      <div>
        <span class="eyebrow">Merchant app · PayGo Merchant</span>
        <h2>The counter, unblocked.</h2>
        <p>Opens directly into amount entry. Tap &amp; Pay and QR are the primary rails; payment link sits lower as a remote-selling tool. A read-only device profile keeps staff fast and the account locked to the owner.</p>
      </div>
    </div>
    <div class="screen-grid">
{merchant}    </div>
  </section>

  <hr class="divider">

  <section class="section" id="customer">
    <div class="section-head">
      <div>
        <span class="eyebrow">Customer app · PayGo Customer</span>
        <h2>Pay in seconds. Keep the receipt.</h2>
        <p>Card details are tokenised at the first checkout; after that, it's saved cards plus biometric confirmation. Receipts build a personal expense log automatically.</p>
      </div>
    </div>
    <div class="screen-grid">
{customer}    </div>
  </section>
</main>

<footer>
  <div class="footer-inner">
    <div class="footer-brand">{wordmark_hero}</div>
    <p><strong>PayGo</strong> · Pay and go your way.<br>Design exploration for the PayWise ecosystem. PayGo is a product of PayWise Limited, licensed by the Central Bank of Trinidad and Tobago.</p>
    <p>© 2026 PayWise Limited</p>
  </div>
</footer>

</body>
</html>
"""
    out = os.path.join(ROOT, "paygo-app-design.html")
    open(out, "w", encoding="utf-8").write(html)
    print(f"{out}  —  {len(html) / 1024:.0f} KB")


if __name__ == "__main__":
    build()


def build_artifact():
    """Same page, shaped for the Artifact host (no doctype/html/head/body)."""
    src = open(os.path.join(ROOT, "paygo-app-design.html"), encoding="utf-8").read()
    head = src.split("<body>", 1)[0]
    body = src.split("<body>", 1)[1].rsplit("</body>", 1)[0]
    title = re.search(r"<title>(.*?)</title>", head, re.S).group(1)
    link = re.search(r'<link href="https://fonts\.googleapis[^>]*>', head).group(0)
    css = re.search(r"<style>(.*?)</style>", head, re.S).group(1)
    css = css.replace(":root{", ":root{\n  color-scheme:light;", 1)
    out = (f"<title>{title}</title>\n{link}\n<style>\n{css}\n</style>\n{body}")
    p = os.path.join(ROOT, "_build", "paygo-artifact.html")
    open(p, "w", encoding="utf-8").write(out)
    print(p, f"— {len(out)/1024:.0f} KB")
    return p
