☰

Hitomi Enhanced

Redesign of hitomi.la (grid with themes, gallery pages, reader, tag autocomplete, blacklist, favorites, and search builder) with the Hitomi Downloader integrated: queue, ZIP/PDF/CBZ, page selection, and preview.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

Tendrás que instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Tendrás que instalar una extensión como Tampermonkey antes de poder instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name         Hitomi Enhanced
// @namespace    hitomi-enhanced
// @version      2.0.0
// @author       SHIMURA
// @license      MIT
// @description  Redesign of hitomi.la (grid with themes, gallery pages, reader, tag autocomplete, blacklist, favorites, and search builder) with the Hitomi Downloader integrated: queue, ZIP/PDF/CBZ, page selection, and preview.
// @icon         data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARnElEQVR42u2df4xc1XXHP+fe9+bX/vIPbMfGEMAQQwzGYEwgDcKBVmmrhBY1kfoLtVWrJGqrtjRVpbYhNI0SVUmrqEmUNAIRKVKllj+aSmkoaaX+gUTTUAwGwg9DiIEY41/r9a53dnZm3r2nf7w3s7O/Z+fXzu6+Iz1Z2hm/efe+7z3ne84951zZdeX+KZSAJcXQSxGRjtxH1TXxLdPE82gTv6XNjCy5ejaPAmjDj9cfFxREXIASwnIASGX9iSiKMelEbGwxMyohlY0owQL2YdWlOXuaSqoBUukYAFLZ4ACQdCpSDZDKBiaBurQW8M34lWtUkSw/tuY4qXToO03R5KZoWzPP3fMA0GIMX0RQ1Y5FAVdHZM1qgN5MzzIvd22//JQDtO3fpwDY4CQwDQClXkAqKQBSWbcksFGstcs6Oot9InPYtqrivV+VcYgIxhhUZVkOo034Cd77nprC3ruBgHrPxMTELOdJFUQAEcySEykoWp8kVSWXy5HNZnvOIUQE5xzj4+MYEyTA1BXPRyOQC4UCQRD0bCxBb1++x6A4rXL/n3yc2w4dxHnFznnhy64khcg7rLWMjp7nG//4MD85/iaZbAHvdYV+eesTHUVVMhnLZx74FNfvey/qdEmbqovoszgzw3L8+HG++rVvcv78BLlsDuddDHjp3DOvKgCMCBfHL3D//X/AX3/6zzt234MHb+KeX/oYpbLDGNuweroHABFhqlTis3/zeT7x27/WoZEc5qo9e7jvvt/De5c8vXZ1q7anALDWoAK33noI7z2VarXOBWTF2kRiVWCEa/dezeWXX87zPzpGoTDQE/WpqhTyOW47dDPOOao+IpCgBa2Y2H5VrBFuOXgzO9+1g7NnRgkzYTIWWR8AiFcOOFfFGIMNLIGxbb0EEUPVOSIX1c1DT8YBGPX4aAbEpo0MO+chsIJ3UbyrIrFxqJFeXS8AmGvjW12tjfcQkd69+QYkK52PXvY6GtqX2cArmQQBRMEYmaVUe7GxVL+/KnhFGkEokrg1DRprifRyI7GqNyhGte4zqpr1wwG6potbYhHtE1pBQEzsuoYLTKUD1CffSQNB60YCY5l2ylQlQiqTuLffYer4Gxj1iA0wI8OE27Zit28DDOpcnczFWmNpNHgBFfAYvAjN5WOkAOiNshFhvFLk6qE8v3PT+9jxnccYK5Zwk0XEJNzAGkw+i1xxGYUP/Ay5A/sxBKiP6DdVEKxg6G1/pxbB66ibpjNksvHqdKKzAAZLsVLl43uv4Y/3Xcu2XJaLFy8AQjCcrT+PoGgUEb14jIsvvkrxhgNs/vVfJti0BY0casCImRMGbKQOgmCRhBMsNF0qfQeAfpQOgkAMpekSDx68kd+/7j1MREXOl6cIrKk58rN/VSAo5GMqcPQoo6dPs+UTv0G46zI00oW34VRBFSMGIxYrBq9ungHoJLTT3cBmJskaitMl/uzAXj55w1WcrYzjFAJjlkzPU+9R7zEjOcLRk4x+8xGiC2cw1sSaShSIv6Mu3gzRTEixWqVYLTMdOSIsYmxCOjuv2VIANMH2Jysl7r50B5/cv4+J0hSh2CZ1YhLIcR7yecy5M1x49HuoOtQoXhVvDBIYJGPwxSnkrVPcsnUzt1+6g6u2FsgHFYq+wmQ0jRofVyrLGt0LWIukzymMqPBHN+4jiCpUEEwLcSd1HpsfoPr0j5g+cJTcrQdBQCoVpo48y/QLR9ATZ2Bskq8d2IeKoegjLlarPDM6xj+/+gY/PHuO0BpCY4h0nQCg7WCNzNyndtXMabvqUkQoVcr8wtW7uWnbMKViCWNNcvPldzAbt6zjfwWb8Yw/8QS5W2+m+vwLTH33u0yfeAdclSCbRayl4iMQIY8wlM1w5eW7uOeynTx+4m0eeOp5zpYjBrIhrgGFrSqFVAMsqcAFC3zk3VdgfWyzpR1SrAqZEDl1igtff4jKa8fw5WlsIY+VAriEM9RADFRcREkdgnDv5bu4fHiQP/zBM7xxoUQutPg2PaqUAyy2MkRxPmJXLsd1Q3miahVps52CaBwuDlyV6vNHMUTYXBZxHu8cXhSszNJmxhhCia9z0xVu2DTCw3fcziWhx0UeKwbBtAzKFABLrP5y5NkzMsLWQp6q9/NS0Vq9swJSyCJqMI4kpCx4FJfsYcy6kv8X2IAL5QrXDgzy6UMHqVBGJWjLTTfNPnRnrjUEAI2J1qYgIG8MvtPP72tRnwQSGm/7LpUOJyihMUxWS3z4it3cuW0HpXIJ2wYuewsArYWwpB7OmhvB65faABFFBDKBjaN2td295KUtRPiWG8cMSRVEErXdsMrNMh5eLT5YVQi851eu3kPoXWIAtJsA2IgmIM7QLVcivPbXcwWiuKrj1ku2sD2fo+JdtzVAJz1rMxPIlv41CypKIMLZsqfkY5rVq6ddSJvUtYoqgsF5x6acZfdAQMVF8ZZzqgE6CFWvZGzAqfIkFypTcdi3j8Sj5GzIrqEtqHMt08DVGVU9eUfmM94+KRBVFQIrnC6XODU1TWBDHB4v3dydXxmHtCIMmpCyKNLiU6UaYFETECd5FisRT50exRrTV46MiODUUapME2Ca6mbafwCQPncNVcEYnjx5hkgEUw+4rLaWEkSVqhjOVB05FZSUA3SFjOXCkGfPjfLS2DjZIMD3AQAcnsBYRstT/PjiODY0qE/dwO64XEY4XZ3mv958m6wNUfU9Ad5Sl1clm83w8rlznJqaxNqwZfO0ugDo40DQDNuK2fbjP32Hs2WHpfVirU6NT9URIXz/zfNEPsR4g0q6F9A1GjAQZHhlfIwn3nmHQiYzpwC1x3j0MBRkODYxzuPH32Igk8G1oZVWBwC6Rkhg4g2IgkiGR195nTIZAnyXSzbnM34RwQuEgSBhhq88+xLnPCAeh2v5edaNBhARxJjkSmIKZoFLzMqupOJoIJPlyXNn+O+TbzGYy7S9D99K6MR7ZTib4dvHXuff3/wpQxlp+zlWJyGkMRBk2mPU3sfbp9VKhfJUEYvECTv1jhNzwifiV64CNC7aKnnloede4fZLLiUbRHjVGSWmdGi7eH52kagnwrFtcIjvvXmSLzz9IrnMAKK+/t2lMpL6DwAdXxme3bt3MDk1SSHfUB6uZmkANmuukrdsrXCmOMWR4gSHN2UpVmNSmHjmXbKWSiSOzblhvn/yNH/65A+ITEhoFN+B4oA1DYAa6o01fOuRhxKDJs2t6hW+hHglalyy9fZJJr7+DaxWQcLuFG+LoF4JrbAlv4lvv/YTPvu/RyhLllAMvkPu6OoCoEMkUAQKuWx9wWoXtEyjRpCrrsTddRfTjz2GyZi4ALSDv6pApBEjuZBKJeAz/3eUh198jYwtkJGoLda/7kxAIxeom2OZ2yKmzezghAfUmpKIwMgHP0DpyFHc6dPYTNBUnnhjC6m5ecUqcUKICgSqDId5njk/wYNPPc3/nL3Alkwe6HxuQtDZddJsTx5tSRUvpwVkUSMvnRuagDqQ/CBDP38349/6F6wo6n2S5bM4mVPAJ8Qtrg2cCQyJiYtN3NQk5Xyef3j2BR459jZFIjbnBvDe1UvOFgsypYGgXlkuA1pVBm85SGb/Hly1AmET5w96JfAQJJVFPulxJCL4ySlcaYrqzTfxuz98ni+/9DrVUBjIZPHquxZ16PGJkJq4YbpmAkGL63IFDCMf/kV8bhCJmuOe3gjOx/0CbGAhclQrSnDzAUY+dT+Fj/0qb02WGbIBWcA519Vt6LQwpFWWZg3OeTK7303+/e+j/B//STBYQJfoWKoKWMGLUC2XEGfI7LuRkTvvILf3agTDxTNjZEWTquCgfo5CCoDVfN9zXsDM4RYxGAbuOszk0ecIzo6i2aCu2Or2PWkoZY2gxWkqAuH+/QzfcRu56/fHtt85rFHUxtu9qoKoINrdToEpAFryOHzdFHgXEQ6PMPxzP8vFf3qU0CjipIHpC2INvjRNJfKEe97D1g8dJrvvvahNWsIm0cxZdQJJ8ol0ec8hBUAbASgRAQveeYZvO0TpyFH01Rchk0e8Yq3gfUR5vEJm106G7r6bzPsPITbEO486F/cWnFVuXKP5nl4U1KQAaBEAjerdq0ODkKHDdzD28itYFG8EX5xGNw2Tv+tDDN11JzJQQDUCV8WYZUq6xMUX2lF3OQVABzlBrRehsRZ1Su76a7E3XAMvvIoTCPdfz/BHP0K4/VLA41w1Xu19lGKeAmAFKn8xMEjcAx+xIYXr9zP+3Cts+s2PMnTHB+PvuLje3xhL8w23auVz3S1JSQHQKWKIw2Iw23eS+637GHr/bXgfp5DSRj/kVAOsBZMgIGJR5xnYew15kfg8A2lD1auNry4TwXUDAOfcqvxuvd29JBtGGnf5lpYLSZSZrSJJNUDTAwlWbygzPf0bXLk1EuVe0wCosXBV+M6//hujo2OEQWb+3C9wgMjKkoJmH0NT28gJw4B7772HwaECTv1MBpo2tP1sfXT1NPKF0uY6FR5e8xlB8cFNns9/4Yu8/NKPyecKOK/Lv2CZ3+5p8SwCP4udiwguihgYzHP48J0MDhXW7LnH68IECDC8eSsj2ybIZrL1DZnGbluNmlka/rhQysjc9gWaJJJKgw5Q58gVcmt+Q319cAAB5x1VF2FdEFdPQL1aRhtebJ1eLQIAbQCASf7oGwCQ6AC8czgXrfmp6+2xcT5Or65lzojKor10VkbAqHMBEYOTePX7RHXrQjxbWNQE1BV//UM7j5/HLWSknpxp6ExvA5MUotQiwL6RU6wLDdBBOznb7taWd711aFPzps2qmHmOmnRPnfVQemzBZreMU0lPC58/Q8kGsDgE33Lnjz4FQPNrbmODoEZSug+ANBTcMmh7AeQNEAlcG76zLmHOuvBbQrwLWKtL7GIgKE0L3+CSAqAfgxpKnD4vLVQzpwBIpQscQDr0nVVYTWvOK2kom0s4QB+kha/VY+PWIgBqj92bfIDUBPQ1eLsPghQAKQBSSUngalKeNncD596nliTSdw0n0zhAKqkGSKU526/MLg3rIg9INUDfSm9OWwuaf5juxAs6tRm0UMPp5m7db7GCOTUBKl11BDoIAOnTVdQJJbiahHJduYG98W3XhfqvhYLXHwDMbPWWyiKL3hAno6aBoNbmUNaBFlh/buB8ZtupQNA6eetz3MAomSuTaoBm3r3MAlBqXvqfBKZp4Yur/no+QHeBnEYC+5YErsn+ANrMyPrMh9Y+RoF0/RmD3r38Bb7TgSNj2geA79DoddkpWOpYl/q/s4rUZVFum6aFr2/9T6/2AlYFAHX0dogExvdbHVXe6byD+uEjtd1A6W7vo1UhgdZavPdtn6TZmARiTNBzDIiYWWOpL2Bd+RhUFe891pq4fWyPpOcAUK+cPz+GMQaLYDrAASanphkbG4sPUVbfYNe7GECxhslSkbOjY1x26U4wpq1f8/HZEYyeH2d07AJiLF4TRrCe+gPk83n+/u++wp4rr2DfdXtx3rUY+YsnZapY5Itf+jInTpygMLQJ73xvVr8xRGXHX/zlg3zpbz/Hzp078Pi4UcRy3t0ce1/rc3BhbIy/euBzTJVKDA4O4XvQ+k52XbG/Si92HepDFqqVMmFoedf27ag6BG2p+MEaw8XJIufOnSc/MIibd6hOM2uydcCICNOlEvl8ns2bBlH1s9rPLOeUCFI3GUEQMDY2xsTkFPmBAZzzdShpd0LcCvieAwCSXsneU61W5x2usFI4BUFAJgyper/Aq+wuAGp8xnmPr0aN50qt3AR4T2ADbBDfb9Zn3TqTEvyqkED1iiBkMtkZp6cFANRMR+TdIi1bus8Ka/2AwzBcUfRhoUdVFOe1i+1n+sQLqLdB0ZUGbRZ7v9JGcKozbqBrOmtKlv68x8HSNBC0wSUFQAqAVFIApJICIJUUAKmkAEglBUAqG0rSnMCOyfI5fM1uevWwt4GmGiA1AWmx3gZWWdSOpUwT9DeeaEoCUw2QAiDVAKmkJDAlgRvXbw0QKmhvU8LWuVbto/ssaPaT+4siuP8HK0zpZTG53YwAAAAASUVORK5CYII=
// @match        http*://hitomi.la/*
// @run-at       document-start
// @connect      github.com
// @connect      ghp.ci
// @connect      hub.gitmirror.com
// @connect      *
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_listValues
// @grant        GM_deleteValue
// @grant        GM_addValueChangeListener
// @grant        GM_addStyle
// @grant        GM_openInTab
// @grant        GM_registerMenuCommand
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// ==/UserScript==

// ============================================================================
// HITOMI ENHANCED: interfaz rediseñada
// ============================================================================
(() => {
  'use strict';

  const LOGO_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARnElEQVR42u2df4xc1XXHP+fe9+bX/vIPbMfGEMAQQwzGYEwgDcKBVmmrhBY1kfoLtVWrJGqrtjRVpbYhNI0SVUmrqEmUNAIRKVKllj+aSmkoaaX+gUTTUAwGwg9DiIEY41/r9a53dnZm3r2nf7w3s7O/Z+fXzu6+Iz1Z2hm/efe+7z3ne84951zZdeX+KZSAJcXQSxGRjtxH1TXxLdPE82gTv6XNjCy5ejaPAmjDj9cfFxREXIASwnIASGX9iSiKMelEbGwxMyohlY0owQL2YdWlOXuaSqoBUukYAFLZ4ACQdCpSDZDKBiaBurQW8M34lWtUkSw/tuY4qXToO03R5KZoWzPP3fMA0GIMX0RQ1Y5FAVdHZM1qgN5MzzIvd22//JQDtO3fpwDY4CQwDQClXkAqKQBSWbcksFGstcs6Oot9InPYtqrivV+VcYgIxhhUZVkOo034Cd77nprC3ruBgHrPxMTELOdJFUQAEcySEykoWp8kVSWXy5HNZnvOIUQE5xzj4+MYEyTA1BXPRyOQC4UCQRD0bCxBb1++x6A4rXL/n3yc2w4dxHnFznnhy64khcg7rLWMjp7nG//4MD85/iaZbAHvdYV+eesTHUVVMhnLZx74FNfvey/qdEmbqovoszgzw3L8+HG++rVvcv78BLlsDuddDHjp3DOvKgCMCBfHL3D//X/AX3/6zzt234MHb+KeX/oYpbLDGNuweroHABFhqlTis3/zeT7x27/WoZEc5qo9e7jvvt/De5c8vXZ1q7anALDWoAK33noI7z2VarXOBWTF2kRiVWCEa/dezeWXX87zPzpGoTDQE/WpqhTyOW47dDPOOao+IpCgBa2Y2H5VrBFuOXgzO9+1g7NnRgkzYTIWWR8AiFcOOFfFGIMNLIGxbb0EEUPVOSIX1c1DT8YBGPX4aAbEpo0MO+chsIJ3UbyrIrFxqJFeXS8AmGvjW12tjfcQkd69+QYkK52PXvY6GtqX2cArmQQBRMEYmaVUe7GxVL+/KnhFGkEokrg1DRprifRyI7GqNyhGte4zqpr1wwG6potbYhHtE1pBQEzsuoYLTKUD1CffSQNB60YCY5l2ylQlQiqTuLffYer4Gxj1iA0wI8OE27Zit28DDOpcnczFWmNpNHgBFfAYvAjN5WOkAOiNshFhvFLk6qE8v3PT+9jxnccYK5Zwk0XEJNzAGkw+i1xxGYUP/Ay5A/sxBKiP6DdVEKxg6G1/pxbB66ibpjNksvHqdKKzAAZLsVLl43uv4Y/3Xcu2XJaLFy8AQjCcrT+PoGgUEb14jIsvvkrxhgNs/vVfJti0BY0casCImRMGbKQOgmCRhBMsNF0qfQeAfpQOgkAMpekSDx68kd+/7j1MREXOl6cIrKk58rN/VSAo5GMqcPQoo6dPs+UTv0G46zI00oW34VRBFSMGIxYrBq9ungHoJLTT3cBmJskaitMl/uzAXj55w1WcrYzjFAJjlkzPU+9R7zEjOcLRk4x+8xGiC2cw1sSaShSIv6Mu3gzRTEixWqVYLTMdOSIsYmxCOjuv2VIANMH2Jysl7r50B5/cv4+J0hSh2CZ1YhLIcR7yecy5M1x49HuoOtQoXhVvDBIYJGPwxSnkrVPcsnUzt1+6g6u2FsgHFYq+wmQ0jRofVyrLGt0LWIukzymMqPBHN+4jiCpUEEwLcSd1HpsfoPr0j5g+cJTcrQdBQCoVpo48y/QLR9ATZ2Bskq8d2IeKoegjLlarPDM6xj+/+gY/PHuO0BpCY4h0nQCg7WCNzNyndtXMabvqUkQoVcr8wtW7uWnbMKViCWNNcvPldzAbt6zjfwWb8Yw/8QS5W2+m+vwLTH33u0yfeAdclSCbRayl4iMQIY8wlM1w5eW7uOeynTx+4m0eeOp5zpYjBrIhrgGFrSqFVAMsqcAFC3zk3VdgfWyzpR1SrAqZEDl1igtff4jKa8fw5WlsIY+VAriEM9RADFRcREkdgnDv5bu4fHiQP/zBM7xxoUQutPg2PaqUAyy2MkRxPmJXLsd1Q3miahVps52CaBwuDlyV6vNHMUTYXBZxHu8cXhSszNJmxhhCia9z0xVu2DTCw3fcziWhx0UeKwbBtAzKFABLrP5y5NkzMsLWQp6q9/NS0Vq9swJSyCJqMI4kpCx4FJfsYcy6kv8X2IAL5QrXDgzy6UMHqVBGJWjLTTfNPnRnrjUEAI2J1qYgIG8MvtPP72tRnwQSGm/7LpUOJyihMUxWS3z4it3cuW0HpXIJ2wYuewsArYWwpB7OmhvB65faABFFBDKBjaN2td295KUtRPiWG8cMSRVEErXdsMrNMh5eLT5YVQi851eu3kPoXWIAtJsA2IgmIM7QLVcivPbXcwWiuKrj1ku2sD2fo+JdtzVAJz1rMxPIlv41CypKIMLZsqfkY5rVq6ddSJvUtYoqgsF5x6acZfdAQMVF8ZZzqgE6CFWvZGzAqfIkFypTcdi3j8Sj5GzIrqEtqHMt08DVGVU9eUfmM94+KRBVFQIrnC6XODU1TWBDHB4v3dydXxmHtCIMmpCyKNLiU6UaYFETECd5FisRT50exRrTV46MiODUUapME2Ca6mbafwCQPncNVcEYnjx5hkgEUw+4rLaWEkSVqhjOVB05FZSUA3SFjOXCkGfPjfLS2DjZIMD3AQAcnsBYRstT/PjiODY0qE/dwO64XEY4XZ3mv958m6wNUfU9Ad5Sl1clm83w8rlznJqaxNqwZfO0ugDo40DQDNuK2fbjP32Hs2WHpfVirU6NT9URIXz/zfNEPsR4g0q6F9A1GjAQZHhlfIwn3nmHQiYzpwC1x3j0MBRkODYxzuPH32Igk8G1oZVWBwC6Rkhg4g2IgkiGR195nTIZAnyXSzbnM34RwQuEgSBhhq88+xLnPCAeh2v5edaNBhARxJjkSmIKZoFLzMqupOJoIJPlyXNn+O+TbzGYy7S9D99K6MR7ZTib4dvHXuff3/wpQxlp+zlWJyGkMRBk2mPU3sfbp9VKhfJUEYvECTv1jhNzwifiV64CNC7aKnnloede4fZLLiUbRHjVGSWmdGi7eH52kagnwrFtcIjvvXmSLzz9IrnMAKK+/t2lMpL6DwAdXxme3bt3MDk1SSHfUB6uZmkANmuukrdsrXCmOMWR4gSHN2UpVmNSmHjmXbKWSiSOzblhvn/yNH/65A+ITEhoFN+B4oA1DYAa6o01fOuRhxKDJs2t6hW+hHglalyy9fZJJr7+DaxWQcLuFG+LoF4JrbAlv4lvv/YTPvu/RyhLllAMvkPu6OoCoEMkUAQKuWx9wWoXtEyjRpCrrsTddRfTjz2GyZi4ALSDv6pApBEjuZBKJeAz/3eUh198jYwtkJGoLda/7kxAIxeom2OZ2yKmzezghAfUmpKIwMgHP0DpyFHc6dPYTNBUnnhjC6m5ecUqcUKICgSqDId5njk/wYNPPc3/nL3Alkwe6HxuQtDZddJsTx5tSRUvpwVkUSMvnRuagDqQ/CBDP38349/6F6wo6n2S5bM4mVPAJ8Qtrg2cCQyJiYtN3NQk5Xyef3j2BR459jZFIjbnBvDe1UvOFgsypYGgXlkuA1pVBm85SGb/Hly1AmET5w96JfAQJJVFPulxJCL4ySlcaYrqzTfxuz98ni+/9DrVUBjIZPHquxZ16PGJkJq4YbpmAkGL63IFDCMf/kV8bhCJmuOe3gjOx/0CbGAhclQrSnDzAUY+dT+Fj/0qb02WGbIBWcA519Vt6LQwpFWWZg3OeTK7303+/e+j/B//STBYQJfoWKoKWMGLUC2XEGfI7LuRkTvvILf3agTDxTNjZEWTquCgfo5CCoDVfN9zXsDM4RYxGAbuOszk0ecIzo6i2aCu2Or2PWkoZY2gxWkqAuH+/QzfcRu56/fHtt85rFHUxtu9qoKoINrdToEpAFryOHzdFHgXEQ6PMPxzP8vFf3qU0CjipIHpC2INvjRNJfKEe97D1g8dJrvvvahNWsIm0cxZdQJJ8ol0ec8hBUAbASgRAQveeYZvO0TpyFH01Rchk0e8Yq3gfUR5vEJm106G7r6bzPsPITbEO486F/cWnFVuXKP5nl4U1KQAaBEAjerdq0ODkKHDdzD28itYFG8EX5xGNw2Tv+tDDN11JzJQQDUCV8WYZUq6xMUX2lF3OQVABzlBrRehsRZ1Su76a7E3XAMvvIoTCPdfz/BHP0K4/VLA41w1Xu19lGKeAmAFKn8xMEjcAx+xIYXr9zP+3Cts+s2PMnTHB+PvuLje3xhL8w23auVz3S1JSQHQKWKIw2Iw23eS+637GHr/bXgfp5DSRj/kVAOsBZMgIGJR5xnYew15kfg8A2lD1auNry4TwXUDAOfcqvxuvd29JBtGGnf5lpYLSZSZrSJJNUDTAwlWbygzPf0bXLk1EuVe0wCosXBV+M6//hujo2OEQWb+3C9wgMjKkoJmH0NT28gJw4B7772HwaECTv1MBpo2tP1sfXT1NPKF0uY6FR5e8xlB8cFNns9/4Yu8/NKPyecKOK/Lv2CZ3+5p8SwCP4udiwguihgYzHP48J0MDhXW7LnH68IECDC8eSsj2ybIZrL1DZnGbluNmlka/rhQysjc9gWaJJJKgw5Q58gVcmt+Q319cAAB5x1VF2FdEFdPQL1aRhtebJ1eLQIAbQCASf7oGwCQ6AC8czgXrfmp6+2xcT5Or65lzojKor10VkbAqHMBEYOTePX7RHXrQjxbWNQE1BV//UM7j5/HLWSknpxp6ExvA5MUotQiwL6RU6wLDdBBOznb7taWd711aFPzps2qmHmOmnRPnfVQemzBZreMU0lPC58/Q8kGsDgE33Lnjz4FQPNrbmODoEZSug+ANBTcMmh7AeQNEAlcG76zLmHOuvBbQrwLWKtL7GIgKE0L3+CSAqAfgxpKnD4vLVQzpwBIpQscQDr0nVVYTWvOK2kom0s4QB+kha/VY+PWIgBqj92bfIDUBPQ1eLsPghQAKQBSSUngalKeNncD596nliTSdw0n0zhAKqkGSKU526/MLg3rIg9INUDfSm9OWwuaf5juxAs6tRm0UMPp5m7db7GCOTUBKl11BDoIAOnTVdQJJbiahHJduYG98W3XhfqvhYLXHwDMbPWWyiKL3hAno6aBoNbmUNaBFlh/buB8ZtupQNA6eetz3MAomSuTaoBm3r3MAlBqXvqfBKZp4Yur/no+QHeBnEYC+5YErsn+ANrMyPrMh9Y+RoF0/RmD3r38Bb7TgSNj2geA79DoddkpWOpYl/q/s4rUZVFum6aFr2/9T6/2AlYFAHX0dogExvdbHVXe6byD+uEjtd1A6W7vo1UhgdZavPdtn6TZmARiTNBzDIiYWWOpL2Bd+RhUFe891pq4fWyPpOcAUK+cPz+GMQaLYDrAASanphkbG4sPUVbfYNe7GECxhslSkbOjY1x26U4wpq1f8/HZEYyeH2d07AJiLF4TRrCe+gPk83n+/u++wp4rr2DfdXtx3rUY+YsnZapY5Itf+jInTpygMLQJ73xvVr8xRGXHX/zlg3zpbz/Hzp078Pi4UcRy3t0ce1/rc3BhbIy/euBzTJVKDA4O4XvQ+k52XbG/Si92HepDFqqVMmFoedf27ag6BG2p+MEaw8XJIufOnSc/MIibd6hOM2uydcCICNOlEvl8ns2bBlH1s9rPLOeUCFI3GUEQMDY2xsTkFPmBAZzzdShpd0LcCvieAwCSXsneU61W5x2usFI4BUFAJgyper/Aq+wuAGp8xnmPr0aN50qt3AR4T2ADbBDfb9Zn3TqTEvyqkED1iiBkMtkZp6cFANRMR+TdIi1bus8Ka/2AwzBcUfRhoUdVFOe1i+1n+sQLqLdB0ZUGbRZ7v9JGcKozbqBrOmtKlv68x8HSNBC0wSUFQAqAVFIApJICIJUUAKmkAEglBUAqG0rSnMCOyfI5fM1uevWwt4GmGiA1AWmx3gZWWdSOpUwT9DeeaEoCUw2QAiDVAKmkJDAlgRvXbw0QKmhvU8LWuVbto/ssaPaT+4siuP8HK0zpZTG53YwAAAAASUVORK5CYII=';
  const VERSION = (typeof GM_info !== 'undefined' && GM_info.script?.version) || '';

  const DEFAULTS = {
    revamp: true,
    newUi: true,
    theme: 'oled',
    accent: 'rose',
    cardSize: 'm',
    cardTags: 'compact',
    classicTheme: false,
    readerAutoHide: true,
    fit: 'height',
    rightArrowIsNext: true,
    escBack: true,
    zoom: 100,
    clickHalves: true,
    wheelPages: true,
    openInReader: false,
    newTab: false,
    newTabFocus: false,
    blMode: 'hide',
    stripPos: 'bottom',
    stripHidden: true,
    thumbSize: 100,
    thumbLoad: 'visible',
    maxParallel: 4,
    delayMs: 150,
    favSort: 'new',
  };
  const SKEY = 'hr-settings';
  const S = Object.assign({}, DEFAULTS, GM_getValue(SKEY, {}));
  const saveSettings = () => GM_setValue(SKEY, { ...S });
  if (S.ui === 'classic') S.newUi = false;
  delete S.ui; delete S.readerUi;
  if (S.cardTags === true) S.cardTags = 'compact'; else if (S.cardTags === false) S.cardTags = 'off';

  const THEMES = {
    midnight: { bg: '#141527', surface: '#1d1f35', surface2: '#272a46', border: '#34385f', text: '#e9eaf7', muted: '#9a9dc8', shadow: 'rgba(0,0,0,.5)', scheme: 'dark' },
    graphite: { bg: '#151517', surface: '#1e1e21', surface2: '#29292d', border: '#37373d', text: '#ededf0', muted: '#9c9ca6', shadow: 'rgba(0,0,0,.5)', scheme: 'dark' },
    oled:     { bg: '#000000', surface: '#0d0d0f', surface2: '#19191c', border: '#29292e', text: '#f3f3f6', muted: '#8d8d97', shadow: 'rgba(0,0,0,.7)', scheme: 'dark' },
    paper:    { bg: '#f3f3f6', surface: '#ffffff', surface2: '#e9e9f0', border: '#d6d6e0', text: '#1a1b26', muted: '#62647a', shadow: 'rgba(20,20,40,.14)', scheme: 'light' },
  };
  const THEME_NAMES = [['midnight', 'Medianoche'], ['graphite', 'Grafito'], ['oled', 'Negro'], ['paper', 'Claro']];
  const ACCENTS = { indigo: '#6d72d8', violet: '#9a5fe0', rose: '#df5279', amber: '#d48d1c', teal: '#1fa392', sky: '#2e8ddf' };
  const ACCENT_ES = { indigo: 'Índigo', violet: 'Violeta', rose: 'Rosa', amber: 'Ámbar', teal: 'Turquesa', sky: 'Celeste' };
  const CARD_W = { s: 160, m: 200, l: 250 };

  const W = unsafeWindow;
  // Al recargar una lista cuya dirección acaba en #hr-favoritos (por ejemplo con «Volver»), el código del sitio pega ese # al archivo
  // de la lista y no consigue cargarla (las tarjetas se quedan vacías). Se quita el # hasta que el sitio haya cargado su lista y entonces se vuelve a poner.
  let hrHashHeld = false;
  function hrHoldHash() {
    if (hrHashHeld || location.hash !== '#hr-favoritos' || location.pathname === '/' || !/\.html$/.test(location.pathname)) return;
    try { history.replaceState(history.state, '', location.pathname + location.search); } catch { return; }
    hrHashHeld = true;
    console.log('[Hitomi Enhanced] #hr-favoritos quitado mientras el sitio carga su lista');
    let tries = 0;
    const iv = setInterval(() => {
      if (location.hash) { clearInterval(iv); return; }
      if (!document.querySelector('.gallery-content > div') && ++tries < 60) return; // hasta 12 s
      clearInterval(iv);
      setTimeout(() => {
        if (location.hash) return;
        history.replaceState(history.state, '', location.pathname + location.search + '#hr-favoritos');
        favNav();
      }, 400);
    }, 200);
  }
  hrHoldHash();
  document.addEventListener('DOMContentLoaded', hrHoldHash, { once: true });
  const isReader = () => location.pathname.startsWith('/reader/');
  const readerGalleryId = () => (location.pathname.match(/\/reader\/(\d+)\.html/) || [])[1];
  const GALLERY_RE = /^\/(?:manga|doujinshi|gamecg|cg|imageset|anime|galleries)\/(?:.*-)?(\d+)\.html$/;
  const pageGalleryId = (location.pathname.match(GALLERY_RE) || [])[1];
  const readerUrl = id => `/reader/${id}.html#1`;
  const el = (tag, props = {}, ...kids) => { const n = Object.assign(document.createElement(tag), props); n.append(...kids); return n; };
  const ready = fn => document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', fn) : fn();
  const onRemote = (key, fn) => {
    if (typeof GM_addValueChangeListener === 'function') GM_addValueChangeListener(key, (k, o, n, remote) => { if (remote) fn(n); });
  };

  // ============================================================================
  // Idioma de la interfaz de Enhanced: sigue al selector del descargador (GM «ui_lang»: es / en).
  // Los textos están escritos en español; en inglés se traducen sobre la marcha (nodos de texto y
  // atributos title / aria-label / placeholder / alt) y al volver a español se restauran.
  // ============================================================================
  const EN_DICT = new Map(Object.entries({
    'Medianoche': 'Midnight', 'Grafito': 'Graphite', 'Negro': 'Black', 'Claro': 'Light',
    'Índigo': 'Indigo', 'Violeta': 'Violet', 'Rosa': 'Rose', 'Ámbar': 'Amber', 'Turquesa': 'Teal', 'Celeste': 'Sky',
    'Anterior': 'Previous', 'Siguiente': 'Next', 'Flecha izquierda': 'Left arrow', 'Flecha derecha': 'Right arrow',
    'Tamaño de la imagen, % de la pantalla (+ / - / 0)': 'Image size, % of the screen (+ / - / 0)',
    'Tamaño': 'Size', 'Escribe un número de página y pulsa Intro': 'Type a page number and press Enter', 'Página': 'Page',
    'Ajustes de Hitomi Enhanced': 'Hitomi Enhanced settings',
    'galería': 'gallery', 'Leer': 'Read', 'Leer en una pestaña nueva': 'Read in a new tab',
    'Página de la galería': 'Gallery page', 'Detalles, etiquetas y todas las páginas': 'Details, tags and all pages',
    'Página de la galería en una pestaña nueva': 'Gallery page in a new tab',
    'Excluido de la búsqueda de esta pestaña': 'Excluded from this tab’s search', 'En la búsqueda de esta pestaña': 'In this tab’s search',
    'En lista negra': 'Blacklisted',
    'Añadir a la búsqueda': 'Add to search', 'Mostrar las galerías que lo tienen': 'Show galleries that have it',
    'Excluir de la búsqueda': 'Exclude from search', 'Ocultar las galerías que lo tienen': 'Hide galleries that have it',
    'Quitar de la búsqueda': 'Remove from search', 'Incluir en su lugar': 'Include instead', 'Excluir en su lugar': 'Exclude instead',
    'Buscar con esto ahora': 'Search with this now', 'Lo añade y ejecuta la búsqueda': 'Adds it and runs the search',
    'Buscar solo esto': 'Search only this', 'Inicia una búsqueda nueva': 'Starts a new search',
    'Abrir en una pestaña nueva': 'Open in a new tab', 'Quitar de la lista negra': 'Remove from blacklist',
    'Volver a mostrar estas galerías': 'Show these galleries again', 'Añadir a la lista negra': 'Add to blacklist',
    'Ocultar las galerías que lo tienen en todas partes': 'Hide galleries that have it everywhere',
    'Excluido. Clic para incluir': 'Excluded. Click to include', 'Clic para excluir': 'Click to exclude', 'no': 'not',
    'Buscar': 'Search', 'Limpiar': 'Clear',
    'Más recientes': 'Newest', 'Populares hoy': 'Popular today', 'Populares esta semana': 'Popular this week',
    'Populares este mes': 'Popular this month', 'Populares este año': 'Popular this year',
    'Cualquier idioma': 'Any language', 'Inglés': 'English', 'Japonés': 'Japanese', 'Chino': 'Chinese', 'Coreano': 'Korean',
    'Español': 'Spanish', 'Francés': 'French', 'Alemán': 'German', 'Ruso': 'Russian', 'Portugués': 'Portuguese',
    'Etiqueta': 'Tag', 'Artista': 'Artist', 'Serie': 'Series', 'Personaje': 'Character', 'Grupo': 'Group', 'Tipo': 'Type',
    'Buscar etiquetas, artistas o títulos': 'Search tags, artists or titles', 'Ordenar': 'Sort', 'Idioma': 'Language',
    'Categorías': 'Categories', 'Etiquetas': 'Tags', 'Artistas': 'Artists', 'Personajes': 'Characters',
    'Explorar': 'Browse', 'Ajustes': 'Settings', 'Últimas galerías': 'Latest galleries', 'Páginas': 'Pages',
    'Sin título': 'Untitled', 'Menos': 'Less', 'Mostrar menos etiquetas': 'Show fewer tags', 'Mostrar todas las etiquetas': 'Show all tags',
    'Resultados de búsqueda': 'Search results',
    'Todo lo de esta página está en la lista negra.': 'Everything on this page is blacklisted.',
    'No hay galerías aquí.': 'There are no galleries here.', 'Galerías relacionadas': 'Related galleries',
    'También en': 'Also in', 'Grupos': 'Groups', 'Añadida': 'Added', 'Ver más': 'Show more', 'Ver todas': 'Show all',
    'Cargando…': 'Loading…', 'Restablecer tamaño (0)': 'Reset size (0)', 'Miniaturas (T)': 'Thumbnails (T)',
    'Volver (Esc)': 'Back (Esc)', 'Página anterior': 'Previous page', 'Página siguiente': 'Next page',
    'Más pequeña (-)': 'Smaller (-)', 'Más grande (+)': 'Larger (+)', 'Ajustar': 'Fit', 'Pantalla completa (F)': 'Fullscreen (F)',
    'Lector': 'Reader', 'Lista negra': 'Blacklist',
    'Aún no hay nada en la lista negra. Haz clic derecho en cualquier etiqueta y elige "Añadir a la lista negra", o escribe una arriba.':
      'Nothing in the blacklist yet. Right-click any tag and choose “Add to blacklist”, or type one above.',
    'Quitar': 'Remove', 'Color de acento': 'Accent color', 'Cambiar a la pestaña nueva': 'Switch to the new tab',
    'Si está desactivado, se abre en segundo plano': 'When off, it opens in the background',
    'Tamaño de las miniaturas': 'Thumbnail size', 'Etiquetas para la lista negra, separadas por comas': 'Blacklist tags, separated by commas',
    'Añadir': 'Add', 'Quitar todas': 'Remove all', 'Cerrar': 'Close', 'Cerrar ajustes': 'Close settings',
    'Restablecer ajustes': 'Reset settings', 'Listo': 'Done',
    'Apariencia': 'Appearance', 'Diseño de Hitomi Enhanced': 'Hitomi Enhanced design',
    'Desactívalo para volver al diseño original del sitio; el descargador sigue funcionando. Un lector abierto cambia en su próxima carga':
      'Turn it off to go back to the site’s original design; the downloader keeps working. An open reader changes on its next load',
    'Interfaz nueva': 'New interface',
    'Listas, páginas de galería y lector rediseñados. Un lector abierto se activa en su próxima carga':
      'Redesigned lists, gallery pages and reader. An open reader switches on its next load',
    'Tema': 'Theme', 'Acento': 'Accent', 'Aplicar el tema a las páginas clásicas': 'Apply the theme to classic pages',
    'Recolorea el sitio donde la interfaz nueva está desactivada': 'Recolors the site where the new interface is off',
    'Tamaño de las tarjetas': 'Card size', 'Etiquetas en las tarjetas': 'Tags on cards', 'Algunas': 'Some', 'Todas': 'All', 'No': 'None',
    '«Algunas» muestra 8; el resto se abre sobre la tarjeta': '“Some” shows 8; the rest opens over the card',
    'Navegación': 'Navigation', 'Abrir las galerías en el lector': 'Open galleries in the reader',
    'Omite la página de detalles': 'Skips the details page', 'Abrir las galerías en una pestaña nueva': 'Open galleries in a new tab',
    'Al hacer clic en un resultado': 'When clicking a result',
    'La flecha derecha avanza': 'Right arrow goes forward', 'Desactívalo para leer de derecha a izquierda': 'Turn it off to read right to left',
    'Clic en las mitades de la imagen para pasar de página': 'Click the halves of the image to turn the page',
    'Rueda del ratón para pasar de página': 'Mouse wheel to turn the page',
    'Si la imagen es más grande que la pantalla, primero se desplaza y al llegar al borde cambia de página':
      'If the image is larger than the screen, it scrolls first and turns the page at the edge',
    'Esc sale del lector': 'Esc exits the reader', 'Ocultar automáticamente la barra del lector': 'Auto-hide the reader bar',
    'Acerca el ratón al borde superior para volver a mostrarla': 'Move the mouse to the top edge to show it again',
    'Tamaño de la imagen': 'Image size', 'Porción de la pantalla que ocupa la página': 'Share of the screen the page takes up',
    'Tira de miniaturas': 'Thumbnail strip', 'Posición': 'Position', 'Abajo': 'Bottom', 'Izquierda': 'Left', 'Derecha': 'Right',
    'Posición de la tira': 'Strip position', 'Cargar miniaturas': 'Load thumbnails', 'En pantalla': 'On screen',
    'Descargas simultáneas': 'Simultaneous downloads', 'Pausa entre descargas': 'Pause between downloads',
    'Galerías de la lista negra': 'Blacklisted galleries', 'Ocultar': 'Hide', 'Atenuar': 'Dim',
    '«Atenuar» las desenfoca hasta que pasas el cursor': '“Dim” blurs them until you hover over them',
    'Descargas': 'Downloads', 'Destino de las descargas': 'Download destination', 'Vista previa': 'Preview',
    'Historial de descargas': 'Download history', 'Imágenes': 'Images', 'Descargas a la vez': 'Downloads at a time',
    'Formato': 'Format', 'ZIP, archivos sueltos, PDF único o cómic (CBZ / CBR)': 'ZIP, individual files, single PDF or comic book (CBZ / CBR)',
    'Archivos': 'Files', 'Dividir el ZIP cada': 'Split the ZIP every', 'Calidad del PDF': 'PDF quality',
    'Solo se usa en modo PDF. Menor calidad = archivo más pequeño. Recomendada: 40 %.': 'Only used in PDF mode. Lower quality = smaller file. Recommended: 40 %.',
    'Subcarpeta': 'Subfolder', 'Crear un subdirectorio': 'Create a subdirectory', 'Ruta de la subcarpeta': 'Subfolder path',
    'Carpeta base': 'Base folder', 'Elegir carpeta': 'Choose folder', 'Nombre de la carpeta': 'Folder name',
    'Usa / para carpetas anidadas. Clic en un marcador para insertarlo.': 'Use / for nested folders. Click a placeholder to insert it.',
    'Clic para insertar': 'Click to insert',
    'Vista previa al pasar el cursor por una obra': 'Preview when hovering over a work',
    'Vista previa al pasar el cursor por las páginas de una obra': 'Preview when hovering over the pages of a work', 'Vista previa en Favoritos': 'Preview in Favorites', 'Tamaño de imagen': 'Image size', 'Pequeño': 'Small',
    'Tiempo de espera': 'Waiting time', 'Tiempo de espera (páginas de una obra)': 'Waiting time (pages of a work)',
    'Usar la rueda del mouse para cambiar de imagen': 'Use the mouse wheel to switch images',
    'Usar las flechas y la barra espaciadora para cambiar de imagen': 'Use the arrow keys and space bar to switch images',
    'Mostrar resumen': 'Show summary', 'Mostrar contador de páginas': 'Show page counter',
    'Obras descargadas': 'Downloaded works', 'Vaciar historial': 'Clear history', 'Copia de seguridad': 'Backup',
    'Exporta o importa el historial como archivo JSON': 'Export or import the history as a JSON file',
    'Exportar': 'Export', 'Importar': 'Import', '¿Vaciar el historial de descargas?': 'Clear the download history?',
    'Archivo de historial no válido': 'Invalid history file',
    'Configuración': 'Settings', 'Exporta o importa todos los ajustes, la lista negra y los favoritos como archivo JSON': 'Export or import all settings, the blacklist and the favorites as a JSON file',
    'Archivo de configuración no válido': 'Invalid settings file',
    'Copiar portada': 'Copy cover', 'Copia la imagen de la portada al portapapeles': 'Copies the cover image to the clipboard',
    'Portada copiada': 'Cover copied', 'No se pudo copiar la portada': 'Could not copy the cover',
    'Doble clic para copiar el nombre': 'Double-click to copy the name', 'Nombre copiado': 'Name copied', 'No se pudo copiar el nombre': 'Could not copy the name',
    'Favoritos': 'Favorites', 'Añadir a favoritos': 'Add to favorites', 'Quitar de favoritos': 'Remove from favorites',
    'En favoritos': 'In favorites', 'Añadida a favoritos': 'Added to favorites', 'Quitada de favoritos': 'Removed from favorites',
    'Deshacer': 'Undo', 'Guárdala en tu apartado de Favoritos': 'Save it in your Favorites',
    'Datos y copia de seguridad': 'Data and backup', 'Archivo de copia de seguridad no válido': 'Invalid backup file',
    'Exporta o importa ajustes, lista negra, favoritos, listas e historial de descargas en un solo archivo JSON': 'Export or import settings, blacklist, favorites, lists and download history in a single JSON file',
    'Artistas y más': 'Artists and more', 'Galerías': 'Galleries', 'Todos': 'All', 'Otros': 'Other', 'Vaciar': 'Clear',
    'Añadido a favoritos': 'Added to favorites', 'Quitado de favoritos': 'Removed from favorites',
    'Aparece en Favoritos, pestaña Artistas y más': 'Shows up in Favorites, Artists and more tab',
    'Se guardan con clic derecho en una etiqueta o con el botón de su página': 'Saved with a right click on a tag or with the button on its page',
    '¿Vaciar los artistas, grupos y etiquetas favoritos?': 'Clear all favorite artists, groups and tags?',
    'Aún no tienes artistas, grupos ni etiquetas favoritos. Haz clic derecho en uno y elige «Añadir a favoritos», o usa el botón de su página.': 'You have no favorite artists, groups or tags yet. Right-click one and choose “Add to favorites”, or use the button on its page.',
    'Abrir página': 'Open page', 'No se pudo cargar el contenido. Usa «Abrir página» para verlo.': 'Could not load the content. Use “Open page” to see it.',
    'Listas': 'Lists', 'Listas…': 'Lists…', 'Guardar en una lista de favoritos': 'Save to a favorites list', 'Añadir a una lista': 'Add to a list',
    'Aún no tienes listas. Crea la primera abajo.': 'You have no lists yet. Create the first one below.',
    'Nueva lista': 'New list', 'Crear': 'Create', 'Sin lista': 'No list', 'Renombrar lista': 'Rename list', 'Eliminar lista': 'Delete list',
    'Nombre de la nueva lista': 'Name of the new list', 'Nuevo nombre de la lista': 'New name for the list',
    '¿Eliminar esta lista? Las galerías seguirán en favoritos.': 'Delete this list? The galleries will stay in favorites.',
    'Ya existe una lista con ese nombre': 'A list with that name already exists',
    'Esta lista está vacía. Usa el botón de listas de una tarjeta para añadir galerías.': 'This list is empty. Use the lists button on a card to add galleries.',
    'Filtrar favoritos por título, artista o etiqueta': 'Filter favorites by title, artist or tag',
    'Filtrar favoritos': 'Filter favorites', 'Ordenar favoritos': 'Sort favorites',
    'Añadidas recientemente': 'Recently added', 'Añadidas hace más tiempo': 'Oldest added',
    'Título (A–Z)': 'Title (A–Z)', 'Artista (A–Z)': 'Artist (A–Z)',
    'Aún no tienes favoritos. Pulsa el corazón de una galería para guardarla aquí.': 'You have no favorites yet. Click the heart on a gallery to save it here.',
    'Ningún favorito coincide con tu búsqueda.': 'No favorites match your search.',
    'Aún se está cargando la galería': 'The gallery is still loading',
    'Galerías favoritas': 'Favorite galleries', 'Vaciar favoritos': 'Clear favorites',
    'Se guardan con el corazón de las tarjetas, de la página de la galería y del lector': 'Saved with the heart on cards, the gallery page and the reader',
    'Exporta o importa los favoritos como archivo JSON': 'Export or import favorites as a JSON file',
    'Archivo de favoritos no válido': 'Invalid favorites file',
    '¿Reemplazar la configuración actual con la del archivo? La página se recargará.': 'Replace the current settings with the ones in the file? The page will reload.',
    'Atajos': 'Shortcuts', 'Pasar de página (A / D también funcionan)': 'Turn the page (A / D work too)',
    'Primera / última página': 'First / last page', 'Ocultar la tira de miniaturas': 'Hide the thumbnail strip',
    'Ajustar al ancho o al alto': 'Fit to width or height', 'Pantalla completa': 'Fullscreen',
    'Ir al cuadro de búsqueda': 'Go to the search box', 'Salir del lector': 'Exit the reader',
    'Clic derecho': 'Right click', 'Menú normal del navegador': 'Normal browser menu',
    'Haz clic derecho en una etiqueta para buscarla o añadirla a la lista negra. La lista de búsqueda pertenece a esta pestaña; las pestañas abiertas desde aquí empiezan con una copia. El intercambio de botones se aplica en la próxima carga de la página.':
      'Right-click a tag to search for it or add it to the blacklist. The search list belongs to this tab; tabs opened from here start with a copy. The button swap applies on the next page load.',
  }));
  const hideWord = w => /^ocult/.test(w) ? 'hidden' : 'dimmed';
  const EN_RE = [
    [/^Ajustes de Hitomi Enhanced \((\d+) galerías? de la lista negra (ocultas?|atenuadas?) aquí\)$/,
      (m, n, w) => `Hitomi Enhanced settings (${n} blacklisted ${+n === 1 ? 'gallery' : 'galleries'} ${hideWord(w)} here)`],
    [/^(\d+) galerías? en esta página(?:, (\d+) (ocultas?|atenuadas?) por tu lista negra)?$/,
      (m, n, b, w) => `${n} ${+n === 1 ? 'gallery' : 'galleries'} on this page` + (b ? `, ${b} ${hideWord(w)} by your blacklist` : '')],
    [/^Lista negra \((\d+)\)$/, 'Blacklist ($1)'],
    [/^(\d+) galerías?$/, (m, n) => `${n} ${+n === 1 ? 'gallery' : 'galleries'}`],
    [/^(\d+) favoritos?$/, (m, n) => `${n} ${+n === 1 ? 'favorite' : 'favorites'}`],
    [/^(\d+) de (\d+) favoritos$/, '$1 of $2 favorites'],
    [/^Favoritos importados: (\d+)$/, 'Favorites imported: $1'],
    [/^¿Vaciar los (\d+) favoritos\?$/, 'Clear all $1 favorites?'],
    [/^Galería (\d+)$/, 'Gallery $1'],
    [/^Página (\d+)$/, 'Page $1'],
    [/(\d+) páginas$/, '$1 pages'],
    [/^Versión (.+)$/, 'Version $1'],
    [/^Carpeta: (.+)$/, 'Folder: $1'],
    [/^Obras importadas: (\d+)$/, 'Works imported: $1'],
    [/^Ajustado al (ancho|alto) \(W para cambiar\)$/, (m, a) => `Fit to ${a === 'ancho' ? 'width' : 'height'} (W to toggle)`],
    [/^¿Quitar las (\d+) etiquetas de la lista negra\?$/, 'Remove all $1 tags from the blacklist?'],
    [/^Quitar (.+)$/, 'Remove $1'],
  ];
  function trExact(core) {
    if (EN_DICT.has(core)) return EN_DICT.get(core);
    for (const [re, to] of EN_RE) if (re.test(core)) return core.replace(re, to);
    return core;
  }
  function trEn(raw) {
    const m = /^(\s*)([\s\S]*?)(\s*)$/.exec(raw);
    const core = m[2];
    if (!core) return raw;
    let out = trExact(core);
    if (out === core && core.includes('. ')) {
      const parts = core.split('. '), tr = parts.map(trExact);
      if (tr.some((x, i) => x !== parts[i])) out = tr.join('. ');
    }
    return out === core ? raw : m[1] + out + m[3];
  }
  const readLang = () => { try { return GM_getValue('ui_lang', 'es') === 'en'; } catch { return false; } };
  let EN_ON = readLang();
  const T = s => EN_ON ? trEn(s) : s;

  const I18N_ATTRS = ['title', 'aria-label', 'placeholder', 'alt'];
  const I18N_SCOPE = '[id^="hr-"]:not(html):not(body), [class*="hr-"]:not(html):not(body)';
  const i18nTexts = new WeakMap(), i18nAttrRecs = new WeakMap(), i18nShadows = new Set();
  function i18nScope(n) {
    const e = n.nodeType === 1 ? n : n.parentElement;
    if (!e) return false;
    const r = e.getRootNode();
    if (r !== document) return !!r.host && r.host.id === 'hr-settings-host';
    return !!e.closest(I18N_SCOPE) && !e.closest('#hr-dl');
  }
  // Nombres de etiquetas, títulos y chips son datos, no interfaz: no se tocan
  const i18nSkipText = e => !e.classList.contains('hr-chip-not') && !!e.closest('a:not(.hr-btn), .hr-tag:not(.hr-more), .chip, .hr-chip, [data-keep]');
  function i18nVisitText(n) {
    const cur = n.data, rec = i18nTexts.get(n);
    if (rec && cur === rec.out) { if (!EN_ON) { n.data = rec.es; i18nTexts.delete(n); } return; }
    if (rec) i18nTexts.delete(n);
    if (!EN_ON || !cur.trim() || !i18nScope(n)) return;
    const e = n.parentElement;
    if (e && i18nSkipText(e)) return;
    const out = trEn(cur);
    if (out !== cur) { n.data = out; i18nTexts.set(n, { es: cur, out }); }
  }
  function i18nVisitEl(e) {
    let recs = i18nAttrRecs.get(e), inScope = null;
    for (const a of I18N_ATTRS) {
      if (!e.hasAttribute(a)) continue;
      const cur = e.getAttribute(a), r = recs && recs[a];
      if (r && cur === r.out) { if (!EN_ON) { e.setAttribute(a, r.es); delete recs[a]; } continue; }
      if (r) delete recs[a];
      if (!EN_ON) continue;
      if (inScope === null) inScope = i18nScope(e);
      if (!inScope) return;
      const out = trEn(cur);
      if (out !== cur) { e.setAttribute(a, out); if (!recs) i18nAttrRecs.set(e, recs = {}); recs[a] = { es: cur, out }; }
    }
  }
  function i18nSubtree(root) {
    if (root.nodeType === 3) return i18nVisitText(root);
    if (root.nodeType !== 1 && root.nodeType !== 11) return;
    if (root.nodeType === 1) i18nVisitEl(root);
    const w = document.createTreeWalker(root, 5);
    for (let n = w.nextNode(); n; n = w.nextNode()) n.nodeType === 3 ? i18nVisitText(n) : i18nVisitEl(n);
  }
  const I18N_OPTS = { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: I18N_ATTRS };
  const i18nObs = new MutationObserver(recs => {
    if (!EN_ON) return;
    for (const r of recs) {
      if (r.type === 'childList') r.addedNodes.forEach(i18nSubtree);
      else if (r.type === 'characterData') i18nVisitText(r.target);
      else i18nVisitEl(r.target);
    }
  });
  i18nObs.observe(document.documentElement, I18N_OPTS);
  function i18nWatch(root) {
    i18nShadows.add(root);
    i18nObs.observe(root, I18N_OPTS);
    i18nSubtree(root);
  }
  function i18nRefresh() {
    EN_ON = readLang();
    if (document.body) i18nSubtree(document.body);
    for (const r of i18nShadows) { if (r.host.isConnected) i18nSubtree(r); else i18nShadows.delete(r); }
  }
  document.addEventListener('hr-lang', i18nRefresh);
  if (typeof GM_addValueChangeListener === 'function') GM_addValueChangeListener('ui_lang', () => i18nRefresh());

  function openTab(url) {
    const href = new URL(url, location.href).href;
    handoff(href);
    GM_openInTab(href, { active: S.newTab && S.newTabFocus, insert: true });
  }

  const curPage = () => {
    const n = parseInt(location.hash.slice(1), 10);
    return Number.isFinite(n) && n > 0 ? n : 1;
  };

  function pageCount() {
    const n = W.galleryinfo?.files?.length;
    if (n) return n;
    let max = 0;
    document.querySelectorAll('select').forEach(s => {
      for (const o of s.options) {
        const v = parseInt((o.value || o.textContent).replace(/\D+/g, ''), 10);
        if (Number.isFinite(v)) max = Math.max(max, v);
      }
    });
    return max || Infinity;
  }

  function goToPage(n) {
    n = Math.max(1, Math.min(n, pageCount()));
    if (n === curPage()) return;
    location.replace('#' + n);
  }

  function goBack() {
    const ref = document.referrer;
    let sameSite = false;
    try { sameSite = ref && new URL(ref).hostname === location.hostname && !ref.includes('/reader/'); } catch {}
    if (sameSite && history.length > 1) history.back();
    else location.href = document.querySelector('.navbar a.brand')?.href || `/galleries/${readerGalleryId()}.html`;
  }

  window.addEventListener('keydown', e => {
    if (!isReader()) return;
    if (e.target instanceof Element && e.target.closest('input, textarea, select, [contenteditable], dialog, #hr-settings-host')) return;
    if (e.altKey || e.ctrlKey || e.metaKey) return;
    if (menu || dlg?.open || document.querySelector('dialog[open]')) return;

    let target = null;
    const k = e.key.toLowerCase();
    if (k === 'arrowright' || k === 'd') target = curPage() + (S.rightArrowIsNext ? 1 : -1);
    else if (k === 'arrowleft' || k === 'a') target = curPage() + (S.rightArrowIsNext ? -1 : 1);
    else if (k === 'home') target = 1;
    else if (k === 'end') target = pageCount();
    else if (k === 't') { setStripHidden(!stripHidden); applyLayout(); }
    else if (k === '=' || k === '+') setZoom(S.zoom + 5);
    else if (k === '-') setZoom(S.zoom - 5);
    else if (k === '0') setZoom(100);
    else if (k === 'f') toggleFullscreen();
    else if (k === 'w' && wantReaderUi()) toggleFit();
    else if (k === 'escape' && S.escBack) goBack();
    else return;

    e.preventDefault(); e.stopImmediatePropagation();
    if (target !== null) goToPage(target);
  }, true);

  document.addEventListener('click', e => {
    if (!isReader() || e.button !== 0) return;
    const a = e.target instanceof Element && e.target.closest('a[href^="#"]');
    if (!a) return;
    const n = parseInt(a.getAttribute('href').slice(1), 10);
    if (!Number.isFinite(n)) return;
    e.preventDefault(); e.stopImmediatePropagation();
    goToPage(n);
  }, true);

  window.addEventListener('click', e => {
    if (!isReader() || !S.clickHalves || e.button !== 0) return;
    const box = e.target instanceof Element && e.target.closest('#comicImages');
    if (!box || getSelection().toString()) return;
    e.preventDefault(); e.stopImmediatePropagation();
    const r = box.getBoundingClientRect();
    const rightHalf = e.clientX >= r.left + r.width / 2;
    goToPage(curPage() + (rightHalf ? 1 : -1));
  }, true);

  // Rueda del ratón: cambia de página. Si la imagen es más grande que la vista (zoom / ajuste al ancho),
  // primero se desplaza y solo pasa de página al llegar al borde.
  let wheelLock = 0;
  window.addEventListener('wheel', e => {
    if (!isReader() || !S.wheelPages) return;
    if (e.ctrlKey || e.altKey || e.metaKey || e.shiftKey || !e.deltaY || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
    if (!(e.target instanceof Element) || e.target.closest('#hr-strip, #hr-rbar, #hr-menu, #hr-settings-host, dialog, input, textarea, select')) return;
    if (menu || dlg?.open || document.querySelector('dialog[open]')) return;
    const down = e.deltaY > 0;
    const box = document.getElementById('comicImages');
    const sc = box && box.scrollHeight - box.clientHeight > 2 ? box : document.scrollingElement;
    if (sc && sc.scrollHeight - sc.clientHeight > 2) {
      const atEdge = down ? sc.scrollTop + sc.clientHeight >= sc.scrollHeight - 2 : sc.scrollTop <= 0;
      if (!atEdge) return;
    }
    e.preventDefault(); e.stopImmediatePropagation();
    const now = Date.now();
    if (now < wheelLock) return;
    const target = curPage() + (down ? 1 : -1);
    if (target < 1 || target > pageCount()) return;
    wheelLock = now + 250;
    goToPage(target);
    const fix = () => { if (sc) sc.scrollTop = down ? 0 : sc.scrollHeight; };
    requestAnimationFrame(fix); setTimeout(fix, 80);
  }, { capture: true, passive: false });

  const PAGE_PATCH = `(() => {
    const fix = (id, two) => {
      const sel = document.getElementById(id);
      if (!sel || typeof sel.onchange !== 'function') return;
      const orig = sel.onchange;
      sel.onchange = function (e) {
        try {
          const val = String(this.value);
          const parts = val.split('-');
          const first = parseInt(parts[0], 10);
          const last = two && parts[1] ? parseInt(parts[1], 10) : first;
          const total = our_galleryinfo.length;
          enable($('#prevPanel')); enable($('#nextPanel'));
          if (first <= 1) disable($('#prevPanel'));
          if (last >= total) disable($('#nextPanel'));
          if (!two) {
            enable($('#prevScene')); enable($('#nextScene'));
            if (at_first_scene()) disable($('#prevScene'));
            if (at_last_scene()) disable($('#nextScene'));
          }
          curPanel = two ? String(first) : val;
          location.replace('#' + val);
          $(this).trigger('blur');
        } catch (err) {
          console.warn('[hitomi-enhanced] falling back to the site page handler', err);
          return orig.call(this, e);
        }
      };
    };
    fix('single-page-select', false);
    fix('two-page-select', true);
  })();`;

  function patchReader() {
    const s = document.createElement('script');
    s.textContent = PAGE_PATCH;
    document.documentElement.append(s);
    s.remove();

    if (!S.rightArrowIsNext) return;
    const swap = (a, b) => {
      const A = document.getElementById(a), B = document.getElementById(b);
      if (!A || !B) return;
      A.id = b; B.id = a;
      return [A, B];
    };
    const p = swap('nextPanel', 'prevPanel');
    if (p) {
      p[0].innerHTML = '<i class="icon-chevron-left icon-white"></i> ' + T('Anterior');
      p[0].title = T('Flecha izquierda');
      p[1].innerHTML = T('Siguiente') + ' <i class="icon-chevron-right icon-white"></i>';
      p[1].title = T('Flecha derecha');
    }
    swap('nextScene', 'prevScene');
  }

  function setZoom(v) {
    S.zoom = Math.max(10, Math.min(300, Math.round(+v || 100)));
    saveSettings();
    document.documentElement.style.setProperty('--hr-zoom', S.zoom / 100);
    syncZoomBox();
  }
  function syncZoomBox() {
    const box = document.getElementById('hr-zoom');
    if (box && document.activeElement !== box) box.value = S.zoom;
    const out = document.getElementById('hr-zoom-out');
    if (out) out.textContent = S.zoom + '%';
  }

  function addZoomBox(ul) {
    const input = el('input', { id: 'hr-zoom', type: 'number', min: 10, max: 300, step: 5, value: S.zoom, title: 'Tamaño de la imagen, % de la pantalla (+ / - / 0)' });
    input.addEventListener('keydown', e => {
      e.stopPropagation();
      if (e.key === 'Enter' || e.key === 'Escape') input.blur();
    });
    input.addEventListener('input', () => { if (input.value) setZoom(input.value); });
    input.addEventListener('change', () => { setZoom(input.value); input.value = S.zoom; });
    ul.append(el('li', { className: 'hr-nav-li' }, el('label', { htmlFor: 'hr-zoom' }, 'Tamaño ', input, ' %')));
  }

  function pageBoxEl(word) {
    const input = el('input', { id: 'hr-page', type: 'number', min: 1, step: 1, value: curPage(), title: 'Escribe un número de página y pulsa Intro' });
    input.setAttribute('aria-label', 'Página');
    const total = el('span', { id: 'hr-total', textContent: '…' });
    input.addEventListener('keydown', e => {
      e.stopPropagation();
      if (e.key === 'Enter') { goToPage(+input.value || 1); input.blur(); }
      else if (e.key === 'Escape') input.blur();
    });
    input.addEventListener('change', () => goToPage(+input.value || 1));
    input.addEventListener('blur', updatePageBox);
    window.addEventListener('hashchange', updatePageBox);
    waitFor(() => W.galleryinfo?.files?.length, 15000).then(updatePageBox);
    return word
      ? el('label', { htmlFor: 'hr-page' }, 'Página ', input, ' / ', total)
      : el('label', { htmlFor: 'hr-page', className: 'hr-pagebox' }, input, el('span', { textContent: '/' }), total);
  }

  function addPageBox(ul) {
    ul.append(el('li', { className: 'hr-nav-li' }, pageBoxEl(true)));
    updatePageBox();
  }

  function updatePageBox() {
    const input = document.getElementById('hr-page');
    const total = document.getElementById('hr-total');
    const n = pageCount();
    const bar = document.querySelector('#hr-progress i');
    if (bar) bar.style.width = Number.isFinite(n) ? Math.min(100, curPage() / n * 100) + '%' : '0';
    const pc = document.getElementById('hr-pcount');
    if (pc) pc.textContent = curPage() + (Number.isFinite(n) ? ' / ' + n : '');
    if (!input) return;
    if (Number.isFinite(n)) { total.textContent = n; input.max = n; }
    if (document.activeElement !== input) input.value = curPage();
  }

  function galleryIdFromLink(a) {
    try {
      const u = new URL(a.dataset.hrInfo || a.href);
      if (u.hostname !== location.hostname) return null;
      return (u.pathname.match(GALLERY_RE) || [])[1] || null;
    } catch { return null; }
  }

  function rewrite(a) {
    if (!S.openInReader || isReader() || a.dataset.hrInfo) return;
    const id = galleryIdFromLink(a);
    if (!id || id === pageGalleryId) return;
    a.dataset.hrInfo = a.href;
    a.href = readerUrl(id);
  }
  for (const ev of ['pointerover', 'focusin', 'touchstart']) {
    document.addEventListener(ev, e => {
      const a = e.target instanceof Element && e.target.closest('a[href]');
      if (a) rewrite(a);
    }, { capture: true, passive: true });
  }

  document.addEventListener('click', e => {
    if (isReader() || !S.newTab || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
    const a = e.target instanceof Element && e.target.closest('a[href]');
    if (!a) return;
    const id = galleryIdFromLink(a);
    if (!id || id === pageGalleryId) return;
    rewrite(a);
    e.preventDefault(); e.stopImmediatePropagation();
    openTab(a.href);
  }, true);

  document.addEventListener('mousedown', e => {
    const newTabGesture = e.button === 1 || e.button === 2 || (e.button === 0 && (e.ctrlKey || e.metaKey || e.shiftKey));
    if (!newTabGesture) return;
    const a = e.target instanceof Element && e.target.closest('a[href]');
    if (!a) return;
    rewrite(a);
    handoff(a.href);
  }, true);

  const TERM_RE = /^\/(tag|artist|series|character|group|type)\/(.+?)-(all|[a-z]+)(?:-\d+)?\.html$/;
  function termFromUrl(u) {
    if (u.hostname !== location.hostname) return null;
    let m = u.pathname.match(TERM_RE);
    if (m) {
      const ns = m[1];
      let val;
      try { val = decodeURIComponent(m[2]); } catch { return null; }
      val = val.trim().replace(/\s+/g, '_');
      if (ns === 'tag') return /^(fe)?male:/.test(val) ? val : 'tag:' + val;
      return `${ns}:${val}`;
    }
    m = u.pathname.match(/^\/index-([a-z]+)(?:-\d+)?\.html$/);
    if (m && m[1] !== 'all') return 'language:' + m[1];
    return null;
  }
  function termFromLink(a) {
    try { return termFromUrl(new URL(a.href)); } catch { return null; }
  }

  function normTerm(s) {
    let t = String(s).trim().toLowerCase().replace(/^-/, '').replace(/\s+/g, '_');
    if (!t) return '';
    if (!/^(tag|female|male|artist|series|character|group|type|language):./.test(t)) t = 'tag:' + t;
    return t;
  }

  const QKEY = 'hr-query';
  const HKEY = 'hr-handoff';
  const HANDOFF_MS = 60000;
  const hasQuery = () => { try { return sessionStorage.getItem(QKEY) !== null; } catch { return false; } };
  const load = () => { try { return JSON.parse(sessionStorage.getItem(QKEY)) || []; } catch { return []; } };
  const store = t => { try { sessionStorage.setItem(QKEY, JSON.stringify(t)); } catch {} };
  const save = t => { store(t); renderPanel(); };
  const pathKey = u => u.pathname + u.search;

  function handoff(url) {
    const terms = load();
    if (!terms.length) return;
    let u;
    try { u = new URL(url, location.href); } catch { return; }
    if (u.hostname !== location.hostname) return;
    const now = Date.now();
    const map = {};
    for (const [k, v] of Object.entries(GM_getValue(HKEY, {}))) if (now - v.t < HANDOFF_MS) map[k] = v;
    map[pathKey(u)] = { terms, t: now };
    GM_setValue(HKEY, map);
  }

  if (!hasQuery()) {
    const h = GM_getValue(HKEY, {})[pathKey(location)];
    if (h && Date.now() - h.t < HANDOFF_MS) store(h.terms);
  }

  function pageQuery() {
    if (location.pathname === '/search.html') {
      if (location.search.length < 2) return null;
      try {
        const q = decodeURIComponent(location.search.slice(1)).split(/\s+/).filter(Boolean);
        return q.length ? q : null;
      } catch { return null; }
    }
    const m = location.pathname.match(TERM_RE);
    if (m) {
      const t = termFromUrl(new URL(location.href));
      if (!t) return null;
      return m[3] !== 'all' ? [t, 'language:' + m[3]] : [t];
    }
    const lm = location.pathname.match(/^\/index-([a-z]+)(?:-\d+)?\.html$/);
    if (lm && lm[1] !== 'all') return ['language:' + lm[1]];
    return null;
  }
  {
    const pq = pageQuery();
    if (pq) store(pq);
  }

  const bare = t => t.replace(/^-/, '');
  function addTerm(term, exclude) {
    const t = load().filter(x => bare(x) !== term);
    t.push(exclude ? '-' + term : term);
    save(t);
  }
  const searchUrl = terms => '/search.html?' + encodeURIComponent(terms.join(' '));

  const BL_KEY = 'hr-blacklist';
  let blacklist = GM_getValue(BL_KEY, []);
  function setBlacklist(list) {
    blacklist = [...new Set(list.map(normTerm).filter(Boolean))].sort();
    GM_setValue(BL_KEY, blacklist);
    blacklistChanged();
  }
  const blAdd = t => setBlacklist([...blacklist, t]);
  const blRemove = t => setBlacklist(blacklist.filter(x => x !== t));
  const blacklistChanged = () => { scanCards(); renderBlacklist(); };

  onRemote(BL_KEY, n => { blacklist = n || []; blacklistChanged(); });
  onRemote(SKEY, n => { Object.assign(S, DEFAULTS, n); applyTheme(); applyLayout(); syncUi(); scanCards(); });

  // ============================================================================
  // Favoritos: galerías guardadas con portada, título, artistas y etiquetas (GM «hr-favorites»,
  // compartido entre pestañas). La portada también se guarda como miniatura propia («hr-favimg-<id>»)
  // porque las direcciones de las miniaturas del sitio pueden cambiar con el tiempo.
  // ============================================================================
  const FAV_KEY = 'hr-favorites', FAVIMG = 'hr-favimg-', FAV_STEP = 60;
  const FAV_SORTS = [['new', 'Añadidas recientemente'], ['old', 'Añadidas hace más tiempo'], ['title', 'Título (A–Z)'], ['artist', 'Artista (A–Z)']];
  const favRead = v => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
  let favs = favRead(GM_getValue(FAV_KEY, {}));
  // Listas personalizadas de favoritos: definiciones en «hr-favlists»; cada favorito guarda los ids de sus listas en «lists»
  const FL_KEY = 'hr-favlists';
  const flRead = v => (Array.isArray(v) ? v.filter(x => x && typeof x.id === 'string' && typeof x.name === 'string' && x.name.trim())
    .map(x => ({ id: x.id.slice(0, 40), name: x.name.trim().slice(0, 60) })) : []);
  let favLists = flRead(GM_getValue(FL_KEY, []));
  // Artistas, grupos, series, personajes y etiquetas favoritos: clave = término de búsqueda («artist:nombre»)
  const FT_KEY = 'hr-favterms';
  let favTerms = favRead(GM_getValue(FT_KEY, {}));
  const favHas = id => !!id && Object.prototype.hasOwnProperty.call(favs, String(id));
  const favIds = () => Object.keys(favs);
  const favView = () => location.hash === '#hr-favoritos';
  const favImg = id => { try { return GM_getValue(FAVIMG + id, '') || ''; } catch { return ''; } };
  const favSave = () => GM_setValue(FAV_KEY, favs);
  const pathOf = h => { try { const u = new URL(h, location.href); return u.pathname + u.search; } catch { return ''; } };
  const favSlim = x => (x && x.text ? { text: String(x.text), href: pathOf(x.href), term: String(x.term || '') } : null);

  // Quita las miniaturas de favoritos que ya no existen (p. ej. tras un «Deshacer» que no llegó a usarse)
  try { for (const k of GM_listValues()) if (k.startsWith(FAVIMG) && !favHas(k.slice(FAVIMG.length))) GM_deleteValue(k); } catch {}

  function favEntry(c, lists) {
    return {
      id: String(c.id), href: pathOf(c.href), title: c.title || 'Sin título',
      covers: (c.covers || []).filter(u => !/^data:/.test(u)).slice(0, 3),
      artists: (c.artists || []).map(favSlim).filter(Boolean), series: (c.series || []).map(favSlim).filter(Boolean),
      tags: (c.tags || []).slice(0, 80).map(favSlim).filter(Boolean),
      type: favSlim(c.type), lang: favSlim(c.lang), t: Date.now(), lists: (lists || []).slice(), pages: c.pages > 0 ? c.pages | 0 : 0,
    };
  }

  // Valida una entrada importada de un archivo: solo rutas del propio sitio y campos con el tipo esperado
  function favClean(v) {
    if (!v || typeof v !== 'object' || !/^\d+$/.test(String(v.id))) return null;
    const str = (x, n) => (typeof x === 'string' ? x.slice(0, n) : '');
    const path = x => { try { const u = new URL(str(x, 500), location.origin); return u.origin === location.origin ? u.pathname + u.search : ''; } catch { return ''; } };
    const link = x => (x && typeof x === 'object' && str(x.text, 120) ? { text: str(x.text, 120), href: path(x.href), term: str(x.term, 160) } : null);
    const links = a => (Array.isArray(a) ? a.slice(0, 80).map(link).filter(Boolean) : []);
    return {
      id: String(v.id), href: path(v.href) || `/galleries/${v.id}.html`, title: str(v.title, 300) || 'Sin título',
      covers: Array.isArray(v.covers) ? v.covers.filter(u => typeof u === 'string' && /^https?:\/\//.test(u)).slice(0, 3) : [],
      artists: links(v.artists), series: links(v.series), tags: links(v.tags), type: link(v.type), lang: link(v.lang),
      lists: Array.isArray(v.lists) ? v.lists.filter(x => typeof x === 'string').slice(0, 60) : [],
      pages: Number.isFinite(+v.pages) && +v.pages > 0 ? Math.min(+v.pages | 0, 99999) : 0,
      t: Number.isFinite(+v.t) && +v.t > 0 ? +v.t : Date.now(),
    };
  }

  // Datos de una galería a partir de «galleryinfo» (página de la galería y lector)
  function favInfoData(g, id, covers) {
    const named = (list, key, path) => (list || []).map(x => ({
      text: x[key], href: x.url || `/${path}/${encodeURIComponent(x[key])}-all.html`, term: `${path}:${String(x[key]).replace(/\s+/g, '_')}`,
    }));
    const tags = (g.tags || []).map(t => {
      const f = +t.female === 1 || t.female === true, m = +t.male === 1 || t.male === true;
      const pre = f ? 'female:' : m ? 'male:' : '';
      return { text: t.tag + (f ? ' ♀' : m ? ' ♂' : ''), href: t.url || `/tag/${encodeURIComponent(pre + t.tag)}-all.html`,
        term: (pre || 'tag:') + String(t.tag).replace(/\s+/g, '_') };
    });
    return {
      id: String(id), href: `/galleries/${id}.html`, title: g.title || 'Sin título', covers,
      artists: [...named(g.artists, 'artist', 'artist'), ...named(g.groups, 'group', 'group')],
      series: named(g.parodys, 'parody', 'series'), tags,
      type: g.type ? { text: g.type, href: `/type/${encodeURIComponent(g.type)}-all.html`, term: 'type:' + g.type } : null,
      lang: g.language ? { text: g.language_localname || g.language, href: `/index-${g.language}.html`, term: 'language:' + g.language } : null,
    };
  }

  function readerFavData() {
    const g = W.galleryinfo, id = readerGalleryId();
    if (!g || !g.files || !id) return null;
    const tn = (f, k) => { try { return W.url_from_url_from_hash(id, f, k, 'webp', 'tn'); } catch { return null; } };
    const f = g.files[0];
    const covers = f && typeof W.url_from_url_from_hash === 'function' ? [tn(f, 'webpbigtn'), tn(f, 'webpsmalltn')].filter(Boolean) : [];
    return favInfoData(g, id, covers);
  }

  // De una entrada guardada a los datos que usa cardEl: la tarjeta se ve igual que las del sitio
  function favToCard(f) {
    const abs = x => (x ? { ...x, href: new URL(x.href, location.origin).href } : null);
    const img = favImg(f.id);
    return {
      id: f.id, href: new URL(f.href, location.origin).href, title: f.title,
      covers: [...(img ? [img] : []), ...(f.covers || [])],
      artists: (f.artists || []).map(abs), series: (f.series || []).map(abs), tags: (f.tags || []).map(abs),
      type: abs(f.type), lang: abs(f.lang), hit: '', pages: f.pages || 0,
    };
  }

  // Miniatura propia de la portada: se descarga y se reduce una sola vez (máximo 2 a la vez)
  const favQueue = [];
  let favBusy = 0;
  function favCache(id) {
    id = String(id);
    if (!favHas(id) || favImg(id) || favQueue.includes(id)) return;
    favQueue.push(id);
    favPump();
  }
  function favPump() {
    while (favBusy < 2 && favQueue.length) {
      const id = favQueue.shift(), f = favs[id];
      if (!f || !f.covers || !f.covers.length || favImg(id)) continue;
      favBusy++;
      const done = () => { favBusy--; favPump(); };
      const attempt = k => {
        if (k >= f.covers.length) return done();
        GM_xmlhttpRequest({
          method: 'GET', url: f.covers[k], responseType: 'blob', headers: { Referer: location.origin + '/' },
          onload: async r => {
            try {
              const bmp = await createImageBitmap(r.response);
              const w = Math.min(320, bmp.width), h = Math.max(1, Math.round(bmp.height * w / bmp.width));
              const cv = document.createElement('canvas');
              cv.width = w; cv.height = h;
              cv.getContext('2d').drawImage(bmp, 0, 0, w, h);
              if (bmp.close) bmp.close();
              if (favHas(id)) GM_setValue(FAVIMG + id, cv.toDataURL('image/jpeg', 0.82));
              done();
            } catch { attempt(k + 1); }
          },
          onerror: () => attempt(k + 1), ontimeout: () => attempt(k + 1),
        });
      };
      attempt(0);
    }
  }

  // Aviso con «Deshacer» (reutiliza el aviso breve de hrToast)
  function favToast(text, undo) {
    hrToast(text);
    if (!undo || !hrToastEl) return;
    const b = el('button', { type: 'button', textContent: T('Deshacer') });
    b.style.cssText = 'margin-left:12px;padding:0;border:0;background:none;color:var(--hr-accent,#6d72d8);font:600 14px/1.3 system-ui,sans-serif;cursor:pointer;';
    const hide = () => { hrToastEl.style.opacity = '0'; hrToastEl.style.pointerEvents = 'none'; };
    b.onclick = () => { undo(); hide(); };
    hrToastEl.append(b);
    hrToastEl.style.pointerEvents = 'auto';
    clearTimeout(hrToastTimer);
    hrToastTimer = setTimeout(hide, 5000);
  }

  function favAdd(c, lists) {
    if (!c || !c.id) return;
    favs[c.id] = favEntry(c, lists);
    favSave();
    favCache(c.id);
    favsChanged();
    hrToast(T('Añadida a favoritos'));
  }
  function favRemove(id) {
    id = String(id);
    const old = favs[id];
    if (!old) return;
    delete favs[id];
    favSave();
    favsChanged();
    favToast(T('Quitada de favoritos'), () => { favs[id] = old; favSave(); favCache(id); favsChanged(); });
    setTimeout(() => { if (!favHas(id)) try { GM_deleteValue(FAVIMG + id); } catch {} }, 7000);
  }

  const favToggle = c => { if (c && c.id) favHas(c.id) ? favRemove(c.id) : favAdd(c); };

  // ---- Listas: crear, renombrar, eliminar y asignar galerías ----
  const flSave = () => GM_setValue(FL_KEY, favLists);
  const flChanged = () => { if (appRefs && appRefs.mode === 'list' && favView()) { gridSig = ''; renderApp(); } paintFavs(); };
  onRemote(FL_KEY, n => { favLists = flRead(n); flChanged(); });
  function flNew(name) {
    name = String(name || '').trim().slice(0, 60);
    if (!name) return null;
    const ex = favLists.find(l => l.name.toLowerCase() === name.toLowerCase());
    if (ex) return ex;
    const l = { id: 'l' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), name };
    favLists.push(l);
    flSave();
    flChanged();
    return l;
  }
  function flRename(id, name) {
    name = String(name || '').trim().slice(0, 60);
    const l = favLists.find(x => x.id === id);
    if (!l || !name || l.name === name) return;
    if (favLists.some(x => x.id !== id && x.name.toLowerCase() === name.toLowerCase())) { hrToast(T('Ya existe una lista con ese nombre')); return; }
    l.name = name;
    flSave();
    flChanged();
  }
  function flDelete(id) {
    favLists = favLists.filter(l => l.id !== id);
    for (const f of Object.values(favs)) if (f.lists) f.lists = f.lists.filter(x => x !== id);
    favSave();
    flSave();
    if (appRefs && appRefs.favL === id) appRefs.favL = '';
    flChanged();
  }
  const flHas = (gid, lid) => !!(favs[gid] && favs[gid].lists && favs[gid].lists.includes(lid));
  // Asignar a una lista una galería que aún no es favorita la añade a favoritos
  function flSet(c, lid, on) {
    if (!favHas(c.id)) { if (on) favAdd(c, [lid]); return; }
    const f = favs[c.id], s = new Set(f.lists || []);
    if (on) s.add(lid); else s.delete(lid);
    f.lists = [...s];
    favSave();
    favsChanged();
  }
  function paintLst(b) {
    const f = favs[b.dataset.lstId];
    b.classList.toggle('on', !!(f && (f.lists || []).some(x => favLists.some(l => l.id === x))));
  }

  // ---- Favoritos de artistas, grupos, series, personajes y etiquetas ----
  const FT_GROUPS = [['', 'Todos'], ['artist', 'Artistas'], ['group', 'Grupos'], ['series', 'Series'], ['character', 'Personajes'], ['tag', 'Etiquetas'], ['other', 'Otros']];
  const ftFind = t => Object.keys(favTerms).find(k => k.toLowerCase() === String(t).toLowerCase());
  const ftHas = t => !!ftFind(t);
  const ftName = t => String(t).slice(String(t).indexOf(':') + 1).replace(/_/g, ' ');
  const ftSave = () => GM_setValue(FT_KEY, favTerms);
  const ftGroup = t => ({ artist: 'artist', group: 'group', series: 'series', character: 'character', tag: 'tag', female: 'tag', male: 'tag' })[String(t).split(':')[0]] || 'other';
  function ftClean(v) {
    if (!v || typeof v.term !== 'string' || v.term.length > 200 || !/^(tag|female|male|artist|series|character|group|type|language):./.test(v.term)) return null;
    let href = '';
    try { const u = new URL(String(v.href || ''), location.origin); if (u.origin === location.origin) href = u.pathname + u.search; } catch {}
    return { term: v.term, text: ftName(v.term), href: href || searchUrl([v.term]), t: Number.isFinite(+v.t) && +v.t > 0 ? +v.t : Date.now() };
  }
  function paintTermFav() {
    const b = appRefs && appRefs.termFav;
    if (!b || !b.dataset.term) return;
    const on = ftHas(b.dataset.term);
    b.classList.toggle('on', on);
    b.setAttribute('aria-pressed', String(on));
    setText(b.lastChild, on ? 'En favoritos' : 'Añadir a favoritos');
  }
  function ftChanged() {
    paintTermFav();
    if (appRefs && appRefs.mode === 'list' && favView()) { gridSig = ''; appRefs.tabSig = ''; renderApp(); }
  }
  onRemote(FT_KEY, n => { favTerms = favRead(n); ftChanged(); });
  function ftAdd(term, href) {
    if (ftHas(term)) return;
    favTerms[term] = { term, text: ftName(term), href: pathOf(href) || searchUrl([term]), t: Date.now() };
    ftSave();
    ftChanged();
    hrToast(T('Añadido a favoritos'));
  }
  function ftRemove(term) {
    const k = ftFind(term);
    if (!k) return;
    const old = favTerms[k];
    delete favTerms[k];
    ftSave();
    ftChanged();
    favToast(T('Quitado de favoritos'), () => { favTerms[k] = old; ftSave(); ftChanged(); });
  }
  const ftToggle = (term, href) => (ftHas(term) ? ftRemove(term) : ftAdd(term, href));
  const termPageKey = () => (TERM_RE.test(location.pathname) ? termFromUrl(new URL(location.href)) || '' : '');

  function renderFavTabs(R) {
    R.tabbar.hidden = false;
    R.termFav.hidden = true;
    const ng = favIds().length, nt = Object.keys(favTerms).length, sig = ng + '|' + nt + '|' + R.favTab;
    if (sig === R.tabSig) return;
    R.tabSig = sig;
    const tab = (key, label, n) => {
      const b = el('button', { type: 'button', className: 'hr-lchip' + (R.favTab === key ? ' on' : '') }, el('span', { textContent: label }), el('small', { textContent: String(n) }));
      b.setAttribute('aria-pressed', String(R.favTab === key));
      b.onclick = () => { R.favTab = key; R.favShown = FAV_STEP; gridSig = ''; R.tabSig = ''; renderApp(); };
      return b;
    };
    R.tabbar.replaceChildren(tab('g', 'Galerías', ng), tab('t', 'Artistas y más', nt));
  }

  // Contenido de cada artista / grupo / etiqueta favorito: ids con la búsqueda del sitio y datos de cada obra desde «galleries/<id>.js»
  const FT_PAGE = 24;
  const ftData = new Map();
  const ftInfoQ = [];
  let ftInfoBusy = 0, ftGgP = null, ftKickT = 0;
  const ftWait = ms => new Promise(r => setTimeout(r, ms));
  function ftGg() {
    if (typeof W.url_from_url_from_hash !== 'function') return Promise.reject(new Error('no url fn'));
    if (W.gg) return Promise.resolve();
    return ftGgP || (ftGgP = new Promise((res, rej) => {
      const sc = document.createElement('script');
      sc.src = '//' + W.domain + '/gg.js';
      sc.onload = () => res();
      sc.onerror = () => { ftGgP = null; rej(new Error('gg')); };
      document.head.appendChild(sc);
    }));
  }
  // Plan B si la búsqueda del sitio no está disponible: primeras 1000 obras del archivo .nozomi
  async function ftIdsNozomi(term) {
    const i = term.indexOf(':'), ns = term.slice(0, i), name = term.slice(i + 1).replace(/_/g, ' ');
    const area = /^(tag|female|male)$/.test(ns) ? 'tag' : ns, tag = ns === 'female' || ns === 'male' ? ns + ':' + name : name;
    const file = encodeURIComponent(area) + '/' + encodeURIComponent(tag).replace(/%3A/gi, ':') + '-all.nozomi';
    for (const pre of ['n/', '']) {
      try {
        const r = await fetch('//' + W.domain + '/' + pre + file, { headers: { Range: 'bytes=0-3999' } });
        if (!r.ok) continue;
        const buf = await r.arrayBuffer(), dv = new DataView(buf), ids = [];
        for (let o = 0; o + 4 <= buf.byteLength; o += 4) ids.push(dv.getInt32(o));
        return ids;
      } catch {}
    }
    throw new Error('nozomi');
  }
  async function ftIds(term) {
    if (typeof W.get_galleryids_for_query === 'function') {
      try {
        const ids = await W.get_galleryids_for_query(term);
        if (ids && typeof ids.length === 'number') return Array.from(ids, Number).filter(Number.isFinite);
      } catch (e) { console.warn('[Hitomi Enhanced] get_galleryids_for_query falló para', term, e); }
    }
    try { return await ftIdsNozomi(term); } catch (e) { console.warn('[Hitomi Enhanced] nozomi falló para', term, e); throw e; }
  }
  async function ftInfo(id) {
    let last;
    for (let i = 0; i < 3; i++) {
      try {
        await ftGg();
        const r = await fetch('//' + W.domain + '/galleries/' + id + '.js');
        if (!r.ok) throw new Error('HTTP ' + r.status);
        const t = await r.text(), g = JSON.parse(t.slice(t.indexOf('=') + 1).trim().replace(/;$/, ''));
        g.id = g.id || id;
        const tn = (f, k) => { try { return W.url_from_url_from_hash(id, f, k, 'webp', 'tn'); } catch { return null; } };
        const f0 = (g.files || [])[0];
        const covers = f0 ? [tn(f0, 'webpbigtn'), tn(f0, 'webpsmalltn')].filter(Boolean) : [];
        const c = favToCard({ ...favInfoData(g, id, covers), t: 0 });
        c.pages = (g.files || []).length;
        return c;
      } catch (e) { last = e; await ftWait(400 * (i + 1)); }
    }
    throw last;
  }
  function ftKick() {
    clearTimeout(ftKickT);
    ftKickT = setTimeout(() => {
      const R = appRefs;
      if (R && R.mode === 'list' && favView() && R.favTab === 't' && R.favTerm && R.tcStatus && R.tcStatus.isConnected) renderTermContent(R, false);
    }, 100);
  }
  function ftLoad(term) {
    let d = ftData.get(term);
    if (!d) {
      d = { ids: null, err: false, info: new Map(), pend: new Set() };
      ftData.set(term, d);
      ftIds(term).then(ids => { d.ids = ids; ftKick(); }, () => { d.err = true; ftKick(); });
    }
    return d;
  }
  function ftWant(id, d) {
    if (d.info.has(id) || d.pend.has(id)) return;
    d.pend.add(id);
    ftInfoQ.push([id, d]);
    ftInfoPump();
  }
  function ftInfoPump() {
    while (ftInfoBusy < 4 && ftInfoQ.length) {
      const [id, d] = ftInfoQ.shift();
      ftInfoBusy++;
      ftInfo(id).then(c => d.info.set(id, c), () => d.info.set(id, null)).finally(() => { d.pend.delete(id); ftInfoBusy--; ftKick(); ftInfoPump(); });
    }
  }

  // ---- Vista previa al pasar el cursor por las portadas en Favoritos (opción «Vista previa en Favoritos» en Ajustes) ----
  // Propia de esta sección: no depende del código del descargador. Usa los mismos ajustes de tamaño, espera, rueda y teclas.
  const FPV = { mw: 0, mh: 0, box: null, item: null, timer: 0, token: 0, gi: null, idx: 0, side: '', cache: new Map(), pos: new Map(), last: 0 };
  const fpvOn = () => favView() && GM_getValue('pv_fav', '1') === '1';
  const fpvId = card => {
    const a = card.querySelector('a.hr-cover-link, a.hr-title'), m = a && (a.dataset.hrInfo || a.href).match(/(?:-|\/)([0-9]+)\.html/);
    return m ? m[1] : '';
  };
  function fpvBox() {
    if (FPV.box && FPV.box.isConnected) return FPV.box;
    const box = el('div', { id: 'hr-fpv' }), img = el('img', { className: 'fpv-img', alt: '' }), msg = el('div', { className: 'fpv-msg' }), cnt = el('div', { className: 'fpv-count' });
    box.style.cssText = 'position:fixed;left:0;top:0;width:max-content;z-index:2147482000;display:none;flex-direction:column;justify-content:center;pointer-events:none;box-sizing:border-box;max-width:calc(100vw - 16px);padding:6px;background:rgba(22,22,22,.97);color:#ddd;border:1px solid rgba(255,255,255,.15);border-radius:10px;box-shadow:0 6px 24px rgba(0,0,0,.6);font:13px/1.4 system-ui,sans-serif;';
    img.style.cssText = 'display:none;max-width:100%;max-height:calc(100vh - 80px);margin:0 auto;border-radius:6px;';
    msg.style.cssText = 'padding:10px 14px;text-align:center;';
    cnt.style.cssText = 'text-align:center;opacity:.8;margin-top:4px;';
    box.append(img, msg, cnt);
    document.body.appendChild(box);
    img.addEventListener('load', fpvPlace);
    return FPV.box = box;
  }
  function fpvHide() {
    if (FPV.gi && FPV.gi.id) FPV.pos.set(String(FPV.gi.id), FPV.idx);
    clearTimeout(FPV.timer);
    FPV.token++; FPV.item = null; FPV.gi = null; FPV.idx = 0; FPV.side = ''; FPV.mw = FPV.mh = 0;
    if (FPV.box) { FPV.box.style.display = 'none'; FPV.box.style.minWidth = FPV.box.style.minHeight = ''; }
  }
  const fpvRect = () => { const it = FPV.item; return it && it.isConnected ? (it.querySelector('.hr-cover') || it).getBoundingClientRect() : null; };
  function fpvAvail() {
    const r = fpvRect(), vw = document.documentElement.clientWidth;
    if (!r) return vw - 30;
    if (!FPV.side) FPV.side = vw - r.right >= r.left ? 'r' : 'l';
    const room = (FPV.side === 'r' ? vw - r.right : r.left) - 10 - 8 - 14;
    return room >= 160 ? room : vw - 30;
  }
  function fpvPlace() {
    const box = FPV.box;
    if (!box || !FPV.item || box.style.display === 'none') return;
    const r = fpvRect();
    if (!r) return fpvHide();
    // La caja nunca se encoge mientras ves una obra: si una página es más pequeña, la imagen queda centrada en el mismo sitio
    if (FPV.mw) box.style.minWidth = FPV.mw + 'px';
    if (FPV.mh) box.style.minHeight = FPV.mh + 'px';
    const vw = document.documentElement.clientWidth, vh = window.innerHeight, w = box.offsetWidth, h = box.offsetHeight;
    if (w > FPV.mw) { FPV.mw = w; box.style.minWidth = w + 'px'; }
    if (h > FPV.mh) { FPV.mh = h; box.style.minHeight = h + 'px'; }
    fpvAvail();
    let left;
    if (FPV.side === 'r' && r.right + 10 + w <= vw - 8) left = r.right + 10;
    else if (FPV.side === 'l' && r.left - 10 - w >= 8) left = r.left - 10 - w;
    else left = r.left + r.width / 2 - w / 2;
    box.style.left = Math.max(8, Math.min(left, vw - w - 8)) + 'px';
    box.style.top = Math.max(8, Math.min(r.top + r.height / 2 - h / 2, vh - h - 8)) + 'px';
  }
  function fpvMsg(t) {
    const box = fpvBox(), img = box.querySelector('.fpv-img'), m = box.querySelector('.fpv-msg');
    img.style.display = 'none'; m.textContent = t; m.style.display = 'block';
    box.querySelector('.fpv-count').textContent = '';
    fpvPlace();
  }
  function fpvGi(id) {
    if (!FPV.cache.has(id)) FPV.cache.set(id, (async () => {
      await ftGg();
      const r = await fetch('//' + W.domain + '/galleries/' + id + '.js');
      if (!r.ok) throw new Error('HTTP ' + r.status);
      const t = await r.text(), g = JSON.parse(t.slice(t.indexOf('=') + 1).trim().replace(/;$/, ''));
      g.id = g.id || id;
      return g;
    })().catch(e => { FPV.cache.delete(id); throw e; }));
    return FPV.cache.get(id);
  }
  function fpvRender() {
    const gi = FPV.gi, box = fpvBox();
    if (!gi || box.style.display === 'none') return;
    const files = gi.files || [], i = FPV.idx, small = GM_getValue('pv_size', 'small') === 'small';
    const img = box.querySelector('.fpv-img'), m = box.querySelector('.fpv-msg'), cnt = box.querySelector('.fpv-count');
    cnt.textContent = GM_getValue('pv_count', '1') === '1' ? (i + 1) + ' / ' + files.length : '';
    const f = files[i];
    if (!f) { console.warn('[Hitomi Enhanced] vista previa: la galería no tiene imágenes', gi.id); return fpvMsg('Vista previa no disponible'); }
    // Varias direcciones posibles por si una falla: miniatura grande y pequeña, y el otro servidor (a/b) de miniaturas
    const mk = k => { try { return k ? W.url_from_url_from_hash(gi.id, f, k, 'webp', 'tn') : W.url_from_url_from_hash(gi.id, f, 'webp'); } catch (e) { console.warn('[Hitomi Enhanced] vista previa: no se pudo calcular la URL', gi.id, e); return ''; } };
    const swap = u => u.replace(/\/\/([ab])tn\./, (m, c) => '//' + (c === 'a' ? 'b' : 'a') + 'tn.');
    const urls = [];
    for (const k of small ? ['webpbigtn', 'webpsmalltn'] : ['']) {
      const u = mk(k);
      if (u) { urls.push(u); const w = swap(u); if (w !== u) urls.push(w); }
    }
    // Último recurso para la primera página: la propia portada de la tarjeta, que ya se ve en pantalla
    const cardImg = FPV.item && FPV.item.querySelector('.hr-cover img');
    if (i === 0 && cardImg && cardImg.currentSrc && !urls.includes(cardImg.currentSrc)) urls.push(cardImg.currentSrc);
    if (!urls.length) return fpvMsg('Vista previa no disponible');
    const tk = FPV.token;
    let n = 0;
    img.style.maxWidth = fpvAvail() + 'px';
    m.style.display = 'none';
    const tryNext = () => {
      if (tk !== FPV.token) return;
      if (n >= urls.length) { console.warn('[Hitomi Enhanced] vista previa: no cargó ninguna imagen', gi.id, urls); return fpvMsg('Vista previa no disponible'); }
      img.src = urls[n++];
    };
    img.onerror = () => { console.warn('[Hitomi Enhanced] vista previa: no cargó la imagen', img.src); tryNext(); };
    img.style.display = 'block';
    tryNext();
    fpvPlace();
  }
  function fpvStep(d) {
    const n = FPV.gi ? (FPV.gi.files || []).length : 0;
    if (n < 2) return;
    FPV.idx = (FPV.idx + d + n) % n;
    fpvRender();
  }
  async function fpvShow(card) {
    const token = ++FPV.token, box = fpvBox();
    FPV.gi = null; FPV.idx = 0; FPV.mw = FPV.mh = 0; box.style.minWidth = box.style.minHeight = ''; box.style.display = 'flex';
    box.querySelector('.fpv-img').removeAttribute('src');
    fpvMsg('Cargando…');
    let gi;
    try { gi = await fpvGi(fpvId(card)); } catch (e) { console.warn('[Hitomi Enhanced] vista previa: no se pudo leer la galería', fpvId(card), e); if (token === FPV.token) fpvMsg('Vista previa no disponible'); return; }
    if (token !== FPV.token) return;
    const saved = FPV.pos.get(String(gi.id)) || 0;
    FPV.gi = gi; FPV.idx = saved >= 0 && saved < (gi.files || []).length ? saved : 0;
    fpvRender();
  }
  document.addEventListener('mouseover', ev => {
    if (!fpvOn()) { if (FPV.item) fpvHide(); return; }
    let card = ev.target.closest && ev.target.closest('#hr-app .hr-card');
    if (card && (!ev.target.closest('.hr-cover') || ev.target.closest('.hr-fav-btn, .hr-lst-btn, .dl-hx') || !fpvId(card))) card = null;
    if (card === FPV.item) return;
    fpvHide();
    if (!card) return;
    FPV.item = card;
    FPV.timer = setTimeout(() => fpvShow(card), Math.max(0, parseInt(GM_getValue('pv_wait', '400')) || 0));
  }, true);
  document.addEventListener('mouseout', ev => { if (!ev.relatedTarget) fpvHide(); }, true);
  window.addEventListener('scroll', () => { if (FPV.item) fpvHide(); }, { passive: true });
  window.addEventListener('hashchange', fpvHide);
  document.addEventListener('wheel', ev => {
    if (!fpvOn() || !FPV.gi || GM_getValue('pv_wheel', '1') !== '1' || (FPV.gi.files || []).length < 2 || !FPV.box || FPV.box.style.display === 'none') return;
    ev.preventDefault();
    const now = Date.now();
    if (now - FPV.last >= 70) { FPV.last = now; fpvStep(ev.deltaY > 0 ? 1 : -1); }
  }, { capture: true, passive: false });
  document.addEventListener('keydown', ev => {
    if (!fpvOn() || !FPV.gi || GM_getValue('pv_keys', '1') !== '1' || !FPV.box || FPV.box.style.display === 'none') return;
    const tag = ev.target && ev.target.tagName;
    if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (ev.target && ev.target.isContentEditable)) return;
    const next = ev.key === 'ArrowRight' || ev.key === 'ArrowDown' || ev.key === ' ', prev = ev.key === 'ArrowLeft' || ev.key === 'ArrowUp';
    if (!next && !prev) return;
    ev.preventDefault(); ev.stopPropagation(); fpvStep(next ? 1 : -1);
  }, true);

  // Paginación numerada (1 2 3 … n) del contenido de un artista / grupo / etiqueta favorito
  function ftPager(R, cur, n) {
    if (n <= 1) { R.pager.replaceChildren(); return; }
    const set = new Set([1, n, cur - 1, cur, cur + 1]);
    if (cur <= 2) [1, 2, 3].forEach(x => set.add(x));
    if (cur >= n - 1) [n - 2, n - 1, n].forEach(x => set.add(x));
    const nums = [...set].filter(x => x >= 1 && x <= n).sort((a, b) => a - b), out = [];
    nums.forEach((x, i) => {
      if (i && x - nums[i - 1] === 2) out.push(x - 1);
      else if (i && x - nums[i - 1] > 2) out.push('…');
      out.push(x);
    });
    R.pager.replaceChildren(...out.map(x => {
      if (x === '…') return el('span', { className: 'hr-pg gap', textContent: '…' });
      if (x === cur) return el('span', { className: 'hr-pg cur', textContent: String(x) });
      const a = el('a', { className: 'hr-pg', href: '#hr-favoritos', textContent: String(x) });
      a.addEventListener('click', e => {
        e.preventDefault();
        // Las tarjetas actuales se quedan (atenuadas) hasta que las de la nueva página estén listas, y entonces se cambian de una vez
        R.tcOld = [...R.grid.children].filter(c => !c.classList.contains('hr-tbar') && c !== R.tcStatus);
        R.tcOld.forEach(c => c.classList.add('hr-fadeold'));
        R.tcCards = new Set();
        R.tcPage = x;
        R.tcDeadline = Date.now() + 2500;
        R.tcStart = Date.now();
        R.tcSkel = false;
        setTimeout(ftKick, 380);
        setTimeout(ftKick, 2600);
        scrollTo({ top: 0, behavior: 'smooth' });
        renderTermContent(R, false);
      });
      return a;
    }));
  }

  function renderTermContent(R, fresh) {
    const term = R.favTerm, d = ftLoad(term);
    if (fresh) {
      const ent = favTerms[ftFind(term)] || {}, ns = term.split(':')[0];
      const name = el('strong', { textContent: ftName(term) });
      name.setAttribute('data-keep', '');
      const rm = el('button', { type: 'button', className: 'hr-btn', textContent: 'Quitar de favoritos' });
      rm.onclick = () => ftRemove(term);
      R.tcCount = el('span', { className: 'hr-kind hr-tcount' });
      R.tcStatus = el('div', { className: 'hr-tstatus' });
      R.tcCards = new Set();
      R.tcOld = null; R.tcSwapping = false; R.tcSkel = false;
      R.grid.style.minHeight = '';
      R.grid.replaceChildren(el('div', { className: 'hr-tbar' }, el('span', { className: 'hr-ns ' + nsClass(ns), textContent: ns }), name, R.tcCount,
        el('a', { className: 'hr-btn', href: ent.href || searchUrl([term]), textContent: 'Abrir página' }), rm), R.tcStatus);
    }
    const st = R.tcStatus, msg = t => el('p', { className: 'hr-msg', textContent: t });
    if (d.err) { setText(R.tcCount, ''); st.replaceChildren(msg('No se pudo cargar el contenido. Usa «Abrir página» para verlo.')); return; }
    if (!d.ids) { setText(R.tcCount, ''); st.replaceChildren(msg('Cargando…')); return; }
    const total = d.ids.length, pages = Math.max(1, Math.ceil(total / FT_PAGE));
    const page = R.tcPage = Math.min(Math.max(1, R.tcPage || 1), pages), wanted = d.ids.slice((page - 1) * FT_PAGE, page * FT_PAGE);
    ftPager(R, page, pages);
    setText(R.tcCount, total ? `${total} ${total === 1 ? 'galería' : 'galerías'}` : '');
    wanted.forEach(id => ftWant(id, d));
    if (R.tcSwapping) return;
    if (R.tcOld) {
      const ready = wanted.every(id => d.info.has(id)) || Date.now() > (R.tcDeadline || 0);
      if (!ready) {
        // si tarda, unos marcadores sustituyen a lo anterior en vez de dejarlo a medio atenuar
        if (!R.tcSkel && Date.now() - (R.tcStart || 0) > 350) {
          R.tcSkel = true;
          const sk = Array.from({ length: Math.min(wanted.length || 12, 12) }, skeleton);
          sk.forEach(x => x.classList.add('hr-fadein'));
          R.tcOld.forEach(c => c.remove());
          sk.forEach(x => R.grid.insertBefore(x, st));
          R.tcOld = sk;
        }
        st.replaceChildren();
        return;
      }
      // cruce suave: lo anterior se desvanece y enseguida entran las tarjetas nuevas, sin que la página se encoja de golpe
      const old = R.tcOld;
      R.tcOld = null; R.tcSkel = false; R.tcSwapping = true;
      R.grid.style.minHeight = R.grid.offsetHeight + 'px';
      old.forEach(c => { c.style.transition = 'opacity .16s ease'; c.style.opacity = '0'; });
      setTimeout(() => {
        old.forEach(c => c.remove());
        R.tcSwapping = false;
        if (R.tcStatus && R.tcStatus.isConnected) renderTermContent(R, false);
        setTimeout(() => { R.grid.style.minHeight = ''; }, 500);
      }, 170);
      return;
    }
    let fadeN = 0;
    for (const id of wanted) {
      if (!d.info.has(id)) break; // las obras se muestran en orden, a medida que llegan
      if (R.tcCards.has(id)) continue;
      R.tcCards.add(id);
      const c = d.info.get(id);
      if (c) {
        const ce = cardEl(c);
        ce.classList.add('hr-fadein');
        ce.style.animationDelay = Math.min(fadeN++, 10) * 14 + 'ms';
        R.grid.insertBefore(ce, st);
      }
    }
    if (!total) { st.replaceChildren(msg('No hay galerías aquí.')); return; }
    if (wanted.some(id => !d.info.has(id))) { st.replaceChildren(...(R.tcCards.size ? [] : [msg('Cargando…')])); return; }
    st.replaceChildren();
    // precarga de la página siguiente y la anterior para que el cambio sea inmediato
    if (page < pages) d.ids.slice(page * FT_PAGE, (page + 1) * FT_PAGE).forEach(id => ftWant(id, d));
    if (page > 1) d.ids.slice((page - 2) * FT_PAGE, (page - 1) * FT_PAGE).forEach(id => ftWant(id, d));
  }

  function renderFavTerms(R) {
    R.favbar.hidden = false;
    R.sortSel.hidden = true;
    R.listbar.hidden = false;
    R.termbar.hidden = false;
    const all = Object.values(favTerms).filter(t => t && t.term);
    const words = R.favQ.toLowerCase().replace(/_/g, ' ').split(/\s+/).filter(Boolean);
    let list = all.filter(t => { const h = (ftName(t.term) + ' ' + t.term).toLowerCase().replace(/_/g, ' '); return words.every(w => h.includes(w)); });
    const cnt = k => list.filter(t => !k || ftGroup(t.term) === k).length;
    const chips = FT_GROUPS.filter(([k]) => !k || cnt(k) || R.favNs === k).map(([k, label]) => {
      const b = el('button', { type: 'button', className: 'hr-lchip' + (R.favNs === k ? ' on' : '') }, el('span', { textContent: label }), el('small', { textContent: String(cnt(k)) }));
      b.setAttribute('aria-pressed', String(R.favNs === k));
      b.onclick = () => { R.favNs = k; renderApp(); };
      return b;
    });
    if (R.favNs) list = list.filter(t => ftGroup(t.term) === R.favNs);
    list.sort((a, b) => ftName(a.term).localeCompare(ftName(b.term)));
    if (!list.some(t => t.term === R.favTerm)) R.favTerm = list[0] ? list[0].term : '';
    const sig = ['favT', all.map(t => t.term).join(','), R.favQ, R.favNs, R.favTerm].join('|');
    if (sig === gridSig) return;
    gridSig = sig;
    setText(R.h1, 'Favoritos');
    R.kind.removeAttribute('data-keep');
    setText(R.kind, '');
    setText(R.stat, !all.length ? '' : list.length === all.length ? `${all.length} ${all.length === 1 ? 'favorito' : 'favoritos'}` : `${list.length} de ${all.length} favoritos`);
    R.listbar.replaceChildren(...chips);
    R.termbar.replaceChildren(...list.map(t => {
      const ns = t.term.split(':')[0], on = t.term === R.favTerm;
      const name = el('span', { textContent: ftName(t.term) });
      name.setAttribute('data-keep', '');
      const b = el('button', { type: 'button', className: 'hr-lchip hr-ttab' + (on ? ' on' : ''), title: t.term }, el('span', { className: 'hr-ns ' + nsClass(ns), textContent: ns }), name);
      b.setAttribute('aria-pressed', String(on));
      b.onclick = () => { R.favTerm = t.term; renderApp(); };
      return b;
    }));
    R.pager.replaceChildren();
    R.tcLimit = FT_PAGE;
    R.tcPage = 1;
    R.tcStatus = null;
    if (!R.favTerm) {
      R.grid.replaceChildren(el('p', { className: 'hr-empty', textContent: all.length ? 'Ningún favorito coincide con tu búsqueda.' : 'Aún no tienes artistas, grupos ni etiquetas favoritos. Haz clic derecho en uno y elige «Añadir a favoritos», o usa el botón de su página.' }));
      return;
    }
    renderTermContent(R, true);
  }

  let lpEl = null;
  function closeListPicker() {
    if (lpEl) lpEl.remove();
    lpEl = null;
    document.removeEventListener('pointerdown', lpOutside, true);
    document.removeEventListener('keydown', lpKey, true);
  }
  function lpOutside(e) { if (lpEl && !lpEl.contains(e.target)) closeListPicker(); }
  function lpKey(e) { if (e.key === 'Escape' && lpEl) { e.stopPropagation(); closeListPicker(); } }
  function openListPicker(c, x, y) {
    closeMenu();
    closeListPicker();
    if (!c || !c.id) return;
    const body = el('div', { className: 'hr-lp-list' });
    const input = el('input', { type: 'text', placeholder: 'Nueva lista', maxLength: 60, spellcheck: false, autocomplete: 'off' });
    input.setAttribute('aria-label', 'Nueva lista');
    const addBtn = el('button', { type: 'button', className: 'hr-btn primary', textContent: 'Crear' });
    const paint = () => {
      body.replaceChildren(...(favLists.length ? favLists.map(l => {
        const cb = el('input', { type: 'checkbox', checked: flHas(c.id, l.id) });
        cb.onchange = () => flSet(c, l.id, cb.checked);
        const name = el('span', { textContent: l.name, title: l.name });
        name.setAttribute('data-keep', '');
        return el('label', { className: 'hr-lp-row' }, cb, name);
      }) : [el('p', { className: 'hr-lp-empty', textContent: 'Aún no tienes listas. Crea la primera abajo.' })]));
    };
    const create = () => {
      const l = flNew(input.value);
      if (!l) return;
      input.value = '';
      flSet(c, l.id, true);
      paint();
      input.focus();
    };
    addBtn.onclick = create;
    input.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); create(); } else if (e.key === 'Escape') closeListPicker(); });
    lpEl = el('div', { id: 'hr-listpick' }, el('div', { className: 'hr-lp-title', textContent: 'Añadir a una lista' }), body, el('div', { className: 'hr-lp-add' }, input, addBtn));
    lpEl.setAttribute('role', 'dialog');
    lpEl.setAttribute('aria-label', 'Listas');
    paint();
    document.body.append(lpEl);
    const r = lpEl.getBoundingClientRect();
    lpEl.style.left = Math.max(8, Math.min(x, innerWidth - r.width - 8)) + 'px';
    lpEl.style.top = Math.max(8, Math.min(y, innerHeight - r.height - 8)) + 'px';
    document.addEventListener('pointerdown', lpOutside, true);
    document.addEventListener('keydown', lpKey, true);
    input.focus();
  }

  function renderListBar(R) {
    const all = Object.values(favs);
    const known = new Set(favLists.map(l => l.id));
    const chip = (key, label, n, keep) => {
      const b = el('button', { type: 'button', className: 'hr-lchip' + (R.favL === key ? ' on' : '') }, el('span', { textContent: label }), el('small', { textContent: String(n) }));
      if (keep) b.firstChild.setAttribute('data-keep', '');
      b.setAttribute('aria-pressed', String(R.favL === key));
      b.onclick = () => { R.favL = key; R.favShown = FAV_STEP; renderApp(); };
      return b;
    };
    const kids = [chip('', 'Todas', all.length)];
    for (const l of favLists) kids.push(chip(l.id, l.name, all.filter(f => (f.lists || []).includes(l.id)).length, true));
    if (favLists.length) kids.push(chip('_none', 'Sin lista', all.filter(f => !(f.lists || []).some(x => known.has(x))).length));
    const add = el('button', { type: 'button', className: 'hr-lchip add' }, icon('plus', 14), el('span', { textContent: 'Nueva lista' }));
    add.onclick = () => {
      const n = prompt(T('Nombre de la nueva lista'));
      const l = n && flNew(n);
      if (l) { R.favL = l.id; R.favShown = FAV_STEP; renderApp(); }
    };
    kids.push(add);
    const cur = favLists.find(l => l.id === R.favL);
    if (cur) {
      const ren = el('button', { type: 'button', className: 'hr-lchip tool', title: 'Renombrar lista' }, icon('edit', 14));
      ren.setAttribute('aria-label', 'Renombrar lista');
      ren.onclick = () => { const n = prompt(T('Nuevo nombre de la lista'), cur.name); if (n != null) flRename(cur.id, n); };
      const del = el('button', { type: 'button', className: 'hr-lchip tool', title: 'Eliminar lista' }, icon('x', 14));
      del.setAttribute('aria-label', 'Eliminar lista');
      del.onclick = () => { if (confirm(T('¿Eliminar esta lista? Las galerías seguirán en favoritos.'))) flDelete(cur.id); };
      kids.push(ren, del);
    }
    R.listbar.replaceChildren(...kids);
  }

  const setAttrT = (n, name, es) => { const cur = n.getAttribute(name); if (cur !== es && !(EN_ON && cur === trEn(es))) n.setAttribute(name, es); };
  function paintFav(b) {
    const on = favHas(b.dataset.favId);
    b.classList.toggle('on', on);
    b.setAttribute('aria-pressed', String(on));
    const t = on ? 'Quitar de favoritos' : 'Añadir a favoritos';
    setAttrT(b, 'title', t);
    setAttrT(b, 'aria-label', t);
    const lab = b.querySelector('.hr-fav-label');
    if (lab) setText(lab, on ? 'En favoritos' : 'Añadir a favoritos');
  }
  function paintFavs() {
    document.querySelectorAll('[data-fav-id]').forEach(paintFav);
    document.querySelectorAll('[data-lst-id]').forEach(paintLst);
    const n = favIds().length, txt = n > 99 ? '99+' : String(n);
    document.querySelectorAll('.hr-fav-count').forEach(b => { if (b.textContent !== txt) b.textContent = txt; b.hidden = !n; });
  }
  function favsChanged() {
    paintFavs();
    if (!(appRefs && appRefs.mode === 'list' && favView())) return;
    if (appRefs.favTab === 't') { appRefs.tabSig = ''; renderFavTabs(appRefs); return; } // el contenido de la pestaña no se redibuja
    gridSig = ''; renderApp();
  }
  onRemote(FAV_KEY, n => { favs = favRead(n); favsChanged(); });

  // Entrar o salir de la vista de favoritos sin recargar (en una lista), o ir a ella desde cualquier otra página
  function openFavs() {
    if (appRefs && appRefs.mode === 'list') {
      history.pushState(null, '', location.pathname + location.search + (favView() ? '' : '#hr-favoritos'));
      favNav();
      scrollTo(0, 0);
    } else location.href = '/#hr-favoritos';
  }
  function favNav() {
    if (!appRefs || appRefs.mode !== 'list') return;
    appRefs.favShown = FAV_STEP;
    gridSig = '';
    renderApp();
  }
  window.addEventListener('popstate', favNav);
  window.addEventListener('hashchange', favNav);

  const favHay = f => [f.title, ...(f.artists || []).map(x => x.text), ...(f.series || []).map(x => x.text),
    ...(f.tags || []).flatMap(x => [x.text, x.term]), f.type && f.type.text, f.lang && f.lang.text]
    .filter(Boolean).join('\n').toLowerCase().replace(/_/g, ' ');
  function favList(R) {
    const words = R.favQ.toLowerCase().replace(/_/g, ' ').split(/\s+/).filter(w => w && w !== '-');
    const inc = words.filter(w => !w.startsWith('-')), exc = words.filter(w => w.startsWith('-')).map(w => w.slice(1));
    let list = Object.values(favs).filter(f => f && f.id);
    if (words.length) list = list.filter(f => { const h = favHay(f); return inc.every(w => h.includes(w)) && !exc.some(w => h.includes(w)); });
    if (R.favL === '_none') list = list.filter(f => !(f.lists || []).some(x => favLists.some(l => l.id === x)));
    else if (R.favL) list = list.filter(f => (f.lists || []).includes(R.favL));
    const first = f => ((f.artists && f.artists[0] && f.artists[0].text) || '\uffff').toLowerCase();
    const by = {
      new: (a, b) => b.t - a.t, old: (a, b) => a.t - b.t,
      title: (a, b) => a.title.localeCompare(b.title),
      artist: (a, b) => first(a).localeCompare(first(b)) || a.title.localeCompare(b.title),
    };
    return list.sort(by[S.favSort] || by.new);
  }

  function renderFavs() {
    const R = appRefs;
    R.favbar.hidden = false;
    R.sortSel.hidden = false;
    R.termbar.hidden = true;
    R.listbar.hidden = false;
    if (R.favL && R.favL !== '_none' && !favLists.some(l => l.id === R.favL)) R.favL = '';
    if (R.favL === '_none' && !favLists.length) R.favL = '';
    const total = favIds().length;
    const list = favList(R);
    const sig = ['fav', Object.values(favs).map(f => f.id + ':' + f.t + ':' + (f.lists || []).join('.')).join(','), favLists.map(l => l.id + '=' + l.name).join(','), R.favL, R.favQ, S.favSort, R.favShown, S.cardTags].join('|');
    if (sig === gridSig) return;
    gridSig = sig;
    setText(R.h1, 'Favoritos');
    const curList = favLists.find(l => l.id === R.favL);
    R.kind.toggleAttribute('data-keep', !!curList);
    setText(R.kind, curList ? curList.name : '');
    renderListBar(R);
    if (R.sortSel.value !== S.favSort) R.sortSel.value = S.favSort;
    setText(R.stat, !total ? '' : list.length === total ? `${total} ${total === 1 ? 'favorito' : 'favoritos'}` : `${list.length} de ${total} favoritos`);
    const shown = list.slice(0, R.favShown);
    if (shown.length) R.grid.replaceChildren(...shown.map(f => cardEl(favToCard(f))));
    else R.grid.replaceChildren(el('p', { className: 'hr-empty', textContent: !total ? 'Aún no tienes favoritos. Pulsa el corazón de una galería para guardarla aquí.' : R.favL && R.favL !== '_none' && !R.favQ ? 'Esta lista está vacía. Usa el botón de listas de una tarjeta para añadir galerías.' : 'Ningún favorito coincide con tu búsqueda.' }));
    if (list.length > shown.length) {
      const moreBtn = el('button', { type: 'button', className: 'hr-btn primary hr-btn-lg' }, icon('chevDown', 16), el('span', { textContent: 'Ver más' }));
      const allBtn = el('button', { type: 'button', className: 'hr-btn primary hr-btn-lg' }, icon('chevsDown', 16), el('span', { textContent: 'Ver todas' }));
      moreBtn.onclick = () => { R.favShown += FAV_STEP; renderApp(); };
      allBtn.onclick = () => { R.favShown = list.length; renderApp(); };
      R.pager.replaceChildren(el('div', { className: 'hr-more-bar' }, moreBtn, allBtn, el('span', { className: 'hr-more-count', textContent: `${shown.length} / ${list.length}` })));
    } else R.pager.replaceChildren();
    shown.forEach(f => favCache(f.id));
  }

  GM_addStyle(`
    .hr-fav-btn { position: absolute; z-index: 3; top: 8px; right: 8px; display: grid; place-items: center; width: 30px; height: 30px; padding: 0;
      border: 0; border-radius: 8px; background: rgba(10,10,16,.68); color: #fff; backdrop-filter: blur(6px); cursor: pointer;
      opacity: 0; transition: opacity .15s, background .15s, color .15s; }
    .hr-cover:has(> .dl-get) > .hr-fav-btn { top: 44px; }
    .hr-card:hover .hr-fav-btn, .hr-fav-btn:focus-visible, .hr-fav-btn.on { opacity: 1; }
    .hr-fav-btn:hover { background: var(--hr-accent); color: #fff; }
    .hr-fav-btn.on { color: var(--hr-accent); }
    .hr-fav-btn.on:hover { color: #fff; }
    .hr-fav-btn:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }
    .hr-fav-btn.on svg, .hr-fav-act.on svg, .hr-fav-rb.on svg, .hr-fav-top.on svg { fill: currentColor; }
    @media (hover: none) { .hr-fav-btn { opacity: 1; } }
    .hr-fav-act.on { border-color: var(--hr-accent); background: var(--hr-accent-soft); }
    .hr-fav-top { position: relative; }
    .hr-fav-top.on { color: var(--hr-accent); border-color: var(--hr-accent); }
    .hr-fav-count { position: absolute; top: -6px; right: -6px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box;
      border-radius: 9px; background: var(--hr-accent); color: #fff; font: 600 11px/18px var(--hr-font); text-align: center; }
    .hr-fav-count[hidden] { display: none; }
    .hr-favbar { display: flex; flex-wrap: wrap; gap: 10px; margin: -6px 0 22px; }
    .hr-favbar[hidden] { display: none; }
    .hr-favbar .hr-sbox { flex: 1 1 280px; max-width: 560px; }
    .hr-lst-btn { position: absolute; z-index: 3; top: 8px; right: 44px; display: grid; place-items: center; width: 30px; height: 30px; padding: 0;
      border: 0; border-radius: 8px; background: rgba(10,10,16,.68); color: #fff; backdrop-filter: blur(6px); cursor: pointer;
      opacity: 0; transition: opacity .15s, background .15s, color .15s; }
    .hr-cover:has(> .dl-get) > .hr-lst-btn { top: 44px; }
    .hr-card:hover .hr-lst-btn, .hr-lst-btn:focus-visible, .hr-lst-btn.on { opacity: 1; }
    .hr-lst-btn:hover { background: var(--hr-accent); color: #fff; }
    .hr-lst-btn.on { color: var(--hr-accent); }
    .hr-lst-btn.on:hover { color: #fff; }
    .hr-lst-btn:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }
    @media (hover: none) { .hr-lst-btn { opacity: 1; } }
    .hr-lbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: -8px 0 22px; }
    .hr-lbar[hidden] { display: none; }
    .hr-lchip { display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 12px; border-radius: 999px;
      border: 1px solid var(--hr-border); background: var(--hr-surface); color: var(--hr-text); font: 600 13px/1 var(--hr-font); cursor: pointer; }
    .hr-lchip small { color: var(--hr-muted); font: 500 12px/1 var(--hr-font); font-variant-numeric: tabular-nums; }
    .hr-lchip:hover { border-color: var(--hr-accent); }
    .hr-lchip.on { background: var(--hr-accent); border-color: var(--hr-accent); color: #fff; }
    .hr-lchip.on small { color: rgba(255,255,255,.8); }
    .hr-lchip.add { border-style: dashed; color: var(--hr-muted); }
    .hr-lchip.tool { width: 32px; padding: 0; justify-content: center; color: var(--hr-muted); }
    .hr-lchip:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }
    #hr-listpick { position: fixed; z-index: 2147483647; width: 270px; max-width: calc(100vw - 16px); padding: 10px; box-sizing: border-box;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; box-shadow: 0 14px 36px var(--hr-shadow);
      color: var(--hr-text); font: 14px/1.4 var(--hr-font); color-scheme: var(--hr-scheme); }
    #hr-listpick * { box-sizing: border-box; }
    .hr-lp-title { margin: 0 0 6px; padding: 0 4px; color: var(--hr-muted); font-size: 12px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
    .hr-lp-list { max-height: 220px; overflow: auto; }
    .hr-lp-row { display: flex; align-items: center; gap: 10px; padding: 7px 6px; border-radius: 8px; cursor: pointer; }
    .hr-lp-row:hover { background: var(--hr-surface2); }
    .hr-lp-row input { width: 16px; height: 16px; margin: 0; accent-color: var(--hr-accent); }
    .hr-lp-row span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .hr-lp-empty { margin: 4px 6px 8px; color: var(--hr-muted); font-size: 13px; }
    .hr-lp-add { display: flex; gap: 6px; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--hr-border); }
    .hr-lp-add input { flex: 1; min-width: 0; height: 32px; padding: 0 10px; background: var(--hr-bg); border: 1px solid var(--hr-border);
      border-radius: 9px; color: inherit; font: inherit; outline: none; }
    .hr-lp-add input:focus { border-color: var(--hr-accent); }
    .hr-termfav { display: inline-flex; align-items: center; gap: 6px; height: 34px; align-self: center; }
    .hr-termfav[hidden] { display: none; }
    .hr-termfav.on { border-color: var(--hr-accent); background: var(--hr-accent-soft); }
    .hr-termfav.on svg { fill: currentColor; }
    .hr-tgrid { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
    .hr-tcard { display: flex; align-items: center; gap: 10px; min-width: 0; padding: 10px 10px 10px 12px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; }
    .hr-tcard:hover { border-color: var(--hr-accent); }
    #hr-app .hr-tcard a { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
    #hr-app .hr-tcard a:hover { color: var(--hr-accent); }
    .hr-tcard button { flex: none; display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 8px;
      background: none; color: var(--hr-muted); cursor: pointer; }
    .hr-tcard button:hover { background: var(--hr-hover); color: var(--hr-text); }
    .hr-tcard button:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 1px; }
    .hr-ttabs { margin-top: -6px; }
    .hr-ttab { height: 36px; padding: 0 14px 0 8px; }
    .hr-ttab .hr-ns { min-width: 0; padding: 3px 7px; }
    .hr-ttab.on .hr-ns { background: rgba(255,255,255,.22); color: #fff; }
    .hr-tbar { grid-column: 1 / -1; justify-self: start; max-width: 100%; display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 12px 14px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; }
    .hr-tbar strong { font-size: 17px; font-weight: 700; overflow-wrap: anywhere; }
    .hr-tbar .hr-tcount { margin-right: 14px; }
    #hr-app .hr-tbar a.hr-btn { display: inline-flex; align-items: center; }
    .hr-tstatus { grid-column: 1 / -1; }
    .hr-tstatus:empty { display: none; }
    .hr-fadein { animation: hr-fi .32s cubic-bezier(.2, .7, .3, 1) backwards; }
    @keyframes hr-fi { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
    .hr-fadeold { opacity: .3; pointer-events: none; transition: opacity .2s ease; }
    @media (prefers-reduced-motion: reduce) { .hr-fadein { animation: none; } }
    .hr-tstatus .hr-msg { margin: 0; padding: 28px 0; text-align: center; color: var(--hr-muted); }
    @media (prefers-reduced-motion: reduce) { .hr-fav-btn, .hr-lst-btn { transition: none; } }
  `);

  const CARD_SEL = '.gallery-content > div';
  function cardHit(card, bl) {
    if (!bl.size) return '';
    for (const a of card.querySelectorAll('a[href]')) {
      const t = termFromLink(a);
      if (t && bl.has(normTerm(t))) return normTerm(t);
    }
    return '';
  }
  let blCount = 0;
  const blState = n => S.blMode === 'hide' ? (n === 1 ? 'oculta' : 'ocultas') : (n === 1 ? 'atenuada' : 'atenuadas');
  function scanCards() {
    if (isReader() || !document.body) return;
    const bl = new Set(blacklist);
    let n = 0;
    for (const card of document.querySelectorAll(CARD_SEL)) {
      const hit = cardHit(card, bl);
      card.classList.toggle('hr-bl-hide', !!hit && S.blMode === 'hide');
      card.classList.toggle('hr-bl-dim', !!hit && S.blMode === 'dim');
      if (hit) { card.dataset.hrBl = hit; n++; }
      else if (card.dataset.hrBl) delete card.dataset.hrBl;
    }
    blCount = n;
    updateBadge();
    renderApp();
  }

  let scanTimer = 0;
  const scheduleScan = () => { if (!scanTimer) scanTimer = setTimeout(() => { scanTimer = 0; scanCards(); }, 60); };

  function updateBadge() {
    const fab = document.getElementById('hr-fab');
    const b = fab?.querySelector('.hr-badge');
    if (!b) return;
    const txt = String(blCount);
    if (b.textContent !== txt) b.textContent = txt;
    b.hidden = !blCount;
    fab.title = blCount
      ? `Ajustes de Hitomi Enhanced (${blCount} ${blCount === 1 ? 'galería' : 'galerías'} de la lista negra ${blState(blCount)} aquí)`
      : 'Ajustes de Hitomi Enhanced';
  }

  GM_addStyle(`
    :root {
      --hr-size: ${S.thumbSize}px;
      --hr-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
      --hr-accent-soft: color-mix(in srgb, var(--hr-accent) 22%, transparent);
      --hr-neg: #d6476b;
      --hr-neg-soft: color-mix(in srgb, #d6476b 22%, transparent);
      --hr-hover: color-mix(in srgb, var(--hr-text) 10%, transparent);
    }

    #hr-menu { position: fixed; z-index: 2147483647; min-width: 250px; max-width: 320px; padding: 6px; background: var(--hr-surface);
      border: 1px solid var(--hr-border); border-radius: 10px; box-shadow: 0 14px 36px var(--hr-shadow);
      color: var(--hr-text); font: 14px/1.4 var(--hr-font); color-scheme: var(--hr-scheme); }
    #hr-menu .hr-mh { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; padding: 6px 8px 10px; }
    #hr-menu .hr-mh .hr-ns { min-width: 0; text-transform: capitalize; }
    #hr-menu .hr-mh strong { flex: 1; min-width: 0; font-size: 14px; font-weight: 650; overflow-wrap: anywhere;
      display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
    #hr-menu .hr-mh small { flex-basis: 100%; color: var(--hr-muted); font-size: 12px; }
    #hr-menu .hr-mi { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; background: none; border: 0;
      color: inherit; padding: 7px 8px; border-radius: 8px; cursor: pointer; font: inherit; }
    #hr-menu .hr-mi:hover, #hr-menu .hr-mi:focus-visible { background: var(--hr-surface2); outline: none; }
    #hr-menu .hr-mi-ic { flex: none; display: grid; place-items: center; width: 18px; color: var(--hr-muted); }
    #hr-menu .hr-mi-txt { display: flex; flex-direction: column; min-width: 0; }
    #hr-menu .hr-mi small { color: var(--hr-muted); font-size: 12px; line-height: 1.3; }
    #hr-menu .hr-mi.danger, #hr-menu .hr-mi.danger .hr-mi-ic { color: var(--hr-neg); }
    #hr-menu hr { border: 0; border-top: 1px solid var(--hr-border); margin: 5px 4px; }

    .hr-chip { display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 0 3px 0 11px; border-radius: 999px;
      background: var(--hr-accent-soft); color: var(--hr-text); font: 13px/1 var(--hr-font); cursor: pointer;
      white-space: nowrap; user-select: none; }
    .hr-chip.neg { background: var(--hr-neg-soft); }
    .hr-chip-not { color: var(--hr-neg); font-weight: 600; font-size: 11px; }
    .hr-chip button { display: grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%;
      background: none; color: var(--hr-muted); cursor: pointer; font: 15px/1 var(--hr-font); }
    .hr-chip button:hover { background: var(--hr-hover); color: var(--hr-text); }
    .hr-btn { height: 32px; padding: 0 14px; border-radius: 9px; border: 1px solid var(--hr-border); background: transparent;
      color: var(--hr-text); font: 600 13px/1 var(--hr-font); cursor: pointer; white-space: nowrap; }
    .hr-btn:hover { background: var(--hr-hover); }
    .hr-btn.primary { background: var(--hr-accent); border-color: var(--hr-accent); color: #fff; }
    .hr-btn.primary:hover { background: color-mix(in srgb, var(--hr-accent) 85%, #fff); }
    .hr-chip button:focus-visible, .hr-btn:focus-visible, .hr-icon:focus-visible, .hr-pg:focus-visible,
    #hr-app a:focus-visible, .hr-select:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }

    #hr-panel { position: fixed; z-index: 2147483646; right: 16px; bottom: 16px; max-width: min(560px, calc(100vw - 96px));
      display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 8px;
      background: color-mix(in srgb, var(--hr-surface) 88%, transparent); backdrop-filter: blur(14px);
      border: 1px solid var(--hr-border); border-radius: 16px; box-shadow: 0 12px 32px var(--hr-shadow);
      color: var(--hr-text); font: 14px/1.4 var(--hr-font); color-scheme: var(--hr-scheme); }
    #hr-panel[hidden], html.hr-ui #hr-panel { display: none !important; }
    #hr-panel .hr-acts { display: flex; gap: 6px; margin-left: auto; }

    #hr-fab { position: fixed; z-index: 2147483646; left: 16px; bottom: 16px; width: 44px; height: 44px; padding: 0;
      border: 0; border-radius: 12px; background: none; cursor: pointer; opacity: .85;
      box-shadow: 0 6px 18px var(--hr-shadow); transition: opacity .15s; }
    #hr-fab:hover, #hr-fab:focus-visible { opacity: 1; }
    #hr-fab:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }
    #hr-fab img { display: block; width: 100%; height: 100%; border-radius: 12px; }
    #hr-fab .hr-badge { position: absolute; top: -6px; right: -6px; min-width: 18px; height: 18px; padding: 0 5px;
      box-sizing: border-box; border-radius: 9px; background: var(--hr-neg); color: #fff;
      font: 600 11px/18px system-ui, sans-serif; text-align: center; }
    #hr-fab .hr-badge[hidden], html.hr-ui #hr-fab { display: none; }

    .hr-bl-hide { display: none !important; }
    .hr-bl-dim { position: relative; opacity: .3; transition: opacity .15s; }
    .hr-bl-dim img { filter: blur(10px) grayscale(1); }
    .hr-bl-dim:hover { opacity: 1; }
    .hr-bl-dim:hover img { filter: none; }
    .hr-bl-dim::before { content: 'En lista negra: ' attr(data-hr-bl); position: absolute; z-index: 2; left: 6px; top: 6px;
      background: var(--hr-neg); color: #fff; font: 12px/1.4 system-ui, sans-serif; padding: 2px 6px; border-radius: 4px; pointer-events: none; }

    html.hr-ui, html.hr-ui body { background: var(--hr-bg) !important; }
    html.hr-ui body { margin: 0 !important; padding: 0 !important; min-width: 0 !important; }
    html.hr-ui body > :not([id^="hr-"]) { display: none !important; }
    #hr-app { min-height: 100vh; color: var(--hr-text); font: 14px/1.45 var(--hr-font); color-scheme: var(--hr-scheme);
      -webkit-font-smoothing: antialiased; }
    #hr-app *, #hr-app *::before, #hr-app *::after { box-sizing: border-box; }
    #hr-app a { color: inherit; text-decoration: none; }

    .hr-top { position: sticky; top: 0; z-index: 100; display: flex; align-items: center; gap: 10px;
      padding: 10px clamp(12px, 3vw, 32px); background: color-mix(in srgb, var(--hr-bg) 82%, transparent);
      backdrop-filter: blur(16px); border-bottom: 1px solid var(--hr-border); }
    .hr-brand { display: flex; align-items: center; gap: 9px; flex: none; font-weight: 700; font-size: 15px; letter-spacing: -.01em; }
    .hr-brand img { width: 30px; height: 30px; border-radius: 8px; display: block; }
    .hr-sbox { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 5px; min-height: 42px;
      padding: 6px 8px 6px 12px; background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; cursor: text; }
    .hr-sbox:focus-within { border-color: var(--hr-accent); box-shadow: 0 0 0 3px var(--hr-accent-soft); }
    .hr-sbox > svg { flex: none; color: var(--hr-muted); margin-right: 2px; }
    .hr-chips { display: contents; }
    .hr-sbox input { flex: 1; min-width: 150px; height: 28px; border: 0; outline: none; background: none; color: inherit;
      font: inherit; padding: 0 4px; }
    .hr-sbox input::placeholder { color: var(--hr-muted); }
    .hr-select { height: 42px; padding: 0 32px 0 12px; border-radius: 12px; border: 1px solid var(--hr-border);
      background: var(--hr-surface) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%238e90b0' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E") no-repeat right 12px center;
      color: inherit; font: inherit; appearance: none; -webkit-appearance: none; cursor: pointer; }
    .hr-select option { background: var(--hr-surface); color: var(--hr-text); }
    .hr-top .hr-btn { height: 42px; border-radius: 12px; padding: 0 18px; }
    .hr-menu { position: relative; flex: none; }
    .hr-menu-btn { white-space: nowrap; text-align: left; }
    .hr-pop { position: absolute; top: calc(100% + 8px); right: 0; z-index: 200; min-width: 220px; padding: 8px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 14px; box-shadow: 0 18px 44px var(--hr-shadow); }
    .hr-pop[hidden] { display: none; }
    .hr-pop-title { padding: 8px 10px 4px; color: var(--hr-muted); font-size: 12px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
    #hr-app .hr-pop-item { display: block; padding: 9px 10px; border-radius: 8px; }
    #hr-app .hr-pop-item:hover, #hr-app .hr-pop-item:focus-visible { background: var(--hr-hover); color: var(--hr-accent); outline: none; }
    .hr-icon { flex: none; display: grid; place-items: center; width: 42px; height: 42px; padding: 0; border-radius: 12px;
      border: 1px solid var(--hr-border); background: var(--hr-surface); color: var(--hr-muted); cursor: pointer; }
    .hr-icon:hover { color: var(--hr-text); }

    .hr-main { max-width: 1680px; margin: 0 auto; padding: 28px clamp(12px, 3vw, 32px) 64px; }
    .hr-headline { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 12px; margin-bottom: 20px; }
    .hr-headline h1 { margin: 0; font-size: 28px; font-weight: 750; letter-spacing: -.02em; line-height: 1.15; overflow-wrap: anywhere; }
    .hr-kind { color: var(--hr-muted); font-size: 14px; }
    .hr-stat { margin-left: auto; color: var(--hr-muted); font-size: 13px; }

    .hr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--hr-card), 1fr)); gap: 26px 18px; }
    .hr-card { position: relative; min-width: 0; display: flex; flex-direction: column; gap: 7px; }
    .hr-cover { position: relative; display: block; aspect-ratio: 5 / 7; overflow: hidden; border-radius: 10px;
      background: var(--hr-surface2); }
    .hr-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
    .hr-cover-link { position: absolute; inset: 0; display: block; border-radius: inherit; }
    .hr-cover:has(.hr-cover-link:hover) { box-shadow: 0 0 0 2px var(--hr-accent); }
    .hr-pill { position: absolute; bottom: 8px; padding: 3px 7px; border-radius: 6px; background: rgba(10,10,16,.68);
      color: #fff; font: 600 11px/1.2 var(--hr-font); backdrop-filter: blur(6px); text-transform: capitalize; max-width: 60%;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .hr-pill.type { left: 8px; }
    #hr-app a.hr-pill:hover { background: var(--hr-accent); color: #fff; }
    .hr-pill.lang { right: 8px; }
    .hr-pill.pages { left: 8px; bottom: 34px; display: inline-flex; align-items: center; gap: 4px; font-variant-numeric: tabular-nums; }
    .hr-pill.pages[hidden] { display: none; }
    .hr-title { font-weight: 600; font-size: 14px; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2;
      -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; }
    .hr-title:hover { color: var(--hr-accent); }
    .hr-sub { margin-top: -3px; color: var(--hr-muted); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .hr-sub a:hover { color: var(--hr-text); }
    .hr-tags { display: flex; flex-wrap: wrap; gap: 4px; }
    .hr-tag { padding: 4px 7px; border-radius: 6px; background: var(--hr-surface2); color: var(--hr-muted);
      font-size: 11.5px; line-height: 1; white-space: nowrap; }
    .hr-tag.f { background: color-mix(in srgb, #df5279 15%, transparent); color: color-mix(in srgb, #df5279 65%, var(--hr-text)); }
    .hr-tag.m { background: color-mix(in srgb, #2e8ddf 15%, transparent); color: color-mix(in srgb, #2e8ddf 65%, var(--hr-text)); }
    .hr-tag:hover { background: var(--hr-hover); color: var(--hr-text); }
    .hr-card.is-dim { opacity: .5; }
    .hr-card.is-dim img { filter: blur(14px) grayscale(1); }
    .hr-card.is-dim:hover { opacity: 1; }
    .hr-card.is-dim:hover img { filter: none; }
    .hr-card.is-dim .hr-cover::after { content: 'En lista negra: ' attr(data-bl); position: absolute; left: 8px; right: 8px; top: 8px;
      padding: 3px 7px; border-radius: 6px; background: var(--hr-neg); color: #fff; font-size: 11px; font-weight: 600;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .hr-skel .hr-cover { animation: hr-pulse 1.4s ease-in-out infinite; }
    .hr-skel i { display: block; height: 12px; border-radius: 6px; background: var(--hr-surface2); }
    .hr-skel i + i { width: 60%; }
    @keyframes hr-pulse { 50% { opacity: .55; } }
    .hr-empty { grid-column: 1 / -1; padding: 96px 0; text-align: center; color: var(--hr-muted); font-size: 15px; }

    .hr-pager { display: flex; justify-content: center; flex-wrap: wrap; gap: 6px; margin-top: 44px; }
    .hr-pg { display: grid; place-items: center; min-width: 40px; height: 40px; padding: 0 12px; border-radius: 10px;
      border: 1px solid var(--hr-border); background: var(--hr-surface); color: var(--hr-text); font: 600 13px/1 var(--hr-font); }
    a.hr-pg:hover { border-color: var(--hr-accent); }
    .hr-pg.cur { background: var(--hr-accent); border-color: var(--hr-accent); color: #fff; }
    .hr-pg.gap { border-color: transparent; background: none; color: var(--hr-muted); }

    @media (max-width: 900px) { .hr-brand span { display: none; } }
    @media (max-width: 720px) {
      .hr-top { flex-wrap: wrap; }
      .hr-sbox { order: 10; flex: 1 1 calc(100% - 100px); }
      .hr-top > .hr-btn.primary { order: 11; }
      .hr-brand { margin-right: auto; }
      .hr-headline h1 { font-size: 22px; }
      .hr-grid { grid-template-columns: repeat(auto-fill, minmax(min(var(--hr-card), 42vw), 1fr)); gap: 20px 12px; }
    }
    @media (prefers-reduced-motion: reduce) { .hr-skel .hr-cover { animation: none; } #hr-fab { transition: none; } }

    #hr-strip { position: fixed; z-index: 2147483645; display: flex; gap: 6px; padding: 8px; box-sizing: border-box;
      background: color-mix(in srgb, var(--hr-bg) 94%, transparent); scrollbar-width: thin;
      scrollbar-color: var(--hr-border) transparent; font: 14px/1.4 var(--hr-font); color: var(--hr-text); }
    #hr-strip[hidden] { display: none; }
    html.hr-pos-bottom #hr-strip { left: 0; right: 0; bottom: 0; height: var(--hr-striph);
      flex-direction: row; overflow-x: auto; overflow-y: hidden; align-items: center; border-top: 1px solid var(--hr-border); }
    html.hr-pos-left #hr-strip, html.hr-pos-right #hr-strip { top: var(--hr-nav); bottom: 0; width: var(--hr-stripw);
      flex-direction: column; overflow-y: auto; overflow-x: hidden; align-items: center; }
    html.hr-pos-left #hr-strip { left: 0; border-right: 1px solid var(--hr-border); }
    html.hr-pos-right #hr-strip { right: 0; border-left: 1px solid var(--hr-border); }

    html.hr-reader { --hr-nav: 41px; --hr-striph: 0px; --hr-stripw: 0px; }
    html.hr-pos-bottom { --hr-striph: calc(var(--hr-size) + 26px); }
    html.hr-pos-left, html.hr-pos-right { --hr-stripw: calc(var(--hr-size) + 26px); }
    html.hr-reader #comicImages { height: calc(100vh - var(--hr-nav) - var(--hr-striph)) !important; box-sizing: border-box; }
    html.hr-pos-left #comicImages { margin-left: var(--hr-stripw); }
    html.hr-pos-right #comicImages { margin-right: var(--hr-stripw); }
    html.hr-reader #comicImages.fitVertical img { max-height: calc(100% * var(--hr-zoom)) !important; }
    html.hr-reader .spread1 #comicImages.fitHorizontal img { width: calc(100% * var(--hr-zoom)) !important; }
    html.hr-reader .spread2 #comicImages.fitHorizontal img { width: calc(50% * var(--hr-zoom)) !important; }
    html.hr-reader #comicImages:fullscreen { height: 100vh !important; margin: 0 !important; }
    html.hr-reader #comicImages:fullscreen.fitVertical img { max-height: calc(100vh * var(--hr-zoom)) !important; }

    .hr-nav-li label { display: block; margin: 0; padding: 10px 12px; color: #999; font-size: 14px; line-height: 20px; font-weight: normal; }
    #hr-zoom, #hr-page { width: 52px; height: 20px; margin: 0 2px; padding: 0 4px; background: #2b2b2b; color: #ddd;
      border: 1px solid #444; border-radius: 3px; font-size: 14px; vertical-align: baseline; box-sizing: content-box; }
    #hr-total { color: #ddd; }
    #hr-navgear { display: block; background: none; border: 0; padding: 10px 12px; cursor: pointer; }
    #hr-navgear img { display: block; width: 20px; height: 20px; border-radius: 5px; }
    #hr-navgear:focus-visible { outline: 2px solid #fff; outline-offset: -2px; }

    .hr-tile { flex: 0 0 auto; position: relative; padding: 0; border: 2px solid transparent; border-radius: 6px;
      background: var(--hr-surface2); cursor: pointer; overflow: hidden; }
    html.hr-pos-bottom .hr-tile { height: var(--hr-size);
      width: clamp(calc(var(--hr-size) * .45), calc(var(--hr-size) * var(--r)), calc(var(--hr-size) * 2)); }
    html.hr-pos-left .hr-tile, html.hr-pos-right .hr-tile { width: var(--hr-size);
      height: clamp(calc(var(--hr-size) * .45), calc(var(--hr-size) / var(--r)), calc(var(--hr-size) * 2)); }
    .hr-tile img { width: 100%; height: 100%; object-fit: cover; display: block; }
    .hr-tile:not([data-state="done"]) img { visibility: hidden; }
    .hr-tile span { position: absolute; left: 3px; bottom: 3px; font-size: 12px; color: #fff;
      background: rgba(0,0,0,.65); padding: 0 5px; border-radius: 4px; }
    .hr-tile.cur { border-color: var(--hr-accent); }
    .hr-tile:focus-visible { outline: 2px solid #fff; outline-offset: 1px; }
  `);

  let menu = null;
  const closeMenu = () => { menu?.remove(); menu = null; };

  function openMenu(x, y, head, items) {
    closeMenu();
    menu = el('div', { id: 'hr-menu' }, head);
    menu.setAttribute('role', 'menu');
    for (const it of items) {
      if (it === '-') { menu.append(el('hr')); continue; }
      const b = el('button', { type: 'button', className: 'hr-mi' + (it.danger ? ' danger' : '') },
        el('span', { className: 'hr-mi-ic' }, icon(it.icon, 16)),
        el('span', { className: 'hr-mi-txt' }, el('span', { textContent: it.label }), ...(it.hint ? [el('small', { textContent: it.hint })] : [])));
      b.setAttribute('role', 'menuitem');
      b.onclick = () => { closeMenu(); it.fn(); };
      menu.append(b);
    }
    menu.addEventListener('keydown', e => {
      if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
      e.preventDefault();
      const bs = [...menu.querySelectorAll('button')];
      const i = bs.indexOf(document.activeElement);
      bs[(i + (e.key === 'ArrowDown' ? 1 : -1) + bs.length) % bs.length].focus();
    });
    document.body.append(menu);
    const r = menu.getBoundingClientRect();
    menu.style.left = Math.max(8, Math.min(x, innerWidth - r.width - 8)) + 'px';
    menu.style.top = Math.max(8, Math.min(y, innerHeight - r.height - 8)) + 'px';
    menu.querySelector('button').focus();
  }

  const menuHead = (ns, name, note) => el('div', { className: 'hr-mh' },
    el('span', { className: 'hr-ns ' + nsClass(ns), textContent: ns }),
    el('strong', { textContent: name, title: name }),
    ...(note ? [el('small', { textContent: note })] : []));

  // Aviso breve (el id empieza por «hr-» para que el recoloreado del sitio lo respete)
  let hrToastEl = null, hrToastTimer = 0;
  function hrToast(text) {
    if (!hrToastEl) {
      hrToastEl = el('div', { id: 'hr-toast' });
      hrToastEl.setAttribute('role', 'status');
      hrToastEl.style.cssText = 'position:fixed;left:50%;bottom:28px;transform:translateX(-50%);z-index:2147483000;padding:9px 16px;border-radius:10px;'
        + 'background:var(--hr-surface2,#272a46);color:var(--hr-text,#e9eaf7);border:1px solid var(--hr-border,#34385f);box-shadow:0 6px 24px rgba(0,0,0,.45);'
        + 'font:14px/1.3 system-ui,sans-serif;pointer-events:none;opacity:0;transition:opacity .2s;';
      document.body.append(hrToastEl);
    }
    hrToastEl.textContent = text;
    hrToastEl.style.pointerEvents = 'none';
    hrToastEl.style.opacity = '1';
    clearTimeout(hrToastTimer);
    hrToastTimer = setTimeout(() => { hrToastEl.style.opacity = '0'; }, 1800);
  }

  // Copia un texto al portapapeles (con plan B para cuando la API moderna no está disponible)
  function copyText(text) {
    const legacy = () => {
      const ta = el('textarea', { value: text });
      ta.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;';
      document.body.append(ta);
      ta.select();
      let ok = false;
      try { ok = document.execCommand('copy'); } catch {}
      ta.remove();
      return ok ? Promise.resolve() : Promise.reject(new Error('copy'));
    };
    return navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(text).catch(legacy) : legacy();
  }

  // Doble clic sobre el nombre de una obra: se copia el nombre completo
  function copyOnDblClick(node, text) {
    node.title = T('Doble clic para copiar el nombre');
    node.addEventListener('dblclick', () => {
      const sel = window.getSelection && window.getSelection();
      if (sel) sel.removeAllRanges();
      copyText(text).then(() => hrToast(T('Nombre copiado')), () => hrToast(T('No se pudo copiar el nombre')));
    });
    return node;
  }

  // Copia la imagen de la portada al portapapeles (se descarga con GM_xmlhttpRequest y se pasa a PNG)
  function copyCover(url) {
    if (!url || !navigator.clipboard || typeof ClipboardItem === 'undefined') { hrToast(T('No se pudo copiar la portada')); return; }
    const png = new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        method: 'GET', url, responseType: 'blob', headers: { Referer: location.origin + '/' },
        onload: r => r.response ? resolve(r.response) : reject(new Error('empty')),
        onerror: reject, ontimeout: reject,
      });
    }).then(async blob => {
      const bmp = await createImageBitmap(blob);
      const c = document.createElement('canvas');
      c.width = bmp.width; c.height = bmp.height;
      c.getContext('2d').drawImage(bmp, 0, 0);
      if (bmp.close) bmp.close();
      return new Promise((resolve, reject) => c.toBlob(b => b ? resolve(b) : reject(new Error('png')), 'image/png'));
    });
    navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
      .then(() => hrToast(T('Portada copiada')), () => hrToast(T('No se pudo copiar la portada')));
  }

  document.addEventListener('contextmenu', e => {
    if (e.shiftKey) return;
    const a = e.target instanceof Element && e.target.closest('a[href]');
    if (!a || isReader()) return;

    const gid = galleryIdFromLink(a);
    if (gid && gid !== pageGalleryId) {
      e.preventDefault();
      const info = a.dataset.hrInfo || a.href;
      const name = a.closest('.hr-card')?.querySelector('.hr-title')?.textContent || a.textContent.trim() || `Galería ${gid}`;
      // clic derecho sobre la portada: se ofrece copiarla
      const coverImg = a.classList.contains('hr-cover-link') || (e.target instanceof HTMLImageElement) ? a.querySelector('img') : null;
      const coverUrl = coverImg && (coverImg.currentSrc || coverImg.src || coverImg.getAttribute('data-src') || '');
      const favNode = a.closest('.hr-card') || a.closest(CARD_SEL);
      const favC = favNode && (favNode._hrC || parseCard(favNode, new Set()));
      const favOn = favHas(gid);
      openMenu(e.clientX, e.clientY, menuHead('galería', name), [
        { label: 'Leer', icon: 'book', fn: () => { location.href = readerUrl(gid); } },
        { label: 'Leer en una pestaña nueva', icon: 'external', fn: () => openTab(readerUrl(gid)) },
        '-',
        { label: 'Página de la galería', icon: 'info', hint: 'Detalles, etiquetas y todas las páginas', fn: () => { location.href = info; } },
        { label: 'Página de la galería en una pestaña nueva', icon: 'external', fn: () => openTab(info) },
        ...(favC && favC.id ? ['-', { label: favOn ? 'Quitar de favoritos' : 'Añadir a favoritos', icon: 'heart', hint: favOn ? '' : 'Guárdala en tu apartado de Favoritos', fn: () => favToggle(favC) },
          { label: 'Listas…', icon: 'list', hint: 'Guardar en una lista de favoritos', fn: () => openListPicker(favC, e.clientX, e.clientY) }] : []),
        ...(coverUrl ? ['-', { label: 'Copiar portada', icon: 'copy', hint: 'Copia la imagen de la portada al portapapeles', fn: () => copyCover(coverUrl) }] : []),
      ]);
      return;
    }

    const term = termFromLink(a);
    if (!term) return;
    e.preventDefault();
    const key = normTerm(term);
    const listed = blacklist.includes(key);
    const cur = load().find(x => bare(x) === term);
    const ns = term.split(':')[0];
    const name = term.slice(ns.length + 1).replace(/_/g, ' ');
    const note = [cur ? (cur.startsWith('-') ? 'Excluido de la búsqueda de esta pestaña' : 'En la búsqueda de esta pestaña') : '', listed ? 'En lista negra' : ''].filter(Boolean).join('. ');
    const removeTerm = () => save(load().filter(x => bare(x) !== term));

    const searchItems = !cur
      ? [{ label: 'Añadir a la búsqueda', icon: 'plus', hint: 'Mostrar las galerías que lo tienen', fn: () => addTerm(term, false) },
         { label: 'Excluir de la búsqueda', icon: 'minus', hint: 'Ocultar las galerías que lo tienen', fn: () => addTerm(term, true) }]
      : [{ label: 'Quitar de la búsqueda', icon: 'x', fn: removeTerm },
         cur.startsWith('-')
           ? { label: 'Incluir en su lugar', icon: 'plus', fn: () => addTerm(term, false) }
           : { label: 'Excluir en su lugar', icon: 'minus', fn: () => addTerm(term, true) }];

    openMenu(e.clientX, e.clientY, menuHead(ns, name, note), [
      ...searchItems,
      { label: 'Buscar con esto ahora', icon: 'search', hint: 'Lo añade y ejecuta la búsqueda', fn: () => { addTerm(term, false); location.href = searchUrl(load()); } },
      { label: 'Buscar solo esto', icon: 'search', hint: 'Inicia una búsqueda nueva', fn: () => { location.href = searchUrl([term]); } },
      '-',
      { label: 'Abrir en una pestaña nueva', icon: 'external', fn: () => openTab(a.href) },
      '-',
      ftHas(term)
        ? { label: 'Quitar de favoritos', icon: 'heart', fn: () => ftRemove(term) }
        : { label: 'Añadir a favoritos', icon: 'heart', hint: 'Aparece en Favoritos, pestaña Artistas y más', fn: () => ftAdd(term, a.href) },
      '-',
      listed
        ? { label: 'Quitar de la lista negra', icon: 'ban', hint: 'Volver a mostrar estas galerías', fn: () => blRemove(key) }
        : { label: 'Añadir a la lista negra', icon: 'ban', hint: 'Ocultar las galerías que lo tienen en todas partes', danger: true, fn: () => blAdd(key) },
    ]);
  }, true);

  document.addEventListener('mousedown', e => { if (menu && !menu.contains(e.target)) closeMenu(); }, true);
  document.addEventListener('keydown', e => { if (e.key === 'Escape' && menu) { e.stopImmediatePropagation(); closeMenu(); } }, true);
  window.addEventListener('scroll', closeMenu, { passive: true });

  function applyTheme() {
    const root = document.documentElement;
    let t = THEMES[S.theme] || THEMES.midnight;
    if (isReader() && t.scheme === 'light') t = THEMES.graphite;
    for (const [k, v] of Object.entries(t)) root.style.setProperty('--hr-' + k, v);
    root.style.setProperty('--hr-accent', ACCENTS[S.accent] || ACCENTS.indigo);
    root.style.setProperty('--hr-card', (CARD_W[S.cardSize] || CARD_W.m) + 'px');
  }
  applyTheme();

  function chipEl(t, i) {
    const neg = t.startsWith('-');
    const chip = el('span', { className: 'hr-chip' + (neg ? ' neg' : ''), title: neg ? 'Excluido. Clic para incluir' : 'Clic para excluir' },
      ...(neg ? [el('span', { className: 'hr-chip-not', textContent: 'no' })] : []),
      el('span', { textContent: neg ? t.slice(1) : t }));
    chip.onclick = () => {
      const next = load();
      next[i] = next[i].startsWith('-') ? next[i].slice(1) : '-' + next[i];
      save(next);
    };
    const x = el('button', { type: 'button', textContent: '×' });
    x.setAttribute('aria-label', 'Quitar ' + t);
    x.onclick = ev => { ev.stopPropagation(); const next = load(); next.splice(i, 1); save(next); };
    chip.append(x);
    return chip;
  }

  const runSearch = () => { const t = load(); location.href = t.length ? searchUrl(t) : '/'; };

  let panel = null;
  function renderPanel() {
    const terms = load();
    if (panel) {
      panel.hidden = terms.length === 0 || isReader();
      const go = el('button', { type: 'button', className: 'hr-btn primary', textContent: 'Buscar' });
      go.onclick = runSearch;
      const clr = el('button', { type: 'button', className: 'hr-btn', textContent: 'Limpiar' });
      clr.onclick = () => save([]);
      panel.replaceChildren(...terms.map(chipEl), el('span', { className: 'hr-acts' }, go, clr));
    }
    if (appRefs) {
      appRefs.chips.replaceChildren(...terms.map(chipEl));
      const flat = terms.filter(t => !t.startsWith('-'));
      const key = flat.find(t => t.startsWith('orderbykey:'));
      appRefs.sort.value = flat.includes('orderby:popular') && key ? key.slice(11) : '';
      const lg = (flat.find(t => t.startsWith('language:')) || '').slice(9);
      if (lg && ![...appRefs.lang.options].some(o => o.value === lg)) appRefs.lang.append(el('option', { value: lg, textContent: lg }));
      appRefs.lang.value = lg;
    }
  }

  GM_addStyle(`
    .hr-sbox { position: relative; }
    .hr-sugg { position: absolute; left: -1px; right: -1px; top: calc(100% + 6px); z-index: 10; padding: 5px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px;
      box-shadow: 0 16px 40px var(--hr-shadow); max-height: 60vh; overflow: auto; cursor: default; }
    .hr-sugg[hidden] { display: none; }
    .hr-sugg-item { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
    .hr-sugg-item.on, .hr-sugg-item:hover { background: var(--hr-surface2); }
    .hr-ns { flex: none; min-width: 58px; text-align: center; padding: 3px 7px; border-radius: 6px; background: var(--hr-surface2);
      color: var(--hr-muted); font-size: 11px; font-weight: 600; }
    .hr-sugg-item.on .hr-ns, .hr-sugg-item:hover .hr-ns { background: var(--hr-bg); }
    .hr-ns.f, .hr-sugg-item .hr-ns.f { background: color-mix(in srgb, #df5279 18%, transparent); color: color-mix(in srgb, #df5279 70%, var(--hr-text)); }
    .hr-ns.m, .hr-sugg-item .hr-ns.m { background: color-mix(in srgb, #2e8ddf 18%, transparent); color: color-mix(in srgb, #2e8ddf 70%, var(--hr-text)); }
    .hr-sugg-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .hr-sugg-count { color: var(--hr-muted); font-size: 12px; font-variant-numeric: tabular-nums; }

    .hr-tagbox { position: relative; }
    .hr-tags.open { position: absolute; z-index: 30; top: -8px; left: -8px; right: -8px; padding: 8px; max-height: 320px; overflow: auto;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; box-shadow: 0 18px 44px var(--hr-shadow); }
    .hr-card.tags-open { z-index: 30; }
    .hr-tags { max-height: none; overflow: visible; }
    .hr-tag.hr-more { border: 0; cursor: pointer; font-family: inherit; font-weight: 600;
      background: var(--hr-accent-soft); color: var(--hr-text); }
    .hr-tag.hr-more:hover { background: var(--hr-accent); color: #fff; }
    #hr-app .hr-btn.primary { color: #fff; }

    .hr-hero { display: grid; grid-template-columns: minmax(200px, 300px) minmax(0, 1fr); gap: clamp(20px, 3vw, 44px); align-items: start; }
    .hr-hero-cover { position: sticky; top: 86px; display: block; aspect-ratio: 5 / 7; overflow: hidden; border-radius: 14px;
      background: var(--hr-surface2); box-shadow: 0 18px 44px var(--hr-shadow); }
    .hr-hero-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
    .hr-hero-info h1 { margin: 0; font-size: clamp(22px, 2.6vw, 32px); font-weight: 750; letter-spacing: -.02em; line-height: 1.15; overflow-wrap: anywhere; }
    .hr-jp { margin: 8px 0 0; color: var(--hr-muted); font-size: 15px; overflow-wrap: anywhere; }
    .hr-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 22px 0; }
    .hr-btn.hr-btn-lg { height: 44px; padding: 0 20px; border-radius: 12px; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; }
    .hr-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 10px 22px; margin: 0; padding: 18px 20px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 14px; }
    .hr-meta dt { color: var(--hr-muted); font-size: 13px; padding-top: 1px; }
    .hr-meta dd { margin: 0; overflow-wrap: anywhere; }
    #hr-app .hr-meta a { border-bottom: 1px solid var(--hr-border); }
    #hr-app .hr-meta a:hover { color: var(--hr-accent); border-color: var(--hr-accent); }
    .hr-tagcloud { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; }
    .hr-meta dt:has(+ dd > .hr-tagcloud) { padding-top: 8px; }
    .hr-tagcloud .hr-tag { font-size: 13px; padding: 7px 10px; border-radius: 8px; }
    .hr-sec { margin-top: 52px; }
    .hr-sec[hidden] { display: none; }
    .hr-sec-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 16px; }
    .hr-sec h2 { margin: 0; font-size: 20px; font-weight: 700; letter-spacing: -.01em; }
    .hr-thumbs { display: grid; grid-template-columns: repeat(auto-fill, minmax(128px, 1fr)); gap: 12px; }
    .hr-thumb { position: relative; display: block; aspect-ratio: 5 / 7; overflow: hidden; border-radius: 8px; background: var(--hr-surface2); }
    .hr-thumb img { display: block; width: 100%; height: 100%; object-fit: cover; transition: opacity .2s; }
    .hr-thumb img:not([data-state="done"]) { opacity: 0; }
    .hr-thumb span { position: absolute; left: 6px; bottom: 6px; padding: 2px 6px; border-radius: 5px; background: rgba(10,10,16,.68);
      color: #fff; font-size: 11px; font-weight: 600; }
    .hr-thumb:hover { box-shadow: 0 0 0 2px var(--hr-accent); }
    .hr-thumb[hidden] { display: none; }
    .hr-more-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 10px; margin-top: 22px; }
    .hr-more-bar[hidden] { display: none; }
    .hr-more-bar .hr-btn.hr-btn-lg { height: 40px; }
    .hr-more-count { color: var(--hr-muted); font-size: 13px; font-variant-numeric: tabular-nums; }
    .hr-skl { display: block; height: 14px; margin: 12px 0; border-radius: 7px; background: var(--hr-surface2); animation: hr-pulse 1.4s ease-in-out infinite; }
    .hr-skl.big { height: 34px; width: 70%; }
    @media (max-width: 720px) {
      .hr-hero { grid-template-columns: 1fr; }
      .hr-hero-cover { position: static; width: min(260px, 70vw); }
    }
    @media (prefers-reduced-motion: reduce) { .hr-skl { animation: none; } .hr-thumb img { transition: none; } }

    html.hr-rv { --hr-nav: 0px; }
    html.hr-rv.hr-rv-pin { --hr-nav: 56px; }
    html.hr-rv .navbar { display: none !important; }
    html.hr-rv, html.hr-rv body { background: var(--hr-bg) !important; }
    html.hr-rv body { margin: 0 !important; padding: var(--hr-nav) 0 0 !important; }
    html.hr-rv #comicImages { background: var(--hr-bg) !important; }
    html.hr-rv.hr-nocur, html.hr-rv.hr-nocur * { cursor: none !important; }
    #hr-rbar { position: fixed; z-index: 2147483646; top: 0; left: 0; right: 0; height: 56px; display: flex; align-items: center;
      gap: 6px; padding: 0 10px; background: color-mix(in srgb, var(--hr-bg) 82%, transparent); backdrop-filter: blur(16px);
      border-bottom: 1px solid var(--hr-border); color: var(--hr-text); font: 14px/1.3 var(--hr-font); color-scheme: dark;
      transition: transform .2s ease, opacity .2s ease; box-sizing: border-box; }
    #hr-rbar * { box-sizing: border-box; }
    html.hr-idle #hr-rbar { transform: translateY(-100%); opacity: 0; pointer-events: none; }
    .hr-rb { flex: none; display: inline-grid; place-items: center; height: 38px; min-width: 38px; padding: 0 8px; border: 0;
      border-radius: 10px; background: none; color: var(--hr-muted); cursor: pointer; font: 600 13px/1 var(--hr-font); }
    .hr-rb:hover { background: var(--hr-hover); color: var(--hr-text); }
    .hr-rb[aria-pressed="true"] { color: var(--hr-accent); }
    .hr-rb:focus-visible, #hr-rbar input:focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 1px; }
    .hr-rtitle { min-width: 0; display: flex; flex-direction: column; margin-left: 4px; }
    .hr-rtitle strong { font-size: 14px; font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .hr-rtitle span { color: var(--hr-muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .hr-rspacer { flex: 1; }
    .hr-rgroup { flex: none; display: flex; align-items: center; gap: 2px; padding: 2px; border-radius: 12px;
      background: var(--hr-surface); border: 1px solid var(--hr-border); }
    .hr-rgroup .hr-rb { height: 34px; min-width: 34px; }
    .hr-pagebox { display: flex; align-items: center; gap: 5px; padding: 0 4px; color: var(--hr-muted); font-variant-numeric: tabular-nums; cursor: text; }
    #hr-rbar #hr-page { width: 52px; height: 30px; margin: 0; padding: 0 4px; text-align: center; border-radius: 8px;
      border: 1px solid transparent; background: var(--hr-bg); color: var(--hr-text); font: 600 14px/1 var(--hr-font); -moz-appearance: textfield; }
    #hr-rbar #hr-page:focus { border-color: var(--hr-accent); outline: none; }
    #hr-rbar #hr-page::-webkit-inner-spin-button, #hr-rbar #hr-page::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
    #hr-rbar #hr-total { color: var(--hr-muted); }
    .hr-zoomval { min-width: 54px !important; font-variant-numeric: tabular-nums; }
    #hr-progress { position: fixed; z-index: 2147483646; left: 0; right: 0; top: 56px; height: 2px; pointer-events: none; transition: top .2s ease; }
    html.hr-idle #hr-progress { top: 0; }
    #hr-pcount { position: fixed; z-index: 2147483645; top: 10px; right: 12px; padding: 4px 10px; border-radius: 999px;
      background: color-mix(in srgb, var(--hr-bg) 78%, transparent); backdrop-filter: blur(8px); border: 1px solid var(--hr-border);
      color: var(--hr-text); font: 600 12px/1.2 var(--hr-font); font-variant-numeric: tabular-nums; pointer-events: none;
      opacity: 0; transform: translateY(-6px); transition: opacity .2s ease, transform .2s ease; }
    html.hr-idle #hr-pcount { opacity: .85; transform: none; }
    #hr-progress i { display: block; height: 100%; width: 0; background: var(--hr-accent); transition: width .2s ease; }
    @media (max-width: 760px) { .hr-rtitle span, .hr-rzoom, #hr-fullbtn { display: none !important; } }
    @media (prefers-reduced-motion: reduce) { #hr-rbar, #hr-progress, #hr-progress i { transition: none; } }

    :where(html.hr-ct:not(.hr-ui)), :where(html.hr-ct:not(.hr-ui)) body { background-color: var(--hr-bg) !important; color: var(--hr-text) !important; color-scheme: var(--hr-scheme); }
    :where(html.hr-ct:not(.hr-ui)) :where(div, table, thead, tbody, tr, td, th, ul, ol, li, section, article, header, footer, main, nav, p, h1, h2, h3):where(:not([id^="hr-"], [id^="hr-"] *)) {
      background-color: transparent !important; border-color: var(--hr-border) !important; }
    :where(html.hr-ct:not(.hr-ui)) :where(h1, h2, h3, h4, h5, h6, p, td, th, li, span, div, label, dt, dd, b, strong):where(:not([id^="hr-"], [id^="hr-"] *)) { color: var(--hr-text) !important; }
    :where(html.hr-ct:not(.hr-ui)) a:where(:not([id^="hr-"] *)) { color: color-mix(in srgb, var(--hr-accent) 45%, var(--hr-text)) !important; }
    :where(html.hr-ct:not(.hr-ui)) :where(input, select, textarea):where(:not([id^="hr-"] *)) {
      background-color: var(--hr-surface) !important; color: var(--hr-text) !important; border: 1px solid var(--hr-border) !important; border-radius: 6px; }
    :where(html.hr-ct:not(.hr-ui)) button:where(:not([id^="hr-"], [id^="hr-"] *)) { background-color: var(--hr-surface2) !important; color: var(--hr-text) !important; border-color: var(--hr-border) !important; }
    html.hr-ct:not(.hr-ui) .gallery-content > div { background-color: var(--hr-surface) !important; border: 1px solid var(--hr-border) !important; border-radius: 12px !important; }
    html.hr-ct:not(.hr-ui) .gallery-content > div h1 a { color: var(--hr-text) !important; }
    html.hr-ct:not(.hr-ui) :is(.relatedtags, .tags, #tags) a { background-color: var(--hr-surface2) !important; color: var(--hr-text) !important; border-color: transparent !important; }
    html.hr-ct:not(.hr-ui) .page-container a { color: var(--hr-text) !important; }
  `);

  let app = null, appRefs = null, gridSig = '', settled = false;
  const wantUi = () => S.revamp && S.newUi && !isReader();
  const wantReaderUi = () => S.revamp && S.newUi && isReader();
  {
    const c = document.documentElement.classList;
    if (wantUi()) c.add('hr-ui');
    if (wantReaderUi()) c.add('hr-rv');
    if (S.revamp && S.classicTheme && !isReader()) c.add('hr-ct');
  }

  const ICONS = {
    search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>',
    sliders: '<path d="M4 7h9M17 7h3M4 17h3M11 17h9"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="17" r="2"/>',
    back: '<path d="M19 12H5M11 18l-6-6 6-6"/>',
    prev: '<path d="M15 18l-6-6 6-6"/>',
    next: '<path d="M9 18l6-6-6-6"/>',
    fitH: '<path d="M12 3v18M8 7l4-4 4 4M8 17l4 4 4-4"/>',
    fitW: '<path d="M3 12h18M7 8l-4 4 4 4M17 8l4 4-4 4"/>',
    full: '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>',
    grid: '<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/>',
    minus: '<path d="M6 12h12"/>',
    plus: '<path d="M12 6v12M6 12h12"/>',
    book: '<path d="M4 5.5C6.5 4 9.5 4 12 6c2.5-2 5.5-2 8-.5V19c-2.5-1.5-5.5-1.5-8 .5-2.5-2-5.5-2-8-.5z"/><path d="M12 6v13.5"/>',
    external: '<path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',
    x: '<path d="M6 6l12 12M18 6L6 18"/>',
    copy: '<rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V6a2 2 0 0 1 2-2h9"/>',
    ban: '<circle cx="12" cy="12" r="8"/><path d="M6.5 6.5l11 11"/>',
    info: '<circle cx="12" cy="12" r="8.5"/><path d="M12 11v5M12 8h.01"/>',
    chevDown: '<path d="M6 9l6 6 6-6"/>',
    chevsDown: '<path d="M6 6l6 6 6-6M6 13l6 6 6-6"/>',
    pages: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>',
    list: '<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>',
    edit: '<path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
    heart: '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
  };
  const svg = html => { const t = document.createElement('template'); t.innerHTML = html; return t.content.firstChild; };
  const icon = (name, size = 18) => svg(`<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[name]}</svg>`);
  const setText = (n, t) => { const c = n.textContent; if (c !== t && !(EN_ON && c === trEn(t))) n.textContent = t; };
  const nsClass = ns => ns === 'female' ? 'f' : ns === 'male' ? 'm' : '';

  const SORTS = [['', 'Más recientes'], ['today', 'Populares hoy'], ['week', 'Populares esta semana'], ['month', 'Populares este mes'], ['year', 'Populares este año']];
  const LANGS = [['', 'Cualquier idioma'], ['english', 'Inglés'], ['japanese', 'Japonés'], ['chinese', 'Chino'], ['korean', 'Coreano'],
    ['spanish', 'Español'], ['french', 'Francés'], ['german', 'Alemán'], ['russian', 'Ruso'], ['portuguese', 'Portugués']];
  const KIND = { tag: 'Etiqueta', artist: 'Artista', series: 'Serie', character: 'Personaje', group: 'Grupo', type: 'Tipo' };

  function replaceTerms(drop, add) {
    const t = load().filter(x => !drop(bare(x)));
    save([...t, ...add]);
    runSearch();
  }

  const suggestFn = () => typeof W.get_suggestions_for_query === 'function' ? W.get_suggestions_for_query : null;
  function attachSuggest(input, box) {
    const list = el('div', { className: 'hr-sugg', hidden: true });
    list.setAttribute('role', 'listbox');
    box.append(list);
    let items = [], idx = -1, seq = 0, timer = 0;
    const close = () => { list.hidden = true; items = []; idx = -1; };

    const collect = (x, out = []) => {
      if (!x || out.length > 50) return out;
      if (Array.isArray(x)) {
        if (typeof x[0] === 'string') out.push({ s: x[0], t: x[1], n: typeof x[3] === 'string' ? x[3] : x[2] });
        else for (const y of x) collect(y, out);
      } else if (typeof x === 'object') {
        if (typeof x.s === 'string') out.push(x);
        else for (const y of Object.values(x)) if (y && typeof y === 'object') collect(y, out);
      }
      return out;
    };
    const norm = x => {
      const name = String(x.s).trim();
      if (!name) return null;
      const n = typeof x.n === 'string' && /^[a-z]+$/.test(x.n) ? x.n : 'tag';
      return { name, count: +x.t || 0, ns: n, term: `${n}:${name.replace(/\s+/g, '_')}` };
    };
    async function run() {
      const raw = (input.value.match(/(\S*)$/) || ['', ''])[1];
      const neg = raw.startsWith('-');
      const q = raw.replace(/^-/, '');
      const fn = suggestFn();
      if (!q || !fn) return close();
      const my = ++seq;
      let res = null;
      try { res = await fn.call(W, q); } catch {}
      if (my !== seq || document.activeElement !== input) return;
      const seen = new Set();
      items = collect(res).map(norm).filter(x => x && !seen.has(x.term) && seen.add(x.term)).slice(0, 10).map(x => ({ ...x, neg }));
      idx = -1;
      draw();
    }
    function draw() {
      if (!items.length) return close();
      list.replaceChildren(...items.map((it, i) => {
        const row = el('div', { className: 'hr-sugg-item' + (i === idx ? ' on' : '') },
          el('span', { className: 'hr-ns ' + nsClass(it.ns), textContent: (it.neg ? 'not ' : '') + it.ns }),
          el('span', { className: 'hr-sugg-name', textContent: it.name }),
          el('span', { className: 'hr-sugg-count', textContent: it.count ? it.count.toLocaleString() : '' }));
        row.setAttribute('role', 'option');
        row.setAttribute('aria-selected', String(i === idx));
        row.addEventListener('mousedown', e => { e.preventDefault(); pick(it); });
        return row;
      }));
      list.hidden = false;
      list.querySelector('.on')?.scrollIntoView({ block: 'nearest' });
    }
    function pick(it) {
      input.value = input.value.replace(/\S*$/, '');
      const t = load().filter(x => bare(x) !== it.term);
      t.push((it.neg ? '-' : '') + it.term);
      save(t);
      close();
      input.focus();
    }
    input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 120); });
    input.addEventListener('blur', () => setTimeout(close, 120));
    return {
      handleKey(e) {
        if (list.hidden || !items.length) return false;
        const n = items.length;
        if (e.key === 'ArrowDown') idx = idx + 1 >= n ? -1 : idx + 1;
        else if (e.key === 'ArrowUp') idx = idx - 1 < -1 ? n - 1 : idx - 1;
        else if ((e.key === 'Enter' && idx >= 0) || (e.key === 'Tab' && !e.shiftKey)) { e.preventDefault(); pick(items[Math.max(idx, 0)]); return true; }
        else if (e.key === 'Escape') { e.preventDefault(); close(); return true; }
        else return false;
        e.preventDefault();
        draw();
        return true;
      },
    };
  }

  function buildTopBar() {
    const chips = el('span', { className: 'hr-chips' });
    const input = el('input', { type: 'text', placeholder: 'Buscar etiquetas, artistas o títulos', spellcheck: false, autocomplete: 'off' });
    input.setAttribute('aria-label', 'Buscar');
    const sbox = el('div', { className: 'hr-sbox' }, icon('search', 16), chips, input);
    sbox.addEventListener('click', e => { if (e.target === sbox) input.focus(); });
    const sugg = attachSuggest(input, sbox);
    const commit = () => {
      const words = input.value.trim().split(/\s+/).filter(Boolean);
      if (words.length) { const t = load(); for (const w of words) if (!t.includes(w)) t.push(w); store(t); }
      input.value = '';
      runSearch();
    };
    input.addEventListener('keydown', e => {
      if (sugg.handleKey(e)) return;
      if (e.key === 'Enter') { e.preventDefault(); commit(); }
      else if (e.key === 'Backspace' && !input.value) { const t = load(); if (t.length) { t.pop(); save(t); } }
      else if (e.key === 'Escape') input.blur();
    });

    const select = (opts, label) => {
      const s = el('select', { className: 'hr-select' });
      s.setAttribute('aria-label', label);
      for (const [v, text] of opts) s.append(el('option', { value: v, textContent: text }));
      return s;
    };
    const sort = select(SORTS, 'Ordenar');
    sort.onchange = () => replaceTerms(x => /^orderby/.test(x), sort.value ? ['orderby:popular', 'orderbykey:' + sort.value] : []);
    const lang = select(LANGS, 'Idioma');
    lang.onchange = () => replaceTerms(x => x.startsWith('language:'), lang.value ? ['language:' + lang.value] : []);

    // Menú expandible "Explorar": las categorías del menú original del sitio (Tags, Artists, Series, Characters) y los tipos
    const navLink = (re, fallback) => [...document.querySelectorAll('.navbar a[href]')].find(a => re.test(a.textContent.trim()))?.getAttribute('href') || fallback;
    const EXPLORE = [
      ['Categorías', [
        ['Etiquetas', navLink(/^tags$/i, '/alltags-a.html')],
        ['Artistas', navLink(/^artists$/i, '/allartists-a.html')],
        ['Series', navLink(/^series$/i, '/allseries-a.html')],
        ['Personajes', navLink(/^characters$/i, '/allcharacters-a.html')],
      ]],
      ['Tipo', [['Doujinshi', 'doujinshi'], ['Manga', 'manga'], ['Artist CG', 'artistcg'], ['Game CG', 'gamecg'], ['Image set', 'imageset'], ['Anime', 'anime']]
        .map(([t, v]) => [t, `/type/${v}-all.html`])],
    ];
    const menuBtn = el('button', { type: 'button', className: 'hr-select hr-menu-btn', textContent: 'Explorar' });
    menuBtn.setAttribute('aria-haspopup', 'true');
    menuBtn.setAttribute('aria-expanded', 'false');
    const pop = el('div', { className: 'hr-pop', hidden: true }, ...EXPLORE.flatMap(([title, items]) =>
      [el('div', { className: 'hr-pop-title', textContent: title }), ...items.map(([t, href]) => el('a', { className: 'hr-pop-item', href, textContent: t }))]));
    const menu = el('div', { className: 'hr-menu' }, menuBtn, pop);
    const setPop = open => {
      pop.hidden = !open;
      menuBtn.setAttribute('aria-expanded', String(open));
      if (!open) return;
      pop.style.left = pop.style.right = '';
      const r = pop.getBoundingClientRect();
      if (r.left < 8) { pop.style.right = 'auto'; pop.style.left = '0'; }
    };
    menuBtn.onclick = e => { e.stopPropagation(); setPop(pop.hidden); };
    document.addEventListener('click', e => { if (menu.isConnected && !menu.contains(e.target)) setPop(false); });
    menu.addEventListener('keydown', e => { if (e.key === 'Escape') { setPop(false); menuBtn.focus(); } });

    const go = el('button', { type: 'button', className: 'hr-btn primary', textContent: 'Buscar' });
    go.onclick = commit;
    const gear = el('button', { type: 'button', className: 'hr-icon', title: 'Ajustes' }, icon('sliders'));
    gear.setAttribute('aria-label', 'Ajustes de Hitomi Enhanced');
    gear.onclick = openSettings;
    const brand = el('a', { className: 'hr-brand', href: '/', title: 'Últimas galerías' },
      el('img', { src: LOGO_URL, alt: '' }), el('span', { textContent: 'Hitomi' }));
    const favTop = el('button', { type: 'button', className: 'hr-icon hr-fav-top', title: 'Favoritos' }, icon('heart'), el('span', { className: 'hr-fav-count', hidden: true }));
    favTop.setAttribute('aria-label', 'Favoritos');
    favTop.onclick = openFavs;
    return { header: el('header', { className: 'hr-top' }, brand, sbox, go, sort, lang, menu, favTop, gear), refs: { chips, input, sort, lang, favTop } };
  }

  function buildApp() {
    if (app) return;
    const top = buildTopBar();
    appRefs = { ...top.refs, mode: pageGalleryId ? 'gallery' : 'list' };
    let main;
    if (appRefs.mode === 'list') {
      const h1 = el('h1'), kind = el('span', { className: 'hr-kind' }), stat = el('span', { className: 'hr-stat' });
      const grid = el('div', { className: 'hr-grid' });
      const pager = el('nav', { className: 'hr-pager' });
      pager.setAttribute('aria-label', 'Páginas');
      const favInput = el('input', { type: 'text', placeholder: 'Filtrar favoritos por título, artista o etiqueta', spellcheck: false, autocomplete: 'off' });
      favInput.setAttribute('aria-label', 'Filtrar favoritos');
      const favBox = el('div', { className: 'hr-sbox' }, icon('search', 16), favInput);
      favBox.addEventListener('click', e => { if (e.target === favBox) favInput.focus(); });
      const sortSel = el('select', { className: 'hr-select' }, ...FAV_SORTS.map(([v, t]) => el('option', { value: v, textContent: t })));
      sortSel.setAttribute('aria-label', 'Ordenar favoritos');
      const favbar = el('div', { className: 'hr-favbar', hidden: true }, favBox, sortSel);
      const listbar = el('div', { className: 'hr-lbar', hidden: true });
      const tabbar = el('div', { className: 'hr-lbar hr-tabbar', hidden: true });
      const termbar = el('div', { className: 'hr-lbar hr-ttabs', hidden: true });
      const termFav = el('button', { type: 'button', className: 'hr-btn hr-termfav', hidden: true }, icon('heart', 16), el('span', { textContent: 'Añadir a favoritos' }));
      termFav.onclick = () => { if (termFav.dataset.term) ftToggle(termFav.dataset.term, location.pathname.replace(/-[a-z]+(?:-\d+)?\.html$/, '-all.html')); };
      Object.assign(appRefs, { h1, kind, stat, grid, pager, favInput, sortSel, favbar, listbar, tabbar, termbar, termFav, favQ: '', favL: '', favTab: 'g', favNs: '', favTerm: '', tcLimit: FT_PAGE, tabSig: '', favShown: FAV_STEP });
      favInput.oninput = () => { appRefs.favQ = favInput.value; appRefs.favShown = FAV_STEP; renderApp(); };
      sortSel.onchange = () => { S.favSort = sortSel.value; saveSettings(); appRefs.favShown = FAV_STEP; renderApp(); };
      main = el('main', { className: 'hr-main' }, el('div', { className: 'hr-headline' }, h1, kind, termFav, stat), tabbar, favbar, listbar, termbar, grid, pager);
    } else {
      main = buildGalleryMain();
    }
    app = el('div', { id: 'hr-app' }, top.header, main);
    document.body.append(app);
    setTimeout(() => { settled = true; renderApp(); }, 8000);
    renderPanel();
    paintFavs();
    renderApp();
  }

  function teardownApp() {
    app?.remove();
    app = appRefs = null;
    gridSig = '';
    document.documentElement.classList.remove('hr-ui');
  }

  function syncUi() {
    if (!document.body || isReader()) return;
    document.documentElement.classList.toggle('hr-ct', !!(S.revamp && S.classicTheme));
    const ok = wantUi() && (pageGalleryId ? !!W.galleryinfo?.files : (favView() || !!document.querySelector('.gallery-content')));
    if (ok) {
      document.documentElement.classList.add('hr-ui');
      if (!app) buildApp(); else { gridSig = ''; renderApp(); }
    } else teardownApp();
  }

  function parseCard(card, bl) {
    const links = [...card.querySelectorAll('a[href]')];
    const ga = links.find(a => galleryIdFromLink(a));
    if (!ga) return null;
    const c = { id: galleryIdFromLink(ga), href: ga.dataset.hrInfo || ga.href, title: '', covers: [], artists: [], series: [], tags: [], type: null, lang: null };
    c.title = (card.querySelector('h1') || ga).textContent.trim() || 'Sin título';

    const push = u => {
      u = (u || '').trim().split(/\s+/)[0];
      if (!u || u.startsWith('data:')) return;
      try { u = new URL(u, location.href).href; } catch { return; }
      if (!c.covers.includes(u)) c.covers.push(u);
    };
    const sets = [];
    const pics = [...card.querySelectorAll('picture')];
    for (const node of pics.length ? pics : [...card.querySelectorAll('img')]) {
      c.covers = [];
      const img = node.tagName === 'IMG' ? node : node.querySelector('img');
      if (img) { push(img.getAttribute('data-src')); push(img.getAttribute('src')); (img.getAttribute('data-srcset') || '').split(',').forEach(push); }
      if (node.tagName !== 'IMG') node.querySelectorAll('source').forEach(s => (s.getAttribute('data-srcset') || s.getAttribute('srcset') || '').split(',').forEach(push));
      if (c.covers.length && !sets.some(x => x[0] === c.covers[0])) sets.push(c.covers);
    }
    c.covers = sets[0] || [];

    for (const a of links) {
      const t = termFromLink(a);
      if (!t) continue;
      const item = { href: a.href, text: a.textContent.trim() || t.replace(/^[a-z]+:/, '').replace(/_/g, ' '), term: t };
      if (t.startsWith('artist:') || t.startsWith('group:')) c.artists.push(item);
      else if (t.startsWith('series:')) c.series.push(item);
      else if (t.startsWith('type:')) c.type = item;
      else if (t.startsWith('language:')) c.lang = item;
      else if (/^(tag|female|male):/.test(t)) c.tags.push(item);
    }
    c.hit = cardHit(card, bl);
    return c;
  }

  const tagLink = t => el('a', { className: 'hr-tag ' + nsClass(t.term.split(':')[0]), href: t.href, textContent: t.text, title: t.term });

  // Número de páginas de cada obra: se consulta «galleries/<id>.js» (máx. 3 a la vez) y se recuerda en esta pestaña
  const PGC_KEY = 'hr-pgc';
  const pgCache = new Map();
  const pgQueue = [];
  let pgBusy = 0, pgStore = null;
  const pgLoadStore = () => { if (!pgStore) { try { pgStore = JSON.parse(sessionStorage.getItem(PGC_KEY)) || {}; } catch { pgStore = {}; } } return pgStore; };
  function pgRemember(id, n) {
    const st = pgLoadStore();
    st[id] = n;
    try { sessionStorage.setItem(PGC_KEY, JSON.stringify(st)); } catch {}
  }
  function pagesFor(id, cb) {
    id = String(id);
    let v = pgCache.get(id);
    if (v === undefined) { const n = pgLoadStore()[id]; if (n > 0) { pgCache.set(id, n); v = n; } }
    if (typeof v === 'number') { cb(v); return; }
    if (v) { v.push(cb); return; }
    pgCache.set(id, [cb]);
    pgQueue.push(id);
    pgPump();
  }
  function pgPump() {
    while (pgBusy < 3 && pgQueue.length) {
      const id = pgQueue.shift();
      pgBusy++;
      const done = n => {
        pgBusy--;
        const cbs = pgCache.get(id) || [];
        if (n > 0) { pgCache.set(id, n); pgRemember(id, n); cbs.forEach(f => f(n)); } else pgCache.delete(id);
        pgPump();
      };
      fetch('//' + (W.domain || location.hostname) + '/galleries/' + id + '.js')
        .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); })
        .then(t => { const g = JSON.parse(t.slice(t.indexOf('=') + 1).trim().replace(/;$/, '')); done((g.files || []).length); })
        .catch(() => done(0));
    }
  }

  function cardEl(c) {
    const coverLink = el('a', { className: 'hr-cover-link', href: c.href });
    coverLink.setAttribute('aria-label', c.title);
    const cover = el('div', { className: 'hr-cover' }, coverLink);
    if (c.covers.length) {
      let k = 0;
      const img = el('img', { alt: '', loading: 'lazy', decoding: 'async' });
      img.onerror = () => { if (++k < c.covers.length) img.src = c.covers[k]; else img.remove(); };
      img.src = c.covers[0];
      coverLink.append(img);
    }
    if (c.type) cover.append(el('a', { className: 'hr-pill type', href: c.type.href, textContent: c.type.text, title: c.type.term }));
    if (c.lang) cover.append(el('a', { className: 'hr-pill lang', href: c.lang.href, textContent: c.lang.text, title: c.lang.term }));
    if (c.id) {
      const pp = el('span', { className: 'hr-pill pages', hidden: true }, icon('pages', 12), el('span'));
      const setN = n => {
        if (!n) return;
        pp.lastChild.textContent = String(n);
        pp.title = n + ' páginas';
        pp.setAttribute('aria-label', n + ' páginas');
        pp.hidden = false;
        c.pages = n;
        if (favHas(c.id) && favs[c.id].pages !== n) { favs[c.id].pages = n; favSave(); }
      };
      if (c.pages) setN(c.pages); else pagesFor(c.id, setN);
      cover.append(pp);
    }
    if (c.id) {
      const fav = el('button', { type: 'button', className: 'hr-fav-btn' }, icon('heart', 16));
      fav.dataset.favId = c.id;
      fav.onclick = e => { e.preventDefault(); e.stopPropagation(); favToggle(c); };
      paintFav(fav);
      cover.append(fav);
      const lst = el('button', { type: 'button', className: 'hr-lst-btn', title: 'Añadir a una lista' }, icon('list', 16));
      lst.setAttribute('aria-label', 'Añadir a una lista');
      lst.dataset.lstId = c.id;
      lst.onclick = e => { e.preventDefault(); e.stopPropagation(); const r = lst.getBoundingClientRect(); openListPicker(c, r.left, r.bottom + 6); };
      paintLst(lst);
      cover.append(lst);
    }

    const card = el('article', { className: 'hr-card' }, cover, el('a', { className: 'hr-title', href: c.href, textContent: c.title, title: c.title }));
    const people = [...c.artists, ...c.series];
    if (people.length) {
      const sub = el('div', { className: 'hr-sub' });
      people.forEach((p, i) => { if (i) sub.append(', '); sub.append(el('a', { href: p.href, textContent: p.text, title: p.term })); });
      card.append(sub);
    }
    if (S.cardTags !== 'off' && c.tags.length) {
      const LIMIT = 8;
      const wrap = el('div', { className: 'hr-tags' });
      const box = el('div', { className: 'hr-tagbox' }, wrap);
      let off = null;
      const fill = open => {
        off?.();
        off = null;
        if (open) box.style.height = box.offsetHeight + 'px';
        else box.style.height = '';
        wrap.classList.toggle('open', open);
        card.classList.toggle('tags-open', open);
        wrap.replaceChildren(...(open || S.cardTags === 'all' ? c.tags : c.tags.slice(0, LIMIT)).map(tagLink));
        if (S.cardTags === 'all' || c.tags.length <= LIMIT) return;
        const b = el('button', { type: 'button', className: 'hr-tag hr-more', textContent: open ? 'Menos' : `+${c.tags.length - LIMIT}`,
          title: open ? 'Mostrar menos etiquetas' : 'Mostrar todas las etiquetas' });
        b.setAttribute('aria-expanded', String(open));
        b.onclick = () => { fill(!open); wrap.querySelector('.hr-more')?.focus(); };
        wrap.append(b);
        if (open) {
          const outside = e => { if (!wrap.contains(e.target) && !menu?.contains(e.target)) fill(false); };
          const esc = e => { if (e.key === 'Escape' && !menu) fill(false); };
          document.addEventListener('pointerdown', outside, true);
          document.addEventListener('keydown', esc);
          off = () => { document.removeEventListener('pointerdown', outside, true); document.removeEventListener('keydown', esc); };
        }
      };
      fill(false);
      card.append(box);
    }
    if (c.hit) { card.classList.add('is-dim'); cover.dataset.bl = c.hit; }
    card._hrC = c;
    return card;
  }

  function cardEls(cards) {
    const bl = new Set(blacklist);
    const out = [];
    for (const card of cards) {
      const c = parseCard(card, bl);
      if (!c || (c.hit && S.blMode === 'hide')) continue;
      out.push(cardEl(c));
    }
    return out;
  }

  const skeleton = () => el('article', { className: 'hr-card hr-skel' }, el('div', { className: 'hr-cover' }), el('i'), el('i'));

  function parsePages() {
    const pc = document.querySelector('.page-container');
    if (!pc) return [];
    return [...pc.querySelectorAll('li')]
      .map(li => ({ label: li.textContent.trim(), href: li.querySelector('a')?.href || '' }))
      .filter(p => p.label);
  }

  // Cambio de página suave: cruce entre documentos (View Transitions) y atenuado de lo que se va
  if (wantUi()) {
    GM_addStyle(`
      @view-transition { navigation: auto; }
      ::view-transition-old(root) { animation: .16s ease-out both hr-vt-out; }
      ::view-transition-new(root) { animation: .26s ease-out both hr-vt-in; }
      @keyframes hr-vt-out { to { opacity: 0; } }
      @keyframes hr-vt-in { from { opacity: 0; } }
      .hr-grid.hr-leaving, .hr-pager.hr-leaving { opacity: .35; transform: translateY(6px); pointer-events: none;
        transition: opacity .16s ease, transform .16s ease; }
      @media (prefers-reduced-motion: reduce) {
        ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }
        .hr-grid.hr-leaving, .hr-pager.hr-leaving { transition: none; transform: none; }
      }
    `);
    // al volver con «atrás» desde la caché, quita el atenuado
    window.addEventListener('pageshow', () => {
      document.querySelectorAll('.hr-leaving').forEach(x => x.classList.remove('hr-leaving'));
      if (appRefs) appRefs.navigating = false;
    });
  }

  function renderApp() {
    if (!appRefs) return;
    const R = appRefs;
    const cards = [...document.querySelectorAll(CARD_SEL)];
    const cardSig = [cards.map(c => c.querySelector('a[href]')?.getAttribute('href')).join(','), blacklist.join(','), S.blMode, S.cardTags].join('|');

    if (R.mode === 'gallery') {
      if (!R.relGrid || cardSig === gridSig) return;
      gridSig = cardSig;
      const out = cardEls(cards);
      R.relSection.hidden = !out.length;
      R.relGrid.replaceChildren(...out);
      return;
    }

    R.favTop.classList.toggle('on', favView());
    if (favView()) { renderFavTabs(R); if (R.favTab === 't') renderFavTerms(R); else renderFavs(); return; }
    R.tabbar.hidden = true;
    R.termbar.hidden = true;
    R.favbar.hidden = true;
    R.listbar.hidden = true;

    const title = (document.title || '').replace(/\s*[|\-]\s*hitomi\.la.*$/i, '').trim();
    const m = location.pathname.match(/^\/([a-z]+)\//);
    setText(R.h1, title && !/^hitomi\.la$/i.test(title) ? title : 'Últimas galerías');
    setText(R.kind, (m && KIND[m[1]]) || (location.pathname === '/search.html' ? 'Resultados de búsqueda' : ''));
    const tk = termPageKey();
    R.termFav.hidden = !tk;
    if (tk) { R.termFav.dataset.term = tk; paintTermFav(); }

    const pages = parsePages();
    const sig = cardSig + '|' + pages.map(p => p.label + (p.href ? '' : '*')).join(',') + '|' + settled;
    if (sig !== gridSig) {
      gridSig = sig;
      const out = cardEls(cards);
      R.shown = out.length;
      // Las tarjetas entran con un fundido suave la primera vez y al sustituir a los marcadores, no en cada redibujado
      if (out.length && (!R.filled || R.grid.querySelector('.hr-skel'))) {
        out.forEach((x, i) => { x.classList.add('hr-fadein'); x.style.animationDelay = Math.min(i, 10) * 14 + 'ms'; });
      }
      if (out.length) R.filled = true;
      if (out.length) R.grid.replaceChildren(...out);
      else if (!cards.length && !settled) R.grid.replaceChildren(...Array.from({ length: 12 }, skeleton));
      else R.grid.replaceChildren(el('p', { className: 'hr-empty', textContent: cards.length ? 'Todo lo de esta página está en la lista negra.' : 'No hay galerías aquí.' }));

      R.pager.replaceChildren(...pages.map(p => {
        if (!p.href) return el('span', { className: 'hr-pg ' + (/^\d+$/.test(p.label) ? 'cur' : 'gap'), textContent: p.label });
        const a = el('a', { className: 'hr-pg', href: p.href, textContent: p.label });
        a.addEventListener('click', e => {
          if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
          e.preventDefault();
          if (R.navigating) return;
          R.navigating = true;
          // Feedback inmediato: la cuadrícula se atenúa y la vista sube suave; luego se navega (el cruce lo hace View Transitions)
          const calm = matchMedia('(prefers-reduced-motion: reduce)').matches;
          R.grid.classList.add('hr-leaving');
          R.pager.classList.add('hr-leaving');
          if (!calm) scrollTo({ top: 0, behavior: 'smooth' });
          setTimeout(() => { location.href = p.href; }, calm ? 0 : 150);
        });
        return a;
      }));
    }

    const n = R.shown || 0;
    let s = cards.length ? `${n} ${n === 1 ? 'galería' : 'galerías'} en esta página` : '';
    if (blCount) s += `, ${blCount} ${blState(blCount)} por tu lista negra`;
    setText(R.stat, s);
  }

  // Miniaturas de la página de una obra: se cargan todas a la vez en cuanto se acercan a la pantalla,
  // sin cola ni pausas (el límite y la pausa de los ajustes solo afectan a la tira del lector).
  function makeThumbLoader() {
    const io = new IntersectionObserver(entries => {
      for (const en of entries) {
        if (!en.isIntersecting) continue;
        io.unobserve(en.target);
        load(en.target);
      }
    }, { rootMargin: '1500px' });
    function load(img) {
      if (img.dataset.state) return;
      const urls = img._hrUrls;
      let k = 0;
      img.dataset.state = 'loading';
      img.onload = () => { img.dataset.state = 'done'; };
      img.onerror = () => {
        if (++k < urls.length) { img.src = urls[k]; return; }
        img.dataset.state = 'err';
      };
      img.src = urls[0];
    }
    return { add(img, urls) { img._hrUrls = urls; io.observe(img); } };
  }

  function fmtDate(s) {
    if (!s) return '';
    const d = new Date(String(s).replace(' ', 'T').replace(/([+-]\d\d)$/, '$1:00'));
    return isNaN(d) ? String(s).slice(0, 10) : d.toLocaleDateString('es', { year: 'numeric', month: 'short', day: 'numeric' });
  }

  function buildGalleryMain() {
    const hero = el('section', { className: 'hr-hero' },
      el('div', { className: 'hr-hero-cover' }),
      el('div', { className: 'hr-hero-info' }, el('i', { className: 'hr-skl big' }), el('i', { className: 'hr-skl' }), el('i', { className: 'hr-skl' })));
    const pagesSec = el('section', { className: 'hr-sec', hidden: true });
    const relGrid = el('div', { className: 'hr-grid' });
    const relSection = el('section', { className: 'hr-sec', hidden: true },
      el('div', { className: 'hr-sec-head' }, el('h2', { textContent: 'Galerías relacionadas' })), relGrid);
    Object.assign(appRefs, { hero, pagesSec, relGrid, relSection });
    waitFor(() => W.galleryinfo?.files, 15000).then(ok => {
      if (!appRefs || appRefs.mode !== 'gallery') return;
      if (ok) fillGallery(W.galleryinfo);
      else teardownApp();
    });
    return el('main', { className: 'hr-main' }, hero, pagesSec, relSection);
  }

  function fillGallery(g) {
    const R = appRefs;
    const id = g.id || pageGalleryId;
    const files = g.files || [];
    const named = (list, key, path) => (list || []).map(x => ({
      text: x[key], href: x.url || `/${path}/${encodeURIComponent(x[key])}-all.html`, term: `${path}:${String(x[key]).replace(/\s+/g, '_')}`,
    }));
    const links = items => items.length
      ? el('span', {}, ...items.flatMap((it, i) => [...(i ? [', '] : []), el('a', { href: it.href, textContent: it.text, title: it.term })]))
      : null;
    const tags = (g.tags || []).map(t => {
      const f = +t.female === 1 || t.female === true, m = +t.male === 1 || t.male === true;
      const pre = f ? 'female:' : m ? 'male:' : '';
      return { text: t.tag + (f ? ' ♀' : m ? ' ♂' : ''), href: t.url || `/tag/${encodeURIComponent(pre + t.tag)}-all.html`,
        term: (pre || 'tag:') + String(t.tag).replace(/\s+/g, '_') };
    }).sort((a, b) => (a.term.startsWith('tag:') - b.term.startsWith('tag:')));

    const rows = [
      ['Tipo', g.type ? links([{ text: g.type, href: `/type/${encodeURIComponent(g.type)}-all.html`, term: 'type:' + g.type }]) : null],
      ['Idioma', g.language ? links([{ text: g.language_localname || g.language, href: `/index-${g.language}.html`, term: 'language:' + g.language }]) : null],
      ['También en', links((g.languages || []).filter(l => String(l.galleryid) !== String(id))
        .map(l => ({ text: l.language_localname || l.name, href: `/galleries/${l.galleryid}.html`, term: 'language:' + l.name })))],
      ['Artistas', links(named(g.artists, 'artist', 'artist'))],
      ['Grupos', links(named(g.groups, 'group', 'group'))],
      ['Series', links(named(g.parodys, 'parody', 'series'))],
      ['Personajes', links(named(g.characters, 'character', 'character'))],
      ['Páginas', String(files.length)],
      ['Añadida', fmtDate(g.date)],
    ].filter(([, v]) => v);
    if (tags.length) rows.push(['Etiquetas', el('div', { className: 'hr-tagcloud' }, ...tags.map(tagLink))]);

    const coverImg = el('img', { alt: '' });
    const cover = el('a', { className: 'hr-hero-cover', href: readerUrl(id), title: 'Leer' }, coverImg);
    const read = el('a', { className: 'hr-btn primary hr-btn-lg', href: readerUrl(id) }, icon('book', 17), el('span', { textContent: 'Leer' }));
    const readTab = el('button', { type: 'button', className: 'hr-btn hr-btn-lg' }, icon('external', 16), el('span', { textContent: 'Leer en una pestaña nueva' }));
    readTab.onclick = () => openTab(readerUrl(id));
    const favAct = el('button', { type: 'button', className: 'hr-btn hr-btn-lg hr-fav-act' }, icon('heart', 16), el('span', { className: 'hr-fav-label' }));
    favAct.dataset.favId = id;
    favAct.onclick = () => favToggle(R.favC);
    paintFav(favAct);
    const lstAct = el('button', { type: 'button', className: 'hr-btn hr-btn-lg' }, icon('list', 16), el('span', { textContent: 'Listas' }));
    lstAct.title = 'Guardar en una lista de favoritos';
    lstAct.onclick = () => { const r = lstAct.getBoundingClientRect(); openListPicker(R.favC, r.left, r.bottom + 6); };

    R.hero.replaceChildren(cover, el('div', { className: 'hr-hero-info' },
      copyOnDblClick(el('h1', { textContent: g.title || 'Sin título' }), g.title || 'Sin título'),
      ...(g.japanese_title && g.japanese_title !== g.title ? [el('p', { className: 'hr-jp', textContent: g.japanese_title })] : []),
      el('div', { className: 'hr-actions' }, read, readTab, favAct, lstAct),
      el('dl', { className: 'hr-meta' }, ...rows.flatMap(([k, v]) => [el('dt', { textContent: k }), el('dd', {}, v)])),
    ));

    const covers = [];
    R.favC = favInfoData(g, id, covers);
    const siteImg = document.querySelector('.cover img, .cover-column img');
    if (siteImg) for (const u of [siteImg.getAttribute('data-src'), siteImg.getAttribute('src')]) if (u && !u.startsWith('data:')) covers.push(new URL(u, location.href).href);
    const thumbs = el('div', { className: 'hr-thumbs' });
    R.pagesSec.replaceChildren(el('div', { className: 'hr-sec-head' }, el('h2', { textContent: 'Páginas' }), el('span', { className: 'hr-kind', textContent: String(files.length) })), thumbs);
    R.pagesSec.hidden = !files.length;

    const STEP = 50;
    let shown = STEP;
    const moreCount = el('span', { className: 'hr-more-count' });
    const moreBtn = el('button', { type: 'button', className: 'hr-btn primary hr-btn-lg' }, icon('chevDown', 16), el('span', { textContent: 'Ver más' }));
    const allBtn = el('button', { type: 'button', className: 'hr-btn primary hr-btn-lg' }, icon('chevsDown', 16), el('span', { textContent: 'Ver todas' }));
    const moreBar = el('div', { className: 'hr-more-bar', hidden: true }, moreBtn, allBtn, moreCount);
    const applyLimit = () => {
      [...thumbs.children].forEach((t, i) => { t.hidden = i >= shown; });
      moreBar.hidden = files.length <= shown;
      moreCount.textContent = `${Math.min(shown, files.length)} / ${files.length}`;
    };
    moreBtn.onclick = () => { shown += STEP; applyLimit(); };
    allBtn.onclick = () => { shown = files.length; applyLimit(); };
    R.pagesSec.append(moreBar);

    waitFor(() => typeof W.url_from_url_from_hash === 'function' && W.gg, 8000).then(ok => {
      const tn = (f, kind) => { try { return W.url_from_url_from_hash(id, f, kind, 'webp', 'tn'); } catch { return null; } };
      if (ok && files[0]) covers.push(...[tn(files[0], 'webpbigtn'), tn(files[0], 'webpsmalltn')].filter(Boolean));
      if (covers.length) {
        let k = 0;
        coverImg.onerror = () => { if (++k < covers.length) coverImg.src = covers[k]; };
        coverImg.src = covers[0];
      }
      const loader = makeThumbLoader();
      files.forEach((f, i) => {
        const img = el('img', { alt: '', decoding: 'async' });
        thumbs.append(el('a', { className: 'hr-thumb', href: `/reader/${id}.html#${i + 1}`, title: `Página ${i + 1}` }, img, el('span', { textContent: i + 1 })));
        if (!ok) return;
        const urls = [tn(f, 'webpsmalltn'), tn(f, 'webpsmallsmalltn')].filter(Boolean);
        if (urls.length) loader.add(img, urls);
      });
      applyLimit();
    });
    gridSig = '';
    renderApp();
  }

  document.addEventListener('keydown', e => {
    if (e.key !== '/' || !appRefs || e.ctrlKey || e.metaKey || e.altKey) return;
    if (e.target instanceof Element && e.target.closest('input, textarea, select, [contenteditable], #hr-settings-host')) return;
    e.preventDefault();
    appRefs.input.focus();
  });

  let rbar = null, idleTimer = 0;

  function applyFit() {
    if (!wantReaderUi()) return;
    const box = document.getElementById('comicImages');
    if (box) {
      box.classList.toggle('fitVertical', S.fit !== 'width');
      box.classList.toggle('fitHorizontal', S.fit === 'width');
    }
    const b = document.getElementById('hr-fit');
    if (b) {
      b.replaceChildren(icon(S.fit === 'width' ? 'fitW' : 'fitH'));
      b.title = (S.fit === 'width' ? 'Ajustado al ancho' : 'Ajustado al alto') + ' (W para cambiar)';
    }
  }
  const toggleFit = () => { S.fit = S.fit === 'width' ? 'height' : 'width'; saveSettings(); applyFit(); };
  const toggleFullscreen = () => {
    if (document.fullscreenElement) document.exitFullscreen?.();
    else document.documentElement.requestFullscreen?.()?.catch?.(() => {});
  };

  // showBar=false: el movimiento solo mantiene el cursor visible, sin mostrar la barra
  function readerActivity(showBar = true) {
    if (!rbar) return;
    const root = document.documentElement;
    if (showBar) root.classList.remove('hr-idle');
    root.classList.remove('hr-nocur');
    clearTimeout(idleTimer);
    if (!S.readerAutoHide) return;
    idleTimer = setTimeout(() => {
      if (rbar.matches(':hover') || rbar.contains(document.activeElement) || dlg?.open) return readerActivity(!root.classList.contains('hr-idle'));
      root.classList.add('hr-idle', 'hr-nocur');
    }, 2200);
  }

  function buildReaderBar() {
    const btn = (name, title, fn, id) => {
      const b = el('button', { type: 'button', className: 'hr-rb', title }, icon(name));
      b.setAttribute('aria-label', title);
      if (id) b.id = id;
      b.onclick = fn;
      return b;
    };
    const dir = S.rightArrowIsNext ? 1 : -1;
    const titleEl = el('strong', { textContent: 'Cargando…' }), subEl = el('span');
    const zoomVal = el('button', { type: 'button', className: 'hr-rb hr-zoomval', id: 'hr-zoom-out', title: 'Restablecer tamaño (0)', textContent: S.zoom + '%' });
    zoomVal.onclick = () => setZoom(100);
    const stripBtn = btn('grid', 'Miniaturas (T)', () => {
      if (S.stripPos === 'off') { S.stripPos = 'bottom'; setStripHidden(false); }
      else setStripHidden(!stripHidden);
      applyLayout();
    }, 'hr-stripbtn');

    const favRb = btn('heart', 'Añadir a favoritos', () => {
      const c = readerFavData();
      if (c) favToggle(c); else hrToast(T('Aún se está cargando la galería'));
    }, 'hr-favbtn');
    favRb.classList.add('hr-fav-rb');
    favRb.dataset.favId = readerGalleryId() || '';
    paintFav(favRb);

    rbar = el('div', { id: 'hr-rbar' },
      btn('back', 'Volver (Esc)', goBack),
      el('div', { className: 'hr-rtitle' }, titleEl, subEl),
      el('span', { className: 'hr-rspacer' }),
      el('div', { className: 'hr-rgroup' },
        btn('prev', dir > 0 ? 'Página anterior' : 'Página siguiente', () => goToPage(curPage() - dir)),
        pageBoxEl(false),
        btn('next', dir > 0 ? 'Página siguiente' : 'Página anterior', () => goToPage(curPage() + dir))),
      el('div', { className: 'hr-rgroup hr-rzoom' },
        btn('minus', 'Más pequeña (-)', () => setZoom(S.zoom - 10)), zoomVal, btn('plus', 'Más grande (+)', () => setZoom(S.zoom + 10))),
      btn('fitH', 'Ajustar', toggleFit, 'hr-fit'),
      stripBtn,
      favRb,
      btn('full', 'Pantalla completa (F)', toggleFullscreen, 'hr-fullbtn'),
      btn('sliders', 'Ajustes', openSettings));
    document.body.append(rbar, el('div', { id: 'hr-progress' }, el('i')), el('div', { id: 'hr-pcount' }));

    // La barra solo aparece al acercar el ratón al borde superior (o al tocar arriba en pantallas táctiles),
    // así no tapa la página con cualquier movimiento del ratón.
    for (const ev of ['pointermove', 'pointerdown']) {
      window.addEventListener(ev, e => {
        if (e.pointerType === 'touch') {
          if (e.type === 'pointerdown' && e.clientY <= 90) readerActivity();
          return;
        }
        if (e.clientY <= 72) { readerActivity(true); return; }
        if (e.clientY > 130 && S.readerAutoHide && !rbar.contains(document.activeElement) && !dlg?.open) document.documentElement.classList.add('hr-idle');
        readerActivity(false);
      }, { passive: true });
    }
    rbar.addEventListener('focusin', readerActivity);
    window.addEventListener('hashchange', applyFit);

    waitFor(() => W.galleryinfo?.files?.length, 15000).then(ok => {
      if (!ok) { titleEl.textContent = document.title.replace(/\s*[|\-]\s*hitomi\.la.*$/i, '') || 'Lector'; return; }
      const g = W.galleryinfo;
      titleEl.textContent = g.title || 'Sin título';
      titleEl.title = g.title || '';
      document.title = (g.title || T('Lector')) + ' | Hitomi.la';
      subEl.textContent = [(g.artists || []).map(a => a.artist).join(', '), g.language_localname || g.language, `${g.files.length} páginas`].filter(Boolean).join(', ');
      updatePageBox();
      setTimeout(applyFit, 300);
    });
    updatePageBox();
    applyFit();
    readerActivity();
  }

  const TN = ['webpsmallsmalltn', 'webpsmalltn'];
  const tnPick = () => (S.thumbSize * (window.devicePixelRatio || 1) > 130 ? 1 : 0);

  let strip = null, stripInit = false, stripHidden = !!S.stripHidden, tiles = [], files = [], gid = null, io = null;
  const setStripHidden = v => { stripHidden = !!v; S.stripHidden = stripHidden; saveSettings(); };
  const queue = [];
  let active = 0, lastStart = 0, pumpTimer = null;

  const waitFor = (fn, ms) => new Promise(res => {
    const t0 = Date.now();
    (function tick() {
      const v = fn();
      if (v || Date.now() - t0 > ms) return res(v);
      setTimeout(tick, 250);
    })();
  });

  async function initStrip() {
    stripInit = true;
    const ok = await waitFor(() => W.galleryinfo?.files?.length && typeof W.url_from_url_from_hash === 'function', 15000);
    if (!ok) { console.warn('[hitomi-enhanced] reader data not found; thumbnail strip disabled'); return; }
    await waitFor(() => W.gg, 5000);
    files = W.galleryinfo.files;
    gid = W.galleryinfo.id || readerGalleryId();
    buildStrip();
  }

  function buildStrip() {
    strip = el('div', { id: 'hr-strip' });
    strip.setAttribute('aria-label', 'Páginas');
    tiles = files.map((f, i) => {
      const r = f.width && f.height ? f.width / f.height : 0.7;
      const b = el('button', { className: 'hr-tile', title: `Página ${i + 1}` },
        el('img', { alt: '', decoding: 'async' }), el('span', { textContent: i + 1 }));
      b.style.setProperty('--r', r);
      b.dataset.i = i;
      b.onclick = () => goToPage(i + 1);
      strip.append(b);
      return b;
    });

    strip.addEventListener('wheel', e => {
      if (S.stripPos === 'bottom' && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
        strip.scrollLeft += e.deltaY; e.preventDefault();
      }
    }, { passive: false });

    io = new IntersectionObserver(entries => {
      for (const en of entries) {
        const i = +en.target.dataset.i;
        if (en.isIntersecting) enqueue(i);
        else if (S.thumbLoad === 'visible') { const q = queue.indexOf(i); if (q !== -1) queue.splice(q, 1); }
      }
      pump();
    }, { root: strip, rootMargin: '300px' });
    tiles.forEach(t => io.observe(t));

    document.body.append(strip);
    window.addEventListener('hashchange', () => markCurrent(true));
    applyLayout();
    markCurrent(false);
  }

  function enqueue(i) {
    const st = tiles[i].dataset.state;
    if (st || queue.includes(i)) return;
    queue.push(i);
  }

  function enqueueAll() {

    const c = curPage() - 1;
    [...tiles.keys()].sort((a, b) => Math.abs(a - c) - Math.abs(b - c)).forEach(enqueue);
    pump();
  }

  function pump() {
    while (active < S.maxParallel && queue.length) {
      const wait = lastStart + S.delayMs - Date.now();
      if (wait > 0) {
        if (!pumpTimer) pumpTimer = setTimeout(() => { pumpTimer = null; pump(); }, wait);
        return;
      }
      lastStart = Date.now();
      loadTile(queue.shift(), tnPick(), false);
    }
  }

  function loadTile(i, pick, retried) {
    const tile = tiles[i];
    const img = tile.firstChild;
    let url;
    try { url = W.url_from_url_from_hash(gid, files[i], TN[pick], 'webp', 'tn'); }
    catch { tile.dataset.state = 'err'; return; }
    active++;
    tile.dataset.state = 'loading';
    img.onload = () => { active--; tile.dataset.state = 'done'; pump(); };
    img.onerror = () => {
      active--;
      if (!retried) { loadTile(i, 1 - pick, true); return; }
      tile.dataset.state = 'err';
      pump();
    };
    img.src = url;
  }

  function markCurrent(smooth) {
    if (!strip) return;
    const t = tiles[curPage() - 1];
    strip.querySelector('.hr-tile.cur')?.classList.remove('cur');
    if (!t) return;
    t.classList.add('cur');
    const behavior = smooth && !matchMedia('(prefers-reduced-motion: reduce)').matches ? 'smooth' : 'auto';
    if (S.stripPos === 'bottom') strip.scrollTo({ left: t.offsetLeft - strip.clientWidth / 2 + t.offsetWidth / 2, behavior });
    else strip.scrollTo({ top: t.offsetTop - strip.clientHeight / 2 + t.offsetHeight / 2, behavior });
  }

  function applyLayout() {
    const root = document.documentElement;
    root.style.setProperty('--hr-size', S.thumbSize + 'px');
    root.style.setProperty('--hr-zoom', S.zoom / 100);
    syncZoomBox();
    if (!isReader()) return;
    root.classList.add('hr-reader');
    root.classList.toggle('hr-rv-pin', wantReaderUi() && !S.readerAutoHide);
    root.classList.remove('hr-pos-bottom', 'hr-pos-left', 'hr-pos-right');
    document.getElementById('hr-stripbtn')?.setAttribute('aria-pressed', String(S.stripPos !== 'off' && !stripHidden));
    if (!document.body) return;
    const show = S.stripPos !== 'off' && !stripHidden;
    if (!strip) { if (show && !stripInit) initStrip(); return; }
    strip.hidden = !show;
    if (show) root.classList.add('hr-pos-' + S.stripPos);
    if (S.thumbLoad === 'all') enqueueAll();
    markCurrent(false);
  }

  let dlg = null, blListEl = null, blHeadEl = null;

  const DLG_CSS = `
    :host { all: initial; }
    * { box-sizing: border-box; }
    dialog { padding: 0; border: 1px solid var(--hr-border); border-radius: 16px; background: var(--hr-bg); color: var(--hr-text);
      width: min(480px, calc(100vw - 24px)); max-height: min(760px, calc(100vh - 24px)); overflow: hidden;
      font: 14px/1.45 var(--hr-font); color-scheme: var(--hr-scheme); box-shadow: 0 24px 64px var(--hr-shadow); }
    dialog[open] { display: flex; flex-direction: column; }
    dialog::backdrop { background: rgba(6,6,14,.55); }

    header { display: flex; align-items: center; gap: 12px; padding: 14px 14px 14px 18px; border-bottom: 1px solid var(--hr-border); }
    header img { width: 36px; height: 36px; border-radius: 9px; flex: none; }
    header h2 { margin: 0; font-size: 16px; font-weight: 700; line-height: 1.2; }
    header .ver { display: block; font-size: 12px; color: var(--hr-muted); }
    header .x { margin-left: auto; width: 32px; height: 32px; border: 0; border-radius: 8px; background: none;
      color: var(--hr-muted); font: 20px/1 system-ui, sans-serif; cursor: pointer; }
    header .x:hover { background: var(--hr-hover); color: var(--hr-text); }

    .body { overflow: auto; padding: 4px 18px 18px; scrollbar-width: thin; scrollbar-color: var(--hr-border) transparent; }
    section { margin-top: 18px; }
    .sh { display: flex; align-items: baseline; justify-content: space-between; margin: 0 2px 8px; }
    h3 { margin: 0; font-size: 13px; font-weight: 600; color: var(--hr-muted); }
    .card { background: var(--hr-surface); border: 1px solid var(--hr-border); border-radius: 12px; }

    .row { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 16px; padding: 10px 14px; min-height: 50px; }
    .row + .row, .row + .bl { border-top: 1px solid var(--hr-border); }
    .row.off { opacity: .45; cursor: not-allowed; }
    .sw:disabled { cursor: not-allowed; }
    label.row { cursor: pointer; }
    .name { display: block; }
    .desc { display: block; font-size: 12px; color: var(--hr-muted); margin-top: 1px; }

    .sw { appearance: none; -webkit-appearance: none; width: 38px; height: 22px; margin: 0; border-radius: 11px;
      background: color-mix(in srgb, var(--hr-text) 22%, transparent); position: relative; cursor: pointer; transition: background .15s; }
    .sw::after { content: ''; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%;
      background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.3); transition: transform .15s; }
    .sw:checked { background: var(--hr-accent); }
    .sw:checked::after { transform: translateX(16px); }

    .seg { display: inline-flex; gap: 2px; padding: 2px; background: var(--hr-bg); border: 1px solid var(--hr-border); border-radius: 9px; }
    .seg button { border: 0; background: none; color: var(--hr-muted); font: inherit; font-size: 13px; padding: 4px 10px;
      border-radius: 7px; cursor: pointer; min-width: 30px; }
    .seg button:hover { color: var(--hr-text); background: var(--hr-hover); }
    .seg button[aria-pressed="true"] { background: var(--hr-accent); color: #fff; }

    .swatches { display: flex; gap: 10px; padding: 0 4px; }
    .swatches button { width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: var(--c); cursor: pointer;
      box-shadow: 0 0 0 2px var(--hr-surface); }
    .swatches button[aria-pressed="true"] { box-shadow: 0 0 0 2px var(--hr-surface), 0 0 0 4px var(--c); }

    .num { display: inline-flex; align-items: center; background: var(--hr-bg); border: 1px solid var(--hr-border); border-radius: 9px; padding-right: 10px; }
    .num:focus-within { border-color: var(--hr-accent); }
    .num input { width: 62px; background: none; border: 0; outline: none; color: inherit; font: inherit;
      padding: 5px 4px 5px 10px; text-align: right; -moz-appearance: textfield; }
    .num input::-webkit-inner-spin-button, .num input::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
    .num span { color: var(--hr-muted); font-size: 12px; }

    .range { display: flex; align-items: center; gap: 10px; }
    .range input { width: 130px; margin: 0; accent-color: var(--hr-accent); cursor: pointer; }
    .range output { min-width: 46px; text-align: right; color: var(--hr-muted); font-size: 13px; font-variant-numeric: tabular-nums; }

    .bl { padding: 12px 14px 14px; }
    .add { display: flex; gap: 8px; }
    .add input { flex: 1; min-width: 0; background: var(--hr-bg); border: 1px solid var(--hr-border); border-radius: 9px;
      color: inherit; font: inherit; padding: 7px 10px; outline: none; }
    .add input:focus { border-color: var(--hr-accent); }
    .add input::placeholder { color: var(--hr-muted); opacity: .8; }
    .chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; max-height: 168px; overflow: auto; }
    .chip { display: inline-flex; align-items: center; gap: 2px; background: var(--hr-neg-soft); color: var(--hr-text);
      border-radius: 999px; padding: 2px 3px 2px 10px; font-size: 13px; }
    .chip button { border: 0; background: none; color: var(--hr-muted); cursor: pointer; width: 20px; height: 20px;
      border-radius: 50%; font: 14px/1 system-ui, sans-serif; }
    .chip button:hover { background: var(--hr-hover); color: var(--hr-text); }
    .empty { color: var(--hr-muted); font-size: 13px; margin: 10px 0 0; }
    .link { border: 0; background: none; color: var(--hr-neg); font: inherit; font-size: 12px; cursor: pointer; padding: 2px 4px; border-radius: 4px; }
    .link:hover { text-decoration: underline; }
    .link[hidden] { display: none; }
    .row[hidden] { display: none; }
    .txt { width: 230px; max-width: 100%; box-sizing: border-box; background: var(--hr-bg); border: 1px solid var(--hr-border); border-radius: 9px;
      color: inherit; font: inherit; padding: 7px 10px; outline: none; }
    .txt:focus { border-color: var(--hr-accent); }
    .txt::placeholder { color: var(--hr-muted); opacity: .8; }
    .row.tagrow { display: flex; flex-wrap: wrap; gap: 6px; min-height: 0; padding: 8px 14px 12px; }
    .tagrow button { border: 1px solid var(--hr-border); background: var(--hr-bg); color: var(--hr-muted); font: 12px/1 var(--hr-font);
      padding: 5px 8px; border-radius: 7px; cursor: pointer; }
    .tagrow button:hover { color: var(--hr-text); background: var(--hr-hover); }
    .ctl { display: inline-flex; align-items: center; gap: 12px; }
    .ctl output { color: var(--hr-muted); font-variant-numeric: tabular-nums; }
    .row .btn { padding: 7px 12px; }

    dl.keys { display: grid; grid-template-columns: auto 1fr; gap: 9px 16px; margin: 0; padding: 12px 14px; font-size: 13px; align-items: center; }
    .keys dt { display: flex; gap: 4px; flex-wrap: wrap; }
    .keys dd { margin: 0; color: var(--hr-muted); }
    kbd { font: 12px/1 var(--hr-font); background: var(--hr-bg); border: 1px solid var(--hr-border); border-bottom-width: 2px;
      border-radius: 5px; padding: 3px 6px; color: var(--hr-text); }
    .note { font-size: 12px; color: var(--hr-muted); margin: 12px 2px 0; }

    footer { display: flex; justify-content: space-between; gap: 8px; padding: 12px 18px; border-top: 1px solid var(--hr-border); background: var(--hr-surface); }
    .btn { border: 1px solid var(--hr-border); background: transparent; color: var(--hr-text); font: 600 13px/1 var(--hr-font);
      padding: 9px 16px; border-radius: 9px; cursor: pointer; }
    .btn:hover { background: var(--hr-hover); }
    .btn.primary { background: var(--hr-accent); border-color: var(--hr-accent); color: #fff; }
    .btn.primary:hover { background: color-mix(in srgb, var(--hr-accent) 85%, #fff); }

    :focus-visible { outline: 2px solid var(--hr-accent); outline-offset: 2px; }
    @media (prefers-reduced-motion: reduce) { .sw, .sw::after { transition: none; } }
  `;

  function gearButton(id) {
    const b = el('button', { id, type: 'button', title: 'Ajustes de Hitomi Enhanced' }, el('img', { src: LOGO_URL, alt: '' }));
    b.setAttribute('aria-label', 'Ajustes de Hitomi Enhanced');
    b.onclick = openSettings;
    return b;
  }

  function renderBlacklist() {
    if (blHeadEl) {
      blHeadEl.firstChild.textContent = blacklist.length ? `Lista negra (${blacklist.length})` : 'Lista negra';
      blHeadEl.lastChild.hidden = !blacklist.length;
    }
    if (!blListEl) return;
    blListEl.textContent = '';
    if (!blacklist.length) {
      blListEl.append(el('p', { className: 'empty', textContent: 'Aún no hay nada en la lista negra. Haz clic derecho en cualquier etiqueta y elige "Añadir a la lista negra", o escribe una arriba.' }));
      return;
    }
    const chips = el('div', { className: 'chips' });
    for (const t of blacklist) {
      const x = el('button', { type: 'button', textContent: '×', title: 'Quitar' });
      x.setAttribute('aria-label', 'Quitar ' + t);
      x.onclick = () => blRemove(t);
      chips.append(el('span', { className: 'chip' }, t, x));
    }
    blListEl.append(chips);
  }

  function openSettings() {
    document.getElementById('hr-settings-host')?.remove();
    const host = el('div', { id: 'hr-settings-host' });
    const root = host.attachShadow({ mode: 'open' });
    i18nWatch(root);
    root.append(el('style', { textContent: DLG_CSS }));

    const sw = (key, after) => {
      const c = el('input', { type: 'checkbox', className: 'sw', checked: !!S[key] });
      c.setAttribute('role', 'switch');
      c.onchange = () => { S[key] = c.checked; changed(); after?.(); };
      return c;
    };
    const seg = (key, opts, label) => {
      const g = el('div', { className: 'seg' });
      g.setAttribute('role', 'group');
      g.setAttribute('aria-label', label);
      for (const [v, text] of opts) {
        const b = el('button', { type: 'button', textContent: text });
        b.setAttribute('aria-pressed', String(String(S[key]) === v));
        b.onclick = () => {
          S[key] = typeof DEFAULTS[key] === 'number' ? +v : v;
          if (key === 'stripPos' && v !== 'off') { stripHidden = false; S.stripHidden = false; }
          g.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', String(x === b)));
          changed();
        };
        g.append(b);
      }
      return g;
    };
    const num = (key, min, max, step, unit) => {
      const n = el('input', { type: 'number', min, max, step, value: S[key] });
      n.onchange = () => {
        const v = Math.max(min, Math.min(max, Math.round(n.value === '' ? DEFAULTS[key] : +n.value)));
        n.value = v; S[key] = v; changed();
      };
      return el('span', { className: 'num' }, n, el('span', { textContent: unit }));
    };
    const swatches = () => {
      const g = el('div', { className: 'swatches' });
      g.setAttribute('role', 'group');
      g.setAttribute('aria-label', 'Color de acento');
      for (const [k, c] of Object.entries(ACCENTS)) {
        const b = el('button', { type: 'button', title: ACCENT_ES[k] || k });
        b.style.setProperty('--c', c);
        b.setAttribute('aria-label', ACCENT_ES[k] || k);
        b.setAttribute('aria-pressed', String(S.accent === k));
        b.onclick = () => {
          S.accent = k;
          g.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', String(x === b)));
          changed();
        };
        g.append(b);
      }
      return g;
    };
    const focusSw = sw('newTabFocus');
    let focusRow = null;
    const syncFocusRow = () => {
      focusSw.disabled = !S.newTab;
      focusRow?.classList.toggle('off', !S.newTab);
      focusRow?.setAttribute('aria-disabled', String(!S.newTab));
    };
    const row = (name, ctrl, desc, tag = 'label') => el(tag, { className: 'row' },
      el('span', {}, el('span', { className: 'name', textContent: name }),
        ...(desc ? [el('span', { className: 'desc', textContent: desc })] : [])),
      ctrl);
    focusRow = row('Cambiar a la pestaña nueva', focusSw, 'Si está desactivado, se abre en segundo plano');
    syncFocusRow();
    const section = (title, ...kids) => el('section', {},
      el('div', { className: 'sh' }, el('h3', { textContent: title })),
      el('div', { className: 'card' }, ...kids));

    const sizeOut = el('output', { textContent: S.thumbSize + ' px' });
    const size = el('input', { type: 'range', min: 60, max: 260, step: 10, value: S.thumbSize });
    size.setAttribute('aria-label', 'Tamaño de las miniaturas');
    size.oninput = () => { S.thumbSize = +size.value; sizeOut.textContent = size.value + ' px'; changed(); };

    const blInput = el('input', { type: 'text', placeholder: 'female:big_breasts, artist:name, full_color' });
    blInput.setAttribute('aria-label', 'Etiquetas para la lista negra, separadas por comas');
    const addFromInput = () => {
      const v = blInput.value.split(',').map(normTerm).filter(Boolean);
      if (!v.length) return;
      setBlacklist([...blacklist, ...v]);
      blInput.value = '';
    };
    blInput.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); addFromInput(); } });
    const addBtn = el('button', { type: 'button', className: 'btn primary', textContent: 'Añadir' });
    addBtn.onclick = addFromInput;
    const clearBtn = el('button', { type: 'button', className: 'link', textContent: 'Quitar todas' });
    clearBtn.onclick = () => { if (confirm(T(`¿Quitar las ${blacklist.length} etiquetas de la lista negra?`))) setBlacklist([]); };
    blHeadEl = el('div', { className: 'sh' }, el('h3'), clearBtn);
    blListEl = el('div');

    const keys = (combo, what) => [el('dt', {}, ...combo.map(k => el('kbd', { textContent: k }))), el('dd', { textContent: what })];

    const close = el('button', { type: 'button', className: 'x', textContent: '×', title: 'Cerrar' });
    close.setAttribute('aria-label', 'Cerrar ajustes');
    const reset = el('button', { type: 'button', className: 'btn', textContent: 'Restablecer ajustes' });
    reset.onclick = () => { Object.assign(S, DEFAULTS); stripHidden = !!DEFAULTS.stripHidden; changed(); openSettings(); };
    const done = el('button', { type: 'button', className: 'btn primary', textContent: 'Listo' });

    // ---- Ajustes del descargador: mismas claves GM que usaba su panel del engranaje ----
    const gm = (k, d) => { try { return GM_getValue(k, d); } catch { return d; } };
    const gmSet = (k, v) => { try { GM_setValue(k, v); } catch {} };
    const DL = window.__hrDl || null;
    const gmSw = (key, def) => {
      const c = el('input', { type: 'checkbox', className: 'sw', checked: String(gm(key, def)) === '1' });
      c.setAttribute('role', 'switch');
      c.onchange = () => gmSet(key, c.checked ? '1' : '0');
      return c;
    };
    const gmSeg = (key, opts, label, def, after) => {
      const g = el('div', { className: 'seg' });
      g.setAttribute('role', 'group');
      g.setAttribute('aria-label', label);
      for (const [v, text] of opts) {
        const b = el('button', { type: 'button', textContent: text });
        b.setAttribute('aria-pressed', String(String(gm(key, def)) === v));
        b.onclick = () => {
          gmSet(key, v);
          g.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', String(x === b)));
          after?.(v);
        };
        g.append(b);
      }
      return g;
    };
    const gmNum = (key, min, max, def, unit) => {
      const n = el('input', { type: 'number', min, max, step: 1, value: gm(key, def) });
      n.onchange = () => {
        let v = Math.round(+n.value);
        if (n.value === '' || !Number.isFinite(v)) v = +def;
        v = Math.max(min, Math.min(max, v));
        n.value = v; gmSet(key, String(v));
      };
      return el('span', { className: 'num' }, n, el('span', { textContent: unit }));
    };
    const gmText = (key, placeholder, label) => {
      const i = el('input', { type: 'text', className: 'txt', placeholder, value: gm(key, ''), spellcheck: false });
      i.setAttribute('aria-label', label);
      i.oninput = () => gmSet(key, i.value);
      return i;
    };

    // Idioma (compartido con el descargador)
    const langSeg = el('div', { className: 'seg' });
    langSeg.setAttribute('role', 'group');
    langSeg.setAttribute('aria-label', 'Idioma / Language');
    langSeg.setAttribute('data-keep', '');
    for (const [v, text] of [['en', 'English'], ['es', 'Español']]) {
      const b = el('button', { type: 'button', textContent: text });
      b.setAttribute('aria-pressed', String((gm('ui_lang', 'es') === 'en' ? 'en' : 'es') === v));
      b.onclick = () => {
        langSeg.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', String(x === b)));
        if (DL?.setLang) DL.setLang(v); else { gmSet('ui_lang', v); document.dispatchEvent(new Event('hr-lang')); }
      };
      langSeg.append(b);
    }

    // Descarga
    const zipRow = row('Dividir el ZIP cada', gmNum('zip_max_length', 1, 100000, '1024', 'MB'), null, 'div');
    const pdfOut = el('output', { textContent: gm('jpg_quality', '40') + ' %' });
    const pdfRange = el('input', { type: 'range', min: 10, max: 100, step: 5, value: gm('jpg_quality', '40') });
    pdfRange.setAttribute('aria-label', 'Calidad del PDF');
    pdfRange.oninput = () => { pdfOut.textContent = pdfRange.value + ' %'; gmSet('jpg_quality', pdfRange.value); };
    const pdfRow = row('Calidad del PDF', el('span', { className: 'range' }, pdfRange, pdfOut),
      'Solo se usa en modo PDF. Menor calidad = archivo más pequeño. Recomendada: 40 %.', 'div');
    const syncFmt = v => { zipRow.hidden = String(v) !== '1'; pdfRow.hidden = String(v) !== '3'; };
    syncFmt(gm('dl_mode', '1'));

    // Destino
    const tplInput = gmText('folder_template', '{artist}/{title}', 'Nombre de la carpeta');
    const tagRow = el('div', { className: 'row tagrow' }, ...['title', 'artist', 'artists', 'group', 'language', 'tag', 'type', 'id', 'date'].map(t => {
      const tag = `{${t}}`;
      const b = el('button', { type: 'button', textContent: tag, title: 'Clic para insertar' });
      b.onmousedown = e => e.preventDefault();
      b.onclick = () => {
        const a = tplInput.selectionStart ?? tplInput.value.length, z = tplInput.selectionEnd ?? a;
        tplInput.value = tplInput.value.slice(0, a) + tag + tplInput.value.slice(z);
        gmSet('folder_template', tplInput.value);
        tplInput.focus(); tplInput.setSelectionRange(a + tag.length, a + tag.length);
      };
      return b;
    }));
    let baseRow = null;
    if (DL?.pickDir) {
      const dirBtn = el('button', { type: 'button', className: 'btn', textContent: 'Elegir carpeta' });
      const paint = n => { dirBtn.textContent = n ? 'Carpeta: ' + n : 'Elegir carpeta'; };
      DL.baseDirName().then(paint).catch(() => {});
      dirBtn.onclick = () => DL.pickDir(paint);
      baseRow = row('Carpeta base', dirBtn, null, 'div');
    }

    // Historial
    const histLoadLocal = () => { try { const h = JSON.parse(gm('dl_history', '{}')); return h && typeof h === 'object' && !Array.isArray(h) ? h : {}; } catch { return {}; } };
    const histOut = el('output', { textContent: String(Object.keys(histLoadLocal()).length) });
    const histRefresh = () => { histOut.textContent = String(Object.keys(histLoadLocal()).length); DL?.histChanged?.(); };
    const histClearBtn = el('button', { type: 'button', className: 'btn', textContent: 'Vaciar historial' });
    histClearBtn.onclick = () => {
      if (!confirm(T('¿Vaciar el historial de descargas?'))) return;
      gmSet('dl_history', '{}'); histRefresh();
    };
    // Copia de seguridad única: ajustes, lista negra, favoritos (con sus listas), ajustes del descargador e historial de descargas
    const CFG_FORMAT = 'hitomi-enhanced-settings';
    const CFG_GM_RE = /^(ui_lang|img_type|dl_mode|dl_thread|zip_max_length|jpg_quality|subdir_enabled|subdir_path|folder_template|sort_by|gear_pos_v2|pv_[a-z_]+)$/;
    const isObj = x => !!x && typeof x === 'object' && !Array.isArray(x);
    const histMerge = inc => {
      const h = histLoadLocal();
      let n = 0;
      for (const id of Object.keys(inc || {})) {
        const v = inc[id];
        if (!/^\d+$/.test(id) || !v || typeof v !== 'object') continue;
        const cur = h[id];
        if (!(cur && cur.t >= v.t)) h[id] = { t: +v.t || Date.now(), title: String(v.title || '').slice(0, 120) };
        n++;
      }
      gmSet('dl_history', JSON.stringify(h)); histRefresh();
      return n;
    };
    const bkExpBtn = el('button', { type: 'button', className: 'btn', textContent: 'Exportar' });
    bkExpBtn.onclick = () => {
      const gmData = {};
      try { for (const k of GM_listValues()) if (CFG_GM_RE.test(k)) gmData[k] = GM_getValue(k); } catch {}
      const data = { format: CFG_FORMAT, version: VERSION || '', exported: new Date().toISOString(), settings: { ...S }, blacklist: [...blacklist],
        favorites: Object.values(favs), favlists: [...favLists], favterms: Object.values(favTerms), history: histLoadLocal(), downloader: gmData };
      const d = new Date(), pd = n => String(n).padStart(2, '0');
      const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }));
      const a = el('a', { href: url, download: `hitomi-enhanced-backup-${d.getFullYear()}${pd(d.getMonth() + 1)}${pd(d.getDate())}.json` });
      root.append(a); a.click(); a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    };
    const bkFile = el('input', { type: 'file', accept: '.json,application/json', hidden: true });
    const bkImpBtn = el('button', { type: 'button', className: 'btn', textContent: 'Importar' });
    bkImpBtn.onclick = () => { bkFile.value = ''; bkFile.click(); };
    bkFile.onchange = () => {
      const f = bkFile.files && bkFile.files[0];
      if (!f) return;
      const rd = new FileReader();
      rd.onload = () => {
        let inc;
        try { inc = JSON.parse(rd.result); } catch { alert(T('Archivo de copia de seguridad no válido')); return; }
        if (isObj(inc) && inc.format === CFG_FORMAT && isObj(inc.settings)) {
          if (!confirm(T('¿Reemplazar la configuración actual con la del archivo? La página se recargará.'))) return;
          // solo se aceptan claves conocidas y del mismo tipo que su valor por defecto
          const st = Object.assign({}, DEFAULTS);
          for (const k of Object.keys(DEFAULTS)) if (k in inc.settings && typeof inc.settings[k] === typeof DEFAULTS[k]) st[k] = inc.settings[k];
          for (const k of Object.keys(S)) delete S[k];
          Object.assign(S, st);
          saveSettings();
          if (Array.isArray(inc.blacklist)) GM_setValue(BL_KEY, [...new Set(inc.blacklist.filter(x => typeof x === 'string').map(normTerm).filter(Boolean))].sort());
          if (Array.isArray(inc.favorites)) {
            const m = {};
            for (const v of inc.favorites) { const e = favClean(v); if (e) m[e.id] = e; }
            if (Array.isArray(inc.favlists)) GM_setValue(FL_KEY, flRead(inc.favlists));
            GM_setValue(FAV_KEY, m);
          }
          if (Array.isArray(inc.favterms)) { const m = {}; for (const v of inc.favterms) { const e = ftClean(v); if (e) m[e.term] = e; } GM_setValue(FT_KEY, m); }
          if (isObj(inc.history)) histMerge(inc.history);
          const g = inc.downloader;
          if (g && typeof g === 'object') for (const k of Object.keys(g)) if (CFG_GM_RE.test(k) && ['string', 'number', 'boolean'].includes(typeof g[k])) gmSet(k, g[k]);
          location.reload();
        } else if (Array.isArray(inc) || (isObj(inc) && inc.format === 'hitomi-enhanced-favorites' && Array.isArray(inc.favorites))) {
          // copia antigua de solo favoritos
          const list = Array.isArray(inc) ? inc : inc.favorites;
          let n = 0;
          if (isObj(inc) && Array.isArray(inc.lists)) { for (const l of flRead(inc.lists)) if (!favLists.some(x => x.id === l.id)) favLists.push(l); flSave(); }
          for (const v of list) { const e = favClean(v); if (e && !favHas(e.id)) { favs[e.id] = e; n++; } }
          favSave(); favsChanged(); favRefresh();
          alert(T('Favoritos importados: ' + n));
        } else if (isObj(inc) && Object.keys(inc).length && Object.keys(inc).every(k => /^\d+$/.test(k))) {
          // copia antigua de solo el historial
          alert(T('Obras importadas: ' + histMerge(inc)));
        } else alert(T('Archivo de copia de seguridad no válido'));
      };
      rd.readAsText(f);
    };

    // Favoritos
    const favOut = el('output', { textContent: String(favIds().length) });
    const favRefresh = () => { favOut.textContent = String(favIds().length); };
    const favClearBtn = el('button', { type: 'button', className: 'btn', textContent: 'Vaciar favoritos' });
    favClearBtn.onclick = () => {
      const ids = favIds();
      if (!ids.length || !confirm(T(`¿Vaciar los ${ids.length} favoritos?`))) return;
      favs = {};
      favSave();
      ids.forEach(id => { try { GM_deleteValue(FAVIMG + id); } catch {} });
      favsChanged(); favRefresh();
    };
    const ftOut = el('output', { textContent: String(Object.keys(favTerms).length) });
    const ftClearBtn = el('button', { type: 'button', className: 'btn', textContent: 'Vaciar' });
    ftClearBtn.onclick = () => {
      if (!Object.keys(favTerms).length || !confirm(T('¿Vaciar los artistas, grupos y etiquetas favoritos?'))) return;
      favTerms = {};
      ftSave(); ftChanged(); ftOut.textContent = '0';
    };

    const dlSections = [
      section('Descargas',
        row('Imágenes', gmSeg('img_type', [['webp', 'webp'], ['avif', 'avif']], 'Imágenes', 'webp'), null, 'div'),
        row('Descargas a la vez', gmNum('dl_thread', 1, 6, '4', ''), null, 'div'),
        row('Formato', gmSeg('dl_mode', [['1', 'ZIP'], ['2', 'Archivos'], ['3', 'PDF'], ['4', 'CBZ'], ['5', 'CBR']], 'Formato', '1', syncFmt),
          'ZIP, archivos sueltos, PDF único o cómic (CBZ / CBR)', 'div'),
        zipRow, pdfRow),

      section('Destino de las descargas',
        ...(baseRow ? [baseRow] : []),
        row('Subcarpeta', gmSw('subdir_enabled', '0'), 'Crear un subdirectorio'),
        row('Ruta de la subcarpeta', gmText('subdir_path', 'X/Downloads', 'Ruta de la subcarpeta'), null, 'div'),
        row('Nombre de la carpeta', tplInput, 'Usa / para carpetas anidadas. Clic en un marcador para insertarlo.', 'div'),
        tagRow),

      section('Vista previa',
        row('Vista previa al pasar el cursor por una obra', gmSw('pv_enabled', '1')),
        row('Vista previa al pasar el cursor por las páginas de una obra', gmSw('pv_thumb_enabled', '1')),
        row('Vista previa en Favoritos', gmSw('pv_fav', '1')),
        row('Tamaño de imagen', gmSeg('pv_size', [['orig', 'Original'], ['small', 'Pequeño']], 'Tamaño de imagen', 'small'), null, 'div'),
        row('Tiempo de espera', gmNum('pv_wait', 0, 5000, '400', 'ms'), null, 'div'),
        row('Tiempo de espera (páginas de una obra)', gmNum('pv_wait_thumb', 0, 5000, '200', 'ms'), null, 'div'),
        row('Usar la rueda del mouse para cambiar de imagen', gmSw('pv_wheel', '1')),
        row('Usar las flechas y la barra espaciadora para cambiar de imagen', gmSw('pv_keys', '1')),
        row('Mostrar resumen', gmSw('pv_summary', '0')),
        row('Mostrar contador de páginas', gmSw('pv_count', '1'))),

    ];

    dlg = el('dialog', {},
      el('header', {},
        el('img', { src: LOGO_URL, alt: '' }),
        el('div', {}, el('h2', { textContent: 'Hitomi Enhanced' }), el('span', { className: 'ver', textContent: VERSION ? 'Versión ' + VERSION : 'Ajustes' })),
        close),
      el('div', { className: 'body' },
        section('Apariencia',
          row('Idioma / Language', langSeg, null, 'div'),
          row('Diseño de Hitomi Enhanced', sw('revamp'), 'Desactívalo para volver al diseño original del sitio; el descargador sigue funcionando. Un lector abierto cambia en su próxima carga'),
          row('Interfaz nueva', sw('newUi'), 'Listas, páginas de galería y lector rediseñados. Un lector abierto se activa en su próxima carga'),
          row('Tema', seg('theme', THEME_NAMES, 'Tema'), null, 'div'),
          row('Acento', swatches(), null, 'div'),
          row('Aplicar el tema a las páginas clásicas', sw('classicTheme'), 'Recolorea el sitio donde la interfaz nueva está desactivada'),
          row('Tamaño de las tarjetas', seg('cardSize', [['s', 'S'], ['m', 'M'], ['l', 'L']], 'Tamaño de las tarjetas'), null, 'div'),
          row('Etiquetas en las tarjetas', seg('cardTags', [['off', 'No'], ['compact', 'Algunas'], ['all', 'Todas']], 'Etiquetas en las tarjetas'), '«Algunas» muestra 8; el resto se abre sobre la tarjeta', 'div')),

        section('Navegación',
          row('Abrir las galerías en el lector', sw('openInReader'), 'Omite la página de detalles'),
          row('Abrir las galerías en una pestaña nueva', sw('newTab', syncFocusRow), 'Al hacer clic en un resultado'),
          focusRow),

        section('Lector',
          row('La flecha derecha avanza', sw('rightArrowIsNext'), 'Desactívalo para leer de derecha a izquierda'),
          row('Clic en las mitades de la imagen para pasar de página', sw('clickHalves')),
          row('Rueda del ratón para pasar de página', sw('wheelPages'), 'Si la imagen es más grande que la pantalla, primero se desplaza y al llegar al borde cambia de página'),
          row('Esc sale del lector', sw('escBack')),
          row('Ocultar automáticamente la barra del lector', sw('readerAutoHide'), 'Acerca el ratón al borde superior para volver a mostrarla'),
          row('Tamaño de la imagen', num('zoom', 10, 300, 5, '%'), 'Porción de la pantalla que ocupa la página')),

        section('Tira de miniaturas',
          row('Posición', seg('stripPos', [['bottom', 'Abajo'], ['left', 'Izquierda'], ['right', 'Derecha'], ['off', 'No']], 'Posición de la tira'), null, 'div'),
          row('Tamaño de las miniaturas', el('span', { className: 'range' }, size, sizeOut), null, 'div'),
          row('Cargar miniaturas', seg('thumbLoad', [['visible', 'En pantalla'], ['all', 'Todas']], 'Cargar miniaturas'), null, 'div'),
          row('Descargas simultáneas', seg('maxParallel', [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4']], 'Descargas simultáneas'), null, 'div'),
          row('Pausa entre descargas', num('delayMs', 0, 3000, 50, 'ms'))),

        ...dlSections,

        el('section', {}, blHeadEl,
          el('div', { className: 'card' },
            row('Galerías de la lista negra', seg('blMode', [['hide', 'Ocultar'], ['dim', 'Atenuar']], 'Galerías de la lista negra'), '«Atenuar» las desenfoca hasta que pasas el cursor', 'div'),
            el('div', { className: 'bl' }, el('div', { className: 'add' }, blInput, addBtn), blListEl))),

        section('Datos y copia de seguridad',
          row('Galerías favoritas', el('span', { className: 'ctl' }, favOut, favClearBtn), 'Se guardan con el corazón de las tarjetas, de la página de la galería y del lector', 'div'),
          row('Artistas y más', el('span', { className: 'ctl' }, ftOut, ftClearBtn), 'Se guardan con clic derecho en una etiqueta o con el botón de su página', 'div'),
          row('Obras descargadas', el('span', { className: 'ctl' }, histOut, histClearBtn), null, 'div'),
          row('Copia de seguridad', el('span', { className: 'ctl' }, bkExpBtn, bkImpBtn, bkFile),
            'Exporta o importa ajustes, lista negra, favoritos, listas e historial de descargas en un solo archivo JSON', 'div')),

        section('Atajos',
          el('dl', { className: 'keys' },
            ...keys(['←', '→'], 'Pasar de página (A / D también funcionan)'),
            ...keys(['Home', 'End'], 'Primera / última página'),
            ...keys(['T'], 'Ocultar la tira de miniaturas'),
            ...keys(['W'], 'Ajustar al ancho o al alto'),
            ...keys(['F'], 'Pantalla completa'),
            ...keys(['+', '−', '0'], 'Tamaño de la imagen'),
            ...keys(['/'], 'Ir al cuadro de búsqueda'),
            ...keys(['Esc'], 'Salir del lector'),
            ...keys(['Shift', 'Clic derecho'], 'Menú normal del navegador'))),

        el('p', { className: 'note', textContent: 'Haz clic derecho en una etiqueta para buscarla o añadirla a la lista negra. La lista de búsqueda pertenece a esta pestaña; las pestañas abiertas desde aquí empiezan con una copia. El intercambio de botones se aplica en la próxima carga de la página.' })),
      el('footer', {}, reset, done));

    close.onclick = done.onclick = () => dlg.close();
    dlg.addEventListener('click', e => { if (e.target === dlg) dlg.close(); });
    dlg.addEventListener('close', () => { host.remove(); dlg = blListEl = blHeadEl = null; });

    root.append(dlg);
    document.body.append(host);
    renderBlacklist();
    dlg.showModal();
  }

  function changed() { saveSettings(); applyTheme(); applyLayout(); syncUi(); scanCards(); readerActivity(); }

  GM_registerMenuCommand('Ajustes', () => ready(openSettings));

  ready(() => {
    if (isReader()) {
      patchReader();
      const ul = document.querySelector('.navbar .nav.navbar-nav');
      if (wantReaderUi()) {
        buildReaderBar();
      } else if (ul) {
        addPageBox(ul);
        addZoomBox(ul);
        ul.append(el('li', { className: 'hr-nav-li' }, gearButton('hr-navgear')));
      } else {
        document.body.append(gearButton('hr-fab'));
      }
    } else {
      const fab = gearButton('hr-fab');
      fab.append(el('span', { className: 'hr-badge', hidden: true }));
      document.body.append(fab);
      if (wantUi()) {
        buildApp();

        if (!pageGalleryId) waitFor(() => document.querySelector('.gallery-content'), 4000).then(ok => { if (!ok && !favView()) teardownApp(); });
      }
      new MutationObserver(scheduleScan).observe(document.body, { childList: true, subtree: true });
      scanCards();
    }
    panel = el('div', { id: 'hr-panel' });
    document.body.append(panel);
    renderPanel();
    applyLayout();
  });
})();

// ============================================================================
// HITOMI DOWNLOADER (SHIMURA): descargador integrado
// Arranca cuando el DOM está listo (igual que cuando era un script aparte),
// después de que Hitomi Enhanced haya dibujado su interfaz.
// ============================================================================
(() => {
  const startDownloader = () => {
    /******/ (() => {
        // webpackBootstrap
        /******/ "use strict";
        const location_hash = location.hash.startsWith("#VIEW#") ? location.hash : void 0;
        let db;
        let baseDir = null, baseSaved = !1, targetDir = null, dirPending = !1, dirReady = !1; // subdirectory (File System Access API)
        const runner = { running: !1, cancelled: !1, xhrs: new Set, paused: !1 }, qStatus = {}, qFailed = new Set, qInfo = {}; // download queue state
        let qDone = 0;
        let lastPick = -1, panelEl = null, pickGuardInstalled = !1, selectMode = "1" === tabGet("select_mode", "0");
        // Page selection state (gallery page: choose which pages are downloaded)
        const pg = { sel: new Set, mode: !1, last: -1, installed: !1 };
        // Hover-preview state
        const pv = { item: null, side: null, timer: 0, token: 0, gi: null, idx: 0, box: null, cache: new Map, ggP: null, lastWheel: 0, pos: new Map };
        // ---------- Panel language (English / Español) ----------
        const I18N = {
            en: {
                queue: "Queue", modeOff: "Select", modeOn: "Done", unselectAll: "Clear selection",
                modeTitle: "While on, links are disabled and clicking anywhere on a gallery selects it",
                selectAll: "Select all", selectAllTitle: "Select / unselect every gallery on this page (also turns selection mode on)",
                crawl: "Crawl selected works", crawlTitle: "Download every gallery in the queue",
                stop: "Stop", clear: "Clear",
                hint: 'Click the square on a gallery to add it. Shift+click selects a range. With "Manually select" on, click anywhere on a gallery.',
                download: "Download", threads: "Threads", format: "Format", zip: "Zip, split every", individual: "Individual files", pdfSingle: "Single PDF",
                cbz: "CBZ (comic book)", cbr: "CBR (comic book)",
                images: "Images", pdfQuality: "PDF quality", pdfQualityTitle: "Only used in PDF mode. Lower quality = smaller file. Recommended: 40%.",
                saveTo: "Save to", subfolder: "Subfolder", subfolderTitle: "Create a subdirectory", baseFolder: "Base folder", chooseFolder: "Choose folder", folderPrefix: "Folder: ",
                sortBy: "Sort by", none: "None", artist: "Artist", group: "Group", language: "Language", tagFirst: "Tag (first one)",
                folderName: "Folder name", folderNameTitle: "Placeholders: {title} {japanese_title} {artist} {artists} {group} {groups} {language} {tag} {type} {id} {date}. Use / for nested folders.",
                pgTitle: "Pages to download", pgMode: "Select pages", pgModeOn: "Stop selecting", pgAll: "All", pgNone: "None", pgInvert: "Invert", pgCount: "Selected", pgBtn: "Pages",
                pgHint: "Click the thumbnails to choose the pages (Shift+click selects a range). If none is selected, all pages are downloaded.",
                preview: "Preview", pvEnable: "Preview when hovering a work", pvEnableThumb: "Preview when hovering the pages of a work", pvSize: "Image size", pvOrig: "Original", pvSmall: "Small", pvWait: "Waiting time", pvWaitThumb: "Waiting time (pages of a work)",
                pvWheel: "Use the mouse wheel to switch images", pvKeys: "Use the arrow keys and space bar to switch images", pvSummary: "Show summary", pvCount: "Show page counter", revampDesign: "Hitomi Enhanced design (reloads the page)",
                pvLoading: "Loading\u2026", pvError: "Preview unavailable", type: "Type", pages: "Pages", tags: "Tags",
                gear: "Download settings", starting: "starting…", error: "error", remove: "Remove from queue",
                pick: "Add to download queue (Shift+click: select a range)",
                getOne: "Download this work now",
                cancelOne: "Cancel download",
                tagInsert: "Click to insert",
                fabStart: "Download",
                histTitle: "History", histCount: "downloaded works", histClear: "Clear history", histClearAsk: "Clear the download history?", histExport: "Export", histImport: "Import", histImported: "Imported works: ", histBad: "Invalid history file", histDone: "Already downloaded", histDoneOn: "Downloaded", fabDone: "Downloaded",
                fabHint: "Right-click to open the queue",
                emptyQueue: "No works selected. Pick some works first to add them to the queue.",
                selection: "Selection",
                stWait: "Pending", stPause: "Paused", pause: "Pause", resume: "Resume", stRun: "Downloading", stErr: "Error", pagesWord: "pages", sumInQueue: "in queue", sumDone: "completed", sumFailed: "failed"
            },
            es: {
                queue: "Cola", modeOff: "Seleccionar", modeOn: "Listo", unselectAll: "Quitar selección",
                modeTitle: "Activado, los enlaces se desactivan y un clic en cualquier parte de una obra la selecciona",
                selectAll: "Seleccionar todas", selectAllTitle: "Selecciona o deselecciona todas las obras de esta página (también activa la selección manual)",
                crawl: "Descargar obras seleccionadas", crawlTitle: "Descarga todas las obras de la cola",
                stop: "Detener", clear: "Vaciar",
                hint: 'Haz clic en el cuadro de una obra para agregarla. Shift+clic selecciona un rango. Con "Selección manual" activada, haz clic en cualquier parte de la obra.',
                download: "Descarga", threads: "Descargas a la vez", format: "Formato", zip: "Zip, dividir cada", individual: "Archivos individuales", pdfSingle: "PDF único",
                cbz: "CBZ (cómic)", cbr: "CBR (cómic)",
                images: "Imágenes", pdfQuality: "Calidad PDF", pdfQualityTitle: "Solo se usa en modo PDF. Menor calidad = archivo más pequeño. Recomendada: 40%.",
                saveTo: "Guardar en", subfolder: "Subcarpeta", subfolderTitle: "Crear un subdirectorio", baseFolder: "Carpeta base", chooseFolder: "Elegir carpeta", folderPrefix: "Carpeta: ",
                sortBy: "Ordenar por", none: "Ninguno", artist: "Artista", group: "Grupo", language: "Idioma", tagFirst: "Etiqueta (la primera)",
                folderName: "Nombre de carpeta", folderNameTitle: "Marcadores: {title} {japanese_title} {artist} {artists} {group} {groups} {language} {tag} {type} {id} {date}. Usa / para carpetas anidadas.",
                pgTitle: "Páginas a descargar", pgMode: "Seleccionar páginas", pgModeOn: "Cancelar selección", pgAll: "Todas", pgNone: "Ninguna", pgInvert: "Invertir", pgCount: "Seleccionadas", pgBtn: "Páginas",
                pgHint: "Haz clic en las miniaturas para elegir las páginas (Shift+clic selecciona un rango). Si no seleccionas ninguna, se descargan todas.",
                preview: "Vista previa", pvEnable: "Vista previa al pasar el cursor por una obra", pvEnableThumb: "Vista previa al pasar el cursor por las p\u00e1ginas de una obra", pvSize: "Tama\u00f1o de imagen", pvOrig: "Original", pvSmall: "Peque\u00f1o", pvWait: "Tiempo de espera", pvWaitThumb: "Tiempo de espera (p\u00e1ginas de una obra)",
                pvWheel: "Usar la rueda del mouse para cambiar de imagen", pvKeys: "Usar las flechas y la barra espaciadora para cambiar de imagen", pvSummary: "Mostrar resumen", pvCount: "Mostrar contador de p\u00e1ginas", revampDesign: "Dise\u00f1o de Hitomi Enhanced (recarga la p\u00e1gina)",
                pvLoading: "Cargando\u2026", pvError: "Vista previa no disponible", type: "Tipo", pages: "P\u00e1ginas", tags: "Etiquetas",
                gear: "Ajustes de descarga", starting: "iniciando…", error: "error", remove: "Quitar de la cola",
                pick: "Agregar a la cola de descarga (Shift+clic: seleccionar un rango)",
                getOne: "Descargar esta obra ahora",
                cancelOne: "Cancelar descarga",
                tagInsert: "Clic para insertar",
                fabStart: "Descargar",
                histTitle: "Historial", histCount: "obras descargadas", histClear: "Vaciar historial", histClearAsk: "\u00bfVaciar el historial de descargas?", histExport: "Exportar", histImport: "Importar", histImported: "Obras importadas: ", histBad: "Archivo de historial no v\u00e1lido", histDone: "Ya descargada", histDoneOn: "Descargada", fabDone: "Descargado",
                fabHint: "Clic derecho para abrir la cola",
                emptyQueue: "No hay obras seleccionadas. Selecciona primero algunas obras para agregarlas a la cola.",
                selection: "Selección",
                stWait: "Pendiente", stPause: "Pausada", pause: "Pausar", resume: "Reanudar", stRun: "Descargando", stErr: "Error", pagesWord: "páginas", sumInQueue: "en cola", sumDone: "completadas", sumFailed: "con error"
            }
        };
        init: {
            if (location.pathname.startsWith("/reader/")) break init;
            const gx = 4;
            if (GM_getValue("update", 0) != gx) {
                GM_getValue("db_update_time", 0) > 0 && localStorage.setItem("db_js", GM_getValue("db_js"));
                const list = GM_listValues();
                for (const key of list) /^hr-/.test(key) || GM_deleteValue(key); // conserva los datos de Hitomi Enhanced (hr-*)
                GM_setValue("update", gx);
            }
            GM_addStyle("\n#lang > a {\n  padding: 10px 15px;\n}\n.gallery-content > div > h1.lillie {\n  white-space: normal; //wrap long titles onto multiple lines\n}\n"),
            unsafeWindow.load_ehtagtranslation_db_text = obj => {
                const data = obj.data;
                obj = {
                    TMap: {
                        tags: "标签",
                        artists: "艺术家",
                        series: "原作",
                        characters: "角色",
                        language: "语言",
                        type: "类型",
                        group: "团队"
                    },
                    aliasMap: {
                        // Tags
                        loli: "lolicon",
                        shota: "shotacon",
                        // Type
                        "artist CG": "artistcg",
                        "game CG": "gamecg",
                        "image set": "imageset"
                    },
                    alias(str) {
                        return this.aliasMap[str] || str.toLowerCase();
                    }
                };
                for (const j of data) obj[j.namespace] = j;
                db = obj, $ && translate();
            };
            let is_add_script = !0;
            const xhr_onload = r => {
                if (200 !== r.status) return xhr.onerror(r), null;
                const responseText = r.responseText;
                if (4 === r.readyState) {
                    if (!responseText.includes("load_ehtagtranslation_db_")) return xhr.onerror(r),
                    null;
                    localStorage.setItem("db_update_time", (new Date).getTime() + 864e5 + ""), localStorage.setItem("db_js", responseText);
                }
                if (is_add_script) {
                    if (!document.head) return r.readyState = 0, void setTimeout(xhr_onload, 100, r);
                    is_add_script = !1;
                    const script = document.createElement("script");
                    script.src = URL.createObjectURL(new Blob([ responseText ], {
                        type: "application/x-javascript"
                    })), document.head.appendChild(script);
                }
            }, db_js = localStorage.getItem("db_js") || "";
            if (db_js.includes("load_ehtagtranslation_db_") && (xhr_onload({
                status: 200,
                responseText: db_js
            }), parseInt(localStorage.getItem("db_update_time") || "0") > (new Date).getTime())) break init;
            let index = 0;
            const urls = [ "https://github.com/EhTagTranslation/Database/releases/latest/download/db.text.js", "https://ghp.ci/https://github.com/EhTagTranslation/Database/releases/latest/download/db.text.js", "https://hub.gitmirror.com/https://github.com/EhTagTranslation/Database/releases/latest/download/db.text.js" ], xhr_onerror = er => {
                console.error(`status:${er.status || 0}, url:${xhr.url} index:${index}`), index >= 2 * urls.length ? is_add_script && alert("No se pudo cargar la base de traducción de etiquetas. Comprueba que puedes acceder a github.com, recarga la página e inténtalo de nuevo.") : xhr_send();
            }, xhr = {
                url: "",
                method: "GET",
                timeout: 1e4,
                onload: xhr_onload,
                onerror: xhr_onerror,
                ontimeout: xhr_onerror,
                onabort: xhr_onerror
            }, xhr_send = () => {
                xhr.url = urls[index++ % urls.length], GM_xmlhttpRequest(xhr);
            };
            xhr_send();
        }
        let $, main = () => {
            console.log("main()");
            {
                let limit, _onresizeT, each_fun = function() {
                    const el = $(this);
                    el.index() >= limit && el.addClass("hidden-list-item");
                }, onclick = function() {
                    let el = $(this);
                    const is = "Expand&gt;" === el.html();
                    el.html(is ? "Collapse&lt;" : "Expand&gt;"), el = el.parent().nextAll(), is ? el.removeClass("hidden-list-item") : el.addClass("hidden-list-item");
                }, each_fun2 = function() {
                    let el = $(this).children();
                    if (el.length > limit) {
                        const ex = $('<li><a style="cursor: pointer; color:aqua">Expand&gt;</a></li>');
                        ex.children().on("click", onclick), el.eq(9).after(ex), el = el.last(), "..." === el.text() && el.remove();
                    }
                };
                const onresize = () => {
                    _onresizeT = void 0;
                    const is = document.body.clientWidth > 768, p = 768 == document.body.clientWidth ? 30 : 15, dom = $(".gallery-content > div");
                    return dom.each((function() {
                        const img = this.firstElementChild, imgD = img.firstElementChild;
                        let top;
                        if (is) top = (this.offsetHeight - imgD.offsetHeight) / 2 + 18 + "px"; else {
                            const title = img.nextElementSibling, artist = title.nextElementSibling;
                            top = title.offsetHeight + artist.offsetHeight + p + "px";
                        }
                        imgD.style.top = top;
                    })), dom;
                };
                unsafeWindow.addEventListener("resize", (() => {
                    null != _onresizeT && clearTimeout(_onresizeT), _onresizeT = setTimeout(onresize, 10);
                }));
                //remove the blank space left behind when the top ad gets blocked
                const el = document.querySelector(".content > div, .top-content > div");
                el && !el.className.match("list-title|cover-column") && el.remove(), (main = () => {
                    limit = 10, $(".relatedtags li, .series-list li").each(each_fun), $(".relatedtags ul, .series-list ul").each(each_fun2),
                    limit = 5, $(".artist-list li").each(each_fun), $(".artist-list ul").each(each_fun2);
                    const dom = onresize();
                    dom.length && dom.find("a.lillie").removeAttr("target");
                })();
            }
            if (!unsafeWindow.galleryinfo) return void initListPage();
            let files = unsafeWindow.galleryinfo.files;
            const allFiles = files; // "files" is narrowed to the selected pages when a download starts
            installPreview(), installPageSelect(); // hover preview also works on the related galleries at the bottom of a gallery page
            // Force the buttons to match the thumbnail's width (the site does not do this by default)
            {
                const coverImg = document.querySelector(".cover-column.lillie > .cover img");
                if (coverImg) {
                    const applyBtnWidth = () => {
                        const w = coverImg.getBoundingClientRect().width;
                        if (w > 0) {
                            const column = coverImg.closest(".cover-column.lillie");
                            if (column) {
                                column.style.width = w + "px";
                                column.style.maxWidth = w + "px";
                                column.style.boxSizing = "border-box";
                            }
                            document.querySelectorAll("#dl-button, #read-online-button").forEach(b => {
                                b.style.width = "100%";
                                b.style.maxWidth = "100%";
                                b.style.boxSizing = "border-box";
                                b.style.marginLeft = "";
                                b.style.marginRight = "";
                            });
                        }
                    };
                    coverImg.complete ? applyBtnWidth() : coverImg.addEventListener("load", applyBtnWidth);
                    unsafeWindow.addEventListener("resize", applyBtnWidth);
                }
            }
            // Reader page
            // Download button extension
                    {
                const dlbt = $("#dl-button");
                dlbt.removeAttr("href").css("cursor", "pointer").children().html("Download"), GM_addStyle('\n.cover > a , #dl_options {\n  text-align: center;\n  display: block;\n}\n#dl_options input[type="radio"] {\n  margin: 0 2px 0 4px;\n}\n#dl_options span, #dl_options label, #dl_options input {\n  vertical-align: middle;\n  font-size: 14px;\n}\n.gallery-info > table {\n  table-layout: fixed; /*limit tag length*/\n}\n.cover-column.lillie {\n  box-sizing: border-box;\n}\n#dl-button, #read-online-button {\n  display: block;\n  width: 100%;\n  max-width: 100%;\n  box-sizing: border-box;\n  text-align: center;\n}\n#dl-button h1, #read-online-button h1 {\n  margin: 0;\n  font-size: 14px;\n  line-height: 1.4;\n  white-space: normal;\n  overflow-wrap: break-word;\n  word-break: break-word;\n  box-sizing: border-box;\n}\n#dl-button {\n  margin-bottom: 10px;\n}\n#read-online-button {\n  margin-top: 6px;\n  margin-bottom: 6px;\n}\n');
                const dl_options = buildPanel();
                // "Pages to download" (+ "Download" options) goes at the top of the gear panel, replacing the "Selection" section (only useful on the list page)
                {
                    const pgSec = dl_options.find("#dl_pg_sec");
                    GM_addStyle(`
    #dl_pg_sec { display: block; box-sizing: border-box; margin: 0 0 10px; padding: 0; text-align: left; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 12px; line-height: 1.3; color: #26323a; }
    #dl_pg_sec .dl-sec { margin: 14px 0 0; }
    #dl_pg_sec .dl-title { font-size: 10.5px; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; color: #c25b5b; margin: 0 0 6px; padding-bottom: 4px; border-bottom: 2px solid #ffcccc; }
    #dl_pg_sec .dl-btngrid { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 26px; gap: 5px; margin: 6px 0; }
    #dl_pg_sec .dl-btngrid button { width: 100% !important; min-width: 0 !important; height: auto !important; margin: 0 !important; padding: 1px 3px !important; box-sizing: border-box !important; white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; font-family: inherit; font-size: 10.5px !important; font-weight: 600; line-height: 1.1 !important; cursor: pointer; color: #26323a; background: #f4f7f9; border: 1px solid #d5dde3; border-radius: 8px; transition: background .15s, border-color .15s, transform .05s; }
    #dl_pg_sec .dl-btngrid button:hover { background: #fff0f0; border-color: #ffb3b3; }
    #dl_pg_sec .dl-btngrid button:active { transform: scale(.97); }
    #dl_pg_sec #dl_pg_mode { grid-column: 1 / -1; }
    #dl_pg_sec #dl_pg_mode.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_pg_sec .dl-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
    #dl_pg_sec #dl_pg_count { font-weight: 600; color: #c25b5b; }
    #dl_pg_sec .dl-hint { font-size: 10px; color: #8a98a3; opacity: 1; margin-top: 2px; }
    #dl_pg_sec .dl-lbl { flex: 0 0 74px; color: #5b6b76; font-weight: 500; }
    #dl_pg_sec .dl-ctl { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
    #dl_pg_sec .dl-ctl.dl-col { flex-direction: column; align-items: flex-start; gap: 5px; }
    #dl_pg_sec label { cursor: pointer; color: #26323a; }
    #dl_pg_sec input[type="radio"] { margin: 0 4px 0 0; }
    #dl_pg_sec input[type="radio"], #dl_pg_sec input[type="range"] { accent-color: #ff9999; }
    #dl_pg_sec input[type="number"] { background: #f7f9fb; color: #26323a; border: 1px solid #d5dde3; border-radius: 7px; padding: 3px 6px; font-size: 12px; outline: none; transition: border-color .15s, box-shadow .15s; }
    #dl_pg_sec input[type="number"]:focus { border-color: #ff9999; box-shadow: 0 0 0 3px rgba(255,153,153,.35); background: #fff; }
    #dl_pg_sec .dl-zip { white-space: nowrap; }
    #dl_pg_sec input[name="zip_max_length"] { width: 52px !important; }
    `);
                    // Hide the site's "Read Online" / "Download" buttons and progress bar (kept in the DOM, the script still uses them); our "Download" / "Queue" buttons replace them
                    GM_addStyle(`
    #dl-button, #read-online-button, #progressbar { display: none !important; }
    `), installGalleryButtons();
                    if (pgSec.length) {
                        // The page-selection controls go to a floating box at the bottom-right corner; the Download options stay in the settings panel
                        GM_addStyle(`
    #dl_pgbar { position: fixed; right: 8px; bottom: 8px; z-index: 2147483000; width: 260px; box-sizing: border-box; padding: 10px 14px; text-align: left; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 12px; line-height: 1.3; color: #26323a; background: #fff; border: 1px solid #e3e8ee; border-radius: 14px; box-shadow: 0 10px 34px rgba(0,0,0,.20); }
    #dl_pgbar .dl-title { font-size: 10.5px; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; color: #c25b5b; margin: 0 0 6px; padding-bottom: 4px; border-bottom: 2px solid #ffcccc; }
    #dl_pgbar .dl-btngrid { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 26px; gap: 5px; margin: 6px 0; }
    #dl_pgbar .dl-btngrid button { width: 100% !important; min-width: 0 !important; height: auto !important; margin: 0 !important; padding: 1px 3px !important; box-sizing: border-box !important; white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; font-family: inherit; font-size: 10.5px !important; font-weight: 600; line-height: 1.1 !important; cursor: pointer; color: #26323a; background: #f4f7f9; border: 1px solid #d5dde3; border-radius: 8px; transition: background .15s, border-color .15s, transform .05s; }
    #dl_pgbar .dl-btngrid button:hover { background: #fff0f0; border-color: #ffb3b3; }
    #dl_pgbar .dl-btngrid button:active { transform: scale(.97); }
    #dl_pgbar #dl_pg_mode { grid-column: 1 / -1; }
    #dl_pgbar #dl_pg_mode.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_pgbar .dl-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
    #dl_pgbar #dl_pg_count { font-weight: 600; color: #c25b5b; }
    #dl_pgbar .dl-hint { font-size: 10px; color: #8a98a3; margin-top: 2px; }
    body.dl-reading #dl_pgbar { display: none !important; }
    #dl_pgbar > .dl-title { display: flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; }
    #dl_pgbar > .dl-title::before { content: "\\25B8"; display: inline-block; font-size: 12px; transition: transform .15s; transform: rotate(90deg); }
    #dl_pgbar.dl-collapsed > .dl-title::before { transform: none; }
    #dl_pgbar > .dl-title:focus-visible { outline: 2px solid #ff9999; outline-offset: 2px; border-radius: 4px; }
    #dl_pgbar > #dl_pgbtn { display: none; }
    html body #dl_pgbar.dl-collapsed { width: fit-content; padding: 0; background: none !important; border: 0 !important; box-shadow: none !important; }
    #dl_pgbar.dl-collapsed > :not(#dl_pgbtn) { display: none !important; }
    #dl_pgbar.dl-collapsed > #dl_pgbtn { display: flex; }
    #dl_corner > #dl_pgbar { position: relative; right: auto; bottom: auto; z-index: auto; margin: 6px 0 0 auto; }
    `);
                        const pgBar = $('<div id="dl_pgbar"></div>');
                        pgBar.append(pgSec.children());
                        { const qb0 = $("#dl_qbtn"), cn0 = $("#dl_corner"); qb0.length ? qb0.after(pgBar) : cn0.length ? cn0.append(pgBar) : $("body").append(pgBar); }
                        {
                            // The panel can be folded by clicking its title (the choice is remembered in this tab)
                            const pgTitle = pgBar.children(".dl-title").first(), pgBtn = $('<button type="button" id="dl_pgbtn"></button>'), setPgOpen = open => {
                                pgBar.toggleClass("dl-collapsed", !open), pgTitle.attr("aria-expanded", String(open)), tabSet("pg_open", open ? "1" : "0");
                            };
                            pgBar.prepend(pgBtn), pgBtn.on("click", () => setPgOpen(!0)), pgTitle.attr({ role: "button", tabindex: "0" }).on("click", () => setPgOpen(pgBar.hasClass("dl-collapsed"))).on("keydown", e => {
                                "Enter" !== e.key && " " !== e.key || (e.preventDefault(), setPgOpen(pgBar.hasClass("dl-collapsed")));
                            }), setPgOpen("1" === tabGet("pg_open", "0")), pgBtnUpdate();
                            // Clicking outside of the panel folds it (not while selecting pages, where clicks on the thumbnails are the point)
                            window.addEventListener("pointerdown", ev => {
                                if (pgBar.hasClass("dl-collapsed") || pg.mode || ev.target.closest && ev.target.closest("#dl_pgbar")) return;
                                setPgOpen(!1);
                            }, !0);
                        }
                        const selEl = dl_options.find("#dl_q_mode").closest(".dl-sec");
                        selEl.length ? (pgSec.insertBefore(selEl), selEl.remove()) : dl_options.prepend(pgSec);
                        // Merge the "Download" section (images, threads, format, PDF quality) into this same panel
                        const dlSec = dl_options.find("input[name=dl_mode]").first().closest(".dl-sec");
                        if (dlSec.length) {
                            pgSec.append(dlSec);
                            const mode = pgSec.find("input[name=dl_mode]:checked").val();
                            pgSec.toggleClass("no-pdf", "3" !== mode).toggleClass("no-zip", "1" !== mode);
                        }
                    }
                }
                const dlt = $('<span style="position:absolute;left:0px;right:0px;vertical-align:middle;"/>'), progressbar = $("#progressbar");
                progressbar.append(dlt), progressbar.css({
                    "text-align": "center",
                    position: "relative"
                }), unsafeWindow.download_gallery = name => {
                    let obj;
                    let files_length = files.length;
                    const dl_fun = {
                        mode1(xhr) {
                            let zip, zip_i = 0;
                            do {
                                if ((zip = obj.zips[zip_i]) || (zip = obj.zips[zip_i] = new JSZip, zip_i > 0 && (zip.index = obj.zips[zip_i - 1].max_index + 1)),
                                xhr.dl_index > zip.max_index) {
                                    if (zip.next_zip) continue;
                                    files_length - xhr.dl_index < 20 ? zip.max_index = files_length : zip.max_index = xhr.dl_index;
                                }
                                break;
                            } while (++zip_i);
                            zip.file(files[xhr.dl_index].name, xhr.response), zip.index++;
                            const is_dl_finish = obj.dl_index_finish === files_length;
                            if (is_dl_finish || (zip.next_zip = (zip.byteLength += xhr.response.byteLength) > obj.zip_max_byteLength) && zip.index > zip.max_index) {
                                const zip_name = zip_i > 0 ? obj.gallery_name + " (" + zip_i + ")" : obj.gallery_name;
                                zip.generateAsync({
                                    type: "blob"
                                }).then((data => saveAs(data, zip_name + ".zip")));
                            }
                            is_dl_finish && this.finish();
                        },
                        mode3(xhr) {
                            if (obj.pages[xhr.dl_index] = new Uint8Array(xhr.response), obj.dl_index_finish !== files_length) return;
                            const pages = [];
                            for (const data of obj.pages) {
                                const size = data && 255 === data[0] && 216 === data[1] && jpegSize(data);
                                size ? pages.push({ data, w: size.w, h: size.h }) : console.warn("[pdf] page skipped (not a valid JPEG)");
                            }
                            pages.length && saveAs(buildPdf(pages), obj.gallery_name + ".pdf"), this.finish();
                        },
                        // CBZ / CBR: all pages (named 0001.ext, 0002.ext...) + ComicInfo.xml in a single archive
                        cbArchive(xhr, ext) {
                            const f = files[xhr.dl_index];
                            obj.cb[xhr.dl_index] = { name: String(xhr.dl_index + 1).padStart(4, "0") + "." + f.name.replace(/^.*\./, ""), data: new Uint8Array(xhr.response) };
                            if (obj.dl_index_finish !== files_length) return;
                            const entries = obj.cb.filter(Boolean);
                            entries.push({ name: "ComicInfo.xml", data: new TextEncoder().encode(comicInfoXml(unsafeWindow.galleryinfo || {}, entries.length)) });
                            saveAs(buildZip(entries), obj.gallery_name + "." + ext), this.finish();
                        },
                        mode4(xhr) {
                            this.cbArchive(xhr, "cbz");
                        },
                        mode5(xhr) {
                            this.cbArchive(xhr, "cbr");
                        },
                        mode2(xhr) {
                            let datas = obj.bolbs;
                            datas || (datas = obj.bolbs = []), xhr.response.dl_index = xhr.dl_index, datas.push(xhr.response),
                            obj.itv_id || (obj.itv_id = setInterval(this.mode2_itv.bind(this), 200));
                        },
                        mode2_itv() {
                            const blob = obj.bolbs.shift();
                            blob && obj ? saveAs(blob, obj.gallery_name + "_" + files[blob.dl_index].name) : (clearInterval(obj.itv_id),
                            obj.itv_id = 0, obj.dl_index_finish === files_length && this.finish());
                        },
                        finish() {
                            galleryQueueEnd(!!obj && obj.dl_index_finish === files_length), progressbar.hide(), dlbt.children().text("Download"), obj = null, pgUpdateLabel();
                        }
                    };
                    function xhr_onreadystatechange() {
                        if (4 === this.readyState) {
                            if (!obj) return;
                            200 === this.status ? (self => {
                                // the extension follows what was really downloaded (animated images keep their original format)
                                files[self.dl_index].name = files[self.dl_index].name.replace(/[^.]*$/, self.dl_cands[self.dl_try].ext);
                                const proceed = data => {
                                    if (!obj) return;
                                    dlt.html(++obj.dl_index_finish + "/" + files_length), galleryQueueProgress(obj.dl_index_finish, files_length), progressbar.progressbar("value", obj.dl_index_finish / files_length * 100),
                                    obj.dl_mode_fun(data), obj && obj.dl_index < files_length && (xhr_init(self), xhr_send.bind(self)());
                                };
                                obj.pages ? webpToJpg(self.response).then(converted => proceed({ response: converted, dl_index: self.dl_index }), err => {
                                    // Conversion failed: keep the original webp and fix the file extension
                                    console.warn("[jpg] conversion failed, keeping webp:", err);
                                    const f = files[self.dl_index];
                                    f.name = f.name.replace(/[^.]*$/, "webp"), proceed(self);
                                }) : proceed(self);
                            })(this) : (this.status >= 500 && this.status < 600 || (this.dl_try = (this.dl_try + 1) % this.dl_cands.length, this.dl_url = this.dl_cands[this.dl_try].url, --this.dl_retry)) && setTimeout(xhr_send.bind(this), 500);
                        }
                    }
                    function xhr_init(xhr) {
                        const image = files[obj.dl_index];
                        xhr.dl_cands = dlCandidates(unsafeWindow.galleryid, image, obj.img_type), xhr.dl_try = 0,
                        xhr.dl_url = xhr.dl_cands[0].url, xhr.dl_index = obj.dl_index++, xhr.dl_retry = 100;
                    }
                    function xhr_send() {
                        this.open("GET", this.dl_url, !0), this.send();
                    }
                    const JSZip = unsafeWindow.JSZip;
                    JSZip.prototype.byteLength = 0, JSZip.prototype.index = 0, JSZip.prototype.max_index = 0,
                    JSZip.prototype.next_zip = !1, (unsafeWindow.download_gallery = name => {
                        if (null != obj) {
                            for (const xhr of obj.xhrs) xhr.abort();
                            return void dl_fun.finish();
                        }
                        wantsDirPicker() || (targetDir = null);
                        if (wantsDirPicker() && !dirReady) {
                            dirPending || (dirPending = !0, ensureTargetDir().then(() => {
                                dirPending = !1, dirReady = !0, unsafeWindow.download_gallery(name), dirReady = !1;
                            }));
                            return;
                        }
                        files = pgFilter(allFiles), files_length = files.length;
                        dlbt.children().text("Cancel download"), dlt.html("0/" + files_length), progressbar.show(),
                        progressbar.progressbar({
                            value: !1
                        }), obj = {}, obj.gallery_name = name || "hitomi", obj.dl_index = 0, obj.dl_index_finish = 0,
                        obj.img_type = "avif" === GM_getValue("img_type", "webp") ? "avif" : "webp";
                        const dl_mode = GM_getValue("dl_mode", "1");
                        galleryQueueStart(files_length);
                        obj.dl_mode_fun = dl_fun["mode" + dl_mode].bind(dl_fun);
                        let xhr_responseType, dl_thread = parseInt(GM_getValue("dl_thread", "6"));
                        // Threads 1-6; more than 6 causes 503 errors
                        if (dl_thread = dl_thread < 1 ? 1 : dl_thread > 6 ? 6 : dl_thread, "1" === dl_mode) {
                            const max_length = parseInt(GM_getValue("zip_max_length", "1024"));
                            obj.zip_max_byteLength = 1048576 * (max_length < 100 ? 100 : max_length > 2048 ? 2048 : max_length),
                            // limit size to 100M-2048M
                            xhr_responseType = "arraybuffer", obj.zips = [];
                        } else if ("3" === dl_mode) {
                            // PDF mode: images are converted to JPEG and bundled into one single PDF (no size splitting)
                            xhr_responseType = "arraybuffer", obj.pages = [];
                        } else if ("4" === dl_mode || "5" === dl_mode) {
                            // CBZ / CBR: raw images collected in memory, then packed into one archive
                            xhr_responseType = "arraybuffer", obj.cb = [];
                        } else "2" === dl_mode && (xhr_responseType = "blob");
                        obj.xhrs = [];
                        for (let xhr, thread = 0; thread < dl_thread && obj.dl_index < files_length; thread++) obj.xhrs.push(xhr = new XMLHttpRequest),
                        xhr.onreadystatechange = xhr_onreadystatechange, xhr.responseType = xhr_responseType,
                        xhr_init(xhr), xhr_send.bind(xhr)();
                    })(name);
                };
            }
            // Online reading
                    {
                let titleA = $("#gallery-brand > a");
                titleA.length && titleA.before("(" + files.length + ")"), GM_addStyle('\n#_VIEW_ {\n    height: 100%;\n  width: 100%;\n  position: fixed;\n  z-index: 99998;\n}\n#_VIEW_ > iframe {\n  height: 100%;\n  width: 100%;\n}\n#_VIEW_ > .lum-close-button {\n  cursor: pointer;\n  position: absolute;\n  right: 5px;\n  top: 3px;\n  width: 32px;\n  height: 32px;\n  z-index: 99999;\n  opacity: 1\n}\n#_VIEW_ > .lum-close-button:hover {\n  opacity: .7\n}\n#_VIEW_ > .lum-close-button:after,.lum-close-button:before {\n  position: absolute;\n  left: 15px;\n  content: " ";\n  height: 33px;\n  width: 2px;\n  background-color: #fff;\n}\n#_VIEW_ > .lum-close-button:before {\n  transform: rotate(45deg)\n}\n#_VIEW_ > .lum-close-button:after {\n  transform: rotate(-45deg)\n}\n');
                const ro = $("#read-online-button > :eq(0)");
                ro.html("Read Online");
                const reader_href = ro.parent().attr("href"), view = $(`\n<div tabindex="1" style="display: none;">\n<div id="_VIEW_">\n  <iframe src="${reader_href}#1"/>\n  <div class="lum-close-button"/>\n </div>\n</div>\n`);
                document.body.prepend(view[0]);
                // While the online reader is open, hide our floating buttons (gear, Download, Queue) so they do not sit on top of it
                GM_addStyle("body.dl-reading #dl_gearbox, body.dl-reading #dl_corner, body.dl-reading #dl_fab, body.dl-reading #dl_qbtn { display: none !important; }");
                const syncReading = () => document.body.classList.toggle("dl-reading", "none" !== view[0].style.display);
                new MutationObserver(syncReading).observe(view[0], { attributes: !0, attributeFilter: [ "style" ] }), syncReading();
                const hideView = e => {
                    view.hide(), void 0 !== e && (unsafeWindow.history.back(), e.stopPropagation(),
                    e.preventDefault());
                };
                view.find(".lum-close-button").on("click", hideView);
                const _get_pagenum_hash = unsafeWindow.get_pagenum_hash;
                unsafeWindow.get_pagenum_hash = function(...args) {
                    if (location.hash.startsWith("#VIEW#")) {
                        const iframe = view.find("#_VIEW_>iframe")[0];
                        view.is(":hidden") && (view.show(), iframe.focus({
                            preventScroll: !0
                        }));
                        const page = location.hash.substring(6);
                        ro.html("Continue reading page " + page);
                        const iframe_hash = reader_href + "#" + page;
                        return $("#read-online-button, #gallery-brand > a").attr("href", iframe_hash), iframe.contentWindow?.location.replace(iframe_hash),
                        $(".simplePagerNav a").length + 1;
                    }
                    return view.is(":hidden") || hideView(void 0), _get_pagenum_hash.apply(this, args);
                }, $("#read-online-button, #gallery-brand > a, .thumbnail-container > a").on("click", (function(e) {
                    const match = this.href.match(/#([0-9-]+)$/), hash = "#VIEW#" + (match ? match[1] : "1");
                    view.is(":hidden") ? location.hash = hash : location.replace(hash), e.stopPropagation(),
                    e.preventDefault();
                })), unsafeWindow.addEventListener("message", (e => {
                    const data = e.data;
                    data.startsWith("#") && location.replace(location.pathname + data.replace("#", "#VIEW#"));
                }), !1), location_hash && (location.hash = location_hash);
            }
        }, translate = () => {
            let translateList;
            const is = null != unsafeWindow.galleryinfo;
            (translate = () => {
                if (document.querySelector(".dj-desc tr > td")) {
                    if (document.querySelector(".dj-desc tr > td[title]")) console.warn("! duplicate translation"); else if ($(".dj-desc tr > td:nth-of-type(1), .gallery-info tr > td:nth-of-type(1)").each(each_fun2),
                    //row name
                    translateList = [ "female", "male", "other", "mixed", "artist", "character", "cosplayer", "group", "parody" ],
                    $(".relatedtags a[href], .tags a[href]").each(each_fun), //tags
                    is && (
                    // $('.gallery-info ul#tags a').each(each_fun); // tags on the detail page
                    // translateList.splice(5, 1);
                    // translateList.unshift('character');
                    translateList = [ "character" ], $(".gallery-info ul#characters a").each(each_fun)),
                    // original work (parody)
                    translateList = [ "parody" ], $(".dj-content tr:nth-of-type(1) > td:nth-of-type(2) a").each(each_fun3),
                    is && ($(".gallery-info tr:nth-of-type(4) > td:nth-of-type(2) a").each(each_fun3),
                    translateList = [ "group" ], // group
                    $(".gallery-info tr:nth-of-type(1) > td:nth-of-type(2) a").each(each_fun3)),
                    // type
                    translateList = [ "reclass" ], $(".dj-content tr:nth-of-type(2) > td:nth-of-type(2) a").each(each_fun3),
                    is) {
                        $(".gallery-info tr:nth-of-type(2) > td:nth-of-type(2)").find("a").each(each_fun3);
                    }
                } else console.warn("? list still loading");
            })(),
            // Toolbar
            $("nav > ul > li > a[href]").each(each_fun2);
            const lang = $("nav > ul > li#lang > a");
            if (lang.length) {
                $("nav > ul #lang-list").children() ? (lang.html(lang.children()[0]), lang.prepend("Language ")) : lang.parent().hide();
            }
            function each_fun() {
                // Tag translation disabled: keep the original (English) text as-is.
            }
            function each_fun2() {
                // Tag translation disabled: keep the original (English) text as-is.
            }
            function each_fun3() {
                // Tag translation disabled: keep the original (English) text as-is.
            }
        };
        {
            let _$ = () => {
                if (!$) return;
                function limitLists(el = $(".gallery-content > div > h1.lillie > a")) {
                    el.length && (el.each(each_fun2), get_galleryinfo_l || get_galleryinfo_fnish(),
                    db && translate());
                }
                _$ = () => $, console.log("Start hijacking limitLists()"), unsafeWindow.limitLists ? unsafeWindow.limitLists = limitLists : Object.defineProperty(unsafeWindow, "limitLists", {
                    get: () => limitLists,
                    set() {}
                });
                let get_galleryinfo_l = 0;
                const galleryinfos = {};
                function each_fun2() {
                    const match = this.href.match(/-([0-9]+)\.html/);
                    match && !galleryinfos[match[1]] && (get_galleryinfo_l++, get_galleryinfo("//" + unsafeWindow.domain + "/galleries/" + match[1] + ".js", 10));
                }
                let galleryinfo_datas = [];
                function get_galleryinfo(url, retry) {
                    $.ajax({
                        type: "get",
                        url,
                        dataType: "text",
                        success: response => {
                            galleryinfo_datas.push(response.replace(/.*?galleryinfo *=/, "galleryinfos[" + url.replace(/.*\/([0-9]+).js$/, "'$1'") + "]= ")),
                            --get_galleryinfo_l || (new Function("galleryinfos", galleryinfo_datas.join("\n"))(galleryinfos),
                            galleryinfo_datas = [], get_galleryinfo_fnish());
                        },
                        error: () => retry && setTimeout(get_galleryinfo, 500, url, retry - 1)
                    });
                }
                function get_galleryinfo_fnish() {
                    $(".gallery-content > div > h1.lillie > a").each(each_fun), main();
                }
                function each_fun() {
                    const match = this.href.match(/-([0-9]+)\.html/);
                    if (!match) return;
                    const galleryinfo = galleryinfos[match[1]];
                    galleryinfo && $(this).before("(" + galleryinfo.files.length + ")");
                }
                const el = $(".gallery-content > div > h1.lillie > a");
                return el.length && limitLists(el), $;
            };
            unsafeWindow.$ ? (console.warn("Script was lazy-loaded"), $ = unsafeWindow.$, _$()) : Object.defineProperty(unsafeWindow, "$", {
                get: () => _$(),
                set(value) {
                    $ = value;
                }
            });
        }
        // Clean the user-typed subdirectory: "/" separates levels, no "..", no invalid characters
        function cleanSubdir(path) {
            return String(path || "").split(/[\\/]+/).map(p => p.replace(/[:*?"<>|]/g, "_").replace(/[. ]+$/, "").trim().slice(0, 120)).filter(p => p && "." !== p && ".." !== p).join("/");
        }
        function currentSubdir() {
            return "1" === GM_getValue("subdir_enabled", "0") ? cleanSubdir(GM_getValue("subdir_path", "")) : "";
        }
        // Folder name template, e.g. "{artist}/{title}" -> values taken from the current gallery
        function currentTemplateFolder(gi = unsafeWindow.galleryinfo || {}) {
            const tpl = GM_getValue("folder_template", "");
            if (!tpl.trim()) return "";
            const list = (arr, key) => Array.isArray(arr) ? arr.map(x => x && x[key]).filter(Boolean) : [];
            const values = {
                title: gi.title, japanese_title: gi.japanese_title, id: gi.id, type: gi.type,
                date: String(gi.date || "").slice(0, 10), language: gi.language || "all",
                artist: list(gi.artists, "artist")[0], artists: list(gi.artists, "artist").join(", "),
                group: list(gi.groups, "group")[0], groups: list(gi.groups, "group").join(", "),
                tag: list(gi.tags, "tag")[0]
            };
            return cleanSubdir(tpl.replace(/\{(\w+)\}/g, (m, key) => key in values ? String(values[key] || "_unknown").replace(/[\\/]+/g, "_") : m));
        }
        // Folder name taken from the current gallery (artist / group / language / first tag)
        function currentSortFolder(gi = unsafeWindow.galleryinfo || {}) {
            const by = GM_getValue("sort_by", "");
            if (!by) return "";
            const first = (arr, key) => Array.isArray(arr) && arr.length && arr[0] ? arr[0][key] : "";
            const value = "artist" === by ? first(gi.artists, "artist") : "group" === by ? first(gi.groups, "group") : "language" === by ? gi.language || "all" : "tag" === by ? first(gi.tags, "tag") : "";
            return cleanSubdir(String(value || "_unknown").replace(/[\\/]+/g, "_"));
        }
        function wantsDirPicker() {
            // a chosen base folder is used even when no subfolder / template is set
            return !!(currentSubdir() || currentSortFolder() || currentTemplateFolder() || baseSaved) && "function" == typeof unsafeWindow.showDirectoryPicker;
        }
        // Remember the base folder across reloads (FileSystemDirectoryHandle stored in IndexedDB)
        function openHandleDb() {
            return new Promise((resolve, reject) => {
                const req = unsafeWindow.indexedDB.open("hitomi_dl", 1);
                req.onupgradeneeded = () => req.result.createObjectStore("h"), req.onsuccess = () => resolve(req.result),
                req.onerror = () => reject(req.error);
            });
        }
        async function loadBaseDir() {
            const idbh = await openHandleDb();
            return new Promise(resolve => {
                const q = idbh.transaction("h").objectStore("h").get("base");
                q.onsuccess = () => (q.result && (baseSaved = !0), resolve(q.result || null)), q.onerror = () => resolve(null);
            });
        }
        async function saveBaseDir(handle) {
            const idbh = await openHandleDb();
            return new Promise(resolve => {
                const t = idbh.transaction("h", "readwrite");
                baseSaved = !0, t.objectStore("h").put(handle, "base"), t.oncomplete = t.onerror = () => resolve();
            });
        }
        loadBaseDir().then(h => { h && !baseDir && (baseDir = h); }).catch(() => {});
        // Make sure we have write access to the saved base folder (asks the user if needed; needs a user gesture)
        async function ensureBaseDir() {
            if ("function" != typeof unsafeWindow.showDirectoryPicker) return !1;
            baseDir || (baseDir = await loadBaseDir().catch(() => null));
            let granted = !1;
            if (baseDir) {
                let perm = await baseDir.queryPermission({ mode: "readwrite" });
                "granted" !== perm && (perm = await baseDir.requestPermission({ mode: "readwrite" })),
                granted = "granted" === perm;
            }
            if (!granted) {
                baseDir = await unsafeWindow.showDirectoryPicker({ id: "hitomi-dl", mode: "readwrite", startIn: "downloads" });
                saveBaseDir(baseDir).catch(() => {});
            }
            return !0;
        }
        // Folder for one gallery: base / subdirectory / sort folder / folder-name template
        async function dirForGallery(gi) {
            const path = [currentSubdir(), currentSortFolder(gi), currentTemplateFolder(gi)].filter(Boolean).join("/");
            if (!baseDir) return null;
            if (!path) return baseDir;
            let dir = baseDir;
            for (const seg of path.split("/")) dir = await dir.getDirectoryHandle(seg, { create: !0 });
            return dir;
        }
        async function ensureTargetDir() {
            targetDir = null;
            if (!wantsDirPicker()) return;
            try {
                if (!await ensureBaseDir()) return;
                targetDir = await dirForGallery(unsafeWindow.galleryinfo || {});
                targetDir && console.log("[subdir] saving into:", baseDir.name + "/" + [currentSubdir(), currentSortFolder(), currentTemplateFolder()].filter(Boolean).join("/"));
            } catch (err) {
                console.warn("[subdir] could not open folder, using normal downloads:", err);
            }
        }
        // Save a blob into a folder handle (or as a normal browser download when there is none)
        async function saveFile(dir, blob, filename) {
            if (dir) try {
                const handle = await dir.getFileHandle(filename.replace(/[\\/:*?"<>|]/g, "_"), { create: !0 });
                const writable = await handle.createWritable();
                return await writable.write(blob), void await writable.close();
            } catch (err) {
                console.warn("[subdir] write failed, using normal download:", err);
            }
            anchorSave(blob, filename);
        }
        // Download URLs to try for one image, in order. Images that have no webp / avif version (animated GIFs, etc.)
        // are downloaded in their original format so the animation is kept; the webp URL is the fallback.
        function dlCandidates(galleryId, image, pref) {
            image.oext = image.oext || (/\.([^.]+)$/.exec(image.name) || [ , "webp" ])[1];
            const t = "avif" === pref && image.hasavif ? "avif" : image.haswebp ? "webp" : "", out = [];
            if (!t) try {
                out.push({ ext: image.oext, url: unsafeWindow.url_from_url_from_hash(galleryId, image, "images", image.oext) });
            } catch (err) {}
            const wt = t || "webp";
            out.push({ ext: wt, url: unsafeWindow.url_from_url_from_hash(galleryId, image, wt) });
            return out;
        }
        function saveAs(blob, filename) {
            saveFile(targetDir, blob, filename);
        }
        // Decode the downloaded webp and re-encode it as JPEG (transparency becomes white)
        // Read width/height from a JPEG's SOF marker
        function jpegSize(u8) {
            let i = 2;
            for (; i + 9 < u8.length; ) {
                if (255 !== u8[i]) { i++; continue; }
                const m = u8[i + 1];
                if (255 === m) { i++; continue; }
                if (m >= 192 && m <= 207 && 196 !== m && 200 !== m && 204 !== m) return { h: u8[i + 5] << 8 | u8[i + 6], w: u8[i + 7] << 8 | u8[i + 8] };
                i += 2 + (u8[i + 2] << 8 | u8[i + 3]);
            }
            return null;
        }
        // Minimal PDF writer: one JPEG per page, page size = image size
        function buildPdf(pages) {
            const enc = new TextEncoder(), parts = [], offsets = [];
            let pos = 0;
            const push = chunk => {
                const u = "string" == typeof chunk ? enc.encode(chunk) : chunk;
                parts.push(u), pos += u.length;
            };
            const total = 2 + 3 * pages.length;
            push("%PDF-1.4\n"), offsets[1] = pos, push("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"),
            offsets[2] = pos, push("2 0 obj\n<< /Type /Pages /Count " + pages.length + " /Kids [" + pages.map((_, i) => 3 + 3 * i + " 0 R").join(" ") + "] >>\nendobj\n");
            pages.forEach((pg, i) => {
                const n = 3 + 3 * i, content = "q " + pg.w + " 0 0 " + pg.h + " 0 0 cm /Im0 Do Q";
                offsets[n] = pos, push(n + " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " + pg.w + " " + pg.h + "] /Resources << /XObject << /Im0 " + (n + 2) + " 0 R >> >> /Contents " + (n + 1) + " 0 R >>\nendobj\n"),
                offsets[n + 1] = pos, push(n + 1 + " 0 obj\n<< /Length " + content.length + " >>\nstream\n" + content + "\nendstream\nendobj\n"),
                offsets[n + 2] = pos, push(n + 2 + " 0 obj\n<< /Type /XObject /Subtype /Image /Width " + pg.w + " /Height " + pg.h + " /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length " + pg.data.length + " >>\nstream\n"),
                push(pg.data), push("\nendstream\nendobj\n");
            });
            const xref = pos;
            let table = "xref\n0 " + (total + 1) + "\n0000000000 65535 f \n";
            for (let i = 1; i <= total; i++) table += String(offsets[i]).padStart(10, "0") + " 00000 n \n";
            return push(table + "trailer\n<< /Size " + (total + 1) + " /Root 1 0 R >>\nstartxref\n" + xref + "\n%%EOF\n"),
            new Blob(parts, { type: "application/pdf" });
        }
        async function webpToJpg(response) {
            const isBlob = "function" == typeof response.arrayBuffer;
            const bitmap = await createImageBitmap(isBlob ? response : new Blob([response]));
            const canvas = document.createElement("canvas");
            canvas.width = bitmap.width, canvas.height = bitmap.height;
            const ctx = canvas.getContext("2d");
            ctx.fillStyle = "#fff", ctx.fillRect(0, 0, canvas.width, canvas.height), ctx.drawImage(bitmap, 0, 0),
            bitmap.close && bitmap.close();
            const quality = Math.min(100, Math.max(1, parseInt(GM_getValue("jpg_quality", "40")) || 40)) / 100;
            const out = await new Promise((resolve, reject) => canvas.toBlob(b => b ? resolve(b) : reject(new Error("toBlob failed")), "image/jpeg", quality));
            return isBlob ? out : await out.arrayBuffer();
        }
        // ---------- ZIP writer (store mode: images are already compressed) ----------
        const CRC_TABLE = (() => {
            const t = new Uint32Array(256);
            for (let n = 0; n < 256; n++) {
                let c = n;
                for (let k = 0; k < 8; k++) c = 1 & c ? 3988292384 ^ c >>> 1 : c >>> 1;
                t[n] = c >>> 0;
            }
            return t;
        })();
        function crc32(u8) {
            let c = 4294967295;
            for (let i = 0; i < u8.length; i++) c = CRC_TABLE[255 & (c ^ u8[i])] ^ c >>> 8;
            return (4294967295 ^ c) >>> 0;
        }
        function buildZip(entries) {
            const enc = new TextEncoder(), parts = [], central = [], now = new Date;
            const dosTime = now.getHours() << 11 | now.getMinutes() << 5 | now.getSeconds() >> 1;
            const dosDate = now.getFullYear() - 1980 << 9 | now.getMonth() + 1 << 5 | now.getDate();
            let offset = 0, cdSize = 0;
            for (const e of entries) {
                const name = enc.encode(e.name), crc = crc32(e.data), size = e.data.length;
                const lh = new DataView(new ArrayBuffer(30));
                lh.setUint32(0, 67324752, !0), lh.setUint16(4, 20, !0), lh.setUint16(6, 2048, !0), lh.setUint16(8, 0, !0),
                lh.setUint16(10, dosTime, !0), lh.setUint16(12, dosDate, !0), lh.setUint32(14, crc, !0),
                lh.setUint32(18, size, !0), lh.setUint32(22, size, !0), lh.setUint16(26, name.length, !0), lh.setUint16(28, 0, !0),
                parts.push(new Uint8Array(lh.buffer), name, e.data);
                const ch = new DataView(new ArrayBuffer(46));
                ch.setUint32(0, 33639248, !0), ch.setUint16(4, 20, !0), ch.setUint16(6, 20, !0), ch.setUint16(8, 2048, !0),
                ch.setUint16(10, 0, !0), ch.setUint16(12, dosTime, !0), ch.setUint16(14, dosDate, !0), ch.setUint32(16, crc, !0),
                ch.setUint32(20, size, !0), ch.setUint32(24, size, !0), ch.setUint16(28, name.length, !0),
                ch.setUint32(42, offset, !0), central.push(new Uint8Array(ch.buffer), name),
                offset += 30 + name.length + size, cdSize += 46 + name.length;
            }
            const end = new DataView(new ArrayBuffer(22));
            return end.setUint32(0, 101010256, !0), end.setUint16(8, entries.length, !0), end.setUint16(10, entries.length, !0),
            end.setUint32(12, cdSize, !0), end.setUint32(16, offset, !0),
            new Blob([ ...parts, ...central, new Uint8Array(end.buffer) ], { type: "application/zip" });
        }
        // ComicInfo.xml (read by YACReader, Komga, Kavita, CDisplayEx, etc.)
        function comicInfoXml(gi, pageCount) {
            const esc = s => String(s == null ? "" : s).replace(/[<>&"']/g, c => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c]);
            const list = (arr, key) => Array.isArray(arr) ? arr.map(x => x && x[key]).filter(Boolean) : [];
            const tags = Array.isArray(gi.tags) ? gi.tags.map(x => x && x.tag ? (1 == x.female ? "female:" : 1 == x.male ? "male:" : "") + x.tag : "").filter(Boolean) : [];
            const xml = [ '<?xml version="1.0" encoding="utf-8"?>', "<ComicInfo>" ];
            gi.title && xml.push("  <Title>" + esc(gi.title) + "</Title>");
            list(gi.artists, "artist").length && xml.push("  <Writer>" + esc(list(gi.artists, "artist").join(", ")) + "</Writer>", "  <Penciller>" + esc(list(gi.artists, "artist").join(", ")) + "</Penciller>");
            list(gi.groups, "group").length && xml.push("  <Publisher>" + esc(list(gi.groups, "group").join(", ")) + "</Publisher>");
            tags.length && xml.push("  <Tags>" + esc(tags.join(", ")) + "</Tags>");
            gi.type && xml.push("  <Genre>" + esc(gi.type) + "</Genre>");
            gi.id && xml.push("  <Web>https://hitomi.la/galleries/" + esc(gi.id) + ".html</Web>");
            xml.push("  <PageCount>" + pageCount + "</PageCount>", "</ComicInfo>");
            return xml.join("\n");
        }
        // ---------- Download any gallery by id (used by the queue) ----------
        const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
        // The site's image-URL helpers need gg.js; list pages may not load it
        function ensureGg() {
            return new Promise((resolve, reject) => {
                if ("function" != typeof unsafeWindow.url_from_url_from_hash) return reject(new Error("the site's url_from_url_from_hash() is not available on this page"));
                if (unsafeWindow.gg) return resolve();
                const script = document.createElement("script");
                script.src = "//" + unsafeWindow.domain + "/gg.js", script.onload = () => resolve(),
                script.onerror = () => reject(new Error("could not load gg.js")), document.head.appendChild(script);
            });
        }
        async function fetchGalleryInfo(id) {
            let lastErr;
            for (let i = 0; i < 5; i++) try {
                const res = await fetch("//" + unsafeWindow.domain + "/galleries/" + id + ".js");
                if (!res.ok) throw new Error("HTTP " + res.status);
                const text = await res.text(), gi = JSON.parse(text.slice(text.indexOf("=") + 1).trim().replace(/;$/, ""));
                return gi.id = gi.id || id, gi;
            } catch (err) {
                lastErr = err, await sleep(500 * (i + 1));
            }
            throw lastErr;
        }
        // ctl = { cancelled, xhrs:Set }. Honours the same settings as the normal download button.
        async function downloadGalleryInfo(gi, name, dir, onProgress, ctl) {
            const files = gi.files || [], total = files.length;
            if (!total) throw new Error("gallery has no files");
            const mode = GM_getValue("dl_mode", "1"), imgType = "avif" === GM_getValue("img_type", "webp") ? "avif" : "webp";
            let threads = parseInt(GM_getValue("dl_thread", "4")) || 4;
            threads = threads < 1 ? 1 : threads > 6 ? 6 : threads;
            let maxLen = parseInt(GM_getValue("zip_max_length", "1024")) || 1024;
            const zipMax = 1048576 * (maxLen < 100 ? 100 : maxLen > 2048 ? 2048 : maxLen);
            const results = new Array(total);
            let next = 0, done = 0, flushPtr = 0, chunk = [], chunkBytes = 0, part = 0, fatal = null;
            const flushZip = async () => {
                if (!chunk.length) return;
                const blob = buildZip(chunk), fname = (part ? name + " (" + part + ")" : name) + ".zip";
                part++, chunk = [], chunkBytes = 0, await saveFile(dir, blob, fname);
            };
            const fetchImage = image => new Promise((resolve, reject) => {
                let tries = 8, k = 0;
                const cands = dlCandidates(gi.id, image, imgType);
                const attempt = () => {
                    if (ctl.cancelled) return reject(new Error("cancelled"));
                    const { url, ext: type } = cands[k % cands.length], xhr = new XMLHttpRequest;
                    ctl.xhrs.add(xhr), xhr.open("GET", url, !0), xhr.responseType = "arraybuffer";
                    const fail = () => {
                        ctl.xhrs.delete(xhr), k++, ctl.cancelled ? reject(new Error("cancelled")) : --tries > 0 ? setTimeout(attempt, 600 * (8 - tries)) : reject(new Error("download failed: " + url));
                    };
                    xhr.onload = () => 200 === xhr.status ? (ctl.xhrs.delete(xhr), resolve({ buf: xhr.response, ext: type })) : fail(),
                    xhr.onerror = xhr.ontimeout = fail, xhr.onabort = () => (ctl.xhrs.delete(xhr), reject(new Error("cancelled"))),
                    xhr.send();
                };
                attempt();
            });
            const worker = async () => {
                for (;;) {
                    for (; ctl.paused && !ctl.cancelled; ) await sleep(250);
                    if (fatal || ctl.cancelled) return;
                    const i = next++;
                    if (i >= total) return;
                    const image = files[i], { buf, ext } = await fetchImage(image), fname = image.name.replace(/[^.]*$/, ext);
                    if ("2" === mode) await saveFile(dir, new Blob([ buf ]), name + "_" + fname); else if ("4" === mode || "5" === mode) results[i] = { name: String(i + 1).padStart(4, "0") + "." + ext, data: new Uint8Array(buf) }; else if ("3" === mode) try {
                        results[i] = new Uint8Array(await webpToJpg(buf));
                    } catch (err) {
                        console.warn("[pdf] conversion failed for", fname, err);
                    } else for (results[i] = { name: fname, data: new Uint8Array(buf) }; results[flushPtr]; ) {
                        const r = results[flushPtr];
                        results[flushPtr++] = !0, chunk.push(r), chunkBytes += r.data.length, chunkBytes >= zipMax && await flushZip();
                    }
                    onProgress(++done, total);
                }
            };
            await Promise.all(Array.from({ length: Math.min(threads, total) }, () => worker().catch(err => {
                fatal = fatal || err;
            })));
            if (ctl.cancelled) throw new Error("cancelled");
            if (fatal) throw fatal;
            if ("1" === mode) await flushZip(); else if ("4" === mode || "5" === mode) {
                const entries = results.filter(Boolean);
                if (!entries.length) throw new Error("no pages downloaded");
                entries.push({ name: "ComicInfo.xml", data: new TextEncoder().encode(comicInfoXml(gi, entries.length)) });
                await saveFile(dir, buildZip(entries), name + ("5" === mode ? ".cbr" : ".cbz"));
            } else if ("3" === mode) {
                const pages = [];
                for (const data of results) {
                    const size = data && 255 === data[0] && 216 === data[1] && jpegSize(data);
                    size && pages.push({ data, w: size.w, h: size.h });
                }
                if (!pages.length) throw new Error("no page could be converted for the PDF");
                await saveFile(dir, buildPdf(pages), name + ".pdf");
            }
        }
        // Settings + queue panel (fixed in the top-left corner). Built once; used on gallery pages and on list pages.
        // Rapid clicks (double / triple click) on the script's buttons or on works / thumbnails in selection mode
        // must not highlight text in blue.
        function noSelectStyles() {
            GM_addStyle(`
    #dl_fab, #dl_qbtn, #dl_selbar, #dl_pgbar, #dl_gearbox, #dl_qpanel, #dl_gear, .dl-pick, .dl-get, .dl-pgchk { -webkit-user-select: none !important; user-select: none !important; }
    #dl_options input[type="text"], #dl_options input[type="number"] { -webkit-user-select: text !important; user-select: text !important; }
    body.dl-selmode .gallery-content > div, body.dl-selmode .gallery-content > div * { -webkit-user-select: none !important; user-select: none !important; }
    body.dl-pgmode .thumbnail-container, body.dl-pgmode .thumbnail-container * { -webkit-user-select: none !important; user-select: none !important; }
    `);
            document.addEventListener("mousedown", ev => {
                if (ev.detail < 2 || !ev.target.closest || ev.target.closest("input, textarea, select")) return;
                const body = document.body;
                if (ev.target.closest("#dl_fab, #dl_qbtn, #dl_selbar, #dl_pgbar, #dl_gearbox, #dl_qpanel, .dl-pick, .dl-get")
                    || body.classList.contains("dl-selmode") && ev.target.closest(".gallery-content > div")
                    || body.classList.contains("dl-pgmode") && ev.target.closest(".thumbnail-container")) ev.preventDefault();
            }, !0);
        }
        function buildPanel() {
            if (panelEl) return panelEl;
            noSelectStyles();
                const dl_options = $(`
    <div id="dl_options">
      <div class="dl-sec">
        <div class="dl-title"><span data-i18n="queue">Queue</span> <span id="dl_q_count">(0)</span></div>
        <div class="dl-btngrid">
          <button type="button" id="dl_q_mode" data-i18n-title="modeTitle">Manually select</button>
          <button type="button" id="dl_q_page" data-i18n-title="selectAllTitle">Select all</button>
          <button type="button" id="dl_q_start" data-i18n-title="crawlTitle">Crawl selected works 0</button>
          <button type="button" id="dl_q_pause" disabled>Pause</button>
          <button type="button" id="dl_q_stop" data-i18n="stop" disabled>Stop</button>
          <button type="button" id="dl_q_clear" data-i18n="clear">Clear</button>
        </div>
        <div id="dl_q_sum" class="dl-qsum"></div>
        <div id="dl_q_list"></div>
        <div class="dl-hint" data-i18n="hint"></div>
      </div>
      <div class="dl-sec">
        <div class="dl-title" data-i18n="download">Download</div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="images">Images</span><span class="dl-ctl">
          <label><input type="radio" name="img_type" value="webp">webp</label>
          <label><input type="radio" name="img_type" value="avif">avif</label>
        </span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="threads">Threads</span><span class="dl-ctl"><input type="number" style="width:48px" name="dl_thread" value="${GM_getValue("dl_thread", "4")}"></span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="format">Format</span><span class="dl-ctl dl-col">
          <label class="dl-zip"><input type="radio" name="dl_mode" value="1"><span data-i18n="zip">Zip, split every</span> <input type="number" style="width:60px" name="zip_max_length" value="${GM_getValue("zip_max_length", "1024")}"> MB</label>
          <label><input type="radio" name="dl_mode" value="2"><span data-i18n="individual">Individual files</span></label>
          <label><input type="radio" name="dl_mode" value="3"><span data-i18n="pdfSingle">Single PDF</span></label>
          <label><input type="radio" name="dl_mode" value="4"><span data-i18n="cbz">CBZ (comic book)</span></label>
          <label><input type="radio" name="dl_mode" value="5"><span data-i18n="cbr">CBR (comic book)</span></label>
        </span></div>
        <div class="dl-row dl-pdf"><span class="dl-lbl" data-i18n="pdfQuality">PDF quality</span><span class="dl-ctl">
          <input type="range" name="jpg_quality" min="10" max="100" step="5" style="flex:1;min-width:0" data-i18n-title="pdfQualityTitle" value="${GM_getValue("jpg_quality", "40")}">
          <span id="dl_q_val" style="min-width:34px;text-align:right">${GM_getValue("jpg_quality", "40")}%</span>
        </span></div>
      </div>
      <div class="dl-sec">
        <div class="dl-title" data-i18n="saveTo">Save to</div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="baseFolder">Base folder</span><span class="dl-ctl"><button type="button" id="dl_subdir_pick">Choose folder</button></span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="subfolder">Subfolder</span><span class="dl-ctl">
          <input type="checkbox" id="dl_subdir_toggle" data-i18n-title="subfolderTitle">
          <input type="text" id="dl_subdir_path" placeholder="X/Downloads" value="${GM_getValue("subdir_path", "").replace(/"/g, "&quot;")}">
        </span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="folderName">Folder name</span><span class="dl-ctl">
          <input type="text" id="dl_folder_tpl" placeholder="{artist}/{title}" data-i18n-title="folderNameTitle" value="${GM_getValue("folder_template", "").replace(/"/g, "&quot;")}">
        </span></div>
        <div class="dl-hint dl-tags">${[ "title", "artist", "artists", "group", "language", "tag", "type", "id", "date" ].map(t => `<span class="dl-tag" data-tag="${t}" data-i18n-title="tagInsert">{${t}}</span>`).join(" ")}</div>
      </div>
      <div class="dl-sec" id="dl_pg_sec">
        <div class="dl-title" data-i18n="pgTitle">Pages to download</div>
        <div class="dl-btngrid">
          <button type="button" id="dl_pg_mode"></button>
          <button type="button" id="dl_pg_all" data-i18n="pgAll">All</button>
          <button type="button" id="dl_pg_none" data-i18n="pgNone">None</button>
          <button type="button" id="dl_pg_inv" data-i18n="pgInvert">Invert</button>
        </div>
        <div class="dl-row"><span id="dl_pg_count"></span></div>
        <div class="dl-hint" data-i18n="pgHint"></div>
      </div>
      <div class="dl-sec">
        <div class="dl-title" data-i18n="preview">Preview</div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_enabled" data-def="1"> <span data-i18n="pvEnable">Preview when hovering a work</span></label></div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_thumb_enabled" data-def="1"> <span data-i18n="pvEnableThumb">Preview when hovering the pages of a work</span></label></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="pvSize">Image size</span><span class="dl-ctl">
          <label><input type="radio" name="pv_size" value="orig"><span data-i18n="pvOrig">Original</span></label>
          <label><input type="radio" name="pv_size" value="small"><span data-i18n="pvSmall">Small</span></label>
        </span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="pvWait">Waiting time</span><span class="dl-ctl"><input type="number" style="width:64px" name="pv_wait" value="${GM_getValue("pv_wait", "400")}"> ms</span></div>
        <div class="dl-row"><span class="dl-lbl" data-i18n="pvWaitThumb">Waiting time (pages of a work)</span><span class="dl-ctl"><input type="number" style="width:64px" name="pv_wait_thumb" value="${GM_getValue("pv_wait_thumb", "200")}"> ms</span></div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_wheel" data-def="1"> <span data-i18n="pvWheel">Use the mouse wheel to switch images</span></label></div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_keys" data-def="1"> <span data-i18n="pvKeys">Use the arrow keys and space bar to switch images</span></label></div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_summary" data-def="0"> <span data-i18n="pvSummary">Show summary</span></label></div>
        <div class="dl-row"><label><input type="checkbox" data-pv="pv_count" data-def="1"> <span data-i18n="pvCount">Show page counter</span></label></div>
      </div>
      <div class="dl-sec">
        <div class="dl-title" data-i18n="histTitle">History</div>
        <div class="dl-row"><span><b id="dl_hist_count">0</b> <span data-i18n="histCount">downloaded works</span></span><button type="button" id="dl_hist_clear" data-i18n="histClear">Clear history</button></div>
        <div class="dl-row"><button type="button" id="dl_hist_export" data-i18n="histExport">Export</button><button type="button" id="dl_hist_import" data-i18n="histImport">Import</button><input type="file" id="dl_hist_file" accept=".json,application/json" style="display:none"></div>
      </div>
      <div class="dl-sec">
        <div class="dl-row"><label><input type="checkbox" id="dl_revamp"> <span data-i18n="revampDesign">Hitomi Enhanced design (reloads the page)</span></label></div>
        <div class="dl-row"><span class="dl-lbl">Language / Idioma</span><span class="dl-ctl"><select id="dl_lang"><option value="en">English</option><option value="es">Espa\u00f1ol</option></select></span></div>
      </div>
    </div>
    `);
                dl_options.find("input[name=dl_mode][value=" + GM_getValue("dl_mode", "1") + "]").attr("checked", "checked"),
                dl_options.find("input[name=img_type][value=" + ("avif" === GM_getValue("img_type", "webp") ? "avif" : "webp") + "]").attr("checked", "checked"),
                dl_options.find("input[type]").on("change", (e => {
                    const target = e.target, name = target.name;
                    name && GM_setValue(name, target.value);
                }));
                // Master switch for the Hitomi Enhanced design (shares its settings with the Enhanced dialog)
                {
                    const rs = GM_getValue("hr-settings", {}), box = dl_options.find("#dl_revamp");
                    box.prop("checked", !(rs && "object" == typeof rs && !1 === rs.revamp)), box.on("change", e => {
                        const cur = GM_getValue("hr-settings", {});
                        GM_setValue("hr-settings", Object.assign({}, cur && "object" == typeof cur ? cur : {}, { revamp: !!e.target.checked })), location.reload();
                    });
                }
                // The page-selection section only makes sense on a gallery page
                unsafeWindow.galleryinfo || dl_options.find("#dl_pg_sec").hide();
                // Download history: count + clear button
                dl_options.find("#dl_hist_count").text(Object.keys(histLoad()).length),
                dl_options.find("#dl_hist_clear").on("click", () => {
                    confirm(uiText("histClearAsk")) && histClear();
                });
                // Export / import the history as a JSON file (backup, or move it to another browser)
                dl_options.find("#dl_hist_export").on("click", () => {
                    const d = new Date, p = n => String(n).padStart(2, "0");
                    saveAs(new Blob([ JSON.stringify(histLoad(), null, 1) ], { type: "application/json" }), "hitomi-history-" + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + ".json");
                }),
                dl_options.find("#dl_hist_import").on("click", () => dl_options.find("#dl_hist_file").val("").trigger("click")),
                dl_options.find("#dl_hist_file").on("change", e => {
                    const f = e.target.files && e.target.files[0];
                    if (!f) return;
                    const rd = new FileReader;
                    rd.onload = () => {
                        try {
                            const inc = JSON.parse(rd.result);
                            if (!inc || "object" != typeof inc || Array.isArray(inc)) throw 0;
                            const h = histLoad();
                            let n = 0;
                            for (const id of Object.keys(inc)) {
                                const v = inc[id];
                                if (!/^\d+$/.test(id) || !v || "object" != typeof v) continue;
                                const cur = h[id];
                                cur && cur.t >= v.t || (h[id] = { t: +v.t || Date.now(), title: String(v.title || "").slice(0, 120) }), n++;
                            }
                            GM_setValue("dl_history", JSON.stringify(h)), renderHistory(), alert(uiText("histImported") + n);
                        } catch (err) {
                            alert(uiText("histBad"));
                        }
                    };
                    rd.readAsText(f);
                });
                // Hover-preview options
                dl_options.find("input[name=pv_size][value=" + ("small" === GM_getValue("pv_size", "small") ? "small" : "orig") + "]").attr("checked", "checked");
                dl_options.find("input[data-pv]").each(function() {
                    this.checked = "1" === GM_getValue(this.dataset.pv, this.dataset.def || "0");
                }).on("change", e => {
                    GM_setValue(e.target.dataset.pv, e.target.checked ? "1" : "0");
                });
                // Subdirectory option (toggle + path), persisted with GM_setValue
                dl_options.find("#dl_subdir_toggle").prop("checked", "1" === GM_getValue("subdir_enabled", "0")).on("change", (e => {
                    GM_setValue("subdir_enabled", e.target.checked ? "1" : "0");
                }));
                dl_options.find("#dl_subdir_path").on("input change", (e => {
                    GM_setValue("subdir_path", e.target.value);
                }));
                dl_options.find("input[name=jpg_quality]").on("input", (e => {
                    $("#dl_q_val").text(e.target.value + "%"), GM_setValue("jpg_quality", e.target.value);
                }));
                dl_options.find("#dl_folder_tpl").on("input change", (e => {
                    GM_setValue("folder_template", e.target.value);
                }));
                dl_options.find(".dl-tag").on("mousedown", e => e.preventDefault()).on("click", e => {
                    const inp = dl_options.find("#dl_folder_tpl")[0], tag = e.currentTarget.textContent;
                    if (!inp) return;
                    const a = inp.selectionStart == null ? inp.value.length : inp.selectionStart, b = inp.selectionEnd == null ? a : inp.selectionEnd;
                    inp.value = inp.value.slice(0, a) + tag + inp.value.slice(b), GM_setValue("folder_template", inp.value);
                    inp.focus(), inp.setSelectionRange(a + tag.length, a + tag.length);
                });
                GM_setValue("sort_by", ""); // "Sort by" option removed: an old saved value must not keep applying
                // Hooks used by the Hitomi Enhanced settings dialog (same GM keys, same language switch)
                window.__hrDl = {
                    setLang: v => (GM_setValue("ui_lang", v), applyLang()),
                    histChanged: () => renderHistory(),
                    baseDirName: async () => (baseDir || (baseDir = await loadBaseDir().catch(() => null)), baseDir ? baseDir.name : ""),
                    pickDir: cb => unsafeWindow.showDirectoryPicker({ id: "hitomi-dl", mode: "readwrite", startIn: "downloads" }).then(handle => {
                        baseDir = handle, saveBaseDir(handle).catch(() => {}), cb && cb(handle.name);
                    }).catch(() => {})
                };
                dl_options.find("#dl_subdir_pick").on("click", (() => {
                    unsafeWindow.showDirectoryPicker({ id: "hitomi-dl", mode: "readwrite", startIn: "downloads" }).then(handle => {
                        baseDir = handle, saveBaseDir(handle).catch(() => {}), dl_options.find("#dl_subdir_pick").text(uiText("folderPrefix") + handle.name);
                    }).catch(() => {});
                }));
                // Settings panel: fixed in the top-left corner, opened/closed with a gear button (state remembered)
                {
                    const corner = $('<div id="dl_corner" style="position:fixed;top:8px;right:8px;z-index:2147483000;text-align:right;"/>');
                    const gear = $('<button type="button" id="dl_gear" data-i18n-title="gear" style="width:32px;height:32px;border-radius:50%;border:1px solid #aaa;background:#fff;color:#222;font-size:18px;line-height:1;cursor:pointer;padding:0;position:relative;">\u2699<span id="dl_badge"></span></button>');
                    GM_addStyle(`
    #dl_options { width: 340px; box-sizing: border-box; font-size: 13px; line-height: 1.3; }
    #dl_options .dl-sec { margin: 0 0 10px; }
    #dl_options .dl-sec:last-child { margin-bottom: 0; }
    #dl_options .dl-title { font-size: 11px; font-weight: bold; letter-spacing: .08em; text-transform: uppercase; opacity: .7; margin: 0 0 6px; padding-bottom: 3px; border-bottom: 1px solid #ccc; }
    #dl_options .dl-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
    #dl_options .dl-lbl { flex: 0 0 84px; opacity: .85; }
    #dl_options .dl-ctl { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
    #dl_options .dl-ctl.dl-col { flex-direction: column; align-items: flex-start; gap: 5px; }
    #dl_options .dl-ctl input[type="text"] { flex: 1; min-width: 0; }
    #dl_options .dl-ctl select { flex: 1; min-width: 0; }
    #dl_options label { cursor: pointer; }
    #dl_options input[type="radio"] { margin: 0 4px 0 0; }
    #dl_options .dl-hint { font-size: 11px; opacity: .6; margin-top: 2px; }
    #dl_options .dl-zip { white-space: nowrap; }
    #dl_options .dl-btns { flex-wrap: wrap; }
    #dl_options button:disabled { opacity: .45; cursor: default; }
    #dl_options .dl-btngrid { display: grid; grid-template-columns: repeat(3, 96px); grid-auto-rows: 46px; justify-content: start; gap: 6px; margin: 6px 0; }
    #dl_options .dl-btngrid button { width: 100% !important; min-width: 0 !important; height: auto !important; margin: 0 !important; padding: 2px 3px !important; box-sizing: border-box !important; white-space: normal !important; overflow: hidden; overflow-wrap: anywhere; font-size: 10.5px !important; line-height: 1.15 !important; }
    #dl_options #dl_q_mode.dl-on, #dl_options #dl_pg_mode.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_q_list { max-height: 170px; overflow-y: auto; margin: 4px 0; }
    #dl_q_list .dl-qi { display: flex; gap: 6px; align-items: center; padding: 2px 0; border-bottom: 1px solid #ddd; }
    #dl_options .dl-qi span { font-size: 12px; }
    #dl_q_list .dl-qt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    #dl_q_list .dl-qs { opacity: .75; white-space: nowrap; }
    #dl_q_list .dl-qx { cursor: pointer; opacity: .7; padding: 0 2px; }
    #dl_badge { display: none; position: absolute; top: -5px; right: -7px; min-width: 16px; height: 16px; padding: 0 3px; box-sizing: border-box; border-radius: 8px; background: #ffcccc; color: #000; font: bold 10px/16px sans-serif; text-align: center; }
    `);
                    GM_addStyle(`
    #dl_options { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif !important; background: #fff !important; color: #26323a !important; border: 1px solid #e3e8ee !important; border-radius: 14px !important; box-shadow: 0 10px 34px rgba(0,0,0,.20) !important; padding: 14px 16px !important; }
    #dl_options .dl-sec { margin: 0 0 16px; }
    #dl_options .dl-title { font-size: 10.5px; font-weight: 700; letter-spacing: .14em; color: #c25b5b; opacity: 1; border-bottom: 2px solid #ffcccc; padding-bottom: 4px; margin: 0 0 8px; }
    #dl_options .dl-lbl { color: #5b6b76; opacity: 1; font-weight: 500; }
    #dl_options .dl-hint { color: #8a98a3; opacity: 1; }
    #dl_options .dl-tag { display: inline-block; margin: 3px 3px 0 0; padding: 1px 7px; border-radius: 6px; background: #f4f7f9; border: 1px solid #d5dde3; color: #26323a; font-size: 11px; cursor: pointer; user-select: none; transition: background .15s, border-color .15s, transform .05s; }
    #dl_options .dl-tag:hover { background: #fff0f0; border-color: #ffb3b3; }
    #dl_options .dl-tag:active { background: #ffcccc; transform: scale(.96); }
    #dl_options label { color: #26323a; }
    #dl_options input[type="radio"], #dl_options input[type="checkbox"], #dl_options input[type="range"] { accent-color: #ff9999; }
    #dl_options input[type="text"], #dl_options input[type="number"], #dl_options select { background: #f7f9fb; color: #26323a; border: 1px solid #d5dde3; border-radius: 7px; padding: 4px 8px; font-size: 12px; outline: none; transition: border-color .15s, box-shadow .15s; }
    #dl_options input[type="text"]:focus, #dl_options input[type="number"]:focus, #dl_options select:focus { border-color: #ff9999; box-shadow: 0 0 0 3px rgba(255,153,153,.35); background: #fff; }
    #dl_options button { font-family: inherit; color: #26323a; background: #f4f7f9; border: 1px solid #d5dde3; border-radius: 8px; padding: 5px 10px; font-size: 12px; font-weight: 600; cursor: pointer; transition: background .15s, border-color .15s, transform .05s; }
    #dl_options button:hover:not(:disabled) { background: #fff0f0; border-color: #ffb3b3; }
    #dl_options button:active:not(:disabled) { transform: scale(.97); }
    #dl_options .dl-btngrid button { font-size: 11px !important; border-radius: 8px !important; }
    #dl_options #dl_q_mode.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_options #dl_q_start:not(:disabled) { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_options #dl_q_start:hover:not(:disabled) { background: #ffb3b3; border-color: #ffb3b3; }
    #dl_q_list { border-radius: 8px; }
    #dl_q_list .dl-qi { border-bottom: 1px solid #eef2f5; }
    #dl_gear { width: 36px !important; height: 36px !important; border: 1px solid #d5dde3 !important; background: #fff !important; color: #26323a !important; box-shadow: 0 4px 14px rgba(0,0,0,.18); transition: transform .2s, background .15s; }
    #dl_gear:hover { background: #fff0f0 !important; transform: rotate(45deg); }
    `);
                    const syncMode = () => {
                        const both = dl_options.add($("#dl_pg_sec")), mode = both.find("input[name=dl_mode]:checked").val();
                        both.toggleClass("no-pdf", "3" !== mode).toggleClass("no-zip", "1" !== mode);
                    };
                    dl_options.find("input[name=dl_mode]").on("change", syncMode), syncMode();
                    dl_options.css({
                        display: "1" === tabGet("opts_open", "0") ? "block" : "none",
                        "margin-top": "6px", padding: "8px 12px", "max-width": "340px", "max-height": "calc(100vh - 64px)", "overflow-y": "auto", "text-align": "left",
                        background: "#fff", color: "#222", border: "1px solid #bbb", "border-radius": "6px"
                    }), gear.on("click", (() => {
                        const show = dl_options.is(":hidden");
                        dl_options.css("display", show ? "block" : "none"), tabSet("opts_open", show ? "1" : "0");
                    })), $("body").append(corner); // top-right: download button + queue panel
                    // Gear + settings panel: own box, bottom-right by default, draggable by the gear (position remembered)
                    GM_addStyle(`
    #dl_gearbox { position: fixed; bottom: 8px; right: 8px; z-index: 2147483000; display: flex; flex-direction: column; align-items: flex-end; text-align: right; }
    #dl_gearbox.dl-left { align-items: flex-start; }
    #dl_gearbox.dl-top { flex-direction: column-reverse; }
    #dl_gearbox #dl_options { margin: 0 0 6px 0 !important; }
    #dl_gearbox.dl-top #dl_options { margin: 6px 0 0 0 !important; }
    #dl_gear { touch-action: none; cursor: grab; }
    #dl_gear:active { cursor: grabbing; }
    `);
                    const box = $('<div id="dl_gearbox"/>');
                    box.append(dl_options, gear), $("body").append(box);
                    {
                        const el = box[0], g = gear[0];
                        let pos = null, drag = null, moved = !1;
                        const apply = (gx, gy) => {
                            const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight, S = g.offsetWidth || 36;
                            gx = Math.max(0, Math.min(gx, vw - S)), gy = Math.max(0, Math.min(gy, vh - S));
                            // with Hitomi Enhanced the gear never goes over its top bar (logo, search): minimum height = bar height + margin
                            hrOn() && (gy = Math.max(gy, hrTopBar()), gy = Math.min(gy, Math.max(0, vh - S)));
                            const left = gx + S / 2 < vw / 2, top = gy + S / 2 < vh / 2;
                            el.classList.toggle("dl-left", left), el.classList.toggle("dl-top", top),
                            el.style.left = left ? gx + "px" : "auto", el.style.right = left ? "auto" : vw - gx - S + "px",
                            el.style.top = top ? gy + "px" : "auto", el.style.bottom = top ? "auto" : vh - gy - S + "px";
                            // the settings panel must fit in the space left next to the gear (it used to be cut off at the bottom under Enhanced's top bar)
                            dl_options[0].style.maxHeight = Math.max(140, top ? vh - gy - S - 14 : gy - 14 - (hrOn() ? hrTopBar() : 0)) + "px";
                            return [ gx, gy ];
                        };
                        pos = apply(8, 8); // default: top-left corner
                        try {
                            const saved = JSON.parse(GM_getValue("gear_pos_v2", "null"));
                            Array.isArray(saved) && 2 === saved.length && (pos = apply(+saved[0], +saved[1]));
                        } catch (err) {}
                        setTimeout(() => pos && (pos = apply(pos[0], pos[1])), 800); // Enhanced's top bar may not exist yet at this point
                        g.addEventListener("pointerdown", ev => {
                            if (0 !== ev.button) return;
                            const r = g.getBoundingClientRect();
                            drag = { dx: ev.clientX - r.left, dy: ev.clientY - r.top, x0: ev.clientX, y0: ev.clientY }, moved = !1;
                            try {
                                g.setPointerCapture(ev.pointerId);
                            } catch (err) {}
                        }), g.addEventListener("pointermove", ev => {
                            if (!drag || !moved && Math.hypot(ev.clientX - drag.x0, ev.clientY - drag.y0) < 5) return;
                            moved = !0, pos = apply(ev.clientX - drag.dx, ev.clientY - drag.dy);
                        }), g.addEventListener("pointerup", () => {
                            drag && moved && pos && GM_setValue("gear_pos_v2", JSON.stringify(pos)), drag = null;
                        }), g.addEventListener("click", ev => {
                            // the click that ends a drag must not open/close the settings
                            moved && (ev.stopImmediatePropagation(), ev.preventDefault(), moved = !1);
                        }, !0), window.addEventListener("resize", () => {
                            pos && (pos = apply(pos[0], pos[1]));
                        });
                    }
                    // Close the panel when clicking outside of it (capture on window so the page can't swallow the event)
                    window.addEventListener("pointerdown", ev => {
                        if (dl_options.is(":hidden") || pg.mode) return;
                        if (ev.target.closest && ev.target.closest("#dl_gearbox, #dl_corner, #dl_fab, #dl_qpanel, #dl_selbar, #dl_pgbar")) return;
                        dl_options.css("display", "none"), tabSet("opts_open", "0");
                    }, !0);
                }
            // ---------- Queue: its own expandable panel (top-left) ----------
            {
                GM_addStyle(`
    #dl_qpanel { position: relative; margin: 6px 0 0 auto; z-index: 2147483000; box-sizing: border-box; width: 560px; max-width: calc(100vw - 16px); max-height: calc(100vh - 120px); overflow-y: auto; padding: 10px 14px; text-align: left; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 13px; line-height: 1.3; color: #26323a; background: #fff; border: 1px solid #e3e8ee; border-radius: 14px; box-shadow: 0 10px 34px rgba(0,0,0,.20); }
    #dl_qpanel:not(.dl-open) { width: fit-content; }
    #dl_qhead { display: flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; font-size: 10.5px; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; color: #c25b5b; }
    #dl_qhead .dl-arrow::before { content: "\\25B8"; display: inline-block; font-size: 12px; transition: transform .15s; }
    #dl_qpanel.dl-open #dl_qhead { padding-bottom: 4px; margin-bottom: 8px; border-bottom: 2px solid #ffcccc; }
    #dl_qpanel.dl-open #dl_qhead .dl-arrow::before { transform: rotate(90deg); }
    #dl_qpanel.dl-hidden { display: none; }
    #dl_qbody { display: none; }
    #dl_qpanel.dl-open #dl_qbody { display: block; }
    #dl_qpanel .dl-sec { margin: 0; }
    #dl_qpanel .dl-hint { font-size: 11px; color: #8a98a3; margin-top: 2px; }
    #dl_qpanel .dl-btngrid { display: grid; grid-template-columns: repeat(4, 1fr); grid-auto-rows: 42px; gap: 6px; margin: 6px 0; }
    #dl_qpanel .dl-btngrid button { width: 100% !important; min-width: 0 !important; height: auto !important; margin: 0 !important; padding: 2px 3px !important; box-sizing: border-box !important; white-space: normal !important; overflow: hidden; overflow-wrap: anywhere; font-family: inherit; font-size: 10.5px !important; font-weight: 600; line-height: 1.15 !important; color: #26323a; background: #f4f7f9; border: 1px solid #d5dde3; border-radius: 8px !important; cursor: pointer; transition: background .15s, border-color .15s, transform .05s; }
    #dl_qpanel .dl-btngrid button:hover:not(:disabled) { background: #fff0f0; border-color: #ffb3b3; }
    #dl_qpanel .dl-btngrid button:active:not(:disabled) { transform: scale(.97); }
    #dl_qpanel button:disabled { opacity: .45; cursor: default; }
    #dl_qpanel #dl_q_mode.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_qpanel #dl_q_start:not(:disabled) { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_qpanel #dl_q_start:hover:not(:disabled) { background: #ffb3b3; }
    #dl_qpanel #dl_q_pause.dl-on { background: #ffcccc; color: #4a1f1f; border-color: #ffb3b3; }
    #dl_qpanel .dl-qi span { font-size: 12px; }
    #dl_qpanel .dl-qsum { margin: 4px 0 2px; font-size: 11.5px; line-height: 1.35; color: #5b6b76; }
    #dl_q_list .dl-qi { flex-direction: column; align-items: stretch; gap: 3px; padding: 6px 0; }
    #dl_q_list .dl-qmain { display: flex; align-items: center; gap: 6px; }
    #dl_q_list .dl-qm { font-size: 10.5px; color: #8a98a3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    #dl_q_list .dl-qbar { height: 4px; border-radius: 2px; background: #eef2f5; overflow: hidden; }
    #dl_q_list .dl-qbar > i { display: block; height: 100%; width: 0; background: #ff9999; transition: width .2s; }
    #dl_q_list .dl-qerr .dl-qbar > i { background: #e57373; }
    #dl_q_list .dl-qerr .dl-qs { color: #c0392b; }
    #dl_q_list .dl-qrun .dl-qt { font-weight: 600; }
    `);
                const qPanel = $('<div id="dl_qpanel"><div id="dl_qhead" role="button" tabindex="0"><span class="dl-arrow"></span></div><div id="dl_qbody"></div></div>');
                const qSec = dl_options.find(".dl-sec").first(), qTitle = qSec.find(".dl-title").first();
                qPanel.find("#dl_qhead").append(qTitle.contents()), qTitle.remove(), qPanel.find("#dl_qbody").append(qSec);
                // Selection buttons: floating bar fixed at the bottom-right corner (list pages only)
                GM_addStyle(`
    #dl_selbar { position: fixed; right: 8px; bottom: 8px; margin: 0; z-index: 2147483000; display: flex; flex-direction: column; gap: 6px; width: 180px; box-sizing: border-box; }
    #dl_selbar button { width: 100%; min-height: 34px; padding: 5px 10px; box-sizing: border-box; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 12px; font-weight: 700; line-height: 1.2; color: #26323a; background: #fff; border: 2px solid #ffcccc; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.25); cursor: pointer; transition: background .15s, transform .1s; }
    #dl_selbar button:hover { background: #fff0f0; }
    #dl_selbar button:active { transform: scale(.96); }
    #dl_selbar button.dl-on { background: #ffcccc; color: #4a1f1f; }
    `);
                const selBar = $('<div id="dl_selbar"></div>');
                selBar.append(qSec.find("#dl_q_mode, #dl_q_page"), $('<button type="button" id="dl_q_unsel"></button>')), unsafeWindow.galleryinfo ? selBar.find("button").remove() : $("body").append(selBar); // list pages: floating at the bottom-right corner
                // List pages: hidden until right-click on the floating download button, then always expanded.
                // Gallery pages (no floating button): collapsible panel like before.
                const listPage = !0; // list and gallery pages: hidden until the "Queue" button (or right-click on Download) toggles it
                const setQOpen = on => {
                    qPanel.toggleClass("dl-open", on), listPage || tabSet("q_open", on ? "1" : "0");
                };
                const headAct = () => listPage ? qPanel.addClass("dl-hidden") : setQOpen(!qPanel.hasClass("dl-open"));
                qPanel.find("#dl_qhead").on("click", headAct).on("keydown", e => {
                    "Enter" !== e.key && " " !== e.key || (e.preventDefault(), headAct());
                }), setQOpen(listPage || "1" === tabGet("q_open", "0")), listPage && qPanel.addClass("dl-hidden"), $("#dl_corner").append(qPanel), initQueuePanel(dl_options.add(qPanel).add(selBar));
                new MutationObserver(() => updateFab()).observe(qPanel[0], { attributes: !0, attributeFilter: [ "class" ] }); // the queue buttons now live outside dl_options, so bind them through the union
                // Close when clicking outside of the panel (the floating button is excluded so right-click can toggle it)
                window.addEventListener("pointerdown", ev => {
                    if (listPage ? qPanel.hasClass("dl-hidden") : !qPanel.hasClass("dl-open")) return;
                    if (ev.target.closest && ev.target.closest("#dl_qpanel, #dl_fab, #dl_qbtn, #dl_selbar")) return;
                    listPage ? qPanel.addClass("dl-hidden") : setQOpen(!1);
                }, !0);
            }
            return applyLang(), panelEl = dl_options;
        }
        // ---------- Manual selection + download queue ----------
        // The queue / selection is kept per tab (sessionStorage), so another tab never shows or runs the works selected in this one
        function qLoad() {
            try {
                let raw;
                try {
                    raw = window.sessionStorage.getItem("dl_queue");
                } catch (err) {
                    raw = qLoad.mem;
                }
                const q = JSON.parse(raw || "[]");
                return Array.isArray(q) ? q : [];
            } catch (err) {
                return [];
            }
        }
        function qSave(q) {
            const v = JSON.stringify(q);
            qLoad.mem = v;
            try {
                window.sessionStorage.setItem("dl_queue", v);
            } catch (err) {}
        }
        // Per-tab UI state (sessionStorage): open panels and selection mode are independent between tabs. Settings (format, threads...) stay shared.
        function tabGet(key, def) {
            try {
                const v = window.sessionStorage.getItem("dl_" + key);
                if (null !== v) return v;
            } catch (err) {
                if (tabGet.mem && key in tabGet.mem) return tabGet.mem[key];
            }
            return def;
        }
        function tabSet(key, val) {
            (tabGet.mem = tabGet.mem || {})[key] = val;
            try {
                window.sessionStorage.setItem("dl_" + key, val);
            } catch (err) {}
        }
        // ---------- Download history (shared between tabs, kept between sessions) ----------
        function histLoad() {
            try {
                const h = JSON.parse(GM_getValue("dl_history", "{}"));
                return h && "object" == typeof h && !Array.isArray(h) ? h : {};
            } catch (err) {
                return {};
            }
        }
        function histAdd(id, title) {
            const h = histLoad();
            h[id] = { t: Date.now(), title: String(title || "").slice(0, 120) }, GM_setValue("dl_history", JSON.stringify(h)), renderHistory();
        }
        function histClear() {
            GM_setValue("dl_history", "{}"), renderHistory();
        }
        // Refresh everything that shows the history: marks on the list, count in the settings, button on the gallery page
        function renderHistory() {
            renderChecks();
            const el = document.getElementById("dl_hist_count");
            el && (el.textContent = Object.keys(histLoad()).length), updateFab();
        }
        function setStatus(id, text, info) {
            qStatus[id] = text, info && (qInfo[id] = Object.assign({}, qInfo[id], info));
            const row = document.querySelector('#dl_q_list [data-id="' + id + '"]'), it = qLoad().find(x => x.id === id);
            row && it && paintRow(row, it), renderSummary(), updateFab();
        }
        // Fill one queue row: title, progress, details line and progress bar
        function paintRow(row, it) {
            const info = qInfo[it.id] || {}, pct = info.total ? Math.round(info.done / info.total * 100) : 0;
            const t = row.querySelector(".dl-qt"), st = row.querySelector(".dl-qs"), meta = row.querySelector(".dl-qm"), bar = row.querySelector(".dl-qbar > i");
            t.textContent = t.title = info.title || it.title || it.id;
            st.textContent = "err" === info.state ? uiText("error") : info.total ? info.done + "/" + info.total + " \u00b7 " + pct + "%" : qStatus[it.id] || "";
            const parts = [ "#" + it.id ];
            info.artist && parts.push(info.artist), info.total && parts.push(info.total + " " + uiText("pagesWord")),
            parts.push(uiText("err" === info.state ? "stErr" : "run" === info.state ? runner.paused ? "stPause" : "stRun" : "stWait")), meta.textContent = parts.join(" \u00b7 "),
            bar.style.width = pct + "%", row.classList.toggle("dl-qerr", "err" === info.state), row.classList.toggle("dl-qrun", "run" === info.state);
        }
        function renderSummary() {
            const el = document.getElementById("dl_q_sum");
            if (!el) return;
            const q = qLoad(), failed = q.filter(it => qInfo[it.id] && "err" === qInfo[it.id].state).length, cur = q.find(it => qInfo[it.id] && "run" === qInfo[it.id].state);
            const bits = [ q.length + " " + uiText("sumInQueue"), qDone + " " + uiText("sumDone") ];
            failed && bits.push(failed + " " + uiText("sumFailed")), cur && bits.push(uiText(runner.paused ? "stPause" : "stRun") + ": " + (qInfo[cur.id].title || cur.title || cur.id)),
            el.textContent = bits.join(" \u00b7 ");
        }
        function renderChecks() {
            const ids = new Set(qLoad().map(x => x.id));
            const done = histLoad();
            document.querySelectorAll(".gallery-content > div[data-dl-id]").forEach(it => {
                it.classList.toggle("dl-selected", ids.has(it.dataset.dlId)), it.classList.toggle("dl-done", it.dataset.dlId in done);
                const g = it.querySelector(":scope > .dl-get");
                g && !g.classList.contains("dl-busy") && (g.title = (it.dataset.dlId in done ? uiText("histDoneOn") + " \u00b7 " : "") + uiText("getOne"));
            }), hrSync(), applySelectMode();
        }
        function renderQueue() {
            const q = qLoad(), list = document.getElementById("dl_q_list");
            const badge = document.getElementById("dl_badge");
            badge && (badge.textContent = q.length, badge.style.display = q.length ? "block" : "none");
            if (!list) return;
            list.textContent = "";
            for (const it of q) {
                const row = document.createElement("div"), main = document.createElement("div"), t = document.createElement("span"), st = document.createElement("span"), x = document.createElement("span");
                const meta = document.createElement("div"), bar = document.createElement("div"), fill = document.createElement("i");
                row.className = "dl-qi", row.dataset.id = it.id, main.className = "dl-qmain", t.className = "dl-qt", st.className = "dl-qs",
                x.className = "dl-qx", x.textContent = "\u2715", x.title = uiText("remove"), meta.className = "dl-qm", bar.className = "dl-qbar",
                x.addEventListener("click", () => {
                    qSave(qLoad().filter(y => y.id !== it.id)), renderChecks(), renderQueue();
                }), bar.append(fill), main.append(t, st, x), row.append(main, meta, bar), paintRow(row, it), list.append(row);
            }
            const count = document.getElementById("dl_q_count"), start = document.getElementById("dl_q_start"), stop = document.getElementById("dl_q_stop");
            count && (count.textContent = "(" + q.length + ")"), start && (start.disabled = runner.running || !q.length, start.textContent = uiText("crawl") + " " + q.length),
            stop && (stop.disabled = !runner.running);
            const pauseBtn = document.getElementById("dl_q_pause");
            pauseBtn && (pauseBtn.disabled = !runner.running, pauseBtn.textContent = uiText(runner.paused ? "resume" : "pause"), pauseBtn.classList.toggle("dl-on", runner.paused)),
            renderSummary(), updateFab();
        }
        // Add/remove galleries (a whole range when `items` has several) from the queue
        function setSelected(items, want) {
            let q = qLoad();
            for (const it of items) {
                const id = it.dataset.dlId;
                q = q.filter(x => x.id !== id), want && q.push({ id, title: it.dataset.dlTitle });
            }
            qSave(q), renderChecks(), renderQueue();
        }
        // Update a floating button in place. The icon / text nodes are only rebuilt when they really change:
        // replacing the button's children while the mouse is down (progress updates arrive many times per second)
        // made the browser drop the click, so the button sometimes needed several presses.
        function fabSet(btn, icon, text) {
            let sp = btn.querySelector(":scope > span");
            if (btn.dataset.ic !== icon || !sp || !btn.querySelector(":scope > svg")) {
                btn.textContent = "", btn.appendChild(dlIcon(icon)), sp = document.createElement("span"), btn.appendChild(sp), btn.dataset.ic = icon;
            }
            sp.textContent !== text && (sp.textContent = text);
        }
        // Floating button (bottom-left): starts / stops the queue without opening the panel
        function updateFab() {
            const fab = document.getElementById("dl_fab");
            if (!fab) return;
            if (unsafeWindow.galleryinfo) return updateGalleryFab(fab);
            const q = qLoad(), n = q.length, cur = runner.running ? q.find(it => qInfo[it.id] && "run" === qInfo[it.id].state) : null, ci = cur ? qInfo[cur.id] : null;
            const prog = ci && ci.total ? ci.done + "/" + ci.total : "", pct = ci && ci.total ? Math.round(ci.done / ci.total * 100) : 0;
            fab.classList.toggle("dl-run", runner.running),
            fabSet(fab, runner.running ? "x" : "dl", runner.running ? uiText(runner.paused ? "stPause" : "stop") + (prog ? " \u00b7 " + prog : "") : uiText("fabStart")), fab.style.setProperty("--p", pct + "%"), fab.removeAttribute("title"), fab.dataset.tip = uiText(runner.running ? "stop" : "fabStart") + " (" + n + ")";
            updateQbtn(n);
        }
        function updateQbtn(n) {
            const qb = document.getElementById("dl_qbtn");
            if (qb) {
                const qp = document.getElementById("dl_qpanel");
                fabSet(qb, "list", uiText("queue") + " \u00b7 " + n),
                qb.classList.toggle("dl-on", !!qp && !qp.classList.contains("dl-hidden"));
            }
        }
        // Gallery page: the "Download" button mirrors the state of the site's own (now hidden) Download button
        function updateGalleryFab(fab) {
            const h = document.querySelector("#dl-button > *"), txt = h ? h.textContent.trim() : "", run = /^Cancel/i.test(txt), m = /\((\d+)\)\s*$/.exec(txt);
            const pt = document.querySelector("#progressbar > span"), pm = pt && /(\d+)\s*\/\s*(\d+)/.exec(pt.textContent);
            const prog = run && pm ? pm[1] + "/" + pm[2] : "", pct = run && pm && +pm[2] ? Math.round(pm[1] / pm[2] * 100) : 0;
            const gid = String((unsafeWindow.galleryinfo || {}).id || unsafeWindow.galleryid || ""), hist = histLoad()[gid];
            fab.classList.toggle("dl-run", run), fab.classList.toggle("dl-done", !run && !!hist), fabSet(fab, run ? "x" : "dl", run ? uiText("stop") + (prog ? " \u00b7 " + prog : "") : uiText(hist ? "fabDone" : "fabStart") + (m ? " (" + m[1] + ")" : "")),
            fab.style.setProperty("--p", pct + "%"), fab.dataset.tip = "",
            !run && hist ? fab.title = uiText("histDoneOn") + " " + new Date(hist.t).toLocaleDateString() : fab.removeAttribute("title");
            updateQbtn(qLoad().length);
        }
        // Gallery page: same "Download" + "Queue" buttons as the list page, in the same top-right corner
        function installGalleryButtons() {
            if (document.getElementById("dl_fab")) return;
            const dlb = document.getElementById("dl-button");
            if (!dlb) return;
            fabStyles(), GM_addStyle("#dl_fab::after { display: none; }"), window.addEventListener("focus", () => renderHistory());
            const toggleQueue = ev => {
                ev.preventDefault(), ev.stopPropagation();
                const q = document.getElementById("dl_qpanel");
                q && q.classList.toggle("dl-hidden");
            };
            const fab = document.createElement("button");
            fab.type = "button", fab.id = "dl_fab", fab.addEventListener("click", ev => {
                ev.preventDefault(), ev.stopPropagation(), dlb.click(); // starts / cancels the download of this work (the site's own handler)
            }), fab.addEventListener("contextmenu", toggleQueue);
            const qb = document.createElement("button");
            qb.type = "button", qb.id = "dl_qbtn", qb.addEventListener("click", toggleQueue);
            const corner = document.getElementById("dl_corner");
            corner ? corner.prepend(fab) : document.body.appendChild(fab), fab.after(qb);
            const obs = new MutationObserver(() => updateFab()), opts = { childList: !0, subtree: !0, characterData: !0 };
            obs.observe(dlb, opts);
            const pbar = document.getElementById("progressbar");
            pbar && obs.observe(pbar, opts), updateFab();
        }
        // Gallery page: this download also shows up in the queue panel (title, progress). Like direct downloads on the list page,
        // it leaves the queue when it finishes (counted as done) or is cancelled; the queue run skips it while it is in progress.
        function galleryQueueStart(total) {
            const gi = unsafeWindow.galleryinfo || {}, id = String(gi.id || unsafeWindow.galleryid || "");
            if (!id) return;
            const title = String(gi.title || document.title || id), artist = gi.artists && gi.artists[0] && gi.artists[0].artist || "", q = qLoad(), added = !q.some(x => x.id === id);
            galleryQueueStart.cur = { id, added, title }, added && qSave(q.concat({ id, title })),
            qStatus[id] = "0/" + total, qInfo[id] = Object.assign({}, qInfo[id], { direct: !0, state: "run", title, artist, total, done: 0 }), renderQueue();
        }
        function galleryQueueProgress(done, total) {
            const c = galleryQueueStart.cur;
            c && setStatus(c.id, done + "/" + total, { state: "run", done, total });
        }
        function galleryQueueEnd(ok) {
            const c = galleryQueueStart.cur;
            if (!c) return;
            galleryQueueStart.cur = null, (ok || c.added) && qSave(qLoad().filter(x => x.id !== c.id)),
            delete qStatus[c.id], delete qInfo[c.id], ok && (qDone++, histAdd(c.id, c.title)), renderQueue();
        }
        // Small message at the bottom of the window
        let toastTimer = 0;
        function showToast(text) {
            let el = document.getElementById("dl_toast");
            el || (el = document.createElement("div"), el.id = "dl_toast",
            el.style.cssText = "position:fixed;left:50%;bottom:28px;transform:translateX(-50%);z-index:2147483600;max-width:min(460px,calc(100vw - 32px));box-sizing:border-box;padding:10px 16px;border-radius:10px;background:rgba(38,50,58,.96);color:#fff;font:600 13px/1.35 system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center;box-shadow:0 6px 22px rgba(0,0,0,.35);pointer-events:none;transition:opacity .2s;",
            document.body.appendChild(el), hrHold()), el.textContent = text, el.style.opacity = "1", clearTimeout(toastTimer),
            toastTimer = setTimeout(() => {
                el.style.opacity = "0";
            }, 3e3);
        }
        function installFab() {
            if (document.getElementById("dl_fab")) return;
            const fab = document.createElement("button");
            fab.type = "button", fab.id = "dl_fab", fab.addEventListener("contextmenu", ev => {
                ev.preventDefault(), ev.stopPropagation();
                const q = document.getElementById("dl_qpanel");
                q && q.classList.toggle("dl-hidden");
            }), fab.addEventListener("click", ev => {
                ev.preventDefault(), ev.stopPropagation(), runner.running ? stopQueue() : qLoad().length ? runQueue() : showToast(uiText("emptyQueue"));
            }), (() => {
                const corner = document.getElementById("dl_corner");
                corner ? corner.prepend(fab) : document.body.appendChild(fab);
                const qb = document.createElement("button");
                qb.type = "button", qb.id = "dl_qbtn", qb.addEventListener("click", ev => {
                    ev.preventDefault(), ev.stopPropagation();
                    const q = document.getElementById("dl_qpanel");
                    q && q.classList.toggle("dl-hidden");
                }), fab.after(qb);
            })(), updateFab();
        }
        // Icons for the per-work download button (built with DOM calls, no innerHTML)
        function dlIcon(kind) {
            const NS = "http://www.w3.org/2000/svg", svg = document.createElementNS(NS, "svg");
            svg.setAttribute("viewBox", "0 0 24 24"), svg.setAttribute("fill", "none"), svg.setAttribute("stroke", "currentColor"),
            svg.setAttribute("stroke-width", "2.4"), svg.setAttribute("stroke-linecap", "round"), svg.setAttribute("stroke-linejoin", "round");
            const paths = "ok" === kind ? [ "M5 12.5l4.5 4.5L19 7.5" ] : "x" === kind ? [ "M6 6l12 12", "M18 6L6 18" ] : "grid" === kind ? [ "M4 4h6v6H4z", "M14 4h6v6h-6z", "M4 14h6v6H4z", "M14 14h6v6h-6z" ] : "list" === kind ? [ "M8 6h12", "M8 12h12", "M8 18h12", "M4 6h.01", "M4 12h.01", "M4 18h.01" ] : [ "M12 4v11", "M7.5 10.5L12 15l4.5-4.5", "M5 20h14" ];
            for (const d of paths) {
                const p = document.createElementNS(NS, "path");
                p.setAttribute("d", d), svg.appendChild(p);
            }
            return svg;
        }
        function dlSetContent(btn, txt) {
            btn.textContent = "";
            if ("\u2193" === txt) btn.appendChild(dlIcon("dl")); else if ("\u2713" === txt) btn.appendChild(dlIcon("ok")); else if (0 === txt.indexOf("\u2715")) {
                btn.appendChild(dlIcon("x"));
                const rest = txt.slice(1).trim();
                if (rest) {
                    const t = document.createElement("span");
                    t.textContent = rest, btn.appendChild(t);
                }
            } else btn.textContent = txt;
        }
        // Put a selection square on every gallery of the current list
        function decorateItems() {
            document.querySelectorAll(".gallery-content > div").forEach(item => {
                if (item.querySelector(":scope > .dl-pick")) return;
                const a = item.querySelector("a.lillie, h1.lillie a"), m = a && (a.dataset.hrInfo || a.href).match(/(?:-|\/)([0-9]+)\.html/);
                if (!m) return;
                item.dataset.dlId = m[1], item.dataset.dlTitle = (a.textContent || "").trim(),
                "static" === getComputedStyle(item).position && (item.style.position = "relative");
                const pick = document.createElement("span");
                pick.className = "dl-pick", pick.title = uiText("pick"),
                item.appendChild(pick);
                const get = document.createElement("span");
                get.className = "dl-get", get.title = uiText("getOne"), dlSetContent(get, "\u2193"),
                item.appendChild(get);
            }), renderChecks();
        }
        // Download a single gallery right away (button in the bottom corner). Clicking it again while it runs cancels the download.
        async function downloadOne(item) {
            const btn = item.querySelector(":scope > .dl-get");
            if (!btn) return;
            const paint = (txt, cls) => {
                dlSetContent(btn, txt), btn.classList.remove("dl-busy", "dl-ok", "dl-err"), cls && btn.classList.add(cls),
                btn.title = uiText("dl-busy" === cls ? "cancelOne" : "getOne");
            };
            if (btn._dlCtl) {
                // already downloading: cancel
                const old = btn._dlCtl;
                btn._dlCtl = null, old.cancelled = !0;
                for (const x of [ ...old.xhrs ]) x.abort();
                old.added && qSave(qLoad().filter(y => y.id !== item.dataset.dlId)), delete qStatus[item.dataset.dlId], delete qInfo[item.dataset.dlId], renderChecks(), renderQueue();
                paint("\u2193", "");
                return;
            }
            const id = item.dataset.dlId, ctl = { running: !0, cancelled: !1, xhrs: new Set, added: !1 };
            btn._dlCtl = ctl;
            // Show this download in the queue panel too (progress, title, status); the queue run skips it
            qLoad().some(x => x.id === id) || (ctl.added = !0, qSave(qLoad().concat({ id, title: item.dataset.dlTitle }))),
            qInfo[id] = Object.assign({}, qInfo[id], { direct: !0, state: "run" }), renderChecks(), renderQueue();
            const setBtn = (txt, cls) => {
                btn._dlCtl === ctl && paint(txt, cls);
            };
            paint("\u2715", "dl-busy");
            try {
                if (wantsDirPicker()) try {
                    await ensureBaseDir();
                } catch (err) {
                    console.warn("[download] no folder chosen, using normal downloads:", err);
                }
                if (ctl.cancelled) return;
                await ensureGg();
                const gi = await fetchGalleryInfo(id);
                ctl.cancelled || setStatus(id, uiText("starting"), { state: "run", title: gi.title, artist: gi.artists && gi.artists[0] && gi.artists[0].artist || "", total: (gi.files || []).length, done: 0 });
                if (ctl.cancelled) return;
                const dir = wantsDirPicker() ? await dirForGallery(gi) : null;
                const name = String(gi.title || item.dataset.dlTitle || id).replace(/[\\/:*?"<>|]+/g, "_").replace(/[. ]+$/, "").trim().slice(0, 150) || id;
                await downloadGalleryInfo(gi, name, dir, (d, t) => (setBtn("\u2715 " + d + "/" + t, "dl-busy"), ctl.cancelled || setStatus(id, d + "/" + t, { state: "run", done: d, total: t })), ctl);
                if (ctl.cancelled) return;
                btn._dlCtl = null, qSave(qLoad().filter(x => x.id !== id)), delete qStatus[id], delete qInfo[id], qDone++, histAdd(id, gi.title || item.dataset.dlTitle), renderChecks(), renderQueue(), paint("\u2713", "dl-ok");
            } catch (err) {
                if (ctl.cancelled) return;
                console.warn("[download] failed:", id, err), setStatus(id, uiText("error"), { state: "err", direct: !1 }), btn._dlCtl = null, paint("!", "dl-err");
            }
            setTimeout(() => {
                btn._dlCtl || paint("\u2193", "");
            }, 3e3);
        }
        async function runQueue() {
            if (runner.running) return;
            runner.running = !0, runner.cancelled = !1, runner.paused = !1, qFailed.clear(), Object.keys(qInfo).forEach(k => qInfo[k].direct || delete qInfo[k]), renderQueue();
            try {
                if (wantsDirPicker()) try {
                    await ensureBaseDir();
                } catch (err) {
                    console.warn("[queue] no folder chosen, using normal downloads:", err);
                }
                for (;;) {
                    const item = qLoad().find(it => !qFailed.has(it.id) && !(qInfo[it.id] && qInfo[it.id].direct));
                    if (!item || runner.cancelled) break;
                    try {
                        setStatus(item.id, uiText("starting"), { state: "run" });
                        await ensureGg();
                        const gi = await fetchGalleryInfo(item.id);
                        setStatus(item.id, uiText("starting"), { state: "run", title: gi.title, artist: gi.artists && gi.artists[0] && gi.artists[0].artist || "", total: (gi.files || []).length, done: 0 });
                        const dir = wantsDirPicker() ? await dirForGallery(gi) : null;
                        const name = String(gi.title || item.title || item.id).replace(/[\\/:*?"<>|]+/g, "_").replace(/[. ]+$/, "").trim().slice(0, 150) || item.id;
                        await downloadGalleryInfo(gi, name, dir, (d, t) => setStatus(item.id, d + "/" + t, { state: "run", done: d, total: t }), runner);
                        qSave(qLoad().filter(x => x.id !== item.id)), delete qStatus[item.id], delete qInfo[item.id], qDone++, histAdd(item.id, gi.title || item.title), renderChecks();
                    } catch (err) {
                        if (runner.cancelled) break;
                        console.warn("[queue] failed:", item.id, err), qFailed.add(item.id), setStatus(item.id, uiText("error"), { state: "err" });
                    }
                    renderQueue();
                }
            } finally {
                runner.running = !1, runner.paused = !1, runner.xhrs.clear(), Object.keys(qInfo).forEach(k => {
                    "run" === qInfo[k].state && !qInfo[k].direct && (delete qInfo[k], delete qStatus[k]);
                }), renderQueue();
            }
        }
        function togglePause() {
            runner.running && (runner.paused = !runner.paused, renderQueue());
        }
        function stopQueue() {
            runner.cancelled = !0, runner.paused = !1;
            for (const x of [ ...runner.xhrs ]) x.abort();
        }
        function initQueuePanel(root) {
            root.find("#dl_pg_mode").on("click", () => setPgMode(!pg.mode)), root.find("#dl_pg_all").on("click", () => pgSet("all")),
            root.find("#dl_pg_none").on("click", () => pgSet("none")), root.find("#dl_pg_inv").on("click", () => pgSet("invert"));
            root.find("#dl_lang").on("change", e => {
                GM_setValue("ui_lang", e.target.value), applyLang();
            });
            root.find("#dl_q_mode").on("click", () => {
                setSelectMode(!selectMode);
            }), root.find("#dl_q_start").on("click", () => {
                runQueue();
            }), root.find("#dl_q_unsel").on("click", () => {
                qSave(qLoad().filter(it => qInfo[it.id] && "run" === qInfo[it.id].state)), renderChecks(), renderQueue();
            }), root.find("#dl_q_stop").on("click", stopQueue), root.find("#dl_q_pause").on("click", togglePause), root.find("#dl_q_clear").on("click", () => {
                runner.running && stopQueue(), qSave([]), qDone = 0, renderChecks(), renderQueue();
            }), root.find("#dl_q_page").on("click", () => {
                setSelectMode(!0);
                const items = hrShownItems();
                if (!items.length) return;
                setSelected(items, !0);
            }), renderQueue(), applySelectMode();
        }
        function uiLang() {
            return "en" === GM_getValue("ui_lang", "es") ? "en" : "es";
        }
        function uiText(key) {
            const d = I18N[uiLang()];
            return key in d ? d[key] : I18N.en[key];
        }
        // Re-translate everything in the panel (and the squares on the list)
        function applyLang() {
            document.dispatchEvent(new Event("hr-lang"));
            document.querySelectorAll("[data-i18n]").forEach(e => e.textContent = uiText(e.dataset.i18n));
            document.querySelectorAll("[data-i18n-title]").forEach(e => e.title = uiText(e.dataset.i18nTitle));
            document.querySelectorAll(".dl-pick").forEach(e => e.title = uiText("pick"));
            document.querySelectorAll(".dl-get:not(.dl-busy)").forEach(e => e.title = uiText("getOne"));
            const pb = document.getElementById("dl_subdir_pick");
            pb && (pb.textContent = baseDir ? uiText("folderPrefix") + baseDir.name : uiText("chooseFolder"));
            const sel = document.getElementById("dl_lang");
            sel && (sel.value = uiLang()), applySelectMode(), renderQueue(), pgRefresh();
        }
        // "Clear selection (N)" shows up while there is something selected
        function updateSelAll() {
            const b = document.getElementById("dl_q_page");
            if (!b) return;
            b.textContent = uiText("selectAll");
            const u = document.getElementById("dl_q_unsel"), n = qLoad().filter(it => !(qInfo[it.id] && "run" === qInfo[it.id].state)).length;
            u && (u.textContent = uiText("unselectAll") + " (" + n + ")", u.classList.toggle("dl-has", n > 0));
        }
        function applySelectMode() {
            document.body && document.body.classList.toggle("dl-selmode", selectMode);
            const b = document.getElementById("dl_q_mode");
            b && (b.classList.toggle("dl-on", selectMode), b.textContent = uiText(selectMode ? "modeOn" : "modeOff") + (selectMode && qLoad().length ? " \u00b7 " + qLoad().length : ""));
            updateSelAll();
        }
        function setSelectMode(on) {
            selectMode = !!on, tabSet("select_mode", on ? "1" : "0"), applySelectMode();
        }
        function togglePick(item, shiftKey) {
            const items = hrShownItems(), idx = items.indexOf(item);
            const want = !qLoad().some(x => x.id === item.dataset.dlId);
            let from = idx, to = idx;
            shiftKey && lastPick >= 0 && lastPick < items.length && (from = Math.min(lastPick, idx), to = Math.max(lastPick, idx));
            setSelected(items.slice(from, to + 1), want), lastPick = idx;
        }
        // Returns the selection square under the pointer, even if another element covers it
        function getUnderPointer(ev) {
            if (ev.target.closest && ev.target.closest("#dl_gearbox, #dl_corner, #dl_fab, #dl_qpanel, #dl_selbar, #dl_pgbar")) return null;
            for (const g of document.querySelectorAll(".dl-get")) {
                const r = g.getBoundingClientRect();
                if (r.width && ev.clientX >= r.left && ev.clientX <= r.right && ev.clientY >= r.top && ev.clientY <= r.bottom) return g;
            }
            return null;
        }
        function pickUnderPointer(ev) {
            if (ev.target.closest && ev.target.closest("#dl_gearbox, #dl_corner, #dl_fab, #dl_qpanel, #dl_selbar, #dl_pgbar")) return null;
            if (getUnderPointer(ev)) return null;
            if (selectMode && ev.target.closest) {
                const it = ev.target.closest(".gallery-content > div[data-dl-id]");
                if (it) return it.querySelector(":scope > .dl-pick");
                const hc = ev.target.closest(".hr-card"); // card drawn by Hitomi Enhanced
                if (hc && hc._dlItem) return hc._dlItem.querySelector(":scope > .dl-pick");
            }
            const M = 12; // extra hit margin (px) around the square so a near miss still selects
            for (const p of document.querySelectorAll(".dl-pick")) {
                const r = p.getBoundingClientRect();
                if (r.width && ev.clientX >= r.left - M && ev.clientX <= r.right + M && ev.clientY >= r.top - M && ev.clientY <= r.bottom + M) return p;
            }
            return null;
        }
        function installPickGuard() {
            if (pickGuardInstalled) return;
            pickGuardInstalled = true;
            // Block any site handler for events over the square
            ["mousedown", "mouseup", "pointerdown", "pointerup", "auxclick", "dblclick"].forEach(type => {
                window.addEventListener(type, ev => {
                    if (!pickUnderPointer(ev) && !getUnderPointer(ev)) return;
                    ev.preventDefault(), ev.stopImmediatePropagation();
                }, true);
            });
            // The click selects and never lets the gallery open
            window.addEventListener("click", ev => {
                const g = getUnderPointer(ev);
                if (g) {
                    ev.preventDefault(), ev.stopImmediatePropagation(), downloadOne(g._dlItem || g.parentElement);
                    return;
                }
                const p = pickUnderPointer(ev);
                if (!p) return;
                ev.preventDefault(), ev.stopImmediatePropagation();
                togglePick(p._dlItem || p.parentElement, ev.shiftKey);
            }, true);
        }
        // ---------- Compatibility with "Hitomi Enhanced" (userscript that redraws lists, gallery pages and the reader) ----------
        // Enhanced hides every element of the page and draws its own cards. The selection squares, the download buttons and the
        // floating panels of this script are moved / mirrored so they keep working on top of that interface.
        function hrTopBar() {
            const t = document.querySelector("#hr-app .hr-top");
            return (t ? Math.ceil(t.getBoundingClientRect().height) : 64) + 8;
        }
        const hrOn = () => document.documentElement.classList.contains("hr-ui");
        // works that are really on screen (Enhanced can hide blacklisted ones)
        function hrShownItems() {
            const all = [ ...document.querySelectorAll(".gallery-content > div[data-dl-id]") ];
            if (!hrOn()) return all;
            const shown = new Set([ ...document.querySelectorAll("#hr-app .hr-card") ].map(c => c._dlItem).filter(Boolean));
            return all.filter(it => shown.has(it));
        }
        // copy the state of the original squares / buttons to the ones drawn over Enhanced's cards
        function hrSync() {
            if (!hrOn()) return;
            document.querySelectorAll("#hr-app .hr-card").forEach(card => {
                const it = card._dlItem;
                if (!it) return;
                for (const c of [ "dl-selected", "dl-done" ]) {
                    const want = it.classList.contains(c);
                    card.classList.contains(c) !== want && card.classList.toggle(c, want);
                }
                const og = it.querySelector(":scope > .dl-get"), g = card.querySelector(".dl-get.dl-hx");
                if (!og || !g) return;
                const cls = og.className + " dl-hx";
                g.className !== cls && (g.className = cls), g.title !== og.title && (g.title = og.title), g.innerHTML !== og.innerHTML && (g.innerHTML = og.innerHTML);
            });
            const h = document.querySelector("#dl-button h1"), s = document.querySelector("#hr-app .dl-hbtn > span");
            if (s) {
                const raw = (h ? h.textContent : "Download").trim() || "Download", t = /^Cancel/i.test(raw) ? uiText("cancelOne") : raw.replace(/^Download/, uiText("fabStart"));
                s.textContent !== t && (s.textContent = t);
            }
        }
        // Enhanced hides / re-colors every element of <body> whose id does not start with "hr-" (and everything inside such elements is left alone).
        // The floating elements of this script (ids "dl_...") are therefore kept inside #hr-dl whenever Enhanced is active.
        const hrPresent = () => /\bhr-(?:ui|ct|rv)\b/.test(document.documentElement.className);
        let hrHolder = null;
        function hrHold() {
            if (!document.body || !hrPresent()) return;
            hrHolder || (hrHolder = document.getElementById("hr-dl") || Object.assign(document.createElement("div"), { id: "hr-dl" })),
            hrHolder.parentNode || document.body.appendChild(hrHolder);
            for (const n of [ ...document.body.children ]) n !== hrHolder && /^dl_/.test(n.id) && hrHolder.appendChild(n);
        }
        let hrInstalled = !1;
        function installRevampBridge() {
            if (hrInstalled) return;
            hrInstalled = !0;
            GM_addStyle(`
    /* position / selection look of the squares over Enhanced's cards */
    .hr-cover > .dl-hx { position: absolute; top: 8px; box-sizing: border-box; cursor: pointer; z-index: 20; opacity: .8; }
    .hr-cover > .dl-pick.dl-hx { left: 8px; width: 24px; height: 24px; border: 2px solid #fff; border-radius: 5px; background: rgba(0,0,0,.55); }
    .hr-cover > .dl-pick.dl-hx::before { content: ""; position: absolute; inset: -12px; }
    .hr-card:hover .hr-cover > .dl-hx, .hr-card.dl-selected .hr-cover > .dl-pick.dl-hx { opacity: 1; }
    .hr-card.dl-selected .hr-cover > .dl-pick.dl-hx { background: #ffcccc; border-color: #ffcccc; }
    .hr-card.dl-selected .hr-cover > .dl-pick.dl-hx::after { content: "\\2713"; display: block; color: #000; font: bold 16px/20px sans-serif; text-align: center; }
    .hr-card.dl-selected .hr-cover { outline: 2px solid #ffcccc; outline-offset: -2px; }
    .hr-cover > .dl-get.dl-hx { right: 8px; min-width: 38px; height: 28px; padding: 0 9px; border: 2px solid #fff; border-radius: 8px; background: rgba(0,0,0,.6); color: #fff; font: bold 18px/24px sans-serif; text-align: center; white-space: nowrap; display: flex; align-items: center; justify-content: center; gap: 4px; }
    .hr-cover > .dl-get.dl-hx svg { display: block; width: 18px; height: 18px; flex: none; }
    .hr-cover > .dl-get.dl-hx.dl-busy svg { width: 12px; height: 12px; }
    .hr-cover > .dl-get.dl-hx:hover, .hr-cover > .dl-get.dl-hx.dl-busy { background: #ffcccc; border-color: #ffcccc; color: #4a1f1f; opacity: 1; font: bold 12px/24px sans-serif; }
    .hr-card.dl-done .hr-cover > .dl-get.dl-hx:not(.dl-busy):not(.dl-err) { opacity: 1; background: #a5d6a7; border-color: #a5d6a7; color: #1b3a1d; }
    .hr-cover > .dl-get.dl-hx.dl-ok { background: #a5d6a7; border-color: #a5d6a7; color: #1b3a1d; opacity: 1; }
    .hr-cover > .dl-get.dl-hx.dl-err { background: #e57373; border-color: #e57373; color: #fff; opacity: 1; }
    body.dl-selmode .hr-card, body.dl-selmode .hr-card a { cursor: pointer; -webkit-user-select: none !important; user-select: none !important; }
    /* page selection over Enhanced's thumbnails */
    body.dl-pgmode .hr-thumb { cursor: pointer; -webkit-user-select: none !important; user-select: none !important; }
    .hr-thumb > .dl-pgchk { display: none; position: absolute; top: 4px; left: 4px; bottom: auto; padding: 0; width: 22px; height: 22px; box-sizing: border-box; border: 2px solid #fff; border-radius: 5px; background: rgba(0,0,0,.55); z-index: 5; }
    body.dl-pgmode .hr-thumb > .dl-pgchk { display: block; }
    .hr-thumb.dl-pgsel > .dl-pgchk { background: #ffcccc; border-color: #ffcccc; }
    .hr-thumb.dl-pgsel > .dl-pgchk::after { content: "\\2713"; display: block; color: #000; font: bold 15px/18px sans-serif; text-align: center; }
    body.dl-pgmode .hr-thumb.dl-pgsel { outline: 2px solid #ffcccc; outline-offset: -2px; }
    /* the top-right buttons must not cover Enhanced's search bar */
    html.hr-ui #dl_corner { top: 72px !important; }
    /* Enhanced's classic theme forces a text color on every span: keep the colors of the per-work button readable */
    html.hr-ct:not(.hr-ui) .gallery-content > div > .dl-get { color: #fff !important; }
    html.hr-ct:not(.hr-ui) .gallery-content > div > .dl-get:hover, html.hr-ct:not(.hr-ui) .gallery-content > div > .dl-get.dl-busy { color: #4a1f1f !important; }
    html.hr-ct:not(.hr-ui) .gallery-content > div.dl-done > .dl-get:not(.dl-busy):not(.dl-err), html.hr-ct:not(.hr-ui) .gallery-content > div > .dl-get.dl-ok { color: #1b3a1d !important; }
    html.hr-ct:not(.hr-ui) .gallery-content > div > .dl-get.dl-err { color: #fff !important; }
    `);
            GM_addStyle(`
    /* ---- Theme sync: panels and buttons follow Enhanced's theme and accent color (its --hr-* variables) ---- */
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_qpanel, #dl_pgbar) { background: var(--hr-surface) !important; color: var(--hr-text) !important; border-color: var(--hr-border) !important; box-shadow: 0 10px 34px var(--hr-shadow) !important; color-scheme: var(--hr-scheme); font-family: var(--hr-font), system-ui, sans-serif !important; }
    html:is(.hr-ui, .hr-ct) #dl_pg_sec { color: var(--hr-text); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_qpanel, #dl_pgbar, #dl_pg_sec) label { color: var(--hr-text); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_qpanel, #dl_pgbar, #dl_pg_sec) :is(.dl-lbl, .dl-hint, .dl-qsum), html:is(.hr-ui, .hr-ct) #dl_q_list .dl-qm { color: var(--hr-muted); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_pgbar, #dl_pg_sec) .dl-title, html:is(.hr-ui, .hr-ct) #dl_qhead, html:is(.hr-ui, .hr-ct) #dl_pg_count { color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_pgbar, #dl_pg_sec) .dl-title, html:is(.hr-ui, .hr-ct) #dl_qpanel.dl-open #dl_qhead { border-bottom-color: color-mix(in srgb, var(--hr-accent) 35%, transparent); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_pg_sec, #dl_pgbar) :is(input[type="text"], input[type="number"], select) { background: var(--hr-surface2); color: var(--hr-text); border-color: var(--hr-border); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_pg_sec, #dl_pgbar) :is(input[type="text"], input[type="number"], select):focus { background: var(--hr-surface2); border-color: var(--hr-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--hr-accent) 30%, transparent); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_pg_sec, #dl_pgbar) :is(input[type="radio"], input[type="checkbox"], input[type="range"]) { accent-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_qpanel, #dl_pgbar, #dl_pg_sec) button { background: var(--hr-surface2); color: var(--hr-text); border-color: var(--hr-border); }
    html:is(.hr-ui, .hr-ct) :is(#dl_options, #dl_qpanel, #dl_pgbar, #dl_pg_sec) button:hover:not(:disabled) { background: color-mix(in srgb, var(--hr-text) 12%, var(--hr-surface2)); border-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) #dl_q_mode.dl-on, html:is(.hr-ui, .hr-ct) #dl_pg_mode.dl-on, html:is(.hr-ui, .hr-ct) #dl_q_pause.dl-on, html:is(.hr-ui, .hr-ct) #dl_q_start:not(:disabled) { background: var(--hr-accent) !important; border-color: var(--hr-accent) !important; color: #fff !important; }
    html:is(.hr-ui, .hr-ct) #dl_q_start:hover:not(:disabled) { background: color-mix(in srgb, var(--hr-accent) 85%, #fff) !important; }
    html:is(.hr-ui, .hr-ct) #dl_gear { background: var(--hr-surface) !important; color: var(--hr-text) !important; border-color: var(--hr-border) !important; }
    html:is(.hr-ui, .hr-ct) #dl_gear:hover { background: var(--hr-surface2) !important; }
    html:is(.hr-ui, .hr-ct) #dl_badge { background: var(--hr-accent); color: #fff; }
    html:is(.hr-ui, .hr-ct) #dl_fab { background: var(--hr-accent); color: #fff; border-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) #dl_fab:hover { background: color-mix(in srgb, var(--hr-accent) 85%, #fff); }
    html:is(.hr-ui, .hr-ct) #dl_fab.dl-done { background: #a5d6a7; border-color: #a5d6a7; color: #1b3a1d; }
    html:is(.hr-ui, .hr-ct) #dl_fab.dl-done:hover { background: #8fcb93; }
    html:is(.hr-ui, .hr-ct) #dl_fab.dl-run { background: linear-gradient(90deg, var(--hr-accent) var(--p, 0%), var(--hr-surface2) var(--p, 0%)); color: var(--hr-text); border-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) :is(#dl_qbtn, #dl_pgbtn, #dl_selbar button) { background: var(--hr-surface); color: var(--hr-text); border-color: var(--hr-border); }
    html:is(.hr-ui, .hr-ct) :is(#dl_qbtn, #dl_pgbtn, #dl_selbar button):hover { background: var(--hr-surface2); border-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) #dl_pgbtn.dl-on, html:is(.hr-ui, .hr-ct) #dl_qbtn.dl-on, html:is(.hr-ui, .hr-ct) #dl_selbar button.dl-on { background: var(--hr-accent); color: #fff; border-color: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) #dl_q_list .dl-qi { border-bottom-color: var(--hr-border); }
    html:is(.hr-ui, .hr-ct) #dl_q_list .dl-qbar { background: var(--hr-surface2); }
    html:is(.hr-ui, .hr-ct) #dl_q_list .dl-qbar > i { background: var(--hr-accent); }
    html:is(.hr-ui, .hr-ct) #dl_q_list .dl-qerr .dl-qbar > i { background: #e57373; }
    html:is(.hr-ui, .hr-ct) #dl_options .dl-tag { background: var(--hr-surface2); border-color: var(--hr-border); color: var(--hr-text); }
    html:is(.hr-ui, .hr-ct) #dl_options .dl-tag:hover { background: color-mix(in srgb, var(--hr-text) 12%, var(--hr-surface2)); border-color: var(--hr-accent); }
    html.hr-ui .hr-card.dl-selected .hr-cover { outline-color: var(--hr-accent); }
    html.hr-ui .hr-card.dl-selected .hr-cover > .dl-pick.dl-hx { background: var(--hr-accent); border-color: var(--hr-accent); }
    html.hr-ui .hr-card.dl-selected .hr-cover > .dl-pick.dl-hx::after { color: #fff; }
    html.hr-ui .hr-card:not(.dl-done) .hr-cover > .dl-get.dl-hx:hover:not(.dl-ok):not(.dl-err), html.hr-ui .hr-cover > .dl-get.dl-hx.dl-busy { background: var(--hr-accent); border-color: var(--hr-accent); color: #fff; }
    html.hr-ui .hr-thumb.dl-pgsel > .dl-pgchk { background: var(--hr-accent); border-color: var(--hr-accent); }
    html.hr-ui .hr-thumb.dl-pgsel > .dl-pgchk::after { color: #fff; }
    html.hr-ui body.dl-pgmode .hr-thumb.dl-pgsel { outline-color: var(--hr-accent); }
    `);
            // squares + download button over Enhanced's cards / gallery page
            const watched = new WeakSet;
            const mark = () => document.documentElement.classList.toggle("dl-hr", hrPresent() || !!document.querySelector("#hr-fab, #hr-app, #hr-navgear, #hr-panel"));
            const decorate = () => {
                mark(), hrHold();
                if (!hrOn()) return;
                const byId = new Map;
                document.querySelectorAll(".gallery-content > div[data-dl-id]").forEach(it => byId.set(it.dataset.dlId, it));
                document.querySelectorAll("#hr-app .hr-card:not(.hr-skel)").forEach(card => {
                    const cover = card.querySelector(".hr-cover");
                    if (!cover || card._dlItem && card._dlItem.isConnected && cover.querySelector(":scope > .dl-hx")) return;
                    const a = card.querySelector("a.hr-title") || card.querySelector("a[href]"), m = a && (a.dataset.hrInfo || a.href).match(/(?:-|\/)([0-9]+)\.html/);
                    const it = m && byId.get(m[1]);
                    if (!it) return;
                    card._dlItem = it, cover.querySelectorAll(":scope > .dl-hx").forEach(x => x.remove());
                    const pick = document.createElement("span"), get = document.createElement("span");
                    pick.className = "dl-pick dl-hx", pick.title = uiText("pick"), pick._dlItem = it,
                    get.className = "dl-get dl-hx", get.title = uiText("getOne"), get._dlItem = it, cover.append(pick, get);
                });
                const orig = document.getElementById("dl-button");
                // follow the original squares / buttons (selection, progress, done...)
                for (const t of [ document.querySelector(".gallery-content"), orig ]) t && !watched.has(t) && (watched.add(t), new MutationObserver(() => hrSync()).observe(t, { attributes: !0, childList: !0, subtree: !0, characterData: !0 }));
                hrSync();
            };
            let timer = 0;
            const later = () => {
                clearTimeout(timer), timer = setTimeout(decorate, 120);
            };
            new MutationObserver(later).observe(document.documentElement, { childList: !0, subtree: !0 }), later();
        }
        // ---------- Choose which pages of a gallery are downloaded ----------
        function pgFilter(arr) {
            return pg.sel.size ? arr.filter((_, i) => pg.sel.has(i)) : arr;
        }
        function pgTotal() {
            return unsafeWindow.galleryinfo && unsafeWindow.galleryinfo.files ? unsafeWindow.galleryinfo.files.length : 0;
        }
        // Site's download button shows how many pages will be downloaded
        function pgUpdateLabel() {
            const h = document.querySelector("#dl-button h1");
            h && /^Download( \(\d+\))?$/.test(h.textContent.trim()) && (h.textContent = pg.sel.size ? "Download (" + pg.sel.size + ")" : "Download");
        }
        function pgRefresh() {
            document.querySelectorAll(".thumbnail-container[data-dl-pg], .hr-thumb[data-dl-pg]").forEach(c => c.classList.toggle("dl-pgsel", pg.sel.has(+c.dataset.dlPg)));
            const cnt = document.getElementById("dl_pg_count"), b = document.getElementById("dl_pg_mode");
            cnt && (cnt.textContent = uiText("pgCount") + ": " + pg.sel.size + " / " + pgTotal()),
            b && (b.classList.toggle("dl-on", pg.mode), b.textContent = uiText(pg.mode ? "pgModeOn" : "pgMode")), pgUpdateLabel(), pgBtnUpdate();
        }
        function pgBtnUpdate() {
            const pb = document.getElementById("dl_pgbtn");
            pb && (fabSet(pb, "grid", uiText("pgBtn") + " \u00b7 " + (pg.sel.size ? pg.sel.size + "/" + pgTotal() : uiText("pgAll"))), pb.classList.toggle("dl-on", pg.mode || pg.sel.size > 0));
        }
        function setPgMode(on) {
            pg.mode = !!on, document.body && document.body.classList.toggle("dl-pgmode", pg.mode), pgDecorate();
        }
        function pgSet(kind) {
            const total = pgTotal();
            if ("none" === kind) pg.sel.clear(); else for (let i = 0; i < total; i++) "all" === kind ? pg.sel.add(i) : pg.sel.has(i) ? pg.sel.delete(i) : pg.sel.add(i);
            pgRefresh();
        }
        function pgToggle(idx, shift) {
            const want = !pg.sel.has(idx);
            let from = idx, to = idx;
            shift && pg.last >= 0 && (from = Math.min(pg.last, idx), to = Math.max(pg.last, idx));
            for (let i = from; i <= to; i++) want ? pg.sel.add(i) : pg.sel.delete(i);
            pg.last = idx, pgRefresh();
        }
        // Put a selection square on every thumbnail of the gallery page
        function pgDecorate() {
            document.querySelectorAll(".thumbnail-container, .hr-thumb").forEach(c => {
                if (c.querySelector(":scope > .dl-pgchk")) return;
                const a = c.matches("a[href]") ? c : c.querySelector("a[href]"), m = a && a.href.match(/#([0-9]+)$/);
                if (!m) return;
                c.dataset.dlPg = String(+m[1] - 1), "static" === getComputedStyle(c).position && (c.style.position = "relative");
                const chk = document.createElement("span");
                chk.className = "dl-pgchk", c.appendChild(chk);
            }), pgRefresh();
        }
        function installPageSelect() {
            if (pg.installed) return;
            pg.installed = !0, GM_addStyle(`
    body.dl-pgmode .thumbnail-container, body.dl-pgmode .thumbnail-container a { cursor: pointer; }
    .thumbnail-container > .dl-pgchk { display: none; position: absolute; top: 4px; left: 4px; width: 22px; height: 22px; box-sizing: border-box; border: 2px solid #fff; border-radius: 5px; background: rgba(0,0,0,.55); z-index: 20; pointer-events: none; }
    body.dl-pgmode .thumbnail-container > .dl-pgchk { display: block; }
    .thumbnail-container.dl-pgsel > .dl-pgchk { background: #ffcccc; border-color: #ffcccc; }
    .thumbnail-container.dl-pgsel > .dl-pgchk::after { content: "\\2713"; display: block; color: #000; font: bold 15px/18px sans-serif; text-align: center; }
    body.dl-pgmode .thumbnail-container.dl-pgsel { outline: 2px solid #ffcccc; outline-offset: -2px; }
    `);
            // In selection mode a click on a thumbnail selects it instead of opening the reader
            window.addEventListener("click", ev => {
                if (!pg.mode || !ev.target.closest) return;
                const c = ev.target.closest(".thumbnail-container, .hr-thumb"), idx = c ? parseInt(c.dataset.dlPg) : NaN;
                if (isNaN(idx)) return;
                ev.preventDefault(), ev.stopImmediatePropagation(), pgToggle(idx, ev.shiftKey);
            }, !0);
            let timer = 0;
            new MutationObserver(() => {
                clearTimeout(timer), timer = setTimeout(pgDecorate, 150);
            }).observe(document.body, { childList: !0, subtree: !0 }), pgDecorate();
        }
        // ---------- Hover preview (like Powerful Pixiv Downloader) ----------
        function pvBox() {
            if (pv.box) return pv.box;
            const box = document.createElement("div");
            box.id = "dl_preview";
            box.style.cssText = "position:fixed;left:0;top:0;width:max-content;z-index:2147482000;display:none;pointer-events:none;box-sizing:border-box;max-width:calc(100vw - 16px);padding:6px;background:rgba(22,22,22,.97);color:#ddd;border:1px solid #555;border-radius:6px;box-shadow:0 4px 18px rgba(0,0,0,.6);font:12px/1.35 sans-serif;text-align:left;";
            const img = document.createElement("img"), msg = document.createElement("div"), cnt = document.createElement("div"), sum = document.createElement("div");
            img.className = "pv-img", img.style.cssText = "display:none;max-width:100%;max-height:calc(100vh - 80px);margin:0 auto;";
            msg.className = "pv-msg", msg.style.cssText = "padding:10px 14px;text-align:center;";
            cnt.className = "pv-count", cnt.style.cssText = "text-align:center;opacity:.8;margin-top:4px;";
            // width:0 + min-width:100% -> the text wraps to the image width instead of making the box wider than the image
            sum.className = "pv-sum", sum.style.cssText = "width:0;min-width:100%;margin-top:6px;max-height:110px;overflow:hidden;";
            box.append(img, msg, cnt, sum), document.body.appendChild(box), hrHold();
            // Re-center whenever the real size is known (image decoded, summary added, ...)
            img.addEventListener("load", () => pvPlace()), "function" == typeof ResizeObserver && new ResizeObserver(() => pvPlace()).observe(box);
            return pv.box = box;
        }
        // Gallery id of a list item (works on list pages and on the "related galleries" of a gallery page)
        function pvIdOf(item) {
            if (item.classList.contains("hr-thumb")) { // page thumbnail on a gallery page
                const gi = unsafeWindow.galleryinfo, m = (item.getAttribute("href") || "").match(/\/reader\/([0-9]+)\.html/);
                return gi && gi.id ? String(gi.id) : m ? m[1] : "";
            }
            if (item.classList.contains("hr-card")) { // card drawn by Hitomi Enhanced
                const ca = item.querySelector("a.hr-title, a.hr-cover-link"), cm = ca && (ca.dataset.hrInfo || ca.href).match(/(?:-|\/)([0-9]+)\.html/);
                return cm ? cm[1] : "";
            }
            const a = item.querySelector("a.lillie, h1.lillie a"), m = a && a.href && (a.dataset.hrInfo || a.href).match(/(?:-|\/)([0-9]+)\.html/);
            return m ? m[1] : "";
        }
        function pvVisible() {
            return !!(pv.box && pv.item && "none" !== pv.box.style.display);
        }
        function pvMsg(text) {
            const box = pvBox(), img = box.querySelector(".pv-img"), msg = box.querySelector(".pv-msg");
            img.style.display = "none", msg.textContent = text, msg.style.display = "block", pvPlace();
        }
        function pvRect() {
            const it = pv.item;
            return it && it.isConnected ? (it.classList.contains("hr-card") && it.querySelector(".hr-cover") || it).getBoundingClientRect() : null;
        }
        // Side of the card where the preview goes: the one with more free room, decided once per hovered work
        function pvSide() {
            if (!pv.side) {
                const r = pvRect();
                if (!r) return "r";
                const vw = document.documentElement.clientWidth;
                pv.side = vw - r.right >= r.left ? "r" : "l";
            }
            return pv.side;
        }
        // Width the image may use on that side (so the box fits there whatever the page's proportions are)
        function pvAvailW() {
            const r = pvRect(), vw = document.documentElement.clientWidth;
            if (!r) return vw - 30;
            const room = ("r" === pvSide() ? vw - r.right : r.left) - 10 - 8 - 14;
            return room >= 160 ? room : vw - 30;
        }
        // Enhanced re-draws the grid from time to time: instead of closing the preview, follow the same work's new card
        function pvRelink() {
            if (pv.item && pv.item.isConnected) return true;
            if (!pv.item || !pv.id || pv.thumb) return false;
            for (const c of document.querySelectorAll("#hr-app .hr-card, .gallery-content > div")) if (!c.classList.contains("hr-thumb") && pvIdOf(c) === pv.id) return pv.item = c, pv.side = null, !0;
            return false;
        }
        function pvPlace() {            const box = pv.box;
            if (!box || !pv.item || "none" === box.style.display) return;
            if (!pvRelink()) return pvHide(); // the work is no longer on the page
            const it = pv.item;
            const r = (it.classList.contains("hr-card") && it.querySelector(".hr-cover") || it).getBoundingClientRect(), vw = document.documentElement.clientWidth, vh = window.innerHeight, w = box.offsetWidth, h = box.offsetHeight;
            // the side is chosen once per work (the side with more room) and kept while its pages change,
            // so a narrow page no longer makes the preview jump from one side of the card to the other
            let left;
            const side = pvSide();
            if ("r" === side && r.right + 10 + w <= vw - 8) left = r.right + 10;
            else if ("l" === side && r.left - 10 - w >= 8) left = r.left - 10 - w;
            else left = r.left + r.width / 2 - w / 2;
            const top = r.top + r.height / 2 - h / 2;
            box.style.left = Math.max(8, Math.min(left, vw - w - 8)) + "px", box.style.top = Math.max(8, Math.min(top, vh - h - 8)) + "px";
        }
        function pvHide() {
            // remember the page where the preview was left, so it resumes there next time
            pv.gi && pv.gi.id && !pv.thumb && pv.pos.set(String(pv.gi.id), pv.idx);
            clearTimeout(pv.timer), pv.token++, pv.item = null, pv.id = "", pv.side = null, pv.gi = null, pv.idx = 0, pv.thumb = !1;
            pv.box && (pv.box.style.display = "none");
        }
        // gg.js changes every so often: reload it when it is old (or after a failed image) so image URLs do not go stale
        function pvLoadGg() {
            return new Promise((resolve, reject) => {
                const sc = document.createElement("script");
                sc.src = "//" + unsafeWindow.domain + "/gg.js?_=" + Date.now(), sc.onload = () => (sc.remove(), resolve()),
                sc.onerror = () => (sc.remove(), reject(new Error("could not reload gg.js"))), document.head.appendChild(sc);
            });
        }
        function pvGg(fresh) {
            const old = pv.ggP && Date.now() - pv.ggAt > 600000;
            if (!pv.ggP || fresh || old) {
                const first = !pv.ggP;
                pv.ggAt = Date.now();
                pv.ggP = (first ? ensureGg() : pvLoadGg()).catch(err => {
                    if (first) pv.ggP = null; // not even the first load worked: try again next time
                    else console.warn("[Hitomi Enhanced] vista previa: no se pudo refrescar gg.js", err);
                });
            }
            return pv.ggP;
        }
        function pvFetch(id) {
            pv.cache.has(id) || pv.cache.set(id, pvGg().then(() => fetchGalleryInfo(id)).catch(err => {
                pv.cache.delete(id);
                throw err;
            }));
            return pv.cache.get(id);
        }
        function pvUrl(gi, file, small) {
            try {
                return small ? unsafeWindow.url_from_url_from_hash(gi.id, file, "webpbigtn", "webp", "tn") : unsafeWindow.url_from_url_from_hash(gi.id, file, "webp");
            } catch (err) {
                return "";
            }
        }
        function pvSummary(sum, gi) {
            sum.textContent = "";
            if ("1" !== GM_getValue("pv_summary", "0")) return;
            const names = (arr, key) => Array.isArray(arr) ? arr.map(x => x && x[key]).filter(Boolean).join(", ") : "";
            const add = (label, value, bold) => {
                if (!value) return;
                const d = document.createElement("div");
                if (label) {
                    const b = document.createElement("b");
                    b.textContent = label + ": ", d.append(b);
                }
                d.append(document.createTextNode(String(value))), bold && (d.style.fontWeight = "bold"), sum.append(d);
            };
            add("", gi.title, !0), add(uiText("artist"), names(gi.artists, "artist")), add(uiText("group"), names(gi.groups, "group")),
            add(uiText("language"), gi.language), add(uiText("type"), gi.type), add(uiText("pages"), (gi.files || []).length);
            const tags = Array.isArray(gi.tags) ? gi.tags.map(x => x && x.tag ? (1 == x.female ? "female:" : 1 == x.male ? "male:" : "") + x.tag : "").filter(Boolean).slice(0, 14).join(", ") : "";
            add(uiText("tags"), tags);
        }
        // Show the current image of the current gallery
        function pvRender() {
            const gi = pv.gi, box = pvBox(), files = gi && gi.files || [], token = pv.token;
            if (!files.length) return pvMsg(uiText("pvError"));
            const img = box.querySelector(".pv-img"), msg = box.querySelector(".pv-msg"), i = pv.idx, small = "small" === GM_getValue("pv_size", "small");
            box.querySelector(".pv-count").textContent = "1" === GM_getValue("pv_count", "1") ? i + 1 + " / " + files.length : "", pv.thumb ? box.querySelector(".pv-sum").textContent = "" : pvSummary(box.querySelector(".pv-sum"), gi);
            // Use (almost) the whole window: leave room only for the counter / summary when they are shown
            const reserve = 30 + ("1" === GM_getValue("pv_count", "1") ? 26 : 0) + (!pv.thumb && "1" === GM_getValue("pv_summary", "0") ? 120 : 0);
            const load = (url, fallback, tries) => {
                const probe = document.createElement("img");
                probe.onload = () => {
                    if (token !== pv.token || i !== pv.idx) return;
                    // Fit the image into the window and give it that exact size, so the box is never wider than the picture
                    const nw = probe.naturalWidth || 1, nh = probe.naturalHeight || 1;
                    const k = Math.min(1, pvAvailW() / nw, (window.innerHeight - reserve) / nh);
                    img.style.maxWidth = "none", img.style.maxHeight = "none", img.style.width = Math.max(1, Math.round(nw * k)) + "px", img.style.height = Math.max(1, Math.round(nh * k)) + "px";
                    img.src = url, img.style.display = "block", msg.style.display = "none", pvPlace();
                };
                probe.onerror = () => {
                    if (token !== pv.token || i !== pv.idx) return;
                    // one quick retry of the same image (a hiccup of the image server), then the other size, then a fresh gg.js
                    if (!tries) return void setTimeout(() => { token === pv.token && i === pv.idx && load(url, fallback, 1); }, 450);
                    if (fallback) return load(fallback, "", 1);
                    if (pv.ggTry === token + ":" + i) return pvMsg(uiText("pvError"));
                    pv.ggTry = token + ":" + i;
                    pvGg(!0).then(() => { token === pv.token && i === pv.idx && pvRender(); });
                };
                probe.src = url;
            };
            const full = pvUrl(gi, files[i], !1);
            load(small ? pvUrl(gi, files[i], !0) : full, small ? full : "", 0);
            // preload the next image so switching feels instant
            files.length > 1 && (document.createElement("img").src = pvUrl(gi, files[(i + 1) % files.length], small));
            pvPlace();
        }
        function pvStep(d) {
            const n = pv.gi && pv.gi.files ? pv.gi.files.length : 0;
            n < 2 || (pv.idx = (pv.idx + d + n) % n, pvRender());
        }
        async function pvShow(item) {
            const token = ++pv.token, box = pvBox();
            pv.gi = null, pv.idx = 0, pv.id = pvIdOf(item), pv.thumb = item.classList.contains("hr-thumb"), box.style.display = "block";
            box.querySelector(".pv-count").textContent = "", box.querySelector(".pv-sum").textContent = "", box.querySelector(".pv-img").removeAttribute("src");
            pvMsg(uiText("pvLoading"));
            let gi;
            try {
                gi = pv.thumb && unsafeWindow.galleryinfo && unsafeWindow.galleryinfo.files ? unsafeWindow.galleryinfo : await pvFetch(pvIdOf(item));
            } catch (err) {
                token === pv.token && pvMsg(uiText("pvError"));
                return;
            }
            try { await pvGg(); } catch (err) {} // also refreshes gg.js when it is old
            if (token === pv.token) {
                const saved = pv.thumb ? (parseInt((item.getAttribute("href") || "").split("#")[1]) || 1) - 1 : pv.pos.get(String(gi.id)) || 0, n = (gi.files || []).length;
                pv.gi = gi, pv.idx = saved >= 0 && saved < n ? saved : 0, pvRender();
            }
        }
        let pvInstalled = !1;
        function installPreview() {
            if (pvInstalled) return;
            pvInstalled = !0;
            document.addEventListener("mouseover", ev => {
                let it = ev.target.closest && ev.target.closest(".gallery-content > div, #hr-app .hr-card, #hr-app .hr-thumb");
                it && !pvIdOf(it) && (it = null);
                it && "#hr-favoritos" === location.hash && (it = null); // en Favoritos la vista previa la gestiona Hitomi Enhanced (opción «Vista previa en Favoritos»)
                // only the cover image triggers the preview, not the title / artist / tags
                if (it && it.classList.contains("hr-thumb")) {} else if (it && it.classList.contains("hr-card")) !(ev.target.closest(".hr-cover") && !ev.target.closest(".dl-hx")) && (it = null); // Enhanced card: its cover, but not our pick / download buttons
                else it && !(it.firstElementChild && it.firstElementChild.contains(ev.target)) && (it = null);
                if (it === pv.item) return;
                if (pvHide(), !it || "1" !== GM_getValue(it.classList.contains("hr-thumb") ? "pv_thumb_enabled" : "pv_enabled", "1")) return;
                pv.item = it;
                const wait = Math.max(0, parseInt(GM_getValue(it.classList.contains("hr-thumb") ? "pv_wait_thumb" : "pv_wait", it.classList.contains("hr-thumb") ? "200" : "400")) || 0);
                pv.timer = setTimeout(() => pvShow(it), wait);
            }, !0);
            // leaving the window
            document.addEventListener("mouseout", ev => {
                ev.relatedTarget || pvHide();
            }, !0);
            // mouse wheel switches images (only when the gallery has several)
            document.addEventListener("wheel", ev => {
                if (!pvVisible() || !pv.gi || pv.thumb || "1" !== GM_getValue("pv_wheel", "1") || (pv.gi.files || []).length < 2) return;
                ev.preventDefault();
                const now = Date.now();
                now - pv.lastWheel < 70 || (pv.lastWheel = now, pvStep(ev.deltaY > 0 ? 1 : -1));
            }, { capture: !0, passive: !1 });
            // arrow keys / space switch images
            document.addEventListener("keydown", ev => {
                if (!pvVisible() || !pv.gi || pv.thumb || "1" !== GM_getValue("pv_keys", "1")) return;
                const tag = ev.target && ev.target.tagName;
                if ("INPUT" === tag || "TEXTAREA" === tag || "SELECT" === tag || ev.target && ev.target.isContentEditable) return;
                const next = "ArrowRight" === ev.key || "ArrowDown" === ev.key || " " === ev.key, prev = "ArrowLeft" === ev.key || "ArrowUp" === ev.key;
                if (!next && !prev) return;
                ev.preventDefault(), ev.stopPropagation(), pvStep(next ? 1 : -1);
            }, !0);
            // scrolling the page moves the item away from the cursor
            window.addEventListener("scroll", () => {
                pv.item && pvHide();
            }, { passive: !0 });
        }
        function initListPage() {
            installPickGuard(), installPreview();
            window.addEventListener("focus", () => renderHistory()), buildPanel(), applySelectMode(), installFab(), fabStyles(), GM_addStyle(`
    body.dl-selmode .gallery-content > div, body.dl-selmode .gallery-content > div a { cursor: pointer; }
    .gallery-content > div > .dl-pick { position: absolute; top: 6px; left: 6px; width: 24px; height: 24px; box-sizing: border-box; border: 2px solid #fff; border-radius: 5px; background: rgba(0,0,0,.55); cursor: pointer; z-index: 20; opacity: .75; }
    .gallery-content > div > .dl-pick::before { content: ""; position: absolute; inset: -12px; }
    .gallery-content > div:hover > .dl-pick, .gallery-content > div.dl-selected > .dl-pick { opacity: 1; }
    .gallery-content > div.dl-selected > .dl-pick { background: #ffcccc; border-color: #ffcccc; }
    .gallery-content > div.dl-selected > .dl-pick::after { content: "\\2713"; display: block; color: #000; font: bold 16px/20px sans-serif; text-align: center; }
    .gallery-content > div.dl-selected { outline: 2px solid #ffcccc; outline-offset: -2px; }
    .gallery-content > div.dl-done > .dl-get:not(.dl-busy):not(.dl-err) { opacity: 1; background: #a5d6a7; border-color: #a5d6a7; color: #1b3a1d; }
    .gallery-content > div.dl-done > .dl-get:not(.dl-busy):not(.dl-err):not(.dl-ok)::after { content: "\\2713"; font: bold 14px/24px sans-serif; }
    .gallery-content > div > .dl-get { position: absolute; bottom: 8px; right: 8px; min-width: 38px; height: 28px; padding: 0 9px; box-sizing: border-box; border: 2px solid #fff; border-radius: 8px; background: rgba(0,0,0,.6); color: #fff; font: bold 18px/24px sans-serif; text-align: center; white-space: nowrap; user-select: none; cursor: pointer; z-index: 20; opacity: .8; display: flex; align-items: center; justify-content: center; gap: 5px; box-shadow: 0 2px 8px rgba(0,0,0,.35); transition: background .15s, border-color .15s, color .15s, transform .1s; }
    .gallery-content > div > .dl-get svg { display: block; width: 18px; height: 18px; flex: none; transition: transform .15s; }
    .gallery-content > div > .dl-get:hover svg { transform: translateY(2px); }
    .gallery-content > div > .dl-get:active { transform: scale(.94); }
    .gallery-content > div > .dl-get.dl-busy svg { width: 12px; height: 12px; }
    .gallery-content > div:hover > .dl-get, .gallery-content > div > .dl-get.dl-busy { opacity: 1; }
    .gallery-content > div > .dl-get:hover, .gallery-content > div > .dl-get.dl-busy { background: #ffcccc; border-color: #ffcccc; color: #4a1f1f; }
    .gallery-content > div > .dl-get.dl-busy { font: bold 12px/24px sans-serif; cursor: pointer; }
    .gallery-content > div > .dl-get.dl-ok { background: #a5d6a7; border-color: #a5d6a7; color: #1b3a1d; opacity: 1; }
    .gallery-content > div > .dl-get.dl-err { background: #e57373; border-color: #e57373; color: #fff; opacity: 1; }
    `);
            let timer = 0;
            new MutationObserver(() => {
                clearTimeout(timer), timer = setTimeout(decorateItems, 150);
            }).observe(document.body, { childList: !0, subtree: !0 }), decorateItems();
        }
        function fabStyles() {
            GM_addStyle(`
    #dl_fab { display: flex; position: relative; width: fit-content; margin: 0 0 0 auto; z-index: 2147483000; align-items: center; justify-content: center; gap: 6px; min-width: 120px; height: 38px; padding: 0 16px; white-space: nowrap; box-sizing: border-box; font: bold 13px/1 sans-serif; color: #4a1f1f; background: #ffcccc; border: 2px solid #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.35); opacity: 1; user-select: none; cursor: pointer; transition: background .15s, border-color .15s, color .15s, opacity .15s, transform .1s; }
    #dl_fab:hover { background: #ffb3b3; }
    #dl_fab.dl-done { background: #a5d6a7; color: #1b3a1d; }
    #dl_fab.dl-done:hover { background: #8fcb93; }
    #dl_fab.dl-run { background: linear-gradient(90deg, #ffcccc var(--p, 0%), #fff var(--p, 0%)); border-color: #ffcccc; color: #4a1f1f; }
    #dl_fab.dl-run:hover { border-color: #ffb3b3; }
    #dl_fab:active { transform: scale(.94); }
    #dl_fab::after { content: attr(data-tip); position: absolute; right: calc(100% + 8px); top: 50%; transform: translateY(-50%); white-space: nowrap; padding: 5px 9px; font: 600 11px/1.2 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #fff; background: rgba(38,50,58,.95); border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,.3); opacity: 0; pointer-events: none; transition: opacity .12s; }
    #dl_fab:hover::after { opacity: 1; }
    #dl_qbtn, #dl_pgbtn { display: flex; position: relative; width: fit-content; margin: 6px 0 0 auto; align-items: center; justify-content: center; gap: 6px; min-width: 120px; height: 34px; padding: 0 16px; box-sizing: border-box; white-space: nowrap; font: bold 13px/1 sans-serif; color: #26323a; background: #fff; border: 2px solid #ffcccc; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.25); cursor: pointer; user-select: none; z-index: 2147483000; transition: background .15s, border-color .15s, transform .1s; }
    #dl_qbtn:hover, #dl_pgbtn:hover { background: #fff0f0; }
    #dl_qbtn.dl-on, #dl_pgbtn.dl-on { background: #ffcccc; color: #4a1f1f; }
    #dl_qbtn:active, #dl_pgbtn:active { transform: scale(.96); }
    #dl_qbtn svg, #dl_pgbtn svg { display: block; width: 16px; height: 16px; flex: none; }
    #dl_fab svg { display: block; width: 18px; height: 18px; flex: none; transition: transform .15s; }
    #dl_fab:hover svg { transform: translateY(2px); }
    #dl_fab.dl-run svg { width: 12px; height: 12px; }
    /* without Hitomi Enhanced: bigger buttons */
    #dl_corner > #dl_fab, #dl_corner > #dl_qbtn, #dl_selbar { width: 175px; min-width: 0; box-sizing: border-box; }
    #dl_corner > #dl_fab, #dl_corner > #dl_qbtn, #dl_selbar button { height: 36px; min-height: 36px; }
    #dl_selbar #dl_q_page { display: none; }
    body.dl-selmode #dl_selbar #dl_q_page { display: block; }
    #dl_selbar #dl_q_unsel { display: none; }
    #dl_selbar #dl_q_unsel.dl-has { display: block; }
    #dl_corner > #dl_qbtn, #dl_corner > #dl_pgbar { margin-top: 8px; }
    #dl_selbar { gap: 8px; }
    #dl_selbar button { padding: 2px 10px; line-height: 1.15; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-width: 2px; }
    #dl_pgbar > #dl_pgbtn { width: 175px; min-width: 0; height: 36px; min-height: 36px; margin: 0; box-sizing: border-box; border-width: 2px; }
    /* with Hitomi Enhanced: compact buttons */
    html.dl-hr #dl_corner > #dl_fab, html.dl-hr #dl_corner > #dl_qbtn, html.dl-hr #dl_selbar { width: 145px; }
    html.dl-hr #dl_corner > #dl_fab, html.dl-hr #dl_corner > #dl_qbtn, html.dl-hr #dl_selbar button { height: 34px; min-height: 34px; font-size: 12px; }
    html.dl-hr #dl_corner > #dl_fab, html.dl-hr #dl_corner > #dl_qbtn { padding: 0 8px; gap: 4px; border-width: 2px; }
    html.dl-hr #dl_corner > #dl_fab svg, html.dl-hr #dl_corner > #dl_qbtn svg { width: 15px; height: 15px; }
    html.dl-hr #dl_corner > #dl_fab.dl-run svg { width: 12px; height: 12px; }
    html.dl-hr #dl_selbar button { padding: 0 6px; line-height: 1; }
    /* los ajustes del descargador viven ahora en el menú de ajustes de Enhanced */
    html.dl-hr #dl_gearbox { display: none !important; }
    html.dl-hr #dl_pgbar > #dl_pgbtn { width: 145px; height: 34px; min-height: 34px; padding: 0 8px; gap: 4px; font-size: 12px; }
    html.dl-hr #dl_pgbar > #dl_pgbtn svg { width: 15px; height: 15px; }
    html:is(.hr-ui, .hr-ct) :is(#dl_corner #dl_qbtn, #dl_corner #dl_pgbtn, #dl_selbar button) { border-color: color-mix(in srgb, var(--hr-text) 45%, transparent); }
    `);
        }
        function anchorSave(blob, filename) {
            const url = URL.createObjectURL(blob), save_link = document.createElement("a");
            save_link.href = url, save_link.download = filename, document.body.appendChild(save_link),
            save_link.click(), save_link.remove(), setTimeout(() => URL.revokeObjectURL(url), 6e5);
        }
        if (location.pathname.startsWith("/reader/")) {
            // Click on the left / right side of the reader to go to the previous / next page (like Suwayomi).
            // Set READER_TAP_RTL to true for manga-style reading (left = next page, right = previous page).
            function installReaderTap() {
                const READER_TAP_RTL = false, ZONE = 0.3; // each side zone = 30% of the window width
                // Fast clicks in the reader must not select / highlight the page (blue overlay on images and text)
                GM_addStyle("html, body, #comicImages, #mobileImages, #comicImages *, #mobileImages * { -webkit-user-select: none !important; user-select: none !important; }\nimg { -webkit-user-drag: none; }\nselect, input, textarea { -webkit-user-select: auto !important; user-select: auto !important; }");
                document.addEventListener("mousedown", ev => {
                    if (ev.detail > 1 && !(ev.target.closest && ev.target.closest("select, input, textarea"))) {
                        ev.preventDefault();
                        const s = window.getSelection && window.getSelection();
                        s && s.removeAllRanges();
                    }
                }, !0);
                document.addEventListener("selectstart", ev => {
                    ev.target.closest && ev.target.closest("select, input, textarea") || ev.preventDefault();
                }, !0);
                const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
                const findBtn = re => [ ...document.querySelectorAll("a, button") ].find(el => re.test((el.textContent || "").trim()) && visible(el));
                const go = next => {
                    const btn = findBtn(next ? /^next$/i : /^prev(ious)?$/i);
                    if (btn) return btn.click();
                    const fn = unsafeWindow[next ? "nextPage" : "prevPage"] || (next ? null : unsafeWindow.previousPage);
                    "function" == typeof fn && fn();
                };
                document.addEventListener("click", ev => {
                    if (0 !== ev.button || ev.shiftKey || ev.ctrlKey || ev.altKey || ev.metaKey) return;
                    if (document.documentElement.classList.contains("hr-rv")) return; // Hitomi Enhanced's reader has its own click zones
                    // ignore the toolbar, links, buttons, form controls and the page scrollbar
                    if (ev.target.closest && ev.target.closest("a, button, select, input, textarea, nav, .navbar, .lum-close-button")) return;
                    const sel = window.getSelection && window.getSelection();
                    if (sel && !sel.isCollapsed) return;
                    const w = document.documentElement.clientWidth, x = ev.clientX;
                    if (x > w) return; // click on the scrollbar
                    const left = x < w * ZONE, right = x > w * (1 - ZONE);
                    if (!left && !right) return;
                    ev.preventDefault(), ev.stopImmediatePropagation();
                    go(READER_TAP_RTL ? left : right);
                }, !0);
            }
            function end() {
                console.log("end()");
                installReaderTap();
                // change the hash without adding a history entry
                const script = document.createElement("script");
                script.type = "text/javascript";
                const fns = [ "singlePageChange", "mobile_singlePageChange", "twoPageChange", "mobile_twoPageChange" ];
                for (const index in fns) fns[index] = unsafeWindow[fns[index]].toString().replace(/location.hash *= *([A-z]*);/g, "location.replace(location.pathname+'#'+$1);");
                script.innerHTML = "'use strict'\n" + fns.join("\n"), document.body.appendChild(script);
                // stop hiding the mouse cursor over the image
                const make_image_element_ = unsafeWindow.make_image_element;
                unsafeWindow.make_image_element = function(...args) {
                    return args.length > 4 && (
                    // disable the img.onmouseover event
                    args[4] = void 0), make_image_element_.apply(this, args);
                };
                // fix preventDefault error
                const addEventListener_ = document.addEventListener;
                if (document.addEventListener = function(...args) {
                    return "touchmove" === args[0] && (2 == args.length && args.push({
                        passive: !1
                    }), document.addEventListener = addEventListener_), addEventListener_.apply(this, args);
                }, GM_addStyle("\n#comicImages.fitVertical > picture {\n  display: contents;\n}\n#comicImages.fitVertical {\n  height: calc(100% - 41px);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n#comicImages.fitVertical img {\n  max-height: 100%;\n  width: auto;\n  height: auto;\n  max-width: calc(100% - 4px);\n}\n#mobileImages.fitVertical {\n  height: 100%;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n#mobileImages.fitVertical img {\n  max-height: 100%;\n  width: auto;\n  height: auto;\n  max-width: 100%;\n}\n"),
                unsafeWindow.mobile_fitHorizontal = unsafeWindow.mobile_fitVertical, unsafeWindow.parent === unsafeWindow) return;
                // iframe
                            $(".mobile-navbar-inner>.gallery-link").remove(), $(".mobile-navbar-inner>.mobile-nav-right").css("float", "left"),
                $(".container>a.brand").remove(), $(".container>.btn-navbar").css("float", "left"),
                $("ul.pull-right").css("float", "left");
                unsafeWindow.addEventListener("hashchange", (() => {
                    const hash = location.hash;
                    unsafeWindow.parent.postMessage("" === hash ? "#1" : hash);
                } // send a message to the parent page
                ), !1);
            }
            "loading" !== document.readyState ? (console.warn(document.readyState), end()) : document.addEventListener("DOMContentLoaded", end, {
                capture: !0,
                once: !0
            });
        } else {
            // List and gallery pages: connect with Hitomi Enhanced (squares, download buttons and panels over its interface)
            "loading" !== document.readyState ? installRevampBridge() : document.addEventListener("DOMContentLoaded", installRevampBridge, {
                once: !0
            });
        }
        /******/})();
  };
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', startDownloader, { once: true });
  else startDownloader();
})();