# SEO

Widget chạy trên store của merchant: không làm chậm, không xê dịch, không sửa URL hay nội dung mà Google index.

## Key rules

- Bật Chatty làm Lighthouse store tụt tối đa 10 điểm; phần chat chỉ tải sau tương tác đầu.
- CLS do Chatty bằng 0: widget `position: fixed`, khối inline giữ sẵn chiều cao.
- 0 lần `pushState`; không sửa `<title>`, meta, canonical, query hay hash của trang.
- Mobile dưới 768px: không tự mở panel, teaser sớm nhất sau 5 giây.
- FAQ hiện được khi script lỗi; 1 node `FAQPage` mỗi trang.

## Principle

Merchant cài Chatty để bán hàng, không phải để đổi thứ hạng tìm kiếm lấy một khung chat. Widget hiện chạy trong light DOM của theme, không có iframe, nên mọi thẻ, script, font và lệnh đổi URL của mình đều được Googlebot render cùng trang. Khi widget chuyển sang element `chatty-*` có shadow root, nội dung cần index vẫn đi qua slot ở light DOM (xem Target và [Web Components](https://chatty-ui-research.avada-tesla-chatty.workers.dev/foundations/web-components/)). Core Web Vitals (LCP, CLS, INP) là tín hiệu xếp hạng, và Shopify chấm Built for Shopify bằng mức tụt Lighthouse. Vì vậy mỗi thay đổi ở storefront phải trả lời ba câu: trang có chậm hơn không, có xê dịch không, Google có thấy thứ gì khác trước không.

Phần chat là nội dung sau tương tác: Google không bấm launcher, nên tin nhắn, heading trong bubble hay link sản phẩm trong panel gần như không ảnh hưởng index. Thứ ảnh hưởng thật là phần tải trước tương tác (loader, font, khối inline), URL, title, và nội dung FAQ mà merchant muốn được tìm thấy.

## Rule details

| Rule | Why | How to check |
| --- | --- | --- |
| Không tụt quá 10 điểm Lighthouse | Ngưỡng Built for Shopify; LCP/INP là tín hiệu xếp hạng | Lighthouse mobile trên cùng store, tắt rồi bật app embed, lấy trung vị 3 lượt |
| Tải async, phần nặng sau tương tác | Script chặn render đẩy LCP lên | Network: không có script/stylesheet chặn trong head; chunk chat chỉ xuất hiện sau mousemove, scroll, touch hoặc focus |
| Không preconnect hay preload khi chưa cần | Hint sớm tranh băng thông với ảnh hero | Head của theme không có hint trỏ về domain Chatty |
| Font của widget dùng `display=swap` và chỉ tải khi merchant chọn font khác theme | Font chặn render làm chữ trang trắng | Network: không có request font trước khi launcher mount |
| Element inline giữ chỗ | Khối từ `display:none` bật ra đẩy nội dung xuống, tính vào CLS | Performance panel: Layout Shift không trỏ vào node của Chatty |
| URL giữ nguyên | Đổi query hay hash tạo URL trùng, mất UTM, sai canonical | Mở rồi đóng widget với `?variant=1&utm_source=x#review`: URL giống hệt trước đó |
| Title chỉ đổi khi tab đang ẩn | Googlebot render ở tab hiện, title đổi lúc tải sẽ bị index | Tải trang ở tab hiện: `document.title` không đổi |
| Không tự mở che nội dung trên mobile | Google hạ hạng trang có interstitial che nội dung ngay khi vào từ kết quả tìm kiếm | Mobile 390px, vào trang mới: chỉ thấy launcher hoặc teaser, không thấy panel |
| JSON-LD khớp nội dung hiển thị | Structured data mà người dùng không thấy là vi phạm chính sách | Rich Results Test: 1 `FAQPage`, câu hỏi trùng với chữ trên trang |
| Link ra ngoài có `rel` đúng | Link do AI sinh ra là nội dung không kiểm soát | Link ngoài domain store có `rel="noopener noreferrer"`; thêm `nofollow` khi link không do merchant tự đặt |

## Surface

### Shared loader

| Point | Now | Source |
| --- | --- | --- |
| App embed | Shopify chèn `chatty.js` từ app embed ở cuối body |  |
| Bundle chính | `chatty.js` chèn `chatty.min.js` dạng `async`, không có cache-buster |  |
| Trang bị loại | Không tải bundle trên trang mà display rule loại trừ, trừ khi trang có theme block |  |
| Chọn surface | Classic hay AI Mode qua dynamic `import()` |  |
| Resource hint | Không có preconnect, dns-prefetch hay preload | Không có trong code |
| Head | Không ghi canonical, robots hay meta; chỉ thêm stylesheet và style | Không có trong code |
| Param Smart link | Lúc boot `replaceState` gỡ các param `chatty_*` |  |
| Lịch sử | Bọc `pushState` và `replaceState` để tracking, không tự gọi `pushState` |  |

### Classic widget

| Point | Now |
| --- | --- |
| Tải panel | Launcher tải trước; panel chờ mousemove, scroll, touchstart hoặc keydown đầu tiên |
| Vị trí | Launcher và popup `position: fixed` |
| Title | Thêm `(n)` vào `document.title` khi tab ẩn và có tin mới, trả lại khi tab hiện |
| Đóng sau khi mở bằng hash | `replaceState(null, '', pathname)` xoá cả query lẫn hash |
| Teaser | Delay `(Number(value) \|\| 5) * 1000`, nên 0 thành 5 giây; có trigger theo % cuộn |
| Mở lại ở trang sau | Panel đang mở thì mở lại ở trang kế; dưới 768px giữ đóng trừ khi có hash |
| Font | fonts.bunny.net với `display=swap`, tải khi panel mount |

### AI Mode widget

| Point | Now |
| --- | --- |
| Tải | Launcher nghỉ render trước; runtime đầy đủ tải khi pointerenter, pointerdown hoặc focus launcher |
| Trần bundle | 61 KB gzip trước first paint, 108 KB trước tương tác |
| Vị trí | Root `position: fixed`, gắn cuối body |
| Teaser | Cho phép delay 0 giây, mặc định 5 giây, có trigger cuộn |
| Font | Tải khi launcher mount, trước tương tác, nếu merchant chọn font khác theme |
| Title | Chỉ đọc, không ghi |

### FAQ page and FAQ blocks

| Point | Now |
| --- | --- |
| Nội dung FAQ page | Render bằng JS vào `#AVADA_PAGE_FAQS`; HTML server chỉ có placeholder |
| Script lỗi | Trang trắng: loader bị CSS ẩn và gỡ sau 30 giây |
| Cache | Loader gắn `&v=` + thời gian hiện tại, mỗi lượt xem tải lại từ đầu |
| Title trang | CSS ẩn `.main-page-title.page-title`, thường là `h1` của theme |
| JSON-LD FAQ page | Liquid render `FAQPage` trên đường dẫn FAQ, `@id` cố định `/faq` |
| JSON-LD FAQ block | Mỗi block render thêm `FAQPage` với cùng `@id/faq`, cả trên trang sản phẩm |
| Hiện block | Container bắt đầu `display:none`, JS bật lên, không giữ chiều cao |

### Idle layout

Không ghi DOM rồi đọc geometry trong cùng một task. Gom geometry reads vào requestAnimationFrame (rAF), cache bề rộng; chỉ invalidate khi resize, font hoặc class/style ảnh hưởng kích thước đổi, hay khi widget/dock được thay thế. Không tạo phần tử chỉ để đo. rAF gom lượt đọc theo frame, không bảo đảm hết forced layout nếu theme vừa làm bẩn style.

| Point | Now |
| --- | --- |
| Geometry reads | Add to cart guard lên lịch đo trong rAF, đọc geometry của control đang có; không chèn phần tử đo tạm. |
| Width cache | Cache bề rộng dock; invalidate khi viewport resize, font tải xong, class/style của widget hoặc class của dock đổi, hay khi dock được thay thế. |
| Performance evidence | Số đo đã bàn giao, trong mười giây sau tải: forced style/layout lúc idle từ 147 xuống 12 ms ở một store, về 0 ở hai store khác. Phần 12 ms còn lại là đọc rect của Add to cart trong rAF khi theme vừa làm bẩn style của frame đó; không phải cam kết mọi store đều về 0. |

Example — Luồng đọc geometry và tổng forced layout lúc idle trước/sau tối ưu.

```jsx
import React, {useEffect, useRef, useState} from 'react';
import {readMotionDuration} from '@avada/chatty-ui/primitives/surfaceMorph.js';
import {IconBag} from '@avada/chatty-ui/icons/chatIcons.jsx';

function Diagram({id, children}) {
  return <figure data-rule-visual={id} style={{margin: 0, color: 'var(--vib-1, #25252a)', fontFamily: 'inherit'}}>
    <style>{`
      [data-rule-visual] * { box-sizing: border-box; }
      [data-rule-visual] .rule-columns { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
      [data-rule-visual] .rule-stage { position:relative; height:230px; overflow:hidden; border:1px solid #85858b; border-radius:12px; background:var(--bg-deep, #fff); margin-top:10px; }
      [data-rule-visual] .rule-store { padding:14px; font-size:12px; line-height:1.5; }
      [data-rule-visual] .rule-product { display:flex; gap:8px; margin-top:12px; align-items:center; }
      [data-rule-visual] .rule-image { width:36px; height:36px; flex:none; background:#d9d5ce; border-radius:4px; }
      [data-rule-visual] .rule-panel { position:absolute; left:12px; bottom:12px; background:#4759a8; border:1px solid #c2c9ef; border-radius:16px; color:white; overflow:hidden; }
      [data-rule-visual] .rule-panel span { display:block; width:130px; padding:10px; font-size:12px; }
      [data-rule-visual] .rule-controls { display:flex; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:14px; }
      [data-rule-visual] .rule-replay { font:inherit; color:inherit; background:transparent; padding:6px 14px; border:1px solid currentColor; border-radius:8px; cursor:pointer; }
      [data-rule-visual] .rule-replay:focus-visible { outline:3px solid #657fdf; outline-offset:3px; }
      [data-rule-visual] figcaption, [data-rule-visual] .rule-note { font-size:12px; line-height:1.55; margin-top:12px; }
      [data-rule-visual] .rule-header-view { position:relative; height:150px; display:grid; place-items:center; border:1px solid #85858b; border-radius:12px; overflow:hidden; margin-top:12px; }
      [data-rule-visual] .rule-header { position:relative; width:150px; height:72px; border:1px solid #85858b; border-radius:10px; display:flex; justify-content:center; align-items:center; }
      [data-rule-visual] .rule-header:after { content:''; position:absolute; left:0; right:0; top:50%; border-top:1px dashed #b55c42; pointer-events:none; }
      [data-rule-visual] .rule-header-control { position:relative; padding:0; border:0; background:transparent; color:inherit; width:48px; height:48px; display:grid; grid-auto-rows:min-content; align-content:center; justify-items:center; transform:scale(2); }
      [data-rule-visual] .rule-header-control::before { content:''; height:6px; width:100%; }
      [data-rule-visual] .rule-header-control[data-fixed]::before { position:absolute; inset:0; }
      [data-rule-visual] .rule-header-control svg { display:block; width:22px; height:22px; }
      [data-rule-visual] .rule-timeline { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; align-items:start; margin:16px 0; font-size:12px; }
      [data-rule-visual] .rule-track { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
      [data-rule-visual] .rule-task { padding:8px; border:1px solid #85858b; border-radius:4px; }
      [data-rule-visual] .rule-cost { display:block; height:16px; border-radius:3px; margin-top:8px; }
      [data-rule-visual] .rule-resize-axis { position:relative; height:90px; margin-top:14px; font-size:12px; }
      [data-rule-visual] .rule-resize-axis::before { content:''; position:absolute; top:32px; left:0; right:0; border-top:1px solid #85858b; }
      [data-rule-visual] .rule-time-mark { position:absolute; top:24px; height:20px; border-left:1px dashed currentColor; }
      [data-rule-visual] .rule-time-mark span { position:absolute; top:-19px; transform:translateX(-50%); }
      [data-rule-visual] .rule-time-bar { position:absolute; top:34px; left:0; height:10px; border-radius:3px; }
      [data-rule-visual] .rule-time-label { position:absolute; top:54px; left:0; right:0; line-height:1.4; }
      [data-rule-visual] .rule-chart { display:grid; gap:8px; margin-top:14px; }
      [data-rule-visual] .rule-metric-columns { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; font-size:12px; text-align:center; }
      [data-rule-visual] .rule-bar-track { height:110px; display:flex; align-items:end; justify-content:center; border-bottom:1px solid #85858b; }
      [data-rule-visual] .rule-bar { width:70%; min-height:2px; background:#4759a8; border-radius:3px 3px 0 0; }
      [data-rule-visual] .rule-bar-value { min-height:36px; display:flex; align-items:end; justify-content:center; }
      @media(max-width:380px) { [data-rule-visual] .rule-columns { gap:8px; } [data-rule-visual] .rule-stage { height:240px; } }
      @media(prefers-reduced-motion:reduce) { [data-rule-visual], [data-rule-visual] * { animation:none !important; transition:none !important; } }
    `}</style>
    {children}
  </figure>;
}

function SurfaceComparison({resize = false}) {
  const root = useRef(null);
  const [run, setRun] = useState(0);
  const played = useRef(0);
  const [state, setState] = useState('Ready');
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    const media = matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReduced(media.matches);
    update();
    media.addEventListener('change', update);
    return () => media.removeEventListener('change', update);
  }, []);
  useEffect(() => {
    if (!run) return;
    if (played.current === run) {
      setState('Ready');
      return;
    }
    played.current = run;
    const element = root.current;
    const stages = [...element.querySelectorAll('.rule-stage')];
    const panels = stages.map(stage => stage.querySelector('.rule-panel'));
    const store = stages[0].querySelector('.rule-store');
    const style = getComputedStyle(element);
    const open = readMotionDuration({style, token: resize ? '--chatty-motion-duration-350' : '--chatty-motion-duration-400', fallback: resize ? 350 : 400});
    const targetDuration = resize ? 280 : open;
    const tailDelay = resize ? 206 : 0;
    const close = readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350});
    const easing = style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)';
    const startWidth = resize ? 94 : 54;
    const startHeight = resize ? 102 : 38;
    const widths = stages.map(stage => stage.clientWidth - 24);
    const animations = [];
    let cancelled = false;
    let hold;
    let releaseHold;
    const pause = () => new Promise(resolve => { releaseHold = resolve; hold = setTimeout(resolve, 500); });
    const animate = (node, frames, duration, delay = 0) => {
      const animation = node.animate(frames, {duration, delay, easing, fill: 'forwards'});
      animations.push(animation);
      return animation.finished;
    };
    const show = expanded => {
      panels.forEach((panel, index) => Object.assign(panel.style, {
        width: `${expanded ? widths[index] : startWidth}px`, height: `${expanded ? 150 : startHeight}px`, clipPath: 'none'
      }));
    };
    const play = async () => {
      setState('Opening');
      if (reduced) {
        show(true);
        await pause();
        if (cancelled) return;
        show(false);
        setState('Done');
        return;
      }
      const geometry = [{width: `${startWidth}px`, height: `${startHeight}px`}, {width: `${widths[0]}px`, height: '150px'}];
      Object.assign(panels[1].style, {width: `${widths[1]}px`, height: '150px'});
      const clips = [
        {clipPath: `inset(${150 - startHeight}px ${Math.max(0, widths[1] - startWidth)}px 0 0 round 16px)`},
        {clipPath: 'inset(0px 0px 0px 0px round 16px)'}
      ];
      await Promise.all([
        animate(panels[0], geometry, open, tailDelay),
        animate(panels[1], clips, targetDuration),
        animate(store, [{transform: 'translateY(0px)'}, {transform: 'translateY(14px)'}], open, tailDelay)
      ]);
      if (cancelled) return;
      setState('Open');
      await pause();
      if (cancelled) return;
      setState('Closing');
      await Promise.all([
        animate(panels[0], [...geometry].reverse(), close, tailDelay),
        animate(panels[1], [...clips].reverse(), resize ? targetDuration : close),
        animate(store, [{transform: 'translateY(14px)'}, {transform: 'translateY(0px)'}], close, tailDelay)
      ]);
      if (!cancelled) setState('Done');
    };
    play().catch(error => { if (!cancelled) throw error; });
    return () => {
      cancelled = true;
      clearTimeout(hold);
      releaseHold?.();
      animations.forEach(animation => animation.cancel());
      store.style.transform = '';
      show(false);
    };
  }, [run, reduced, resize]);
  return <div ref={root} data-comparison={resize ? 'resize' : 'overlay'} data-run={run} data-state={state} data-reduced={reduced}>
    <div className="rule-controls">
      <button className="rule-replay" type="button" onClick={() => setRun(value => value + 1)}>Replay</button>
      <span role="status">{state}{reduced ? ' · Reduced motion · static endpoints' : resize ? ' · Current tail 556 ms / Target 280 ms' : ' · 400 / 350 ms'}</span>
    </div>
    <div className="rule-columns">
      {['width/height', 'clip-path'].map((label, index) => <div key={label}>
        <strong>{resize ? index ? 'Target' : 'Current code' : label}</strong>
        {resize && <div className="rule-note">{label}</div>}
        <div className="rule-stage">
          <div className="rule-store"><strong>Store</strong><p>Everyday essentials</p>{[0, 1].map(item => <div className="rule-product" key={item}><span className="rule-image" /><span>Ceramic collection<br />View product</span></div>)}</div>
          <div className="rule-panel" style={{width: resize ? 94 : 54, height: resize ? 102 : 38}}><span>Chat</span></div>
        </div>
        {resize ? <>
          <div className="rule-note">Time after input (ms), 0–600</div>
          <div className="rule-resize-axis" aria-label="Time after input, milliseconds">
            <span className="rule-time-mark" data-target-deadline="300" style={{left: '50%'}}><span>300</span></span>
            <span className="rule-time-mark" data-input-window="500" style={{left: '83.333%'}}><span>500</span></span>
            <span className="rule-time-bar" style={{width: index ? '46.667%' : '92.667%', background: index ? '#39765c' : '#a55740'}} />
            <span className="rule-time-label">{index ? 'Target: 280 ms' : 'Observed end: 345–556 ms'}</span>
          </div>
          <div className="rule-note">{index ? 'Đích ≤300 ms kể cả đuôi; chưa phải code hiện tại.' : 'Layout shift: AI Mode bag 0.29–0.44; Classic Expand/Collapse 0.073–0.080.'}</div>
        </> : <div className="rule-note">{index ? 'CLS 0.000–0.003' : 'CLS 0.67–0.74'}</div>}
      </div>)}
    </div>
    <p className="rule-note">Mô phỏng phóng đại dịch chuyển để nhìn rõ hai cách đổi bounds; không phải phép đo CLS của preview. {resize ? 'Current code còn đổi width từng frame. CLS báo 0 không có nghĩa là không dịch: 23/24 lần bị loại do cửa sổ 500 ms sau input; một frame tại 556 ms đã bị tính vào CLS (0.0013). Preview minh họa biên kết thúc chậm nhất bằng clock 350 ms cộng khoảng chờ 206 ms, không phải trace frame gốc. Target 280 ms là mô phỏng đích ≤300 ms kể cả đuôi, không phải số đo production. Mobile không có resize morph; product detail chưa kiểm.' : 'CLS lấy từ số đo bàn giao trên store thật; hình chỉ minh họa cơ chế. Màu và nội dung panel được đơn giản hóa.'}</p>
  </div>;
}

function Metric({title, values, unit, maximum}) {
  return <section className="rule-chart" aria-label={title}>
    <strong>{title}</strong>
    <div className="rule-metric-columns">{values.map((value, index) => <div key={index}>
      <span className="rule-bar-value">{value === null ? 'Not measured' : `${value}${unit}`}</span>
      <div className="rule-bar-track">{value !== null && <div className="rule-bar" data-value={value} style={{height: `${value / maximum * 100}%`, background: ['#a55740', '#4759a8', '#39765c'][index]}} />}</div>
      <span>{['A', 'B', 'C'][index]}</span>
    </div>)}</div>
  </section>;
}

export function IdleLayout() {
  return <Diagram id="idle-layout">
    <div className="rule-timeline"><strong>Old task</strong><div>
      <div className="rule-track"><span className="rule-task">DOM write</span><span>→</span><span className="rule-task">Rect read</span><span>→</span><span className="rule-task">Forced layout</span></div>
      <span className="rule-cost" style={{width: '100%', background: '#a55740'}} />
      <p className="rule-note">147 ms idle forced style/layout</p>
    </div></div>
    <div className="rule-timeline"><strong>rAF + cache</strong><div>
      <div className="rule-track"><span className="rule-task">rAF read</span><span>→</span><span className="rule-task">Cache width</span><span>→</span><span className="rule-task">Reuse</span></div>
      <span className="rule-cost" style={{width: '8.163%', background: '#39765c'}} />
      <p className="rule-note">12 ms idle forced style/layout</p>
    </div></div>
    <figcaption>Luồng task là sơ đồ, không phải trace từng event. Hai thanh biểu diễn tổng forced style/layout trong mười giây sau tải ở một store: 147 → 12 ms; hai store khác về 0. rAF vẫn có thể đọc rect sau khi theme làm bẩn style.</figcaption>
  </Diagram>;
}
```

Example — Số đo A/B/C: mỗi metric có thang riêng, cột thiếu dữ liệu không được suy diễn.

```jsx
import React, {useEffect, useRef, useState} from 'react';
import {readMotionDuration} from '@avada/chatty-ui/primitives/surfaceMorph.js';
import {IconBag} from '@avada/chatty-ui/icons/chatIcons.jsx';

function Diagram({id, children}) {
  return <figure data-rule-visual={id} style={{margin: 0, color: 'var(--vib-1, #25252a)', fontFamily: 'inherit'}}>
    <style>{`
      [data-rule-visual] * { box-sizing: border-box; }
      [data-rule-visual] .rule-columns { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
      [data-rule-visual] .rule-stage { position:relative; height:230px; overflow:hidden; border:1px solid #85858b; border-radius:12px; background:var(--bg-deep, #fff); margin-top:10px; }
      [data-rule-visual] .rule-store { padding:14px; font-size:12px; line-height:1.5; }
      [data-rule-visual] .rule-product { display:flex; gap:8px; margin-top:12px; align-items:center; }
      [data-rule-visual] .rule-image { width:36px; height:36px; flex:none; background:#d9d5ce; border-radius:4px; }
      [data-rule-visual] .rule-panel { position:absolute; left:12px; bottom:12px; background:#4759a8; border:1px solid #c2c9ef; border-radius:16px; color:white; overflow:hidden; }
      [data-rule-visual] .rule-panel span { display:block; width:130px; padding:10px; font-size:12px; }
      [data-rule-visual] .rule-controls { display:flex; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:14px; }
      [data-rule-visual] .rule-replay { font:inherit; color:inherit; background:transparent; padding:6px 14px; border:1px solid currentColor; border-radius:8px; cursor:pointer; }
      [data-rule-visual] .rule-replay:focus-visible { outline:3px solid #657fdf; outline-offset:3px; }
      [data-rule-visual] figcaption, [data-rule-visual] .rule-note { font-size:12px; line-height:1.55; margin-top:12px; }
      [data-rule-visual] .rule-header-view { position:relative; height:150px; display:grid; place-items:center; border:1px solid #85858b; border-radius:12px; overflow:hidden; margin-top:12px; }
      [data-rule-visual] .rule-header { position:relative; width:150px; height:72px; border:1px solid #85858b; border-radius:10px; display:flex; justify-content:center; align-items:center; }
      [data-rule-visual] .rule-header:after { content:''; position:absolute; left:0; right:0; top:50%; border-top:1px dashed #b55c42; pointer-events:none; }
      [data-rule-visual] .rule-header-control { position:relative; padding:0; border:0; background:transparent; color:inherit; width:48px; height:48px; display:grid; grid-auto-rows:min-content; align-content:center; justify-items:center; transform:scale(2); }
      [data-rule-visual] .rule-header-control::before { content:''; height:6px; width:100%; }
      [data-rule-visual] .rule-header-control[data-fixed]::before { position:absolute; inset:0; }
      [data-rule-visual] .rule-header-control svg { display:block; width:22px; height:22px; }
      [data-rule-visual] .rule-timeline { display:grid; grid-template-columns:100px minmax(0,1fr); gap:12px; align-items:start; margin:16px 0; font-size:12px; }
      [data-rule-visual] .rule-track { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
      [data-rule-visual] .rule-task { padding:8px; border:1px solid #85858b; border-radius:4px; }
      [data-rule-visual] .rule-cost { display:block; height:16px; border-radius:3px; margin-top:8px; }
      [data-rule-visual] .rule-resize-axis { position:relative; height:90px; margin-top:14px; font-size:12px; }
      [data-rule-visual] .rule-resize-axis::before { content:''; position:absolute; top:32px; left:0; right:0; border-top:1px solid #85858b; }
      [data-rule-visual] .rule-time-mark { position:absolute; top:24px; height:20px; border-left:1px dashed currentColor; }
      [data-rule-visual] .rule-time-mark span { position:absolute; top:-19px; transform:translateX(-50%); }
      [data-rule-visual] .rule-time-bar { position:absolute; top:34px; left:0; height:10px; border-radius:3px; }
      [data-rule-visual] .rule-time-label { position:absolute; top:54px; left:0; right:0; line-height:1.4; }
      [data-rule-visual] .rule-chart { display:grid; gap:8px; margin-top:14px; }
      [data-rule-visual] .rule-metric-columns { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; font-size:12px; text-align:center; }
      [data-rule-visual] .rule-bar-track { height:110px; display:flex; align-items:end; justify-content:center; border-bottom:1px solid #85858b; }
      [data-rule-visual] .rule-bar { width:70%; min-height:2px; background:#4759a8; border-radius:3px 3px 0 0; }
      [data-rule-visual] .rule-bar-value { min-height:36px; display:flex; align-items:end; justify-content:center; }
      @media(max-width:380px) { [data-rule-visual] .rule-columns { gap:8px; } [data-rule-visual] .rule-stage { height:240px; } }
      @media(prefers-reduced-motion:reduce) { [data-rule-visual], [data-rule-visual] * { animation:none !important; transition:none !important; } }
    `}</style>
    {children}
  </figure>;
}

function SurfaceComparison({resize = false}) {
  const root = useRef(null);
  const [run, setRun] = useState(0);
  const played = useRef(0);
  const [state, setState] = useState('Ready');
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    const media = matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReduced(media.matches);
    update();
    media.addEventListener('change', update);
    return () => media.removeEventListener('change', update);
  }, []);
  useEffect(() => {
    if (!run) return;
    if (played.current === run) {
      setState('Ready');
      return;
    }
    played.current = run;
    const element = root.current;
    const stages = [...element.querySelectorAll('.rule-stage')];
    const panels = stages.map(stage => stage.querySelector('.rule-panel'));
    const store = stages[0].querySelector('.rule-store');
    const style = getComputedStyle(element);
    const open = readMotionDuration({style, token: resize ? '--chatty-motion-duration-350' : '--chatty-motion-duration-400', fallback: resize ? 350 : 400});
    const targetDuration = resize ? 280 : open;
    const tailDelay = resize ? 206 : 0;
    const close = readMotionDuration({style, token: '--chatty-motion-duration-350', fallback: 350});
    const easing = style.getPropertyValue('--chatty-motion-ease-surface').trim() || 'cubic-bezier(0.2, 0, 0, 1)';
    const startWidth = resize ? 94 : 54;
    const startHeight = resize ? 102 : 38;
    const widths = stages.map(stage => stage.clientWidth - 24);
    const animations = [];
    let cancelled = false;
    let hold;
    let releaseHold;
    const pause = () => new Promise(resolve => { releaseHold = resolve; hold = setTimeout(resolve, 500); });
    const animate = (node, frames, duration, delay = 0) => {
      const animation = node.animate(frames, {duration, delay, easing, fill: 'forwards'});
      animations.push(animation);
      return animation.finished;
    };
    const show = expanded => {
      panels.forEach((panel, index) => Object.assign(panel.style, {
        width: `${expanded ? widths[index] : startWidth}px`, height: `${expanded ? 150 : startHeight}px`, clipPath: 'none'
      }));
    };
    const play = async () => {
      setState('Opening');
      if (reduced) {
        show(true);
        await pause();
        if (cancelled) return;
        show(false);
        setState('Done');
        return;
      }
      const geometry = [{width: `${startWidth}px`, height: `${startHeight}px`}, {width: `${widths[0]}px`, height: '150px'}];
      Object.assign(panels[1].style, {width: `${widths[1]}px`, height: '150px'});
      const clips = [
        {clipPath: `inset(${150 - startHeight}px ${Math.max(0, widths[1] - startWidth)}px 0 0 round 16px)`},
        {clipPath: 'inset(0px 0px 0px 0px round 16px)'}
      ];
      await Promise.all([
        animate(panels[0], geometry, open, tailDelay),
        animate(panels[1], clips, targetDuration),
        animate(store, [{transform: 'translateY(0px)'}, {transform: 'translateY(14px)'}], open, tailDelay)
      ]);
      if (cancelled) return;
      setState('Open');
      await pause();
      if (cancelled) return;
      setState('Closing');
      await Promise.all([
        animate(panels[0], [...geometry].reverse(), close, tailDelay),
        animate(panels[1], [...clips].reverse(), resize ? targetDuration : close),
        animate(store, [{transform: 'translateY(14px)'}, {transform: 'translateY(0px)'}], close, tailDelay)
      ]);
      if (!cancelled) setState('Done');
    };
    play().catch(error => { if (!cancelled) throw error; });
    return () => {
      cancelled = true;
      clearTimeout(hold);
      releaseHold?.();
      animations.forEach(animation => animation.cancel());
      store.style.transform = '';
      show(false);
    };
  }, [run, reduced, resize]);
  return <div ref={root} data-comparison={resize ? 'resize' : 'overlay'} data-run={run} data-state={state} data-reduced={reduced}>
    <div className="rule-controls">
      <button className="rule-replay" type="button" onClick={() => setRun(value => value + 1)}>Replay</button>
      <span role="status">{state}{reduced ? ' · Reduced motion · static endpoints' : resize ? ' · Current tail 556 ms / Target 280 ms' : ' · 400 / 350 ms'}</span>
    </div>
    <div className="rule-columns">
      {['width/height', 'clip-path'].map((label, index) => <div key={label}>
        <strong>{resize ? index ? 'Target' : 'Current code' : label}</strong>
        {resize && <div className="rule-note">{label}</div>}
        <div className="rule-stage">
          <div className="rule-store"><strong>Store</strong><p>Everyday essentials</p>{[0, 1].map(item => <div className="rule-product" key={item}><span className="rule-image" /><span>Ceramic collection<br />View product</span></div>)}</div>
          <div className="rule-panel" style={{width: resize ? 94 : 54, height: resize ? 102 : 38}}><span>Chat</span></div>
        </div>
        {resize ? <>
          <div className="rule-note">Time after input (ms), 0–600</div>
          <div className="rule-resize-axis" aria-label="Time after input, milliseconds">
            <span className="rule-time-mark" data-target-deadline="300" style={{left: '50%'}}><span>300</span></span>
            <span className="rule-time-mark" data-input-window="500" style={{left: '83.333%'}}><span>500</span></span>
            <span className="rule-time-bar" style={{width: index ? '46.667%' : '92.667%', background: index ? '#39765c' : '#a55740'}} />
            <span className="rule-time-label">{index ? 'Target: 280 ms' : 'Observed end: 345–556 ms'}</span>
          </div>
          <div className="rule-note">{index ? 'Đích ≤300 ms kể cả đuôi; chưa phải code hiện tại.' : 'Layout shift: AI Mode bag 0.29–0.44; Classic Expand/Collapse 0.073–0.080.'}</div>
        </> : <div className="rule-note">{index ? 'CLS 0.000–0.003' : 'CLS 0.67–0.74'}</div>}
      </div>)}
    </div>
    <p className="rule-note">Mô phỏng phóng đại dịch chuyển để nhìn rõ hai cách đổi bounds; không phải phép đo CLS của preview. {resize ? 'Current code còn đổi width từng frame. CLS báo 0 không có nghĩa là không dịch: 23/24 lần bị loại do cửa sổ 500 ms sau input; một frame tại 556 ms đã bị tính vào CLS (0.0013). Preview minh họa biên kết thúc chậm nhất bằng clock 350 ms cộng khoảng chờ 206 ms, không phải trace frame gốc. Target 280 ms là mô phỏng đích ≤300 ms kể cả đuôi, không phải số đo production. Mobile không có resize morph; product detail chưa kiểm.' : 'CLS lấy từ số đo bàn giao trên store thật; hình chỉ minh họa cơ chế. Màu và nội dung panel được đơn giản hóa.'}</p>
  </div>;
}

function Metric({title, values, unit, maximum}) {
  return <section className="rule-chart" aria-label={title}>
    <strong>{title}</strong>
    <div className="rule-metric-columns">{values.map((value, index) => <div key={index}>
      <span className="rule-bar-value">{value === null ? 'Not measured' : `${value}${unit}`}</span>
      <div className="rule-bar-track">{value !== null && <div className="rule-bar" data-value={value} style={{height: `${value / maximum * 100}%`, background: ['#a55740', '#4759a8', '#39765c'][index]}} />}</div>
      <span>{['A', 'B', 'C'][index]}</span>
    </div>)}</div>
  </section>;
}

export function Performance() {
  return <Diagram id="performance">
    <div className="rule-columns">
      <Metric title="CLS · Store 1" values={[0.671, 0, null]} maximum={0.75} unit="" />
      <Metric title="CLS · Store 2" values={[0.744, 0.003, null]} maximum={0.75} unit="" />
      <Metric title="Main thread · Home" values={[485, 317, 163]} maximum={600} unit=" ms" />
      <Metric title="Main thread · Product page" values={[580, 315, 197]} maximum={600} unit=" ms" />
    </div>
    <figcaption>A: trước tối ưu; B: clip-path + idle guard; C: defer boot. CLS: cold median, mỗi nhóm ba lượt, mobile rộng 390 pixel, CPU chậm bốn lần; chưa có CLS của C nên bỏ thanh C. Main thread là thời gian của script Chatty, không phải toàn trang: Home B ba lượt, Product page B năm lượt; C Home tám lượt, Product page ba lượt. Product page C dùng số cập nhật 197 ms (172–246), thay cho quan sát ban đầu 246 ms. Các nhóm có điều kiện tải khác nhau, không dùng biểu đồ để quy mọi chênh lệch cho một thay đổi. Đơn vị CLS và ms nằm ở biểu đồ riêng.</figcaption>
  </Diagram>;
}
```

## Do / Don't

Do: tải phần nặng sau tương tác đầu tiên và đo Lighthouse store trước, sau khi bật app embed.

Don't: thêm preconnect, preload hay font vào head của theme cho thứ khách chưa mở.

Do: khi dọn URL, xoá đúng param của mình bằng `URL.searchParams.delete` rồi ghi lại phần còn lại.

Don't: `replaceState(null, '', location.pathname)` hay gán `location.hash`, vì mất query, UTM và hash của theme.

Do: khối inline giữ `min-height` bằng chiều cao dự kiến trước khi có dữ liệu.

Don't: tự mở panel full-screen trên mobile khi khách vừa vào trang từ kết quả tìm kiếm.

## Target

```target
| Surface | Now | Target | Source |
| --- | --- | --- | --- |
| Classic | Đóng widget sau khi mở bằng hash gọi `replaceState(pathname)`, xoá query và hash. | Not in code yet — build with the body values. Chỉ gỡ hash `#chatty-*`, giữ nguyên `location.search` và hash khác. | [Google Search Central: URL structure](https://developers.google.com/search/docs/crawling-indexing/url-structure) |
| Classic | FAQ page render hoàn toàn bằng JS, script lỗi thì trang trắng. | Not in code yet — build with the body values. Render câu hỏi và câu trả lời bằng Liquid như JSON-LD đang làm; JS chỉ thêm accordion và search. | [Google Search Central: JavaScript SEO basics](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics) |
| Classic | Loader FAQ page gắn `&v=` + thời gian, không cache được. | Not in code yet — build with the body values. Dùng version của bundle làm cache key để lượt xem lặp lại dùng cache. | [web.dev: loading third-party JavaScript](https://web.dev/articles/optimizing-content-efficiency-loading-third-party-javascript) |
| Classic | FAQ page và FAQ block cùng render `FAQPage` với `@id/faq`, trang có cả hai thì có 2 node trùng id. | Not in code yet — build with the body values. 1 node mỗi trang, `@id` theo URL trang hiện tại. | [Google Search Central: FAQPage structured data](https://developers.google.com/search/docs/appearance/structured-data/faqpage) |
| Classic | FAQ block và AI assistant block bật từ `display:none`, không giữ chiều cao. | Not in code yet — build with the body values. Giữ `min-height` theo số câu hỏi hoặc skeleton cùng kích thước. | [web.dev: Cumulative Layout Shift](https://web.dev/articles/cls) |
| Classic / AI Mode | Widget render trong light DOM của theme, không có Shadow DOM. | Not available — new build follows Target. Element `chatty-*` dùng open shadow root; text cần index, chọn chữ hay dịch trang (câu trả lời FAQ, trang FAQ) đi qua slot ở light DOM; host giữ id và class cũ ở light DOM. | [Google Search Central: JavaScript SEO basics](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics) |
| AI Mode | Teaser cho phép delay 0 giây. | Not in code yet — build with the body values. Sàn 5 giây hoặc trigger cuộn trên mobile, như Classic. | [Google Search Central: avoid intrusive interstitials](https://developers.google.com/search/docs/appearance/avoid-intrusive-interstitials) |
```


- [Google Search Central: avoid intrusive interstitials](https://developers.google.com/search/docs/appearance/avoid-intrusive-interstitials)
- [Google Search Central: JavaScript SEO basics](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics)
- [Google Search Central: URL structure](https://developers.google.com/search/docs/crawling-indexing/url-structure)
- [Google Search Central: qualify outbound links](https://developers.google.com/search/docs/crawling-indexing/qualify-outbound-links)
- [Google Search Central: FAQPage structured data](https://developers.google.com/search/docs/appearance/structured-data/faqpage)
- [web.dev: Core Web Vitals](https://web.dev/articles/vitals)
- [web.dev: Cumulative Layout Shift](https://web.dev/articles/cls)
- [web.dev: Largest Contentful Paint](https://web.dev/articles/lcp)
- [web.dev: Interaction to Next Paint](https://web.dev/articles/inp)
- [web.dev: loading third-party JavaScript](https://web.dev/articles/optimizing-content-efficiency-loading-third-party-javascript)
- [Shopify: Built for Shopify requirements](https://shopify.dev/docs/apps/launch/built-for-shopify/requirements)
- [Shopify: storefront performance for apps](https://shopify.dev/docs/apps/build/performance/storefront)
