# Add to cart

Xác nhận đúng sản phẩm và giá sau khi giỏ hàng đã cập nhật thành công.

## Key rules

- Classic: xác nhận thêm giỏ nằm trong nút bằng `AddToCartFeedback`; receipt cũng có thể xuất hiện trong thread.
- AI Mode: tin chat có `cartConfirmation` hiện `CartConfirmation`; nút thêm giỏ vẫn dùng `AddToCartFeedback`.
- Admin: receipt chỉ đọc; action View cart chỉ hiện khi caller truyền `onViewCart`.
- Chỉ đặt `added` true sau khi server xác nhận; không suy ra từ thao tác click.

## Use when / Avoid

Dùng sau khi giỏ đã cập nhật thành công. Lỗi thêm giỏ và xác nhận đơn hàng thuộc pattern khác.

### Use instead

| Component | Use when |
| --- | --- |
| `AddToCartFeedback` | Xác nhận trong nút thêm giỏ trên Classic và AI Mode. |
| `CartConfirmation` | Receipt hệ thống của AI Mode; Admin dùng bản chỉ đọc qua block. |
| `Button` | Nút bao ngoài trên Classic; xem trang Button. |

## Entry points

| Surface | Owner |
| --- | --- |
| Classic | Nút thêm giỏ của ProductCard |
| AI Mode | Nút thêm giỏ của ProductCard và receipt trong ChatMessage |
| Admin | Block cart-confirmation trong inbox |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| Classic | Đang thêm | Khách bấm nút | Nút disabled, Spinner small, `aria-busy` | Spinner | Add to cart / Add to cart | Theo request của caller |
| Classic | Đã thêm | Caller đặt added true | Label `opacity: 0`, check vào rồi vẽ nét | AddToCartFeedback | Added to cart / Added to cart (announcement) | 150ms rồi 300ms; tháo sau `2000` milliseconds |
| Classic | Về trạng thái nghỉ | Landing xong | Status về idle sau `ADDED_RESET_MS` | useAddToCartFeedback | Add to cart / Add to cart | Hook reset sau landing |
| Classic | Lỗi | Request thất bại | `addError` với `role="alert"` | addError | Could not add to cart / Could not add to cart | Theo response |
| AI Mode | Đang thêm | Khách bấm nút | Class `is-loading`, nút disabled | AddToCartButton | Add to cart / Add to cart | Theo request của caller |
| AI Mode | Đã thêm | `isAdded` true | Check trong nút; announcement đọc `successLabel` | AddToCartFeedback | Added to cart / Added to cart | 150ms rồi 300ms; tháo sau `1650` |
| AI Mode | Receipt | Tin chat có `cartConfirmation` | Card receipt trong luồng chat | CartConfirmation | Added to cart / Added to cart | Receipt không tự biến mất |
| AI Mode | Mở giỏ | Khách bấm View cart | Mở sidebar bag | CartConfirmation | View cart / View cart | Ngay khi bấm |
| Admin | Receipt chỉ đọc | Block cart-confirmation | Card receipt không có View cart | CartConfirmationBlock | Added to cart / Added to cart | Receipt không tự biến mất |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| Classic | Nút hết hàng hoặc admin xem | Nút disabled; không có check |
| Classic | Reduced motion | Check và nét vẽ tắt animation; label vẫn fade |
| AI Mode | Ảnh thiếu hoặc lỗi | Body phủ cả grid, không có khung ảnh trống |
| AI Mode | Receipt không hợp lệ | Không render gì |
| AI Mode | Label nút dài | Nowrap và ellipsis |
| Admin | Người xem là admin | Không có View cart |

## Live preview

Classic: bubble thu gọn là fixture từ chatty-icon-button; Current: FloatButtonWidget, chưa có element. Bag và menu (…) ở header: N/A trong preview.

AI Mode: SignIn, EmailContinue, Reset và Bag ở header: N/A trong preview.

### Standard

Example (Standard) — Widget thread Standard; tương tác bằng dữ liệu fixture.

