-- factoryos.apps.guides — in-system documentation viewer.
-- Reads plain-text guides from cfg.guideDir (default /factoryos/guides).
-- Write guides as .txt files; a leading "# Title" line becomes the title,
-- the rest is word-wrapped body text. Edit in-game with `edit`, or ship
-- them with the deployment manifest.

return {
  id = "guides", name = "GUIDES",
  desc = "System documentation",

  create = function(ctx)
    local W    = require("factoryos.ui.widgets")
    local util = require("factoryos.util")
    local wm   = ctx.wm

    local dir = (ctx.node.cfg and ctx.node.cfg.guideDir) or "/factoryos/guides"
    local listWd, textWd

    local function loadGuides()
      local guides = {}
      if fs and fs.exists(dir) then
        local names = fs.list(dir)
        table.sort(names)
        for _, fname in ipairs(names) do
          if fname:sub(-4) == ".txt" then
            local h = fs.open(dir .. "/" .. fname, "r")
            if h then
              local title = fname:sub(1, -5)
              local lines = {}
              for line in h.readAll():gmatch("([^\n]*)\n?") do
                if line == "" and #lines > 0 then break end
                lines[#lines + 1] = line
              end
              h.close()
              if lines[1] and lines[1]:sub(1, 2) == "# " then
                title = lines[1]:sub(3)
                table.remove(lines, 1)
              end
              guides[#guides + 1] = { title = title, lines = lines }
            end
          end
        end
      end
      if #guides == 0 then
        guides[1] = { title = "(none)", lines = {
          "No guides installed.",
          "",
          "Drop .txt files into " .. dir .. ".",
          "Start a file with '# Title' to name it.",
        } }
      end
      return guides
    end

    local function wrapTo(lines, w)
      local out = {}
      for _, l in ipairs(lines) do
        local wrapped = util.wrap(l, w)
        for _, wl in ipairs(wrapped) do out[#out + 1] = wl end
      end
      return out
    end

    local guides = loadGuides()
    local items = {}
    for i, g in ipairs(guides) do items[i] = { text = g.title, data = g } end

    local cw = wm.cv.w
    local listW = 18
    local contentW = math.max(20, cw - 14 - listW)

    textWd = W.ScrollText({ x = listW + 2, y = 2, w = contentW, h = 13,
      lines = wrapTo(guides[1].lines, contentW) })
    listWd = W.ListBox({ x = 2, y = 2, w = listW, h = 13, items = items,
      onActivate = function(item)
        textWd.lines = wrapTo(item.data.lines, contentW)
        textWd.scroll = 0
        wm:focusWidget(textWd)
      end })

    return {
      title = "GUIDES", x = 3, y = 2, w = cw - 4, h = 16,
      widgets = {
        W.Label({ x = 2, y = 1, w = listW, text = "DOCUMENTS",
          color = W.colors.dim }),
        listWd,
        W.Label({ x = listW + 2, y = 1, w = contentW,
          text = "GUIDE", color = W.colors.dim }),
        textWd,
      },
    }
  end,
}
