# HomelandCMS Integration Guide

This guide walks you through integrating HomelandCMS into an existing Next.js project or setting it up as a standalone application.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Integration Methods](#integration-methods)
3. [Step-by-Step Integration](#step-by-step-integration)
4. [Configuration](#configuration)
5. [Customization](#customization)
6. [Troubleshooting](#troubleshooting)

---

## Prerequisites

Before integrating HomelandCMS, ensure you have:

- ✅ Node.js 18+ installed
- ✅ A Next.js 14+ project (or create a new one)
- ✅ A Supabase account (free tier works)
- ✅ Basic knowledge of Next.js and TypeScript

---

## Integration Methods

Choose the method that best fits your needs:

### Method 1: Full Integration (Recommended)
Copy all CMS files into your Next.js project. Best for new projects or when you want complete control.

### Method 2: Selective Integration
Copy only the components you need (e.g., just the admin panel or specific content types).

### Method 3: Standalone Installation
Use HomelandCMS as a separate application alongside your main site.

---

## Step-by-Step Integration

### Method 1: Full Integration

#### Step 1: Prepare Your Next.js Project

If you don't have a Next.js project yet:

```bash
npx create-next-app@latest my-project
cd my-project
```

Choose these options when prompted:
- TypeScript: **Yes**
- ESLint: **Yes**
- Tailwind CSS: **Yes**
- `src/` directory: **No** (or adjust paths accordingly)
- App Router: **Yes**
- Import alias: **@/*** (default)

#### Step 2: Copy CMS Files

```bash
# From the homeland-cms directory, copy files to your project
cp -r admin/ your-project/app/admin/
cp -r api/ your-project/app/api/
cp -r components/ your-project/components/cms/
cp -r lib/ your-project/lib/cms/
cp -r database/ your-project/database/
```

#### Step 3: Install Dependencies

Add HomelandCMS dependencies to your `package.json`:

```bash
npm install @supabase/supabase-js @supabase/auth-helpers-nextjs \
  @radix-ui/react-accordion @radix-ui/react-alert-dialog \
  @radix-ui/react-avatar @radix-ui/react-checkbox \
  @radix-ui/react-dialog @radix-ui/react-dropdown-menu \
  @radix-ui/react-label @radix-ui/react-popover \
  @radix-ui/react-scroll-area @radix-ui/react-select \
  @radix-ui/react-separator @radix-ui/react-slot \
  @radix-ui/react-switch @radix-ui/react-tabs \
  @radix-ui/react-toast @radix-ui/react-tooltip \
  react-hook-form @hookform/resolvers zod \
  lucide-react recharts sonner \
  class-variance-authority clsx tailwind-merge \
  tailwindcss-animate date-fns resend
```

#### Step 4: Update Tailwind Configuration

Merge the CMS Tailwind config with yours:

```typescript
// tailwind.config.ts
import type { Config } from "tailwindcss";

const config: Config = {
  darkMode: ["class"],
  content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    // Add CMS paths if you copied to different locations
  ],
  theme: {
    extend: {
      // Copy theme extensions from config/tailwind.config.ts
      colors: {
        border: "hsl(var(--border))",
        // ... rest of the colors
      },
      // ... rest of the theme
    },
  },
  plugins: [require("tailwindcss-animate")],
};

export default config;
```

#### Step 5: Add Global Styles

Import CMS styles in your `app/globals.css`:

```css
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Copy the @layer base and @layer components sections from config/globals.css */
```

Or simply:

```bash
cat homeland-cms/config/globals.css >> app/globals.css
```

#### Step 6: Set Up Environment Variables

Create or update `.env.local`:

```bash
cp homeland-cms/env.example .env.local
```

Edit `.env.local` and add your Supabase credentials:

```env
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# Optional: Email and SMS
RESEND_API_KEY=your-resend-key
ADMIN_EMAIL=admin@yourdomain.com
```

Get these from your Supabase project:
1. Go to [Supabase Dashboard](https://app.supabase.com)
2. Select your project
3. Go to Settings → API
4. Copy the URL and keys

#### Step 7: Set Up Database

Run the database migrations in your Supabase project:

**Option A: Supabase SQL Editor (Recommended)**

1. Go to your Supabase project → SQL Editor
2. Create a new query
3. Copy and paste the contents of `database/schema.sql`
4. Click "Run"
5. Repeat for `database/storage-setup.sql`
6. Repeat for `database/storage-policies.sql`

**Option B: Supabase CLI**

```bash
# Install Supabase CLI if you haven't
npm install -g supabase

# Login to Supabase
supabase login

# Link your project
supabase link --project-ref your-project-ref

# Run migrations
supabase db push
cat database/schema.sql | supabase db execute
cat database/storage-setup.sql | supabase db execute
cat database/storage-policies.sql | supabase db execute
```

#### Step 8: Create Admin User

In Supabase Dashboard:
1. Go to Authentication → Users
2. Click "Add User"
3. Enter email and password
4. Click "Create User"

Or use the Supabase CLI:

```bash
supabase auth signup --email admin@yourdomain.com --password yourpassword
```

#### Step 9: Update Import Paths

If you copied files to different locations, update import paths:

```typescript
// Before (in CMS files)
import { Button } from '@/components/ui/button'

// After (if you copied to components/cms/)
import { Button } from '@/components/cms/ui/button'
```

Use find and replace:

```bash
# Example: Update component imports
find app/admin -type f -name "*.tsx" -exec sed -i 's|@/components/|@/components/cms/|g' {} +
find app/admin -type f -name "*.tsx" -exec sed -i 's|@/lib/|@/lib/cms/|g' {} +
```

#### Step 10: Test the Integration

Start your development server:

```bash
npm run dev
```

Navigate to:
- Admin login: `http://localhost:3000/admin/login`
- Admin dashboard: `http://localhost:3000/admin/dashboard` (after login)

---

## Configuration

### Customize Admin Path

By default, the admin panel is at `/admin`. To change it:

1. Rename the `app/admin` folder to your preferred path (e.g., `app/dashboard`)
2. Update the environment variable:

```env
NEXT_PUBLIC_ADMIN_PATH=/dashboard
```

3. Update redirect in admin pages if needed

### Configure Email Notifications

**Using Resend (Recommended):**

```env
RESEND_API_KEY=re_your_api_key
EMAIL_FROM=noreply@yourdomain.com
ADMIN_EMAIL=admin@yourdomain.com
```

**Using SMTP:**

```env
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password
```

### Configure SMS Notifications

For Beem SMS (Tanzania):

```env
BEEM_API_KEY=your_beem_api_key
BEEM_SECRET_KEY=your_beem_secret_key
BEEM_SENDER_NAME=YourBrand
```

---

## Customization

### Change Branding

1. **Update Colors** - Edit `app/globals.css`:

```css
:root {
  --primary: 0 0% 9%;        /* Change to your brand color */
  --secondary: 0 0% 96.1%;   /* Secondary color */
  /* ... */
}
```

2. **Update Logo** - Replace logo in admin layout:

```typescript
// app/admin/components/layout/Sidebar.tsx
<div className="logo">
  <img src="/your-logo.png" alt="Your Brand" />
</div>
```

3. **Update Site Name** - Search and replace "Homeland" with your brand name

### Add New Content Types

See `docs/extending.md` for detailed instructions on adding new content types.

Quick example - Adding a "Services" content type:

1. **Create database table:**

```sql
CREATE TABLE services (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  title text NOT NULL,
  description text,
  icon text,
  active boolean DEFAULT true,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);
```

2. **Create API route:** `app/api/services/route.ts`

3. **Create admin page:** `app/admin/services/page.tsx`

4. **Add to sidebar navigation**

---

## Troubleshooting

### Common Issues

#### "Module not found" errors

**Problem:** Import paths are incorrect after copying files.

**Solution:** Update import paths to match your project structure:

```bash
# Find all TypeScript files and update imports
find app/admin -type f -name "*.tsx" -exec sed -i 's|@/components/ui/|@/components/cms/ui/|g' {} +
```

#### Database connection errors

**Problem:** Supabase credentials are incorrect or missing.

**Solution:** 
1. Verify `.env.local` has correct values
2. Check Supabase project is active
3. Ensure you're using the correct project URL and keys

#### Admin login not working

**Problem:** User doesn't exist or RLS policies are blocking access.

**Solution:**
1. Create admin user in Supabase Dashboard
2. Verify RLS policies are applied (run `database/schema.sql`)
3. Check browser console for errors

#### Storage upload errors

**Problem:** Storage buckets not created or policies not set.

**Solution:**
1. Run `database/storage-setup.sql` in Supabase SQL Editor
2. Run `database/storage-policies.sql`
3. Verify buckets exist in Supabase Dashboard → Storage

#### Build errors

**Problem:** Missing dependencies or TypeScript errors.

**Solution:**
1. Run `npm install` to ensure all dependencies are installed
2. Check `tsconfig.json` paths are correct
3. Run `npm run build` to see detailed errors

---

## Next Steps

After successful integration:

1. ✅ Customize branding and colors
2. ✅ Add your content (portfolio, team, etc.)
3. ✅ Configure email/SMS notifications
4. ✅ Set up custom domain
5. ✅ Deploy to production (see `docs/deployment.md`)

---

## Need Help?

- 📖 [Full Documentation](docs/)
- 🐛 [Report Issues](https://github.com/yourusername/homeland-cms/issues)
- 💬 [Community Support](https://github.com/yourusername/homeland-cms/discussions)

---

**Happy building with HomelandCMS! 🚀**
