/* sokoban.c —— 推箱子（Sokoban），跑在任意 VML 宿主上
 * sokoban.c -- Sokoban, runs on any VML host
 *
 *     vml run examples/c/app/sokoban.c
 *
 * ## 跨平台口径（用户会把手机上编译的 .vmb 拿到别的宿主上跑）
 * ## Cross-platform notes (the .vmb compiled on the phone will run on other hosts)
 *
 * - 只用稳定 `ui_*` 接口；布局每帧按画布尺寸现算，竖屏/横屏/桌面窗口都成立；
 * - 触摸与鼠标同时兼容，并对 MAUI 的「一次点击两条消息」去重（E411）；
 * - 同时支持**方向键**（桌面/外接键盘）。
 *
 * ## 玩法
 * ## How to play
 *
 * 方向键 / 屏幕下方方向盘移动小人；推箱子到圆点上。箱子只能推、不能拉。
 * 移动方向键或点方向盘移动。点「重来」复位本关。全部箱子就位即过关。
 */

#include <vml_ui.h>

#define MAPW 7
#define MAPH 7
#define UNDO_MAX 512

/* 地图：0 地板 / 1 墙 / 3 目标点（箱子另用 box[] 表示） */
/* Map: 0 floor / 1 wall / 3 target (boxes live in box[]) */
int base_map[MAPW * MAPH] = {
    1,1,1,1,1,1,1,
    1,0,0,0,0,0,1,
    1,0,3,0,3,0,1,
    1,0,0,0,0,0,1,
    1,0,0,0,0,0,1,
    1,0,0,0,0,0,1,
    1,1,1,1,1,1,1
};

/* 初始箱子与小人（每次重来从这里恢复） */
/* Initial boxes and player (restored on restart) */
int init_box[MAPW * MAPH] = {
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,
    0,0,2,0,2,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,0
};
int init_px = 3, init_py = 5;

int W, H;
int g_lang;
int box[MAPW * MAPH];
int px, py;
int moves, won;

/* 撤销栈 / undo stack */
int hx[UNDO_MAX], hy[UNDO_MAX];
int hbx[UNDO_MAX], hby[UNDO_MAX], hp[UNDO_MAX];
int hn;

char g_buf[32];

char* fmt_int(int v, char* buf)
{
    int n = 0, i = 0;
    if (v < 0) { buf[n] = '-'; n = n + 1; v = -v; }
    if (v == 0) { buf[n] = '0'; n = n + 1; }
    else {
        char t[12];
        i = 0;
        while (v > 0 && i < 11) { t[i] = (char)('0' + v % 10); i = i + 1; v = v / 10; }
        while (i > 0) { i = i - 1; buf[n] = t[i]; n = n + 1; }
    }
    buf[n] = 0;
    return buf;
}

int idx(int x, int y) { return y * MAPW + x; }
int wall_at(int x, int y) { return base_map[idx(x, y)] == 1; }

void restart(void)
{
    int i;
    for (i = 0; i < MAPW * MAPH; i++) box[i] = init_box[i];
    px = init_px;
    py = init_py;
    moves = 0;
    won = 0;
    hn = 0;
}

int all_done(void)
{
    int i;
    for (i = 0; i < MAPW * MAPH; i++)
        if (box[i] && base_map[i] != 3) return 0;
    return 1;
}

/* 推一步；成功返回 1 */
/* Push one step; returns 1 on success */
int step(int dx, int dy)
{
    int nx = px + dx, ny = py + dy;
    int bx, by, i;

    if (wall_at(nx, ny)) return 0;

    i = idx(nx, ny);
    if (box[i]) {
        bx = nx + dx; by = ny + dy;
        if (wall_at(bx, by)) return 0;
        if (box[idx(bx, by)]) return 0;
        /* 记录撤销 */
        if (hn < UNDO_MAX) {
            hx[hn] = px; hy[hn] = py;
            hbx[hn] = bx; hby[hn] = by;
            hp[hn] = i;
            hn = hn + 1;
        }
        box[i] = 0;
        box[idx(bx, by)] = 1;
        moves = moves + 1;
        ui_audio_beep(520, 45);
    } else {
        if (hn < UNDO_MAX) {
            hx[hn] = px; hy[hn] = py;
            hp[hn] = -1;
            hn = hn + 1;
        }
    }

    px = nx; py = ny;
    if (all_done()) {
        won = 1;
        ui_audio_beep(1047, 240);
    }
    return 1;
}

