# -*- coding: utf-8 -*-
"""
F0NT Autokern - Dedicated Auto Spacing & Kerning Plugin for FontLab 7 & FontLab 8
Bilingual (Thai / English)
Modules:
1. ปรับช่องไฟซ้าย-ขวาตามความเว้าโค้ง (Optical LSB / RSB)
2. คำนวณคู่ Kerning เฉพาะคู่ที่มีโพรงว่าง (Smart Auto Kerning)
"""

import html

import fontlab as fl6
from PythonQt import QtCore, QtGui

__version__ = "1.1"

# ---- การตั้งค่า ----
WINDOW_OBJECT_NAME = "F0NTAutokernPanel"
# จำนวนคู่ kerning สูงสุดที่เขียนต่อการรัน (เก็บคู่ที่ค่ามากที่สุดไว้)
MAX_KERN_PAIRS = 3500
# สระลอยและวรรณยุกต์ไทย (ไม่จัดช่องไฟ / kerning)
THAI_FLOATING_MARKS = (0x0E31, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, 0x0E3A,
                       0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E)
# ระดับ slider ความแน่น -> ตัวคูณระยะขอบ (1 = ชิดสุด, 5 = โปร่งสุด)
DENSITY_FACTORS = {1: 0.80, 2: 0.90, 3: 1.00, 4: 1.10, 5: 1.25}
# การวัด outline: จำนวนแถบแนวนอนตั้งแต่ baseline ถึงความสูงอ้างอิง
PROFILE_SLICES = 24
# ช่องไฟ: ระยะขอบ = Base SB × (1 − SPACING_DEPTH_WEIGHT × ความลึกโพรงเฉลี่ย)
SPACING_DEPTH_WEIGHT = 1.5
# Kerning: น้ำหนักของระยะแคบสุด (ที่เหลือคือระยะเฉลี่ย), ความแรง, จำนวนแถบซ้อนกันขั้นต่ำ
KERN_MIN_WEIGHT = 0.8
KERN_STRENGTH = 0.35
MIN_OVERLAP_SLICES = 3
# ตัวอักษรที่ใช้วัด "ความสูงพยัญชนะไทย" (ลองตามลำดับ ตัวที่ไม่มีในฟอนต์ข้ามไป)
THAI_HEIGHT_SOURCES = (('ก', 0x0E01), ('ด', 0x0E14), ('บ', 0x0E1A), ('อ', 0x0E2D))
# คู่อ้างอิงของระยะ kerning (ใช้ตัวแรกที่วัด outline ได้; ไม่พบเลย = 2 × Base SB)
KERN_REFERENCE_GLYPHS = ('H', 'n', 'I', 'l')

# อีโมจิใน log -> สัญลักษณ์เรียบๆ บนแถบสถานะ
STATUS_SYMBOLS = (('🎉', '✓'), ('✅', '✓'), ('🗑️', '✓'), ('🏷️', '✓'), ('⚠️', '⚠'), ('❌', '✕'))


def _get(obj, attr):
    """อ่านค่าจาก object ของ FontLab ที่อาจเป็น property หรือ method ก็ได้"""
    val = getattr(obj, attr)
    return val() if callable(val) else val


def _get_name(obj):
    try:
        return str(_get(obj, 'name'))
    except Exception:
        return "?"

# ตารางเทียบชื่อ Glyph มาตรฐาน -> Unicode
THAI_NAME_TO_UNICODE = {
    'kokai': 0x0E01, 'khokhai': 0x0E02, 'khokhuat': 0x0E03, 'khokhwai': 0x0E04,
    'khokhon': 0x0E05, 'khorakhang': 0x0E06, 'ngongu': 0x0E07, 'chochan': 0x0E08,
    'choching': 0x0E09, 'chochang': 0x0E0A, 'soso': 0x0E0B, 'chochoe': 0x0E0C,
    'yoying': 0x0E0D, 'dochada': 0x0E0E, 'topatak': 0x0E0F, 'thothan': 0x0E10,
    'thonangmontho': 0x0E11, 'thophuthao': 0x0E12, 'nonen': 0x0E13, 'dodek': 0x0E14,
    'totao': 0x0E15, 'thothung': 0x0E16, 'thothahan': 0x0E17, 'thothong': 0x0E18,
    'nonu': 0x0E19, 'bobaimai': 0x0E1A, 'popla': 0x0E1B, 'phophung': 0x0E1C,
    'fofa': 0x0E1D, 'phophan': 0x0E1E, 'fofan': 0x0E1F, 'phosamphao': 0x0E20,
    'moma': 0x0E21, 'yoyak': 0x0E22, 'rorua': 0x0E23, 'ru': 0x0E24,
    'loling': 0x0E25, 'lu': 0x0E26, 'wowaen': 0x0E27, 'sosala': 0x0E28,
    'sorusi': 0x0E29, 'sosua': 0x0E2A, 'hohip': 0x0E2B, 'lochula': 0x0E2C,
    'oang': 0x0E2D, 'honokhuk': 0x0E2E, 'paiyannoi': 0x0E2F, 'saraa': 0x0E30,
    'maihanakat': 0x0E31, 'saraaa': 0x0E32, 'saraam': 0x0E33,
    'sarai': 0x0E34, 'saraii': 0x0E35, 'saraue': 0x0E36, 'sarauee': 0x0E37,
    'sarau': 0x0E38, 'sarauu': 0x0E39, 'phinthu': 0x0E3A, 'sarae': 0x0E40,
    'saraae': 0x0E41, 'sarao': 0x0E42, 'saraaimaimalai': 0x0E43, 'saraaimaimuan': 0x0E44,
    'lakkhangyao': 0x0E45, 'maiyamok': 0x0E46, 'maitaikhu': 0x0E47,
    'maiek': 0x0E48, 'maitho': 0x0E49, 'maitri': 0x0E4A, 'maichattawa': 0x0E4B,
    'thanthakhat': 0x0E4C, 'nikhahit': 0x0E4D, 'nikkhahit': 0x0E4D, 'yamakkan': 0x0E4E,
    'fongman': 0x0E4F, 'zerothai': 0x0E50, 'onethai': 0x0E51, 'twothai': 0x0E52,
    'threethai': 0x0E53, 'fourthai': 0x0E54, 'fivethai': 0x0E55, 'sixthai': 0x0E56,
    'seventhai': 0x0E57, 'eightthai': 0x0E58, 'ninethai': 0x0E59,

    # Adobe Glyph List (AGLFN) & FontLab standard Thai aliases:
    'u-thai': 0x0E38, 'uu-thai': 0x0E39, 'phinthu-thai': 0x0E3A,
    'i-thai': 0x0E34, 'ii-thai': 0x0E35, 'ue-thai': 0x0E36, 'uee-thai': 0x0E37,
    'maihanakat-thai': 0x0E31, 'nikhahit-thai': 0x0E4D,
    'maiek-thai': 0x0E48, 'maitho-thai': 0x0E49, 'maitri-thai': 0x0E4A,
    'maichattawa-thai': 0x0E4B, 'thanthakhat-thai': 0x0E4C,
    'maitaikhu-thai': 0x0E47, 'yamakkan-thai': 0x0E4E,
    'saraa-thai': 0x0E30, 'saraaa-thai': 0x0E32, 'saraam-thai': 0x0E33,
    'sarae-thai': 0x0E40, 'saraae-thai': 0x0E41, 'sarao-thai': 0x0E42,
    'saraaimaimalai-thai': 0x0E43, 'saraaimaimuan-thai': 0x0E44,

    # Underscore & Hyphen aliases (e.g. sara_u, sara-u, sara_uu):
    'sara_u': 0x0E38, 'sara-u': 0x0E38, 'sarau': 0x0E38,
    'sara_uu': 0x0E39, 'sara-uu': 0x0E39, 'sarauu': 0x0E39,
    'sara_i': 0x0E34, 'sara-i': 0x0E34,
    'sara_ii': 0x0E35, 'sara-ii': 0x0E35,
    'sara_ue': 0x0E36, 'sara-ue': 0x0E36,
    'sara_uee': 0x0E37, 'sara-uee': 0x0E37,
    'sara_a': 0x0E30, 'sara-a': 0x0E30,
    'sara_aa': 0x0E32, 'sara-aa': 0x0E32,
    'sara_am': 0x0E33, 'sara-am': 0x0E33,
    'mai_ek': 0x0E48, 'mai-ek': 0x0E48,
    'mai_tho': 0x0E49, 'mai-tho': 0x0E49,
    'mai_tri': 0x0E4A, 'mai-tri': 0x0E4A,
    'mai_chattawa': 0x0E4B, 'mai-chattawa': 0x0E4B,
    'mai_hanakat': 0x0E31, 'mai-hanakat': 0x0E31,
    'mai_taikhu': 0x0E47, 'mai-taikhu': 0x0E47
}

