1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>TTS Playground · Adom</title>
  <link rel="icon" type="image/svg+xml" href="favicon.svg">
  <style>
    @import url("https://adom.inc/fonts/fonts.css");

    :root {
      --bg: #0d1117;
      --surface: #161b22;
      --surface2: #1c2129;
      --elevated: #1c2128;
      --border: #30363d;
      --border-muted: #21262d;
      --text: #e6edf3;
      --text-dim: #8b949e;
      --text2: #8b949e;       /* canonical alias of --text-dim */
      --text3: #484f58;       /* tertiary / separator */
      --accent: #00b8b0;
      --green: #3fb950;
      --red: #f85149;
      --yellow: #d29922;
      --blue: #58a6ff;
    }

    * { box-sizing: border-box; }

    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      background: var(--bg);
      color: var(--text);
      font-family: "Satoshi", "Familjen Grotesk", sans-serif;
      font-size: 14px;
      line-height: 1.5;
      -webkit-font-smoothing: antialiased;
    }

    h1, h2, h3, .headline {
      font-family: "Familjen Grotesk", "Satoshi", sans-serif;
      font-weight: 600;
      letter-spacing: -0.01em;
      margin: 0;
    }

    code, .mono { font-family: "JetBrains Mono", ui-monospace, monospace; }

    .app {
      display: grid;
      grid-template-rows: auto 1fr;
      height: 100vh;
      min-height: 0;
    }

    /* Canonical Adom app-header — see gallia/skills/adom-app-header. */
    header {
      height: 44px;
      padding: 0 16px;
      display: flex;
      align-items: center;
      gap: 12px;
      border-bottom: 1px solid var(--border-muted);
      background: var(--surface);
      position: relative;
      font-family: 'Familjen Grotesk', sans-serif;
      flex-shrink: 0;
    }
    header .brand {
      display: flex; align-items: center; gap: 8px;
      color: var(--accent);
      font-size: 13px; font-weight: 600;
      letter-spacing: 0.01em;
      cursor: default;
      flex-shrink: 0;
      outline: none;
    }
    header .brand:hover .app-name { text-decoration: underline; text-decoration-color: var(--accent); text-underline-offset: 3px; }
    header .brand svg.logo { width: 16px; height: 16px; flex-shrink: 0; color: var(--accent); }
    header .brand svg.logo rect { fill: currentColor; }
    header .brand .app-name { color: var(--accent); }
    header .brand .app-subtitle { color: var(--text2); font-weight: 500; }
    header .brand .sep { color: var(--text3); font-weight: 400; }
    header .vsep { width: 1px; height: 18px; background: var(--border); flex-shrink: 0; }
    header .subject {
      display: flex; align-items: center; gap: 8px;
      min-width: 0; flex: 1 1 auto;
    }
    header .subject-name {
      color: var(--text);
      font-family: 'Familjen Grotesk', sans-serif;
      font-size: 14px; font-weight: 600;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
      min-width: 0;
    }
    header .subject-meta {
      display: flex; align-items: center; gap: 6px;
      color: var(--text2);
      font-family: 'JetBrains Mono', monospace;
      font-size: 11px;
      white-space: nowrap;
      flex-shrink: 0;
    }
    header .subject-meta .sep { color: var(--text3); }
    @media (max-width: 720px) {
      header .subject-meta { display: none; }
    }
    /* Service-status pill in the subject zone — reuses the canonical state-pill shape. */
    header .pill {
      display: inline-flex; align-items: center; gap: 6px;
      padding: 2px 8px; border-radius: 10px;
      background: var(--elevated); border: 1px solid var(--border);
      font-family: 'Familjen Grotesk', sans-serif;
      font-size: 10px; font-weight: 500; letter-spacing: 0.3px;
      color: var(--text2);
      flex-shrink: 0;
    }
    header .pill .dot {
      width: 6px; height: 6px; border-radius: 50%;
      background: var(--text3);
    }
    header .pill.ok .dot { background: var(--green); }
    header .pill.ok { color: var(--green); border-color: var(--green); }
    header .pill.err .dot { background: var(--red); }
    header .pill.err { color: var(--red); border-color: var(--red); }

    /* Interactive hover-popover */
    header .hover-popover {
      position: absolute; top: calc(100% + 6px); left: 16px;
      background: var(--elevated); border: 1px solid var(--border);
      border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.5);
      padding: 12px 14px; min-width: 300px; max-width: 420px;
      font-family: 'Satoshi', sans-serif; font-size: 12px; color: var(--text);
      z-index: 99999; opacity: 0; transform: translateY(-2px);
      pointer-events: none;
      transition: opacity 120ms ease, transform 120ms ease;
    }
    header .hover-popover.show { opacity: 1; transform: none; pointer-events: auto; }
    header .hover-popover .popover-title { font-family: 'Familjen Grotesk', sans-serif; font-size: 14px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
    header .hover-popover .popover-row { display: flex; gap: 12px; padding: 3px 0; align-items: baseline; }
    header .hover-popover .popover-row .k { color: var(--text3); font-family: 'JetBrains Mono', monospace; font-size: 10px; text-transform: lowercase; width: 64px; flex-shrink: 0; }
    header .hover-popover .popover-row .v { color: var(--text); font-family: 'Satoshi', sans-serif; font-size: 12px; flex: 1; word-break: break-word; }
    header .hover-popover .popover-actions { margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-muted); display: flex; gap: 12px; }
    header .hover-popover .popover-link { color: var(--accent); text-decoration: none; font-family: 'Familjen Grotesk', sans-serif; font-size: 12px; font-weight: 600; }
    header .hover-popover .popover-link:hover { text-decoration: underline; }

    /* ───── Body ───── */
    main {
      display: grid;
      grid-template-columns: minmax(0, 1fr) minmax(260px, 340px);
      grid-template-rows: auto minmax(0, 1fr);
      min-height: 0;
      padding: 16px;
      gap: 16px;
      overflow: hidden;
    }
    main > .compose { grid-column: 1 / 2; grid-row: 1 / 2; }
    main > .history { grid-column: 1 / 2; grid-row: 2 / 3; }
    main > .pron    { grid-column: 2 / 3; grid-row: 1 / 3; }
    @media (max-width: 980px) {
      main {
        grid-template-columns: minmax(0, 1fr);
        grid-template-rows: auto minmax(180px, 1fr) auto;
        overflow-y: auto;
      }
      main > .compose { grid-column: 1; grid-row: 1; }
      main > .history { grid-column: 1; grid-row: 2; }
      main > .pron    { grid-column: 1; grid-row: 3; }
      .pron-list { max-height: 180px; }
    }

    .compose {
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 12px;
      padding: 16px;
      display: grid;
      gap: 12px;
    }

    textarea {
      width: 100%;
      min-height: 88px;
      padding: 12px;
      background: var(--bg);
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 8px;
      font-family: inherit;
      font-size: 14px;
      resize: vertical;
    }
    textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: transparent; }

    .controls {
      display: grid;
      grid-template-columns: 1fr 1fr auto;
      gap: 12px;
      align-items: end;
    }
    .field { display: grid; gap: 4px; }
    .field label {
      font-size: 11px;
      color: var(--text-dim);
      text-transform: none;
      letter-spacing: 0;
    }

    select, input[type=range] {
      width: 100%;
      padding: 8px 12px;
      background: var(--bg);
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 8px;
      font-family: inherit;
      font-size: 14px;
    }
    select:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: transparent; }
    input[type=range] { padding: 0; accent-color: var(--accent); }

    .rate-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center; }
    .rate-value { font-family: "JetBrains Mono", monospace; font-size: 12px; color: var(--text-dim); min-width: 42px; text-align: right; }

    button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      padding: 10px 18px;
      background: var(--accent);
      color: #00221f;
      border: none;
      border-radius: 8px;
      font-family: inherit;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: filter 120ms, transform 60ms, background 120ms;
    }
    button:hover:not(:disabled) { filter: brightness(1.08); }
    button:active:not(:disabled) { transform: translateY(1px); }
    button:disabled { opacity: 0.5; cursor: not-allowed; }

    button.ghost {
      background: var(--surface2);
      color: var(--text);
      border: 1px solid var(--border);
      padding: 6px 10px;
      font-weight: 500;
    }
    button.ghost:hover:not(:disabled) { background: var(--border); filter: none; }

    button.icon {
      width: 32px; height: 32px;
      padding: 0;
      background: var(--surface2);
      color: var(--text);
      border: 1px solid var(--border);
    }
    button.icon:hover:not(:disabled) { background: var(--border); filter: none; }
    button.icon svg { width: 16px; height: 16px; fill: currentColor; }

    button.danger.icon:hover:not(:disabled) {
      background: rgba(248, 81, 73, 0.15);
      color: var(--red);
      border-color: var(--red);
    }

    /* ───── History ───── */
    .history {
      display: grid;
      grid-template-rows: auto minmax(0, 1fr);
      gap: 8px;
      min-height: 0;
    }
    .history-head {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0 4px;
    }
    .history-head h2 { font-size: 13px; color: var(--text-dim); font-weight: 500; }
    .history-head .count {
      font-family: "JetBrains Mono", monospace;
      font-size: 11px;
      color: var(--text-dim);
    }
    .history-head .spacer { flex: 1; }

    .history-list {
      overflow-y: auto;
      display: grid;
      gap: 8px;
      padding-right: 4px;
      min-height: 0;
    }
    .history-list::-webkit-scrollbar { width: 8px; }
    .history-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }

    .clip {
      display: grid;
      grid-template-columns: auto 1fr auto;
      gap: 12px;
      align-items: center;
      padding: 12px;
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 8px;
      transition: border-color 120ms;
    }
    .clip:hover { border-color: var(--border); }
    .clip.playing { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }

    .clip .play {
      width: 40px; height: 40px;
      border-radius: 50%;
      background: var(--accent);
      color: #00221f;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }
    .clip .play svg { width: 18px; height: 18px; fill: currentColor; }
    .clip.playing .play { background: var(--surface2); color: var(--accent); border: 1px solid var(--accent); }

    .clip .meta {
      display: grid;
      gap: 4px;
      min-width: 0;
    }
    .clip .text {
      color: var(--text);
      font-size: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .clip .sub {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
      align-items: center;
      font-size: 11px;
      color: var(--text-dim);
    }
    .clip .badge {
      padding: 2px 6px;
      border-radius: 4px;
      background: var(--surface2);
      border: 1px solid var(--border);
      font-family: "JetBrains Mono", monospace;
      font-size: 10px;
    }
    .clip .badge.source-ui { color: var(--blue); border-color: var(--blue); }
    .clip .badge.source-cli { color: var(--yellow); border-color: var(--yellow); }
    .clip .badge.source-external { color: var(--text-dim); }

    .clip .actions {
      display: flex;
      gap: 6px;
      flex-shrink: 0;
    }

    .empty {
      padding: 48px 16px;
      text-align: center;
      color: var(--text-dim);
      border: 1px dashed var(--border);
      border-radius: 12px;
    }
    .empty h3 {
      font-size: 15px;
      font-weight: 500;
      color: var(--text);
      margin-bottom: 4px;
    }
    .empty p { font-size: 13px; }

    /* ───── Toast ───── */
    .toast {
      position: fixed;
      bottom: 16px;
      right: 16px;
      padding: 10px 14px;
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 8px;
      color: var(--text);
      font-size: 13px;
      box-shadow: 0 8px 24px rgba(0,0,0,0.4);
      max-width: 360px;
      opacity: 0;
      transform: translateY(10px);
      transition: opacity 200ms, transform 200ms;
      pointer-events: none;
      z-index: 100;
    }
    .toast.show { opacity: 1; transform: translateY(0); }
    .toast.err { border-color: var(--red); color: var(--red); }
    .toast.ok { border-color: var(--green); }

    /* ───── Tooltip (§1d — one body-appended fixed div, cursor-anchored, z:99999) ───── */
    #global-tooltip {
      position: fixed;
      top: 0; left: 0;
      z-index: 99999;
      pointer-events: none;
      padding: 7px 10px;
      background: #000;
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 6px;
      font-family: "Satoshi", sans-serif;
      font-size: 12px;
      font-weight: 400;
      line-height: 1.45;
      text-transform: none;
      letter-spacing: 0;
      white-space: pre-line;
      max-width: min(320px, calc(100vw - 40px));
      width: max-content;
      box-shadow: 0 8px 24px rgba(0,0,0,0.5);
      transform: translate(var(--tip-x, 0), var(--tip-y, 0));
      opacity: 0;
      display: none;
      transition: opacity 180ms ease;
    }
    #global-tooltip.visible { display: block; }
    #global-tooltip.shown { opacity: 1; }

    @media (max-width: 640px) {
      .controls { grid-template-columns: 1fr; }
      .clip { grid-template-columns: auto 1fr; }
      .clip .actions { grid-column: 1 / -1; justify-content: flex-end; }
    }

    /* ───── Pronunciation hint banner above compose ───── */
    .pron-hint {
      display: none;
      padding: 8px 12px;
      background: rgba(0, 184, 176, 0.08);
      border: 1px solid rgba(0, 184, 176, 0.35);
      border-radius: 8px;
      color: var(--text);
      font-size: 12.5px;
      line-height: 1.5;
    }
    .pron-hint.show { display: block; }
    .pron-hint strong { color: var(--accent); font-weight: 600; }
    .pron-hint .mono { color: var(--text-dim); }

    /* ───── Pronunciation panel ───── */
    .pron {
      display: grid;
      grid-template-rows: auto auto auto minmax(0, 1fr);
      gap: 12px;
      min-height: 0;
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: 12px;
      padding: 16px;
    }
    .pron-head {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .pron-head h2 { font-size: 14px; font-weight: 600; }
    .pron-head .count {
      font-family: "JetBrains Mono", monospace;
      font-size: 11px;
      color: var(--text-dim);
      margin-left: 4px;
    }
    .pron-head .spacer { flex: 1; }
    .pron-explain {
      font-size: 12px;
      color: var(--text-dim);
      line-height: 1.5;
    }
    .pron-add {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      padding: 12px;
      background: var(--surface2);
      border: 1px solid var(--border);
      border-radius: 8px;
    }
    .pron-add .full { grid-column: 1 / -1; }
    .pron-add input, .pron-add textarea {
      width: 100%;
      padding: 8px 10px;
      background: var(--bg);
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 6px;
      font-family: inherit;
      font-size: 13px;
    }
    .pron-add input:focus, .pron-add textarea:focus {
      outline: 2px solid var(--accent);
      outline-offset: -1px;
      border-color: transparent;
    }
    .pron-add label {
      font-size: 11px;
      color: var(--text-dim);
      margin-bottom: 3px;
      display: block;
    }
    .pron-add textarea { min-height: 50px; resize: vertical; font-size: 12.5px; }
    .pron-actions {
      display: flex;
      gap: 6px;
      grid-column: 1 / -1;
      justify-content: flex-end;
    }
    .pron-actions button { padding: 6px 12px; font-size: 12.5px; }

    .pron-search {
      padding: 8px 10px;
      background: var(--bg);
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 6px;
      font-family: inherit;
      font-size: 12.5px;
    }
    .pron-search:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: transparent; }

    .pron-list {
      overflow-y: auto;
      display: grid;
      gap: 4px;
      padding-right: 2px;
      min-height: 120px;
    }
    .pron-list::-webkit-scrollbar { width: 6px; }
    .pron-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
    .pron-row {
      display: grid;
      grid-template-columns: 1fr auto 1fr;
      align-items: center;
      gap: 6px;
      padding: 6px 10px;
      background: var(--surface2);
      border: 1px solid var(--border);
      border-radius: 6px;
      font-size: 12px;
    }
    .pron-row .from { color: var(--text); font-weight: 500; font-family: "JetBrains Mono", monospace; font-size: 11.5px; }
    .pron-row .arrow { color: var(--text-dim); font-size: 11px; }
    .pron-row .to { color: var(--accent); font-family: "JetBrains Mono", monospace; font-size: 11.5px; }
  </style>
</head>
<body>
  <div class="app">
    <!-- Canonical Adom app-header — see gallia/skills/adom-app-header/SKILL.md. -->
    <header>
      <div class="brand" data-tooltip-target="app-info" tabindex="0">
        <svg class="logo" viewBox="0 0 64 64" aria-hidden="true">
          <rect x="8"  y="28" width="6" height="8"  rx="2"/>
          <rect x="18" y="22" width="6" height="20" rx="2"/>
          <rect x="28" y="14" width="6" height="36" rx="2"/>
          <rect x="38" y="22" width="6" height="20" rx="2"/>
          <rect x="48" y="28" width="6" height="8"  rx="2"/>
        </svg>
        <span class="app-name">adom-tts</span>
        <span class="sep">·</span>
        <span class="app-subtitle">TTS playground</span>
      </div>

      <div class="vsep" aria-hidden="true"></div>

      <div class="subject">
        <span class="subject-name">Speech synthesis &amp; pronunciations</span>
        <span id="service-pill" class="pill" data-tooltip="Status of the shared service-tts container. Green = reachable. Red = unreachable (your clips will fail to synthesize).">
          <span class="dot"></span>
          <span id="service-pill-text">connecting…</span>
        </span>
        <span class="subject-meta" id="topMeta"></span>
      </div>

      <div class="hover-popover" id="app-info" role="dialog" aria-label="App information">
        <div class="popover-title">adom-tts</div>
        <div class="popover-row"><span class="k">about</span>
          <span class="v">Shared edge-tts wrapper with pronunciation overrides + source-hash cache. Every Adom tool that speaks routes through here so an Adom-term fix (KiCad, adom-tsci, etc.) applies everywhere.</span></div>
        <div class="popover-row"><span class="k">version</span><span class="v" id="popVersion">v0.1.0</span></div>
        <div class="popover-row"><span class="k">engine</span><span class="v">service-tts · edge-tts (Andrew Multilingual)</span></div>
        <div class="popover-row"><span class="k">author</span><span class="v">Adom Inc · adom.inc</span></div>
        <div class="popover-actions">
          <a class="popover-link" href="https://wiki-ufypy5dpx93o.adom.cloud/apps/adom-tts" target="_blank" rel="noopener">Open wiki ↗</a>
          <a class="popover-link" href="https://github.com/adom-inc/adom-tts" target="_blank" rel="noopener">GitHub ↗</a>
        </div>
      </div>
    </header>

    <script>
    // Interactive hover-popover. SHOW_DELAY = 500ms (human-ui-patterns §1b).
    (function attachHeaderPopovers(){
      const SHOW_DELAY = 500, HIDE_GRACE = 220;
      const wire = () => {
        document.querySelectorAll('header [data-tooltip-target]').forEach(trigger => {
          if (trigger.__popoverWired) return;
          trigger.__popoverWired = true;
          const target = document.getElementById(trigger.dataset.tooltipTarget);
          if (!target) return;
          let showTimer = null, hideTimer = null;
          const show = () => {
            clearTimeout(hideTimer);
            if (target.classList.contains('show')) return;
            clearTimeout(showTimer);
            showTimer = setTimeout(() => target.classList.add('show'), SHOW_DELAY);
          };
          const queueHide = () => {
            clearTimeout(showTimer);
            clearTimeout(hideTimer);
            hideTimer = setTimeout(() => target.classList.remove('show'), HIDE_GRACE);
          };
          trigger.addEventListener('mouseenter', show);
          trigger.addEventListener('mouseleave', queueHide);
          trigger.addEventListener('focus', show);
          trigger.addEventListener('blur', queueHide);
          target.addEventListener('mouseenter', show);
          target.addEventListener('mouseleave', queueHide);
          trigger.addEventListener('click', e => {
            clearTimeout(showTimer);
            if (target.classList.contains('show')) target.classList.remove('show');
            else target.classList.add('show');
            e.stopPropagation();
          });
        });
      };
      if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wire);
      else wire();
    })();

    // Mirror clip count + pronunciation count into the canonical subject-meta.
    function updateAdomTtsMeta() {
      const meta = document.getElementById('topMeta');
      if (!meta) return;
      const clips = document.querySelectorAll('.clip').length;
      const prons = (window.pronEntries || []).length;
      const parts = [];
      if (prons) parts.push(`${prons} pronunciations`);
      if (clips) parts.push(`${clips} clip${clips === 1 ? '' : 's'}`);
      meta.innerHTML = parts.length
        ? '<span class="sep">·</span>' + parts.map(p => `<span>${p}</span>`).join('<span class="sep">·</span>')
        : '';
    }
    window.addEventListener('load', updateAdomTtsMeta);
    setInterval(updateAdomTtsMeta, 2000);
    </script>

    <main>
      <section class="compose">
        <div id="pron-hint" class="pron-hint"></div>
        <textarea id="text"
                  placeholder="Type what you want to hear — e.g. &quot;hi everyone, this is the adom hydrogen editor and its amazing that it can build so much stuff for me&quot;"></textarea>
        <div class="controls">
          <div class="field">
            <label for="voice">Voice</label>
            <select id="voice" data-tooltip="Which edge-tts voice synthesizes the clip.&#10;&#10;Default is en-US-AndrewNeural — the house voice for every Adom demo. Change only if you want variety."></select>
          </div>
          <div class="field">
            <label for="rate">Rate</label>
            <div class="rate-row">
              <input type="range" id="rate" min="-50" max="50" step="5" value="0"
                     data-tooltip="Speaking rate, percent offset from normal.&#10;&#10;0% is normal. Positive = faster, negative = slower. Adom demos usually stay within ±10%; bigger offsets can make the voice sound unnatural.">
              <span id="rate-value" class="rate-value">+0%</span>
            </div>
          </div>
          <button id="speak"
                  data-tooltip="Synthesize the text above using the selected voice and rate.&#10;&#10;The clip is rendered by service-tts (with pronunciation overrides for Adom terms), saved to ~/.adom/tts/history/, and appears in the list below.&#10;&#10;Shortcut: press Enter in the text box. Shift+Enter inserts a newline.">
            <span id="speak-label">Speak</span>
          </button>
        </div>
      </section>

      <section class="pron" id="pron">
        <div class="pron-head">
          <h2>Pronunciations</h2>
          <span class="count"><span id="pron-count">–</span></span>
          <div class="spacer"></div>
          <button class="ghost" id="pron-preview"
                  data-tooltip-pos="bottom"
                  data-tooltip="Synthesize &quot;written&quot; and &quot;narration&quot; back-to-back so you can hear whether the phonetic spelling actually helps.&#10;&#10;Both clips land in History — the raw one is tagged source=external, the applied one source=ui, so you can compare.">
            Preview
          </button>
        </div>
        <div class="pron-explain">
          The shared service-tts container rewrites text before synthesis using a global pronunciation table. Adding an entry here updates the gallia tts-pronunciation skill — every Adom tool that uses TTS benefits.
        </div>
        <div class="pron-add">
          <div>
            <label for="pron-written">Written</label>
            <input id="pron-written" placeholder="adom-tsci"
                   data-tooltip-pos="bottom"
                   data-tooltip="The term as it appears in code, UIs, captions, or chat.&#10;&#10;Matched case-insensitively by the service. Keep this the natural spelling — only the &quot;Narration&quot; field gets phoneticized.">
          </div>
          <div>
            <label for="pron-narration">Narration</label>
            <input id="pron-narration" placeholder="adom t s c i"
                   data-tooltip-pos="bottom"
                   data-tooltip="The phonetic spelling fed to the TTS engine.&#10;&#10;For acronyms, separate each letter with a space (letter-by-letter). For mispronounced words, spell them phonetically (e.g. &quot;KiCad&quot; → &quot;kai cad&quot;).">
          </div>
          <div class="full">
            <label for="pron-reason">Reason (optional)</label>
            <textarea id="pron-reason" placeholder="TTS reads 'tsci' as 'sci' — letter-by-letter forces the intended four-letter reading."
                      data-tooltip-pos="bottom"
                      data-tooltip="Why this entry exists — documented in the gallia skill file for future readers.&#10;&#10;Skip this and a default note is filled in (&quot;Added via TTS Playground&quot;)."></textarea>
          </div>
          <div class="pron-actions">
            <button class="ghost" id="pron-clear"
                    data-tooltip-pos="bottom"
                    data-tooltip="Empty the Written / Narration / Reason fields.&#10;&#10;Does NOT affect the table below or any entry that's already been added.">Clear</button>
            <button id="pron-propose"
                    data-tooltip-pos="bottom"
                    data-tooltip="Add this pronunciation to the gallia tts-pronunciation skill.&#10;&#10;Writes directly to gallia/skills/tts-pronunciation/pronunciations.json on your container — you still need to commit + push so the service-tts container picks it up on next redeploy (watchdog auto-pulls every 2 min).&#10;&#10;If gallia isn't checked out locally, the entry is queued at ~/.adom/tts/proposed-pronunciations.json and the JSON snippet is shown for manual paste.">Propose</button>
          </div>
        </div>
        <input type="search" id="pron-search" class="pron-search" placeholder="Search pronunciations…"
               data-tooltip-pos="bottom"
               data-tooltip="Filter the table below by either column.&#10;&#10;Match is case-insensitive and substring-based: &quot;pcb&quot; finds PCB, JLCPCB, and anything with that letter run.">
        <div class="pron-list" id="pron-list"></div>
      </section>

      <section class="history">
        <div class="history-head">
          <h2>History</h2>
          <span class="count"><span id="history-count">0</span> clips</span>
          <div class="spacer"></div>
          <button class="ghost" id="refresh"
                  data-tooltip="Re-scan ~/.adom/tts/history/ and redraw the list.&#10;&#10;The list auto-refreshes every 2 seconds anyway; use this if you just dropped a clip in from the CLI and don't want to wait.">
            Refresh
          </button>
        </div>
        <div class="history-list" id="history-list">
          <div class="empty">
            <h3>No clips yet</h3>
            <p>Type something above and hit Speak — or run <span class="mono">adom-tts say "hello" --out hi.mp3 --history</span> in a terminal.</p>
          </div>
        </div>
      </section>
    </main>
  </div>

  <div id="toast" class="toast" role="status" aria-live="polite"></div>
  <div id="global-tooltip"></div>

  <audio id="audio-player" preload="none"></audio>

  <script>
    // ───── Global tooltip (§1d — body-appended fixed div, cursor-anchored, 500ms delay) ─────
    (function () {
      const tip = document.getElementById("global-tooltip");
      let cursorX = 0, cursorY = 0;
      let currentTrigger = null;
      let revealTimer = null;
      const suppressedAncestors = [];
      const OFFSET = 14;
      const DELAY = 500;

      document.addEventListener("mousemove", (e) => {
        cursorX = e.clientX;
        cursorY = e.clientY;
        if (currentTrigger && tip.classList.contains("shown")) {
          place(currentTrigger);
        }
      }, true);

      function pickAnchor(triggerRect, tipW, tipH) {
        const vw = window.innerWidth, vh = window.innerHeight;
        const cands = [
          { x: cursorX + OFFSET,           y: cursorY + OFFSET },
          { x: cursorX - tipW - OFFSET,    y: cursorY + OFFSET },
          { x: cursorX + OFFSET,           y: cursorY - tipH - OFFSET },
          { x: cursorX - tipW - OFFSET,    y: cursorY - tipH - OFFSET },
        ];
        function overlapsTrigger(c) {
          return !(c.x + tipW < triggerRect.left || c.x > triggerRect.right
                || c.y + tipH < triggerRect.top  || c.y > triggerRect.bottom);
        }
        function offscreen(c) {
          return (c.x < 4 || c.y < 4 || c.x + tipW > vw - 4 || c.y + tipH > vh - 4);
        }
        function coversCursor(c) {
          // Tip must not sit under the cursor itself.
          return (cursorX >= c.x && cursorX <= c.x + tipW
               && cursorY >= c.y && cursorY <= c.y + tipH);
        }
        let best = cands[0], bestScore = Infinity;
        for (const c of cands) {
          let s = 0;
          if (offscreen(c)) s += 1000;
          if (overlapsTrigger(c)) s += 100;
          if (coversCursor(c)) s += 50;
          if (s < bestScore) { bestScore = s; best = c; }
        }
        // Clamp inside viewport as a last step.
        best.x = Math.max(4, Math.min(best.x, vw - tipW - 4));
        best.y = Math.max(4, Math.min(best.y, vh - tipH - 4));
        return best;
      }

      function place(trigger) {
        const r = trigger.getBoundingClientRect();
        const tipW = tip.offsetWidth, tipH = tip.offsetHeight;
        const { x, y } = pickAnchor(r, tipW, tipH);
        tip.style.setProperty("--tip-x", x + "px");
        tip.style.setProperty("--tip-y", y + "px");
      }

      function show(trigger) {
        tip.textContent = trigger.getAttribute("data-tooltip") || "";
        tip.classList.add("visible");
        place(trigger);
        // reveal after DELAY so mouse fly-bys don't fire anything
        clearTimeout(revealTimer);
        revealTimer = setTimeout(() => {
          if (currentTrigger === trigger) {
            place(trigger);
            requestAnimationFrame(() => tip.classList.add("shown"));
          }
        }, DELAY);
      }

      function hide() {
        clearTimeout(revealTimer);
        tip.classList.remove("shown");
        tip.classList.remove("visible");
        currentTrigger = null;
        while (suppressedAncestors.length) {
          suppressedAncestors.pop().removeAttribute("data-tooltip-suppress");
        }
      }

      document.addEventListener("mouseover", (e) => {
        const t = e.target.closest && e.target.closest("[data-tooltip]:not([data-tooltip-suppress])");
        if (!t) { if (currentTrigger) hide(); return; }
        if (t === currentTrigger) return;
        // §1f — innermost wins, suppress ancestor triggers while active.
        while (suppressedAncestors.length) {
          suppressedAncestors.pop().removeAttribute("data-tooltip-suppress");
        }
        let n = t.parentElement;
        while (n && n !== document.body) {
          if (n.hasAttribute && n.hasAttribute("data-tooltip")) {
            n.setAttribute("data-tooltip-suppress", "");
            suppressedAncestors.push(n);
          }
          n = n.parentElement;
        }
        currentTrigger = t;
        show(t);
      }, true);

      document.addEventListener("mouseout", (e) => {
        if (!currentTrigger) return;
        // hide when we leave the current trigger entirely (relatedTarget not inside it)
        const to = e.relatedTarget;
        if (!to || !currentTrigger.contains(to)) hide();
      }, true);

      // hide on scroll or visibility change (tooltip would dangle)
      window.addEventListener("scroll", hide, true);
      document.addEventListener("visibilitychange", hide);
    })();

    // ───── Console forwarding to server (/console) ─────
    (function () {
      const CAP = 200;
      const buf = [];
      let flushing = false;
      async function flush() {
        if (flushing || !buf.length) return;
        flushing = true;
        const batch = buf.splice(0, buf.length);
        for (const e of batch) {
          try {
            await fetch("console", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(e),
            });
          } catch (_) { /* drop — not fatal */ }
        }
        flushing = false;
      }
      ["log", "warn", "error", "info"].forEach((lvl) => {
        const orig = console[lvl].bind(console);
        console[lvl] = (...args) => {
          orig(...args);
          const msg = args.map((a) => {
            try { return typeof a === "string" ? a : JSON.stringify(a); }
            catch (_) { return String(a); }
          }).join(" ");
          if (buf.length >= CAP) buf.shift();
          buf.push({ level: lvl, msg, t: new Date().toISOString() });
          setTimeout(flush, 0);
        };
      });
      window.addEventListener("error", (e) => console.error("window.onerror:", e.message, e.filename + ":" + e.lineno));
      window.addEventListener("unhandledrejection", (e) => console.error("unhandledrejection:", e.reason));
    })();

    // ───── State & DOM ─────
    const $ = (id) => document.getElementById(id);
    const textEl = $("text");
    const voiceEl = $("voice");
    const rateEl = $("rate");
    const rateValEl = $("rate-value");
    const speakBtn = $("speak");
    const speakLabel = $("speak-label");
    const listEl = $("history-list");
    const countEl = $("history-count");
    const pillEl = $("service-pill");
    const pillTextEl = $("service-pill-text");
    const toastEl = $("toast");
    const audio = $("audio-player");

    let playingId = null;
    audio.addEventListener("ended", () => {
      playingId = null;
      render();
    });

    function toast(msg, kind = "") {
      toastEl.textContent = msg;
      toastEl.className = "toast show" + (kind ? " " + kind : "");
      clearTimeout(toast._t);
      toast._t = setTimeout(() => { toastEl.classList.remove("show"); }, 3500);
    }

    function fmtTime(iso) {
      try {
        const d = new Date(iso);
        const now = new Date();
        const diff = (now - d) / 1000;
        if (diff < 60) return Math.round(diff) + "s ago";
        if (diff < 3600) return Math.round(diff / 60) + "m ago";
        if (diff < 86400) return Math.round(diff / 3600) + "h ago";
        return d.toLocaleString();
      } catch (_) { return iso; }
    }

    function fmtBytes(n) {
      if (n < 1024) return n + " B";
      if (n < 1024 * 1024) return (n / 1024).toFixed(1) + " KB";
      return (n / 1024 / 1024).toFixed(2) + " MB";
    }

    rateEl.addEventListener("input", () => {
      const v = parseInt(rateEl.value, 10);
      rateValEl.textContent = (v >= 0 ? "+" : "") + v + "%";
    });

    // Enter → speak (like Claude's chat box).
    // Shift+Enter → newline. Alt+Enter also inserts a newline for muscle-memory.
    textEl.addEventListener("keydown", (e) => {
      if (e.key !== "Enter" || e.isComposing) return;
      if (e.shiftKey || e.altKey) return;  // let the newline through
      e.preventDefault();
      speak();
    });

    // ───── Load voices ─────
    async function loadVoices() {
      try {
        const r = await fetch("voices");
        const j = await r.json();
        // service-tts returns {short_name, gender, locale?}. Fall back to
        // edge-tts raw keys (ShortName, Gender, Locale) if a different
        // backend ever gets swapped in.
        const all = j.voices || j || [];
        const norm = (v) => ({
          short_name: v.short_name || v.ShortName || "",
          gender: v.gender || v.Gender || "",
          locale: v.locale || v.Locale || (v.short_name || v.ShortName || "").slice(0, 5),
        });
        const voices = all.map(norm).filter((v) => v.locale.startsWith("en-"));
        voices.sort((a, b) => a.short_name.localeCompare(b.short_name));
        voiceEl.innerHTML = "";
        for (const v of voices) {
          const opt = document.createElement("option");
          opt.value = v.short_name;
          const name = v.short_name.replace(/^en-[A-Z]{2}-/, "").replace(/Neural$/, "");
          const gender = v.gender ? " · " + v.gender : "";
          opt.textContent = `${name} (${v.short_name})${gender}`;
          if (v.short_name === "en-US-AndrewNeural") opt.selected = true;
          voiceEl.appendChild(opt);
        }
        if (!voiceEl.value) voiceEl.value = "en-US-AndrewNeural";
        console.log("voices loaded:", voices.length);
      } catch (e) {
        console.error("voice load failed:", e);
        // Fall back to Andrew as the only option.
        voiceEl.innerHTML = '<option value="en-US-AndrewNeural" selected>Andrew (en-US-AndrewNeural)</option>';
      }
    }

    // ───── /state poller ─────
    async function pollState() {
      try {
        const r = await fetch("state");
        const j = await r.json();
        pillEl.className = "pill ok";
        pillTextEl.textContent = "service-tts ok";
      } catch (_) {
        pillEl.className = "pill err";
        pillTextEl.textContent = "service-tts unreachable";
      }
    }

    // ───── /history list ─────
    let lastListFingerprint = "";
    let clips = [];

    async function refreshHistory() {
      try {
        const r = await fetch("history");
        const j = await r.json();
        if (!j.ok) return;
        const fp = (j.clips || []).map((c) => c.id + "/" + c.size_bytes).join("|");
        if (fp === lastListFingerprint) return;
        lastListFingerprint = fp;
        clips = j.clips || [];
        render();
      } catch (e) { /* transient */ }
    }

    function render() {
      countEl.textContent = clips.length;
      if (!clips.length) {
        listEl.innerHTML = `
          <div class="empty">
            <h3>No clips yet</h3>
            <p>Type something above and hit Speak — or run <span class="mono">adom-tts say "hello" --out hi.mp3 --history</span> in a terminal.</p>
          </div>`;
        return;
      }
      listEl.innerHTML = "";
      for (const c of clips) {
        const row = document.createElement("div");
        row.className = "clip" + (c.id === playingId ? " playing" : "");
        const playing = c.id === playingId;
        row.innerHTML = `
          <button class="play" data-play="${c.id}"
                  data-tooltip="${playing ? "Pause playback of this clip." : "Play this clip in the browser.\nAudio is streamed from ~/.adom/tts/history/" + c.id + ".mp3."}">
            <svg viewBox="0 0 24 24">
              ${playing
                ? '<rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/>'
                : '<path d="M8 5v14l11-7z"/>'}
            </svg>
          </button>
          <div class="meta">
            <div class="text">${escapeHtml(c.text)}</div>
            <div class="sub">
              <span class="badge">${escapeHtml(shortVoice(c.voice))}</span>
              <span class="badge">${escapeHtml(c.rate)}</span>
              <span class="badge source-${escapeHtml(c.source)}">${escapeHtml(c.source)}</span>
              <span>${fmtTime(c.created_at)}</span>
              <span>·</span>
              <span>${fmtBytes(c.size_bytes)}</span>
            </div>
          </div>
          <div class="actions">
            <a class="ghost" style="text-decoration:none"
               href="history/${encodeURIComponent(c.id)}.mp3"
               download="${encodeURIComponent(c.id)}.mp3"
               data-tooltip="Save the .mp3 to your computer's Downloads folder.&#10;&#10;The file is also on disk at ~/.adom/tts/history/${c.id}.mp3 — that's the same path video-post and other tools read from.">
              <button class="icon" data-tooltip-pos="bottom" data-tooltip="Download the .mp3 to your computer.&#10;&#10;File is also on disk at ~/.adom/tts/history/${c.id}.mp3 — that's where other Adom tools pick it up from.">
                <svg viewBox="0 0 24 24"><path d="M12 3v10.6l3.3-3.3 1.4 1.4L12 16.4 7.3 11.7l1.4-1.4L12 13.6V3h0zM5 19h14v2H5z"/></svg>
              </button>
            </a>
            <button class="icon" data-copy="${c.id}"
                    data-tooltip="Copy the playground URL for this clip to your clipboard.&#10;&#10;Paste into a chat or browser tab to play it directly — the URL serves the audio with audio/mpeg content-type, so any player can stream it.">
              <svg viewBox="0 0 24 24"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>
            </button>
            <button class="icon danger" data-delete="${c.id}"
                    data-tooltip="Delete this clip permanently.&#10;&#10;Removes both the .mp3 and the .json sidecar from ~/.adom/tts/history/. No undo. Any tool that had already read the file keeps its copy — only new reads fail.">
              <svg viewBox="0 0 24 24"><path d="M9 3v1H4v2h1l1 14c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2l1-14h1V4h-5V3H9zm2 5h2v10h-2V8zm-4 0h2v10H7V8zm8 0h2v10h-2V8z"/></svg>
            </button>
          </div>
        `;
        listEl.appendChild(row);
      }

      listEl.querySelectorAll("[data-play]").forEach((b) => {
        b.addEventListener("click", () => play(b.dataset.play));
      });
      listEl.querySelectorAll("[data-copy]").forEach((b) => {
        b.addEventListener("click", () => copyUrl(b.dataset.copy));
      });
      listEl.querySelectorAll("[data-delete]").forEach((b) => {
        b.addEventListener("click", () => delClip(b.dataset.delete));
      });
    }

    function shortVoice(v) {
      return (v || "").replace(/^en-[A-Z]{2}-/, "").replace(/Neural$/, "") || v;
    }

    function escapeHtml(s) {
      return String(s || "")
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;");
    }

    function play(id) {
      if (playingId === id) {
        audio.pause();
        playingId = null;
        render();
        return;
      }
      audio.src = "history/" + encodeURIComponent(id) + ".mp3";
      audio.play().catch((e) => {
        console.error("play failed:", e);
        toast("couldn't play clip: " + e.message, "err");
      });
      playingId = id;
      render();
    }

    async function copyUrl(id) {
      const url = new URL("history/" + encodeURIComponent(id) + ".mp3", location.href).toString();
      try {
        await navigator.clipboard.writeText(url);
        toast("copied " + url, "ok");
      } catch (e) {
        toast("copy failed — " + url, "err");
      }
    }

    async function delClip(id) {
      if (!confirm("Delete this clip?")) return;
      try {
        const r = await fetch("history/" + encodeURIComponent(id), { method: "DELETE" });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error || "delete failed");
        if (playingId === id) { audio.pause(); playingId = null; }
        toast("clip deleted", "ok");
        await refreshHistory();
      } catch (e) {
        toast("delete failed: " + e.message, "err");
      }
    }

    // ───── Speak ─────
    async function speak() {
      const text = textEl.value.trim();
      if (!text) { toast("type something first", "err"); textEl.focus(); return; }
      speakBtn.disabled = true;
      speakLabel.textContent = "Synthesizing…";
      try {
        const r = await fetch("synth", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text,
            voice: voiceEl.value || "en-US-AndrewNeural",
            rate: (rateEl.value >= 0 ? "+" : "") + rateEl.value + "%",
          }),
        });
        const j = await r.json();
        if (!r.ok || !j.ok) throw new Error(j.error || ("HTTP " + r.status));
        toast("clip saved", "ok");
        await refreshHistory();
        if (j.clip && j.clip.id) play(j.clip.id);
      } catch (e) {
        console.error("synth failed:", e);
        toast("synth failed: " + e.message, "err");
      } finally {
        speakBtn.disabled = false;
        speakLabel.textContent = "Speak";
      }
    }

    speakBtn.addEventListener("click", speak);
    $("refresh").addEventListener("click", refreshHistory);

    // ───── Pronunciations ─────
    let pronEntries = [];
    const pronHint = $("pron-hint");
    const pronListEl = $("pron-list");
    const pronCountEl = $("pron-count");
    const pronSearchEl = $("pron-search");
    const pronWrittenEl = $("pron-written");
    const pronNarrationEl = $("pron-narration");
    const pronReasonEl = $("pron-reason");

    async function loadPronunciations() {
      try {
        const r = await fetch("pronunciations");
        const j = await r.json();
        pronEntries = j.overrides || j.entries || [];
        pronCountEl.textContent = pronEntries.length;
        renderPronList();
        updatePronHint();
      } catch (e) { console.error("pronunciations load failed:", e); }
    }

    function renderPronList() {
      const q = (pronSearchEl.value || "").toLowerCase();
      const shown = pronEntries.filter((e) =>
        !q || (e.from || e.written || "").toLowerCase().includes(q)
           || (e.to || e.narration || "").toLowerCase().includes(q));
      pronListEl.innerHTML = "";
      if (!shown.length) {
        pronListEl.innerHTML = '<div style="color:var(--text-dim);font-size:12px;padding:8px;text-align:center;">no matches</div>';
        return;
      }
      for (const e of shown) {
        const from = e.from || e.written || "";
        const to = e.to || e.narration || "";
        const row = document.createElement("div");
        row.className = "pron-row";
        row.innerHTML = `
          <span class="from">${escapeHtml(from)}</span>
          <span class="arrow">→</span>
          <span class="to">${escapeHtml(to)}</span>
        `;
        row.addEventListener("click", () => {
          pronWrittenEl.value = from;
          pronNarrationEl.value = to;
          pronWrittenEl.focus();
        });
        row.style.cursor = "pointer";
        row.setAttribute("data-tooltip", `Click to copy this entry into the add form, e.g. for editing.\nCurrent: "${from}" → "${to}"`);
        row.setAttribute("data-tooltip-pos", "bottom");
        pronListEl.appendChild(row);
      }
    }

    pronSearchEl.addEventListener("input", renderPronList);

    function updatePronHint() {
      const text = textEl.value;
      if (!text || !pronEntries.length) { pronHint.className = "pron-hint"; return; }
      const lc = text.toLowerCase();
      const hits = pronEntries.filter((e) => {
        const from = (e.from || e.written || "").toLowerCase();
        return from && lc.includes(from);
      }).slice(0, 3);
      if (!hits.length) { pronHint.className = "pron-hint"; return; }
      pronHint.className = "pron-hint show";
      pronHint.innerHTML = hits.map((e) => {
        const from = e.from || e.written || "";
        const to = e.to || e.narration || "";
        return `<strong>${escapeHtml(from)}</strong> will be voiced as <span class="mono">${escapeHtml(to)}</span>`;
      }).join(" · ") + ' <span class="mono" style="opacity:0.7">· global override</span>';
    }

    textEl.addEventListener("input", updatePronHint);

    // Preview: synth the "written" raw and the "narration" raw back-to-back.
    async function pronPreview() {
      const written = pronWrittenEl.value.trim();
      const narration = pronNarrationEl.value.trim();
      if (!written || !narration) {
        toast("fill Written and Narration first", "err");
        return;
      }
      const btn = $("pron-preview");
      btn.disabled = true; btn.textContent = "Rendering…";
      try {
        // Raw: no pronunciation override, plain written form — hear what the TTS does.
        const r1 = await fetch("synth", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text: written,
            voice: voiceEl.value || "en-US-AndrewNeural",
            rate: "+0%",
            apply_pronunciations: false,
          }),
        });
        const j1 = await r1.json();
        if (!j1.ok) throw new Error(j1.error || "raw synth failed");

        // Applied: feed the narration form directly (no-op pronunciation apply).
        const r2 = await fetch("synth", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text: narration,
            voice: voiceEl.value || "en-US-AndrewNeural",
            rate: "+0%",
            apply_pronunciations: false,
          }),
        });
        const j2 = await r2.json();
        if (!j2.ok) throw new Error(j2.error || "narration synth failed");

        toast(`preview: "${written}" then "${narration}"`, "ok");
        await refreshHistory();
        play(j1.clip.id);
        setTimeout(() => {
          if (!audio.paused) {
            audio.addEventListener("ended", function onend() {
              audio.removeEventListener("ended", onend);
              play(j2.clip.id);
            }, { once: true });
          } else {
            play(j2.clip.id);
          }
        }, 100);
      } catch (e) {
        toast("preview failed: " + e.message, "err");
      } finally {
        btn.disabled = false; btn.textContent = "Preview";
      }
    }

    async function pronPropose() {
      const written = pronWrittenEl.value.trim();
      const narration = pronNarrationEl.value.trim();
      const reason = pronReasonEl.value.trim();
      if (!written || !narration) {
        toast("fill Written and Narration first", "err");
        return;
      }
      const btn = $("pron-propose");
      btn.disabled = true;
      try {
        const r = await fetch("pronunciation/propose", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ written, narration, reason }),
        });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error || "propose failed");
        const target = j.target === "gallia"
          ? `added to gallia skill (${j.total_entries} entries)`
          : `queued locally (${j.total_entries} pending)`;
        toast(target, "ok");
        pronWrittenEl.value = "";
        pronNarrationEl.value = "";
        pronReasonEl.value = "";
        await loadPronunciations();
      } catch (e) {
        toast("propose failed: " + e.message, "err");
      } finally {
        btn.disabled = false;
      }
    }

    $("pron-preview").addEventListener("click", pronPreview);
    $("pron-propose").addEventListener("click", pronPropose);
    $("pron-clear").addEventListener("click", () => {
      pronWrittenEl.value = "";
      pronNarrationEl.value = "";
      pronReasonEl.value = "";
      pronWrittenEl.focus();
    });

    // ───── Boot ─────
    loadVoices();
    loadPronunciations();
    pollState();
    refreshHistory();
    setInterval(refreshHistory, 2000);
    setInterval(pollState, 10000);

    // Support direct links like ?scroll=pron — the outer <main> is the
    // scroll container in narrow layout so native anchor scrolling doesn't
    // always reach the target; scroll explicitly.
    (function () {
      const params = new URLSearchParams(location.search);
      const target = params.get("scroll") || location.hash.replace("#", "");
      if (!target) return;
      requestAnimationFrame(() => {
        const el = document.getElementById(target);
        if (el) el.scrollIntoView({ behavior: "auto", block: "start" });
      });
    })();
  </script>
</body>
</html>