```js
import '@avada/chatty-ui/tokens/tokens.css';
import {html} from 'lit';
import {IconClose, IconMessage} from '@avada/chatty-ui/elements/icon-glyphs.js';
import '@avada/chatty-ui/elements/surface.js';
import '@avada/chatty-ui/elements/avatar.js';
import '@avada/chatty-ui/elements/badge.js';
import '@avada/chatty-ui/elements/icon-button.js';
import '@avada/chatty-ui/elements/launcher.js';
import '@avada/chatty-ui/elements/button.js';
import {sameGroup} from '@avada/chatty-ui/behaviors/messages.js';

// Reference viewport: 1280 × 900 desktop, 390 × 900 mobile.
const sizes = {
  classic: {width: 400, height: 700},
  'ai-mode': {width: 820, height: 657},
  admin: {width: 527, height: 842}
};
const question = {
  id: 'question',
  senderType: 'customer',
  text: 'Can you help me?',
  createdAt: '2026-01-15T10:00:00Z'
};

/** Viewport-relative sizing survives the initial hidden iframe layout. */
function widgetSize(surface) {
  const mode = new URLSearchParams(location.search).get('mobile');
  const isMobile = mode === null ? innerWidth < 900 : mode === 'true';
  const width = `min(${sizes[surface].width}px, max(0px, 100vw - 40px))`;
  const height = isMobile
    ? `min(${surface === 'admin' ? 848 : 888}px, round(down, calc(${width} * 2.2), 1px))`
    : `${sizes[surface].height}px`;
  return {...sizes[surface], height, mobile: isMobile};
}

/** Local immutable message state with real subscriptions for live previews. */
function fixtureStore(initial) {
  let state = {messages: initial};
  const listeners = new Set();
  return {
    getState: () => state,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    setMessages(messages) {
      state = {messages};
      listeners.forEach(listener => listener());
    }
  };
}

/** Appends the viewer message without replacing the existing conversation. */
function appendViewer(store, surface, text) {
  const message = {
    id: `viewer-${store.getState().messages.length}`,
    senderType: surface === 'admin' ? 'agent' : 'customer',
    senderMeta: {name: surface === 'admin' ? 'Alex' : 'You'},
    text,
    createdAt: new Date().toISOString()
  };
  store.setMessages([...store.getState().messages, message]);
}

/**
 * One shell owns surface sizing, header, thread and composer for every pattern.
 * @param {string} surface
 * @param {Object} store
 * @param {Object} strings
 * @param {Object} content
 * @param {Function} renderMessage
 * @param {Function} onSend
 * @param {Object} registry
 * @param {boolean} composerHidden
 * @param {string} title
 * @param {Object} headerStart
 * @param {Object} headerActions
 * @param {boolean} sheet
 * @param {string | null} status
 * @returns {Object}
 */
function patternShell({
  surface,
  store,
  strings = {header: 'Store assistant', message: 'Message', send: 'Send'},
  content,
  renderMessage,
  onSend,
  registry,
  title,
  headerStart,
  headerActions,
  status = 'online',
  sheet = false,
  composerHidden = false
}) {
  const size = widgetSize(surface);
  const mobileSheet = sheet && size.mobile;
  if (mobileSheet) {
    size.width = 'none';
    size.height = 'calc(100dvh - 12px)';
  }
  const toggle = (event, closed) => {
    const frame = event.currentTarget.closest('[data-pattern-frame]');
    const panel = frame.querySelector('chatty-surface');
    const launcher = frame.querySelector('[data-pattern-launcher]');
    panel.hidden = closed;
    frame.dataset.closed = String(closed);
    const background = frame.querySelector('[data-sheet-page]');
    if (background) background.inert = !closed && surface === 'ai-mode';
    launcher.hidden = !closed;
    if (closed) {
      launcher.style.insetBlockEnd = `${Math.max(surface === 'ai-mode' ? 40 : 16, frame.getBoundingClientRect().bottom - innerHeight + 20)}px`;
      launcher.focus({preventScroll: true});
    } else {
      const composer = panel.querySelector('chatty-composer');
      const input = !composer.hidden
        ? composer.renderRoot.querySelector('textarea')
        : (panel
            .querySelector('chatty-contact-form:not([hidden])')
            ?.renderRoot.querySelector('chatty-text-field') ??
          panel.querySelector('form chatty-text-field') ??
          panel.querySelector('[data-welcome-invitation]:not([hidden]) chatty-button') ??
          panel
            .querySelector('chatty-pre-chat:not([hidden])')
            ?.renderRoot.querySelector('chatty-button'));
      input?.focus({preventScroll: true});
    }
  };
  const sender = message => {
    const content = renderMessage?.(message) ?? {};
    const messages = store.getState().messages;
    const previous = messages[messages.indexOf(message) - 1];
    if (message.senderType !== 'bot' || sameGroup(message, previous)) return content;
    return {
      ...content,
      sender: html`<span style="display:inline-flex;align-items:center;gap:6px"
        ><chatty-avatar size="sm" label="Assistant">A</chatty-avatar
        >${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}</span
      >`
    };
  };
  return html`<style>
      [data-pattern-frame] {
        display: flex;
        position: relative;
        justify-content: center;
        inline-size: 100%;
        min-inline-size: 0;
      }
      [data-pattern-frame='classic'] {
        justify-content: flex-end;
      }
      [data-pattern-frame] chatty-surface::part(header) {
        padding: 0;
      }
      [data-pattern-frame='classic'] chatty-surface::part(header),
      [data-pattern-frame='ai-mode'] chatty-surface::part(header) {
        border-bottom-width: 0;
      }
      [data-pattern-frame] [hidden] {
        display: none !important;
      }
      [data-pattern-header] {
        display: flex;
        align-items: center;
        gap: 10px;
        box-sizing: border-box;
        min-inline-size: 0;
        block-size: 52px;
        padding: 0 16px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] {
        block-size: 56px;
        background: var(--chatty-color-accent);
        color: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-icon-button {
        --chatty-color-border-focus: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='admin'] [data-pattern-header] {
        block-size: 68px;
        padding: 8px 12px;
      }
      [data-pattern-header] chatty-avatar {
        --chatty-avatar-size: 32px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar {
        --chatty-avatar-background: #fff;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar::part(base) {
        color: #303030;
        border: 1px solid #767676;
      }
      [data-pattern-actions] {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      [data-pattern-title] {
        flex: 1;
        min-inline-size: 0;
        display: flex;
        flex-direction: column;
      }
      [data-pattern-frame='admin'] [data-pattern-title] {
        gap: 4px;
      }
      [data-pattern-frame='admin'] [data-pattern-title] strong {
        display: flex;
        align-items: center;
        min-block-size: 28px;
        font: var(--p-font-weight-semibold, 650) var(--p-text-heading-md-font-size, 14px) /
          var(--p-text-heading-md-font-line-height, 20px) var(--p-font-family-sans, system-ui);
      }
      [data-pattern-title] strong {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      [data-pattern-header] chatty-icon-button {
        --chatty-icon-button-size: 32px;
        --chatty-icon-button-color: currentColor;
      }
      @media (max-width: 899px), (pointer: coarse) {
        [data-pattern-header] chatty-icon-button {
          --chatty-icon-button-size: 44px;
        }
      }
      [data-pattern-launcher] {
        position: absolute;
        inset-inline-end: 0;
        inset-block-end: 0;
      }
      [data-pattern-frame='ai-mode'] [data-pattern-launcher] {
        inset-inline-end: auto;
        inset-inline-start: 50%;
        transform: translateX(-50%);
      }
      [data-pattern-frame='classic'] [data-pattern-launcher] {
        --chatty-icon-button-size: 56px;
        border-radius: 50%;
        background: var(--chatty-color-accent);
        --chatty-icon-button-color: var(--chatty-color-on-accent);
      }
      [data-sheet-mobile='true'] {
        position: fixed;
        inset: 0;
        inline-size: 100vw;
      }
      [data-sheet-mobile='true'] chatty-surface::part(base) {
        border-radius: 16px 16px 0 0;
      }
      [data-sheet-mobile='true'] chatty-surface {
        position: relative;
        z-index: 2;
        margin-block-start: 12px;
      }
      [data-sheet-page],
      [data-sheet-scrim] {
        position: absolute;
        inset: 0;
        box-sizing: border-box;
      }
      [data-sheet-page] {
        padding: 20px;
        background: var(--chatty-color-bg-surface);
        color: var(--chatty-color-text);
      }
      [data-sheet-scrim] {
        z-index: 1;
        border: 0;
        background: rgb(0 0 0 / 40%);
        animation: sheet-scrim 400ms ease;
      }
      [data-sheet-mobile='true'][data-closed='true'] [data-sheet-scrim] {
        display: none;
      }
      [data-sheet-mobile='true'] [data-pattern-launcher] {
        z-index: 3;
      }
      @keyframes sheet-scrim {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        [data-sheet-scrim] {
          animation: none;
        }
      }
    </style>
    <div
      data-pattern-frame=${surface}
      data-sheet-mobile=${String(mobileSheet)}
      data-closed="false"
      style=${`block-size:calc(${size.height} + ${mobileSheet ? 12 : 0}px)`}
    >
      ${
        mobileSheet
          ? html`<div data-sheet-page .inert=${surface === 'ai-mode'}>
                <p>Example storefront</p>
                <chatty-button
                  variant="secondary"
                  type="button"
                  @click=${event => {
                    event.currentTarget.textContent = 'Products opened';
                  }}
                >
                  Browse products
                </chatty-button>
              </div>
              ${surface === 'ai-mode' ? html`<button type="button" data-sheet-scrim tabindex="-1" aria-label="Close chat background" @click=${event => toggle(event, true)}></button>` : ''}`
          : ''
      }
      <chatty-surface
        data-chatty-surface=${surface}
        data-chatty-theme=${surface === 'admin' ? 'light' : (document.documentElement.dataset.chattyTheme ?? document.documentElement.dataset.theme ?? 'light')}
        style=${`inline-size:100%;max-inline-size:${mobileSheet ? 'none' : `${size.width}px`};--chatty-surface-height:${size.height}`}
        .store=${store}
        .registry=${registry ?? null}
        viewer-type=${surface === 'admin' ? 'agent' : 'customer'}
        .selfTypes=${surface === 'admin' ? ['agent', 'bot'] : null}
        .renderMessage=${sender}
      >
        <div slot="header" data-pattern-header>
          ${headerStart ?? ''}
          ${surface === 'admin' ? '' : html`<chatty-avatar label="Store" .status=${status}>S</chatty-avatar>`}
          <span data-pattern-title
            ><strong
              >${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}</strong
            >${surface === 'admin' ? html`<chatty-badge size="sm" variant="secondary" style="align-self:flex-start">Customer</chatty-badge>` : status == null ? '' : html`<small data-pattern-status>${status === 'online' ? 'Open' : 'Closed'}</small>`}</span
          >
          <span data-pattern-actions>${headerActions ?? ''}</span>
          ${
            surface === 'admin'
              ? ''
              : html`<chatty-icon-button label="Close panel" @click=${event => toggle(event, true)}
                  >${IconClose()}</chatty-icon-button
                >`
          }
        </div>
        <chatty-thread .strings=${{bot: 'Assistant', ...strings}}></chatty-thread>${content ?? ''}
        <chatty-composer
          slot="footer"
          ?hidden=${composerHidden}
          .label=${strings.message}
          .sendLabel=${strings.send}
          @chatty-send=${event => {
            appendViewer(store, surface, event.detail.text);
            if (onSend) onSend(event.detail.text, event.currentTarget);
            else if (surface !== 'admin')
              store.setMessages([
                ...store.getState().messages,
                {
                  id: `fixture-${store.getState().messages.length}`,
                  senderType: 'bot',
                  text: `You asked: “${event.detail.text}”. I can help with that.`,
                  hasEventTime: false
                }
              ]);
          }}
        ></chatty-composer> </chatty-surface
      >${
        surface === 'admin'
          ? ''
          : surface === 'ai-mode'
            ? html`<chatty-launcher
                data-pattern-launcher
                hidden
                label="Open chat"
                @chatty-open=${event => toggle(event, false)}
                >${IconMessage({size: 20, slot: 'icon'})}Ask a question</chatty-launcher
              >`
            : html`<chatty-icon-button
                data-pattern-launcher
                hidden
                size="lg"
                label="Open chat"
                @click=${event => toggle(event, false)}
                >${IconMessage({size: 24})}</chatty-icon-button
              >`
      }
    </div>`;
}

import '@avada/chatty-ui/elements/chatty-block-products.js';
const products = [
  {
    id: 'tote',
    title: 'Canvas tote',
    amount: 24,
    price: '$24.00',
    compareAtPrice: '$32.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'
  },
  {
    id: 'cap',
    title: 'Cotton cap',
    amount: 18,
    price: '$18.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/cap.svg',
    available: false
  },
  {
    id: 'mug',
    title: 'Stoneware mug',
    amount: 16,
    price: '$16.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/mug.svg',
    cartState: 'error',
    cartError: 'Could not add to cart'
  }
];
/** Builds a shopping thread with isolated host-owned fixture cart state.
 * @param {string} surface
 * @returns {Object}
 */
function cartPattern(surface) {
  const store = fixtureStore([
    question,
    {
      id: 'products',
      senderType: 'bot',
      text: 'Here are three options for you.',
      blocks: [{type: 'products', data: {products}}]
    }
  ]);
  const add = event => {
    const product = event.detail.product;
    const update = cartState =>
      store.setMessages(
        store.getState().messages.map(m =>
          m.id !== 'products'
            ? m
            : {
                ...m,
                blocks: [
                  {
                    type: 'products',
                    data: {
                      products: m.blocks[0].data.products.map(p =>
                        p.id === product.id ? {...p, cartState} : p
                      )
                    }
                  }
                ]
              }
        )
      );
    update('loading');
    const finish = () => {
      update('added');
      if (surface === 'ai-mode')
        store.setMessages([
          ...store.getState().messages,
          {
            id: `receipt-${store.getState().messages.length}`,
            senderType: 'bot',
            blocks: [
              {
                type: 'cart-confirmation',
                data: {
                  receipts: [
                    {title: product.title, quantity: 1, linePrice: product.amount, currency: 'USD'}
                  ]
                }
              }
            ]
          }
        ]);
      setTimeout(() => update('idle'), surface === 'classic' ? 2000 : 1650);
    };
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
    else setTimeout(finish, 450);
  };
  if (surface === 'admin')
    store.setMessages([
      ...store.getState().messages,
      {
        id: 'receipt',
        senderType: 'bot',
        blocks: [
          {
            type: 'cart-confirmation',
            data: {receipts: [{title: 'Canvas tote', quantity: 1, linePrice: 24, currency: 'USD'}]}
          }
        ]
      }
    ]);
  return html`<div
    style="inline-size:100%;min-inline-size:0"
    @chatty-add-to-cart=${add}
    @chatty-view-cart=${event => {
      const line = store
        .getState()
        .messages.flatMap(message => message.blocks ?? [])
        .filter(block => block.type === 'cart-confirmation')
        .at(-1).data.receipts[0];
      store.setMessages([
        ...store.getState().messages,
        {
          id: `bag-${store.getState().messages.length}`,
          senderType: 'bot',
          text: `Your bag: ${line.title} × ${line.quantity} — ${new Intl.NumberFormat('en', {style: 'currency', currency: line.currency}).format(line.linePrice)}`
        }
      ]);
    }}
  >
    ${patternShell({surface, store})}
  </div>`;
}

export function Standard({surface}) {
  return cartPattern(surface);
}
```

Example (Standard) — Admin read-only Standard.

```js
import '@avada/chatty-ui/tokens/admin.css';
import {html} from 'lit';
import {IconClose, IconMessage} from '@avada/chatty-ui/elements/icon-glyphs.js';
import '@avada/chatty-ui/elements/surface.js';
import '@avada/chatty-ui/elements/avatar.js';
import '@avada/chatty-ui/elements/badge.js';
import '@avada/chatty-ui/elements/icon-button.js';
import '@avada/chatty-ui/elements/launcher.js';
import '@avada/chatty-ui/elements/button.js';
import {sameGroup} from '@avada/chatty-ui/behaviors/messages.js';

// Reference viewport: 1280 × 900 desktop, 390 × 900 mobile.
const sizes = {
  classic: {width: 400, height: 700},
  'ai-mode': {width: 820, height: 657},
  admin: {width: 527, height: 842}
};
const question = {
  id: 'question',
  senderType: 'customer',
  text: 'Can you help me?',
  createdAt: '2026-01-15T10:00:00Z'
};

/** Viewport-relative sizing survives the initial hidden iframe layout. */
function widgetSize(surface) {
  const mode = new URLSearchParams(location.search).get('mobile');
  const isMobile = mode === null ? innerWidth < 900 : mode === 'true';
  const width = `min(${sizes[surface].width}px, max(0px, 100vw - 40px))`;
  const height = isMobile
    ? `min(${surface === 'admin' ? 848 : 888}px, round(down, calc(${width} * 2.2), 1px))`
    : `${sizes[surface].height}px`;
  return {...sizes[surface], height, mobile: isMobile};
}

/** Local immutable message state with real subscriptions for live previews. */
function fixtureStore(initial) {
  let state = {messages: initial};
  const listeners = new Set();
  return {
    getState: () => state,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    setMessages(messages) {
      state = {messages};
      listeners.forEach(listener => listener());
    }
  };
}

/** Appends the viewer message without replacing the existing conversation. */
function appendViewer(store, surface, text) {
  const message = {
    id: `viewer-${store.getState().messages.length}`,
    senderType: surface === 'admin' ? 'agent' : 'customer',
    senderMeta: {name: surface === 'admin' ? 'Alex' : 'You'},
    text,
    createdAt: new Date().toISOString()
  };
  store.setMessages([...store.getState().messages, message]);
}

/**
 * One shell owns surface sizing, header, thread and composer for every pattern.
 * @param {string} surface
 * @param {Object} store
 * @param {Object} strings
 * @param {Object} content
 * @param {Function} renderMessage
 * @param {Function} onSend
 * @param {Object} registry
 * @param {boolean} composerHidden
 * @param {string} title
 * @param {Object} headerStart
 * @param {Object} headerActions
 * @param {boolean} sheet
 * @param {string | null} status
 * @returns {Object}
 */
function patternShell({
  surface,
  store,
  strings = {header: 'Store assistant', message: 'Message', send: 'Send'},
  content,
  renderMessage,
  onSend,
  registry,
  title,
  headerStart,
  headerActions,
  status = 'online',
  sheet = false,
  composerHidden = false
}) {
  const size = widgetSize(surface);
  const mobileSheet = sheet && size.mobile;
  if (mobileSheet) {
    size.width = 'none';
    size.height = 'calc(100dvh - 12px)';
  }
  const toggle = (event, closed) => {
    const frame = event.currentTarget.closest('[data-pattern-frame]');
    const panel = frame.querySelector('chatty-surface');
    const launcher = frame.querySelector('[data-pattern-launcher]');
    panel.hidden = closed;
    frame.dataset.closed = String(closed);
    const background = frame.querySelector('[data-sheet-page]');
    if (background) background.inert = !closed && surface === 'ai-mode';
    launcher.hidden = !closed;
    if (closed) {
      launcher.style.insetBlockEnd = `${Math.max(surface === 'ai-mode' ? 40 : 16, frame.getBoundingClientRect().bottom - innerHeight + 20)}px`;
      launcher.focus({preventScroll: true});
    } else {
      const composer = panel.querySelector('chatty-composer');
      const input = !composer.hidden
        ? composer.renderRoot.querySelector('textarea')
        : (panel
            .querySelector('chatty-contact-form:not([hidden])')
            ?.renderRoot.querySelector('chatty-text-field') ??
          panel.querySelector('form chatty-text-field') ??
          panel.querySelector('[data-welcome-invitation]:not([hidden]) chatty-button') ??
          panel
            .querySelector('chatty-pre-chat:not([hidden])')
            ?.renderRoot.querySelector('chatty-button'));
      input?.focus({preventScroll: true});
    }
  };
  const sender = message => {
    const content = renderMessage?.(message) ?? {};
    const messages = store.getState().messages;
    const previous = messages[messages.indexOf(message) - 1];
    if (message.senderType !== 'bot' || sameGroup(message, previous)) return content;
    return {
      ...content,
      sender: html`<span style="display:inline-flex;align-items:center;gap:6px"
        ><chatty-avatar size="sm" label="Assistant">A</chatty-avatar
        >${content.sender ?? message.senderName ?? message.senderMeta?.name ?? 'Assistant'}</span
      >`
    };
  };
  return html`<style>
      [data-pattern-frame] {
        display: flex;
        position: relative;
        justify-content: center;
        inline-size: 100%;
        min-inline-size: 0;
      }
      [data-pattern-frame='classic'] {
        justify-content: flex-end;
      }
      [data-pattern-frame] chatty-surface::part(header) {
        padding: 0;
      }
      [data-pattern-frame='classic'] chatty-surface::part(header),
      [data-pattern-frame='ai-mode'] chatty-surface::part(header) {
        border-bottom-width: 0;
      }
      [data-pattern-frame] [hidden] {
        display: none !important;
      }
      [data-pattern-header] {
        display: flex;
        align-items: center;
        gap: 10px;
        box-sizing: border-box;
        min-inline-size: 0;
        block-size: 52px;
        padding: 0 16px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] {
        block-size: 56px;
        background: var(--chatty-color-accent);
        color: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-icon-button {
        --chatty-color-border-focus: var(--chatty-color-on-accent);
      }
      [data-pattern-frame='admin'] [data-pattern-header] {
        block-size: 68px;
        padding: 8px 12px;
      }
      [data-pattern-header] chatty-avatar {
        --chatty-avatar-size: 32px;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar {
        --chatty-avatar-background: #fff;
      }
      [data-pattern-frame='classic'] [data-pattern-header] chatty-avatar::part(base) {
        color: #303030;
        border: 1px solid #767676;
      }
      [data-pattern-actions] {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      [data-pattern-title] {
        flex: 1;
        min-inline-size: 0;
        display: flex;
        flex-direction: column;
      }
      [data-pattern-frame='admin'] [data-pattern-title] {
        gap: 4px;
      }
      [data-pattern-frame='admin'] [data-pattern-title] strong {
        display: flex;
        align-items: center;
        min-block-size: 28px;
        font: var(--p-font-weight-semibold, 650) var(--p-text-heading-md-font-size, 14px) /
          var(--p-text-heading-md-font-line-height, 20px) var(--p-font-family-sans, system-ui);
      }
      [data-pattern-title] strong {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      [data-pattern-header] chatty-icon-button {
        --chatty-icon-button-size: 32px;
        --chatty-icon-button-color: currentColor;
      }
      @media (max-width: 899px), (pointer: coarse) {
        [data-pattern-header] chatty-icon-button {
          --chatty-icon-button-size: 44px;
        }
      }
      [data-pattern-launcher] {
        position: absolute;
        inset-inline-end: 0;
        inset-block-end: 0;
      }
      [data-pattern-frame='ai-mode'] [data-pattern-launcher] {
        inset-inline-end: auto;
        inset-inline-start: 50%;
        transform: translateX(-50%);
      }
      [data-pattern-frame='classic'] [data-pattern-launcher] {
        --chatty-icon-button-size: 56px;
        border-radius: 50%;
        background: var(--chatty-color-accent);
        --chatty-icon-button-color: var(--chatty-color-on-accent);
      }
      [data-sheet-mobile='true'] {
        position: fixed;
        inset: 0;
        inline-size: 100vw;
      }
      [data-sheet-mobile='true'] chatty-surface::part(base) {
        border-radius: 16px 16px 0 0;
      }
      [data-sheet-mobile='true'] chatty-surface {
        position: relative;
        z-index: 2;
        margin-block-start: 12px;
      }
      [data-sheet-page],
      [data-sheet-scrim] {
        position: absolute;
        inset: 0;
        box-sizing: border-box;
      }
      [data-sheet-page] {
        padding: 20px;
        background: var(--chatty-color-bg-surface);
        color: var(--chatty-color-text);
      }
      [data-sheet-scrim] {
        z-index: 1;
        border: 0;
        background: rgb(0 0 0 / 40%);
        animation: sheet-scrim 400ms ease;
      }
      [data-sheet-mobile='true'][data-closed='true'] [data-sheet-scrim] {
        display: none;
      }
      [data-sheet-mobile='true'] [data-pattern-launcher] {
        z-index: 3;
      }
      @keyframes sheet-scrim {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        [data-sheet-scrim] {
          animation: none;
        }
      }
    </style>
    <div
      data-pattern-frame=${surface}
      data-sheet-mobile=${String(mobileSheet)}
      data-closed="false"
      style=${`block-size:calc(${size.height} + ${mobileSheet ? 12 : 0}px)`}
    >
      ${
        mobileSheet
          ? html`<div data-sheet-page .inert=${surface === 'ai-mode'}>
                <p>Example storefront</p>
                <chatty-button
                  variant="secondary"
                  type="button"
                  @click=${event => {
                    event.currentTarget.textContent = 'Products opened';
                  }}
                >
                  Browse products
                </chatty-button>
              </div>
              ${surface === 'ai-mode' ? html`<button type="button" data-sheet-scrim tabindex="-1" aria-label="Close chat background" @click=${event => toggle(event, true)}></button>` : ''}`
          : ''
      }
      <chatty-surface
        data-chatty-surface=${surface}
        data-chatty-theme=${surface === 'admin' ? 'light' : (document.documentElement.dataset.chattyTheme ?? document.documentElement.dataset.theme ?? 'light')}
        style=${`inline-size:100%;max-inline-size:${mobileSheet ? 'none' : `${size.width}px`};--chatty-surface-height:${size.height}`}
        .store=${store}
        .registry=${registry ?? null}
        viewer-type=${surface === 'admin' ? 'agent' : 'customer'}
        .selfTypes=${surface === 'admin' ? ['agent', 'bot'] : null}
        .renderMessage=${sender}
      >
        <div slot="header" data-pattern-header>
          ${headerStart ?? ''}
          ${surface === 'admin' ? '' : html`<chatty-avatar label="Store" .status=${status}>S</chatty-avatar>`}
          <span data-pattern-title
            ><strong
              >${title ?? (surface === 'admin' ? 'Customer conversation' : strings.header)}</strong
            >${surface === 'admin' ? html`<chatty-badge size="sm" variant="secondary" style="align-self:flex-start">Customer</chatty-badge>` : status == null ? '' : html`<small data-pattern-status>${status === 'online' ? 'Open' : 'Closed'}</small>`}</span
          >
          <span data-pattern-actions>${headerActions ?? ''}</span>
          ${
            surface === 'admin'
              ? ''
              : html`<chatty-icon-button label="Close panel" @click=${event => toggle(event, true)}
                  >${IconClose()}</chatty-icon-button
                >`
          }
        </div>
        <chatty-thread .strings=${{bot: 'Assistant', ...strings}}></chatty-thread>${content ?? ''}
        <chatty-composer
          slot="footer"
          ?hidden=${composerHidden}
          .label=${strings.message}
          .sendLabel=${strings.send}
          @chatty-send=${event => {
            appendViewer(store, surface, event.detail.text);
            if (onSend) onSend(event.detail.text, event.currentTarget);
            else if (surface !== 'admin')
              store.setMessages([
                ...store.getState().messages,
                {
                  id: `fixture-${store.getState().messages.length}`,
                  senderType: 'bot',
                  text: `You asked: “${event.detail.text}”. I can help with that.`,
                  hasEventTime: false
                }
              ]);
          }}
        ></chatty-composer> </chatty-surface
      >${
        surface === 'admin'
          ? ''
          : surface === 'ai-mode'
            ? html`<chatty-launcher
                data-pattern-launcher
                hidden
                label="Open chat"
                @chatty-open=${event => toggle(event, false)}
                >${IconMessage({size: 20, slot: 'icon'})}Ask a question</chatty-launcher
              >`
            : html`<chatty-icon-button
                data-pattern-launcher
                hidden
                size="lg"
                label="Open chat"
                @click=${event => toggle(event, false)}
                >${IconMessage({size: 24})}</chatty-icon-button
              >`
      }
    </div>`;
}

import '@avada/chatty-ui/elements/chatty-block-products.js';
const products = [
  {
    id: 'tote',
    title: 'Canvas tote',
    amount: 24,
    price: '$24.00',
    compareAtPrice: '$32.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/tote.svg'
  },
  {
    id: 'cap',
    title: 'Cotton cap',
    amount: 18,
    price: '$18.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/cap.svg',
    available: false
  },
  {
    id: 'mug',
    title: 'Stoneware mug',
    amount: 16,
    price: '$16.00',
    image: 'https://chatty-ui-research.avada-tesla-chatty.workers.dev/fixtures/mug.svg',
    cartState: 'error',
    cartError: 'Could not add to cart'
  }
];
/** Builds a shopping thread with isolated host-owned fixture cart state.
 * @param {string} surface
 * @returns {Object}
 */
function cartPattern(surface) {
  const store = fixtureStore([
    question,
    {
      id: 'products',
      senderType: 'bot',
      text: 'Here are three options for you.',
      blocks: [{type: 'products', data: {products}}]
    }
  ]);
  const add = event => {
    const product = event.detail.product;
    const update = cartState =>
      store.setMessages(
        store.getState().messages.map(m =>
          m.id !== 'products'
            ? m
            : {
                ...m,
                blocks: [
                  {
                    type: 'products',
                    data: {
                      products: m.blocks[0].data.products.map(p =>
                        p.id === product.id ? {...p, cartState} : p
                      )
                    }
                  }
                ]
              }
        )
      );
    update('loading');
    const finish = () => {
      update('added');
      if (surface === 'ai-mode')
        store.setMessages([
          ...store.getState().messages,
          {
            id: `receipt-${store.getState().messages.length}`,
            senderType: 'bot',
            blocks: [
              {
                type: 'cart-confirmation',
                data: {
                  receipts: [
                    {title: product.title, quantity: 1, linePrice: product.amount, currency: 'USD'}
                  ]
                }
              }
            ]
          }
        ]);
      setTimeout(() => update('idle'), surface === 'classic' ? 2000 : 1650);
    };
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
    else setTimeout(finish, 450);
  };
  if (surface === 'admin')
    store.setMessages([
      ...store.getState().messages,
      {
        id: 'receipt',
        senderType: 'bot',
        blocks: [
          {
            type: 'cart-confirmation',
            data: {receipts: [{title: 'Canvas tote', quantity: 1, linePrice: 24, currency: 'USD'}]}
          }
        ]
      }
    ]);
  return html`<div
    style="inline-size:100%;min-inline-size:0"
    @chatty-add-to-cart=${add}
    @chatty-view-cart=${event => {
      const line = store
        .getState()
        .messages.flatMap(message => message.blocks ?? [])
        .filter(block => block.type === 'cart-confirmation')
        .at(-1).data.receipts[0];
      store.setMessages([
        ...store.getState().messages,
        {
          id: `bag-${store.getState().messages.length}`,
          senderType: 'bot',
          text: `Your bag: ${line.title} × ${line.quantity} — ${new Intl.NumberFormat('en', {style: 'currency', currency: line.currency}).format(line.linePrice)}`
        }
      ]);
    }}
  >
    ${patternShell({surface, store})}
  </div>`;
}

export function StandardAdmin() {
  return cartPattern('admin');
}
```

Standard dùng fixture cart; View cart mở trạng thái bag fixture trong thread. Sidebar bag thật: N/A trong preview. Không gọi cart API. Added reset theo surface; animation check của React chỉ ở Current.

### Current

Example (Current (React), being replaced) — Card sản phẩm Classic thật (`ChatbotProductsMessage`): nút Add to cart và card hết hàng.

```jsx
import React, {useState} from 'react';
import {ChatProductCarousel} from '@scripttag/v2/views/chat/ChatProductCarousel.jsx';
import {ChatNavigationContext} from '@scripttag/v2/views/chat/chatNavigationContext.js';
import ChatbotProductsMessage from '@scripttag/v1/Parts/InsertProduct/ChatbotProductsMessage/ChatbotProductsMessage.js';
import {ChatMessage} from '@scripttag/v2/views/chat/ChatMessage.jsx';
import {CartConfirmationBlock} from '@assets/pages/InboxManagement/v2/blocks/CartConfirmationBlock.jsx';

const product = (id, title, slug, image, price, availableForSale = true) => ({
  productId: `gid://shopify/Product/${id}`,
  title,
  url: `https://shop.example/products/${slug}`,
  image,
  imageAlt: title,
  availableForSale,
  currency: 'USD',
  prices: [price],
  compareAtPrices: [],
  variantOptions: [`Default Title: ${id}1`]
});

const products = [
  product(102, 'Ceramic mug', 'ceramic-mug', '/fixtures/mug.svg', '$18.00'),
  product(103, 'Wool cap', 'wool-cap', '/fixtures/cap.svg', '$28.00', false)
];

const receipt = {title: 'Everyday tote', variant: 'Blue / Medium', quantity: 2, linePrice: 48, currency: 'USD'};

export function Feedback({surface}) {
  if (surface === 'classic')
    return (
      <div style={{width: 360}}>
        <ChatbotProductsMessage products={products} messageId="guide-classic-atc" />
      </div>
    );
  return (
    <ChatNavigationContext.Provider value>
      <ChatProductCarousel messageId="guide-atc" products={products} />
    </ChatNavigationContext.Provider>
  );
}
```

Example (Current (React), being replaced) — Carousel AI Mode thật (`ChatProductCarousel`): `AddToCartButton` trong card, kèm card hết hàng.

```jsx
import React, {useState} from 'react';
import {ChatProductCarousel} from '@scripttag/v2/views/chat/ChatProductCarousel.jsx';
import {ChatNavigationContext} from '@scripttag/v2/views/chat/chatNavigationContext.js';
import ChatbotProductsMessage from '@scripttag/v1/Parts/InsertProduct/ChatbotProductsMessage/ChatbotProductsMessage.js';
import {ChatMessage} from '@scripttag/v2/views/chat/ChatMessage.jsx';
import {CartConfirmationBlock} from '@assets/pages/InboxManagement/v2/blocks/CartConfirmationBlock.jsx';

const product = (id, title, slug, image, price, availableForSale = true) => ({
  productId: `gid://shopify/Product/${id}`,
  title,
  url: `https://shop.example/products/${slug}`,
  image,
  imageAlt: title,
  availableForSale,
  currency: 'USD',
  prices: [price],
  compareAtPrices: [],
  variantOptions: [`Default Title: ${id}1`]
});

const products = [
  product(102, 'Ceramic mug', 'ceramic-mug', '/fixtures/mug.svg', '$18.00'),
  product(103, 'Wool cap', 'wool-cap', '/fixtures/cap.svg', '$28.00', false)
];

const receipt = {title: 'Everyday tote', variant: 'Blue / Medium', quantity: 2, linePrice: 48, currency: 'USD'};

export function Feedback({surface}) {
  if (surface === 'classic')
    return (
      <div style={{width: 360}}>
        <ChatbotProductsMessage products={products} messageId="guide-classic-atc" />
      </div>
    );
  return (
    <ChatNavigationContext.Provider value>
      <ChatProductCarousel messageId="guide-atc" products={products} />
    </ChatNavigationContext.Provider>
  );
}
```

Example (Current (React), being replaced) — `ChatMessage` thật render `CartConfirmation` từ `cartConfirmation` của tin nhắn.

```jsx
import React, {useState} from 'react';
import {ChatProductCarousel} from '@scripttag/v2/views/chat/ChatProductCarousel.jsx';
import {ChatNavigationContext} from '@scripttag/v2/views/chat/chatNavigationContext.js';
import ChatbotProductsMessage from '@scripttag/v1/Parts/InsertProduct/ChatbotProductsMessage/ChatbotProductsMessage.js';
import {ChatMessage} from '@scripttag/v2/views/chat/ChatMessage.jsx';
import {CartConfirmationBlock} from '@assets/pages/InboxManagement/v2/blocks/CartConfirmationBlock.jsx';

const product = (id, title, slug, image, price, availableForSale = true) => ({
  productId: `gid://shopify/Product/${id}`,
  title,
  url: `https://shop.example/products/${slug}`,
  image,
  imageAlt: title,
  availableForSale,
  currency: 'USD',
  prices: [price],
  compareAtPrices: [],
  variantOptions: [`Default Title: ${id}1`]
});

const products = [
  product(102, 'Ceramic mug', 'ceramic-mug', '/fixtures/mug.svg', '$18.00'),
  product(103, 'Wool cap', 'wool-cap', '/fixtures/cap.svg', '$28.00', false)
];

const receipt = {title: 'Everyday tote', variant: 'Blue / Medium', quantity: 2, linePrice: 48, currency: 'USD'};

export function Receipt({surface}) {
  if (surface === 'admin') return <CartConfirmationBlock block={{receipt}} vm={{viewerType: 'admin'}} />;
  return (
    <ChatMessage
      message={{id: 'guide-receipt', senderType: 'bot', blocks: [], raw: {cartConfirmation: receipt}}}
      messageKey="guide-receipt"
      assistantName="Assistant"
    />
  );
}
```

Example (Current (React), being replaced) — `CartConfirmationBlock` thật với người xem là admin: không có View cart.

```jsx
import React, {useState} from 'react';
import {ChatProductCarousel} from '@scripttag/v2/views/chat/ChatProductCarousel.jsx';
import {ChatNavigationContext} from '@scripttag/v2/views/chat/chatNavigationContext.js';
import ChatbotProductsMessage from '@scripttag/v1/Parts/InsertProduct/ChatbotProductsMessage/ChatbotProductsMessage.js';
import {ChatMessage} from '@scripttag/v2/views/chat/ChatMessage.jsx';
import {CartConfirmationBlock} from '@assets/pages/InboxManagement/v2/blocks/CartConfirmationBlock.jsx';

const product = (id, title, slug, image, price, availableForSale = true) => ({
  productId: `gid://shopify/Product/${id}`,
  title,
  url: `https://shop.example/products/${slug}`,
  image,
  imageAlt: title,
  availableForSale,
  currency: 'USD',
  prices: [price],
  compareAtPrices: [],
  variantOptions: [`Default Title: ${id}1`]
});

const products = [
  product(102, 'Ceramic mug', 'ceramic-mug', '/fixtures/mug.svg', '$18.00'),
  product(103, 'Wool cap', 'wool-cap', '/fixtures/cap.svg', '$28.00', false)
];

const receipt = {title: 'Everyday tote', variant: 'Blue / Medium', quantity: 2, linePrice: 48, currency: 'USD'};

export function Receipt({surface}) {
  if (surface === 'admin') return <CartConfirmationBlock block={{receipt}} vm={{viewerType: 'admin'}} />;
  return (
    <ChatMessage
      message={{id: 'guide-receipt', senderType: 'bot', blocks: [], raw: {cartConfirmation: receipt}}}
      messageKey="guide-receipt"
      assistantName="Assistant"
    />
  );
}
```

## Classic

### Import / element

#### AddToCartFeedback

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `AddToCartFeedback` | @avada/chatty-ui/primitives/AddToCartFeedback.jsx | .Avada-Faqs_Popup |

### Anatomy

#### AddToCartFeedback

| Part | Element |
| --- | --- |
| 1 | Wrapper `chatty-atc-feedback` giữ chỗ cho label; thêm `is-added` khi check đang hiện. |
| 2 | Label `chatty-atc-label`; `title` chỉ gắn khi label là string. |
| 3 | Check `chatty-atc-check`, ẩn khỏi screen reader bằng `aria-hidden`. |
| 4 | Announcement `chatty-atc-announcement` với `role="status"`. |

### Placement / order

#### AddToCartFeedback

| Context | Order |
| --- | --- |
| Nút thêm giỏ của ProductCard | Button chứa Spinner (khi `isBusy`) rồi tới AddToCartFeedback; receipt thuộc luồng tin nhắn. |

### Props

#### AddToCartFeedback

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `label` | any | Chuỗi hoặc node | Caller truyền | Label i18n của caller |
| `added` | boolean | true / false | Caller truyền | Caller so sánh status với ADD_STATUS.ADDED |
| `successLabel` | string | Chuỗi đã dịch | Chuỗi rỗng | i18n của caller |

### Sizes

#### AddToCartFeedback

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| label | Theo Button caller | — | — | — | Theo Button caller | Theo Button caller | `max-width: 100%`; nowrap và ellipsis |
| check | `size={20}` | — | — | — | Không có chữ | Không nhận pointer (`pointer-events: none`) | Absolute, phủ wrapper; không có breakpoint |
| announcement | 1px | — | — | — | Không hiển thị | Không hiển thị | Ẩn bằng clip-path inset(50%); không có breakpoint |

### Tokens

#### AddToCartFeedback

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Label fade | `--chatty-motion-duration-150` | 150ms (fallback) | Same |
| Easing | `--ease` | Fallback `ease` | Same |
| Check fade-in | `--chatty-motion-duration-150` | 150ms (fallback) | Same |
| Check draw | `--chatty-motion-duration-300` | 300ms (fallback) | Same |
| Check hold | setTimeout | Đến `2000` rồi tháo check | Same |

### States

#### AddToCartFeedback

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Idle | added false | Label hiện đầy đủ, chưa có check. | Announcement `role="status"` rỗng |
| Added | added true | Label `opacity: 0`; check vào 150ms rồi vẽ nét 300ms. | Announcement đọc `successLabel` |
| Hold kết thúc | Sau `2000` | Check bị tháo; label trở lại qua transition 150ms. | Announcement vẫn đọc `successLabel` khi added còn true |
| Reduced motion | `prefers-reduced-motion: reduce` | Check và nét vẽ `animation: none !important`; transition label không tắt. | Không đổi |
| Loading của caller | `isBusy` | Spinner small thay chỗ trước label; nút disabled; component không có trạng thái loading riêng. | `aria-busy` |

### Behaviour

#### AddToCartFeedback

| Interaction | Result |
| --- | --- |
| Server OK | Caller đặt `added` true; effect gọi setShowCheck và đặt timer `2000`. |
| Nhãn dài | Label nowrap và ellipsis; `title` gắn khi label là string. |
| Kích hoạt lặp | Component không chặn; caller disable nút khi `isAddToCartDisabled`. |

### Copy

#### AddToCartFeedback

| String | i18n key | Where |
| --- | --- | --- |
| Add to cart | Add to cart | Label truyền qua i18n caller |
| Added to cart | Added to cart | `successLabel` của AddToCartFeedback |
| Could not add to cart | Could not add to cart | `addError` hiện với `role="alert"` |

### Source

#### AddToCartFeedback

| File | Evidence |
| --- | --- |
|  | API và markup |
|  | Layout, motion, announcement ẩn |
|  | Caller Classic |

## AI Mode

### Import / element

#### AddToCartFeedback

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `AddToCartFeedback` | @avada/chatty-ui/primitives/AddToCartFeedback.jsx | .chatty-ai-mode[data-theme] |

#### CartConfirmation

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `CartConfirmation` | @avada/chatty-ui/primitives/CartConfirmation.jsx | .chatty-ai-mode[data-theme] |

### Anatomy

#### AddToCartFeedback

| Part | Element |
| --- | --- |
| 1 | Wrapper `chatty-atc-feedback` giữ chỗ cho label; thêm `is-added` khi check đang hiện. |
| 2 | Label `chatty-atc-label`; `title` chỉ gắn khi label là string. |
| 3 | Check `chatty-atc-check`, ẩn khỏi screen reader bằng `aria-hidden`. |
| 4 | Announcement `chatty-atc-announcement` với `role="status"`. |

#### CartConfirmation

| Part | Element |
| --- | --- |
| 1 | Section `chatty-cart-confirmation` với `aria-label`. |
| 2 | Label `chatty-cart-confirmation__label`. |
| 3 | Thumbnail `img`, chỉ khi có ảnh và ảnh chưa lỗi. |
| 4 | Title `chatty-cart-confirmation__title`; variant tuỳ chọn. |
| 5 | Dòng số lượng và giá trong `bdi`. |
| 6 | Action `chatty-cart-confirmation__action`, chỉ khi có `onViewCart`. |

### Placement / order

#### AddToCartFeedback

| Context | Order |
| --- | --- |
| Nút thêm giỏ của ProductCard | Trong `BusyLabel`, bên trong `buttonchatty-btn--glass`; `chatty-btn-spinner` thêm khi busy. |

#### CartConfirmation

| Context | Order |
| --- | --- |
| Tin chat có `cartConfirmation` | Receipt thay bubble: ChatMessage trả `CartConfirmation` trước các nhánh sender. Trong card: label, thumbnail, title, variant, dòng số lượng và giá, View cart. |

### Props

#### AddToCartFeedback

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `label` | any | Chuỗi hoặc node | Caller truyền | `getAddToCartLabel` |
| `added` | boolean | true / false | Caller truyền | `isAdded` |
| `successLabel` | string | Chuỗi đã dịch | Chuỗi rỗng | `t('Added to cart')` |

#### CartConfirmation

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `receipt` | object | Dữ liệu một dòng giỏ | Bắt buộc | Đọc qua `readCartConfirmation` |
| `formatMoney` | function | AI Mode truyền `presentPrice` | Bắt buộc | Định dạng giá dòng |
| `onViewCart` | function | Mở sidebar bag | Không có | Không truyền thì không có action |

### Sizes

#### AddToCartFeedback

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| label | Theo button caller | — | — | — | Theo button caller | Theo button caller | `max-width: 100%`; nowrap và ellipsis |
| check | `size={20}` | — | — | — | Không có chữ | Không nhận pointer (`pointer-events: none`) | Absolute, phủ wrapper; không có breakpoint |
| announcement | 1px | — | — | — | Không hiển thị | Không hiển thị | Ẩn bằng clip-path inset(50%); không có breakpoint |

#### CartConfirmation

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| card | Theo nội dung | 16px | 12px | 20px | body-medium: Derived(15px = type(body-medium, desktop, size)) / Derived(22px = type(body-medium, desktop, line)) desktop, Derived(17px = type(body-medium, mobile, size)) / Derived(24px = type(body-medium, mobile, line)) mobile | Không phải điều khiển | Width `min(100%, 360px)` |
| thumbnail | 80px | — | — | 10px | — | Không phải điều khiển | Width 64px; `object-fit: cover`; chỉ khi có ảnh |
| label | Theo nội dung | — | — | — | body-small: Derived(14px = type(body-small, desktop, size)) / Derived(20px = type(body-small, desktop, line)) desktop, Derived(15px = type(body-small, mobile, size)) / Derived(22px = type(body-small, mobile, line)) mobile | Không phải điều khiển | Role theo `.is-mobile` hoặc max-width 899px |
| line price | Theo nội dung | — | 4px / 12px | — | body-medium, weight 600 | Không phải điều khiển | `white-space: nowrap`; không co lại |
| action | min-height 40px | 8px / 0 | — | 6px | `font: inherit` | 40px desktop; 44px mobile | Max-width 899px đổi min-height 44px |

### Tokens

#### AddToCartFeedback

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Label fade | `--chatty-motion-duration-150` | 150ms (fallback) | Same |
| Easing | `--ease` | `--chatty-motion-ease-out-emphasized` | Same |
| Check fade-in | `--chatty-motion-duration-150` | 150ms (fallback) | Same |
| Check draw | `--chatty-motion-duration-300` | 300ms (fallback) | Same |
| Check hold | setTimeout | Đến `1650` rồi tháo check | Same |

#### CartConfirmation

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Border | `--chatty-color-border` | rgba(20, 19, 24, 0.08) | rgba(255, 255, 255, 0.12) |
| Surface | `--chatty-color-bg-surface` | #f6f4f0 | #131215 |
| Text | `--chatty-color-text` | rgba(20, 19, 24, 0.94) | rgba(255, 255, 255, 0.96) |
| Text phụ | `--chatty-color-text-secondary` | rgba(20, 19, 24, 0.74) | rgba(255, 255, 255, 0.74) |
| Nền thumbnail | `--chatty-color-bg-surface-secondary` | #f7f7f7 (fallback) | Same fallback |

### States

#### AddToCartFeedback

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Idle | added false | Label hiện đầy đủ, chưa có check. | Announcement `role="status"` rỗng |
| Added | added true | Label `opacity: 0`; check vào 150ms rồi vẽ nét 300ms. | Announcement đọc `successLabel` |
| Hold kết thúc | Sau `1650` | Check bị tháo; label trở lại qua transition 150ms. | Announcement vẫn đọc `successLabel` khi added còn true |
| Reduced motion | `prefers-reduced-motion: reduce` | Check và nét vẽ `animation: none !important`; transition label không tắt. | Không đổi |
| Loading của caller | `is-loading` | Class `is-loading`; nút disabled khi `isAdding`. | `aria-busy` |

#### CartConfirmation

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Không có ảnh | Thiếu thumbnail hoặc ảnh lỗi | Body phủ cả grid (`chatty-cart-confirmation--no-media`). | Không đổi |
| Receipt không hợp lệ | `readCartConfirmation` trả null | Không render gì. | Không có node |
| Action hover | pointer | Gạch chân 1px → 2px. | Native button |
| Action active | pointer down | Gạch chân 3px. | Native button |
| Action focus-visible | keyboard | Outline 2px `currentColor`, offset 2px. | Native focus |

### Behaviour

#### AddToCartFeedback

| Interaction | Result |
| --- | --- |
| Server OK | Caller đặt `added` true; effect gọi setShowCheck và đặt timer `1650`. |
| Nhãn dài | Label nowrap và ellipsis; `title` gắn khi label là string. |
| Kích hoạt lặp | Nút `disabled` khi sold out hoặc đang adding. |

#### CartConfirmation

| Interaction | Result |
| --- | --- |
| Chọn View cart | Mở sidebar bag `SIDEBAR.BAG`. |
| Giá | Hiện qua `formatMoney(line.linePrice, line.currency)`. |
| Tên dài | `overflow-wrap: anywhere` trong body. |

### Copy

#### AddToCartFeedback

| String | i18n key | Where |
| --- | --- | --- |
| Add to cart | Add to cart | Label từ `getAddToCartLabel` khi idle |
| Added to cart | Added to cart | `successLabel` |
| Sold out | Sold out | `getAddToCartLabel` khi hết hàng |

#### CartConfirmation

| String | i18n key | Where |
| --- | --- | --- |
| Added to cart | Added to cart | `aria-label` và label của section |
| Quantity in cart | Quantity in cart | Dòng số lượng |
| View cart | View cart | Action, chỉ khi có `onViewCart` |

### Source

#### AddToCartFeedback

| File | Evidence |
| --- | --- |
|  | API và markup |
|  | Caller AI Mode |
|  | Alias --ease |

#### CartConfirmation

| File | Evidence |
| --- | --- |
|  | API và markup |
|  | Layout và motion |
|  | Caller AI Mode |

## Admin

### Import / element

#### CartConfirmationBlock

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `CartConfirmationBlock` | @assets/pages/InboxManagement/v2/blocks/CartConfirmationBlock.jsx | .inbox-v2 |
| `CartConfirmation` | @avada/chatty-ui/primitives/CartConfirmation.jsx | .inbox-v2 |

### Anatomy

#### CartConfirmationBlock

| Part | Element |
| --- | --- |
| 1 | Section `chatty-cart-confirmation` với `aria-label`. |
| 2 | Label `chatty-cart-confirmation__label`. |
| 3 | Thumbnail `img`, chỉ khi có ảnh và ảnh chưa lỗi. |
| 4 | Title `chatty-cart-confirmation__title`; variant tuỳ chọn. |
| 5 | Dòng số lượng và giá trong `bdi`. |
| 6 | Action `chatty-cart-confirmation__action`, chỉ khi có `onViewCart`. |

### Placement / order

#### CartConfirmationBlock

| Context | Order |
| --- | --- |
| Block `cart-confirmation` trong inbox | Registry map block sang CartConfirmationBlock; receipt giống AI Mode, không có action cho người xem là admin. |

### Props

#### CartConfirmationBlock

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `receipt` | object | `block.receipt` | Bắt buộc | Truyền thẳng từ block |
| `formatMoney` | function | `presentPrice` | Bắt buộc | Định dạng giá dòng |
| `onViewCart` | function | undefined khi `isAdminViewer(vm)` | Không có | Admin không mở giỏ của khách |

### Sizes

#### CartConfirmationBlock

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| card | Theo nội dung | 16px | 12px | 20px | body-medium: Derived(13px = type(body-medium, admin, desktop, size)) / Derived(20px = type(body-medium, admin, desktop, line)) desktop, Derived(15px = type(body-medium, admin, mobile, size)) / Derived(22px = type(body-medium, admin, mobile, line)) mobile | Không phải điều khiển | Width `min(100%, 360px)` |
| thumbnail | 80px | — | — | 10px | — | Không phải điều khiển | Width 64px; `object-fit: cover`; chỉ khi có ảnh |
| label | Theo nội dung | — | — | — | body-small: Derived(12px = type(body-small, admin, desktop, size)) / Derived(18px = type(body-small, admin, desktop, line)) desktop, Derived(13px = type(body-small, admin, mobile, size)) / Derived(20px = type(body-small, admin, mobile, line)) mobile | Không phải điều khiển | Role theo `.is-mobile` hoặc max-width 899px |
| line price | Theo nội dung | — | 4px / 12px | — | body-medium, weight 600 | Không phải điều khiển | `white-space: nowrap`; không co lại |
| action | min-height 40px | 8px / 0 | — | 6px | `font: inherit` | 40px desktop; 44px mobile | Max-width 899px đổi min-height 44px |

### Tokens

#### CartConfirmationBlock

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Border | `--chatty-color-border` | #e3e3e3 (fallback) | No Dark skin |
| Surface | `--chatty-color-bg-surface` | #fff (fallback) | No Dark skin |
| Text | `--chatty-color-text` | #303030 (fallback) | No Dark skin |
| Text phụ | `--chatty-color-text-secondary` | #616161 (fallback) | No Dark skin |
| Nền thumbnail | `--chatty-color-bg-surface-secondary` | #f7f7f7 (fallback) | No Dark skin |

### States

#### CartConfirmationBlock

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Không có ảnh | Thiếu thumbnail hoặc ảnh lỗi | Body phủ cả grid (`chatty-cart-confirmation--no-media`). | Không đổi |
| Receipt không hợp lệ | `readCartConfirmation` trả null | Không render gì. | Không có node |
| Action hover | pointer | Gạch chân 1px → 2px. | Native button |
| Action active | pointer down | Gạch chân 3px. | Native button |
| Action focus-visible | keyboard | Outline 2px `currentColor`, offset 2px. | Native focus |

### Behaviour

#### CartConfirmationBlock

| Interaction | Result |
| --- | --- |
| Người xem là admin | Không có action View cart; receipt chỉ đọc. |
| Giá | Hiện qua `formatMoney(line.linePrice, line.currency)`. |
| Tên dài | `overflow-wrap: anywhere` trong body. |

### Copy

#### CartConfirmationBlock

| String | i18n key | Where |
| --- | --- | --- |
| Added to cart | Added to cart | `aria-label` và label của section |
| Quantity in cart | Quantity in cart | Dòng số lượng |
| View cart | View cart | Action, chỉ khi có `onViewCart` |

### Source

#### CartConfirmationBlock

| File | Evidence |
| --- | --- |
|  | Block inbox |
|  | API và markup |
|  | Layout và motion |

## Do / Don't

Do: đọc rõ variant, quantity và giá dòng trong receipt.

Don't: gắn xác nhận vào đoạn văn AI hoặc cho inbox có hành động đổi giỏ của khách.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| Classic | `status`; nút giữ label của caller | Nút native; component không gọi focus | `role="status"` ẩn đọc `successLabel` | Check kế thừa foreground của nút caller |
| AI Mode | Section có `aria-label`; nút native | Action View cart là native button, focus ring theo States | `role="status"` ẩn trong nút | Light Measured(rgba(20, 19, 24, 0.94) / #f6f4f0 = 14.65:1); Dark Measured(rgba(255, 255, 255, 0.96) / #131215 = 17.20:1) |
| Admin | Section có `aria-label` | Không có điều khiển trong receipt | Không có | Light Measured(#303030 / #ffffff = 13.20:1) |

## Target

```target
| Surface | Now | Target |
| --- | --- | --- |
| AI Mode | Check bị tháo sau `1650` khi không có successText | Not in code yet — build with the body values. Target: cùng thay đổi 2s ở AddToCartFeedback; không thêm timer riêng cho AI Mode. |
```