UI_TEXT = {
    'th': {
        'app_title': 'F0NT Autokern',
        'tip_help': 'คู่มือการใช้งาน',
        'tip_tools': 'เครื่องมือ',

        'lbl_scope': 'ขอบเขต',
        'scope_font': 'ทั้งฟอนต์',
        'scope_sel': 'Glyph ที่เปิดอยู่',
        'chk_all_masters': 'ทำทุก Master',
        'lbl_scripts': 'ตัวอักษร',
        'sc_thai': 'ไทย',
        'sc_latin': 'ละติน',
        'sc_num': 'ตัวเลข',
        'sc_sym': 'สัญลักษณ์',
        'tip_scripts': 'ไทย: พยัญชนะและสระที่มีความกว้าง (ไม่รวมสระลอย / วรรณยุกต์)\nละติน: A–Z a–z · ตัวเลข: 0–9 และ ๐–๙ · สัญลักษณ์: เครื่องหมาย ASCII',
        'lbl_density': 'ความแน่น',
        'density_names': ('ชิดมาก', 'ชิด', 'ปกติ', 'โปร่ง', 'โปร่งมาก'),
        'lbl_base_sb': 'ระยะขอบพื้นฐาน',
        'tip_base_sb': 'ระยะขอบซ้าย / ขวาของตัวตรงอย่าง H (หน่วยที่ 1000 UPM) ตัวกลมหรือเว้าจะได้น้อยกว่านี้ตามรูปทรง',
        'lbl_tasks': 'งานที่ทำ',
        'chk_metrics': 'ปรับช่องไฟ (LSB / RSB)',
        'chk_kern': 'สร้าง Kerning',
        'chk_clr_kern': 'ล้างคู่เดิมแบบ glyph–glyph ก่อน (ไม่แตะคู่ class)',

        'btn_run_main': 'จัดช่องไฟและ Kerning',
        'btn_run_main_sel': 'จัดช่องไฟและ Kerning — Glyph ที่เปิดอยู่',

        'ready_status': 'พร้อมทำงาน',
        'next_step_init': 'ทดสอบกับไฟล์สำเนาก่อนเสมอ — สคริปต์ไม่มี Undo',
        'next_step_done': 'เสร็จแล้ว — ตรวจคู่ Kerning ใน Window › Panels › Kerning และลองพิมพ์ใน Preview',
        'btn_stop': 'หยุด',
        'log_toggle': 'รายละเอียด',
        'btn_clear_log': 'ล้าง',

        'menu_diag': 'ตรวจระบบ (Diagnostics)',
        'menu_scan': 'นับตัวอักษรแต่ละกลุ่ม',
        'menu_debug': 'Log แบบละเอียด',

        'help_main_title': 'คู่มือ F0NT Autokern',
        'help_main_body': (
            '<b>จัดช่องไฟและ Kerning จากรูปทรงจริงของตัวอักษร</b><br><br>'
            '<b>ขั้นตอน</b><br>'
            '1. เลือก <b>ขอบเขต</b> (ทั้งฟอนต์ / Glyph ที่เปิดอยู่) และติ๊ก <b>ทำทุก Master</b> ถ้าต้องการ<br>'
            '2. เลือก <b>ตัวอักษร</b> ที่จะจัด (กดเพื่อเปิด / ปิดแต่ละกลุ่ม)<br>'
            '3. ตั้ง <b>ความแน่น</b> และ <b>ระยะขอบพื้นฐาน</b><br>'
            '4. เลือก <b>งานที่ทำ</b>: ปรับช่องไฟ และ/หรือ สร้าง Kerning<br>'
            '5. กดปุ่มสีเขียวแล้วยืนยัน — ตรวจผลใน Kerning panel และ Preview<br><br>'
            '<b>ควรรู้</b><br>'
            '• สคริปต์ไม่มี Undo — ทดสอบกับไฟล์สำเนาเสมอ<br>'
            '• Kerning เขียนลงตาราง Kerning ของแต่ละ Master (คู่ชื่อเดียวกันจะถูกแทนค่า)<br>'
            '• ถ้าฟอนต์มี feature <code>kern</code> ที่เขียนเอง อาจซ้ำกับตาราง Kerning<br>'
            '• ถ้ามีข้อผิดพลาด กด “รายละเอียด” ที่ด้านล่างเพื่อดู log<br><br>'
            'คู่มือฉบับเต็ม: <code>docs/manual.md</code>'
        )
    },
    'en': {
        'app_title': 'F0NT Autokern',
        'tip_help': 'User guide',
        'tip_tools': 'Tools',

        'lbl_scope': 'Scope',
        'scope_font': 'Whole font',
        'scope_sel': 'Active glyph',
        'chk_all_masters': 'All masters',
        'lbl_scripts': 'Scripts',
        'sc_thai': 'Thai',
        'sc_latin': 'Latin',
        'sc_num': 'Digits',
        'sc_sym': 'Symbols',
        'tip_scripts': 'Thai: consonants & spacing vowels (no floating vowels / tones)\nLatin: A–Z a–z · Digits: 0–9 and ๐–๙ · Symbols: ASCII punctuation',
        'lbl_density': 'Density',
        'density_names': ('Extra tight', 'Tight', 'Normal', 'Loose', 'Extra loose'),
        'lbl_base_sb': 'Base sidebearing',
        'tip_base_sb': 'Left / right sidebearing of a straight glyph like H (units at 1000 UPM); round or open shapes get less',
        'lbl_tasks': 'Tasks',
        'chk_metrics': 'Set spacing (LSB / RSB)',
        'chk_kern': 'Generate kerning',
        'chk_clr_kern': 'Clear existing glyph–glyph pairs first (class pairs untouched)',

        'btn_run_main': 'Space & Kern',
        'btn_run_main_sel': 'Space & Kern — Active Glyph',

        'ready_status': 'Ready',
        'next_step_init': 'Always test on a copy first — the script has no undo',
        'next_step_done': 'Done — review pairs in Window › Panels › Kerning and test in the Preview',
        'btn_stop': 'Stop',
        'log_toggle': 'Details',
        'btn_clear_log': 'Clear',

        'menu_diag': 'Diagnostics',
        'menu_scan': 'Count glyphs per script',
        'menu_debug': 'Verbose log',

        'help_main_title': 'F0NT Autokern Guide',
        'help_main_body': (
            '<b>Spacing and kerning measured from the actual outlines</b><br><br>'
            '<b>Steps</b><br>'
            '1. Choose a <b>Scope</b> (whole font / active glyph) and tick <b>All masters</b> if needed<br>'
            '2. Pick the <b>Scripts</b> to process (click to toggle)<br>'
            '3. Set <b>Density</b> and <b>Base sidebearing</b><br>'
            '4. Choose <b>Tasks</b>: spacing and/or kerning<br>'
            '5. Click the green button and confirm — review in the Kerning panel and Preview<br><br>'
            '<b>Good to know</b><br>'
            '• No undo — always test on a copy<br>'
            '• Kerning goes into each master\'s kerning table (same-name pairs are replaced)<br>'
            '• A hand-written <code>kern</code> feature may duplicate the kerning table<br>'
            '• If something fails, open “Details” at the bottom to see the log<br><br>'
            'Full manual: <code>docs/manual.md</code>'
        )
    }
}


def _ensure_ui_indicator_icons():
    import os
    import zlib
    import struct
    import tempfile

    def write_rgba_png(path, width, height, pixel_fn):
        raw_rows = []
        for y in range(height):
            row = bytearray([0])
            for x in range(width):
                r, g, b, a = pixel_fn(x, y)
                row.extend((r, g, b, a))
            raw_rows.append(bytes(row))
        raw_data = b"".join(raw_rows)
        compressed = zlib.compress(raw_data, 9)

        def make_chunk(chunk_type, data):
            chunk = chunk_type + data
            crc = zlib.crc32(chunk) & 0xffffffff
            return struct.pack(">I", len(data)) + chunk + struct.pack(">I", crc)

        png = (
            b"\x89PNG\r\n\x1a\n" +
            make_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) +
            make_chunk(b"IDAT", compressed) +
            make_chunk(b"IEND", b"")
        )
        with open(path, "wb") as f:
            f.write(png)

    cache_dir = os.path.join(tempfile.gettempdir(), "f0nt_autokern_assets")
    try:
        os.makedirs(cache_dir)
    except Exception:
        pass

    chk_path = os.path.join(cache_dir, "chk_on.png")
    rad_path = os.path.join(cache_dir, "rad_on.png")

    if not os.path.exists(chk_path):
        def chk_px(x, y):
            pts = [(3, 8), (4, 9), (5, 10), (6, 11), (7, 10), (8, 9), (9, 8), (10, 7), (11, 6), (12, 5)]
            pts_thick = [(x, y - 1) for x, y in pts] + [(x, y + 1) for x, y in pts]
            if (x, y) in pts or (x, y) in pts_thick:
                return 255, 255, 255, 255
            return 0, 0, 0, 0
        try:
            write_rgba_png(chk_path, 16, 16, chk_px)
        except Exception:
            pass

    if not os.path.exists(rad_path):
        def rad_px(x, y):
            dx = x - 7.5
            dy = y - 7.5
            d = (dx * dx + dy * dy) ** 0.5
            if d <= 3.6:
                return 255, 255, 255, 255
            return 0, 0, 0, 0
        try:
            write_rgba_png(rad_path, 16, 16, rad_px)
        except Exception:
            pass

    return chk_path.replace("\\", "/"), rad_path.replace("\\", "/")


_CHK_ICON_PATH, _RAD_ICON_PATH = _ensure_ui_indicator_icons()

# ---- ธีม (ตามธีมสว่าง / มืดของ FontLab อัตโนมัติ) ----
THEME_COLORS = {
    'dark': {
        'bg': '#232427', 'surface': '#2d2e32', 'surface_hover': '#36373c', 'field': '#1b1c1f',
        'border': '#3c3d42', 'border_strong': '#5a5b61', 'text': '#ececee', 'muted': '#9b9ca3',
        'accent': '#2e9d68', 'accent_hover': '#35b376', 'accent_text': '#ffffff', 'accent_soft': '#203a2d',
        'danger': '#e5675f'
    },
    'light': {
        'bg': '#f4f4f6', 'surface': '#ffffff', 'surface_hover': '#ececf0', 'field': '#ffffff',
        'border': '#d6d6dc', 'border_strong': '#b4b4bc', 'text': '#1d1d1f', 'muted': '#6e6e76',
        'accent': '#1f8a57', 'accent_hover': '#24a065', 'accent_text': '#ffffff', 'accent_soft': '#e2f3e9',
        'danger': '#c8443c'
    }
}

