// page-docs.jsx — /docs (with sidebar). Self-routing: each nav item shows its own section.

const DOCS_NAV = {
  en: [
    { group: 'Getting started', items: [
      { id: 'getting-started', label: 'Install &amp; first run' },
      { id: 'permissions', label: 'Permissions' },
      { id: 'licensing', label: 'Trial &amp; licensing' },
    ]},
    { group: 'Concepts', items: [
      { id: 'presets', label: 'Presets' },
      { id: 'arrange', label: 'Arrange &amp; Clear Desk' },
      { id: 'chains', label: 'Chains' },
      { id: 'sessions', label: 'Sessions &amp; breaks' },
      { id: 'triggers', label: 'Triggers' },
    ]},
    { group: 'Operate', items: [
      { id: 'shortcuts', label: 'Keyboard shortcuts' },
      { id: 'troubleshooting', label: 'Troubleshooting' },
      { id: 'updates', label: 'Updates' },
    ]},
  ],
  vi: [
    { group: 'Bắt đầu', items: [
      { id: 'getting-started', label: 'Cài đặt &amp; mở lần đầu' },
      { id: 'permissions', label: 'Quyền' },
      { id: 'licensing', label: 'Dùng thử &amp; giấy phép' },
    ]},
    { group: 'Khái niệm', items: [
      { id: 'presets', label: 'Preset' },
      { id: 'arrange', label: 'Sắp xếp &amp; Clear Desk' },
      { id: 'chains', label: 'Chains' },
      { id: 'sessions', label: 'Phiên &amp; nghỉ' },
      { id: 'triggers', label: 'Trigger' },
    ]},
    { group: 'Vận hành', items: [
      { id: 'shortcuts', label: 'Phím tắt' },
      { id: 'troubleshooting', label: 'Khắc phục sự cố' },
      { id: 'updates', label: 'Cập nhật' },
    ]},
  ],
};

// Flat ordered id list for "next" navigation
const DOCS_ORDER = ['getting-started', 'permissions', 'licensing', 'presets', 'arrange', 'chains', 'sessions', 'triggers', 'shortcuts', 'troubleshooting', 'updates'];

const DOCS_TITLE = {
  'getting-started': ['Install & first run', 'Cài đặt & mở lần đầu'],
  permissions: ['Permissions', 'Quyền'],
  licensing: ['Trial & licensing', 'Dùng thử & giấy phép'],
  presets: ['Presets', 'Preset'],
  arrange: ['Arrange & Clear Desk', 'Sắp xếp & Clear Desk'],
  chains: ['Chains', 'Chains'],
  sessions: ['Sessions & breaks', 'Phiên & nghỉ'],
  triggers: ['Triggers', 'Trigger'],
  shortcuts: ['Keyboard shortcuts', 'Phím tắt'],
  troubleshooting: ['Troubleshooting', 'Khắc phục sự cố'],
  updates: ['Updates', 'Cập nhật'],
};

const DOCS_GROUP = {
  'getting-started': ['Getting started', 'Bắt đầu'], permissions: ['Getting started', 'Bắt đầu'], licensing: ['Getting started', 'Bắt đầu'],
  presets: ['Concepts', 'Khái niệm'], arrange: ['Concepts', 'Khái niệm'], chains: ['Concepts', 'Khái niệm'], sessions: ['Concepts', 'Khái niệm'], triggers: ['Concepts', 'Khái niệm'],
  shortcuts: ['Operate', 'Vận hành'], troubleshooting: ['Operate', 'Vận hành'], updates: ['Operate', 'Vận hành'],
};

