# Offline / after hours

Classic đổi sang form liên hệ ngoài giờ; AI Mode báo tình trạng giờ làm việc ở header.

## Key rules

- Classic: ngoài giờ dùng `OfflineForm` thay vùng tin nhắn; Send chỉ bật khi đủ tên, email hợp lệ và nội dung.
- AI Mode: trạng thái giờ làm việc nằm ở header bằng `LiveDot` và nhãn; ẩn hẳn khi hook trả null.
- Classic: Send cao tối thiểu 44px; input cao 38px.
- AI Mode: chấm trạng thái 9px; màu lấy từ `STATUS_DOT_COLOR` theo state.
- Nhãn trạng thái do hook tính từ cấu hình giờ; component không hard-code nhãn hay màu.

## Use when / Avoid

Classic cần form liên hệ khi shop ngoài giờ; AI Mode chỉ có chỉ báo trạng thái ở header, không có form ngoài giờ trong code. Thu thông tin liên hệ theo nhóm field xem [Contact / email form](https://chatty-ui-research.avada-tesla-chatty.workers.dev/patterns/contact-email-form/); chuyển người xem [Handoff to a human](https://chatty-ui-research.avada-tesla-chatty.workers.dev/patterns/handoff-to-a-human/).

### Use instead

| Component | Use when |
| --- | --- |
| `OfflineForm` | Classic ngoài giờ: tên, email và nội dung trong một form. |
| `LiveDot` | AI Mode: chấm trạng thái ở header theo availability. |
| `ContactComposer` | Thu thông tin liên hệ theo nhóm field trong composer, không phụ thuộc giờ làm việc. |

## Entry points

| Surface | Owner |
| --- | --- |
| Classic | `OfflineForm` thay vùng tin nhắn trong ChatPage |
| AI Mode | `LiveDot` trong Panel header |

## Flow

| Surface | Step | Trigger | UI shown | Component | Copy + i18n key | Timing |
| --- | --- | --- | --- | --- | --- | --- |
| Classic | Hiện form | Ngoài giờ và đủ điều kiện hiện form | Form thay vùng tin nhắn | `OfflineForm` | Leave your details and our team will get back to you. / Leave your details and our team will get back to you. | Khi điều kiện đúng ở lần render |
| Classic | Gửi | Bấm Send với dữ liệu hợp lệ | Form aria-busy, field và nút disabled | `OfflineForm` | Send / Send | Theo prepareBeforeSend |
| Classic | Lỗi | Không tạo được hội thoại | Dòng lỗi role alert | `OfflineForm` | Couldn't send. Please try again. / Couldn't send. Please try again. | Sau khi prepareBeforeSend trả về |
| AI Mode | Tính trạng thái | Panel mount, rồi mỗi phút | Không hiển thị gì nếu hook trả null | `LiveDot` | Online status / Online status | Mỗi phút |
| AI Mode | Hiện trạng thái | Hook trả label | Chấm màu và nhãn dưới tên shop | `LiveDot` | Offline status message / Offline status message | Ngay khi availability có giá trị |

## Edge cases

| Surface | Case | Behaviour |
| --- | --- | --- |
| Classic | Visitor đang bị sign-in gate | Form nhường cho sign-in gate |
| Classic | Preview trong admin | Submit không làm gì |
| Classic | Thiếu tên, email hoặc nội dung, hoặc email sai | Send bị disable |
| Classic | Không tạo được hội thoại | Hiện dòng lỗi và giữ form |
| AI Mode | Merchant chưa bật trạng thái | Hook trả null, header không có chấm và nhãn |
| AI Mode | Cấu hình giờ thiếu hoặc sai | Hook trả null thay vì làm hỏng header |
| AI Mode | Label rỗng | Hook trả null |

## Live preview

Classic dùng form fixture, lần Send đầu hiện lỗi và giữ dữ liệu, Retry thành công mới hiện lại thread; không gọi API. Availability của AI Mode đổi Open / Closed / No status bằng control ngoài widget và ngoài Code.

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 {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>`;
}

import {contactFieldError} from '@avada/chatty-ui/behaviors/contact.js';
import '@avada/chatty-ui/elements/text-field.js';
export function Standard({surface}) {
  const store = fixtureStore([
    {
      id: 'greeting',
      senderType: 'bot',
      text: 'Our team is away. Leave a message and we will reply by email.'
    }
  ]);
  if (surface === 'ai-mode')
    return patternShell({surface, store, title: 'Example store', status: 'offline'});
  let busy = false;
  let attempts = 0;
  const fields = form => [...form.querySelectorAll('chatty-text-field, textarea')];
  const values = form =>
    Object.fromEntries(fields(form).map(field => [field.name, field.value.trim()]));
  const update = form => {
    const data = values(form);
    form.querySelector('chatty-button').disabled =
      busy ||
      !data.name ||
      !data.message ||
      !!contactFieldError({field: 'email', value: data.email, required: true});
  };
  const submit = event => {
    event.preventDefault();
    const form = event.currentTarget;
    update(form);
    const button = form.querySelector('chatty-button');
    if (busy || button.disabled) return;
    const data = values(form);
    const error = form.querySelector('[role=alert]');
    error.hidden = true;
    busy = true;
    form.setAttribute('aria-busy', 'true');
    fields(form).forEach(field => {
      field.disabled = true;
    });
    button.loading = true;
    const finish = () => {
      if (!form.isConnected) return;
      busy = false;
      form.setAttribute('aria-busy', 'false');
      fields(form).forEach(field => {
        field.disabled = false;
      });
      button.loading = false;
      if (++attempts === 1) {
        error.hidden = false;
        error.focus({preventScroll: true});
        update(form);
        return;
      }
      const host = form.closest('chatty-surface');
      appendViewer(store, surface, data.message);
      store.setMessages([
        ...store.getState().messages,
        {
          id: 'offline-answer',
          senderType: 'bot',
          text: `Thanks, ${data.name}. We will reply to ${data.email}.`
        }
      ]);
      host.querySelector('chatty-thread').hidden = false;
      const composer = host.querySelector('chatty-composer');
      composer.hidden = false;
      host.closest('[data-offline-frame]').removeAttribute('data-offline-frame');
      form.remove();
      composer.renderRoot.querySelector('textarea').focus({preventScroll: true});
    };
    if (matchMedia('(prefers-reduced-motion: reduce)').matches) finish();
    else setTimeout(finish, 450);
  };
  return html`<div data-offline-frame style="inline-size:100%;min-inline-size:0">
    <style>
      [data-offline-frame] chatty-surface::part(footer) {
        display: none;
      }
    </style>
    ${patternShell({
      surface,
      store,
      status: 'offline',
      title: 'Example store',
      composerHidden: true,
      content: html`<form
        aria-label="Offline message"
        aria-busy="false"
        style="display:grid;gap:12px;--chatty-text-field-height:38px;--chatty-button-height:44px"
        ${ref(form => {
          if (form)
            queueMicrotask(() => {
              const thread = form.closest('chatty-surface')?.querySelector('chatty-thread');
              if (thread) thread.hidden = true;
            });
        })}
        @input=${event => update(event.currentTarget)}
        @submit=${submit}
      >
        <p style="margin:0">Leave your details and our team will get back to you.</p>
        <chatty-text-field
          name="name"
          autocomplete="name"
          placeholder="Name"
          required
          .label=${html`Name <span style="color:var(--chatty-color-critical)">*</span>`}
        ></chatty-text-field>
        <chatty-text-field
          name="email"
          type="email"
          autocomplete="email"
          placeholder="Email address"
          required
          .label=${html`Email address <span style="color:var(--chatty-color-critical)">*</span>`}
        ></chatty-text-field>
        <label style="display:grid;gap:4px">
          <span>Message <span style="color:var(--chatty-color-critical)">*</span></span>
          <textarea
            name="message"
            required
            placeholder="Message"
            style="box-sizing:border-box;min-block-size:88px;inline-size:100%;padding:8px 12px;border:1px solid var(--chatty-color-border-strong);border-radius:8px;background:var(--chatty-color-bg-surface);color:inherit;font:inherit"
          ></textarea>
        </label>
        <p role="alert" tabindex="-1" hidden style="margin:0;color:var(--chatty-color-critical)">
          Couldn't send. Please try again.
        </p>
        <chatty-button
          type="submit"
          variant="primary"
          style="inline-size:100%;--chatty-button-width:100%"
          disabled
          >Send</chatty-button
        >
      </form>`
    })}
  </div>`;
}
```

### Current

Example (Current (React), being replaced) — OfflineForm thật ở chế độ preview; không gửi dữ liệu ra ngoài.

```jsx
import React from 'react';
import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx';
import {LiveDot} from '@scripttag/v2/components/LiveDot.jsx';
import {CHAT_STATUS, STATUS_DOT_COLOR} from '@assets/const/chatAvailability';

export function Offline({surface}) {
  if (surface === 'classic')
    return <OfflineForm i18n={text => text} prepareBeforeSend={async () => true} isPreview />;
  return (
    <div className="aimode-panel-header-title">
      {[CHAT_STATUS.ONLINE, CHAT_STATUS.OFFLINE].map(state => (
        <span key={state} className="aimode-panel-header-status">
          <LiveDot availability={{dotColor: STATUS_DOT_COLOR[state]}} /> {state}
        </span>
      ))}
    </div>
  );
}
```

Example (Current (React), being replaced) — LiveDot thật với màu STATUS_DOT_COLOR; markup bao quanh chỉ là fixture, không phải Panel header.

```jsx
import React from 'react';
import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx';
import {LiveDot} from '@scripttag/v2/components/LiveDot.jsx';
import {CHAT_STATUS, STATUS_DOT_COLOR} from '@assets/const/chatAvailability';

export function Offline({surface}) {
  if (surface === 'classic')
    return <OfflineForm i18n={text => text} prepareBeforeSend={async () => true} isPreview />;
  return (
    <div className="aimode-panel-header-title">
      {[CHAT_STATUS.ONLINE, CHAT_STATUS.OFFLINE].map(state => (
        <span key={state} className="aimode-panel-header-status">
          <LiveDot availability={{dotColor: STATUS_DOT_COLOR[state]}} /> {state}
        </span>
      ))}
    </div>
  );
}
```

## Classic

### Import / element

#### OfflineForm

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `OfflineForm` | import OfflineForm from '@scripttag/v1/Parts/OfflineForm/OfflineForm.jsx'; | .Avada-Faqs_Popup |

### Anatomy

#### OfflineForm

| Part | Element |
| --- | --- |
| 1 | Dòng dẫn đầu trước các field. |
| 2 | Ba field có nhãn và dấu \* ngoài i18n: Name, Email address, Message. |
| 3 | Dòng lỗi `p` với role alert khi gửi thất bại. |
| 4 | Nút Send dùng class `Avada-Faqs_Primary-Button`. |

### Placement / order

#### OfflineForm

| Context | Order |
| --- | --- |
| Trong ChatPage | Form thay `ChatMessagesArea` khi `showOfflineForm` đúng; điều kiện nhường cho sign-in gate. |
| Bên trong form | Dòng dẫn đầu, Name, Email address, Message, lỗi, Send. |

### Props

#### OfflineForm

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `i18n` | Function | Hàm dịch của caller | None | Dịch mọi chuỗi trong form. |
| `prepareBeforeSend` | Function | Hàm async của caller | None | Tạo hội thoại offline; trả về giá trị falsy thì form báo lỗi. |
| `isPreview` | boolean | true / false | `false` | true: submit không làm gì. |

### Sizes

#### OfflineForm

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Form | Theo nội dung | 16px | 12px | Không khai báo | Kế thừa màu và cỡ chữ từ popup | Không áp dụng | Không có override theo viewport |
| Label | Theo nội dung | Không khai báo | 4px | Không khai báo | 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 tương tác | JS .mobile khi mobileMaxWidth 899px |
| Input | 38px | 8px 12px | Không khai báo | Không khai báo | input-value Derived(15px = type(input-value, desktop, size)) / Derived(22px = type(input-value, desktop, line)) desktop → Derived(18px = type(input-value, mobile, size)) / Derived(24px = type(input-value, mobile, line)) mobile | 38px | JS .mobile khi mobileMaxWidth 899px |
| Send | min-height 44px | Theo style trình duyệt | Không khai báo | Không khai báo | button-label Derived(14px = type(button-label, desktop, size)) / Derived(18px = type(button-label, desktop, line)) desktop → Derived(17px = type(button-label, mobile, size)) / Derived(24px = type(button-label, mobile, line)) mobile | 44px | JS .mobile khi mobileMaxWidth 899px |

### Tokens

#### OfflineForm

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Viền field | `--chatty-form-border` | #8a8a8a | #b0b0b0 |
| Nền input | Không có token | Không khai báo | rgba(255, 255, 255, 0.16) |

### States

#### OfflineForm

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Send disabled | Chưa hợp lệ hoặc đang gửi | opacity 0.5; trong popup Dark opacity 0.7 | Native disabled |
| Đang gửi | Submit đang chạy | Field và Send disabled | `aria-busy` trên form |
| Lỗi | prepareBeforeSend thất bại | Hiện dòng lỗi | role alert |
| Preview | `isPreview` bật | Submit không làm gì | Không thêm ARIA |

### Behaviour

#### OfflineForm

| Interaction | Result |
| --- | --- |
| Gửi hợp lệ | Gọi prepareBeforeSend với nội dung, email, tên, type guest và cờ isOfflineForm. |
| Validity | Send chỉ bật khi có tên, email hợp lệ và nội dung. |
| Kích hoạt lặp | Bỏ qua submit khi preview, đang gửi hoặc chưa hợp lệ. |
| Thất bại | Kết quả rỗng hoặc lỗi ném ra đều hiện dòng lỗi. |
| Hiển thị | Form thay vùng tin nhắn khi showOfflineForm đúng; nhường cho sign-in gate. |

### Copy

#### OfflineForm

| String | i18n key | Where |
| --- | --- | --- |
| Leave your details and our team will get back to you. | Leave your details and our team will get back to you. | Dòng dẫn đầu |
| Name | Name | Nhãn và placeholder; dấu \* nằm ngoài i18n |
| Email address | Email address | Nhãn và placeholder |
| Message | Message | Nhãn và placeholder |
| Send | Send | Nút gửi |
| Couldn't send. Please try again. | Couldn't send. Please try again. | Dòng lỗi |

### Source

#### OfflineForm

| File | Evidence |
| --- | --- |
|  | API, validation và ARIA |
|  | Kích thước và state |
|  | Điều kiện hiển thị |

## AI Mode

### Import / element

#### LiveDot

| Component / element | Import / file | Scope root |
| --- | --- | --- |
| `LiveDot` | @scripttag/v2/components/LiveDot.jsx | .chatty-ai-mode; .aimode-panel-header-avatar |

### Anatomy

#### LiveDot

| Part | Element |
| --- | --- |
| 1 | Chấm trạng thái `chatty-live-dot`, màu lấy từ `dotColor`. |
| 2 | Nhãn trạng thái trong `aimode-panel-header-status`, dưới tên shop. |

### Placement / order

#### LiveDot

| Context | Order |
| --- | --- |
| Panel header | Avatar kèm chấm ở góc; bên phải là tên shop rồi nhãn trạng thái; cả hai chỉ render khi có availability. |

### Props

#### LiveDot

| Prop | Type | Values | Default | Notes |
| --- | --- | --- | --- | --- |
| `availability` | object hoặc null | label, state, dotColor | `null` | Panel nhận từ useChatAvailability; null thì ẩn chấm và nhãn. |
| `useChatAvailability` | hook | Trả label, state, dotColor hoặc null | None | Null khi merchant chưa bật, thiếu cấu hình giờ hoặc không có label; tính lại mỗi phút. |

### Sizes

#### LiveDot

| Size | Height | Padding | Gap | Radius | Font role (px/rem) | Hit target | Breakpoint / mechanism |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Dot | 9px | Ring 2px | Không khai báo | 50% | Không có chữ | Không tương tác | Không có override theo viewport |
| Label | Theo role | Không khai báo | Không khai báo | Không khai báo | 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 tương tác | JS .is-mobile ≤899px; hoặc media (hover: none) and (pointer: coarse) |

### Tokens

#### LiveDot

| Part | Token | Light | Dark |
| --- | --- | --- | --- |
| Chấm online | `STATUS_DOT_COLOR` | #29845A | Giống Light |
| Chấm offline và holiday | `STATUS_DOT_COLOR` | #8C9196 | Giống Light |
| Chấm break | `STATUS_DOT_COLOR` | #E6A700 | Giống Light |
| Ring chấm | `--glass-edge` | rgba(20, 19, 24, 0.08) | rgba(255, 255, 255, 0.12) |
| Chữ nhãn | `--vib-2` | rgba(20, 19, 24, 0.74) | rgba(255, 255, 255, 0.74) |

### States

#### LiveDot

| State | Trigger | Visual change (values) | ARIA/attribute |
| --- | --- | --- | --- |
| Online | availability state online | Chấm nền #29845A | Không đặt attribute |
| Offline hoặc holiday | availability state offline hoặc holiday | Chấm nền #8C9196 | Không đặt attribute |
| Break | availability state break | Chấm nền #E6A700 | Không đặt attribute |
| Ẩn | availability là null | Không render chấm và nhãn | Không có node |

### Behaviour

#### LiveDot

| Interaction | Result |
| --- | --- |
| Tính lại | Hook tính lại mỗi phút và khi presence của nhân viên đổi. |
| Ẩn khi lỗi | Thiếu hoặc sai cấu hình giờ thì trả null, header không có trạng thái. |
| Màu chấm | LiveDot đặt background từ dotColor; không có dotColor thì không đặt style. |

### Copy

#### LiveDot

| String | i18n key | Where |
| --- | --- | --- |
| Online status | Online status | Nhãn khi trong giờ và merchant chưa đổi nhãn |
| Offline status message | Offline status message | Nhãn ngoài giờ khi merchant chưa đổi nhãn |
| Usually reply in a few minutes | Usually reply in a few minutes | Nhãn offline mặc định theo cấu hình |

### Source

#### LiveDot

| File | Evidence |
| --- | --- |
|  | Chấm trạng thái |
|  | Hook availability |
|  | CSS chấm và nhãn |

## Do / Don't

Do: ẩn trạng thái khi chưa có cấu hình giờ thay vì hiện nhãn đoán.

Don't: tự đặt nhãn hoặc màu trạng thái ngoài kết quả của hook.

## Accessibility

| Surface | Role / name | Keyboard / focus | Live region | Contrast pair / ratio |
| --- | --- | --- | --- | --- |
| Classic | Form có aria-busy khi gửi; label bọc từng field; lỗi nằm trong `p` với role alert. | Enter trong form gửi dữ liệu; Send disabled khi chưa hợp lệ. OfflineForm không quản lý focus sau khi gửi hay khi lỗi; không có control Retry riêng, người dùng bấm Send lại. | Lỗi trong role alert; không có live region cho thành công. | Không đo: màu chữ kế thừa từ popup và nền Send do class của merchant |
| AI Mode | Chấm là span không có role hay tên; trạng thái đọc qua nhãn chữ. | Không tương tác và không nhận focus. | Không có live region; nhãn đổi khi hook tính lại. | Không đo vì nền glass có alpha |