void undo(void)
{
    int p;
    if (hn <= 0) return;
    hn = hn - 1;
    px = hx[hn]; py = hy[hn];
    p = hp[hn];
    if (p >= 0) {
        box[idx(hbx[hn], hby[hn])] = 0;   /* 箱子被推到的新格 / the new box cell */
        box[p] = 1;                        /* 原来的格子 / the original box cell */
        if (moves > 0) moves = moves - 1;
    }
    won = 0;
}

/* ── 布局（每帧现算）── */
/* -- Layout (recomputed every frame) -- */

int pad_h(void)
{
    int h = H * 30 / 100;
    if (h > 240) h = 240;
    if (h < 140) h = 140;
    return h;
}

int tile_size(void)
{
    int avail_w = (W - 32) / MAPW;
    int avail_h = (H - 88 - pad_h()) / MAPH;
    int t = avail_w < avail_h ? avail_w : avail_h;
    if (t < 8) t = 8;
    return t;
}

int board_x(void) { return (W - MAPW * tile_size()) / 2; }
int board_y(void)
{
    int free = H - 88 - pad_h() - MAPH * tile_size();
    int y = 80 + free / 2;
    if (y < 76) y = 76;
    return y;
}

/* ── 绘制 ── */
/* -- Drawing -- */

void draw_arrow(int cx, int cy, int r, int dir, int hot)
{
    int col = hot ? 0xFF5EC8F0 : 0xFFE6EBF5;
    if (dir == 0) {          /* up */
        ui_2d_line(cx, cy - r, cx - r, cy + r / 2, col, 3);
        ui_2d_line(cx, cy - r, cx + r, cy + r / 2, col, 3);
    } else if (dir == 1) {   /* left */
        ui_2d_line(cx - r, cy, cx + r / 2, cy - r, col, 3);
        ui_2d_line(cx - r, cy, cx + r / 2, cy + r, col, 3);
    } else if (dir == 2) {   /* down */
        ui_2d_line(cx, cy + r, cx - r, cy - r / 2, col, 3);
        ui_2d_line(cx, cy + r, cx + r, cy - r / 2, col, 3);
    } else {                 /* right */
        ui_2d_line(cx + r, cy, cx - r / 2, cy - r, col, 3);
        ui_2d_line(cx + r, cy, cx - r / 2, cy + r, col, 3);
    }
}

void draw(void)
{
    int x, y, i, t, bx, by, ph, pcx, pcy, r;
    char* s;

    ui_2d_clear(0xFF11141C);

    /* 状态行 */
    ui_2d_text_v(16, 28, g_lang == 0 ? "推箱子" : "Sokoban", 0xFFE6EBF5, 22,
                 VML_ANCHOR_LEFT, VML_VANCHOR_MIDDLE, VML_FONT_BOLD);
    fmt_int(moves, g_buf);
    ui_2d_text_v(W - 16, 28, g_buf, 0xFF8B94A7, 16,
                 VML_ANCHOR_RIGHT, VML_VANCHOR_MIDDLE, 0);
    s = won ? (g_lang == 0 ? "过关！点「重来」再来一次" : "Solved! Tap Restart")
            : (g_lang == 0 ? "把箱子推到圆点上" : "Push boxes onto the dots");
    ui_2d_text_v(W / 2, 56, s, won ? 0xFF4ADE80 : 0xFF8B94A7, 14,
                 VML_ANCHOR_CENTER, VML_VANCHOR_MIDDLE, 0);

    t = tile_size();
    bx = board_x();
    by = board_y();

    for (y = 0; y < MAPH; y++) {
        for (x = 0; x < MAPW; x++) {
            i = idx(x, y);
            int cx = bx + x * t, cy = by + y * t;
            if (wall_at(x, y)) {
                ui_2d_rect(cx + 1, cy + 1, t - 2, t - 2, 0xFF2A3346, 1, 0, 2);
            } else {
                ui_2d_rect(cx + 1, cy + 1, t - 2, t - 2, 0xFF171C27, 1, 0, 2);
                if (base_map[i] == 3)
                    ui_2d_circle(cx + t / 2, cy + t / 2, t / 7 + 1, 0xFF4ADE80, 1, 0);
                if (box[i])
                    ui_2d_rect(cx + t / 6, cy + t / 6, t * 2 / 3, t * 2 / 3,
                               0xFFC88A3C, 1, 0, 3);
            }
        }
    }

    /* 小人 */
    ui_2d_circle(bx + px * t + t / 2, by + py * t + t / 2, t / 3, 0xFF5EC8F0, 1, 0);

    /* 底部方向盘 + 重来 */
    ph = pad_h();
    pcx = W / 2;
    pcy = H - ph / 2 + 8;
    r = ph / 8;
    if (r < 18) r = 18;
    if (r > 34) r = 34;
    ui_2d_rect(pcx - r * 3, pcy - r, r * 2, r * 2, 0xFF202737, 1, 0, 6);
    draw_arrow(pcx - r * 2, pcy, r * 2 / 3, 1, 0);
    draw_arrow(pcx, pcy - r * 2, r * 2 / 3, 0, 0);
    draw_arrow(pcx, pcy + r * 2, r * 2 / 3, 2, 0);
    draw_arrow(pcx + r * 2, pcy, r * 2 / 3, 3, 0);

    ui_2d_rect(W - 100, H - 44, 88, 32, 0xFF232938, 1, 0, 8);
    ui_2d_text_v(W - 56, H - 28, g_lang == 0 ? "重来" : "Restart", 0xFFE6EBF5, 13,
                 VML_ANCHOR_CENTER, VML_VANCHOR_MIDDLE, 0);
    ui_2d_rect(12, H - 44, 88, 32, 0xFF232938, 1, 0, 8);
    ui_2d_text_v(56, H - 28, g_lang == 0 ? "撤销" : "Undo", 0xFFE6EBF5, 13,
                 VML_ANCHOR_CENTER, VML_VANCHOR_MIDDLE, 0);

    ui_2d_present();
}

