# Admin reply with suggestions

Giữ quyền dùng hoặc bỏ gợi ý ở nhân viên và ngăn chấp nhận câu trả lời đã cũ.

## Key rules

- Admin: `AISuggestions` hiện mọi trạng thái (đang tạo, rỗng, lỗi, chờ) ngay trong một vùng gợi ý.
- Admin: `Use` chỉ đưa nội dung vào composer qua `setInputValue`; nhân viên đọc, chỉnh và tự quyết định gửi.
- Admin: gợi ý chỉ được dùng lại từ cache khi `customerMessageCount` khớp.
- Admin: chưa có nút hủy khi đang tạo và chưa kiểm tra tin khách mới lúc Use; xem Target.

## Use when / Avoid

Dùng khi nhân viên nhờ AI soạn gợi ý trong lúc khách vẫn có thể nhắn thêm. Nội dung gợi ý chỉ là bản nháp; không dùng để tự gửi.

### Use instead

| Component | Use when |
| --- | --- |
| `AISuggestions` | Vùng gợi ý trả lời phía trên composer. |
| `Button` | Polaris Button cho Use, Retry và Generate again; xem trang Button. |

## Entry points

| Surface | Owner |
| --- | --- |
| Admin | ChatBox render `AISuggestions` khi có gợi ý trả lời, quyền yêu cầu bản nháp và thread đã tải. |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| Admin | Đang tạo | Mount hoặc `retryKey` đổi, cache không dùng được | Gif trên desktop và dòng đang tạo | `LoadingState` | AI is generating...; không có i18n key | Đến khi request xong |
| Admin | Sẵn sàng | Request thành công và có data | Văn bản gợi ý, nút Use, header Tab to accept | `SuggestionItem` | Use, Tab to accept; không có i18n key | Sau response |
| Admin | Dùng gợi ý | Bấm Use | Nội dung vào composer, vùng chuyển sang chờ | `handleUse` | Waiting for next customer message...; không có i18n key | Đồng bộ |
| Admin | Lỗi | Response không thành công | Thông báo lỗi và nút Retry | `Button` | Could not generate suggestion. Please try again.; Retry | Sau response |
| Admin | Rỗng | Data là null | Dòng không có gợi ý mới và nút Generate again | `NoDataState` | No new suggestion available...; Generate again | Sau response |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| Admin | Cache khớp | Dùng lại ngay, không gọi API, đo latencyMs là 0. |
| Admin | Số tin khách đổi | Điều kiện cache `customerMessageCount` không khớp nên bỏ cache và tạo lại. |
| Admin | Tab chấp nhận | `usedKey` đổi thì xóa gợi ý, chuyển chờ và ghi cache consumed. |
| Admin | Mobile | Không hiện gif ở trạng thái đang tạo (`isMobile`). |
| Admin | Thread đang tải hoặc ở tab ghi chú | Không render vùng gợi ý. |

## Live preview

### Standard

Example (Standard) — Thread Standard dùng fixture cục bộ.

```js
import '@avada/chatty-ui/tokens/admin.css';
import {html, render} from 'lit';
import '@avada/chatty-ui/elements/icon.js';
import {ref} from 'lit/directives/ref.js';
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>`;
}

