# TIA GPC Widget

Intelligent chat widget for TIA GPC integration. Compatible with **React, HTML, Angular, ASP.NET, Vue, and any other framework**.

[![npm version](https://img.shields.io/npm/v/tia-gpc-widget.svg)](https://www.npmjs.com/package/tia-gpc-widget)
[![jsDelivr](https://data.jsdelivr.com/v1/package/npm/tia-gpc-widget/badge)](https://www.jsdelivr.com/package/npm/tia-gpc-widget)
[![License](https://img.shields.io/badge/license-UNLICENSED-red.svg)](LICENSE)

---

## 📋 Table of Contents

- [Features](#-features)
- [Installation](#-installation)
  - [Option 1: NPM (For React/Node Projects)](#option-1-npm-for-reactnode-projects)
  - [Option 2: CDN (For HTML, Angular, ASP.NET, etc.)](#option-2-cdn-for-html-angular-aspnet-etc)
- [Quick Start](#-quick-start)
- [Framework Examples](#-framework-examples)
  - [React](#1-react)
  - [HTML / Vanilla JavaScript](#2-html--vanilla-javascript)
  - [Angular](#3-angular)
  - [ASP.NET / ASPX](#4-aspnet--aspx)
  - [Vue.js](#5-vuejs)
  - [Next.js](#6-nextjs)
  - [PHP](#7-php)
- [API & Configuration](#-api--configuration)
  - [Props/Attributes](#propsattributes)
  - [Events](#events)
  - [Programmatic API (JavaScript)](#programmatic-api-javascript)
- [Customization](#-customization)
  - [Themes](#themes)
  - [Positions](#positions)
  - [Languages](#languages)
  - [Colors](#colors)
- [Build & Development](#-build--development)
- [Publishing](#-publishing)
- [Support](#-support)

---

## 🚀 Features

- ✅ **Framework Agnostic**: Works in React, Angular, Vue, ASP.NET, plain HTML, etc.
- ✅ **Web Component**: Based on native web standards
- ✅ **Themes**: Light, dark, or automatic mode
- ✅ **Internationalization**: Spanish, English, French
- ✅ **Responsive**: Adaptive design for mobile and desktop
- ✅ **Customizable**: Colors, positions, dimensions
- ✅ **TypeScript Ready**: Types included
- ✅ **Zero Dependencies**: Standalone bundle includes everything needed

---

## 🚀 Auto-Update Loader (Recommended)

**NEW!** Install once, get updates forever. No more manual version updates!

The **TIA GPC Widget Loader** is a small, stable script (~1KB gzipped) that automatically loads the latest version of the widget. Your clients install it **ONCE** and receive all future updates automatically.

### Quick Start with Loader

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My App with TIA GPC</title>
</head>
<body>
  <h1>My Application</h1>

  <!-- TIA GPC Widget Loader (install once, updates forever) -->
  <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"></script>

  <!-- Widget element -->
  <tia-gpc-widget
    token="your-license-token-here"
    theme="auto"
    position="bottom-right"
    language="en"
  ></tia-gpc-widget>
</body>
</html>
```

**Benefits:**
- ✅ Install once, never update manually again
- ✅ Automatic updates when you publish new versions
- ✅ Built-in error handling and retries
- ✅ Support for stable/beta channels
- ✅ Extremely small (~1KB gzipped)
- ✅ Works with all frameworks (HTML, React, Angular, ASP.NET, etc.)

[See complete loader documentation and examples →](#loader-advanced-usage)

---

## 📦 Installation

### Option 1: Auto-Update Loader (Recommended)

Use the loader for automatic updates:

```html
<!-- jsDelivr (Recommended) -->
<script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"></script>

<!-- unpkg -->
<script src="https://unpkg.com/tia-gpc-widget@latest/dist/loader.min.js"></script>
```

Then use the widget as normal:
```html
<tia-gpc-widget token="your-token" theme="auto"></tia-gpc-widget>
```

### Option 2: NPM (For React/Node Projects)

```bash
npm install tia-gpc-widget
```

or with yarn:

```bash
yarn add tia-gpc-widget
```

or with pnpm:

```bash
pnpm add tia-gpc-widget
```

### Option 3: Direct CDN (Legacy - Not Recommended)

⚠️ **Note:** This method is still supported but **not recommended** for new installations.
It requires manual updates every time we release a new version.
**Use the Auto-Update Loader instead** (see Option 1 above).

#### jsDelivr - Fixed Version

```html
<!-- ⚠️ Legacy method: Requires manual version updates -->
<script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.css">
```

#### unpkg - Fixed Version

```html
<!-- ⚠️ Legacy method: Requires manual version updates -->
<script src="https://unpkg.com/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.css">
```

**Why use the loader instead?**
- ✅ Automatic updates - no code changes needed
- ✅ Always get bug fixes and improvements
- ✅ Smaller initial load (~2KB vs ~420KB until needed)
- ✅ Built-in error handling and fallbacks

**For existing installations:** See [Migration Guide](MIGRATION.md) to upgrade to the auto-update loader.

---

## ⚡ Quick Start

### In Plain HTML

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My App with TIA GPC</title>
</head>
<body>
  <h1>My Application</h1>

  <!-- TIA GPC Widget -->
  <tia-gpc-widget
    token="your-license-token-here"
    theme="auto"
    position="bottom-right"
    language="en"
  ></tia-gpc-widget>

  <!-- Auto-Update Loader (loads latest version automatically) -->
  <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"></script>
</body>
</html>
```

### In React

```jsx
import { TiaGPCWidget } from 'tia-gpc-widget';
import 'tia-gpc-widget/styles';

function App() {
  return (
    <div>
      <h1>My Application</h1>
      <TiaGPCWidget
        token="your-license-token-here"
        theme="auto"
        position="bottom-right"
        language="en"
      />
    </div>
  );
}

export default App;
```

---

## 📚 Framework Examples

> **💡 Important:** The examples below may show both installation methods:
> - **Recommended:** Auto-Update Loader (install once, updates automatically)
> - **Legacy:** Direct CDN with fixed version (requires manual updates)
>
> **For new installations, always use the Auto-Update Loader** shown in [Option 1](#option-1-auto-update-loader-recommended).

### 1. React

#### Installation

```bash
npm install tia-gpc-widget
```

#### Basic Usage

```jsx
import { TiaGPCWidget } from 'tia-gpc-widget';
import 'tia-gpc-widget/styles';

function App() {
  return (
    <TiaGPCWidget
      token="your-license-token"
      theme="auto"
      position="bottom-right"
      language="en"
      primaryColor="#2563eb"
      onReady={() => console.log('Widget ready')}
      onError={(error) => console.error('Error:', error)}
    />
  );
}
```

#### Advanced Configuration

```jsx
import { TiaGPCWidget, WIDGET_POSITIONS, THEMES, LANGUAGES } from 'tia-gpc-widget';
import 'tia-gpc-widget/styles';

function App() {
  const handleReady = () => {
    console.log('✅ Widget initialized successfully');
  };

  const handleError = (error) => {
    console.error('❌ Widget error:', error);
  };

  return (
    <TiaGPCWidget
      token="your-license-token"
      theme={THEMES.AUTO}
      position={WIDGET_POSITIONS.BOTTOM_RIGHT}
      language={LANGUAGES.EN}
      primaryColor="#10b981"
      width="450px"
      height="650px"
      autoOpen={false}
      showBranding={true}
      mobileFullscreen={true}
      onReady={handleReady}
      onError={handleError}
      onClose={() => console.log('Widget closed')}
    />
  );
}
```

---

### 2. HTML / Vanilla JavaScript

#### Method 1: Using HTML element directly

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>TIA GPC Widget - Plain HTML</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">
</head>
<body>
  <h1>My Website</h1>

  <!-- Widget as HTML element -->
  <tia-gpc-widget
    token="your-license-token"
    theme="light"
    position="bottom-right"
    language="en"
    primary-color="#3b82f6"
    width="400px"
    height="600px"
    auto-open="false"
    show-branding="true"
  ></tia-gpc-widget>

  <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>

  <!-- Optional events -->
  <script>
    const widget = document.querySelector('tia-gpc-widget');

    widget.addEventListener('ready', () => {
      console.log('Widget ready');
    });

    widget.addEventListener('error', (e) => {
      console.error('Error:', e.detail);
    });

    widget.addEventListener('close', () => {
      console.log('Widget closed');
    });
  </script>
</body>
</html>
```

#### Method 2: Programmatic creation with JavaScript

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>TIA GPC Widget - Programmatic</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">
</head>
<body>
  <h1>My Website</h1>
  <button id="create-widget">Create Widget</button>

  <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
  <script>
    document.getElementById('create-widget').addEventListener('click', () => {
      // Use the global TiaGPC API
      const widget = TiaGPC.create({
        token: 'your-license-token',
        theme: 'auto',
        position: TiaGPC.POSITIONS.BOTTOM_RIGHT,
        language: TiaGPC.LANGUAGES.EN,
        primaryColor: '#3b82f6',
        autoOpen: false,
        onReady: () => console.log('✅ Widget ready'),
        onError: (error) => console.error('❌ Error:', error),
        onClose: () => console.log('Widget closed')
      });

      console.log('Widget created:', widget);
    });

    // View widget information
    TiaGPC.info();
  </script>
</body>
</html>
```

---

### 3. Angular

#### Step 1: Install the widget

```bash
npm install tia-gpc-widget
```

#### Step 2: Configure Angular for Web Components

In `src/main.ts` or `src/polyfills.ts`, add:

```typescript
// Enable Custom Elements (Web Components)
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
```

In your main module (`app.module.ts`):

```typescript
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  schemas: [CUSTOM_ELEMENTS_SCHEMA], // ← Important
  bootstrap: [AppComponent]
})
export class AppModule { }
```

#### Step 3: Import widget files

In `angular.json`, add the CSS and JS files:

```json
{
  "projects": {
    "your-project": {
      "architect": {
        "build": {
          "options": {
            "styles": [
              "src/styles.css",
              "node_modules/tia-gpc-widget/dist/tia-gpc-widget.standalone.css"
            ],
            "scripts": [
              "node_modules/tia-gpc-widget/dist/tia-gpc-widget.standalone.js"
            ]
          }
        }
      }
    }
  }
}
```

#### Step 4: Use the widget in your component

```typescript
// app.component.ts
import { Component, OnInit } from '@angular/core';

declare global {
  interface Window {
    TiaGPC: any;
  }
}

@Component({
  selector: 'app-root',
  template: `
    <h1>My Angular Application</h1>

    <!-- Option 1: Direct HTML element -->
    <tia-gpc-widget
      [attr.token]="widgetToken"
      [attr.theme]="theme"
      [attr.position]="position"
      [attr.language]="language"
      (ready)="onWidgetReady()"
      (error)="onWidgetError($event)"
    ></tia-gpc-widget>
  `
})
export class AppComponent implements OnInit {
  widgetToken = 'your-license-token';
  theme = 'auto';
  position = 'bottom-right';
  language = 'en';

  ngOnInit() {
    console.log('TiaGPC available:', window.TiaGPC);
  }

  onWidgetReady() {
    console.log('✅ TIA GPC widget ready');
  }

  onWidgetError(event: any) {
    console.error('❌ Widget error:', event.detail);
  }
}
```

#### Alternative option: Programmatic creation

```typescript
// app.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>My Angular Application</h1>
    <button (click)="createWidget()">Create Widget</button>
    <div #widgetContainer></div>
  `
})
export class AppComponent implements OnInit {
  ngOnInit() {
    this.createWidget();
  }

  createWidget() {
    if (window.TiaGPC) {
      window.TiaGPC.create({
        token: 'your-license-token',
        theme: 'auto',
        language: 'en',
        onReady: () => console.log('Widget ready'),
        onError: (err: any) => console.error(err)
      });
    }
  }
}
```

---

### 4. ASP.NET / ASPX

#### Option 1: In an ASPX page

```aspx
<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<html>
<head>
    <title>TIA GPC Widget - ASP.NET</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css" />
</head>
<body>
    <form id="form1" runat="server">
        <h1>My ASP.NET Application</h1>

        <!-- TIA GPC Widget -->
        <tia-gpc-widget
            token="<%= ConfigurationManager.AppSettings["TiaGpcToken"] %>"
            theme="auto"
            position="bottom-right"
            language="en"
            primary-color="#2563eb"
        ></tia-gpc-widget>
    </form>

    <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
    <script>
        // Optional events
        document.querySelector('tia-gpc-widget').addEventListener('ready', function() {
            console.log('TIA GPC Widget initialized');
        });
    </script>
</body>
</html>
```

#### Option 2: With Master Page

In your `Site.Master`:

```aspx
<head runat="server">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css" />
</head>
<body>
    <asp:ContentPlaceHolder ID="MainContent" runat="server">
    </asp:ContentPlaceHolder>

    <!-- Global widget -->
    <tia-gpc-widget
        token="<%= GetTiaGpcToken() %>"
        theme="auto"
        language="en"
    ></tia-gpc-widget>

    <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
</body>
```

In your `Site.Master.cs`:

```csharp
public partial class SiteMaster : MasterPage
{
    protected string GetTiaGpcToken()
    {
        return ConfigurationManager.AppSettings["TiaGpcToken"];
    }
}
```

#### Option 3: MVC / Razor

In your layout `_Layout.cshtml`:

```html
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css" />
</head>
<body>
    @RenderBody()

    <!-- TIA GPC Widget -->
    <tia-gpc-widget
        token="@ViewBag.TiaGpcToken"
        theme="auto"
        language="en"
    ></tia-gpc-widget>

    <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
</body>
</html>
```

In your `Controller`:

```csharp
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.TiaGpcToken = ConfigurationManager.AppSettings["TiaGpcToken"];
        return View();
    }
}
```

---

### 5. Vue.js

#### Installation

```bash
npm install tia-gpc-widget
```

#### Configuration

In `main.js` or `main.ts`:

```javascript
import { createApp } from 'vue';
import App from './App.vue';

// Import the standalone widget
import 'tia-gpc-widget/dist/tia-gpc-widget.standalone.js';
import 'tia-gpc-widget/dist/tia-gpc-widget.standalone.css';

const app = createApp(App);

// Configure Vue to ignore custom elements
app.config.compilerOptions.isCustomElement = (tag) => tag === 'tia-gpc-widget';

app.mount('#app');
```

#### Usage in components

```vue
<template>
  <div>
    <h1>My Vue Application</h1>

    <!-- TIA GPC Widget -->
    <tia-gpc-widget
      :token="widgetToken"
      :theme="theme"
      :language="language"
      position="bottom-right"
      @ready="onReady"
      @error="onError"
    ></tia-gpc-widget>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const widgetToken = ref('your-license-token');
const theme = ref('auto');
const language = ref('en');

const onReady = () => {
  console.log('✅ TIA GPC Widget ready');
};

const onError = (event) => {
  console.error('❌ Error:', event.detail);
};

onMounted(() => {
  console.log('TiaGPC available:', window.TiaGPC);
});
</script>
```

---

### 6. Next.js

#### Installation

```bash
npm install tia-gpc-widget
```

#### Usage (with Client Component)

```jsx
// components/TiaWidget.jsx
'use client'; // ← Important: Client Component

import { useEffect } from 'react';

export default function TiaWidget() {
  useEffect(() => {
    // Import widget only on client side
    import('tia-gpc-widget/dist/tia-gpc-widget.standalone.js');
  }, []);

  return (
    <>
      {/* CSS */}
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css" />

      {/* Widget */}
      <tia-gpc-widget
        token={process.env.NEXT_PUBLIC_TIA_GPC_TOKEN}
        theme="auto"
        language="en"
      ></tia-gpc-widget>
    </>
  );
}
```

In your page:

```jsx
// app/page.jsx
import TiaWidget from '@/components/TiaWidget';

export default function Home() {
  return (
    <main>
      <h1>My Next.js App</h1>
      <TiaWidget />
    </main>
  );
}
```

---

### 7. PHP

```php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TIA GPC Widget - PHP</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">
</head>
<body>
    <h1>My PHP Application</h1>

    <?php
    // Get token from environment variables or config
    $tiaGpcToken = getenv('TIA_GPC_TOKEN') ?: 'your-license-token';
    $userLanguage = $_SESSION['user_language'] ?? 'en';
    ?>

    <!-- TIA GPC Widget -->
    <tia-gpc-widget
        token="<?php echo htmlspecialchars($tiaGpcToken); ?>"
        theme="auto"
        position="bottom-right"
        language="<?php echo htmlspecialchars($userLanguage); ?>"
    ></tia-gpc-widget>

    <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
</body>
</html>
```

---

## 🎛️ API & Configuration

### Props/Attributes

All frameworks support the same attributes:

| Attribute | Type | Default | Description |
|----------|------|-------------|-------------|
| `token` | `string` | **Required** | TIA GPC license token |
| `theme` | `'auto' \| 'light' \| 'dark'` | `'auto'` | Widget theme |
| `position` | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | `'bottom-right'` | Screen position |
| `language` | `'es' \| 'en' \| 'fr'` | `'es'` | Widget language |
| `primary-color` | `string` | `'#2563eb'` | Primary color (hexadecimal) |
| `width` | `string` | `'400px'` | Widget width |
| `height` | `string` | `'600px'` | Widget height |
| `api-url` | `string` | Default API | Custom API URL |
| `turnstile-site-key` | `string` | - | Cloudflare Turnstile site key |
| `auto-open` | `boolean` | `false` | Auto-open on load |
| `show-branding` | `boolean` | `true` | Show TIA GPC branding |
| `mobile-fullscreen` | `boolean` | `true` | Fullscreen on mobile |

### Events

| Event | Description | Payload |
|--------|-------------|---------|
| `ready` | Fired when widget is ready | - |
| `error` | Fired when an error occurs | `{ detail: ErrorObject }` |
| `close` | Fired when widget closes | - |

#### Event usage example

```html
<script>
  const widget = document.querySelector('tia-gpc-widget');

  widget.addEventListener('ready', () => {
    console.log('Widget ready');
  });

  widget.addEventListener('error', (e) => {
    console.error('Error:', e.detail);
    // Send to logging system
  });

  widget.addEventListener('close', () => {
    console.log('User closed the widget');
    // Analytics or tracking
  });
</script>
```

### Programmatic API (JavaScript)

The widget exposes a global `TiaGPC` API for programmatic control:

```javascript
// Create widget programmatically
const widget = TiaGPC.create({
  token: 'your-token',
  theme: 'dark',
  language: 'en',
  position: TiaGPC.POSITIONS.BOTTOM_LEFT,
  onReady: () => console.log('Ready'),
  onError: (err) => console.error(err)
});

// Open widget
widget.open();

// Close widget
widget.close();

// View information
TiaGPC.info();

// Available constants
console.log(TiaGPC.POSITIONS);  // { BOTTOM_RIGHT, BOTTOM_LEFT, ... }
console.log(TiaGPC.THEMES);     // { AUTO, LIGHT, DARK }
console.log(TiaGPC.LANGUAGES);  // { ES, EN, FR }
```

---

## 🎨 Customization

### Themes

```html
<!-- Automatic (follows system preferences) -->
<tia-gpc-widget theme="auto"></tia-gpc-widget>

<!-- Light -->
<tia-gpc-widget theme="light"></tia-gpc-widget>

<!-- Dark -->
<tia-gpc-widget theme="dark"></tia-gpc-widget>
```

### Positions

```html
<!-- Bottom right corner (default) -->
<tia-gpc-widget position="bottom-right"></tia-gpc-widget>

<!-- Bottom left corner -->
<tia-gpc-widget position="bottom-left"></tia-gpc-widget>

<!-- Top right corner -->
<tia-gpc-widget position="top-right"></tia-gpc-widget>

<!-- Top left corner -->
<tia-gpc-widget position="top-left"></tia-gpc-widget>
```

### Languages

```html
<!-- Spanish -->
<tia-gpc-widget language="es"></tia-gpc-widget>

<!-- English -->
<tia-gpc-widget language="en"></tia-gpc-widget>

<!-- French -->
<tia-gpc-widget language="fr"></tia-gpc-widget>
```

### Colors

```html
<!-- Custom color -->
<tia-gpc-widget
  primary-color="#10b981"
></tia-gpc-widget>

<!-- Blue (default) -->
<tia-gpc-widget primary-color="#2563eb"></tia-gpc-widget>

<!-- Green -->
<tia-gpc-widget primary-color="#16a34a"></tia-gpc-widget>

<!-- Purple -->
<tia-gpc-widget primary-color="#9333ea"></tia-gpc-widget>
```

---

## 🛠️ Build & Development

### Available scripts

```bash
# Development (dev mode with hot reload)
npm run dev

# Complete build (NPM + Standalone)
npm run build

# Build only for NPM (without bundled React)
npm run build:npm

# Standalone build (with bundled React)
npm run build:standalone

# Lint
npm run lint

# Preview
npm run preview
```

### Generated file structure

```
dist/
├── tia-gpc.es.js              # ESM build for NPM
├── tia-gpc.cjs.js             # CommonJS build for NPM
├── tia-gpc.css                # CSS for NPM build
├── tia-gpc-widget.standalone.js   # Standalone build (IIFE with React)
└── tia-gpc-widget.standalone.css  # CSS for standalone
```

### Which file to use?

| Environment | File to use |
|---------|----------------|
| React, Vue (with build system) | `tia-gpc.es.js` + `tia-gpc.css` |
| Node.js CommonJS | `tia-gpc.cjs.js` + `tia-gpc.css` |
| Plain HTML, Angular, ASP.NET, PHP | `tia-gpc-widget.standalone.js` + `tia-gpc-widget.standalone.css` |

---

## 📤 Publishing

### Publish to NPM (Public)

```bash
# 1. Login to NPM
npm login

# 2. Build the project
npm run build

# 3. Publish
npm publish
```

### Publish to Private NPM / GitLab Package Registry

#### Configure `.npmrc`

Create an `.npmrc` file in the project root:

```ini
# For GitLab Package Registry
@your-scope:registry=https://gitlab.com/api/v4/projects/YOUR_PROJECT_ID/packages/npm/
//gitlab.com/api/v4/projects/YOUR_PROJECT_ID/packages/npm/:_authToken=${CI_JOB_TOKEN}
```

#### Update `package.json`

```json
{
  "name": "@your-scope/tia-gpc-widget",
  "publishConfig": {
    "@your-scope:registry": "https://gitlab.com/api/v4/projects/YOUR_PROJECT_ID/packages/npm/"
  }
}
```

#### Publish

```bash
npm run build
npm publish
```

### CDN Distribution

After publishing to npm, your package is automatically available on these CDNs:

#### jsDelivr
```html
<script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">
```

#### unpkg
```html
<script src="https://unpkg.com/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">
```

**Note:** CDNs may take 5-10 minutes to sync after publishing to npm.

### Manual Distribution

Copy files from `dist/` to your web server:

```bash
# Copy standalone files to server
cp dist/tia-gpc-widget.standalone.* /var/www/html/assets/
```

---

## 🔐 Getting a License Token

To use this widget you need a TIA GPC license token. Contact the TIA team to get your token:

- **Email**: support@tia.com
- **Web**: https://tia.com/gpc

---

## 📊 Bundle Sizes

| File | Size (gzip) | Description |
|---------|---------------|-------------|
| `tia-gpc.es.js` | ~45 KB | NPM build (without React) |
| `tia-gpc-widget.standalone.js` | ~180 KB | Standalone build (with React) |
| `*.css` | ~15 KB | Styles |

The standalone bundle is larger because it includes React and all dependencies.

---

## 🐛 Troubleshooting

### Widget doesn't appear

1. Verify you included both files (JS and CSS)
2. Check browser console for errors
3. Make sure the token is valid

### Error: "customElements.define() called with incorrect arguments"

- In Angular: Add `CUSTOM_ELEMENTS_SCHEMA` to your module
- In Vue: Configure `isCustomElement` in compiler options

### CSS Conflicts

The widget uses `gpc-` prefixes on all classes to avoid conflicts. If there are still issues, you can increase specificity:

```css
.your-container tia-gpc-widget {
  /* your custom styles */
}
```

### React is not defined (in standalone build)

If you see this error, make sure you're using the `standalone.js` file and not the regular NPM build.

---

## 📝 License

UNLICENSED - Internal use by TIA

---

## 👥 Support

For technical support:

- **Email**: support@tia.com
- **GitLab Issues**: https://gitlab.com/softia/tiagpc-frontend/issues
- **Documentation**: This README

---

## 🚀 Changelog

### v1.0.6 (2025-01-11)

- ✨ Added CDN support via jsDelivr and unpkg
- 📝 Updated documentation to English
- 🔧 Added `unpkg` and `jsdelivr` fields to package.json

### v1.0.0 (2025-01-10)

- ✨ Initial release
- ✅ React support
- ✅ Standalone build for HTML/Angular/ASP.NET
- ✅ Web Component API
- ✅ Light/dark themes
- ✅ Internationalization (ES/EN/FR)
- ✅ Full customization

---

## 📚 Loader Advanced Usage

### What is the Auto-Update Loader?

The **TIA GPC Widget Loader** is a revolutionary approach to widget distribution that solves the update problem:

- **Traditional approach**: Clients must manually update the version number in their code every time you release
- **Loader approach**: Clients install once, you control which version they receive via `version.json`

### How it Works

1. **Client installs the loader** (one time only):
   ```html
   <script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"></script>
   ```

2. **Loader fetches** `version.json` to determine which widget version to load

3. **Loader dynamically loads** the appropriate widget version

4. **You publish a new version**:
   ```bash
   npm run build  # Automatically updates version.json
   npm publish
   ```

5. **All clients automatically receive the new version** (within minutes, when CDN syncs)

### Configuration Options

#### Loader Attributes

| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `data-channel` | `'stable' \| 'beta'` | `'stable'` | Distribution channel |
| `data-version` | `string` | `null` | Pin to specific version (disables auto-update) |
| `data-debug` | `boolean` | `false` | Enable debug logging |
| `data-api-url` | `string` | `null` | Analytics endpoint URL |

#### Examples

**Use beta channel:**
```html
<script
  src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"
  data-channel="beta"
></script>
```

**Pin to specific version (no auto-update):**
```html
<script
  src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"
  data-version="1.0.8"
></script>
```

**Enable debug mode:**
```html
<script
  src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"
  data-debug="true"
></script>
```

### Loader Events

The loader emits custom events you can listen to:

```javascript
// Widget loaded successfully
window.addEventListener('tia-gpc-loader-ready', (event) => {
  console.log('Widget loaded:', event.detail);
  // event.detail = {
  //   version: "1.0.9",
  //   loadTime: 1234,  // milliseconds
  //   attempts: 1,
  //   channel: "stable"
  // }
});

// Widget failed to load
window.addEventListener('tia-gpc-loader-error', (event) => {
  console.error('Widget error:', event.detail);
  // event.detail = {
  //   error: "Failed to load...",
  //   attempts: 3,
  //   version: "1.0.9"
  // }
});
```

### Loader API

The loader exposes a global `TiaGPCLoader` object:

```javascript
// Get loader version
console.log(window.TiaGPCLoader.version);  // "1.0.0"

// Reload widget
window.TiaGPCLoader.reload();

// Get configuration
console.log(window.TiaGPCLoader.config);
```

### Version Control with version.json

The `version.json` file controls which version is served to clients:

```json
{
  "version": "1.0.9",
  "stable": {
    "version": "1.0.9",
    "js": "https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.js",
    "css": "https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.9/dist/tia-gpc-widget.standalone.css",
    "cdn": "jsdelivr"
  },
  "beta": {
    "version": "1.1.0-beta",
    "js": "https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.1.0-beta/dist/tia-gpc-widget.standalone.js",
    "css": "https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.1.0-beta/dist/tia-gpc-widget.standalone.css",
    "cdn": "jsdelivr"
  }
}
```

This file is automatically generated when you run `npm run build`.

### Deployment Workflow

#### Before (without loader):
```bash
# 1. Make changes to widget
# 2. Build
npm run build

# 3. Publish to npm
npm publish

# ❌ Clients must manually update their code:
# <script src="...@1.0.6/..."></script>  →  <script src="...@1.0.7/..."></script>
```

#### After (with loader):
```bash
# 1. Make changes to widget
# 2. Build (automatically updates version.json)
npm run build

# 3. Publish to npm
npm publish

# ✅ All clients automatically receive the new version!
# No manual updates required!
```

### Advanced: Gradual Rollout

You can manually edit `version.json` to implement gradual rollouts:

```json
{
  "stable": {
    "version": "1.0.9",
    "rollout": {
      "percentage": 50,  // Only 50% of users get this version
      "whitelist": ["client-id-1", "client-id-2"],
      "blacklist": ["problematic-client"]
    }
  }
}
```

Note: Rollout logic must be implemented on your backend.

### Migration Guide

#### Migrating from Direct CDN Links

**Before:**
```html
<script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tia-gpc-widget@1.0.6/dist/tia-gpc-widget.standalone.css">

<tia-gpc-widget token="xxx"></tia-gpc-widget>
```

**After:**
```html
<script src="https://cdn.jsdelivr.net/npm/tia-gpc-widget@latest/dist/loader.min.js"></script>

<tia-gpc-widget token="xxx"></tia-gpc-widget>
```

That's it! The loader handles everything else.

### Troubleshooting

#### Loader not loading widget

1. Open browser console and check for errors
2. Enable debug mode: `data-debug="true"`
3. Check network tab for failed requests
4. Verify `version.json` is accessible

#### Widget not updating

1. Clear browser cache
2. Check that `version.json` has the correct version
3. Wait for CDN to sync (can take 5-10 minutes)
4. Check if client is using `data-version` (which pins to specific version)

#### Using with Content Security Policy (CSP)

If your site uses CSP, you may need to add:

```html
<meta http-equiv="Content-Security-Policy" content="
  script-src 'self' https://cdn.jsdelivr.net https://unpkg.com;
  style-src 'self' https://cdn.jsdelivr.net https://unpkg.com;
  connect-src 'self' https://cdn.jsdelivr.net https://unpkg.com;
">
```

### Examples

See complete examples in the `/examples` folder:
- `examples/loader-usage.html` - Complete loader demo with all features

---

**Built with ❤️ by the TIA team**
