# 🎨 Dynamic Theme System - Complete Implementation Guide

## Overview

This is a **production-ready, fully dynamic theming system** for your Angular application with:
- ✅ Runtime theme switching
- ✅ Multiple theme support (Default/Dark/Custom)
- ✅ Dynamic colors, logos, favicon, titles
- ✅ SCSS variable injection
- ✅ LocalStorage persistence
- ✅ SSR-safe implementation
- ✅ TypeScript type safety

---

## 📁 Architecture & Folder Structure

```
src/
├── app/
│   ├── core/
│   │   └── theme/
│   │       ├── models/
│   │       │   └── theme.model.ts          ← Theme interfaces
│   │       ├── configs/
│   │       │   ├── default.theme.ts        ← Default theme
│   │       │   └── dark.theme.ts           ← Dark theme
│   │       └── services/
│   │           └── theme.service.ts        ← Theme management
│   ├── shared/
│   │   └── components/
│   │       └── theme-switcher/
│   │           └── theme-switcher.component.ts  ← UI component
│   └── app.component.ts                    ← Initialize theme
├── assets/
│   └── styles/
│       ├── _theme-variables.scss           ← CSS variables
│       └── _theme-utilities.scss           ← Utility classes
└── styles.scss                             ← Main styles
```

---

## 🚀 Quick Start

### Step 1: Run Migration Script

Convert existing hardcoded colors to theme variables:

```bash
node migrate-to-theme-variables.js
```

This will:
- Create backup of your files
- Replace all hardcoded colors with CSS variables
- Show detailed migration report

### Step 2: Verify Imports

Check that `src/styles.scss` includes:

```scss
@import "tailwindcss";
@import "common.scss";
@import "assets/styles/theme-variables";
@import "assets/styles/theme-utilities";
```

### Step 3: Start Development Server

```bash
npm start
```

**Done!** Your app now has dynamic theming! 🎉

---

## 📝 How to Use

### 1. Basic Usage in Components

```typescript
import { Component } from '@angular/core';
import { ThemeService } from '@core/theme/services/theme.service';

@Component({
  selector: 'app-header',
  template: `
    <header>
      <img [src]="branding.logo" [alt]="branding.appName">
      <h1>{{ branding.appName }}</h1>
      <p>{{ branding.tagline }}</p>
    </header>
  `
})
export class HeaderComponent {
  branding = this.themeService.getBranding();
  
  constructor(private themeService: ThemeService) {}
}
```

### 2. Switch Themes Programmatically

```typescript
// Switch to dark mode
this.themeService.switchMode('dark');

// Toggle between light/dark
this.themeService.toggleMode();

// Switch to a specific theme
this.themeService.switchTheme('default');
```

### 3. Use Theme Variables in SCSS

```scss
.my-component {
  background-color: var(--color-primary);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  font-family: var(--font-family);
}
```

### 4. Use Utility Classes in HTML

```html
<!-- Text Colors -->
<p class="text-primary">Primary text</p>
<p class="text-secondary">Secondary text</p>
<p class="text-muted">Muted text</p>

<!-- Background Colors -->
<div class="bg-primary">Primary background</div>
<div class="bg-surface">Surface background</div>

<!-- Buttons -->
<button class="btn-primary">Primary Button</button>
<button class="btn-secondary">Secondary Button</button>
<button class="btn-outline">Outline Button</button>

<!-- Gradients -->
<div class="bg-gradient-primary">Gradient background</div>
```

### 5. Add Theme Switcher to Your App

```typescript
// In your header/navbar component
import { ThemeSwitcherComponent } from '@shared/components/theme-switcher/theme-switcher.component';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [ThemeSwitcherComponent],
  template: `
    <header>
      <nav>
        <!-- Your navigation -->
      </nav>
      <app-theme-switcher></app-theme-switcher>
    </header>
  `
})
export class HeaderComponent {}
```

---

## 🎨 Creating Custom Themes

### Step 1: Create Theme Configuration

Create `src/app/core/theme/configs/custom.theme.ts`:

```typescript
import { ThemeConfig } from '../models/theme.model';
import { DEFAULT_THEME } from './default.theme';

export const CUSTOM_THEME: ThemeConfig = {
  ...DEFAULT_THEME,
  id: 'custom',
  name: 'Custom Theme',
  
  colors: {
    ...DEFAULT_THEME.colors,
    primary: '#FF5733',        // Your custom primary color
    secondary: '#33FF57',      // Your custom secondary color
    accent: '#3357FF',         // Your custom accent color
  },
  
  branding: {
    ...DEFAULT_THEME.branding,
    appName: 'blu2green 2',
    appTitle: 'blu2green 2 - Tagline',
    tagline: 'Your custom tagline here',
    logo: 'assets/custom/logo.png',
    favicon: 'assets/custom/favicon.ico',
  },
};
```

### Step 2: Register Theme

In `theme.service.ts` constructor or app initialization:

```typescript
// In app.component.ts or theme.service.ts
import { CUSTOM_THEME } from './core/theme/configs/custom.theme';

ngOnInit() {
  this.themeService.registerTheme(CUSTOM_THEME);
  this.themeService.switchTheme('custom');
}
```

---

## 🔧 Advanced Features

### 1. Subscribe to Theme Changes

