--
-- Example PocketOS App: "Notes"
--
-- Demonstrates the full SDK: container, per-app config, elements,
-- buttons, fields, and going home.
--
-- This is what gets served from a store manifest entry like:
--   { "id": "notes", "name": "Notes", "icon": "N", "color": "lime",
--     "version": "1.0.0", "url": "https://.../notes.lua",
--     "description": "A tiny notepad" }
--

local c = pocketos.container

local core = core
local cpair = core.cpair

--#region UI

local TextBox = TextBox
local PushButton = PushButton
local TextField = TextField

local title = TextBox{parent=c, y=1, text="Notes", alignment=core.ALIGN.CENTER,
    fg_bg=cpair(colors.lime, colors._INHERIT)}

-- load saved notes from the app's config
local notes = pocketos.config.load().notes or {}

local list = ListBox{parent=c, y=3, height=11, scroll_height=100,
    nav_fg_bg=cpair(colors.lightGray, colors.gray), nav_active=cpair(colors.white, colors.gray)}

local function redraw()
    list.remove_all()
    if #notes == 0 then
        TextBox{parent=list, text="no notes yet - add one!", fg_bg=cpair(colors.gray, colors._INHERIT)}
    else
        for i, note in ipairs(notes) do
            local row = Div{parent=list, height=2}
            TextBox{parent=row, text=i .. ". " .. note, fg_bg=cpair(colors.white, colors._INHERIT)}
            PushButton{parent=row, x=1, y=2, text="delete",
                fg_bg=cpair(colors.red, colors.black), active_fg_bg=cpair(colors.white, colors.black),
                callback=function ()
                    table.remove(notes, i)
                    pocketos.config.save({ notes = notes })
                    redraw()
                end}
            local _ = Div{parent=list, height=1}
        end
    end
end

redraw()

-- new note input
local field = TextField{parent=c, y=15, width=20, max_len=60,
    fg_bg=cpair(colors.white, colors.gray)}

PushButton{parent=c, x=22, y=15, text="Add",
    fg_bg=cpair(colors.lime, colors.black), active_fg_bg=cpair(colors.white, colors.black),
    callback=function ()
        local text = field.get_value()
        if text and #text > 0 then
            table.insert(notes, text)
            pocketos.config.save({ notes = notes })
            field.set_value("")
            redraw()
        end
    end}

PushButton{parent=c, y=18, text="Home",
    fg_bg=cpair(colors.green, colors.black), active_fg_bg=cpair(colors.white, colors.black),
    callback=function () pocketos.go_home() end}
