# -*- coding: utf-8 -*-
"""Generates the full PayGo FigCraft build script."""
import sys
import build_screens as S
from paygo_ui import *

PAGE_BG = "#EDF1F6"

PALETTE = [
    ("Pay Blue", BLUE, "Wordmark, links, accents"),
    ("Go Green", GREEN, "Wordmark, success, primary CTA"),
    ("Blue Mid", BLUE_MID, "Gradient headers"),
    ("Blue Deep", BLUE_DEEP, "Primary buttons, active nav"),
    ("Blue Darkest", BLUE_DARK, "Gradients, links on light"),
    ("Green Mid", GREEN_MID, "Green button border"),
    ("Green Dark", GREEN_DEEP, "Success banners, success text"),
    ("Ink", INK, "Body text, QR modules"),
    ("Muted", MUTED, "Secondary text, inactive nav"),
    ("Line", LINE, "Borders, dividers"),
    ("Surface Soft", BG, "App background"),
    ("Tint", TINT, "Selected rows, info surfaces"),
    ("Tint Line", TINT_LINE, "Tinted surface borders"),
    ("Error", DANGER, "Declined state only"),
    ("Error Soft", DANGER_SOFT, "Declined badge background"),
    ("On Green", ON_GREEN, "Text on Go Green"),
]

TYPE_SCALE = [
    ("Amount / XL", "$150.00 TTD", 31, "ExtraBold", "-2% tracking"),
    ("Amount / L", "$150.00 TTD", 24, "ExtraBold", "-2% tracking"),
    ("Title / Screen", "Transaction History", 19, "SemiBold", "Headers, banners"),
    ("Title / Header", "PayGo Checkout", 16, "SemiBold", "App bar titles"),
    ("Button", "Generate QR Code", 14.5, "Bold", "All CTAs"),
    ("Body / Strong", "Global Trade Co. (GTC)", 14, "SemiBold", "Emphasis in cards"),
    ("Body", "Received from VISA ···· 4242", 13.5, "Regular", "Default copy"),
    ("Caption", "Tree City Mall · Branch #3", 11.5, "Regular", "Subtitles"),
    ("Overline", "Merchant profile", 11, "Bold", "12% tracking, uppercase"),
    ("Nav", "Transactions", 10.5, "ExtraBold", "Bottom nav labels"),
]


# --------------------------------------------------------------------------
def section(parent, title, sub=None):
    h = col(parent, "§ " + title, gap=4, fill_w=True)
    txt(h, title, 30, "ExtraBold", INK, tracking="-2%", name="Heading")
    if sub:
        t = txt(h, sub, 15, "Regular", MUTED, line_height="150%", name="Sub")
        nset(t, sizingH="fill", textAutoResize="height")
    return h


def logo_card(parent, label, bg, mono=None, border=None):
    c = col(parent, "Lockup · " + label, gap=16, padding=[34, 26, 28, 26],
            fill=bg, radius=R_CARD, width=304, cross="center", main="center",
            stroke=border)
    nset(c, sizingH="fixed", minHeight=184)
    logo(c, 176, mono=mono)
    fg = PAPER if mono == PAPER else MUTED
    txt(c, label, 10.5, "Bold", fg, tracking="10%", case="upper", name="Caption")
    return c


def slug(name):
    return name.lower().replace(" ", "-").replace("/", "-")


def swatch(parent, name, hexv, usage):
    c = col(parent, "Swatch · " + name, gap=0, width=212, radius=12,
            fill=PAPER, stroke=LINE, clip=True)
    nset(c, sizingH="fixed")
    chip = create("frame", parent=c, name="Chip", width=212, height=86,
                  props={"fill": hexv, "sizingH": "fill", "layout": None})
    meta_box = col(c, "Meta", gap=2, padding=[11, 13, 13, 13], fill_w=True)
    txt(meta_box, name, 12.5, "Bold", INK, name="Name")
    txt(meta_box, hexv.upper(), 11.5, "Medium", MUTED, name="Hex")
    t = txt(meta_box, usage, 10.5, "Regular", MUTED, name="Usage")
    nset(t, sizingH="fill", textAutoResize="height")
    cmd("variable.create", collection="PayGo", name="colour/" + slug(name),
        type="color", value=hexv, description=usage)
    cmd("variable.bind", ids=[chip], field="fill",
        variable="colour/" + slug(name))
    cmd("style.create", type="paint", name="Colour/" + name, **{"from": chip},
        description=usage)
    return c


def type_row(parent, label, sample, size, style, note):
    r = row(parent, "Type · " + label, gap=24, padding=[14, 0, 14, 0],
            fill_w=True, cross="center", stroke=LINE,
            stroke_sides=[False, False, True, False])
    lab = col(r, "Spec", gap=2, width=210)
    nset(lab, sizingH="fixed")
    txt(lab, label, 12.5, "Bold", INK, name="Name")
    txt(lab, f"Poppins {style} · {size}px", 11, "Regular", MUTED, name="Spec")
    t = txt(r, sample, size, style, INK, name="Sample")
    nset(t, sizingH="fill", textAutoResize="height")
    n = txt(r, note, 11, "Regular", MUTED, width=170, name="Note")
    nset(n, sizingH="fixed", textAutoResize="height")
    cmd("style.create", type="text", name="Type/" + label, **{"from": t},
        description=f"Poppins {style} {size}px — {note}")
    return r