const DocsBody = ({ id, L }) => {
  switch (id) {
    case 'permissions':
      return (<>
        <p>{L('Snapovo asks for the minimum macOS permissions it needs — nothing more. You can review or revoke any of them in System Settings → Privacy & Security.', 'Snapovo chỉ xin những quyền macOS tối thiểu cần thiết — không hơn. Bạn có thể xem lại hoặc thu hồi bất kỳ quyền nào trong System Settings → Privacy & Security.')}</p>
        <h2>Accessibility</h2>
        <p>{L('Required — and it is the one permission people pause on, so here is exactly why. macOS lets an app move its own windows freely, but moving another app\'s window is privileged. Restoring a layout means positioning Safari, Slack, VS Code and everything else, so Snapovo cannot do its one job without it.', 'Bắt buộc — và đây là quyền khiến nhiều người chần chừ, nên xin nói rõ lý do. macOS cho phép một app tự di chuyển cửa sổ của chính nó, nhưng di chuyển cửa sổ của app khác là quyền đặc biệt. Khôi phục bố cục nghĩa là đặt lại vị trí Safari, Slack, VS Code và mọi thứ khác, nên Snapovo không thể làm việc của mình mà thiếu quyền này.')}</p>
        <p>{L('It grants Snapovo window identity, position and size — nothing else. Window contents are never read, keystrokes are never observed, and the permission is revocable any time in System Settings → Privacy & Security → Accessibility.', 'Quyền này cho Snapovo biết danh tính, vị trí và kích thước cửa sổ — không gì khác. Không bao giờ đọc nội dung cửa sổ, không theo dõi bàn phím, và bạn có thể thu hồi bất cứ lúc nào trong System Settings → Privacy & Security → Accessibility.')}</p>
        <h2>{L('Automation (optional)', 'Automation (tuỳ chọn)')}</h2>
        <p>{L("Snapovo asks Safari, Chrome, Edge, Brave, Vivaldi or Cốc Cốc for the current tab URLs — approved per browser, the first time. (Arc can be reopened but doesn't expose its tabs.)", 'Snapovo hỏi Safari, Chrome, Edge, Brave, Vivaldi hoặc Cốc Cốc để lấy URL tab hiện tại — cấp quyền cho từng trình duyệt ở lần đầu. (Arc chỉ mở lại được app, không lấy được tab.)')}</p>
        <h2>{L('Notifications (optional)', 'Thông báo (tuỳ chọn)')}</h2>
        <p>{L('Used only for session/break reminders and trigger confirmations. Decline it and Snapovo stays silent.', 'Chỉ dùng cho nhắc phiên/nghỉ và xác nhận trigger. Từ chối thì Snapovo im lặng.')}</p>
      </>);
    case 'licensing':
      return (<>
        <p>{L('Snapovo is a one-time purchase, not a subscription. Try it free for 7 days, then buy a key when you are ready.', 'Snapovo mua một lần, không phải thuê bao. Dùng thử miễn phí 7 ngày, rồi mua key khi bạn sẵn sàng.')}</p>
        <h2>{L('The 7-day trial', 'Dùng thử 7 ngày')}</h2>
        <p>{L('Full features, capped at 3 presets. Settings shows how many days are left. When it ends, Snapovo keeps running your existing presets and chains — you just cannot create new ones until you activate.', 'Đầy đủ tính năng, giới hạn tối đa 3 preset. Settings hiển thị số ngày còn lại. Khi hết hạn, Snapovo vẫn chạy các preset và chain đã có — chỉ là bạn không tạo mới được cho tới khi kích hoạt.')}</p>
        <h2>{L('Buy & activate', 'Mua & kích hoạt')}</h2>
        <p>{L('Pick the 1-Mac or 2-Mac license via Lemon Squeezy. You will get an email with a license key — paste it into Settings → License with your email to activate. Keys are movable between your own Macs.', 'Chọn giấy phép 1 Mac hoặc 2 Mac qua Lemon Squeezy. Bạn sẽ nhận email kèm license key — dán vào Settings → License cùng email để kích hoạt. Key chuyển được giữa các máy Mac của bạn.')}</p>
      </>);
    case 'presets':
      return (<>
        <p>{L('A preset is a saved snapshot of your workspace: which apps are open, where each window sits (across displays), and any captured browser tabs and Finder paths.', 'Preset là ảnh chụp không gian làm việc của bạn: app nào đang mở, mỗi cửa sổ nằm đâu (trên các màn hình), cùng các tab trình duyệt và đường dẫn Finder đã lưu.')}</p>
        <h2>{L('Save & restore', 'Lưu & khôi phục')}</h2>
        <p>{L('Capture with ⌃⌥⌘S, name it, and optionally give it a hotkey. Restore from the menu-bar list, its hotkey, Spotlight or Apple Shortcuts — everything snaps back, adapting to whatever displays are connected now.', 'Lưu bằng ⌃⌥⌘S, đặt tên, và tuỳ chọn đặt phím tắt. Khôi phục từ danh sách thanh menu, phím tắt, Spotlight hoặc Apple Shortcuts — mọi thứ về chỗ cũ, thích ứng với màn hình đang cắm.')}</p>
        <p>{L('Undo the last restore with ⌃⌥⌘Z.', 'Hoàn tác lần khôi phục gần nhất bằng ⌃⌥⌘Z.')}</p>
      </>);
    case 'arrange':
      return (<>
        <p>{L('Two commands for tidying what is already open — no preset needed.', 'Hai lệnh để dọn gọn những gì đang mở — không cần preset.')}</p>
        <h2>Arrange <span style={{ color: 'var(--text-dim)', fontWeight: 400 }}>⌃⌥⌘A</span></h2>
        <p>{L('Snaps the current windows into a tidy grid layout on their displays, without changing which apps are open.', 'Sắp các cửa sổ hiện tại vào lưới gọn gàng trên màn hình của chúng, không đổi các app đang mở.')}</p>
        <h2>Clear Desk</h2>
        <p>{L('Resets the desk in one move: close everything (⌃⌥⌘X) or hide everything (⌃⌥H), with an optional keep-list of apps to leave untouched. Reversible with ⌃⌥⌘Z.', 'Đặt lại bàn làm việc trong một thao tác: đóng tất cả (⌃⌥⌘X) hoặc ẩn tất cả (⌃⌥H), kèm danh sách giữ lại tuỳ chọn. Hoàn tác được bằng ⌃⌥⌘Z.')}</p>
      </>);
    case 'chains':
      return (<>
        <p>{L('Chains link presets into a timed routine — a Pro feature. Run a sequence like “Standup → Deep work → Review” with a delay or a manual step between each.', 'Chains nối các preset thành quy trình hẹn giờ — tính năng Pro. Chạy chuỗi như “Standup → Tập trung → Review” với khoảng chờ hoặc bước thủ công giữa mỗi bước.')}</p>
        <p>{L('Build a chain in Settings → Chains: add presets in order, set a delay or “wait for me” between steps, then trigger the whole chain from a hotkey or the menu bar.', 'Tạo chain trong Settings → Chains: thêm preset theo thứ tự, đặt khoảng chờ hoặc “đợi tôi” giữa các bước, rồi kích hoạt cả chain bằng phím tắt hoặc thanh menu.')}</p>
        <div className="callout">{L('After the trial ends you can still run chains you already built — you just cannot create new ones until you activate a license.', 'Sau khi hết dùng thử bạn vẫn chạy được chain đã tạo — chỉ là không tạo mới được cho tới khi kích hoạt giấy phép.')}</div>
      </>);
    case 'sessions':
      return (<>
        <p>{L('Sessions turn a preset into a focused work block with an optional break reminder — handy for time-boxing or Pomodoro-style work.', 'Phiên biến một preset thành khối làm việc tập trung kèm nhắc nghỉ tuỳ chọn — tiện cho time-box hoặc làm kiểu Pomodoro.')}</p>
        <p>{L('Start a session from a preset, set its length, and Snapovo nudges you when the block ends. Breaks can dim the screen so you actually step away.', 'Bắt đầu phiên từ một preset, đặt độ dài, và Snapovo nhắc bạn khi khối kết thúc. Giờ nghỉ có thể làm mờ màn hình để bạn thật sự rời đi.')}</p>
      </>);
    case 'triggers':
      return (<>
        <p>{L('Triggers auto-run a preset when something happens — no clicking required.', 'Trigger tự chạy một preset khi có sự kiện — không cần bấm.')}</p>
        <ul>
          <li>{L('On login or wake from sleep', 'Khi đăng nhập hoặc thức khỏi ngủ')}</li>
          <li>{L('When a display is connected or disconnected', 'Khi cắm hoặc rút màn hình')}</li>
          <li>{L('On a schedule (e.g. 9:00 every weekday)', 'Theo lịch (vd. 9:00 mỗi ngày làm việc)')}</li>
          <li>{L('When macOS Focus Mode changes', 'Khi Focus Mode của macOS thay đổi')}</li>
        </ul>
        <p>{L('Set them up per preset in Settings → Triggers. You can also drive Snapovo from Apple Shortcuts, Raycast or Alfred.', 'Thiết lập cho từng preset trong Settings → Triggers. Bạn cũng có thể điều khiển Snapovo từ Apple Shortcuts, Raycast hoặc Alfred.')}</p>
      </>);
    case 'shortcuts': {
      const rows = [
        ['⌃⌥⌘S', L('Capture the current layout as a preset', 'Lưu bố cục hiện tại thành preset')],
        ['⌃⌥⌘O', L('Show the preset list', 'Hiện danh sách preset')],
        ['⌃⌥⌘Z', L('Undo the last restore or Clear Desk', 'Hoàn tác khôi phục / Clear Desk gần nhất')],
        ['⌃⌥⌘A', L('Arrange open windows', 'Sắp xếp cửa sổ đang mở')],
        ['⌃⌥⌘X', L('Clear Desk — close everything', 'Clear Desk — đóng tất cả')],
        ['⌃⌥H', L('Clear Desk — hide everything', 'Clear Desk — ẩn tất cả')],
        ['⌃⌥⌘E', L('Start an eye break', 'Bắt đầu nghỉ mắt')],
        ['⌃⌥⌘F', L('Focus Timer, while a session is running', 'Focus Timer, khi phiên đang chạy')],
        ['⌃⌥⌘/', L('Move the workspace to the other display', 'Chuyển workspace sang màn hình kia')],
      ];
      return (<>
        <p>{L('Every default hotkey in one place. Per-preset hotkeys are yours to assign when you save a preset.', 'Toàn bộ phím tắt mặc định ở một nơi. Phím tắt của từng preset do bạn tự đặt khi lưu.')}</p>
        <div className="sc-list">
          {rows.map(([k, d]) => (
            <div key={k} className="sc-row"><span>{d}</span><Kbd>{k}</Kbd></div>
          ))}
        </div>
      </>);
    }
    case 'troubleshooting':
      return (<>
        <h2>{L('A window did not restore', 'Một cửa sổ không khôi phục')}</h2>
        <p>{L('Make sure the app is installed and that Snapovo still has Accessibility permission (System Settings → Privacy & Security → Accessibility). Re-toggle it if the app was updated.', 'Đảm bảo app đã cài và Snapovo vẫn có quyền Accessibility (System Settings → Privacy & Security → Accessibility). Bật lại nếu app vừa cập nhật.')}</p>
        <h2>{L('Browser tabs are missing', 'Thiếu tab trình duyệt')}</h2>
        <p>{L('Tab capture needs Automation permission for that browser. Approve it the first time Snapovo asks, or enable it under Privacy & Security → Automation.', 'Lưu tab cần quyền Automation cho trình duyệt đó. Chấp nhận ở lần Snapovo hỏi đầu tiên, hoặc bật trong Privacy & Security → Automation.')}</p>
        <h2>{L('Still stuck?', 'Vẫn chưa được?')}</h2>
        <p>{L('Email us and we will help.', 'Gửi email cho chúng tôi, sẽ hỗ trợ ngay.')} <a style={{ color: 'var(--accent)' }} href={window.SN_SUPPORT_EMAIL ? `mailto:${window.SN_SUPPORT_EMAIL}` : '#'}>{window.SN_SUPPORT_EMAIL || 'support'}</a></p>
      </>);
    case 'updates':
      return (<>
        <p>{L('Check any time from Help → Check for Updates… — new versions download and install in place, and your presets carry over untouched.', 'Kiểm tra bất cứ lúc nào từ Help → Check for Updates… — phiên bản mới tải và cài tại chỗ, các preset của bạn giữ nguyên.')}</p>
        <p>{L('Automatic checking is on after installation, so Snapovo asks the update server for a new version from time to time. The request is anonymous and carries no personal identifiers. Turn it off in Settings → Updates and only manual checks remain.', 'Tự kiểm tra cập nhật bật sẵn khi cài, nên Snapovo định kỳ hỏi máy chủ cập nhật xem có bản mới. Lần hỏi này ẩn danh, không kèm định danh cá nhân. Tắt trong Settings → Updates thì chỉ còn kiểm tra thủ công.')}</p>
        <p>{L('Updates are free for the lifetime of your license.', 'Cập nhật miễn phí trọn đời giấy phép của bạn.')}</p>
      </>);
    default: // getting-started
      return (<>
        <p>{L("You'll be capturing and restoring layouts in about three minutes. This is the whole onboarding.", 'Bạn sẽ lưu và khôi phục bố cục trong khoảng ba phút. Đây là toàn bộ phần làm quen.')}</p>
        <h2>{L('1. Install', '1. Cài đặt')}</h2>
        <p>{L('Download Snapovo from the', 'Tải Snapovo từ')} <a style={{ color: 'var(--accent)' }} href="#/download" onClick={(e) => { e.preventDefault(); window.location.hash = '#/download'; }}>{L('download page', 'trang tải về')}</a>, {L('open the', 'mở tệp')} <code>.dmg</code>, {L('and drag', 'và kéo')} <code>Snapovo.app</code> {L('into', 'vào')} <code>/Applications</code>. {L('The app is signed with a Developer ID and notarized by Apple — Gatekeeper opens it without a right-click trick.', 'Ứng dụng được ký bằng Developer ID và được Apple công chứng — Gatekeeper mở được mà không cần mẹo chuột phải.')}</p>
        <h2>{L('2. First launch', '2. Mở lần đầu')}</h2>
        <p>{L("Press Save Current Layout (⌃⌥⌘S). macOS will ask for", 'Bấm Lưu bố cục hiện tại (⌃⌥⌘S). macOS sẽ xin quyền')} <strong>Accessibility</strong> {L("permission — that's how Snapovo reads & positions windows. Approve it; Snapovo reopens automatically.", '— đó là cách Snapovo đọc & sắp vị trí cửa sổ. Chấp nhận; Snapovo tự mở lại.')}</p>
        <h2>{L('3. Save a preset', '3. Lưu một preset')}</h2>
        <p>{L("After capture you'll see every running app, its windows, browser tabs and which display each window lives on. Name the preset, optionally give it a hotkey, and press Save.", 'Sau khi lưu, bạn sẽ thấy mọi app đang chạy, các cửa sổ, tab trình duyệt và mỗi cửa sổ thuộc màn hình nào. Đặt tên cho preset, tuỳ chọn đặt phím tắt, rồi bấm Lưu.')}</p>
        <h2>{L('4. Restore', '4. Khôi phục')}</h2>
        <p>{L("Move some windows around, then press your preset's hotkey, click it in the menu bar, or run it from Spotlight / Shortcuts. Everything snaps back — and adapts to whatever screens are connected now.", 'Di chuyển vài cửa sổ, rồi bấm phím tắt của preset, chọn trong thanh menu, hoặc chạy từ Spotlight / Shortcuts. Mọi thứ về chỗ cũ — và thích ứng với màn hình đang cắm.')}</p>
      </>);
  }
};

