# Pagination

A smart pagination component that provides intuitive page navigation with intelligent page number display and gap handling for large datasets.

## Features

- **Smart Page Display**: Intelligent algorithm to show relevant page numbers with gaps
- **Multiple Styles**: Support for plain, round, and circle visual styles
- **Size Variants**: Normal and big size options
- **Click Navigation**: Easy page selection with click handlers
- **Responsive Logic**: Adapts page display based on current position
- **Boundary Handling**: Automatic boundary validation and correction
- **Gap Indication**: Shows ellipsis (...) for non-consecutive page ranges
- **Current Page Highlighting**: Visual indication of the active page

## Installation

```bash
npm install @ticatec/uniface-element
```

## Basic Usage

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let currentPage = 1;
  let totalPages = 10;
  
  function handlePageChange(page) {
    currentPage = page;
    console.log('Page changed to:', page);
  }
</script>

<Pagination 
  pageNo={currentPage}
  pageCount={totalPages}
  onPageChange={handlePageChange}
/>
```

## API Reference

### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `pageNo` | `number` | `1` | Current active page number |
| `pageCount` | `number` | `0` | Total number of pages |
| `type` | `'plain' \| 'round' \| 'circle'` | `'round'` | Visual style variant |
| `style` | `string` | `''` | Custom CSS styles |
| `big` | `boolean` | `false` | Enable larger size variant |
| `onPageChange` | `OnPageChange` | `undefined` | Page change event handler |

### Types

```typescript
export type OnPageChange = (page: number) => void;
```

## Page Display Logic

The pagination component uses intelligent logic to display page numbers:

- **1-5 pages**: Show all page numbers
- **6+ pages**: Show first page, relevant middle pages, and last page with gaps
- **Current page positioning**: Adjusts display based on current page position
- **Gap representation**: Uses ellipsis (...) for non-consecutive ranges

## Examples

### Basic Data Table Pagination

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let currentPage = 1;
  let totalPages = 20;
  let itemsPerPage = 10;
  let totalItems = 200;
  
  let data = [];
  
  function loadData(page) {
    // Simulate API call
    const startIndex = (page - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    
    data = Array.from({ length: itemsPerPage }, (_, i) => ({
      id: startIndex + i + 1,
      name: `Item ${startIndex + i + 1}`,
      value: Math.random() * 100
    }));
  }
  
  function handlePageChange(page) {
    currentPage = page;
    loadData(page);
  }
  
  // Load initial data
  loadData(currentPage);
</script>

<div class="data-table">
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Value</th>
      </tr>
    </thead>
    <tbody>
      {#each data as item}
        <tr>
          <td>{item.id}</td>
          <td>{item.name}</td>
          <td>{item.value.toFixed(2)}</td>
        </tr>
      {/each}
    </tbody>
  </table>
  
  <div class="pagination-wrapper">
    <Pagination 
      pageNo={currentPage}
      pageCount={totalPages}
      onPageChange={handlePageChange}
      type="round"
    />
  </div>
</div>

<style>
  .data-table {
    width: 100%;
  }
  
  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
  }
  
  th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
  }
  
  th {
    background-color: #f5f5f5;
    font-weight: 600;
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
</style>
```

### Search Results Pagination

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let searchQuery = '';
  let currentPage = 1;
  let totalPages = 0;
  let results = [];
  let loading = false;
  
  async function performSearch(query, page = 1) {
    if (!query.trim()) return;
    
    loading = true;
    
    try {
      // Simulate API search
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const mockResults = Array.from({ length: 10 }, (_, i) => ({
        id: i + 1,
        title: `Search Result ${i + 1} for "${query}"`,
        description: `This is a description for search result ${i + 1}`,
        url: `https://example.com/result-${i + 1}`
      }));
      
      results = mockResults;
      totalPages = Math.ceil(100 / 10); // Assume 100 total results
      currentPage = page;
    } finally {
      loading = false;
    }
  }
  
  function handlePageChange(page) {
    performSearch(searchQuery, page);
  }
  
  function handleSearch() {
    currentPage = 1;
    performSearch(searchQuery, 1);
  }
</script>