```typescript
export class MyComponent implements OnInit {
  constructor(private themeService: ThemeService) {}
  
  ngOnInit() {
    // Subscribe to theme changes
    this.themeService.theme$.subscribe(theme => {
      console.log('Theme changed:', theme.name);
    });
    
    // Subscribe to mode changes
    this.themeService.mode$.subscribe(mode => {
      console.log('Mode changed:', mode);
    });
  }
}
```

### 2. Use Signals (Angular 16+)

```typescript
export class MyComponent {
  // Access theme as signal
  theme = this.themeService.themeSignal;
  mode = this.themeService.modeSignal;
  
  constructor(private themeService: ThemeService) {}
}
```

```html
<div>Current theme: {{ theme().name }}</div>
<div>Current mode: {{ mode() }}</div>
```

### 3. Auto Dark Mode (System Preference)

```typescript
// Switch to auto mode (follows system preference)
this.themeService.switchMode('auto');
```

### 4. Dynamic Color Changes

```typescript
// Change a specific color at runtime
this.themeService.changeColor('--color-primary', '#FF0000');
```

---

## 📋 Available CSS Variables

### Colors
```scss
--color-primary
--color-primary-light
--color-primary-dark
--color-secondary
--color-secondary-light
--color-secondary-dark
--color-accent
--color-success
--color-warning
--color-error
--color-info
--color-background
--color-surface
--color-text
--color-text-secondary
--color-border
--color-divider
--color-link
--color-disabled
--color-shadow
```

### Typography
```scss
--font-family
--font-family-heading
--font-family-mono
--font-size-xs
--font-size-sm
--font-size-base
--font-size-lg
--font-size-xl
--font-size-2xl
--font-size-3xl
--font-weight-light
--font-weight-normal
--font-weight-medium
--font-weight-semibold
--font-weight-bold
--line-height-tight
--line-height-normal
--line-height-relaxed
```

### Layout
```scss
--radius-sm
--radius-md
--radius-lg
--radius-xl
--radius-full
--spacing-xs
--spacing-sm
--spacing-md
--spacing-lg
--spacing-xl
--sidebar-width
--sidebar-collapsed-width
--header-height
--footer-height
```

---

## 🎯 Migration Examples

### Before (Hardcoded)
```scss
.button {
  background-color: #0F6FB7;
  color: #FFFFFF;
  border-radius: 8px;
  padding: 8px 16px;
}
```

### After (Dynamic)
```scss
.button {
  background-color: var(--color-primary);
  color: var(--color-background);
  border-radius: var(--radius-md);
  padding: var(--spacing-sm) var(--spacing-md);
}
```

---

## 🔄 Theme Persistence

Themes are automatically saved to localStorage:
- Theme ID: `app-theme-id`
- Theme Mode: `app-theme-mode`

Users' theme preferences persist across sessions!

---

## 🌙 Dark Mode Support

Dark mode is automatically applied when:
1. User switches to dark mode manually
2. User sets mode to 'auto' and system prefers dark
3. Theme is loaded from storage as 'dark'

CSS variables are automatically updated via `[data-theme-mode="dark"]` selector.

---

## 📱 Responsive Design

All theme variables work seamlessly with responsive design:

```scss
.component {
  padding: var(--spacing-sm);
  
  @media (min-width: 768px) {
    padding: var(--spacing-md);
  }
  
  @media (min-width: 1024px) {
    padding: var(--spacing-lg);
  }
}
```

---

## ✅ Best Practices

1. **Always use CSS variables** instead of hardcoded colors
2. **Use utility classes** for common patterns
3. **Create custom themes** for different clients/brands
4. **Test both light and dark modes**
5. **Keep theme configs in separate files**
6. **Use TypeScript interfaces** for type safety
7. **Subscribe to theme changes** for dynamic updates

---

## 🐛 Troubleshooting

### Theme not applying?
1. Check that ThemeService is initialized in app.component.ts
2. Verify imports in styles.scss
3. Clear browser cache and localStorage
4. Restart dev server

### Colors not changing?
1. Run migration script: `node migrate-to-theme-variables.js`
2. Check that CSS variables are used in SCSS
3. Verify theme is registered and active

### Dark mode not working?
1. Check `[data-theme-mode="dark"]` selector in _theme-variables.scss
2. Verify mode is set: `this.themeService.switchMode('dark')`
3. Check browser console for errors

---

## 📊 Performance

- ✅ **Minimal overhead**: CSS variables are native browser feature
- ✅ **No runtime compilation**: SCSS compiled at build time
- ✅ **Instant switching**: Theme changes apply immediately
- ✅ **Small bundle size**: ~5KB for theme system

---

## 🎉 Summary

You now have a **complete, production-ready dynamic theming system**!

### What You Can Do:
✅ Switch themes at runtime
✅ Support multiple themes (default/dark/custom)
✅ Dynamic logos, favicons, titles
✅ Persistent user preferences
✅ Type-safe theme configurations
✅ SSR-safe implementation
✅ Easy to extend and customize

### Quick Commands:
```bash
# Migrate existing code
node migrate-to-theme-variables.js

# Start development
npm start

# Build for production
npm run build
```

**Your app is now fully themeable!** 🎨✨

---

## 📚 Additional Resources

- Theme Model: `src/app/core/theme/models/theme.model.ts`
- Theme Service: `src/app/core/theme/services/theme.service.ts`
- Default Theme: `src/app/core/theme/configs/default.theme.ts`
- CSS Variables: `src/assets/styles/_theme-variables.scss`
- Utilities: `src/assets/styles/_theme-utilities.scss`

**Happy theming!** 🚀