STYLESHEET_TEMPLATE = """
QDialog {{ background: {bg}; color: {text}; font-size: 12px; }}
QLabel {{ color: {text}; background: transparent; }}
QLabel#title {{ font-size: 15px; font-weight: 600; }}
QLabel#formLabel {{ color: {muted}; }}
QLabel#section {{ color: {muted}; font-size: 11px; font-weight: 600; padding-top: 4px; }}
QLabel#hint {{ color: {muted}; font-size: 11px; }}
QLabel#status {{ color: {text}; font-size: 11px; }}

QPushButton {{ background: {surface}; color: {text}; border: 1px solid {border};
    border-radius: 6px; padding: 4px 10px; }}
QPushButton:hover {{ background: {surface_hover}; }}
QPushButton:disabled {{ color: {muted}; }}
QPushButton::menu-indicator {{ image: none; width: 0px; }}

QPushButton#primary {{ background: {accent}; color: {accent_text}; border: none; border-radius: 8px;
    font-size: 13px; font-weight: 600; padding: 9px 12px; }}
QPushButton#primary:hover {{ background: {accent_hover}; }}
QPushButton#primary:disabled {{ background: {border}; color: {muted}; }}

QPushButton#segFirst, QPushButton#segMid, QPushButton#segLast {{ border-radius: 0px; padding: 4px 12px; }}
QPushButton#segFirst {{ border-top-left-radius: 6px; border-bottom-left-radius: 6px; }}
QPushButton#segMid, QPushButton#segLast {{ border-left: none; }}
QPushButton#segLast {{ border-top-right-radius: 6px; border-bottom-right-radius: 6px; }}
QPushButton#segFirst:checked, QPushButton#segMid:checked, QPushButton#segLast:checked {{
    background: {accent}; color: {accent_text}; border-color: {accent}; }}

QPushButton#chip {{ border-radius: 11px; padding: 3px 12px; }}
QPushButton#chip:checked {{ background: {accent_soft}; border-color: {accent}; }}

QPushButton#link, QPushButton#dangerLink {{ background: transparent; border: none; padding: 2px 0px; color: {accent}; }}
QPushButton#dangerLink {{ color: {danger}; }}
QPushButton#link:hover, QPushButton#dangerLink:hover {{ text-decoration: underline; }}
QPushButton#link:disabled {{ color: {muted}; }}

QPushButton#icon {{ border-radius: 11px; min-width: 22px; max-width: 22px; min-height: 22px; max-height: 22px;
    padding: 0px; font-weight: 600; }}
QPushButton#reset {{ background: transparent; border: none; color: {muted}; padding: 0px 2px; }}
QPushButton#reset:hover {{ color: {accent}; }}

QToolButton#disclosure {{ background: transparent; border: none; color: {muted}; font-weight: 600; padding: 2px 0px; }}
QToolButton#disclosure:hover {{ color: {text}; }}

QCheckBox {{ spacing: 7px; color: {text}; }}
QCheckBox:disabled {{ color: {muted}; }}
QCheckBox::indicator {{ width: 14px; height: 14px; border: 1px solid {border_strong}; border-radius: 4px; background: {field}; }}
QCheckBox::indicator:checked {{ background: {accent}; border-color: {accent}; image: url("{chk_icon}"); }}

QLineEdit, QSpinBox, QComboBox {{ background: {field}; color: {text}; border: 1px solid {border};
    border-radius: 5px; padding: 2px 6px; min-height: 20px; }}
QLineEdit:focus, QSpinBox:focus, QComboBox:focus {{ border-color: {accent}; }}
QComboBox QAbstractItemView {{ background: {surface}; color: {text}; selection-background-color: {accent}; }}

QFrame#divider {{ background: {border}; border: none; min-height: 1px; max-height: 1px; }}
QProgressBar {{ background: {surface}; border: none; border-radius: 2px; min-height: 4px; max-height: 4px; }}
QProgressBar::chunk {{ background: {accent}; border-radius: 2px; }}
QTextEdit {{ background: {field}; color: {text}; border: 1px solid {border}; border-radius: 6px;
    font-family: Menlo, monospace; font-size: 11px; padding: 4px; }}
QSlider::groove:horizontal {{ height: 4px; background: {border}; border-radius: 2px; }}
QSlider::sub-page:horizontal {{ background: {accent}; border-radius: 2px; }}
QSlider::handle:horizontal {{ width: 14px; height: 14px; margin: -5px 0px; border-radius: 7px; background: {accent}; }}
QMenu {{ background: {surface}; color: {text}; border: 1px solid {border}; padding: 4px; }}
QMenu::item {{ padding: 5px 18px 5px 22px; border-radius: 4px; }}
QMenu::item:selected {{ background: {accent}; color: {accent_text}; }}
QMenu::separator {{ height: 1px; background: {border}; margin: 4px 6px; }}
QMessageBox QLabel {{ min-width: 360px; }}
"""


def build_stylesheet():
    """stylesheet ตามธีมปัจจุบันของ FontLab (ตรวจจากความสว่างของสีพื้นหลังหน้าต่าง)"""
    try:
        is_dark = QtGui.QApplication.palette().color(QtGui.QPalette.Window).lightness() < 128
    except Exception:
        is_dark = True
    colors = dict(THEME_COLORS['dark' if is_dark else 'light'])
    colors['chk_icon'] = _CHK_ICON_PATH
    return STYLESHEET_TEMPLATE.format(**colors)


def make_segmented(owner, count):
    """ปุ่มแบบแบ่งส่วน (เลือกได้ทีละปุ่ม) คืน (widget, [ปุ่ม])"""
    box = QtGui.QWidget()
    lay = QtGui.QHBoxLayout(box)
    lay.setContentsMargins(0, 0, 0, 0)
    lay.setSpacing(0)
    group = QtGui.QButtonGroup(box)
    group.setExclusive(True)
    owner._button_groups.append(group)  # เก็บ reference กัน garbage collector
    buttons = []
    for i in range(count):
        btn = QtGui.QPushButton("")
        btn.setCheckable(True)
        btn.setCursor(QtCore.Qt.PointingHandCursor)
        btn.setObjectName('segFirst' if i == 0 else ('segLast' if i == count - 1 else 'segMid'))
        group.addButton(btn)
        lay.addWidget(btn)
        buttons.append(btn)
    lay.addStretch()
    return box, buttons


def make_disclosure(window, content):
    """ปุ่มลูกศรสำหรับพับ / กาง content (เริ่มต้นพับไว้)"""
    btn = QtGui.QToolButton()
    btn.setObjectName('disclosure')
    btn.setCheckable(True)
    btn.setCursor(QtCore.Qt.PointingHandCursor)
    btn.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
    btn.setArrowType(QtCore.Qt.RightArrow)
    content.setVisible(False)

    def on_toggle(opened):
        content.setVisible(opened)
        btn.setArrowType(QtCore.Qt.DownArrow if opened else QtCore.Qt.RightArrow)
        window.adjustSize()
    btn.toggled.connect(on_toggle)
    return btn


def make_button(object_name, slot=None):
    btn = QtGui.QPushButton("")
    btn.setObjectName(object_name)
    btn.setCursor(QtCore.Qt.PointingHandCursor)
    if slot is not None:
        btn.clicked.connect(slot)
    return btn


def make_label(object_name, word_wrap=False):
    lbl = QtGui.QLabel("")
    lbl.setObjectName(object_name)
    lbl.setWordWrap(word_wrap)
    return lbl


def make_divider():
    line = QtGui.QFrame()
    line.setObjectName('divider')
    return line