<div class="search-container">
  <div class="search-box">
    <input 
      type="text" 
      bind:value={searchQuery}
      placeholder="Enter search query..."
      on:keydown={(e) => e.key === 'Enter' && handleSearch()}
    />
    <button on:click={handleSearch}>Search</button>
  </div>
  
  {#if loading}
    <div class="loading">Searching...</div>
  {:else if results.length > 0}
    <div class="results">
      {#each results as result}
        <div class="result-item">
          <h3>{result.title}</h3>
          <p>{result.description}</p>
          <a href={result.url} target="_blank">{result.url}</a>
        </div>
      {/each}
      
      <Pagination 
        pageNo={currentPage}
        pageCount={totalPages}
        onPageChange={handlePageChange}
        type="circle"
        style="margin-top: 30px;"
      />
    </div>
  {/if}
</div>

<style>
  .search-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .search-box {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }
  
  .search-box input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .search-box button {
    padding: 10px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .loading {
    text-align: center;
    padding: 40px;
    color: #666;
  }
  
  .result-item {
    padding: 20px 0;
    border-bottom: 1px solid #eee;
  }
  
  .result-item h3 {
    margin: 0 0 10px 0;
    color: #007bff;
  }
  
  .result-item p {
    margin: 0 0 10px 0;
    color: #666;
  }
  
  .result-item a {
    color: #28a745;
    text-decoration: none;
  }
</style>
```

### Blog Posts with Different Styles

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let posts = [];
  let currentPage = 1;
  let totalPages = 15;
  let paginationStyle = 'round';
  
  function loadPosts(page) {
    // Simulate loading blog posts
    posts = Array.from({ length: 5 }, (_, i) => ({
      id: (page - 1) * 5 + i + 1,
      title: `Blog Post ${(page - 1) * 5 + i + 1}`,
      excerpt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit...',
      author: `Author ${i + 1}`,
      date: new Date(2024, 0, (page - 1) * 5 + i + 1).toLocaleDateString()
    }));
  }
  
  function handlePageChange(page) {
    currentPage = page;
    loadPosts(page);
  }
  
  // Load initial posts
  loadPosts(currentPage);
</script>

<div class="blog-container">
  <div class="style-selector">
    <label>Pagination Style:</label>
    <select bind:value={paginationStyle}>
      <option value="plain">Plain</option>
      <option value="round">Round</option>
      <option value="circle">Circle</option>
    </select>
  </div>
  
  <div class="posts">
    {#each posts as post}
      <article class="post">
        <h2>{post.title}</h2>
        <div class="post-meta">
          By {post.author} on {post.date}
        </div>
        <p>{post.excerpt}</p>
        <a href="/posts/{post.id}">Read more</a>
      </article>
    {/each}
  </div>
  
  <div class="pagination-container">
    <Pagination 
      pageNo={currentPage}
      pageCount={totalPages}
      onPageChange={handlePageChange}
      type={paginationStyle}
    />
  </div>
</div>

<style>
  .blog-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .style-selector {
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .style-selector select {
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .post {
    padding: 30px 0;
    border-bottom: 1px solid #eee;
  }
  
  .post h2 {
    margin: 0 0 10px 0;
    color: #333;
  }
  
  .post-meta {
    color: #666;
    font-size: 14px;
    margin-bottom: 15px;
  }
  
  .post p {
    margin: 0 0 15px 0;
    line-height: 1.6;
  }
  
  .post a {
    color: #007bff;
    text-decoration: none;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 40px;
  }
</style>
```

### Gallery with Large Pagination

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let images = [];
  let currentPage = 1;
  let totalPages = 25;
  
  function loadImages(page) {
    // Simulate loading gallery images
    images = Array.from({ length: 12 }, (_, i) => ({
      id: (page - 1) * 12 + i + 1,
      src: `https://picsum.photos/300/200?random=${(page - 1) * 12 + i + 1}`,
      title: `Image ${(page - 1) * 12 + i + 1}`,
      description: `Beautiful image number ${(page - 1) * 12 + i + 1}`
    }));
  }
  
  function handlePageChange(page) {
    currentPage = page;
    loadImages(page);
    // Scroll to top after page change
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
  
  // Load initial images
  loadImages(currentPage);
</script>

<div class="gallery-container">
  <h1>Photo Gallery</h1>
  <p>Page {currentPage} of {totalPages}</p>
  
  <div class="image-grid">
    {#each images as image}
      <div class="image-card">
        <img src={image.src} alt={image.title} loading="lazy" />
        <div class="image-info">
          <h3>{image.title}</h3>
          <p>{image.description}</p>
        </div>
      </div>
    {/each}
  </div>
  
  <div class="pagination-wrapper">
    <Pagination 
      pageNo={currentPage}
      pageCount={totalPages}
      onPageChange={handlePageChange}
      type="round"
      big
    />
  </div>
</div>

<style>
  .gallery-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .gallery-container h1 {
    text-align: center;
    margin-bottom: 10px;
  }
  
  .gallery-container p {
    text-align: center;
    color: #666;
    margin-bottom: 30px;
  }
  
  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 40px;
  }
  
  .image-card {
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: transform 0.2s;
  }
  
  .image-card:hover {
    transform: translateY(-2px);
  }
  
  .image-card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
  }
  
  .image-info {
    padding: 15px;
  }
  
  .image-info h3 {
    margin: 0 0 5px 0;
    font-size: 16px;
  }
  
  .image-info p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
  }
</style>
```

### E-commerce Product Listing

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let products = [];
  let currentPage = 1;
  let totalPages = 12;
  let sortBy = 'name';
  
  function loadProducts(page, sort = 'name') {
    // Simulate loading products
    products = Array.from({ length: 8 }, (_, i) => ({
      id: (page - 1) * 8 + i + 1,
      name: `Product ${(page - 1) * 8 + i + 1}`,
      price: (Math.random() * 100 + 10).toFixed(2),
      rating: (Math.random() * 2 + 3).toFixed(1),
      image: `https://picsum.photos/250/250?random=${(page - 1) * 8 + i + 1}`,
      description: 'High quality product with excellent features'
    }));
    
    // Sort products
    if (sort === 'price') {
      products.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
    } else if (sort === 'rating') {
      products.sort((a, b) => parseFloat(b.rating) - parseFloat(a.rating));
    }
  }
  
  function handlePageChange(page) {
    currentPage = page;
    loadProducts(page, sortBy);
  }
  
  function handleSortChange() {
    loadProducts(currentPage, sortBy);
  }
  
  // Load initial products
  loadProducts(currentPage, sortBy);