/* ── 交互 ── */
/* -- Input -- */

void tap(int x, int y)
{
    int ph = pad_h();
    int pcx = W / 2;
    int pcy = H - ph / 2 + 8;
    int r = ph / 8;
    if (r < 18) r = 18;
    if (r > 34) r = 34;

    if (x >= W - 100 && x < W - 12 && y >= H - 44 && y < H - 12) { restart(); return; }
    if (x >= 12 && x < 100 && y >= H - 44 && y < H - 12) { undo(); return; }

    if (x >= pcx && x < pcx + r * 2 && y >= pcy - r * 2 && y < pcy) { step(1, 0); return; }
    if (x >= pcx - r * 4 && x < pcx - r * 2 && y >= pcy - r && y < pcy + r) { step(-1, 0); return; }
    if (x >= pcx - r * 2 && x < pcx && y >= pcy + r && y < pcy + r * 3) { step(0, 1); return; }
    if (x >= pcx && x < pcx + r * 2 && y >= pcy - r * 3 && y < pcy - r) { step(0, -1); return; }
}

int main(void)
{
    int m[4];
    int t;
    int lastX = -1, lastY = -1, sawTouch = 0;

    g_lang = ui_scr_get_language();
    ui_win_open_ex(g_lang == 0 ? "推箱子" : "Sokoban", 0, 0,
                   VML_WIN_ROTATABLE, VML_WIN_NO_GAMEPAD);
    W = ui_scr_get_w();
    H = ui_scr_get_h();
    ui_scr_set_keep_on(1);

    restart();
    draw();

    while (ui_win_is_closed() == 0) {
        t = ui_msg_wait(m, 100);
        if (t == VML_MSG_WINDOWCLOSE) break;
        if (t == VML_MSG_WINDOWRESIZE) {
            W = ui_scr_get_w();
            H = ui_scr_get_h();
            draw();
            continue;
        }
        if (t == VML_MSG_TOUCHDOWN) {
            lastX = m[1]; lastY = m[2]; sawTouch = 1;
            tap(m[1], m[2]);
            draw();
            continue;
        }
        if (t == VML_MSG_MOUSEDOWN) {
            if (sawTouch && m[1] == lastX && m[2] == lastY) { sawTouch = 0; continue; }
            tap(m[1], m[2]);
            draw();
            continue;
        }
        if (t == VML_MSG_KEYDOWN) {
            if (m[1] == 37) step(-1, 0);
            else if (m[1] == 39) step(1, 0);
            else if (m[1] == 38) step(0, -1);
            else if (m[1] == 40) step(0, 1);
            else if (m[1] == 82) restart();      /* R */
            else if (m[1] == 85) undo();         /* U */
            else continue;
            draw();
            continue;
        }
    }

    ui_scr_set_keep_on(0);
    return 0;
}
