# TGBOT Builder: Complete Dashboard Analytics, Modules Hub & Settings Architecture Plan

## Goal Description
Transform **TGBOT Builder** into a complete Telegram Bot Control System with dedicated functionality across all three primary tabs:
1. **Dashboard Tab**: High-level executive overview with **Visual Analytics & Analyses** (traffic trends, message distribution, 500-user quota meter, live health latency, and recent activity).
2. **Modules Hub Tab (formerly Spaces)**: The operational engine with **Bot Status**, **Active Modules Summary**, **Dynamic Management Cards** (Cards for Welcome, Broadcast, Force Join, and Logs that only appear when active), and the **Module Library** with toggle switches.
3. **Settings Tab**: Configuration center tailored for bot creators (User Plan & Quota Tier, Bot Engine & Telegram API settings, Admin Alert notifications, Data backup/export, and Security/Theme).

---

## Complete Tab-by-Tab Architecture

```mermaid
graph TD
    subgraph Navigation ["Bottom Navigation"]
        Tab1["📊 Dashboard (Analytics & Health)"]
        Tab2["🧩 Modules Hub (Bot Control Center)"]
        Tab3["⚙️ Settings (Engine & Preferences)"]
    end

    subgraph DashboardDetails ["1. Dashboard Tab"]
        TopBar1["TopBar: Bot Selector + Quick Create Bot"]
        Metrics["4 Core Metrics: Total Bots | Active Bots | Users | Messages"]
        QuotaMeter["Free Plan Quota Meter: 500 Users Progress Ring"]
        Analyses["Visual Analytics: 7-Day User Growth & Activity Trends"]
        Health["Bot Health Card: Real-time Ping Latency (ms) & Online Check"]
        Activity["Recent Activity Feed: Live Event Timeline"]
    end

    subgraph ModulesDetails ["2. Modules Hub Tab"]
        BotHeader["Bot Status Header: @username, Live Badge, Token"]
        ActiveBar["Active Modules Bar: Quick Status Tags"]
        DynamicCards["Dynamic Management Cards (Appear when Active)"]
        WelcomeCard["• Welcome Card: /start Preview & Quick Edit"]
        BroadcastCard["• Broadcast Card: Audience Stats & New Campaign"]
        ForceJoinCard["• Force Join Card: @channel & Join Verification"]
        LogsCard["• Live Logs Card: Recent Events & Log Viewer"]
        Library["Module Library: Catalogue with ON/OFF Switches"]
    end

    subgraph SettingsDetails ["3. Settings Tab"]
        ProfileCard["User Profile & Free Tier Badge (1 Bot, 500 Users)"]
        UpgradeCard["Pro Tier Info: Unlimited Bots & Advanced Features"]
        EngineSettings["Bot Engine Settings: Polling / Webhook & API Gateway"]
        AdminAlerts["Admin Alerts: Telegram Chat ID for Bot Notifications"]
        DataManagement["Backup & Export: Export/Import Bot JSON Configuration"]
        SecurityAppearance["Appearance & Security: Dark Mode, Theme, App Lock"]
    end

    Tab1 --> DashboardDetails
    Tab2 --> ModulesDetails
    Tab3 --> SettingsDetails
```

---

## Detailed Component Specifications

### 1. Dashboard: Metrics & Visual Analyses

The Dashboard provides creators with instant insight into bot traction and performance:

