<div align="center">

```text
      _  _____ _     _  __   __   ____  _____     _     _   _ 
     | || ____| |   | | \ \ / /  | __ )| ____|   / \   | \ | |
  _  | ||  _| | |   | |  \ V /   |  _ \|  _|    / _ \  |  \| |
 | |_| || |___| |___| |___| |    | |_) | |___  / ___ \ | |\  |
  \___/ |_____|_____|_____|_|    |____/|_____|/_/   \_\|_| \_|
```

### ✨ Consistently Engineered. Brutally Disciplined. ✨

[![React](https://img.shields.io/badge/React-19.0-61DAFB?style=for-the-badge&logo=react&logoColor=black)](https://react.dev/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8-3178C6?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Capacitor](https://img.shields.io/badge/Capacitor-6.2-119EFF?style=for-the-badge&logo=capacitor&logoColor=white)](https://capacitorjs.com/)
[![Supabase](https://img.shields.io/badge/Supabase-2.106-3ECF8E?style=for-the-badge&logo=supabase&logoColor=white)](https://supabase.com/)
[![TailwindCSS](https://img.shields.io/badge/TailwindCSS-4.0-06B6D4?style=for-the-badge&logo=tailwindcss&logoColor=white)](https://tailwindcss.com/)

[Download Native APK (Debug)](JellyBean.apk) • [System Handover Sheet](handover.md) • [Database DDL Schema](schema.sql)

---

Jelly Bean is a high-performance, **offline-first 75-Day Challenge engine** built with React 19 and Capacitor 6, featuring transactional bi-directional cloud synchronization. Engineered with an asynchronous Supabase sync layer, the application guarantees zero-latency user interactions by offloading heavy remote operations from the main UI thread via local storage state mirroring.

</div>

---

## ⚡ Architectural Core & Capabilities

Jelly Bean is designed to perform seamlessly under unstable network conditions, securing habit streaks and telemetry logs with absolute consistency.

*   **Offline-First State Machine**: All UI mutations write instantly to a highly optimized local state (`jellybean_pro_state` v2) committed directly to `localStorage`. User interactions feel instantaneous (0ms UI lag) because network transactions are completely decoupled from UI lifecycle loops.
*   **Asynchronous Bi-directional Sync Layer**: An intelligent synchronization engine handles guest-to-cloud profile migrations. Upon user sign-up, existing guest progress data is transactionally synced and merged with remote Supabase databases, preserving historical streaks.
*   **Floating Island Dock**: A hardware-accelerated, navigation element built with `Motion` physics. Transitions between views occur smoothly using fluid `AnimatePresence` spring layouts, emulating high-end native mobile aesthetics.
*   **Vector Telemetry & SVG Rendering Pipeline**: Dynamic mood telemetry, weekly habit grids, and completion percentages are evaluated mathematically and drawn using raw, inline SVG components to eliminate heavy charting library overhead and keep APK package size low.
*   **Capacitor Native Bridge**: Compiled natively using Capacitor 6 to expose a native Android web-bridge, featuring a custom Scheduled Notification Engine (`@capacitor/local-notifications`) cycling through a 75-day quote payload for background engagement.
*   **Supabase Storage Pipeline**: Direct multi-part streaming uploads for progress photos, routed to an authenticated bucket with file-ownership verification policies and instant local fallback data URI rendering.

---

## 📐 Data Flow Architecture

The diagram below illustrates how user actions commit instantly to local storage to maintain zero UI latency, while an async synchronization layer coordinates database and object storage operations in the background.

```mermaid
sequenceDiagram
    autonumber
    actor User as User Interface (React 19)
    participant Local as Local Storage (State Machine)
    participant Sync as Sync Manager (supabaseSync.ts)
    participant DB as PostgreSQL Database (Supabase)
    participant OS as Supabase Storage (Objects)

    User->>Local: Toggle Habit / Log Thought (0ms delay)
    Local-->>User: Refresh View (Confetti / Scale Physics)
    
    rect rgb(20, 20, 20)
        Note over Sync: Async Background Loop Started
        Sync->>Local: Read fresh state delta
        Sync->>DB: Upsert day_progress / custom_tasks
        DB-->>Sync: DB Transaction Confirmed
    end

    User->>Sync: Capture Daily Progress Photo
    Sync->>OS: Stream upload to authenticated/progress-photos
    OS-->>Sync: Return Signed HTTPS CDN URL
    Sync->>Local: Set photoUrl locally
    Sync->>DB: Update photo_path in day_progress
```

---

## 🗄️ Database Modeling & PostgreSQL Schema

The database architecture is designed with strict relational constraints, transactional integrity, and Row-Level Security (RLS) policies protecting user privacy at the database engine level.

### 1. User Profiles Table (`profiles`)
Maintains core user challenge settings and local layout overrides.
```sql
CREATE TABLE public.profiles (
    id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
    start_date DATE NOT NULL DEFAULT CURRENT_DATE,
    habit_overrides JSONB NOT NULL DEFAULT '{}'::jsonb,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL
);
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users manage own profile" ON public.profiles FOR ALL USING (auth.uid() = id);
```

### 2. Custom Habits Table (`custom_tasks`)
Allows dynamic schema extension, supporting customizable user tasks.
```sql
CREATE TABLE public.custom_tasks (
    id TEXT PRIMARY KEY, -- Client-generated ID (timestamp string)
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    subtitle TEXT DEFAULT '',
    duration TEXT DEFAULT '',
    icon TEXT NOT NULL DEFAULT 'star',
    color_idx INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL
);
ALTER TABLE public.custom_tasks ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users manage own tasks" ON public.custom_tasks FOR ALL USING (auth.uid() = user_id);
```

### 3. Log Records Table (`day_progress`)
Tracks 75-day challenges logs, moods, journaling, custom habit arrays, and photo reference paths.
```sql
CREATE TABLE public.day_progress (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    day_number INTEGER NOT NULL CHECK (day_number >= 1 AND day_number <= 75),
    workout BOOLEAN NOT NULL DEFAULT false,
    diet BOOLEAN NOT NULL DEFAULT false,
    book BOOLEAN NOT NULL DEFAULT false,
    water BOOLEAN NOT NULL DEFAULT false,
    photo BOOLEAN NOT NULL DEFAULT false,
    custom_done TEXT[] NOT NULL DEFAULT '{}'::text[],
    note TEXT DEFAULT '',
    mood TEXT DEFAULT NULL,
    photo_path TEXT DEFAULT NULL, -- Key pointer inside progress-photos bucket
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT TIMEZONE('utc'::text, NOW()) NOT NULL,
    UNIQUE (user_id, day_number)
);
ALTER TABLE public.day_progress ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users manage own progress" ON public.day_progress FOR ALL USING (auth.uid() = user_id);
```

### 4. Automatic Profile Provisioning Trigger
An automated trigger handles instant profile creation upon sign-up inside Supabase Auth.
```sql
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO public.profiles (id, start_date)
    VALUES (NEW.id, CURRENT_DATE);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

CREATE OR REPLACE TRIGGER on_auth_user_created
    AFTER INSERT ON auth.users
    FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
```

---

## 🗃️ Directory Mapping & Engineering System

```text
├── android/                   # Native Gradle-compiled Android Studio Project
├── public/                    # Static UI vectors, icons, and logo assets
├── src/
│   ├── components/            # Clean, Single-Responsibility UI Modules
│   │   ├── AddTaskSheet.tsx   # Custom task creator and color mapper
│   │   ├── AuthSheet.tsx      # Supabase Session and Auth form controller
│   │   ├── CalendarView.tsx   # 75-Day grid, heatmaps, and completed badges
│   │   ├── EditTaskModal.tsx  # Long-press context editor with live preview
│   │   ├── Onboarding.tsx     # 3-step cinematic intro and splash layout
│   │   ├── PhotoDetailModal.tsx# Zoom-to-full progress photo viewer
│   │   ├── PomodoroSheet.tsx  # Focus timer with dynamic SVG countdown ring
│   │   ├── RulesSheet.tsx     # Official rules guidelines sheet
│   │   ├── SettingsSheet.tsx  # Appearance toggle, reset controls, and account linkers
│   │   ├── StatsView.tsx      # SVG weekly charts and mood analytics
│   │   └── ThoughtsView.tsx   # Daily journal logs and timeline overview
│   ├── App.tsx                # Core React App shell and State Machine
│   ├── constants.tsx          # Default habit metadata and color registries
│   ├── index.css              # Custom Tailwind CSS v4 setup and Dark Mode variables
│   ├── main.tsx               # App entrypoint mounting React 19 concurrent mode
│   ├── supabaseClient.ts      # Cloud-sync initialization interface
│   └── supabaseSync.ts        # Sync operations layer (guest data migration, photos CRUD)
├── capacitor.config.ts        # Android platform bridge settings
├── schema.sql                 # Complete Postgres database schema script
├── vite.config.ts             # Bundler options
└── package.json               # Package assembly
```

---

## 🛠️ Compilation, Assembly & Build Setup

### Local Development Setup

Ensure you have **Node.js (>= 22.0.0)** and **npm (>= 10.0.0)** installed.

1.  **Clone & Install Dependencies**:
    ```bash
    git clone https://github.com/Nyx-abu/Jelly-Bean---habit-tracker.git
    cd Jelly-Bean---habit-tracker
    npm install
    ```

2.  **Configure Environment**:
    Create a `.env.local` file inside the root directory and insert your Supabase API endpoints:
    ```env
    VITE_SUPABASE_URL=https://your-project-id.supabase.co
    VITE_SUPABASE_ANON_KEY=your-anon-public-key-here
    ```

3.  **Run Development Server**:
    ```bash
    npm run dev
    ```
    Open `http://localhost:3001` in your browser.

---

### Android Production Compilation (Native APK Build)

To build the native Android executable package (`.apk`):

1.  **System Prerequisites**:
    Ensure Android Studio, Gradle, and Android SDK (API level 34+) are installed and configured in your environment path.

2.  **Vite Asset Compilation**:
    Build the React production assets into the distribution bundle:
    ```bash
    npm run build
    ```

3.  **Synchronize Native Assets**:
    Export compiled web assets to the native Android platform project:
    ```bash
    npx cap sync android
    ```

4.  **Gradle Assembly**:
    Compile the native Gradle wrapper in the android directory:
    ```bash
    cd android
    .\gradlew.bat assembleDebug
    ```
    The compiled native installer will be written to:
    `android/app/build/outputs/apk/debug/app-debug.apk`

---

## 📱 Hardware Tuning & Performance Specifications

To maintain high-fidelity performance on low-end mobile devices, Jelly Bean utilizes several low-level performance tricks:

*   **GPU Rendering Layer**: Transitions on card scales, tab toggles, and modal sheets are constrained to `scale`, `x`, `y`, and `opacity` properties. These trigger GPU-based rendering and prevent expensive browser recalculations.
*   **Overscroll Prevention**: Explicit layout boundaries are configured with `overscroll-behavior: none` to stop bouncy web scrolling artifacts on native Android WebView screens.
*   **Touch Optimizations**: The CSS property `-webkit-tap-highlight-color: transparent` and user select overrides are applied globally. This makes web elements feel like rigid, native Android widgets.
*   **Background CPU Preservation**: Timer clocks and ticking progress circles are completely suspended when components are unmounted. This reduces CPU usage and prolongs device battery life.
