// orcaFrame.c - ORCA-style desktop application.
//
// Opens a Window Manager window via startdesk()'s full toolset chain,
// runs an event loop via TaskMaster until the user clicks the close
// box, presses Q, or the watchdog fires.
//
// Modeled after ORCA-C's Frame.cc / Reversi.cc samples.  Exercises
// our LLVM/Clang toolchain + the new bank-byte relocation
// end-to-end against the real GS/OS 6.0.2 / 6.0.4 Window Manager.
//
// Phase 4.1 migration: NewWindowParm and event dispatch boilerplate
// folded into iigs/uiBuilder.h and iigs/eventLoop.h respectively.

#include "iigs/toolbox.h"
#include "iigs/desktop.h"
#include "iigs/eventLoop.h"
#include "iigs/uiBuilder.h"


static void *gWin;
static volatile uint16_t gIdleTicks;


static unsigned char gMsg[] = "\x14Hello from llvm816!";


static void onClose(uint32_t windowPtr) {
    CloseWindow((void *)(uintptr_t)windowPtr);
    if (windowPtr == (uint32_t)(uintptr_t)gWin) {
        gWin = (void *)0;
        iigsEventLoopQuit();
    }
}


static void onIdle(void) {
    if (++gIdleTicks > 3000) {
        iigsEventLoopQuit();
    }
}


int main(void) {
    unsigned short userId = startdesk(640);
    (void)userId;

    paintDesktopBackdrop();

    UiWindowT spec = {
        (const char *)0,                       // no title (Font Mgr setup)
        UW_VIS | UW_MOVE | UW_CLOSE,
        { 40, 60, 140, 580 },                  // v1, h1, v2, h2
        200, 320,
        0,
        (void *)0
    };
    gWin = uiBuilderOpenWindow(&spec);

    ShowCursor();
    if (gWin) {
        *(volatile unsigned char *)0x71 = 0xAA;
        BeginUpdate(gWin);
        SetPort(gWin);
        MoveTo(20, 30);
        DrawString(gMsg);
        EndUpdate(gWin);
    }

    IigsEventCallbacksT cb;
    {
        unsigned char *p = (unsigned char *)&cb;
        for (uint16_t i = 0; i < sizeof cb; i++) {
            p[i] = 0;
        }
    }
    cb.onClose = onClose;
    cb.onIdle  = onIdle;
    iigsEventLoop(&cb);

    if (gWin) {
        CloseWindow(gWin);
    }

    *(volatile unsigned char *)0x70 = 0x99;
    return 0;
}