</script>

<div class="shop-container">
  <div class="shop-header">
    <h1>Our Products</h1>
    <div class="sort-controls">
      <label>Sort by:</label>
      <select bind:value={sortBy} on:change={handleSortChange}>
        <option value="name">Name</option>
        <option value="price">Price</option>
        <option value="rating">Rating</option>
      </select>
    </div>
  </div>
  
  <div class="products-grid">
    {#each products as product}
      <div class="product-card">
        <img src={product.image} alt={product.name} />
        <div class="product-info">
          <h3>{product.name}</h3>
          <p class="description">{product.description}</p>
          <div class="product-details">
            <span class="price">${product.price}</span>
            <span class="rating">★ {product.rating}</span>
          </div>
          <button class="add-to-cart">Add to Cart</button>
        </div>
      </div>
    {/each}
  </div>
  
  <div class="pagination-footer">
    <Pagination 
      pageNo={currentPage}
      pageCount={totalPages}
      onPageChange={handlePageChange}
      type="round"
    />
    <div class="page-info">
      Showing page {currentPage} of {totalPages}
    </div>
  </div>
</div>

<style>
  .shop-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .shop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
  }
  
  .sort-controls {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .sort-controls select {
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 40px;
  }
  
  .product-card {
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    transition: box-shadow 0.2s;
  }
  
  .product-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .product-card img {
    width: 100%;
    height: 250px;
    object-fit: cover;
  }
  
  .product-info {
    padding: 16px;
  }
  
  .product-info h3 {
    margin: 0 0 8px 0;
    font-size: 18px;
  }
  
  .description {
    color: #666;
    font-size: 14px;
    margin: 0 0 12px 0;
  }
  
  .product-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .price {
    font-size: 20px;
    font-weight: bold;
    color: #007bff;
  }
  
  .rating {
    color: #ff9500;
  }
  
  .add-to-cart {
    width: 100%;
    padding: 10px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
  }
  
  .add-to-cart:hover {
    background: #0056b3;
  }
  
  .pagination-footer {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .page-info {
    color: #666;
    font-size: 14px;
  }
</style>
```

### Mobile-Responsive Pagination

```svelte
<script>
  import Pagination from '@ticatec/uniface-element/Pagination';
  
  let currentPage = 1;
  let totalPages = 20;
  let isMobile = false;
  
  import { onMount } from 'svelte';
  
  onMount(() => {
    const checkMobile = () => {
      isMobile = window.innerWidth < 768;
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    
    return () => window.removeEventListener('resize', checkMobile);
  });
  
  function handlePageChange(page) {
    currentPage = page;
  }
</script>

<div class="responsive-container">
  <div class="content">
    <h2>Responsive Pagination Example</h2>
    <p>This pagination adapts to mobile and desktop screens.</p>
    
    <!-- Sample content -->
    <div class="sample-content">
      {#each Array(10) as _, i}
        <div class="content-item">
          Item {(currentPage - 1) * 10 + i + 1}
        </div>
      {/each}
    </div>
  </div>
  
  <div class="pagination-section">
    <Pagination 
      pageNo={currentPage}
      pageCount={totalPages}
      onPageChange={handlePageChange}
      type="round"
      style={isMobile ? 'transform: scale(0.9);' : ''}
    />
    
    {#if isMobile}
      <div class="mobile-info">
        Page {currentPage} of {totalPages}
      </div>
    {/if}
  </div>
</div>

<style>
  .responsive-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .content h2 {
    text-align: center;
    margin-bottom: 10px;
  }
  
  .content p {
    text-align: center;
    color: #666;
    margin-bottom: 30px;
  }
  
  .sample-content {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 16px;
    margin-bottom: 30px;
  }
  
  .content-item {
    padding: 20px;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    text-align: center;
  }
  
  .pagination-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .mobile-info {
    font-size: 14px;
    color: #666;
  }
  
  @media (max-width: 767px) {
    .sample-content {
      grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
    
    .content-item {
      padding: 16px;
      font-size: 14px;
    }
  }
</style>
```

## Best Practices

1. **Page State Management**: Always maintain current page state properly
2. **Loading States**: Show loading indicators during page transitions
3. **URL Synchronization**: Keep URL in sync with current page when appropriate
4. **Accessibility**: Ensure keyboard navigation and screen reader support
5. **Mobile Optimization**: Consider touch-friendly sizing on mobile devices
6. **Performance**: Implement virtual scrolling for very large datasets
7. **User Feedback**: Provide clear indication of current page and total pages

## Styling

The Pagination component provides several CSS classes for customization:

```css
.uniface-pagination-panel {
  display: flex;
  align-items: center;
  gap: 4px;
}

.uniface-pagination-panel.big {
  /* Larger size variant */
}

.uniface-page-no {
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.uniface-page-no:hover {
  background-color: #f5f5f5;
}

.uniface-page-no.selected {
  background-color: #007bff;
  color: white;
}

.uniface-page-gap {
  padding: 8px 4px;
  color: #666;
}

/* Style variants */
.uniface-pagination-panel.round .uniface-page-no {
  border-radius: 8px;
}

.uniface-pagination-panel.circle .uniface-page-no {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uniface-pagination-panel.plain .uniface-page-no {
  border-radius: 0;
  border-bottom: 2px solid transparent;
}

.uniface-pagination-panel.plain .uniface-page-no.selected {
  background-color: transparent;
  color: #007bff;
  border-bottom-color: #007bff;
}
```

## Accessibility

- Keyboard navigation support (Tab, Enter, Space)
- ARIA labels for screen readers
- Focus management and visual indicators
- High contrast mode compatibility
- Semantic HTML structure

## Related Components

- [PaginationPanel](../pagination-panel/README.md) - Full pagination panel with page size controls
- [DataTable](../data-table/README.md) - Data table with built-in pagination
- [Button](../button/README.md) - For custom pagination controls