def spec_tile(parent, title, child_builder, width=300):
    t = col(parent, "Spec · " + title, gap=14, padding=20, fill=PAPER,
            radius=R_CARD, stroke=LINE, width=width)
    nset(t, sizingH="fixed")
    txt(t, title, 11, "Bold", MUTED, tracking="10%", case="upper", name="Label")
    inner = col(t, "Preview", gap=10, fill_w=True)
    child_builder(inner)
    return t


# --------------------------------------------------------------------------
def foundations():
    cmd("variable.createCollection", name="PayGo")
    cmd("page.rename", id=1, name="01 · Foundations")
    cmd("page.setBackground", id=1, color=PAGE_BG)

    root = col(None, "PayGo — Design foundations", gap=56, padding=[72, 72, 88, 72],
               fill=PAGE_BG, width=1480, x=0, y=0)
    nset(root, sizingH="fixed")

    # ---- masthead
    head = col(root, "Masthead", gap=18, fill_w=True)
    logo(head, 260)
    t = txt(head, "PayGo — app design system", 44, "ExtraBold", INK,
            tracking="-3%", name="Title")
    nset(t, sizingH="fill")
    t = txt(head, "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. "
                  "Artboards are 390 × 844 (iPhone 14 / standard Android), "
                  "auto-layout throughout.", 16, "Regular", MUTED,
            line_height="160%", name="Intro")
    nset(t, sizingH="fill", textAutoResize="height", maxWidth=900)

    # ---- logo lockups
    sec = col(root, "Logo", gap=24, fill_w=True)
    section(sec, "One wordmark, inverted.",
            "PayGo keeps the PayWise letterforms and flips the colour split — "
            "Pay in blue, Go in green, so “Go” reads like a green light. "
            "Artwork is the official PayGo vector (#1E64A7 / #5CA032); the UI "
            "palette below is the PayWise app palette.")
    r = row(sec, "Lockups", gap=22, fill_w=True, wrap=True)
    logo_card(r, "Primary · on white", PAPER, border=LINE)
    logo_card(r, "On PayWise blue", BLUE_DARK, mono=PAPER)
    logo_card(r, "Reverse · on dark", INK, mono=PAPER)
    logo_card(r, "Reverse · on green", GREEN, mono=PAPER)

    # ---- colour
    sec = col(root, "Colour", gap=24, fill_w=True)
    section(sec, "Colour.",
            "Large blue buttons use Blue Deep #195A9E (not the lighter Pay Blue) "
            "and green buttons use dark text on Go Green for AA contrast.")
    g = row(sec, "Swatches", gap=16, fill_w=True, wrap=True)
    for name, hexv, usage in PALETTE:
        swatch(g, name, hexv, usage)
    for vname, val, desc in (("radius/card", R_CARD, "Cards, tinted surfaces"),
                             ("radius/button", R_BTN, "Buttons, keypad keys"),
                             ("radius/input", R_INPUT, "Text inputs"),
                             ("radius/pill", 999, "Pills, badges, toggles"),
                             ("space/screen-x", PAD, "Screen side padding"),
                             ("space/stack", 14, "Default vertical rhythm"),
                             ("size/screen-w", SCREEN_W, "Artboard width"),
                             ("size/screen-h", SCREEN_H, "Artboard height")):
        cmd("variable.create", collection="PayGo", name=vname, type="number",
            value=val, description=desc)

    # ---- type
    sec = col(root, "Type", gap=20, fill_w=True)
    section(sec, "Type.",
            "Poppins throughout — no display faces, no decorative weights. "
            "Weights in use: Regular, Medium, SemiBold, Bold, ExtraBold.")
    tbl = col(sec, "Scale", gap=0, padding=[8, 24, 16, 24], fill=PAPER,
              radius=R_CARD, stroke=LINE, fill_w=True)
    for args in TYPE_SCALE:
        type_row(tbl, *args)

    # ---- components
    sec = col(root, "Components", gap=24, fill_w=True)
    section(sec, "Components.",
            "The atoms every screen is assembled from. Bottom nav is a real "
            "component — the three states below are its main components, "
            "instanced into the merchant screens.")
    grid = row(sec, "Component sheet", gap=22, fill_w=True, wrap=True)

    def _buttons(p):
        button(p, "Tap & Pay", "green", "nfc")
        button(p, "Generate QR Code", "blue", "qr")
        button(p, "Return to Home Screen", "ghost")
        button(p, "Cancel Transaction", "danger", "x")
        link_button(p, "Send Payment Link")
    spec_tile(grid, "Buttons", _buttons, 320)

    def _inputs(p):
        field(p, "Device ID", "DEV-8849-GTC")
        field(p, "Device Key", "· · · · · · · · · ·", muted_value=True)
        r2 = row(p, "Row", gap=14, fill_w=True, main="spaceBetween", cross="center")
        txt(r2, "Audio notification chime", 13.5, "Regular", INK, name="Label")
        toggle(r2, True)
        r3 = row(p, "Consent", gap=11, fill_w=True, cross="min")
        checkbox(r3, True)
        tt = txt(r3, "Enable biometric authorization", 13, "Regular", "#243447",
                 name="Consent")
        nset(tt, sizingH="fill", textAutoResize="height")
    spec_tile(grid, "Inputs & controls", _inputs, 320)

    def _surfaces(p):
        c = card(p, "Card", gap=4)
        meta(c, "Ref #:", "TXN-998204112")
        meta(c, "Time:", "14:32:05 TST")
        c2 = card(p, "Card · tinted", padding=[12, 14, 12, 14], gap=0,
                  fill=TINT, border=TINT_LINE)
        meta(c2, "Security:", "staff devices stay read-only.", size=12,
             label_color=BLUE_DARK)
        r2 = row(p, "Badges", gap=8, fill_w=True)
        badge(r2, "SUCCESS", "success")
        badge(r2, "DECLINED", "declined")
        badge(r2, "PENDING", "pending")
        pill(r2, "TTD")
    spec_tile(grid, "Surfaces", _surfaces, 320)

    def _rows(p):
        box = col(p, "List", gap=0, fill_w=True, radius=12, stroke=LINE,
                  clip=True, fill=PAPER)
        txn_row(box, "TXN-998204112", "+ $150.00 TTD",
                "14:32 · Tap & Pay · VISA 4242", "SUCCESS")
        txn_row(box, "TXN-9980", "$220.00 TTD", "11:05 · 3DS timeout",
                "DECLINED", "declined", last=True)
    spec_tile(grid, "Transaction rows", _rows, 360)

    def _bars(p):
        b1 = col(p, "Status bar · light", gap=0, fill_w=True, fill=PAPER,
                 radius=10, stroke=LINE, clip=True)
        status_bar(b1, "9:41")
        b2 = col(p, "Status bar · dark", gap=0, fill_w=True, fill=BLUE_DARK,
                 radius=10, clip=True)
        status_bar(b2, "12:00", right="100%", dark=True)
        h = col(p, "App header", gap=0, fill_w=True, radius=10, stroke=LINE,
                clip=True)
        app_header(h, title="Transaction History", right_icon="search")
    spec_tile(grid, "Bars", _bars, 360)

    def _icons(p):
        r2 = row(p, "Icon set", gap=18, fill_w=True, wrap=True)
        for k in ICONS:
            icon(r2, k, 24, INK)
    spec_tile(grid, "Icon set · 24px, 1.8 stroke", _icons, 320)

    # ---- bottom nav main components
    navs = col(root, "Bottom nav components", gap=18, fill_w=True)
    section(navs, "Bottom navigation.",
            "Three main components — one per active tab. The merchant screens "
            "use instances, so editing these updates every screen.")
    strip = row(navs, "Nav components", gap=22, fill_w=True, wrap=True)
    for state in ("Home", "Transactions", "Settings"):
        holder = col(strip, "Holder · " + state, gap=10, width=SCREEN_W)
        nset(holder, sizingH="fixed")
        txt(holder, "Bottom nav / " + state, 11, "Bold", MUTED,
            tracking="10%", case="upper", name="Label")
        start = mark()
        nav = bottom_nav(holder, state)
        size = since(start)
        nset(nav, sizingH="fixed", width=SCREEN_W)
        S.NAV[state] = (make_component(nav), size)

    cmd("node.set", ids=[root], name="PayGo — Design foundations")


# --------------------------------------------------------------------------
def main():
    foundations()

    add_page("02 · Merchant app")
    cmd("page.setBackground", color=PAGE_BG)
    S.m0()
    S.m1()
    S.m2()
    S.outcome(3, "M-3a · Outcome", "Payment successful",
              "Colour, chime and receipt actions resolve the moment hands-free.",
              "success")
    S.outcome(4, "M-3b · Outcome", "Payment declined",
              "Unambiguous failure state with a clear reason and fast retry.",
              "declined")
    S.m4()
    S.m5()
    S.m6()

    add_page("03 · Customer app")
    cmd("page.setBackground", color=PAGE_BG)
    S.c1()
    S.c2()
    S.c3()
    S.c4()

    cmd("text.refit")
    cmd("page.select", index=0)
    cmd("select.none")

    n = dump(sys.argv[1] if len(sys.argv) > 1 else "paygo_build.json")
    import paygo_lib; print(f"{n} commands, next node id {paygo_lib._NEXT[0]}")


if __name__ == "__main__":
    main()