export function Standard() {
  const store = fixtureStore([{...question, text: 'Where is my order?'}]);
  const suggestion = 'Your order is in transit. I will send you the tracking details.';
  let attempt = 0;
  let panel;
  const use = async () => {
    const composer = panel.closest('chatty-surface').querySelector('chatty-composer');
    composer.value = suggestion;
    await composer.updateComplete;
    composer.shadowRoot.querySelector('textarea').focus();
    show('waiting');
  };
  const request = (focus = false) => {
    show('loading', focus);
    const finish = () => show(['ready', 'error', 'empty'][attempt++ % 3], focus);
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
    else setTimeout(finish, 450);
  };
  const show = (state, focus = false) => {
    render(
      html`<section
        role="region"
        aria-label="AI suggestions"
        style="box-sizing:border-box;padding:12px;border:1px solid var(--p-color-border-magic,#e4deff);border-radius:8px;background:var(--p-color-bg-surface-magic,#f8f7ff);font-size:var(--chatty-type-body-medium-size);line-height:var(--chatty-type-body-medium-line)"
        @keydown=${event => {
          if (event.key === 'Tab' && state === 'ready') {
            event.preventDefault();
            use();
          }
        }}
      >
        <chatty-icon label="AI suggestions" style="display:block;margin-bottom:8px;color:#5700d1"
          ><svg width="20" height="20" fill="currentColor" aria-hidden="true" viewBox="0 0 20 20">
            <path
              d="M5.702 4.253a.625.625 0 0 1 1.096 0l.196.358c.207.378.517.688.895.895l.358.196a.625.625 0 0 1 0 1.097l-.358.196a2.25 2.25 0 0 0-.895.894l-.196.359a.625.625 0 0 1-1.096 0l-.196-.359a2.25 2.25 0 0 0-.895-.894l-.358-.196a.625.625 0 0 1 0-1.097l.358-.196a2.25 2.25 0 0 0 .895-.895l.196-.358Z"
            />
            <path
              fill-rule="evenodd"
              d="M12.948 7.89c-.18-1.167-1.852-1.19-2.064-.029l-.03.164a3.756 3.756 0 0 1-3.088 3.031c-1.15.189-1.173 1.833-.03 2.054l.105.02a3.824 3.824 0 0 1 3.029 3.029l.032.165c.233 1.208 1.963 1.208 2.196 0l.025-.129a3.836 3.836 0 0 1 3.077-3.045c1.184-.216 1.12-1.928-.071-2.107a3.789 3.789 0 0 1-3.18-3.154Zm-.944 6.887a5.34 5.34 0 0 1 2.542-2.647 5.305 5.305 0 0 1-2.628-2.548 5.262 5.262 0 0 1-2.488 2.508 5.329 5.329 0 0 1 2.574 2.687Z"
            /></svg
        ></chatty-icon>
        ${
          state === 'loading'
            ? html`<p role="status" tabindex="-1">AI is generating...</p>`
            : state === 'ready'
              ? html`<p
                    style="margin:0 0 4px;font-size:var(--chatty-type-body-small-size);color:var(--chatty-color-text-secondary)"
                  >
                    Tab to accept
                  </p>
                  <p style="margin:0 0 8px;color:var(--p-color-text-magic,#5700d1)">
                    ${suggestion}
                  </p>
                  <chatty-button @click=${use}>Use</chatty-button>`
              : state === 'error'
                ? html`<p role="alert" tabindex="-1">
                      Could not generate suggestion. Please try again.
                    </p>
                    <chatty-button @click=${() => request(true)}>Retry</chatty-button>`
                : html`<p role="status" tabindex="-1">
                      ${state === 'empty' ? 'No new suggestion available...' : 'Waiting for next customer message...'}
                    </p>
                    <chatty-button @click=${() => request(true)}>Generate again</chatty-button>`
        }
      </section>`,
      panel
    );
    if (focus) {
      const target =
        panel.querySelector('chatty-button') ?? panel.querySelector('[role=status],[role=alert]');
      Promise.resolve(target.updateComplete).then(() => target.focus());
    }
  };
  return patternShell({
    surface: 'admin',
    store,
    content: html`<div
      slot="footer"
      style="margin-block-end:8px"
      ${ref(node => {
        if (node) {
          panel = node;
          queueMicrotask(() => request());
        }
      })}
    ></div>`
  });
}
```

Fixture lần lượt ready → error → empty khi Generate again/Retry. Use hoặc Tab đưa bản nháp vào composer, không gửi. Cache/server/thread-loading/note tab: N/A trong preview.

### Current

Example (Current (React), being replaced) — Ba Polaris Button mà vùng gợi ý dùng (Use, Retry, Generate again); không gọi API và không phải AISuggestions đầy đủ.

```jsx
import React from 'react';
import {AppProvider, Button} from '@shopify/polaris';