| Component | Description | Free Plan Rule |
| :--- | :--- | :--- |
| **Top Bar & Bot Switcher** | Dropdown pill showing active bot (`@bot 🟢 ▾`), switch between bots, or `+ Add Bot`. | Max 1 Bot in Free Plan |
| **Key Metrics Grid** | 4 compact stat cards: <br>• **Total Bots**: `1 / 1`<br>• **Active Bots**: `1 Online`<br>• **Total Users**: `X / 500 Users`<br>• **Messages Sent**: Lifetime count | Capped at 500 users |
| **Free Plan Quota Meter** | Circular / Donut progress meter showing user saturation (`X / 500 used`, percentage, and remaining slots). | Visual alert when approaching 500 |
| **User Activity & Growth Graph** | 7-day activity bar/line graph (Mon-Sun) displaying daily active users and interaction peaks. | Analyzed locally from bot log data |
| **Message Analytics Breakdown** | Distribution indicator: Broadcast messages vs Command executions vs Auto-welcome greetings. | Real-time counts |
| **Bot Health Monitoring Card** | Live Telegram API round-trip latency (`ms`), status dot (`🟢 Online` / `🔴 Offline`), and manual "Ping Health ⚡" button. | Direct `getMe` HTTP latency test |
| **Recent Activity Timeline** | Live feed of recent events (e.g. `User @alex started bot`, `Broadcast sent to 45 users`, `Channel membership checked`). | Last 10 events |

---

### 2. Modules Hub (Spaces): Dynamic Management & Library

The Modules screen is the hands-on control room for configuring how the bot behaves:

1. **Bot Status Bar**:
   - Avatar icon with active status indicator (`ONLINE 🟢`).
   - Bot name and `@username` with direct "Open in TG ↗" button.
   - Masked token (`712345****`).
2. **Active Modules Overview**:
   - Interactive badge row: `Welcome ✅`, `Broadcast 📢`, `Force Join 🔒`, `Logs 📜`.
3. **Dynamic Management Cards** (Cards render **dynamically based on active modules**):
   - **Welcome Card** *(Shown if Welcome is ON)*:
     - Live preview of the `/start` greeting text.
     - Attached media indicator (Text only or Photo/Video).
     - Inline buttons count.
     - "Edit Greeting ✏️" button ➔ opens `WelcomeConfigDialog`.
   - **Broadcast Manager Card** *(Shown if Broadcast is ON)*:
     - Audience reach counter (`Target: 500 Users max`).
     - Last campaign timestamp & delivered count.
     - "New Broadcast 📢" button ➔ opens `BroadcastComposerDialog`.
   - **Force Join (FSub) Card** *(Shown if Force Join is ON)*:
     - Target channel tag (`@channel_name`).
     - Channel join verification status.
     - "Configure Channel ⚙️" button ➔ opens `ForceJoinConfigDialog`.
   - **Live Logs Card** *(Shown if Logs is ON)*:
     - Counter of recorded events (Commands, Errors, Webhooks).
     - Snippet of the 2 most recent log entries.
     - "Open Full Logs 📜" button ➔ opens `BotLogsViewerDialog`.
4. **Module Library**:
   - A clean catalogue listing all modules with title, description, icon, and an instant **Switch toggle**.
   - Toggling a switch immediately adds or removes the corresponding dynamic management card above.

---

### 3. Settings: Bot Engine, Preferences & Account

The Settings tab is tailored specifically for Telegram Bot administration:

1. **User Profile & Plan Tier**:
   - User Name & Email address.
   - Plan Badge: **FREE PLAN** (`1 Bot, 500 Users`).
   - Quota overview: 1/1 Bot used, 500 Users cap.
   - "Explore Pro Plan" banner (describing future Pro features: Unlimited bots, Unlimited users, Custom Webhook URL, AI chatbot mode).
   - "Logout" action.
2. **Bot Engine & Connectivity Settings**:
   - **Telegram Connection Mode**: Polling vs Webhook selection.
   - **Telegram API Gateway**: Default (`https://api.telegram.org`) with option to connect to custom self-hosted Bot API servers.
   - **Active Bot Token**: View masked token, copy token, test connection, or disconnect/delete bot.
3. **Admin Alerts & Notifications**:
   - **Admin Alert Switch**: Enable push notifications when new users start the bot or errors occur.
   - **Admin Telegram ID**: Store Admin's Telegram ID to receive system alerts.
