(function() {
    var ADMIN_USER = "nak";

    if (AccountServices.username !== ADMIN_USER) {
        return;
    }

    var APP_NAME = "POKER";
    var APP_URL = "https://wizards.cyou/tablet/poker-admin.html";
    var APP_ICON = "https://wizards.cyou/tablet/poker-admin-icon.svg";
    var tablet = Tablet.getTablet("com.highfidelity.interface.tablet.system");
    var button = tablet.addButton({
        text: APP_NAME,
        icon: APP_ICON
    });

    var webEventHandler = function(data) {
        try {
            var msg = JSON.parse(data);
            if (msg.type === "ready") {
                var username = AccountServices.username || "";
                tablet.emitScriptEvent(JSON.stringify({
                    type: "init",
                    username: username,
                    position: MyAvatar.position,
                    rotation: MyAvatar.orientation,
                }));
            } else if (msg.type === "getPosition") {
                // Tablet can request a fresh position snapshot any time
                tablet.emitScriptEvent(JSON.stringify({
                    type: "position",
                    position: MyAvatar.position,
                    rotation: MyAvatar.orientation,
                }));
            } else if (msg.type === "spawnSeats") {
                // HTML side has confirmed table created, now spawn seat pads in world
                spawnSeatPads(msg.tableEntityID, msg.pokerID, msg.seatCount,
                              msg.position, msg.rotation);
            }
        } catch(e) {
            print("[pokerAdmin] web event error: " + e);
        }
    };

    function spawnSeatPads(tableEntityID, pokerID, seatCount, position, rotation) {
        var constants = Script.require(Script.resolvePath("poker_constants.js"));
        var layout = constants.POKER_SEATS[seatCount];
        if (!layout) {
            print("[pokerAdmin] no layout for seatCount=" + seatCount);
            return;
        }

        // Spawn the table model entity first
        var tableID = Entities.addEntity({
            type: "Model",
            name: "poker_table_" + pokerID,
            modelURL: constants.POKER_TABLE_MODEL_URL,
            position: position,
            rotation: rotation,
            dimensions: { x: 3.0, y: 1.0, z: 3.0 },
            userData: JSON.stringify({
                pokerID: pokerID,
                seatCount: seatCount,
            }),
            grabbable: false,
        });

        print("[pokerAdmin] spawned table entity " + tableID);

        // Spawn a seat pad for each seat
        for (var i = 0; i < seatCount; i++) {
            var seat = layout[i];
            var worldOffset = Vec3.multiplyQbyV(rotation, seat.offset);
            var seatPos = Vec3.sum(position, worldOffset);
            var seatRot = Quat.fromPitchYawRollDegrees(0, seat.yaw, 0);

            Entities.addEntity({
                type: "Image",
                name: "poker_seat_" + pokerID + "_" + i,
                imageURL: constants.POKER_SEAT_PAD.imageURL,
                dimensions: constants.POKER_SEAT_PAD.dimensions,
                alpha: constants.POKER_SEAT_PAD.alpha,
                position: seatPos,
                rotation: seatRot,
                script: "https://wizards.cyou/scripts/poker_sit.js",
                userData: JSON.stringify({
                    tableID: tableID,
                    pokerID: pokerID,
                    seatIndex: i,
                }),
                triggerable: true,
                grabbable: false,
                ignorePickIntersection: false,
            });

            print("[pokerAdmin] spawned seat " + i + " for table " + pokerID);
        }

        tablet.emitScriptEvent(JSON.stringify({
            type: "spawnComplete",
            tableEntityID: tableID,
        }));
    }

    button.clicked.connect(function() {
        tablet.gotoWebScreen(APP_URL);
        tablet.webEventReceived.connect(webEventHandler);
    });

    Script.scriptEnding.connect(function() {
        tablet.removeButton(button);
        tablet.webEventReceived.disconnect(webEventHandler);
    });
})();