export function Controls() {
  return (
    <AppProvider i18n={{}}>
      <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>
        <Button>Use</Button>
        <Button>Retry</Button>
        <Button>Generate again</Button>
      </div>
    </AppProvider>
  );
}
```

## Admin

### Import / element

#### AISuggestions

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `AISuggestions` | import AISuggestions from '@assets/pages/InboxManagement/Parts/ChatBox/AISuggestions.js'; | Vùng `Avada-Faqs__AI-Suggestions` trong MainChat |

### Anatomy

#### AISuggestions

| Part | Element |
| --- | --- |
| 1 | Header gợi ý Tab to accept, chỉ hiện khi đã có gợi ý. |
| 2 | Trạng thái đang tạo: gif (chỉ desktop) và dòng chữ. |
| 3 | Văn bản gợi ý cùng Polaris `Button` Use. |
| 4 | Vùng lỗi role alert với `Button` Retry. |
| 5 | Trạng thái rỗng hoặc chờ, kèm `Button` Generate again. |

### Placement / order

#### AISuggestions

| Context | Order |
| --- | --- |
| Trong vùng gợi ý | Header, rồi trạng thái đang tạo, rỗng hoặc lỗi, rồi gợi ý, rồi trạng thái chờ, cuối cùng Generate again. |
| Trong ChatBox | Chỉ render khi bật gợi ý trả lời, có quyền yêu cầu bản nháp, thread đã tải xong và không ở tab ghi chú. |

### Props

#### AISuggestions

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `convoId` | string | Id hội thoại | Bắt buộc | Tạo cache key và URL suggest-reply. |
| `channel` | string | Kênh hội thoại | Bắt buộc | Chỉ dùng cho sự kiện đo lường. |
| `mode` | string | manual / auto | manual | ChatBox truyền auto cho kênh draft. |
| `setInputValue` | function | Setter của composer | Bắt buộc | Use gọi hàm này; không có đường gửi tin trực tiếp. |
| `onUse` | function | Callback sau khi dùng | Không có | ChatBox ghi nhận bản nháp được chấp nhận. |
| `usedKey` | number | Bộ đếm tăng khi Tab chấp nhận | 0 | Đổi giá trị thì vùng chuyển sang chờ. |
| `customerMessageCount` | number | Tổng số tin của khách | Bắt buộc | So khớp với cache để dùng lại gợi ý. |

### Sizes

#### AISuggestions

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Vùng gợi ý | Theo nội dung | 12px 16px | 8px | Không khai báo | Theo từng phần tử con | Không tương tác | Không có breakpoint riêng trong rule này |
| Header Tab to accept | 28px | 6px 10px | 4px | 8px | Không khai báo | Không tương tác | Không có breakpoint riêng trong rule này |
| Văn bản gợi ý | Tối đa 3 dòng (`line-clamp: 3`) | Không khai báo | 8px giữa văn bản và nút | Không khai báo | body-medium: Derived(13px = type(body-medium, admin, desktop, size)) / Derived(20px = type(body-medium, admin, desktop, line)) desktop | Văn bản không tương tác | Không có breakpoint riêng trong rule này |
| Đang tạo | Theo nội dung | 12px 0 | 4px | Không khai báo | body-medium: Derived(13px = type(body-medium, admin, desktop, size)) / Derived(20px = type(body-medium, admin, desktop, line)) desktop | Không tương tác | Không có breakpoint riêng trong rule này |
| Rỗng và chờ | Theo nội dung | 12px 0 | Không khai báo | Không khai báo | body-medium: Derived(13px = type(body-medium, admin, desktop, size)) / Derived(20px = type(body-medium, admin, desktop, line)) desktop | Không tương tác | Không có breakpoint riêng trong rule này |

### Tokens

#### AISuggestions

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Văn bản gợi ý | Không có token | #303030 | No Dark skin |
| Chữ trạng thái | Không có token | rgba(0, 0, 0, 0.5) | No Dark skin |
| Nền header | Không có token | rgba(30, 30, 30, 0.04) | No Dark skin |
| Viền header | Không có token | #e3e3e3 | No Dark skin |

### States

#### AISuggestions

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Đang tạo | `status` là loading | Gif 35px trên desktop, dòng AI is generating... | Không có ARIA riêng |
| Sẵn sàng | Có gợi ý sau khi tải | Văn bản gợi ý, nút Use và header Tab to accept | Không có ARIA riêng |
| Rỗng | `status` là empty | Dòng No new suggestion available, kèm Generate again | Không có ARIA riêng |
| Lỗi | `status` là error | Thông báo lỗi và nút Retry | `role` alert |
| Chờ | `status` là waiting | Dòng Waiting for next customer message, kèm Generate again | Không có ARIA riêng |

### Behaviour

#### AISuggestions

| Interaction | Result |
| --- | --- |
| Use | Gọi `setInputValue` với gợi ý đã đổi markdown, chuyển sang chờ, ghi cache consumed; không gửi tin. |
| Tab | Header nhắc Tab to accept; ChatBox chấp nhận qua `acceptSuggestion` và tăng `usedKey`. |
| Retry và Generate again | `handleRequestAgain` xóa cache, quay về loading và gửi lại với `regenerate`. |
| Cache | Chỉ dùng lại khi `customerMessageCount` khớp và còn text, consumed hoặc noData. |
| Liên kết trong gợi ý | `stripAnchorTags` bỏ thẻ a mà LLM có thể sinh ra. |

### Copy

#### AISuggestions

| String | i18n key | Where |
| --- | --- | --- |
| Use | Không có i18n key | Nút trên gợi ý |
| Tab to accept | Không có i18n key | Header khi đã có gợi ý |
| AI is generating... | Không có i18n key | Trạng thái đang tạo |
| No new suggestion available. Waiting for next customer message... | Không có i18n key | Trạng thái rỗng |
| Waiting for next customer message... | Không có i18n key | Trạng thái chờ |
| Could not generate suggestion. Please try again. | Could not generate suggestion. Please try again. | Thông báo lỗi qua `t` |
| Retry | Retry | Nút ở vùng lỗi qua `t` |
| Generate again | Generate again | Nút ở trạng thái rỗng hoặc chờ qua `t` |

### Source

#### AISuggestions

| File | Evidence |
| --- | --- |
|  | Luồng trạng thái và phần tử |
|  | Kiểu vùng gợi ý |
|  | Điều kiện hiển thị và callback |

## Do / Don't

Do: giữ để nhân viên xem lại và chỉnh bản nháp trước khi gửi.

Don't: gửi tự động chỉ vì AI tạo xong.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| Admin | Vùng lỗi có `role` alert; Use, Retry và Generate again là Polaris Button. | Button nhận focus theo Tab; trong AISuggestions không có lệnh đặt focus sau Use hay Retry. | Chỉ vùng lỗi là alert; đang tạo, rỗng và chờ không có live region. | Không đo: nền vùng do MainChat cấp |

## Target

```target
| Surface | Now | Target | Source |
| --- | --- | --- | --- |
| Admin | Trạng thái đang tạo chỉ có gif và dòng chữ; `AISuggestions` không có nút hủy. | Not available — new build follows Target. Sau khi loading kéo dài hơn 1s, hiện chatty-ui Button tertiary cao 28px (Target) tên Cancel cạnh dòng AI is generating... mà không đổi chiều cao vùng loading. Nút có aria-label Cancel; bấm thì vô hiệu hóa nút (chặn kích hoạt lặp), bỏ kết quả của request đang chờ và chuyển sang trạng thái rỗng kèm Generate again. Về trạng thái thường khi khách nhắn tin mới hoặc bấm Generate again. | [WCAG — status messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) |
| Admin | `handleUse` đưa text vào composer mà không đọc lại số tin khách. | Not available — new build follows Target. Trước khi gọi `setInputValue`, so `customerMessageCount` hiện tại với số lúc gợi ý được tạo; nếu lớn hơn thì không áp dụng im lặng mà hiện chatty-ui Banner/Callout tone warning (Target, component dùng chung chưa có) ngay trong vùng gợi ý, giữ nguyên chiều cao vùng, đổi Use thành Generate again. Banner có role status (live polite) và focus ở yên trên nút vừa bấm; nút bị vô hiệu hóa trong lúc tạo lại. Trở về trạng thái sẵn sàng khi gợi ý mới được tạo. |  |
```

Example (Current (React), being replaced) — Target: Cancel 28px và cảnh báo stale trong Inbox; mẫu bố cục tĩnh, chưa nối request thật.

```jsx
import React from 'react';
const radii = {"container": "20px", "dialog": "20px", "popover": "12px", "control": "10px", "element": "8px", "tag": "6px", "checkbox": "4px", "avatar": "clamp(6px, 30%, 12px)", "action": "9999px", "chat-control": ".5rem", "option-item": ".5rem", "kbd": ".25rem"};
const themes = {"light": {"--chatty-color-bg": "#fff", "--chatty-color-bg-fill-caution-secondary": "oklch(.9167 .1785 98.00)", "--chatty-color-bg-fill-critical": "oklch(.9470 .0300 20.50)", "--chatty-color-bg-fill-info-secondary": "oklch(.8637 .1018 216.95)", "--chatty-color-bg-fill-inverse": "#1b1b1b", "--chatty-color-bg-fill-secondary": "#ebebeb", "--chatty-color-bg-fill-success": "oklch(.9672 .0599 131.73)", "--chatty-color-bg-fill-success-secondary": "oklch(.9053 .1942 133.49)", "--chatty-color-bg-fill-tertiary": "#ddd", "--chatty-color-bg-fill-tertiary-hover": "#d0d0d0", "--chatty-color-bg-surface": "#fff", "--chatty-color-bg-surface-critical": "oklch(.9470 .0300 20.50)", "--chatty-color-bg-surface-secondary": "#f7f7f7", "--chatty-color-bg-surface-secondary-selected": "#ebebeb", "--chatty-color-bg-surface-success": "oklch(.9672 .0599 131.73)", "--chatty-color-bg-surface-tertiary": "#f2f2f2", "--chatty-color-bg-surface-warning": "oklch(.9557 .0350 67.45)", "--chatty-color-border": "rgba(221,221,221,1)", "--chatty-color-border-secondary": "rgba(242,242,242,1)", "--chatty-color-border-tertiary": "rgba(192,192,192,1)", "--chatty-color-border-warning": "oklch(.9316 .0545 67.18)", "--chatty-color-icon-secondary": "#606060", "--chatty-color-text": "#101010", "--chatty-color-text-brand-on-accent": "#fff", "--chatty-color-text-caution": "oklch(.2708 .0638 90.28)", "--chatty-color-text-critical": "oklch(.2121 .0942 30.90)", "--chatty-color-text-info": "oklch(.2715 .0576 221.37)", "--chatty-color-text-link": "oklch(.4840 .2413 262.80)", "--chatty-color-text-link-inverse": "oklch(.7340 .1449 264.63)", "--chatty-color-text-on-accent": "#fff", "--chatty-color-text-secondary": "rgba(74,74,74,1)", "--chatty-color-text-success": "oklch(.2334 .0796 134.14)", "--chatty-color-text-warning": "oklch(.2475 .0726 51.49)"}, "dark": {"--chatty-color-bg": "#121212", "--chatty-color-bg-fill-caution-secondary": "#4f4700", "--chatty-color-bg-fill-critical": "#2f040b", "--chatty-color-bg-fill-info-secondary": "#003a5a", "--chatty-color-bg-fill-inverse": "#303030", "--chatty-color-bg-fill-secondary": "#373737", "--chatty-color-bg-fill-success": "#014b40", "--chatty-color-bg-fill-success-secondary": "#014b40", "--chatty-color-bg-fill-tertiary": "#414141", "--chatty-color-bg-fill-tertiary-hover": "#585858", "--chatty-color-bg-surface": "#1a1a1a", "--chatty-color-bg-surface-critical": "#5f0716", "--chatty-color-bg-surface-secondary": "#282828", "--chatty-color-bg-surface-secondary-selected": "#373737", "--chatty-color-bg-surface-success": "#073630", "--chatty-color-bg-surface-tertiary": "#2f2f2f", "--chatty-color-bg-surface-warning": "#412d00", "--chatty-color-border": "#ffffff17", "--chatty-color-border-secondary": "#ffffff0f", "--chatty-color-border-tertiary": "#ffffff2e", "--chatty-color-border-warning": "#956f00", "--chatty-color-icon-secondary": "#aaa", "--chatty-color-text": "#eee", "--chatty-color-text-brand-on-accent": "#121212", "--chatty-color-text-caution": "#ffeb78", "--chatty-color-text-critical": "#f78086", "--chatty-color-text-info": "#a8d8ff", "--chatty-color-text-link": "#c5d0ff", "--chatty-color-text-link-inverse": "#c5d0ff", "--chatty-color-text-on-accent": "#121212", "--chatty-color-text-secondary": "#aaa", "--chatty-color-text-success": "#2ced83", "--chatty-color-text-warning": "#ffc879"}};
const frameStyle = {
 ...themes.light,
 ...Object.fromEntries(Object.entries(radii).map(([role,value])=>['--chatty-radius-'+role,value])),
 '--chatty-type-family':'ShopifyInter, ui-sans-serif, system-ui, sans-serif',
 '--chatty-type-weight-regular':400,'--chatty-type-weight-medium':500,'--chatty-type-weight-semibold':600,
 '--chatty-type-body-medium-size':'13px','--chatty-type-body-medium-line':'20px',
 '--chatty-type-button-label-size':'12px','--chatty-type-button-label-line':'16px',
 '--chatty-type-badge-label-size':'12px','--chatty-type-badge-label-line':'18px',
 fontFamily:'var(--chatty-type-family)',fontSize:'var(--chatty-type-body-medium-size)',lineHeight:'var(--chatty-type-body-medium-line)',fontWeight:'var(--chatty-type-weight-regular)',
 color:'var(--chatty-color-text)',background:'var(--chatty-color-bg-surface)',padding:16
};
const box = {border:'1px solid #888',background:'#f7f7f7',padding:12,color:'#101010',font:'inherit'};
function Target({children}) { return <div data-inbox-target style={frameStyle}><link rel="stylesheet" href="https://cdn.shopify.com/static/fonts/shopifyinter/v0/styles.css"/><p style={{marginTop:0}}>Target · design fixture · phase 1b chưa ship</p>{children}</div>; }
function RadiusSample({role,value}) {
 const style={...box,borderRadius:`var(--chatty-radius-${role})`};
 if(role==='checkbox')return <input aria-label="Checkbox radius sample" type="checkbox" style={{...style,appearance:'none',width:24,height:24,padding:0}}/>;
 if(role==='avatar')return <span role="img" aria-label="Avatar initials" style={{...style,width:36,height:36,padding:0,display:'grid',placeItems:'center'}}>AB</span>;
 if(role==='tag')return <span style={{...style,padding:'0 8px',display:'inline-block'}}>Status</span>;
 if(role==='kbd')return <kbd style={{...style,padding:'0 6px'}}>A</kbd>;
 if(['action','control','chat-control','option-item'].includes(role))return <button type="button" style={style}>Action</button>;
 if(role==='dialog')return <dialog open aria-label="Dialog radius sample" style={{...style,position:'static',margin:0}}>Dialog</dialog>;
 return <section aria-label={`${role} radius sample`} style={style}>{role}</section>;
}
export function Feedback() {
 const action={font:'var(--chatty-type-weight-medium) var(--chatty-type-button-label-size)/var(--chatty-type-button-label-line) var(--chatty-type-family)',height:28,padding:'0 12px',border:0,borderRadius:'var(--chatty-radius-action)',color:'var(--chatty-color-text)',background:'transparent'};
 return <Target><div style={{display:'grid',gap:16}}><section data-feedback-kind="loading" style={{...box,borderRadius:'var(--chatty-radius-element)'}}><span role="status">AI is generating…</span> <button type="button" style={action}>Cancel</button></section><section data-feedback-kind="stale" role="status" aria-live="polite" style={{padding:12,border:'1px solid var(--chatty-color-border-warning)',borderRadius:'var(--chatty-radius-element)',background:'var(--chatty-color-bg-surface-warning)',color:'var(--chatty-color-text-warning)'}}><strong style={{fontWeight:'var(--chatty-type-weight-semibold)'}}>New customer message</strong><p>This suggestion is out of date.</p><button type="button" style={action}>Generate again</button></section></div><p>Target · mẫu bố cục tĩnh; không có request thật để hủy. API chatty-ui mới và logic tránh dùng gợi ý cũ chưa ship.</p></Target>;
}
```


- [WCAG — status messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