class F0NTAutokernPanel(QtGui.QDialog):
    """
    Main F0NT Autokern Dialog (Clean, Minimal, Ultra-Friendly UI)
    """
    def __init__(self):
        super(F0NTAutokernPanel, self).__init__()
        self.lang = 'th'
        self.cancel_requested = False
        self._error_counts = {}
        self.font_error = ""

        self.fg_font = None
        self.fl_pkg = None
        self.fl_font = None
        self._button_groups = []

        self.refresh_font_context()
        self.initUI()
        self.apply_language()

    def is_valid_fl_obj(self, obj):
        if obj is None:
            return False
        try:
            return not bool(getattr(obj, 'isNull', lambda: False)())
        except Exception:
            return True

    def safe_iter(self, col, max_items=4000):
        if not col:
            return []
        try:
            if hasattr(col, '__len__') and not hasattr(col, 'values'):
                n = len(col)
                if n > max_items:
                    n = max_items
                out = []
                for i in range(n):
                    try:
                        it = col[i]
                        if self.is_valid_fl_obj(it):
                            out.append(it)
                    except Exception:
                        pass
                return out
        except Exception:
            pass
        out = []
        try:
            for it in col:
                if len(out) >= max_items:
                    break
                if self.is_valid_fl_obj(it):
                    out.append(it)
        except Exception:
            pass
        return out

    def get_val(self, widget, default=0):
        if widget is None:
            return default
        try:
            fn_text = getattr(widget, 'text', None)
            if fn_text is not None:
                t = str(fn_text() if callable(fn_text) else fn_text).strip()
                if t and t not in ('-', '+'):
                    return int(t)
                return default
        except Exception:
            pass

        try:
            fn_val = getattr(widget, 'value', None)
            if fn_val is not None:
                v = fn_val() if callable(fn_val) else fn_val
                return int(v)
        except Exception:
            pass

        return default

    def is_checked(self, widget):
        try:
            return bool(getattr(widget, 'isChecked', lambda: False)())
        except Exception:
            return False

    def set_progress(self, percent, status_text=""):
        self.progress_bar.setValue(percent)
        if status_text:
            self.lbl_progress_status.setText(status_text)
        try:
            QtCore.QCoreApplication.processEvents()
        except Exception:
            pass

    def request_cancel(self):
        self.cancel_requested = True
        self.log("⚠️ ผู้ใช้สั่งหยุดการทำงาน (Cancelling...)" if self.lang == 'th' else "⚠️ Operation cancelled by user.")
        self.btn_stop.setEnabled(False)

    def show_help_dialog(self):
        t = UI_TEXT[self.lang]
        box = QtGui.QMessageBox(self)
        box.setWindowTitle(t['help_main_title'])
        box.setTextFormat(QtCore.Qt.RichText)
        box.setText(t['help_main_body'])
        box.exec_()

    def show_log(self):
        if not self.btn_log.isChecked():
            self.btn_log.setChecked(True)

    def run_diagnostics_from_menu(self):
        self.show_log()
        self.run_spacing_diagnostics()

    def initUI(self):
        self.setWindowTitle("F0NT Autokern")
        self.setMinimumWidth(440)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowStaysOnTopHint)
        self.setStyleSheet(build_stylesheet())

        root = QtGui.QVBoxLayout()
        root.setContentsMargins(16, 14, 16, 14)
        root.setSpacing(12)

        # --- Header: ชื่อ + คู่มือ + เครื่องมือ + ภาษา ---
        head = QtGui.QHBoxLayout()
        head.setSpacing(6)
        self.lbl_title = make_label('title')
        self.lbl_title.setText("F0NT Autokern")
        head.addWidget(self.lbl_title)
        head.addStretch()
        self.btn_help = make_button('icon', self.show_help_dialog)
        self.btn_help.setText("?")
        self.btn_tools = make_button('icon')
        self.btn_tools.setText("⋯")
        self.menu_tools = QtGui.QMenu(self)
        self.act_diag = self.menu_tools.addAction("")
        self.act_diag.triggered.connect(self.run_diagnostics_from_menu)
        self.act_scan = self.menu_tools.addAction("")
        self.act_scan.triggered.connect(self.scan_script_counts)
        self.menu_tools.addSeparator()
        self.act_debug = self.menu_tools.addAction("")
        self.act_debug.setCheckable(True)
        self.btn_tools.setMenu(self.menu_tools)
        lang_box, (self.btn_lang_th, self.btn_lang_en) = make_segmented(self, 2)
        self.btn_lang_th.setText("TH")
        self.btn_lang_en.setText("EN")
        self.btn_lang_th.setChecked(True)
        self.btn_lang_th.clicked.connect(lambda *args: self.set_language('th'))
        self.btn_lang_en.clicked.connect(lambda *args: self.set_language('en'))
        head.addWidget(self.btn_help)
        head.addWidget(self.btn_tools)
        head.addSpacing(4)
        head.addWidget(lang_box)
        root.addLayout(head)

        # --- ฟอร์มหลัก ---
        form = QtGui.QGridLayout()
        form.setHorizontalSpacing(14)
        form.setVerticalSpacing(8)
        form.setColumnStretch(1, 1)

        self.lbl_scope = make_label('formLabel')
        scope_box, (self.btn_scope_font, self.chk_selected_only) = make_segmented(self, 2)
        self.btn_scope_font.setChecked(True)
        self.chk_selected_only.toggled.connect(self.update_scope_badge)
        form.addWidget(self.lbl_scope, 0, 0)
        form.addWidget(scope_box, 0, 1)
        self.chk_all_masters = QtGui.QCheckBox("")
        form.addWidget(self.chk_all_masters, 1, 1)

        self.lbl_scripts = make_label('formLabel')
        chips = QtGui.QHBoxLayout()
        chips.setSpacing(6)
        self.chk_sc_thai = make_button('chip')
        self.chk_sc_latin = make_button('chip')
        self.chk_sc_num = make_button('chip')
        self.chk_sc_sym = make_button('chip')
        for chip in (self.chk_sc_thai, self.chk_sc_latin, self.chk_sc_num, self.chk_sc_sym):
            chip.setCheckable(True)
            chip.setChecked(True)
            chips.addWidget(chip)
        chips.addStretch()
        form.addWidget(self.lbl_scripts, 2, 0)
        form.addLayout(chips, 2, 1)

        self.lbl_density = make_label('formLabel')
        dens_row = QtGui.QHBoxLayout()
        dens_row.setSpacing(10)
        self.slider_density = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.slider_density.setRange(1, 5)
        self.slider_density.setValue(3)
        self.slider_density.setPageStep(1)
        self.slider_density.valueChanged.connect(self.update_density_label)
        self.lbl_density_val = make_label('hint')
        self.lbl_density_val.setMinimumWidth(110)
        dens_row.addWidget(self.slider_density, 1)
        dens_row.addWidget(self.lbl_density_val)
        form.addWidget(self.lbl_density, 3, 0)
        form.addLayout(dens_row, 3, 1)

        self.lbl_base_sb = make_label('formLabel')
        sb_row = QtGui.QHBoxLayout()
        self.spin_base_sb = QtGui.QSpinBox()
        self.spin_base_sb.setRange(0, 300)
        self.spin_base_sb.setValue(45)
        self.spin_base_sb.setFixedWidth(72)
        self.spin_base_sb.setAlignment(QtCore.Qt.AlignRight)
        sb_row.addWidget(self.spin_base_sb)
        sb_row.addStretch()
        form.addWidget(self.lbl_base_sb, 4, 0)
        form.addLayout(sb_row, 4, 1)

        self.lbl_tasks = make_label('formLabel')
        tasks = QtGui.QVBoxLayout()
        tasks.setSpacing(6)
        self.chk_do_metrics = QtGui.QCheckBox("")
        self.chk_do_metrics.setChecked(True)
        self.chk_do_kerning = QtGui.QCheckBox("")
        self.chk_do_kerning.setChecked(True)
        self.chk_clear_kern = QtGui.QCheckBox("")
        self.chk_do_kerning.toggled.connect(lambda *args: self.chk_clear_kern.setEnabled(self.chk_do_kerning.isChecked()))
        clear_row = QtGui.QHBoxLayout()
        clear_row.setContentsMargins(22, 0, 0, 0)
        clear_row.addWidget(self.chk_clear_kern)
        tasks.addWidget(self.chk_do_metrics)
        tasks.addWidget(self.chk_do_kerning)
        tasks.addLayout(clear_row)
        form.addWidget(self.lbl_tasks, 5, 0, QtCore.Qt.AlignTop)
        form.addLayout(tasks, 5, 1)
        root.addLayout(form)

        # --- ปุ่มหลัก ---
        self.btn_kern = make_button('primary', self.run_spacing_and_kerning)
        root.addWidget(self.btn_kern)

        # --- สถานะ ---
        root.addWidget(make_divider())
        self.progress_bar = QtGui.QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(False)
        root.addWidget(self.progress_bar)
        status_row = QtGui.QHBoxLayout()
        self.lbl_progress_status = make_label('status')
        self.btn_stop = make_button('link', self.request_cancel)
        self.btn_stop.setEnabled(False)
        status_row.addWidget(self.lbl_progress_status, 1)
        status_row.addWidget(self.btn_stop)
        root.addLayout(status_row)
        self.lbl_next_step = make_label('hint', word_wrap=True)
        root.addWidget(self.lbl_next_step)

        # --- Log (พับไว้) ---
        self.log_box = QtGui.QTextEdit()
        self.log_box.setReadOnly(True)
        self.log_box.setMinimumHeight(150)
        log_row = QtGui.QHBoxLayout()
        self.btn_log = make_disclosure(self, self.log_box)
        self.btn_clear_log = make_button('link', lambda *args: self.log_box.clear())
        log_row.addWidget(self.btn_log)
        log_row.addStretch()
        log_row.addWidget(self.btn_clear_log)
        root.addLayout(log_row)
        root.addWidget(self.log_box)

        self.setLayout(root)

    def update_scope_badge(self):
        t = UI_TEXT[self.lang]
        self.btn_kern.setText(t['btn_run_main_sel'] if self.is_checked(self.chk_selected_only) else t['btn_run_main'])

    def set_language(self, lang):
        self.lang = lang
        self.apply_language()

    def apply_language(self):
        t = UI_TEXT[self.lang]
        self.btn_lang_th.setChecked(self.lang == 'th')
        self.btn_lang_en.setChecked(self.lang == 'en')
        self.setWindowTitle(t['app_title'])
        self.btn_help.setToolTip(t['tip_help'])
        self.btn_tools.setToolTip(t['tip_tools'])
        self.act_diag.setText(t['menu_diag'])
        self.act_scan.setText(t['menu_scan'])
        self.act_debug.setText(t['menu_debug'])

        self.lbl_scope.setText(t['lbl_scope'])
        self.btn_scope_font.setText(t['scope_font'])
        self.chk_selected_only.setText(t['scope_sel'])
        self.chk_all_masters.setText(t['chk_all_masters'])
        self.lbl_scripts.setText(t['lbl_scripts'])
        self.chk_sc_thai.setText(t['sc_thai'])
        self.chk_sc_latin.setText(t['sc_latin'])
        self.chk_sc_num.setText(t['sc_num'])
        self.chk_sc_sym.setText(t['sc_sym'])
        for chip in (self.chk_sc_thai, self.chk_sc_latin, self.chk_sc_num, self.chk_sc_sym):
            chip.setToolTip(t['tip_scripts'])
        self.lbl_density.setText(t['lbl_density'])
        self.lbl_base_sb.setText(t['lbl_base_sb'])
        self.lbl_base_sb.setToolTip(t['tip_base_sb'])
        self.spin_base_sb.setToolTip(t['tip_base_sb'])
        self.lbl_tasks.setText(t['lbl_tasks'])
        self.chk_do_metrics.setText(t['chk_metrics'])
        self.chk_do_kerning.setText(t['chk_kern'])
        self.chk_clear_kern.setText(t['chk_clr_kern'])

        self.lbl_progress_status.setText(t['ready_status'])
        self.lbl_next_step.setText(t['next_step_init'])
        self.btn_stop.setText(t['btn_stop'])
        self.btn_log.setText(t['log_toggle'])
        self.btn_clear_log.setText(t['btn_clear_log'])

        self.update_scope_badge()
        self.update_density_label()

    def update_density_label(self):
        val = self.get_val(self.slider_density, 3)
        names = UI_TEXT[self.lang]['density_names']
        self.lbl_density_val.setText("{} · {}%".format(names[val - 1], int(round(DENSITY_FACTORS[val] * 100))))

    def refresh_font_context(self):
        """fg_font = fgFont (FontGate), fl_pkg = flPackage (FontLab) ของฟอนต์ที่เปิดอยู่ หรือ None"""
        self.fg_font = None
        self.fl_pkg = None
        try:
            self.fg_font = fl6.CurrentFont()
            if self.fg_font is not None:
                self.fl_pkg = fl6.flPackage(self.fg_font)
        except Exception as e:
            self.font_error = "{}: {}".format(type(e).__name__, e)
        self.fl_font = self.fl_pkg

    def log(self, text):
        self.log_box.append(str(text))

    def report(self, text):
        """บันทึกผลลง log และแสดงบรรทัดแรกที่แถบสถานะ (log อาจพับอยู่)"""
        self.log(text)
        line = str(text).splitlines()[0] if text else ""
        for emoji, symbol in STATUS_SYMBOLS:
            if line.startswith(emoji):
                line = symbol + line[len(emoji):]
                break
        self.lbl_progress_status.setText(line.strip())

    def log_error(self, where, exc, detail=""):
        """แสดง error จริงใน log (แต่ละจุดแสดงไม่เกิน 3 ครั้งต่อการรัน แล้วสรุปจำนวนตอนจบ)"""
        key = (where, type(exc).__name__)
        n = self._error_counts.get(key, 0) + 1
        self._error_counts[key] = n
        self.show_log()
        if n <= 3:
            self.log("<span style='color: #e5675f;'>❌ {}{}: {}: {}</span>".format(
                where, " [" + detail + "]" if detail else "", type(exc).__name__, exc))

    def error_total(self):
        return sum(self._error_counts.values())

    def debug_log(self, text):
        if self.is_checked(self.act_debug):
            self.log_box.append("<span style='color: #38bdf8;'>[DEBUG] " + str(text) + "</span>")

    def get_cap_height(self):
        try:
            val = float(_get(self.fl_pkg, 'capsHeight_value'))
            if val > 0:
                return val
        except Exception as e:
            self.log_error("capsHeight_value", e)
        self.log("⚠️ อ่าน Caps Height ไม่ได้ ใช้ค่า 700" if self.lang == 'th' else "⚠️ Caps Height unavailable, using 700")
        return 700.0

    def get_upm(self):
        try:
            val = float(_get(self.fl_pkg, 'upm'))
            if val > 0:
                return val
        except Exception as e:
            self.log_error("upm", e)
        self.log("⚠️ อ่าน UPM ไม่ได้ ใช้ค่า 1000" if self.lang == 'th' else "⚠️ UPM unavailable, using 1000")
        return 1000.0

    def get_upm_scale(self):
        return self.get_upm() / 1000.0

    def parse_unicode_value(self, val):
        if val is None:
            return None
        if isinstance(val, int):
            return val if val > 0 else None
        try:
            val_str = str(val).strip()
            if not val_str:
                return None
            if val_str.startswith('0x') or val_str.startswith('0X'):
                return int(val_str, 16)
            if val_str.isdigit():
                return int(val_str, 10)
            if len(val_str) == 1:
                return ord(val_str)
        except Exception:
            pass
        return None

    def resolve_name_to_unicode(self, raw_name):
        if not raw_name:
            return None, ""
        clean = raw_name.strip()
        base = clean
        suffix = ""
        if '.' in clean:
            parts = clean.split('.', 1)
            base = parts[0]
            suffix = '.' + parts[1]
            if suffix.lower() == '.thai':
                base = base + '-thai'
                suffix = ""

        lower_base = base.lower()
        if lower_base in THAI_NAME_TO_UNICODE:
            return THAI_NAME_TO_UNICODE[lower_base], suffix

        norm = lower_base.replace('_', '').replace('-', '')
        if norm in THAI_NAME_TO_UNICODE:
            return THAI_NAME_TO_UNICODE[norm], suffix

        if lower_base.endswith('-thai'):
            th_key = lower_base[:-5]
            if th_key in THAI_NAME_TO_UNICODE:
                return THAI_NAME_TO_UNICODE[th_key], suffix
            norm_th = th_key.replace('_', '').replace('-', '')
            if norm_th in THAI_NAME_TO_UNICODE:
                return THAI_NAME_TO_UNICODE[norm_th], suffix

        for pfx in ('uni', 'u', 'u+'):
            if lower_base.startswith(pfx):
                hex_part = lower_base[len(pfx):]
                if len(hex_part) == 4:
                    try:
                        return int(hex_part, 16), suffix
                    except Exception:
                        pass
        return None, suffix

    def get_glyph_unicode_and_suffix(self, fg_glyph, fl_glyph=None):
        raw_name = ""
        for g in (fg_glyph, fl_glyph):
            if g is not None:
                name_val = getattr(g, 'name', "")
                raw_name = str(name_val() if callable(name_val) else name_val)
                if raw_name:
                    break

        for g in (fg_glyph, fl_glyph):
            if g is not None:
                for attr in ('unicodes', 'unicode'):
                    if hasattr(g, attr):
                        val = getattr(g, attr)
                        val = val() if callable(val) else val
                        if isinstance(val, (list, tuple)) and len(val) > 0:
                            u = self.parse_unicode_value(val[0])
                            if u:
                                sfx = ('.' + raw_name.split('.', 1)[1]) if '.' in raw_name else ""
                                return u, sfx, raw_name
                        else:
                            u = self.parse_unicode_value(val)
                            if u:
                                sfx = ('.' + raw_name.split('.', 1)[1]) if '.' in raw_name else ""
                                return u, sfx, raw_name

        u, sfx = self.resolve_name_to_unicode(raw_name)
        return u, sfx, raw_name

    def get_all_font_glyphs(self):
        """list ของ fgGlyph ตามขอบเขต: ทั้งฟอนต์ หรือเฉพาะ Glyph ที่เปิดอยู่ (ถ้าเลือกไว้ใน Debug)"""
        self.refresh_font_context()
        if self.fg_font is None or self.fl_pkg is None:
            return []

        if self.is_checked(self.chk_selected_only):
            try:
                curr_g = fl6.CurrentGlyph()
            except Exception as e:
                self.log_error("CurrentGlyph()", e)
                curr_g = None
            return [curr_g] if curr_g is not None else []

        try:
            return list(self.fg_font.glyphs)
        except Exception as e:
            self.log_error("fgFont.glyphs", e)
            return []

    def get_master_layer_name(self):
        try:
            name = _get(self.fl_pkg, 'master')
            return str(name) if name else None
        except Exception as e:
            self.log_error("flPackage.master", e)
            return None

    def get_active_layers(self, item, need_fl_layer=False):
        """คืน (fg_glyph, fl_glyph, None, fl_layer) — fl_layer คือ layer ของ master ที่เปิดอยู่"""
        fg_glyph = item
        fl_layer = None
        try:
            fl_glyph = fl6.flGlyph(fg_glyph, self.fg_font)
        except Exception as e:
            self.log_error("flGlyph()", e, _get_name(fg_glyph))
            return fg_glyph, None, None, None

        if need_fl_layer:
            master = self.get_master_layer_name()
            try:
                if master:
                    fl_layer = fl_glyph.findLayer(master)
                if fl_layer is None:
                    fl_layer = _get(fl_glyph, 'activeLayer')
            except Exception as e:
                self.log_error("findLayer / activeLayer", e, _get_name(fl_glyph))
        return fg_glyph, fl_glyph, None, fl_layer

    def get_layer_bbox(self, fl_layer):
        """(x_min, y_min, w, h) ของเส้นจริง (ink) — คืน (0, 0, 0, 0) ถ้า layer ว่าง
        วัดจาก contour (getContours -> QPainterPath) เพราะ flLayer.boundingBox อาจกว้างกว่าเส้นจริง
        (พบใน FontLab 8.4.2 — น่าจะรวม anchor) ถ้ามี component หรือไม่มี contour จึงใช้ boundingBox แทน"""
        if fl_layer is None:
            return (0.0, 0.0, 0.0, 0.0)
        try:
            if not any(_get(s, 'isComponent') for s in fl_layer.shapes):
                contours = list(fl_layer.getContours())
                if contours:
                    path = QtGui.QPainterPath()
                    for contour in contours:
                        path.addPath(contour.path())
                    r = path.boundingRect()
                    return (float(r.x()), float(r.y()), float(r.width()), float(r.height()))
            r = _get(fl_layer, 'boundingBox')
            return (float(r.x()), float(r.y()), float(r.width()), float(r.height()))
        except Exception as e:
            self.log_error("bounding box", e, _get_name(fl_layer))
            return (0.0, 0.0, 0.0, 0.0)

    def notify_glyph_updated(self, fl_glyph):
        if fl_glyph is None or self.fl_pkg is None:
            return
        try:
            fl_glyph.update()
        except Exception as e:
            self.log_error("flGlyph.update()", e)
        try:
            fl6.flItems.notifyGlyphUpdated(self.fl_pkg.id, fl_glyph.id)
        except Exception as e:
            self.log_error("notifyGlyphUpdated", e)

    def update_fontlab_viewport(self):
        try:
            fl6.Update()
        except Exception as e:
            self.log_error("fontlab.Update()", e)

    def confirm_action(self, text_th, text_en):
        res = QtGui.QMessageBox.question(
            self, "F0NT Autokern", text_th if self.lang == 'th' else text_en,
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No
        )
        return res == QtGui.QMessageBox.Yes

    def get_script_group(self, u):
        if not u:
            return None
        # ตรวจตัวเลขก่อน เพราะเลขไทย ๐-๙ (U+0E50–0E59) อยู่ในช่วง Unicode ภาษาไทยด้วย
        if (0x0030 <= u <= 0x0039) or (0x0E50 <= u <= 0x0E59):
            return 'DIGIT'
        if 0x0E01 <= u <= 0x0E5B:
            return 'THAI'
        if (0x0041 <= u <= 0x005A) or (0x0061 <= u <= 0x007A):
            return 'LATIN'
        if (0x0020 <= u <= 0x002F) or (0x003A <= u <= 0x0040) or (0x005B <= u <= 0x0060) or (0x007B <= u <= 0x007E):
            return 'SYMBOL'
        return None

    def get_structural_band_profile(self, u, y_min, h, cap_height):
        b0_ratio = 0.0
        b1_ratio = 0.0
        b2_ratio = 0.0

        if u:
            # 1. กลวงบน เช่น โ ไ ใ T V Y
            if u in [0x0E42, 0x0E43, 0x0E44, 0x0054, 0x0056, 0x0059]:
                b0_ratio, b1_ratio, b2_ratio = 0.40, 0.20, 0.00
            # 2. กลวงล่าง เช่น ข ช ซ ย A
            elif u in [0x0E02, 0x0E0A, 0x0E0B, 0x0E22, 0x0041]:
                b0_ratio, b1_ratio, b2_ratio = 0.00, 0.20, 0.45
            # 3. โค้งมนกึ่งโปร่ง เช่น อ ฮ C G O
            elif u in [0x0E2D, 0x0E2E, 0x0043, 0x0047, 0x004F]:
                b0_ratio, b1_ratio, b2_ratio = 0.20, 0.05, 0.20
            # 4. แท่งตรงทึบ เช่น ก ถ พ ฟ H I M
            elif u in [0x0E01, 0x0E16, 0x0E1E, 0x0E1F, 0x0048, 0x0049, 0x004D]:
                b0_ratio, b1_ratio, b2_ratio = 0.00, 0.00, 0.00
            else:
                b0_ratio, b1_ratio, b2_ratio = 0.15, 0.10, 0.15
        else:
            b0_ratio, b1_ratio, b2_ratio = 0.15, 0.10, 0.15

        return (
            (b0_ratio, b1_ratio, b2_ratio),
            (b0_ratio, b1_ratio, b2_ratio)
        )

    def find_glyph_by_code(self, code):
        """glyph ตัวหลัก (ชื่อไม่มี suffix) ของ Unicode นี้ — หาจาก Unicode ก่อน
        ถ้าไม่มี glyph ไหนผูก Unicode นี้ไว้ หาจากชื่อแทน (เช่น uni0E01, kokai, kokai-thai) — ไม่พบคืน None"""
        by_name = None
        for g in self.fg_font.glyphs:
            name = _get_name(g)
            if '.' in name:
                continue
            try:
                if code in list(g.unicodes):
                    return g
            except Exception:
                pass
            if by_name is None:
                u, sfx = self.resolve_name_to_unicode(name)
                if u == code and not sfx:
                    by_name = g
        return by_name

    def get_thai_height(self):
        """ความสูงพยัญชนะไทย = ขอบบนของ outline ตัวแรกที่ดึงได้ (ก -> ด -> บ -> อ) ใน master ปัจจุบัน
        ตัวที่ไม่พบหรือไม่มี outline ข้ามไป  ไม่ได้เลยใช้ Caps Height"""
        for label, code in THAI_HEIGHT_SOURCES:
            try:
                g = self.find_glyph_by_code(code)
                if g is None:
                    continue
                _, _, _, fl_layer = self.get_active_layers(g, need_fl_layer=True)
                x_min, y_min, w, h = self.get_layer_bbox(fl_layer)
            except Exception as e:
                self.log_error("thai height", e, label)
                continue
            if h > 0:
                self.debug_log("ความสูงพยัญชนะไทยจาก '{}' ({})".format(label, _get_name(g)))
                return float(y_min + h)
        self.log("⚠️ ไม่พบ ก / ด / บ / อ ที่มี outline — ใช้ Caps Height แทนความสูงพยัญชนะไทย" if self.lang == 'th'
                 else "⚠️ No ก / ด / บ / อ outline found — using Caps Height as Thai consonant height")
        return self.get_cap_height()

    def get_outline_path(self, fl_layer, bbox):
        """QPainterPath ของ contour ทั้งหมดใน layer — คืน None ถ้าอ่านไม่ได้หรือไม่ครบ
        (เช่น glyph ที่มี component ซึ่ง getContours ไม่รวม) ตรวจโดยเทียบกรอบกับ boundingBox ของ layer"""
        x_min, y_min, w, h = bbox
        try:
            path = QtGui.QPainterPath()
            path.setFillRule(QtCore.Qt.WindingFill)
            for contour in fl_layer.getContours():
                path.addPath(contour.path())
            r = path.boundingRect()
        except Exception as e:
            self.log_error("getContours / path", e, _get_name(fl_layer))
            return None
        tol = max(3.0, 0.02 * max(w, h))
        if (abs(r.x() - x_min) > tol or abs(r.y() - y_min) > tol or
                abs(r.width() - w) > tol or abs(r.height() - h) > tol):
            return None
        return path

    def measure_profile(self, path, bbox, y_top):
        """วัดขอบซ้าย / ขวาของ outline ใน PROFILE_SLICES แถบแนวนอน ตั้งแต่ baseline ถึง y_top
        คืน {'xl': [...], 'xr': [...]} (None = แถบนั้นไม่มีเส้น)"""
        x_min, y_min, w, h = bbox
        step = y_top / float(PROFILE_SLICES)
        xl, xr = [], []
        for i in range(PROFILE_SLICES):
            band = QtGui.QPainterPath()
            band.addRect(QtCore.QRectF(x_min - 10.0, i * step, w + 20.0, step))
            part = path.intersected(band)
            if part.isEmpty():
                xl.append(None)
                xr.append(None)
            else:
                r = part.boundingRect()
                xl.append(r.left())
                xr.append(r.right())
        return {'xl': xl, 'xr': xr, 'step': step}

    def bands_from_profile(self, prof, bbox, ref_height):
        """ความลึกของโพรงซ้าย / ขวา (สัดส่วนของความกว้าง 0–0.5) ใน 3 ระนาบ (บน, กลาง, ล่าง) ภายในความสูง ref_height"""
        x_min, y_min, w, h = bbox
        thirds = ([], [], [])  # top, middle, bottom
        for i in range(PROFILE_SLICES):
            y_mid = (i + 0.5) * prof['step']
            if y_mid > ref_height or prof['xl'][i] is None:
                continue
            idx = 2 - min(2, int(3 * y_mid / ref_height))
            thirds[idx].append(i)

        def depth(values):
            return min(0.5, sum(values) / len(values)) if values else 0.0

        left = tuple(depth([(prof['xl'][i] - x_min) / w for i in t]) for t in thirds)
        right = tuple(depth([(x_min + w - prof['xr'][i]) / w for i in t]) for t in thirds)
        return left, right

    def set_glyph_sidebearings(self, fl_glyph, fl_layer, new_lsb, new_rsb, bbox):
        """ตั้ง LSB / RSB ของ fl_layer
        - ถ้า fl_layer เป็น active layer ของ glyph: ใช้ flGlyph.setSB (ยืนยันแล้ว)
        - ถ้าไม่ใช่ (master อื่น): เลื่อน outline ด้วย flLayer.applyTransform แล้วตั้ง advanceWidth
        ตรวจผลด้วยการอ่าน boundingBox กลับมา"""
        if fl_glyph is None or fl_layer is None:
            return False
        x_min, y_min, w, h = bbox
        try:
            if _get_name(_get(fl_glyph, 'activeLayer')) == _get_name(fl_layer):
                fl_glyph.setSB(float(new_lsb), float(new_rsb), False, False, QtGui.QTransform())
                return True
            shift = QtGui.QTransform()
            shift.translate(float(new_lsb) - x_min, 0.0)
            fl_layer.applyTransform(shift)
            fl_layer.advanceWidth = float(new_lsb) + w + float(new_rsb)
        except Exception as e:
            self.log_error("set sidebearings", e, _get_name(fl_glyph))
            return False

        new_x_min = self.get_layer_bbox(fl_layer)[0]
        if abs(new_x_min - float(new_lsb)) > 1.0:
            self.log_error("applyTransform", RuntimeError("LSB หลังเลื่อน = {:.1f} (ต้องการ {})".format(
                new_x_min, new_lsb)), "{} / {}".format(_get_name(fl_glyph), _get_name(fl_layer)))
            return False
        return True

    def are_groups_compatible(self, g1, g2):
        if g1 == g2:
            return True
        if (g1, g2) in [('THAI', 'DIGIT'), ('DIGIT', 'THAI'), ('LATIN', 'DIGIT'), ('DIGIT', 'LATIN')]:
            return True
        return False

    def generate_optical_kerning_pairs(self, profiles, density_factor, base_sb, status_prefix):
        """คำนวณคู่ kerning จากระยะห่างจริงระหว่างขอบขวาของตัวซ้ายกับขอบซ้ายของตัวขวา ในทุกแถบความสูงที่มีเส้นทั้งคู่
        ระยะที่ใช้ = KERN_MIN_WEIGHT × ระยะแคบสุด + ส่วนที่เหลือ × ระยะเฉลี่ย  เทียบกับระยะเป้าหมาย (2 × Base SB)
        คืน list ของ (left_name, right_name, value) — สร้างเฉพาะค่าติดลบ (ดึงเข้าหากัน)"""
        collected_pairs = []
        scale = self.get_upm_scale()
        threshold = int(round(-12 * scale))
        max_limit = int(round(-120 * scale))
        pull_strength = max(0.5, min(2.0, 1.4 - (density_factor * 0.4)))

        # ระยะจากเส้นถึงขอบ advance ในแต่ละแถบ (คำนวณครั้งเดียวต่อ glyph)
        for p in profiles:
            prof = p['prof']
            p['gap_r'] = [None if x is None else (p['x_max'] - x) + p['rsb'] for x in prof['xr']]
            p['gap_l'] = [None if x is None else (x - p['x_min']) + p['lsb'] for x in prof['xl']]

        # ระยะเป้าหมาย = ระยะจริงของคู่อ้างอิง (เช่น H–H) ใน master นี้ เพื่อให้ถูกต้องแม้ช่องไฟไม่ได้ถูกปรับ
        target_gap = 2.0 * base_sb
        ref = next((p for name in KERN_REFERENCE_GLYPHS for p in profiles if p['name'] == name), None)
        if ref is not None:
            ref_gaps = [a + b for a, b in zip(ref['gap_r'], ref['gap_l']) if a is not None and b is not None]
            if ref_gaps:
                target_gap = min(ref_gaps)
        ref_label = "{0}–{0}".format(ref['name']) if ref is not None else "2 × Base SB"
        self.log("ระยะอ้างอิง kerning = {:.0f} ({})".format(target_gap, ref_label) if self.lang == 'th'
                 else "Kerning reference gap = {:.0f} ({})".format(target_gap, ref_label))

        total_l = len(profiles)
        for i, prof_l in enumerate(profiles):
            if self.cancel_requested:
                break
            if i % 8 == 0:
                pct = 50 + int((i / float(max(1, total_l))) * 45)
                self.set_progress(pct, "{} ({}/{})".format(status_prefix, i, total_l))

            for prof_r in profiles:
                if not self.are_groups_compatible(prof_l['group'], prof_r['group']):
                    continue

                gaps = [a + b for a, b in zip(prof_l['gap_r'], prof_r['gap_l']) if a is not None and b is not None]
                if len(gaps) < MIN_OVERLAP_SLICES:
                    continue

                effective = KERN_MIN_WEIGHT * min(gaps) + (1.0 - KERN_MIN_WEIGHT) * (sum(gaps) / len(gaps))
                excess = effective - target_gap
                if excess <= 0:
                    continue

                raw_kern = -int(round(excess * KERN_STRENGTH * pull_strength))
                if raw_kern <= threshold:
                    collected_pairs.append((prof_l['name'], prof_r['name'], max(max_limit, raw_kern)))

        if len(collected_pairs) > MAX_KERN_PAIRS:
            collected_pairs.sort(key=lambda item: abs(item[2]), reverse=True)
            collected_pairs = collected_pairs[:MAX_KERN_PAIRS]
        return collected_pairs

    def write_kerning_pairs(self, pairs):
        """เขียนคู่ kerning ลงตาราง kerning ของ master ปัจจุบัน (คู่ชื่อเดียวกันจะถูกแทนค่า)  คืนจำนวนที่เขียนสำเร็จ"""
        master = self.get_master_layer_name()
        try:
            kern = self.fl_pkg.kerning(master) if master else self.fl_pkg.kerning()
        except Exception as e:
            self.log_error("flPackage.kerning()", e, str(master))
            return 0

        written = 0
        for name_l, name_r, val in pairs:
            try:
                kern.set((name_l, name_r), float(val))
                written += 1
            except Exception as e:
                self.log_error("kerning.set", e, "{} {}".format(name_l, name_r))
        try:
            fl6.flItems.notifyPackageContentUpdated(self.fl_pkg.id)
        except Exception as e:
            self.log_error("notifyPackageContentUpdated", e)
        return written

    def clear_scope_kerning(self, names):
        """ลบคู่ kerning แบบ glyph–glyph ที่ทั้งสองฝั่งอยู่ใน names (master ปัจจุบัน) — คู่ที่มี class ไม่ถูกแตะ
        คืนจำนวนคู่ที่ลบ"""
        master = self.get_master_layer_name()
        try:
            kern = self.fl_pkg.kerning(master) if master else self.fl_pkg.kerning()
            targets = []
            for pair in kern.keys():
                l_id, l_mode = pair.left.asTuple()
                r_id, r_mode = pair.right.asTuple()
                if l_mode == 'glyphMode' and r_mode == 'glyphMode' and l_id in names and r_id in names:
                    targets.append((l_id, r_id))
        except Exception as e:
            self.log_error("kerning.keys()", e, str(master))
            return 0

        removed = 0
        for pair in targets:
            try:
                kern.remove(pair)
                removed += 1
            except Exception as e:
                self.log_error("kerning.remove", e, "{} {}".format(*pair))
        self.log("🗑️ ล้างคู่ Kerning เดิม (glyph–glyph) {} คู่".format(removed) if self.lang == 'th'
                 else "🗑️ Cleared {} existing glyph–glyph kerning pairs".format(removed))
        return removed

    def warn_if_kern_feature_exists(self):
        """เตือนเมื่อมี feature kern (เช่นจากสคริปต์รุ่นเก่า) ซึ่งอาจซ้ำกับตาราง kerning"""
        try:
            if self.fg_font.features.has_key('kern'):
                self.log("⚠️ พบ feature 'kern' ใน Features panel — อาจซ้ำกับตาราง Kerning ควรตรวจสอบ/ลบเองก่อน export"
                         if self.lang == 'th' else "⚠️ A 'kern' feature exists in the Features panel — it may duplicate the kerning table; review it before export")
        except Exception as e:
            self.log_error("features.has_key('kern')", e)

    def scan_script_counts(self):
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            self.log("ไม่พบไฟล์ฟอนต์ที่กำลังเปิดอยู่" if self.lang == 'th' else "No active font found.")
            return

        c_thai = 0
        c_latin = 0
        c_num = 0
        c_sym = 0

        for item in raw_glyphs:
            fg_g, fl_g, _, _ = self.get_active_layers(item, need_fl_layer=False)
            u, _, _ = self.get_glyph_unicode_and_suffix(fg_g, fl_g)
            grp = self.get_script_group(u)
            if grp == 'THAI':
                c_thai += 1
            elif grp == 'LATIN':
                c_latin += 1
            elif grp == 'DIGIT':
                c_num += 1
            elif grp == 'SYMBOL':
                c_sym += 1

        info_th = "ไทย {} · ละติน {} · ตัวเลข {} · สัญลักษณ์ {}".format(
            c_thai, c_latin, c_num, c_sym
        )
        info_en = "Thai {} · Latin {} · Digits {} · Symbols {}".format(
            c_thai, c_latin, c_num, c_sym
        )
        self.report(info_th if self.lang == 'th' else info_en)

    def run_spacing_diagnostics(self):
        """ตรวจระบบแบบอ่านอย่างเดียว (ไม่แก้ไขฟอนต์)"""
        self.log_box.clear()
        self._error_counts = {}
        self.log("🔍 เริ่มการวินิจฉัยระบบจัดช่องไฟ (อ่านอย่างเดียว)..." if self.lang == 'th' else "🔍 Running Spacing Diagnostics (read-only)...")

        raw_glyphs = self.get_all_font_glyphs()
        self.log("1. ตรวจสอบการเชื่อมต่อโมเดลฟอนต์:")
        self.log("   - fgFont: {}, flPackage: {}".format(
            type(self.fg_font).__name__ if self.fg_font is not None else "None",
            type(self.fl_pkg).__name__ if self.fl_pkg is not None else "None"))
        if self.fl_pkg is None:
            self.log("⚠️ ไม่พบฟอนต์ที่เปิดอยู่")
            return
        self.log("   - Master ปัจจุบัน: {}".format(self.get_master_layer_name()))
        self.log("   - จำนวน Glyph ทั้งหมด: {}".format(len(raw_glyphs)))
        self.log("   - UPM: {}, Cap Height: {}".format(self.get_upm(), self.get_cap_height()))

        sample_item = None
        for item in raw_glyphs:
            u, _, _ = self.get_glyph_unicode_and_suffix(item)
            if u in (0x0E01, 0x0048, 0x0041):
                sample_item = item
                break
        if sample_item is None and raw_glyphs:
            sample_item = raw_glyphs[0]
        if sample_item is None:
            self.log("⚠️ ไม่พบ Glyph ในฟอนต์ที่กำลังเปิดอยู่")
            return

        fg_g, fl_g, _, fl_l = self.get_active_layers(sample_item, need_fl_layer=True)
        u, sfx, g_name = self.get_glyph_unicode_and_suffix(fg_g, fl_g)
        x_min, y_min, w, h = self.get_layer_bbox(fl_l)

        self.log("2. Glyph ตัวอย่าง '{}' (U+{:04X}):".format(g_name, u if u else 0))
        self.log("   - BBox: x_min={:.1f}, y_min={:.1f}, w={:.1f}, h={:.1f}".format(x_min, y_min, w, h))
        try:
            adv_w = float(_get(fl_l, 'advanceWidth'))
            self.log("   - จาก BBox: LSB={:.1f}, RSB={:.1f}, Advance={:.1f}".format(x_min, adv_w - (x_min + w), adv_w))
        except Exception as e:
            self.log_error("advanceWidth", e)
        try:
            self.log("   - flGlyph.getSB(): {}, active layer: {}".format(
                fl_g.getSB(QtGui.QTransform()), _get_name(_get(fl_g, 'activeLayer'))))
        except Exception as e:
            self.log_error("getSB", e)
        bbox = (x_min, y_min, w, h)
        ref_height = self.get_thai_height() if self.get_script_group(u) == 'THAI' else self.get_cap_height()
        path = self.get_outline_path(fl_l, bbox) if fl_l is not None and w > 0 else None
        if path is None:
            self.log("   - ⚠️ อ่าน outline ไม่ครบ (จะใช้ตารางค่าประมาณแทนสำหรับ glyph นี้)")
        else:
            prof = self.measure_profile(path, bbox, ref_height)
            l_bands, r_bands = self.bands_from_profile(prof, bbox, ref_height)
            filled = sum(1 for x in prof['xl'] if x is not None)
            self.log("   - วัด outline: {} / {} แถบมีเส้น (ความสูงอ้างอิง {:.0f})".format(filled, PROFILE_SLICES, ref_height))
            self.log("   - โพรง (บน, กลาง, ล่าง): ซ้าย={}, ขวา={}".format(
                tuple(round(v, 2) for v in l_bands), tuple(round(v, 2) for v in r_bands)))
        try:
            master = self.get_master_layer_name()
            kern = self.fl_pkg.kerning(master) if master else self.fl_pkg.kerning()
            self.log("   - คู่ Kerning ใน Master นี้: {}".format(len(kern.keys())))
        except Exception as e:
            self.log_error("flPackage.kerning()", e)

        if self.error_total():
            self.report("⚠️ พบข้อผิดพลาด {} ครั้ง — ส่ง log นี้กลับมาเพื่อแก้ไข".format(self.error_total()))
        else:
            self.report("✅ วินิจฉัยเสร็จ ไม่พบข้อผิดพลาด")

    def run_spacing_and_kerning(self):
        self._error_counts = {}
        raw_glyphs = self.get_all_font_glyphs()
        if not raw_glyphs:
            msg = "ไม่พบไฟล์ฟอนต์ที่กำลังเปิดอยู่" if self.lang == 'th' else "No active font found."
            self.log(msg)
            return

        do_metrics = self.is_checked(self.chk_do_metrics)
        do_kerning = self.is_checked(self.chk_do_kerning)
        do_clear_kern = do_kerning and self.is_checked(self.chk_clear_kern)
        if not (do_metrics or do_kerning):
            return
        master = self.get_master_layer_name()
        masters = [master]
        if self.is_checked(self.chk_all_masters):
            try:
                masters += [str(m) for m in _get(self.fl_pkg, 'masters') if str(m) != master]
            except Exception as e:
                self.log_error("flPackage.masters", e)
        if not self.confirm_action(
            "{} ใน Master '{}' ({} glyph ในขอบเขต)\nสคริปต์ไม่มี Undo — แนะนำให้ทดสอบกับไฟล์สำเนา\nดำเนินการต่อ?".format(
                " + ".join((["ปรับ LSB/RSB"] if do_metrics else []) + (["ล้างคู่ Kerning เดิม (glyph–glyph)"] if do_clear_kern else [])
                           + (["เขียนคู่ Kerning"] if do_kerning else [])),
                "', '".join(masters), len(raw_glyphs)),
            "{} in master '{}' ({} glyphs in scope)\nNo undo — test on a copy first.\nContinue?".format(
                " + ".join((["set LSB/RSB"] if do_metrics else []) + (["clear old glyph–glyph pairs"] if do_clear_kern else [])
                           + (["write kerning pairs"] if do_kerning else [])),
                "', '".join(masters), len(raw_glyphs))
        ):
            return

        self.cancel_requested = False
        self.btn_stop.setEnabled(True)
        self.log_box.clear()
        self.set_progress(0, "กำลังเริ่มต้นจัดช่องไฟ..." if self.lang == 'th' else "Initializing spacing & kerning...")

        try:
            settings = {
                'do_metrics': do_metrics,
                'do_kerning': do_kerning,
                'do_clear_kern': do_clear_kern,
                'density_factor': DENSITY_FACTORS.get(self.get_val(self.slider_density, 3), 1.00),
                'base_sb_val': self.get_val(self.spin_base_sb, 45),
                'inc_thai': self.is_checked(self.chk_sc_thai)
            }
            target_items = self.collect_target_items(raw_glyphs)

            results = []
            for m in masters:
                if self.cancel_requested:
                    break
                if m != master and not self.switch_master(m):
                    continue
                results.append((m,) + self.process_master(m, target_items, settings))
            # กลับไป master เดิมของผู้ใช้
            if self.get_master_layer_name() != master:
                self.switch_master(master)
            if do_kerning:
                self.warn_if_kern_feature_exists()

            self.update_fontlab_viewport()
            self.set_progress(100, "เสร็จสิ้น" if self.lang == 'th' else "Completed")

            err_total = self.error_total()
            if not err_total and not self.cancel_requested:
                self.lbl_next_step.setText(UI_TEXT[self.lang]['next_step_done'])

            lines_th = ["- Master '{}': ปรับ LSB / RSB {} ตัว, เขียนคู่ Kerning {} คู่".format(*r) for r in results]
            lines_en = ["- Master '{}': LSB / RSB updated {}, kerning pairs written {}".format(*r) for r in results]
            summary_th = "{} จัดช่องไฟ{}\n{}\n{}".format(
                "⚠️" if (err_total or self.cancel_requested) else "🎉",
                " (หยุดกลางทาง)" if self.cancel_requested else "เสร็จสิ้น",
                "\n".join(lines_th),
                "- ❌ พบข้อผิดพลาด {} ครั้ง — ตรวจ log ด้านบน".format(err_total) if err_total
                else "- 👉 ตรวจผลใน Kerning panel / Preview")
            summary_en = "{} Spacing{}\n{}\n{}".format(
                "⚠️" if (err_total or self.cancel_requested) else "🎉",
                " cancelled" if self.cancel_requested else " finished",
                "\n".join(lines_en),
                "- ❌ {} errors — see log above".format(err_total) if err_total
                else "- 👉 Check the result in the Kerning panel / Preview")
            self.report(summary_th if self.lang == 'th' else summary_en)

        except Exception as e:
            import traceback
            self.log("เกิดข้อผิดพลาด: {}".format(e) if self.lang == 'th' else "Error occurred: {}".format(e))
            self.log("<pre>{}</pre>".format(html.escape(traceback.format_exc())))
        finally:
            self.btn_stop.setEnabled(False)

    def collect_target_items(self, raw_glyphs):
        """[(fg_glyph, unicode, suffix, name, group)] ของ glyph ในกลุ่มตัวอักษรที่เลือก"""
        inc = {
            'THAI': self.is_checked(self.chk_sc_thai),
            'LATIN': self.is_checked(self.chk_sc_latin),
            'DIGIT': self.is_checked(self.chk_sc_num),
            'SYMBOL': self.is_checked(self.chk_sc_sym)
        }
        target_items = []
        for item in raw_glyphs:
            u, sfx, g_name = self.get_glyph_unicode_and_suffix(item)
            grp = self.get_script_group(u)
            if not grp or not inc[grp] or not g_name:
                continue
            # ข้ามสระลอยและวรรณยุกต์
            if grp == 'THAI' and u in THAI_FLOATING_MARKS:
                continue
            target_items.append((item, u, sfx, g_name, grp))
        return target_items

    def switch_master(self, name):
        """สลับ master ปัจจุบันของฟอนต์ แล้วตรวจว่าสลับสำเร็จ"""
        try:
            self.fl_pkg.setMaster(name, True)
        except Exception as e:
            self.log_error("setMaster", e, name)
            return False
        current = self.get_master_layer_name()
        if current != name:
            self.log_error("setMaster", RuntimeError("master ยังเป็น '{}'".format(current)), name)
            return False
        return True

    def process_master(self, master, target_items, settings):
        """จัดช่องไฟ / kerning ใน master เดียว (master ต้องเป็น master ปัจจุบันของฟอนต์แล้ว)
        คืน (จำนวน glyph ที่ปรับ LSB/RSB, จำนวนคู่ kerning ที่เขียน)"""
        scale = self.get_upm_scale()
        cap_height = self.get_cap_height()
        thai_height = self.get_thai_height() if settings['inc_thai'] else cap_height
        profile_top = max(cap_height, thai_height)
        base_sb = int(round(settings['base_sb_val'] * scale * settings['density_factor']))

        total_targets = len(target_items)
        self.log("พบตัวอักษรเป้าหมาย: {} ตัว (Master: {}, UPM Scale: {:.2f}, Base SB: {} U, Caps: {:.0f}, ไทย: {:.0f})".format(
            total_targets, master, scale, base_sb, cap_height, thai_height
        ))

        profiles = []
        metrics_updated_count = 0
        fallback_names = []

        for idx, (item, u, sfx, g_name, grp) in enumerate(target_items):
            if self.cancel_requested:
                break

            if idx % 10 == 0:
                pct = int((idx / float(max(1, total_targets))) * 50)
                self.set_progress(pct, "[{}] วิเคราะห์ช่องไฟ {}/{}".format(master, idx, total_targets))

            fg_glyph, fl_glyph, _, fl_layer = self.get_active_layers(item, need_fl_layer=True)
            x_min, y_min, w, h = self.get_layer_bbox(fl_layer)

            if w <= 0:
                continue

            bbox = (x_min, y_min, w, h)
            ref_height = thai_height if grp == 'THAI' else cap_height
            prof = None
            path = self.get_outline_path(fl_layer, bbox)
            if path is not None:
                prof = self.measure_profile(path, bbox, profile_top)
                l_bands, r_bands = self.bands_from_profile(prof, bbox, ref_height)
            else:
                # อ่าน outline ไม่ครบ (เช่นมี component) — ใช้ตารางค่าเดิม และไม่นำไปคำนวณ kerning
                fallback_names.append(g_name)
                l_bands, r_bands = self.get_structural_band_profile(u, y_min, h, cap_height)
            self.debug_log("{}: L={} R={}".format(g_name, [round(v, 2) for v in l_bands], [round(v, 2) for v in r_bands]))

            try:
                lsb = x_min
                rsb = float(_get(fl_layer, 'advanceWidth')) - (x_min + w)
            except Exception as e:
                self.log_error("advanceWidth", e, g_name)
                continue

            if settings['do_metrics']:
                # โพรงลึกเฉลี่ย (3 ระนาบ) มาก -> ระยะขอบน้อยลง
                avg_l = sum(l_bands) / 3.0
                avg_r = sum(r_bands) / 3.0
                adj_l = int(round(base_sb * max(0.0, 1.0 - SPACING_DEPTH_WEIGHT * avg_l)))
                adj_r = int(round(base_sb * max(0.0, 1.0 - SPACING_DEPTH_WEIGHT * avg_r)))
                if self.set_glyph_sidebearings(fl_glyph, fl_layer, adj_l, adj_r, bbox):
                    metrics_updated_count += 1
                    lsb, rsb = adj_l, adj_r
                    self.notify_glyph_updated(fl_glyph)

            if prof is not None:
                profiles.append({
                    'name': g_name,
                    'group': grp,
                    'x_min': x_min,
                    'x_max': x_min + w,
                    'lsb': lsb,
                    'rsb': rsb,
                    'prof': prof
                })

        if fallback_names:
            self.log("ℹ️ อ่าน outline ไม่ครบ {} ตัว (ใช้ค่าประมาณ และไม่คำนวณ kerning): {}".format(
                len(fallback_names), ", ".join(fallback_names[:15]) + (" ..." if len(fallback_names) > 15 else ""))
                if self.lang == 'th' else "ℹ️ Outline not fully readable for {} glyphs (estimated, no kerning): {}".format(
                len(fallback_names), ", ".join(fallback_names[:15]) + (" ..." if len(fallback_names) > 15 else "")))

        kern_pairs_count = 0
        if settings['do_clear_kern'] and not self.cancel_requested:
            self.clear_scope_kerning(set(item[3] for item in target_items))
        if settings['do_kerning'] and not self.cancel_requested:
            pairs = self.generate_optical_kerning_pairs(
                profiles, settings['density_factor'], base_sb,
                "[{}] คำนวณคู่ Kerning".format(master) if self.lang == 'th' else "[{}] Calculating Kerning".format(master)
            )
            if not self.cancel_requested:
                kern_pairs_count = self.write_kerning_pairs(pairs)
        return metrics_updated_count, kern_pairs_count


# Launch Standalone Panel — ปิดหน้าต่างเดิมก่อน (ตัวแปร global ถูกรีเซ็ตทุกครั้งที่รันสคริปต์ จึงค้นจาก objectName)
for _w in QtGui.QApplication.topLevelWidgets():
    try:
        if _get(_w, 'objectName') == WINDOW_OBJECT_NAME:
            _w.close()
            _w.deleteLater()
    except Exception:
        pass

_f0nt_autokern_instance = F0NTAutokernPanel()
_f0nt_autokern_instance.setObjectName(WINDOW_OBJECT_NAME)
_f0nt_autokern_instance.show()
_f0nt_autokern_instance.raise_()
_f0nt_autokern_instance.activateWindow()