4. **Backup & Data Management**:
   - **Export Bot Configuration**: Export full bot configuration (modules, greeting, FSub settings) as a `.json` backup file.
   - **Import Configuration**: Restore bot settings from a backup file.
   - **Clear Activity Logs**: Purge cached event logs to free up device memory.
5. **App Security & Appearance**:
   - **Theme**: Dark Mode, Light Mode, or Auto (System).
   - **Dynamic Colors**: Material You dynamic theming.
   - **App Security**: Fingerprint / Biometric Lock on app open.
   - **Block Screenshots**: Prevent screen recording for security.
6. **About & Documentation**:
   - App Version (`3.7.0 TGBOT Builder Edition`).
   - Guide: How to create a bot in `@BotFather` & get token.
   - Terms & Privacy.

---

## File Changes Summary

### New Files
- `composeApp/.../tgbot/TgMetricsGrid.kt`: 4-card metric grid.
- `composeApp/.../tgbot/TgAnalysesCard.kt`: 7-day user growth graph & message distribution.
- `composeApp/.../tgbot/BotHealthCard.kt`: Real-time ping latency and online status monitor.
- `composeApp/.../tgbot/RecentActivityCard.kt`: Chronological event activity feed.
- `composeApp/.../tgbot/dialogs/WelcomeConfigDialog.kt`: Modal to edit greeting message and inline buttons.
- `composeApp/.../tgbot/dialogs/BroadcastComposerDialog.kt`: Broadcast composer with instant preview and audience meter.
- `composeApp/.../tgbot/dialogs/ForceJoinConfigDialog.kt`: Target channel setup and test verification.
- `composeApp/.../tgbot/dialogs/BotLogsViewerDialog.kt`: Searchable, filterable event log inspector.

### Modified Files
- `composeApp/.../tgbot/TgBot.kt`: Data models for modules, health stats, and log entries.
- `composeApp/.../presentation/main/MainViewModel.kt`: State flows and actions for module toggles, pinging health, broadcasting, and logging.
- `composeApp/.../presentation/main/DashboardScreen.kt`: Integrate Metrics, Analyses Graph, Health Card, Activity Feed, and Bot Selector.
- `composeApp/.../presentation/main/SpacesScreen.kt`: Transform into the Bot Modules Hub (Status, Active Bar, Dynamic Cards, Library).
- `composeApp/.../presentation/main/SettingsScreen.kt`: Reorganize into Bot Creator Settings (Profile & Plan, Bot Engine, Admin Alerts, Backup/Export, Theme).

---

## Verification Plan

### Build Verification
- **Build Status**: Completed (`BUILD SUCCESSFUL in 51s`)
- **APK Output**: `/root/TGBOT-Builder.apk` (46.3 MB)
- **Live URL**: `http://148.113.1.66:8088/TGBOT-Builder.apk`
- **Application Label**: `TGBOT Builder`
- **Package**: `com.mhss.app.mybrain.debug`

### Functional Checklist
- [x] **Dashboard Tab**:
   - Total Bots, Active Bots, Total Users (0/500 Max), Messages Sent.
   - 7-Day Activity Analysis Bar Chart & User Saturation Progress Bar.
   - Bot Health Monitoring with live latency ping in ms and status dot.
   - Live Activity Feed stream.
- [x] **Modules Hub Tab (Spaces)**:
   - Bot Status Header (Selected bot, online dot, masked token).
   - Active Modules Status Bar.
   - Dynamic conditional cards (Welcome, Broadcast Manager, Force Join / FSub, Bot Logs).
   - Module Library with interactive ON/OFF switches and instant dialog openers.
- [x] **Settings Tab**:
   - User Profile & Free Plan Card (1/1 Bot slot, 500 Max Users, Logout action).
   - Bot Engine & Protocol Card (Telegram Gateway `api.telegram.org`, Long Polling).
   - Backup & Cache Management.
- [x] **Top Bar & Quota**:
   - Bot Selector Dropdown + Add Bot with live `getMe` auto-fetching.
   - Free Plan quota limit strictly enforced (1 Bot per user, max 500 users).