const Docs = ({ lang }) => {
  const vi = lang === 'vi';
  const L = (en, v) => (vi ? v : en);
  const nav = vi ? DOCS_NAV.vi : DOCS_NAV.en;

  const readHash = () => {
    const m = (window.location.hash || '').match(/#\/?docs\/([\w-]+)/);
    return (m && DOCS_ORDER.includes(m[1])) ? m[1] : null;
  };
  const [active, setActive] = React.useState(readHash() || 'getting-started');
  const spyLock = React.useRef(0);

  const scrollTo = (id, smooth = true) => {
    const el = document.getElementById(`doc-${id}`);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.pageYOffset - 92;
    spyLock.current = Date.now() + 700;
    window.scrollTo({ top: y, behavior: smooth ? 'smooth' : 'auto' });
  };

  // On mount: jump to hash target if present
  React.useEffect(() => {
    const target = readHash();
    if (target) { setActive(target); setTimeout(() => scrollTo(target, false), 60); }
  }, []);

  // Scroll-spy
  React.useEffect(() => {
    const onScroll = () => {
      if (Date.now() < spyLock.current) return;
      let current = DOCS_ORDER[0];
      for (const id of DOCS_ORDER) {
        const el = document.getElementById(`doc-${id}`);
        if (el && el.getBoundingClientRect().top <= 140) current = id;
      }
      setActive((prev) => (prev === current ? prev : current));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const go = (id) => {
    setActive(id);
    if (history.replaceState) history.replaceState(null, '', `#/docs/${id}`);
    scrollTo(id);
  };

  return (
  <main>
    <div className="container docs">
      <aside className="docs-side">
        {nav.map((g) => (
          <React.Fragment key={g.group}>
            <h6>{g.group}</h6>
            {g.items.map((it) => (
              <a key={it.id} href={`#/docs/${it.id}`}
                 className={it.id === active ? 'is-active' : ''}
                 onClick={(e) => { e.preventDefault(); go(it.id); }}
                 dangerouslySetInnerHTML={{ __html: it.label }} />
            ))}
          </React.Fragment>
        ))}
      </aside>

      <article className="docs-content">
        {DOCS_ORDER.map((id, i) => (
          <section key={id} id={`doc-${id}`} className="docs-section" data-screen-label={`Docs · ${DOCS_TITLE[id][0]}`}>
            <Eyebrow>{vi ? DOCS_GROUP[id][1] : DOCS_GROUP[id][0]}</Eyebrow>
            <h1 style={{ marginTop: 12 }}>{vi ? DOCS_TITLE[id][1] : DOCS_TITLE[id][0]}</h1>
            <DocsBody id={id} L={L} />
            {i < DOCS_ORDER.length - 1 && <hr className="hairline" style={{ margin: '56px 0' }} />}
          </section>
        ))}
      </article>
    </div>
  </main>
  );
};

window.Docs = Docs;
