TCDD Taşımacılık ile bağlantısı yoktur.

Dolu görünen trende yer bul.

ebilet, yolun başından sonuna boş tek bir koltuk yoksa treni dolu gösterir. Bilet Bul ara istasyonlardaki boş koltukları birleştirir, gidilebilecek rotaları fiyatıyla sıralar.

Nasıl kullanılır
  • Ücretsiz
  • Kurulum gerekmez
  • Veri tarayıcında kalır
  • Klavye ve ekran okuyucuyla kullanılır

Panel böyle görünür

ebilet'in sayfasında açılır, yolculuğunun bütün kalkışlarına bakar. Bulduğu rotaları fiyatıyla sıralar, hangi istasyonda koltuk değiştireceğini yazar.

Yer varDolu görünen trende, 2 biletle

Örnek görünüm, uydurma verilerle. Fiyatlar gerçek değil.

Nasıl kullanılır

Önerilen yol konsol: kodu kopyala, ebilet'te konsola yapıştır, hiçbir şey kurman gerekmez. Her açılışta otomatik çalışsın istersen Tampermonkey sekmesine bak.

  1. Aşağıdan kodu kopyala.
  2. ebilet.tcddtasimacilik.gov.tr sitesini aç.
  3. Konsolu aç: F12 ya da Mac'te ⌥ ⌘ J, sonra Console.
  4. Kodu yapıştır, Enter. Panel sağ altta açılır.

⚠ Yapıştırma engellenirseChrome ilk seferde uyarı verir. Konsola allow pasting yaz (yapıştırma değil, elle yaz), Enter tuşuna bas, sonra kodu yeniden yapıştır.

Sayfa yenilenince kodu tekrar yapıştırman gerekir.

Panelde

  1. ebilet'te yolculuğunu ara, örneğin Ankara Gar → İstanbul(Söğütlüçeşme). Panel o günün bütün kalkışlarına bakar; istersen bir kalkış saati aralığı seçersin.
  2. Panel sıradaki ara parçayı forma yazar ve Ara düğmesini öne çıkarır; sen sadece Enter tuşuna basarsın.
  3. Aramalar sürerken panel yalnız sıradaki adımı gösterir. Duraklat ile istediğin an rotalara bakabilirsin.
  4. Rotalar her aramada güncellenir: en ucuz, en erken varış, en az bilet.

Klavye, ekran okuyucu ve sesli kullanım

  • Alt + Shift + K paneli açar ve klavye odağını panele getirir. Sekmeler arasında ok tuşlarıyla geçilir.
  • Her aramanın sonucu ekran okuyucuya duyurulur: kaç trende yer olduğu, kaç rota bulunduğu, sıradaki arama.
  • Ayarlardaki Sesli bildirim açılırsa aynı duyurular cihazındaki Türkçe sesle okunur. Metin hiçbir yere gönderilmez.
  • Düğmelerin adı ekranda yazanla aynıdır; sesle kontrol (macOS Sesle Denetim, Windows Sesli Erişim, Android Voice Access) ile “Formu doldur'a dokun” gibi komutlar çalışır.
ebilet-koltuk-bulucu.user.js
// ==UserScript==
// @name         Bilet Bul: ebilet için koltuk bulucu (resmi değil)
// @namespace    tcdd-split-seat
// @version      0.13.0
// @description  Dolu görünen seferler için ara istasyonlar üzerinden tüm rotaları çıkarır: aynı trende koltuk değiştirme, istasyonda bekleyip başka trene aktarma, fiyat ve süre karşılaştırması. Sıradaki aramayı forma yazar; her aramayı sen Enter tuşuyla başlatırsın.
// @homepageURL  https://github.com/yasarcelep/bilet-bul
// @supportURL   https://github.com/yasarcelep/bilet-bul/issues
// @downloadURL  https://raw.githubusercontent.com/yasarcelep/bilet-bul/main/src/ebilet-koltuk-bulucu.user.js
// @updateURL    https://raw.githubusercontent.com/yasarcelep/bilet-bul/main/src/ebilet-koltuk-bulucu.user.js
// @match        https://ebilet.tcddtasimacilik.gov.tr/*
// @run-at       document-start
// @sandbox      raw
// @inject-into  page
// @grant        none
// ==/UserScript==

/*
 * NASIL ÇALIŞIR
 * -------------
 * ebilet her aramayı Cloudflare Turnstile ile koruyor. Script bu korumayı aşmaz:
 * siteye kendisi istek atmaz, aramayı kendisi başlatmaz. Yaptığı:
 *   - senin yaptığın aramaların yanıtlarını okumak (bir arama o iki istasyon
 *     arasındaki BÜTÜN trenleri kapsar),
 *   - bilinen parçaları birleştirip rotaları çıkarmak (aynı trende koltuk
 *     değiştirme + istasyonda bekleyip başka trene aktarma),
 *   - sıradaki aramayı forma yazıp Ara butonuna odaklanmak → sen Enter tuşuna basarsın.
 *
 * KULLANIM
 * --------
 * 1. Yolculuğunu ara (ör. Ankara Gar → Bozüyük YHT). Script o günün bütün
 *    kalkışlarına bakar; istersen bir kalkış saati aralığı seçebilirsin.
 * 2. Script sıradaki ara parçayı forma yazar ve Ara düğmesini öne çıkarır, sen
 *    Enter tuşuna basarsın. Aramalar sürerken panel yalnızca sıradaki adımı
 *    gösterir; Duraklat ile rotalara, seferlere ve geçmişe bakabilirsin.
 * 3. Rotalar: en ucuz / en erken varış / en az bilet sıralaması.
 *
 * Sayfa açılınca script formu doldurmaz. Yarım kalan bir yolculuk, aynı aramayı
 * yeniden yaptığında kaldığı yerden sürer.
 *
 * ERİŞİLEBİLİRLİK
 * Panel klavyeyle ve ekran okuyucuyla kullanılır: Alt+Shift+K paneli açar ve
 * odaklar, sekmeler ok tuşlarıyla gezilir, arama sonuçları duyurulur. Ayarlardan
 * "Sesli bildirim" açılırsa sonuçlar tarayıcının yerel Türkçe sesiyle okunur.
 *
 * Engelli (tekerlekli sandalye, DSB) koltukları varsayılan olarak hesaba katılmaz;
 * engelli yolcular Ayarlar'dan açabilir.
 * Veriler bu tarayıcıda 6 saat saklanır (localStorage).
 */

(() => {
  'use strict';
  if (window.__tcddSplitLoaded) return;
  window.__tcddSplitLoaded = true;

  const CFG = {
    searchMatch: /\/train-availability(\?|$)/i,
    seatMatch: /seat|vagon|wagon|coach/i,
    ignoredClassCodes: ['DSB'],
    ignoredClassRe: /tekerlek|engel|wheelchair/i,
    storeKey: 'tcddSplit.v6',
    maxAgeMs: 6 * 3600 * 1000,
    minTransferMin: 10,   // farklı trene geçişte en az bekleme
    maxWaitMin: 240,      // bir istasyonda en çok bekleme
    maxLegs: 4,           // bir rotada en çok bilet
    autoFill: true,       // her aramadan sonra sıradakini forma yaz
    staleMin: 20,         // bu kadar dakikadan eski koltuk bilgisi 'eski' sayılır
    speak: false,         // sonuçları yerel Türkçe sesle oku
    includeDisabled: false, // engelli (DSB) koltuklarını da boş yer say
    debug: false,
  };
  const log = (...a) => CFG.debug && console.log('[tcdd-split]', ...a);
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  /* ------------------------------------------------------------------ *
   *  STORAGE                                                            *
   *  pairs:    "trainId|a>b" -> { usable, disabled, per, price, cls,    *
   *                               dep, arr, ts }                        *
   *  searched: "a>b|day"     -> ts   (a search covers every train)      *
   *  missed:   "a>b|day"     -> station id not in ebilet's list (skipped)*
   *  failed:   "a>b|day"     -> HTTP status ebilet refused it with (skipped)*
   *  journey:  { o, d, day, range:{from,to}|null, trains:[trainId],    *
   *              trainStops:{id:[stops]}, deps:{id:ms}, ts }            *
   *  log:      [{ ts, a, b, day, kind, n, free, status, changes }]      *
   * ------------------------------------------------------------------ */
  function emptyStore() { return { pairs: {}, searched: {}, missed: {}, failed: {}, names: {}, journey: null, log: [] }; }
  function load() {
    try {
      const s = Object.assign(emptyStore(), JSON.parse(localStorage.getItem(CFG.storeKey)) || {});
      const now = Date.now();
      for (const k of Object.keys(s.pairs)) if (now - s.pairs[k].ts > CFG.maxAgeMs) delete s.pairs[k];
      for (const k of Object.keys(s.searched)) if (now - s.searched[k] > CFG.maxAgeMs) delete s.searched[k];
      for (const m of [s.missed, s.failed]) for (const k of Object.keys(m)) if (!s.searched[k]) delete m[k];
      if (s.journey && (now - (s.journey.ts || 0) > CFG.maxAgeMs || !Array.isArray(s.journey.trains))) s.journey = null;
      s.log = (s.log || []).filter((e) => now - e.ts <= CFG.maxAgeMs).slice(-40);
      return s;
    } catch (e) { return emptyStore(); }
  }
  function save() { try { localStorage.setItem(CFG.storeKey, JSON.stringify(store)); } catch (e) { /* ignore */ } }

  const store = load();
  const ui = {
    sort: 'price', showAll: false, fillMsg: '', lastFilledKey: null,
    live: false,      // a journey was started in this page session; a stored one waits until you search it again
    paused: false,    // searches on hold: the tabs are shown
    fill: null,       // the next search in ebilet's form: { key, a, b, st: filling|ready|searching|failed (no form), btn, away }
    rangeEdit: null,  // the departure-time range being edited: { from, to, was }
  };
  const state = { lastSearch: null, lastSeat: null, store };
  window.__tcddSplit = state;

  const pairKey = (trainId, a, b) => `${trainId}|${a}>${b}`;
  const searchedKey = (a, b, day) => `${a}>${b}|${day}`;

  /* ------------------------------------------------------------------ *
   *  CAPTURE (read-only) — XHR (site uses it) + fetch fallback          *
   * ------------------------------------------------------------------ */
  function handle(url, method, status, bodyText, respText) {
    try {
      if (CFG.searchMatch.test(url) && method === 'POST') {
        let body = null, resp = null;
        try { body = JSON.parse(bodyText); } catch (e) { /* no body */ }
        try { resp = JSON.parse(respText); } catch (e) { /* not JSON */ }
        if (status === 200 && body && resp) onSearch(body, resp);
        else if (body && resp && resp.code === 604) onSearch(body, { trainLegs: [] }); // "no journeys match": an empty result
        else if (body && status >= 400 && status < 500 && ![401, 403, 408, 429].includes(status)) onSearchRefused(status, resp, body);
        else onSearchFail(status, resp, body);
      } else if (status === 200 && CFG.seatMatch.test(url) && !/availability/i.test(url)) {
        onSeatMap(JSON.parse(respText));
      }
    } catch (e) { log('parse fail', url, e); }
  }

  function addLog(e) {
    store.log.push(Object.assign({ ts: Date.now() }, e));
    if (store.log.length > 40) store.log.splice(0, store.log.length - 40);
  }

  const whyOf = (resp) => (resp && (resp.message || resp.error) ? String(resp.message || resp.error).slice(0, 80) : '');
  function onSearchFail(status, resp, body) {
    const why = whyOf(resp) ? ` — ${whyOf(resp)}` : '';
    const route = body && (body.searchRoutes || [])[0];
    if (route) {
      addLog({ a: route.departureStationId, b: route.arrivalStationId, day: dayOf(route.departureDate), kind: 'error', status, why: whyOf(resp) });
      save();
    }
    ui.fill = null;
    ui.fillMsg = `Site bu aramaya yanıt vermedi (HTTP ${status}${why}). Enter tuşuna yeniden bas ya da "Atla"yı kullan.`;
    log('search failed', status, resp);
    render();
    announce(ui.fillMsg, true);
  }

  // ebilet refused one of the journey's pieces (HTTP 4xx that is not "no
  // journeys", a sign-in or a rate limit). Asking again gets the same answer,
  // so it is skipped without waiting and listed when the searches end.
  function onSearchRefused(status, resp, body) {
    const route = (body.searchRoutes || [])[0];
    const j = liveJ();
    if (!route || !j || ui.paused) return onSearchFail(status, resp, body);
    const a = route.departureStationId, b = route.arrivalStationId, day = dayOf(route.departureDate);
    if (day !== j.day || (a === j.o && b === j.d) || !onLine({ a, b })) return onSearchFail(status, resp, body);
    if (route.departureStationName) store.names[a] = route.departureStationName;
    if (route.arrivalStationName) store.names[b] = route.arrivalStationName;
    const k = searchedKey(a, b, day);
    store.searched[k] = Date.now();
    store.failed[k] = status;
    addLog({ a, b, day, kind: 'error', status, why: whyOf(resp), skipped: true });
    Object.assign(ui, { fill: null, fillMsg: '', lastFilledKey: null });
    save(); render();
    const m = model();
    announce(`ebilet ${title(nameOf(a))} → ${title(nameOf(b))} aramasına hata verdi (HTTP ${status}), arama atlandı.` +
      (m.phase === 'done' ? ' Aramalar bitti.' : ''));
  }

  const xo = XMLHttpRequest.prototype.open;
  const xs = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.open = function (m, u) {
    this.__ts = { m: String(m).toUpperCase(), u: String(u) };
    return xo.apply(this, arguments);
  };
  XMLHttpRequest.prototype.send = function (b) {
    const t = this.__ts;
    if (t && (CFG.searchMatch.test(t.u) || CFG.seatMatch.test(t.u))) {
      this.addEventListener('load', () => {
        handle(t.u, t.m, this.status, typeof b === 'string' ? b : null, this.responseText);
      });
    }
    return xs.apply(this, arguments);
  };

  const nf = window.fetch;
  window.fetch = async function (input, init) {
    const url = typeof input === 'string' ? input : (input && input.url) || '';
    const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
    const res = await nf.apply(this, arguments);
    if (CFG.searchMatch.test(url) || CFG.seatMatch.test(url)) {
      const body = init && typeof init.body === 'string' ? init.body : null;
      res.clone().text().then((t) => handle(url, method, res.status, body, t)).catch(() => {});
    }
    return res;
  };

  /* ------------------------------------------------------------------ *
   *  PARSING — matches the live schema (checked 2026-12)                *
   * ------------------------------------------------------------------ */
  function trainsOf(resp) {
    return (resp.trainLegs || []).flatMap((l) => l.trainAvailabilities || []).flatMap((a) => a.trains || []);
  }

  const isIgnored = (cc) => CFG.ignoredClassCodes.includes(cc.code) || CFG.ignoredClassRe.test(cc.name || '');

  // Usable seats per class + cheapest price among classes that still have seats.
  function availOf(t) {
    const rows = [];
    for (const ff of t.availableFareInfo || []) for (const c of ff.cabinClasses || []) rows.push(c);
    for (const c of t.cabinClassAvailabilities || []) rows.push(c);
    const best = {};
    for (const r of rows) {
      const cc = r.cabinClass || {};
      const name = cc.name || cc.code || '?';
      const n = Math.max(0, Number(r.availabilityCount) || 0);
      const price = typeof r.minPrice === 'number' ? r.minPrice : null;
      const b = best[name] || (best[name] = { n: 0, cc, price: null });
      if (n > b.n) b.n = n;
      if (price != null && n > 0 && (b.price == null || price < b.price)) b.price = price;
    }
    const per = {};
    let usable = 0, disabled = 0, price = null, cls = null;
    const all = { usable: 0, price: null, cls: null };  // with wheelchair seats, for the setting
    for (const [name, b] of Object.entries(best)) {
      const ignored = isIgnored(b.cc);
      if (ignored) disabled += b.n;
      else usable += b.n;
      all.usable += b.n;
      if (b.n > 0) {
        if (!ignored) per[name] = b.n;
        if (b.price != null && !ignored && (price == null || b.price < price)) { price = b.price; cls = name; }
        if (b.price != null && (all.price == null || b.price < all.price)) { all.price = b.price; all.cls = name; }
      }
    }
    return { usable, disabled, per, price, cls, all };
  }

  // A stored pair as the settings see it: with wheelchair seats counted if the
  // user asked for that. Pairs stored before 0.10 have no .all and stay as they are.
  function seatsOf(p) {
    return p && CFG.includeDisabled && p.all ? Object.assign({}, p, p.all) : p;
  }

  function stopsOf(t) {
    const stops = [];
    for (const s of t.segments || []) {
      const seg = s.segment || {};
      const d = seg.departureStation, a = seg.arrivalStation;
      if (d) {
        const ex = stops.find((x) => x.id === d.id);
        if (!ex) stops.push({ id: d.id, name: d.name, dep: s.departureTime });
        else if (ex.dep == null) ex.dep = s.departureTime;
      }
      if (a && !stops.some((x) => x.id === a.id)) stops.push({ id: a.id, name: a.name, arr: s.arrivalTime });
    }
    return stops;
  }
  const depOf = (t) => { const s = (t.segments || [])[0]; return s ? s.departureTime : null; };
  const arrOf = (t) => { const s = (t.segments || []).slice(-1)[0]; return s ? s.arrivalTime : null; };

  // "05-12-2026 21:00:00" is the UTC start of the Istanbul day searched.
  function dayOf(apiDate) {
    const m = String(apiDate || '').match(/(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})/);
    if (!m) return '?';
    const ms = Date.UTC(+m[3], +m[2] - 1, +m[1], +m[4], +m[5]) + 3 * 3600 * 1000;
    return new Date(ms).toLocaleDateString('tr-TR', { timeZone: 'Europe/Istanbul' });
  }

  const tz = { timeZone: 'Europe/Istanbul' };
  const dayOf2 = (ms) => (ms == null ? '?' : new Date(ms).toLocaleDateString('tr-TR', tz));
  const fmtTime = (ms) => (ms == null ? '' : new Date(ms).toLocaleTimeString('tr-TR', Object.assign({ hour: '2-digit', minute: '2-digit' }, tz)));
  const fmtDay = (day) => {
    const m = String(day).match(/(\d+)\.(\d+)\.(\d+)/);
    if (!m) return day;
    return new Date(Date.UTC(+m[3], +m[2] - 1, +m[1], 12)).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', timeZone: 'UTC' });
  };
  const fmtDur = (ms) => {
    const min = Math.round(ms / 60000);
    const h = Math.floor(min / 60), m = min % 60;
    return h ? `${h} sa${m ? ' ' + m + ' dk' : ''}` : `${m} dk`;
  };
  const ago = (ts) => {
    const m = Math.round((Date.now() - ts) / 60000);
    return m < 1 ? 'az önce' : m < 60 ? `${m} dk önce` : `${Math.floor(m / 60)} sa önce`;
  };
  // Forget that these pairs were searched, so the panel asks for them again;
  // first (default: the same pairs) are asked before anything else.
  function recheck(pairs, first) {
    const j = J();
    if (!j) return;
    for (const [a, b] of pairs) for (const m of [store.searched, store.missed, store.failed]) delete m[searchedKey(a, b, j.day)];
    j.again = (first || pairs).map(([a, b]) => [a, b]);
    ui.lastFilledKey = null;
    ui.fillMsg = '';
    ui.fill = null;
    ui.paused = false;
    save(); render();
  }
  const fmtPrice = (p) => (p == null ? '₺?' : '₺' + Math.round(p).toLocaleString('tr-TR'));
  const nameOf = (id) => store.names[id] || String(id);
  const KEEP_UPPER = new Set(['YHT']);
  const title = (s) => String(s || '').split(/(\s+|\(|\))/).map((w) => {
    if (KEEP_UPPER.has(w)) return w;
    const l = w.toLocaleLowerCase('tr-TR');
    return l.charAt(0).toLocaleUpperCase('tr-TR') + l.slice(1);
  }).join('');

  function onSearch(body, resp) {
    const route = (body.searchRoutes || [])[0];
    if (!route) return;
    const a = route.departureStationId, b = route.arrivalStationId;
    const day = dayOf(route.departureDate);
    if (route.departureStationName) store.names[a] = route.departureStationName;
    if (route.arrivalStationName) store.names[b] = route.arrivalStationName;
    const trains = trainsOf(resp);
    const now = Date.now();
    const changes = [];
    let free = 0;
    for (const t of trains) {
      for (const s of stopsOf(t)) store.names[s.id] = s.name;
      const k = pairKey(t.id, a, b);
      const prev = store.pairs[k];
      const cur = Object.assign(availOf(t), { dep: depOf(t), arr: arrOf(t), ts: now });
      const was = seatsOf(prev), is = seatsOf(cur);
      if (prev && was.usable !== is.usable) changes.push({ dep: cur.dep, from: was.usable, to: is.usable });
      if (is.usable > 0) free++;
      store.pairs[k] = cur;
    }
    // trains we knew on this pair that are gone now: no seats left
    const seen = new Set(trains.map((t) => String(t.id)));
    for (const [k, p] of Object.entries(store.pairs)) {
      const m = k.match(/^(\d+)\|(\d+)>(\d+)$/);
      if (!m || +m[2] !== a || +m[3] !== b || seen.has(m[1]) || p.ts >= now) continue;
      if (dayOf2(p.dep) !== day) continue;
      const was = seatsOf(p);
      if (was.usable > 0) changes.push({ dep: p.dep, from: was.usable, to: 0 });
      store.pairs[k] = Object.assign({}, p, { usable: 0, per: {}, price: null, all: { usable: 0, price: null, cls: null }, ts: now, gone: true });
    }
    addLog({ a, b, day, kind: trains.length ? 'ok' : 'empty', n: trains.length, free, changes });
    store.searched[searchedKey(a, b, day)] = now;
    delete store.missed[searchedKey(a, b, day)];
    delete store.failed[searchedKey(a, b, day)];
    if (J() && J().day === day) J().ts = now;   // still in use: keep it past maxAgeMs
    save();
    const ls = { a, b, day, trains };
    const j = liveJ();
    state.lastSearch = ls;
    ui.fillMsg = '';
    ui.fill = null;
    if (j && partOfJourney(ls)) {
      // a piece of the journey: the routes take it in
    } else if (j && !ui.paused && onJourneyLine(ls) && !(a === j.o && b === j.d)) {
      // a piece on another day while the searches run: the date in the form
      ui.fillMsg = `Bu arama ${fmtDay(day)} için yapıldı, yolculuğun ${fmtDay(j.day)}. ebilet'te tarihi ${fmtDay(j.day)} yap, sonra Enter tuşuna bas.`;
    } else if (trains.length) {
      startJourney(ls);   // a new trip (or the same one again): every departure counts
      save();
    } else ui.live = false;   // no trains: nothing to search
    log('search', a, '>', b, day, trains.length);
    render();
    announce(searchSummary(ls, free, changes), !!ui.fillMsg);
  }

  // One sentence for screen readers / speech after each search.
  function searchSummary(ls, free, changes) {
    const n = ls.trains.length;
    let t = `${title(nameOf(ls.a))} → ${title(nameOf(ls.b))}: ` +
      (n ? `${n} tren, ${free ? `${free} tanesinde yer var` : 'hepsi dolu'}.` : 'sefer yok.');
    const opened = changes.filter((c) => c.from === 0 && c.to > 0).length;
    if (opened) t += ` ${opened} seferde yer açıldı.`;
    if (ui.fillMsg) return `${t} ${ui.fillMsg}`;
    const m = model();
    if (m.j && partOfJourney(ls)) {
      t += ` ${m.routes.length ? `${m.routes.length} rota bulundu.` : 'Henüz rota yok.'}`;
      if (!m.next) t += ' Tüm aramalar tamam.';
      else if (!ui.paused) t += ` Sıradaki arama: ${title(nameOf(m.next.a))} → ${title(nameOf(m.next.b))}.`;
    }
    return t;
  }

  /* ------------------------------------------------------------------ *
   *  JOURNEY                                                            *
   * ------------------------------------------------------------------ */
  const J = () => store.journey;
  // The journey the panel works on: a stored one counts once you search it again.
  const liveJ = () => (ui.live && J() ? J() : null);
  const sameJourney = (ls) => !!(J() && J().o === ls.a && J().d === ls.b && J().day === ls.day);
  const onLine = (ls) => { const st = journeyStations(), i = st.indexOf(ls.a); return i >= 0 && st.indexOf(ls.b) > i; };
  // One of the journey's pieces (or the journey itself), on its day.
  const partOfJourney = (ls) => !!(J() && J().day === ls.day && onLine(ls));
  // The journey's stations searched on another day.
  const onJourneyLine = (ls) => !!(J() && J().day !== ls.day && onLine(ls));

  // Start the searches for a trip: every departure of the search counts, or
  // those in the departure-time range kept from the same trip before.
  function startJourney(ls) {
    const old = sameJourney(ls) ? J() : null;
    const j = { o: ls.a, d: ls.b, day: ls.day, range: (old && old.range) || null, again: (old && old.again) || [], trains: [], trainStops: {}, deps: {}, ts: Date.now() };
    for (const t of ls.trains) {
      j.trains.push(t.id);
      j.trainStops[t.id] = stopsOf(t).map((s) => ({ id: s.id, name: s.name }));
      j.deps[t.id] = depOf(t);
    }
    store.journey = j;
    Object.assign(ui, { live: true, paused: false, rangeEdit: null, tab: null, fill: null, fillMsg: '', lastFilledKey: null });
  }

  // Departure-time range, "HH:MM" to "HH:MM" (Turkey time); over midnight if from > to.
  const minOf = (hm) => { const [x, y] = String(hm).split(':').map(Number); return x * 60 + y; };
  function inRange(ms, r) {
    if (!r) return true;
    const x = minOf(fmtTime(ms)), f = minOf(r.from), t = minOf(r.to);
    return f <= t ? x >= f && x <= t : x >= f || x <= t;
  }
  const rangeText = (r) => (r ? `${r.from}–${r.to} arası` : 'tüm gün');

  // Ordered station list of the journey, merged from all ticked trains.
  function journeyStations() {
    const j = J();
    let list = [];
    for (const id of j.trains) {
      const stops = j.trainStops[id] || [];
      if (stops.length > list.length) list = stops.map((s) => s.id);
    }
    for (const id of j.trains) {
      const stops = (j.trainStops[id] || []).map((s) => s.id);
      stops.forEach((sid, k) => {
        if (list.includes(sid)) return;
        const prev = stops.slice(0, k).reverse().find((x) => list.includes(x));
        list.splice(prev == null ? 0 : list.indexOf(prev) + 1, 0, sid);
      });
    }
    return list;
  }

  /* ------------------------------------------------------------------ *
   *  ROUTES — all itineraries from known pairs                          *
   *  The first ticket leaves within the departure range. A change needs *
   *  minTransfer..maxWait minutes; continuing on the same train is a    *
   *  seat change at the stop (no wait).                                 *
   * ------------------------------------------------------------------ */
  function buildEdges(stations) {
    const idx = new Map(stations.map((s, i) => [s, i]));
    const from = new Map();
    for (const [k, raw] of Object.entries(store.pairs)) {
      const p = seatsOf(raw);
      if (!(p.usable > 0) || p.dep == null || p.arr == null) continue;
      const m = k.match(/^(\d+)\|(\d+)>(\d+)$/);
      if (!m) continue;
      const train = +m[1], a = +m[2], b = +m[3];
      if (!idx.has(a) || !idx.has(b) || idx.get(a) >= idx.get(b)) continue;
      const e = { train, a, b, dep: p.dep, arr: p.arr, price: p.price, cls: p.cls, seats: p.usable, ts: p.ts };
      if (!from.has(a)) from.set(a, []);
      from.get(a).push(e);
    }
    return from;
  }

  // A first leg must leave the origin within the departure-time range.
  const firstLegOk = (e) => inRange(e.dep, J().range);

  function findRoutes() {
    const j = J();
    const stations = journeyStations();
    const edges = buildEdges(stations);
    const routes = [];
    const sameTrainDirect = (x, y) => {
      const p = seatsOf(store.pairs[pairKey(x.train, x.a, y.b)]);
      return p && p.usable > 0;
    };
    const dfs = (st, arrT, last, legs) => {
      if (st === j.d) { routes.push(legs); return; }
      if (legs.length >= CFG.maxLegs || routes.length > 400) return;
      for (const e of edges.get(st) || []) {
        if (!legs.length) { if (!firstLegOk(e)) continue; }
        else if (e.train === last.train) {
          if (e.dep < arrT - 60000) continue;
          if (sameTrainDirect(last, e)) continue; // a single ticket covers it
        } else {
          const w = e.dep - arrT;
          if (w < CFG.minTransferMin * 60000 || w > CFG.maxWaitMin * 60000) continue;
        }
        dfs(e.b, e.arr, e, legs.concat(e));
      }
    };
    dfs(j.o, null, null, []);
    return { stations, routes: routes.map(summarize) };
  }

  function summarize(legs) {
    const prices = legs.map((l) => l.price);
    return {
      legs,
      dep: legs[0].dep,
      arr: legs[legs.length - 1].arr,
      price: prices.includes(null) ? null : prices.reduce((s, x) => s + x, 0),
      tickets: legs.length,
      changes: legs.filter((l, i) => i && l.train !== legs[i - 1].train).length,
      seats: Math.min(...legs.map((l) => l.seats)),
      checked: Math.min(...legs.map((l) => l.ts || 0)),
    };
  }

  const SORTS = {
    price: { label: 'En ucuz', fn: (x, y) => (x.price ?? 1e12) - (y.price ?? 1e12) || x.arr - y.arr },
    arr: { label: 'En erken varış', fn: (x, y) => x.arr - y.arr || (x.price ?? 1e12) - (y.price ?? 1e12) },
    tickets: { label: 'En az bilet', fn: (x, y) => x.tickets - y.tickets || x.changes - y.changes || (x.price ?? 1e12) - (y.price ?? 1e12) },
  };

  // ebilet's own list of the pairs it sells, which the site keeps in
  // localStorage ("vuex" → station.fromToStations[].pairs: the stations each
  // one sells tickets to). Read only, never fetched. Without it every pair counts.
  const sold = { at: 0, map: null };
  function soldMap() {
    if (sold.map || Date.now() - sold.at < 30000) return sold.map;
    sold.at = Date.now();
    try {
      const v = JSON.parse(localStorage.getItem('vuex') || 'null');
      const list = v && v.station && v.station.fromToStations;
      const map = new Map();
      for (const s of Array.isArray(list) ? list : []) {
        if (Array.isArray(s.pairs) && s.pairs.length) map.set(Number(s.id), new Set(s.pairs.map(Number)));
      }
      if (map.size) sold.map = map;
    } catch (e) { /* not there or not JSON */ }
    return sold.map;
  }
  const sells = (a, b) => { const m = soldMap(), to = m && m.get(Number(a)); return !to || to.has(Number(b)); };

  // Does this train already have a route from o to d on its own (seat changes only)?
  function ownRoute(all, o, d, free) {
    const stops = all.slice(Math.max(0, all.indexOf(o)));
    const legs = new Map([[o, 0]]);
    for (let i = 0; i < stops.length; i++) {
      if (!legs.has(stops[i])) continue;
      for (let k = i + 1; k < stops.length; k++) {
        const n = legs.get(stops[i]) + 1;
        if (free(stops[i], stops[k]) && !(legs.get(stops[k]) <= n)) legs.set(stops[k], n);
      }
    }
    return legs.get(d) <= CFG.maxLegs;
  }

  // Next search: first the pairs asked for again (Tekrar kontrol et, Tekrar
  // dene) and the trip itself; then only for the trains still full (no route
  // on the same train), each with its own stops:
  //   1. origin → a stop, farthest stop first; right after it that stop →
  //      destination, if a full train has a seat on the first piece (2 tickets);
  //   2. later stops → destination, for full trains that can leave the origin;
  //   3. the middle piece between the two (3 tickets).
  // Pairs ebilet does not sell are left out; one search answers for every train.
  // left counts what is planned now: it shrinks as the pieces come in.
  function nextSearch(found) {
    const j = J(), o = j.o, d = j.d;
    const asked = (a, b) => !!store.searched[searchedKey(a, b, j.day)];
    // seats count once the pair is searched (again): after a re-check old ones do not
    const free = (t) => (a, b) => { const p = asked(a, b) && seatsOf(store.pairs[pairKey(t, a, b)]); return !!(p && p.usable > 0); };
    const stops = new Map(j.trains.map((t) => [t, (j.trainStops[t] || []).map((s) => s.id)]));
    const full = j.trains.filter((t) => inRange(j.deps[t], j.range) && stops.get(t).length > 1 && !ownRoute(stops.get(t), o, d, free(t)));
    const plan = [];
    const add = (a, b, ready, any) => {
      if (a !== b && !asked(a, b) && (any || sells(a, b)) && !plan.some((x) => x.a === a && x.b === b)) plan.push({ a, b, ready });
    };
    for (const [a, b] of (j.again || []).concat([[o, d]])) add(a, b, true, true);
    const mids = found.stations.filter((m) => m !== o && m !== d).reverse();
    const at = (m) => full.filter((t) => stops.get(t).includes(m));
    for (const m of mids) {
      if (!at(m).length || !sells(o, m)) continue;
      if (!asked(o, m)) { add(o, m, true); add(m, d, false); }
      else if (at(m).some((t) => free(t)(o, m))) add(m, d, true);
    }
    const ends = full.map((t) => {
      const st = stops.get(t), f = free(t);
      return { st, A: st.filter((x) => x !== o && x !== d && f(o, x)), B: st.filter((x) => x !== o && x !== d && f(x, d)) };
    });
    for (const m of mids) {
      if (ends.some(({ st, A }) => st.includes(m) && A.some((a) => st.indexOf(a) < st.indexOf(m)))) add(m, d, true);
    }
    for (const { st, A, B } of ends) for (const a of A) for (const b of B) if (st.indexOf(a) < st.indexOf(b)) add(a, b, true);
    const next = plan.find((x) => x.ready) || null;
    return { next: next && { a: next.a, b: next.b }, left: next ? plan.length : 0 };
  }

  /* ------------------------------------------------------------------ *
   *  FORM PREFILL — writes from/to into the site's own form and focuses *
   *  its search button. Never clicks it: each search starts with your   *
   *  own Enter/click, so the site's Turnstile check sees you.           *
   * ------------------------------------------------------------------ */
  const normName = (s) => String(s).toLocaleUpperCase('tr-TR').replace(/\s+/g, ' ').trim();
  function setInput(el, v) {
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, v);
    el.dispatchEvent(new Event('input', { bubbles: true }));
    el.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'a' }));
  }
  const visible = (e) => e && e.offsetParent !== null;
  function findToggle(kind) {
    const byId = document.getElementById(kind === 'from' ? 'fromTrainInput' : 'toTrainInput');
    if (visible(byId)) return byId;
    const nm = kind === 'from' ? 'Tren kalkış' : 'Tren varış';
    return [...document.querySelectorAll(`input[name="${nm}"]`)].find(visible) || null;
  }
  function findSearchButton() {
    const byId = document.getElementById('searchSeferButton');
    if (visible(byId)) return byId;
    return [...document.querySelectorAll('button')].find((b) => visible(b) && /^(sefer ara|ara)$/i.test(b.innerText.trim())) || null;
  }
  // 'ok', 'missing' (the station is not in ebilet's list) or 'noform'.
  async function pickStation(kind, name) {
    const toggle = findToggle(kind);
    if (!toggle) return 'noform';
    if (normName(toggle.value).startsWith(normName(name) + ' ,')) return 'ok';
    const wrap = toggle.closest('.dropdown') || toggle.parentElement;
    if (!wrap.classList.contains('show')) { toggle.click(); await sleep(300); }
    const search = [...wrap.querySelectorAll('input')].find((e) => e !== toggle && e.type === 'text');
    if (!search) return 'noform';
    setInput(search, name);
    for (let i = 0; i < 25; i++) {
      await sleep(150);
      const btn = [...wrap.querySelectorAll('button.dropdown-item')].find((b) => {
        const m = normName(b.innerText).match(/^(?:İSTASYON )?(.+?) ,/);
        return m && m[1] === normName(name);
      });
      if (btn) { btn.click(); await sleep(300); return 'ok'; }
    }
    // leave the list empty and closed for the next search
    setInput(search, '');
    search.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));
    return 'missing';
  }
  // Stations already missing from ebilet's list on this day: their other searches are skipped at once.
  const missingStations = (day) => new Set(Object.entries(store.missed).filter(([k]) => k.endsWith('|' + day)).map(([, st]) => st));
  // A station that ebilet's list does not have: skip the search and carry on; the done step lists it.
  function skipMissing(a, b, st) {
    const day = J().day, k = searchedKey(a, b, day);
    store.searched[k] = Date.now();
    store.missed[k] = st;
    addLog({ a, b, day, kind: 'missed', st });
    Object.assign(ui, { fill: null, fillMsg: '', lastFilledKey: null });
    save(); render();
    const m = model();
    announce(`${title(nameOf(st))} ebilet'in istasyon listesinde yok, ${title(nameOf(a))} → ${title(nameOf(b))} araması atlandı.` +
      (m.phase === 'done' ? ' Aramalar bitti.' : ''));
  }
  async function prefill(a, b, retry) {
    const key = `${a}>${b}|${J().day}`;
    const current = () => ui.fill && ui.fill.key === key && !ui.paused;
    const gone = missingStations(J().day);
    if (gone.has(a) || gone.has(b)) return skipMissing(a, b, gone.has(a) ? a : b);
    ui.fill = { key, a, b, st: 'filling' };
    ui.fillMsg = '';
    render();
    let res = await pickStation('from', nameOf(a)), bad = a;
    if (res === 'ok') { res = await pickStation('to', nameOf(b)); bad = b; }
    if (!current()) return;   // paused, skipped or searched meanwhile
    if (res === 'missing') return skipMissing(a, b, bad);
    const ok = res === 'ok';
    const sb = ok ? findSearchButton() : null;
    ui.fill = { key, a, b, st: ok ? 'ready' : 'failed', btn: sb, away: !sb };
    if (sb) { watchButton(sb); sb.focus(); }
    render();
    const route = `${title(nameOf(a))} → ${title(nameOf(b))}`, day = ` Tarih ${fmtDay(J().day)} olmalı.`;
    announce(ok ? `Form hazır: ${route}. Şimdi Enter tuşuna bas.${day}`
      : `ebilet'in arama formu bu sayfada görünmüyor. Form görününce Formu doldur'a bas ya da bu aramayı kendin yap: ${route}.${day}`, !ok);
    if (ok && !retry) {
      await sleep(1500);
      if (!current() || ui.fill.st !== 'ready') return;
      const f = findToggle('from'), t = findToggle('to');
      const holds = (el, name) => el && normName(el.value).startsWith(normName(name) + ' ,');
      if (!holds(f, nameOf(a)) || !holds(t, nameOf(b))) { log('form was reset by the site, refilling'); prefill(a, b, true); }
    }
  }
  function maybeAutoFill(nx) {
    if (!CFG.autoFill || !nx) return;
    const key = `${nx.a}>${nx.b}|${J().day}`;
    if (ui.lastFilledKey === key) return;
    ui.lastFilledKey = key;
    ui.fill = { key, a: nx.a, b: nx.b, st: 'filling' };
    setTimeout(() => { if (ui.fill && ui.fill.key === key && ui.fill.st === 'filling' && !ui.paused) prefill(nx.a, nx.b); }, 900);
  }

  // The focused search button: the spotlight follows its focus, and a click
  // (Enter on it is a click) means the search is on its way. Only the text
  // box and the spotlight are updated here, never the whole panel: a redraw
  // on blur would remove a panel button between its mousedown and click.
  let unwatch = null;
  function watchButton(sb) {
    if (unwatch) unwatch();
    const mine = () => ui.fill && ui.fill.btn === sb;
    const away = (v) => () => { if (mine() && ui.fill.st === 'ready' && ui.fill.away !== v) { ui.fill.away = v; refreshDo(); } };
    const ev = {
      focus: away(false),
      blur: away(true),
      click: () => { if (mine() && ui.fill.st === 'ready') { ui.fill.st = 'searching'; refreshDo(); } },
    };
    for (const [k, f] of Object.entries(ev)) sb.addEventListener(k, f);
    unwatch = () => { for (const [k, f] of Object.entries(ev)) sb.removeEventListener(k, f); unwatch = null; };
  }

  /* ------------------------------------------------------------------ *
   *  SPOTLIGHT — while the form waits for Enter, the page is dimmed      *
   *  except ebilet's search button, with "Ara · Enter" next to it. It    *
   *  lets clicks through and goes away when the button loses focus.      *
   * ------------------------------------------------------------------ */
  let spotFor = null;
  function syncSpot() {
    if (!spot) return;
    const f = ui.fill;
    const on = !!(f && f.st === 'ready' && !f.away && f.btn && f.btn.isConnected && liveJ() && !ui.paused && !ui.collapsed && !ui.settings);
    spotFor = on ? f.btn : null;
    spot.dataset.on = on ? '1' : '';
    if (on) placeSpot(); else spot.hidden = true;
  }
  function placeSpot() {
    if (!spotFor) return;
    const r = spotFor.getBoundingClientRect();
    if (!r.width || !r.height) { spot.hidden = true; return; }
    const pad = 6;
    Object.assign(spot.style, { left: `${r.left - pad}px`, top: `${r.top - pad}px`, width: `${r.width + 2 * pad}px`, height: `${r.height + 2 * pad}px` });
    spot.firstChild.classList.toggle('up', r.bottom + 80 > window.innerHeight);
    spot.hidden = false;
  }
  const followSpot = () => { if (spotFor) requestAnimationFrame(placeSpot); };
  window.addEventListener('scroll', followSpot, true);
  window.addEventListener('resize', followSpot);

  /* ------------------------------------------------------------------ *
   *  SEAT MAP — generic parse of whatever the site loads                *
   * ------------------------------------------------------------------ */
  const SEATNUM_KEYS = ['seatNumber', 'seatNo', 'koltukNo', 'number', 'name'];
  const CAR_KEYS = ['carName', 'carNo', 'carIndex', 'carNumber', 'vagonNo'];
  const POS_KEYS = ['available', 'isAvailable', 'selectable', 'isSelectable', 'empty', 'isEmpty'];
  const NEG_KEYS = ['reserved', 'isReserved', 'locked', 'isLocked', 'sold', 'isSold', 'occupied', 'allocated'];
  const STATUS_KEYS = ['status', 'state', 'seatStatus', 'durum'];
  const FREE_RE = /^(available|empty|free|bos|boş|musait|müsait)$/i;
  const OCC_RE = /(reserved|sold|occupied|dolu|taken|locked|rezerve|allocated)/i;
  const DIS_RE = /engel|tekerlek|wheelchair|\bdsb\b/i;

  function extractSeats(resp) {
    const cars = new Map(), dis = new Map();
    let free = 0, disabled = 0, unknown = 0;
    const cls = (o) => {
      for (const k of POS_KEYS) if (o[k] === true) return 'free';
      for (const k of NEG_KEYS) if (o[k] === true) return 'occ';
      for (const k of POS_KEYS) if (o[k] === false) return 'occ';
      for (const k of STATUS_KEYS) if (k in o) {
        const v = o[k];
        if (v === 0 || v === '0') return 'free';
        if (typeof v === 'string') { if (FREE_RE.test(v)) return 'free'; if (OCC_RE.test(v)) return 'occ'; }
        if (typeof v === 'number') return 'occ';
      }
      return 'unknown';
    };
    const looksDis = (o) => Object.entries(o).some(([k, v]) =>
      (typeof v === 'string' && DIS_RE.test(v)) || (v === true && DIS_RE.test(k)) ||
      (v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).some((x) => typeof x === 'string' && DIS_RE.test(x))));
    const walk = (o, car) => {
      if (!o || typeof o !== 'object') return;
      if (Array.isArray(o)) { o.forEach((x) => walk(x, car)); return; }
      for (const k of CAR_KEYS) if (typeof o[k] === 'number' || typeof o[k] === 'string') { car = String(o[k]); break; }
      const nk = SEATNUM_KEYS.find((k) => typeof o[k] === 'string' || typeof o[k] === 'number');
      if (nk && POS_KEYS.concat(NEG_KEYS, STATUS_KEYS).some((k) => k in o)) {
        const c = cls(o);
        if (c === 'free') {
          const m = looksDis(o) ? dis : cars;
          if (m === dis) disabled++; else free++;
          const key = car || '?';
          if (!m.has(key)) m.set(key, []);
          m.get(key).push(String(o[nk]));
        } else if (c === 'unknown') unknown++;
        return;
      }
      Object.values(o).forEach((v) => walk(v, car));
    };
    walk(resp, null);
    return { cars, dis, free, disabled, unknown };
  }

  function onSeatMap(resp) {
    const seats = extractSeats(resp);
    if (!seats.free && !seats.disabled && !seats.unknown) return;
    state.lastSeat = { seats, raw: resp, ts: Date.now() };
    render();
  }

  /* ------------------------------------------------------------------ *
   *  PANEL — rendered inside a shadow root so ebilet's own CSS cannot   *
   *  touch it. Layout: header • next-step card • tabs (Rotalar /        *
   *  Seferler / Geçmiş) • scrollable body. Collapses to a summary pill. *
   * ------------------------------------------------------------------ */
  const SETTINGS_KEYS = ['minTransferMin', 'maxWaitMin', 'autoFill', 'speak', 'includeDisabled'];
  store.settings = store.settings || {};
  for (const k of SETTINGS_KEYS) if (k in store.settings) CFG[k] = store.settings[k];
  const prefs = (() => { try { return JSON.parse(localStorage.getItem(CFG.storeKey + '.ui')) || {}; } catch (e) { return {}; } })();
  const savePrefs = () => { try { localStorage.setItem(CFG.storeKey + '.ui', JSON.stringify({ collapsed: ui.collapsed })); } catch (e) { /* ignore */ } };
  ui.collapsed = !!prefs.collapsed;
  ui.tab = null;          // 'routes' | 'trains' | 'log'; null = Rotalar
  ui.settings = false;

  const CSS = `
:host{all:initial}
*{box-sizing:border-box;min-width:0}
.sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
h2,h3,h4{margin:0;font:inherit}
.card,.pill{font:14px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#111827;-webkit-font-smoothing:antialiased}
.card,.pill{position:relative;z-index:1}
.card{width:min(410px,calc(100vw - 24px));max-height:min(760px,calc(100vh - 24px));display:flex;flex-direction:column;background:#fff;border:1px solid #e5e7eb;border-radius:18px;box-shadow:0 20px 50px rgba(17,24,39,.22),0 2px 6px rgba(17,24,39,.08);overflow:hidden}
.pill{display:flex;align-items:center;gap:10px;background:#111827;color:#fff;border:0;border-radius:999px;padding:10px 16px 10px 12px;box-shadow:0 10px 30px rgba(17,24,39,.3);cursor:pointer;font-weight:600}
.pill small{font-weight:400;color:#d1d5db}
header{display:flex;align-items:center;gap:10px;padding:12px 12px 12px 14px;border-bottom:1px solid #f0f1f3}
header .t{flex:1}
header h2{display:block;font-size:15px;font-weight:700}
header h2:focus{outline:none}
header span{display:block;color:#6b7280;font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.icon{width:34px;height:34px;border-radius:10px;border:0;background:transparent;color:#374151;font-size:17px;cursor:pointer;display:grid;place-items:center}
.icon:hover{background:#f3f4f6}
button{font:inherit}
.btn{border:1px solid #d1d5db;background:#fff;color:#111827;border-radius:10px;padding:7px 12px;min-height:36px;font-weight:600;font-size:13.5px;cursor:pointer;white-space:nowrap}
.btn:hover{background:#f9fafb}
.btn.primary{background:#e30a17;border-color:#e30a17;color:#fff}
.btn.primary:hover{background:#c80814}
.btn.link{border:0;background:none;color:#e30a17;padding:4px 0;min-height:0}
.btn:focus-visible,.icon:focus-visible,.tab:focus-visible,.row:focus-visible,.pill:focus-visible,.seg button:focus-visible,.body:focus-visible,.set input:focus-visible{outline:2px solid #e30a17;outline-offset:2px}
.next{margin:12px 12px 0;padding:12px;border-radius:14px;background:#fef2f2;border:1px solid #fecaca}
.next.done{background:#ecfdf5;border-color:#a7f3d0}
.next .lab{font-size:12px;color:#991b1b;font-weight:600}
.next.done .lab{color:#065f46}
.next .route{font-size:16px;font-weight:700;margin:2px 0 8px}
.bar{height:6px;border-radius:3px;background:rgba(17,24,39,.08);overflow:hidden;margin-bottom:10px}
.bar i{display:block;height:100%;background:#e30a17;border-radius:3px}
.next.done .bar i{background:#0a8a4a}
.acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.msg{margin-top:8px;font-size:12.5px;color:#4b5563}
.msg.err{color:#b45309}
.next.guide,.next.paused{background:#f9fafb;border-color:#e5e7eb}
.next.paused .lab,.next.guide .lab{color:#374151}
.ask{font-size:13.5px;color:#374151;margin:2px 0 10px}
.ask b{display:block;font-size:16px;color:#111827;margin-bottom:2px}
.steps{display:flex;gap:6px;list-style:none;margin:0 0 10px;padding:0;font-size:12px;color:#6b7280}
.steps li{flex:1;display:flex;align-items:center;gap:6px}
.steps i{flex:none;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-style:normal;font-weight:700;background:#e5e7eb;color:#374151}
.steps .on{color:#111827;font-weight:600}
.steps .on i{background:#e30a17;color:#fff}
.steps .ok i{background:#0a8a4a;color:#fff}
.do{margin:0 0 10px;padding:10px 12px;border-radius:12px;background:#fff;border:1px solid #fecaca;font-size:13px;color:#374151}
.do b{display:block;font-size:15px;color:#111827;margin-bottom:2px}
.do.go{background:#111827;border-color:#111827;color:#d1d5db}
.do.go b{color:#fff;font-size:18px}
.do.err{background:#fffbeb;border-color:#fde68a;color:#78350f}
.do.err b{color:#78350f}
kbd{font:inherit;font-weight:700;border:1.5px solid currentColor;border-bottom-width:3px;border-radius:6px;padding:0 6px}
.spot{position:fixed;z-index:0;pointer-events:none;border-radius:12px;box-shadow:0 0 0 4px #38d39f,0 0 0 200vmax rgba(17,24,39,.55)}
.spot[hidden]{display:none}
.tip{position:absolute;left:50%;top:calc(100% + 12px);transform:translateX(-50%);background:#38d39f;color:#052e16;padding:7px 14px;border-radius:10px;font:600 15px/1.3 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;white-space:nowrap;box-shadow:0 8px 24px rgba(0,0,0,.3)}
.tip.up{top:auto;bottom:calc(100% + 12px)}
.tip kbd{border-color:#052e16}
.tabs{display:flex;gap:4px;margin:12px 12px 0;padding:4px;background:#f3f4f6;border-radius:12px}
.tab{flex:1;border:0;background:transparent;border-radius:9px;padding:7px 4px;font-weight:600;font-size:13.5px;color:#4b5563;cursor:pointer}
.tab[aria-selected=true]{background:#fff;color:#111827;box-shadow:0 1px 3px rgba(0,0,0,.12)}
.tab em{font-style:normal;font-size:11.5px;background:#e30a17;color:#fff;border-radius:999px;padding:0 6px;margin-left:4px}
.body{overflow:auto;padding:12px 12px 14px;flex:1}
.sec{font-size:12px;font-weight:600;color:#6b7280;margin:4px 0 6px}
.empty{padding:22px 10px;text-align:center;color:#6b7280}
.empty b{display:block;color:#111827;font-size:15px;margin-bottom:4px}
.warnbox{padding:10px 12px;border-radius:12px;background:#fffbeb;border:1px solid #fde68a;color:#78350f;font-size:13px}
.warnbox b{display:block;margin-bottom:4px}
.next .warnbox.miss{margin-top:10px}
.target{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid #e5e7eb;border-radius:12px;margin-bottom:6px}
.target .tm{font-weight:700;font-size:16px;font-variant-numeric:tabular-nums}
.target .st{flex:1;font-size:13px}
.ok{color:#0a8a4a}.wait{color:#6b7280}.bad{color:#b45309}
.seg{display:flex;gap:4px;margin:12px 0 8px;flex-wrap:wrap}
.seg button{border:1px solid #e5e7eb;background:#fff;border-radius:999px;padding:5px 11px;min-height:32px;font-size:12.5px;font-weight:600;color:#374151;cursor:pointer}
.seg button[aria-pressed=true]{background:#111827;border-color:#111827;color:#fff}
.rc{border:1px solid #e5e7eb;border-radius:14px;padding:12px;margin-bottom:8px}
.rc.best{border-color:#0a8a4a;box-shadow:0 0 0 1px #0a8a4a inset}
.rh{font-weight:400;display:flex;align-items:baseline;justify-content:space-between;gap:8px}
.price{font-size:20px;font-weight:800;color:#0a8a4a;letter-spacing:-.01em}
.times{font-weight:700;font-variant-numeric:tabular-nums}
.meta{color:#6b7280;font-size:12.5px;margin:2px 0 8px}
.tl{position:relative;margin-left:6px;padding-left:16px;border-left:2px solid #e5e7eb}
.stop{position:relative;padding:3px 0;display:flex;justify-content:space-between;gap:8px;font-size:13.5px}
.stop::before{content:"";position:absolute;left:-22px;top:8px;width:10px;height:10px;border-radius:50%;background:#fff;border:2px solid #111827}
.stop .c{color:#6b7280;font-size:12.5px;white-space:nowrap}
.xfer{margin:3px 0;padding:4px 8px;border-radius:8px;font-size:12.5px;background:#fff7ed;color:#9a3412}
.xfer.same{background:#eff6ff;color:#1e40af}
.rf{display:flex;justify-content:space-between;align-items:center;margin-top:8px;font-size:12px;color:#6b7280}
.rf.stale{color:#b45309}
.row{display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:12px;cursor:pointer;border:1px solid transparent}
.row:hover{background:#f9fafb}
.row.on{background:#fef2f2;border-color:#fecaca}
.row.static{cursor:default}
.row.dim{opacity:.5}
.rng{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:8px;font-size:12.5px;color:#4b5563}
.rng.edit{display:block;padding:10px;border:1px solid #e5e7eb;border-radius:12px;background:#fff}
.rng.edit label{display:inline-flex;flex-direction:column;gap:2px;margin:0 10px 8px 0;font-size:12px;color:#4b5563}
.rng input{font:inherit;font-size:16px;padding:4px 6px;border:1px solid #d1d5db;border-radius:8px}
.rng input:focus-visible{outline:2px solid #e30a17;outline-offset:2px}
.box{width:20px;height:20px;border-radius:6px;border:2px solid #d1d5db;flex:none;display:grid;place-items:center;color:#fff;font-size:13px;font-weight:800}
.row.on .box{background:#e30a17;border-color:#e30a17}
.row .tm{font-weight:700;font-variant-numeric:tabular-nums;flex:1}
.badge{font-size:12.5px;font-weight:600;border-radius:999px;padding:2px 9px;white-space:nowrap}
.badge.free{background:#ecfdf5;color:#065f46}
.badge.full{background:#f3f4f6;color:#4b5563}
.note{font-size:12px;color:#6b7280;margin:6px 2px}
.log{padding:7px 0;border-bottom:1px solid #f3f4f6;font-size:13px}
.log .w{color:#6b7280;font-variant-numeric:tabular-nums;margin-right:6px}
.chg{font-size:12.5px;padding-left:44px}
.set label{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid #f3f4f6}
.set input[type=number]{width:84px;font:inherit;font-size:16px;padding:5px 8px;border:1px solid #d1d5db;border-radius:8px;text-align:right}
.set small{display:block;color:#6b7280;font-size:12px}
.seats div{font-size:13px;padding:2px 0}
`;

  // Shadow root layout: <style>, two live regions that stay put (so screen
  // readers hear what is written into them), and `view`, redrawn by render().
  let host, root, view, liveEl, alertEl, spot;
  function ensurePanel() {
    if (host && document.body && document.body.contains(host)) return true;
    if (!document.body) return false;
    host = document.createElement('div');
    host.id = 'tcdd-split-panel';
    host.lang = 'tr';
    host.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:2147483647;';
    root = host.attachShadow({ mode: 'open' });
    root.appendChild(h('style', null, CSS));
    liveEl = h('div', 'sr');
    liveEl.setAttribute('role', 'status');
    liveEl.setAttribute('aria-live', 'polite');
    alertEl = h('div', 'sr');
    alertEl.setAttribute('role', 'alert');
    spot = h('div', 'spot', '<div class="tip" aria-hidden="true"><b>Ara</b> · <kbd>Enter</kbd> tuşuna bas</div>');
    spot.hidden = true;
    view = h('div');
    root.append(liveEl, alertEl, spot, view);
    document.body.appendChild(host);
    return true;
  }

  /* ------------------------------------------------------------------ *
   *  ANNOUNCEMENTS — live region for screen readers; optional speech    *
   *  with a voice that runs on this device (no text leaves the browser) *
   * ------------------------------------------------------------------ */
  function announce(text, urgent) {
    if (!text || !ensurePanel()) return;
    const el = urgent ? alertEl : liveEl;
    el.textContent = '';
    setTimeout(() => { el.textContent = text; }, 60);  // cleared first, so a repeated message is read again
    if (CFG.speak) say(text);
  }
  function trVoice() {
    const ss = window.speechSynthesis;
    if (!ss || !window.SpeechSynthesisUtterance) return null;
    return ss.getVoices().find((v) => /^tr\b/i.test(v.lang) && v.localService) || null;
  }
  function say(text) {
    const v = trVoice();
    if (!v) return false;
    const u = new window.SpeechSynthesisUtterance(String(text).replace(/\s*→\s*/g, ', '));
    u.voice = v;
    u.lang = v.lang;
    window.speechSynthesis.cancel();
    window.speechSynthesis.speak(u);
    return true;
  }
  if (window.speechSynthesis && window.speechSynthesis.addEventListener) {
    window.speechSynthesis.addEventListener('voiceschanged', () => { if (ui.settings) render(); });
  }

  // Alt+Shift+K: open the panel and put the keyboard focus in it.
  document.addEventListener('keydown', (e) => {
    if (!(e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && e.code === 'KeyK')) return;
    e.preventDefault();
    ui.collapsed = false;
    savePrefs();
    ui.focusKey = '@primary';   // the main button of the step you are on
    render();
  }, true);
  const esc = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  const h = (tag, cls, html) => { const e = document.createElement(tag); if (cls) e.className = cls; if (html != null) e.innerHTML = html; return e; };
  // Every button carries data-k, a key that survives a redraw, so render()
  // can give the keyboard focus back to the same control.
  const button = (label, cls, fn, attrs) => {
    const b = h('button', cls, label);
    b.type = 'button';
    b.dataset.k = `${cls}:${b.textContent}`;
    for (const [k, v] of Object.entries(attrs || {})) b.setAttribute(k, v);
    b.addEventListener('click', (e) => { e.stopPropagation(); fn(); });
    return b;
  };

  // The panel shows one step at a time:
  //   start   nothing searched yet in this page: how it works
  //   run     the searches: only the next one and what to do now
  //   paused  searches on hold: routes, departures and history
  //   done    every piece searched: routes, departures and history
  function model() {
    const j = liveJ();
    const found = j ? findRoutes() : null;
    const routes = found ? found.routes.slice().sort(SORTS[ui.sort].fn) : [];
    const ns = found ? nextSearch(found) : { next: null, left: 0 };
    let done = 0;
    if (found) {
      const st = found.stations;
      for (let i = 0; i < st.length - 1; i++) for (let k = i + 1; k < st.length; k++) if (store.searched[searchedKey(st[i], st[k], j.day)]) done++;
    }
    const m = { j, found, routes, next: ns.next, left: ns.left, done };
    m.phase = !j ? 'start' : !m.next ? 'done' : ui.paused ? 'paused' : 'run';
    return m;
  }

  function render() {
    if (!ensurePanel()) { document.addEventListener('DOMContentLoaded', render, { once: true }); return; }
    const m = model();
    // the next search goes into the form only while the searches run
    if (m.phase === 'run' && !ui.collapsed && !ui.settings) maybeAutoFill(m.next);
    if (m.phase !== 'run' && unwatch) unwatch();
    const prevBody = view.querySelector('.body');
    const scroll = prevBody ? prevBody.scrollTop : 0;
    // Focus is given back only if it was in the panel (or asked for): a
    // redraw after a search must not pull it away from ebilet's form.
    const active = root.activeElement;
    const want = ui.focusKey || (active ? (active.dataset && active.dataset.k) || '-' : null);
    ui.focusKey = null;
    view.innerHTML = '';
    const body = draw(m);
    if (body) body.scrollTop = scroll;
    if (want) {
      const el = (want === '@primary' && (view.querySelector('.next .btn.primary') || view.querySelector('.next .btn'))) ||
        [...view.querySelectorAll('[data-k]')].find((e) => e.dataset.k === want) || view.querySelector('.pill, h2');
      if (el) el.focus({ preventScroll: true });
    }
    syncSpot();
  }
  // Redraw only the "what to do now" box (focus changes on ebilet's button).
  function refreshDo() {
    const old = view && view.querySelector('.next .do');
    if (old) old.replaceWith(doBox());
    syncSpot();
  }

  function draw(m) {
    if (ui.collapsed) { view.appendChild(pill(m)); return null; }
    const card = h('section', 'card');
    card.setAttribute('aria-label', 'Bilet Bul');
    card.appendChild(header(m));
    view.appendChild(card);
    if (ui.settings) {
      const b = h('div', 'body');
      b.appendChild(settingsView());
      card.appendChild(b);
      return b;
    }
    card.appendChild(nextCard(m));
    if (m.phase === 'start') {
      const v = seatsBlock(h('div'));
      if (!v.childNodes.length) return null;
      const b = h('div', 'body');
      b.appendChild(v);
      card.appendChild(b);
      return b;
    }
    if (m.phase === 'run') return null;   // while searching, only the next step
    const tab = ui.tab || 'routes';
    const tabs = h('div', 'tabs');
    tabs.setAttribute('role', 'tablist');
    tabs.setAttribute('aria-label', 'Panel bölümleri');
    const defs = [['routes', 'Rotalar', m.routes.length], ['trains', 'Seferler', 0], ['log', 'Geçmiş', 0]];
    const go = (id) => { ui.tab = id; ui.focusKey = 'tab:' + id; render(); };
    for (const [id, label, n] of defs) {
      tabs.appendChild(button(`${label}${n ? `<em>${n}</em>` : ''}`, 'tab', () => go(id), {
        role: 'tab', id: 'tcdd-tab-' + id, 'aria-selected': String(tab === id), 'aria-controls': 'tcdd-tabpanel',
        tabindex: tab === id ? '0' : '-1', 'data-k': 'tab:' + id,
      }));
    }
    // arrow keys move between tabs (WAI-ARIA tabs pattern)
    tabs.addEventListener('keydown', (e) => {
      const ids = defs.map((d) => d[0]);
      const i = ids.indexOf(tab);
      const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: ids.length - 1 }[e.key];
      if (to == null) return;
      e.preventDefault();
      go(ids[(to + ids.length) % ids.length]);
    });
    card.appendChild(tabs);
    const body = h('div', 'body');
    body.id = 'tcdd-tabpanel';
    body.setAttribute('role', 'tabpanel');
    body.setAttribute('aria-labelledby', 'tcdd-tab-' + tab);
    body.tabIndex = 0;
    body.appendChild(tab === 'routes' ? routesView(m) : tab === 'trains' ? trainsView(m) : logView());
    card.appendChild(body);
    return body;
  }

  function pill(m) {
    const prices = m.routes.map((r) => r.price).filter((p) => p != null);
    const cheapest = prices.length ? ` · en ucuz ${fmtPrice(Math.min(...prices))}` : '';
    const sub = { start: 'hazır' }[m.phase] ||
      (m.routes.length ? `${m.routes.length} rota${cheapest}` : { done: 'yer yok', paused: 'duraklatıldı' }[m.phase] || 'aramalar sürüyor');
    return button(`Bilet Bul <small>${esc(sub)}</small>`, 'pill', () => { ui.collapsed = false; savePrefs(); render(); },
      { 'aria-expanded': 'false', title: 'Bilet Bul panelini aç (Alt+Shift+K)', 'data-k': 'pill' });
  }

  function header(m) {
    const hd = h('header');
    const t = h('div', 't');
    const sub = m.j ? `${title(nameOf(m.j.o))} → ${title(nameOf(m.j.d))} · ${fmtDay(m.j.day)}` : 'ebilet\'te yolculuğunu ara';
    t.innerHTML = `<h2 tabindex="-1">Bilet Bul</h2><span>${esc(sub)}</span>`;
    hd.appendChild(t);
    const setLabel = ui.settings ? 'Ayarları kapat' : 'Ayarlar';
    hd.appendChild(button(ui.settings ? '✕' : '⚙', 'icon', () => { ui.settings = !ui.settings; render(); },
      { 'aria-label': setLabel, title: setLabel, 'aria-expanded': String(ui.settings), 'data-k': 'settings' }));
    hd.appendChild(button('–', 'icon', () => { ui.collapsed = true; savePrefs(); render(); },
      { 'aria-label': 'Küçült', title: 'Küçült', 'aria-expanded': 'true', 'data-k': 'min' }));
    return hd;
  }

  const STEPS = ['Yolculuğu ara', 'Parçaları Enter ile ara', 'Rotayı seç'];
  function steps(n) {
    const ol = h('ol', 'steps', STEPS.map((t, i) => `<li class="${i + 1 < n ? 'ok' : i + 1 === n ? 'on' : ''}"${i + 1 === n ? ' aria-current="step"' : ''}><i aria-hidden="true">${i + 1 < n ? '✓' : i + 1}</i>${t}</li>`).join(''));
    ol.setAttribute('aria-label', 'Adımlar');
    return ol;
  }
  const routeOf = (a, b) => `${esc(title(nameOf(a)))} → ${esc(title(nameOf(b)))}`;
  const progress = (m, total) => `<div class="bar" role="progressbar" aria-label="Arama ilerlemesi" aria-valuemin="0" aria-valuemax="${total}" aria-valuenow="${m.done}" aria-valuetext="${m.done} / ${total} arama yapıldı"><i style="width:${total ? Math.round((m.done / total) * 100) : 100}%"></i></div>`;

  // What to do right now, while the searches run.
  function doBox() {
    const f = ui.fill, j = liveJ();
    const day = j ? esc(fmtDay(j.day)) : '';
    const box = (cls, head, text) => h('div', 'do' + (cls ? ' ' + cls : ''), `<b>${head}</b>${text}`);
    if (ui.fillMsg) return box('err', 'Bu arama sayılmadı', esc(ui.fillMsg));
    if (!f) return box('', 'Sıradaki aramayı yap', `“Formu doldur”a bas ya da ebilet'te bu iki istasyonu seçip ara. Tarih ${day} olmalı.`);
    if (f.st === 'filling') return box('', 'Bekle…', 'Sıradaki arama ebilet\'in formuna yazılıyor.');
    if (f.st === 'searching') return box('', 'Aranıyor…', 'Sonuç gelince sıradaki arama forma yazılır.');
    if (f.st === 'failed') return box('err', 'Arama formu bulunamadı', `ebilet'in arama formu bu sayfada görünmüyor. Form görününce “Formu doldur”a bas ya da ${routeOf(f.a, f.b)} aramasını kendin yap, tarih ${day}.`);
    if (f.away) return box('', 'Şimdi ebilet\'te Ara\'ya bas', `Form hazır, tarih ${day} olmalı. Ara düğmesine tıkla ya da “Formu doldur” ile yeniden seç.`);
    return box('go', 'Şimdi <kbd>Enter</kbd> tuşuna bas', `Form hazır ve ebilet'te Ara düğmesi seçili. Tarih ${day} olmalı.`);
  }

  function pause() {
    Object.assign(ui, { paused: true, fill: null, fillMsg: '', lastFilledKey: null, tab: null, focusKey: 'pause' });
    render();
    announce('Aramalar duraklatıldı. Rotalara, seferlere ve geçmişe bakabilirsin; sürdürmek için Devam et.');
  }
  function resume() {
    Object.assign(ui, { paused: false, fillMsg: '', focusKey: 'pause' });
    render();
  }

  // The departure-time range: the searches hold while it is edited.
  function editRange() {
    const j = J(), deps = Object.values(j.deps).filter((x) => x != null).sort((x, y) => x - y);
    const r = j.range || { from: deps.length ? fmtTime(deps[0]) : '06:00', to: deps.length ? fmtTime(deps[deps.length - 1]) : '23:59' };
    Object.assign(ui, { rangeEdit: { from: r.from, to: r.to, was: ui.paused }, paused: true, fill: null, fillMsg: '', lastFilledKey: null, focusKey: 'rf' });
    render();
  }
  function setRange(r) {
    J().range = r;
    J().ts = Date.now();
    Object.assign(ui, { rangeEdit: null, paused: false, fill: null, fillMsg: '', lastFilledKey: null, focusKey: '@primary' });
    save(); render();
    const m = model();
    announce(`Kalkış saati: ${rangeText(r)}. ${m.routes.length ? `${m.routes.length} rota.` : 'Henüz rota yok.'}${m.next ? ` Sıradaki arama: ${title(nameOf(m.next.a))} → ${title(nameOf(m.next.b))}.` : ''}`);
  }
  function rangeBox(m) {
    const e = ui.rangeEdit;
    if (!e) {
      const d = h('div', 'rng', `<span>Kalkış saati: <b>${esc(rangeText(m.j.range))}</b></span>`);
      d.appendChild(button(m.j.range ? 'Değiştir' : 'Aralık seç', 'btn link', editRange, { 'data-k': 'range', 'aria-label': `Kalkış saati aralığı: ${rangeText(m.j.range)}. ${m.j.range ? 'Değiştir' : 'Aralık seç'}` }));
      return d;
    }
    const f = h('div', 'rng edit');
    f.setAttribute('role', 'group');
    f.setAttribute('aria-label', 'Kalkış saati aralığı');
    const time = (k, label) => {
      const l = h('label', null, `<span>${label}</span>`);
      const i = document.createElement('input');
      i.type = 'time'; i.value = e[k]; i.dataset.k = k === 'from' ? 'rf' : 'rt';
      i.addEventListener('input', () => { e[k] = i.value; });
      l.appendChild(i);
      return l;
    };
    f.append(time('from', 'En erken'), time('to', 'En geç'));
    const a = h('div', 'acts');
    a.appendChild(button('Uygula', 'btn primary', () => { if (e.from && e.to) setRange({ from: e.from, to: e.to }); }, { 'data-k': 'range-ok' }));
    a.appendChild(button('Tüm gün', 'btn', () => setRange(null)));
    a.appendChild(button('Vazgeç', 'btn', () => { Object.assign(ui, { paused: e.was, rangeEdit: null, focusKey: 'range' }); render(); }));
    f.appendChild(a);
    return f;
  }

  function nextCard(m) {
    const total = m.done + m.left;
    if (m.phase === 'start') {
      const c = h('div', 'next guide');
      c.appendChild(steps(1));
      const ls = state.lastSearch;
      if (ls && !ls.trains.length) {
        c.appendChild(h('div', 'ask', `<b>Sefer bulunamadı</b>${esc(fmtDay(ls.day))} günü ${routeOf(ls.a, ls.b)} arasında sefer yok. Başka bir gün ya da yakın bir istasyon dene.`));
        return c;
      }
      c.appendChild(h('div', 'ask', '<b>ebilet\'te yolculuğunu ara</b>Nereden, nereye ve tarihi seç, Ara\'ya bas.'));
      c.appendChild(h('div', 'msg', 'Script o günün bütün kalkışlarına bakar. Dolu trenler için ara istasyonları sırayla forma yazar, ' +
        'her birinde sen Enter tuşuna basarsın. Belirli bir saat aralığı istersen sonra seçebilirsin.'));
      return c;
    }
    if (m.phase === 'run') {
      const c = h('div', 'next');
      c.innerHTML = `<div class="lab">Sıradaki arama · ${m.done + 1} / ${total}</div>` +
        `<div class="route">${routeOf(m.next.a, m.next.b)}</div>` + progress(m, total);
      c.appendChild(doBox());
      const a = h('div', 'acts');
      a.appendChild(button('Formu doldur', 'btn' + (CFG.autoFill ? '' : ' primary'),
        () => { ui.lastFilledKey = `${m.next.a}>${m.next.b}|${m.j.day}`; prefill(m.next.a, m.next.b); }, { 'data-k': 'fill' }));
      a.appendChild(button('Atla', 'btn', () => {
        store.searched[searchedKey(m.next.a, m.next.b, m.j.day)] = Date.now();
        ui.fillMsg = ''; ui.fill = null; save(); render();
      }, { title: 'Bu aramayı yapmadan geç' }));
      a.appendChild(button('Duraklat', 'btn', pause, { 'data-k': 'pause', title: 'Rotalara, seferlere ve geçmişe bak' }));
      c.appendChild(a);
      c.appendChild(rangeBox(m));
      const prices = m.routes.map((r) => r.price).filter((p) => p != null);
      c.appendChild(h('div', 'msg', m.routes.length
        ? `${m.routes.length} rota bulundu${prices.length ? ` · en ucuz ${fmtPrice(Math.min(...prices))}` : ''}. Görmek için Duraklat'a bas.`
        : 'Henüz rota yok; her aramadan sonra yeniden hesaplanır.'));
      return c;
    }
    if (m.phase === 'paused') {
      const c = h('div', 'next paused');
      c.innerHTML = `<div class="lab">Duraklatıldı · ${m.done} / ${total} arama yapıldı</div>` + progress(m, total);
      if (!ui.rangeEdit) {
        const a = h('div', 'acts');
        a.appendChild(button('Devam et', 'btn primary', resume, { 'data-k': 'pause' }));
        c.appendChild(a);
        c.appendChild(h('div', 'msg', `Sıradaki arama: ${routeOf(m.next.a, m.next.b)}`));
      }
      c.appendChild(rangeBox(m));
      return c;
    }
    const c = h('div', 'next done');
    const { miss, fail } = skippedOf(m);
    const skipped = miss.length + fail.length;
    c.innerHTML = `<div class="lab">${skipped ? `Aramalar bitti · ${total - skipped} / ${total} yapıldı` : `Tüm aramalar tamam · ${total}`}</div>` +
      '<div class="bar" aria-hidden="true"><i style="width:100%"></i></div>';
    if (!ui.rangeEdit) {
      if (miss.length) {
        const names = [...new Set(miss.map((x) => x.st))].map((st) => esc(title(nameOf(st))));
        c.appendChild(h('div', 'warnbox miss', `<b>ebilet'te bulunamadı: ${names.join(', ')}</b>` +
          `Bu ${names.length > 1 ? 'istasyonlar' : 'istasyon'} ebilet'in istasyon listesinde çıkmadı, ${miss.length} arama atlandı.`));
      }
      if (fail.length) {
        c.appendChild(h('div', 'warnbox miss', `<b>ebilet hata verdi: ${fail.map((x) => routeOf(x.a, x.b)).join(', ')}</b>` +
          `ebilet ${fail.length > 1 ? 'bu aramalara' : 'bu aramaya'} sonuç yerine hata döndü (HTTP ${[...new Set(fail.map((x) => x.status))].join(', ')}), ` +
          `${fail.length > 1 ? 'aramalar' : 'arama'} atlandı.`));
      }
      const a = h('div', 'acts');
      if (skipped) a.appendChild(button('Tekrar dene', 'btn primary', () => recheck(miss.concat(fail).map((x) => [x.a, x.b])), { 'data-k': 'retry', title: 'Atlanan aramaları yeniden dene' }));
      a.appendChild(button('Hepsini yeniden kontrol et', 'btn', recheckAll, { 'data-k': 'fill' }));
      c.appendChild(a);
    }
    c.appendChild(rangeBox(m));
    return c;
  }

  // The journey's skipped searches: a station not in ebilet's list (miss) or
  // a search ebilet refused (fail).
  function skippedOf(m) {
    const miss = [], fail = [];
    if (!m.found) return { miss, fail };
    const st = m.found.stations;
    for (let i = 0; i < st.length - 1; i++) {
      for (let k = i + 1; k < st.length; k++) {
        const key = searchedKey(st[i], st[k], m.j.day);
        if (store.missed[key] != null) miss.push({ a: st[i], b: st[k], st: store.missed[key] });
        else if (store.failed[key] != null) fail.push({ a: st[i], b: st[k], status: store.failed[key] });
      }
    }
    return { miss, fail };
  }

  function recheckAll() {
    const st = journeyStations();
    const pairs = [];
    for (let i = 0; i < st.length - 1; i++) for (let k = i + 1; k < st.length; k++) pairs.push([st[i], st[k]]);
    recheck(pairs, [[J().o, J().d]]);   // the whole trip first; the pieces are planned from its answer
  }

  /* ---------- Rotalar ---------- */
  function routesView(m) {
    const v = h('div');
    if (!m.routes.length) {
      if (m.next) v.appendChild(h('div', 'empty', '<b>Henüz rota yok</b>Devam et\'e bas, kalan aramaları yap; her sonuçtan sonra liste güncellenir.'));
      else v.appendChild(h('div', 'warnbox',
        `<b>${m.j.range ? 'Bu saat aralığında' : 'Bu gün'} şu an yer yok</b>Tüm parçalar arandı, satılabilir koltuk kalmamış. ${m.j.range ? 'Saat aralığını genişletebilir, başka bir günü arayabilir' : 'Başka bir günü arayabilir'}, ` +
        'ebilet\'te seferin yanındaki 🔔 zil ile TCDD\'nin boş yer bildirimini açabilir ya da bir süre sonra “Hepsini yeniden kontrol et”e basabilirsin.'));
      return v;
    }

    const seg = h('div', 'seg');
    seg.setAttribute('role', 'group');
    seg.setAttribute('aria-label', 'Sıralama');
    for (const [k, s] of Object.entries(SORTS)) seg.appendChild(button(s.label, '', () => { ui.sort = k; render(); }, { 'aria-pressed': String(ui.sort === k) }));
    v.appendChild(seg);
    const shown = ui.showAll ? m.routes : m.routes.slice(0, 5);
    shown.forEach((r, i) => v.appendChild(routeCard(r, i === 0)));
    if (m.routes.length > 5) v.appendChild(button(ui.showAll ? 'Daha az göster' : `Tüm rotalar (${m.routes.length})`, 'btn', () => { ui.showAll = !ui.showAll; render(); }, { 'aria-expanded': String(ui.showAll), 'data-k': 'more' }));
    return v;
  }

  function routeCard(r, best) {
    const c = h('article', 'rc' + (best ? ' best' : ''));
    const kind = r.tickets === 1 ? 'tek bilet' : `${r.tickets} bilet · ${r.changes ? `${r.changes} aktarma` : 'aynı tren'}`;
    c.innerHTML = `<h4 class="rh"><span class="price">${fmtPrice(r.price)}</span><span class="times">${fmtTime(r.dep)} → ${fmtTime(r.arr)}</span></h4>` +
      `<div class="meta">${fmtDur(r.arr - r.dep)} · ${kind} · ${r.seats} koltuk</div>`;
    const tl = h('div', 'tl');
    r.legs.forEach((l, i) => {
      if (i) {
        const prev = r.legs[i - 1];
        const where = esc(title(nameOf(l.a)));
        tl.appendChild(l.train === prev.train
          ? h('div', 'xfer same', `${where} · aynı trende koltuk değiştir`)
          : h('div', 'xfer', `${where} · ${fmtDur(l.dep - prev.arr)} bekle, sonraki trene bin`));
      }
      tl.appendChild(h('div', 'stop', `<span><b>${fmtTime(l.dep)}</b> ${esc(title(nameOf(l.a)))}</span><span class="c">${esc(title(l.cls || ''))} ${fmtPrice(l.price)}</span>`));
    });
    const last = r.legs[r.legs.length - 1];
    tl.appendChild(h('div', 'stop', `<span><b>${fmtTime(last.arr)}</b> ${esc(title(nameOf(last.b)))}</span>`));
    c.appendChild(tl);
    const stale = Date.now() - r.checked > CFG.staleMin * 60000;
    const f = h('div', 'rf' + (stale ? ' stale' : ''), `<span>${ago(r.checked)} kontrol edildi${stale ? ' · almadan önce yenile' : ''}</span>`);
    f.appendChild(button('Tekrar kontrol et', 'btn link', () => recheck(r.legs.map((l) => [l.a, l.b]))));
    c.appendChild(f);
    return c;
  }

  /* ---------- Seferler ---------- */
  // A departure of a search, with its free seats.
  function trainRow(t, ls, dim) {
    const p = seatsOf(store.pairs[pairKey(t.id, ls.a, ls.b)]) || {};
    const row = h('div', 'row static' + (dim ? ' dim' : ''));
    row.appendChild(h('span', 'tm', `${fmtTime(depOf(t))} → ${fmtTime(arrOf(t))}`));
    row.appendChild(p.usable > 0
      ? h('span', 'badge free', `${p.usable} boş · ${fmtPrice(p.price)}`)
      : h('span', 'badge full', 'dolu'));
    return row;
  }
  const byDep = (trains) => trains.slice().sort((x, y) => (depOf(x) || 0) - (depOf(y) || 0));

  function trainsView() {
    const v = h('div');
    const ls = state.lastSearch, j = liveJ();
    if (!ls || !j) {
      v.appendChild(h('div', 'empty', '<b>Arama bekleniyor</b>ebilet\'te gitmek istediğin iki istasyonu ve tarihi seçip ara. Seferler burada listelenecek.'));
      return seatsBlock(v);
    }
    const own = sameJourney(ls);
    v.appendChild(h('h3', 'sec', `Son arama: ${routeOf(ls.a, ls.b)} · ${esc(fmtDay(ls.day))}`));
    if (own) v.appendChild(h('div', 'note', j.range
      ? `Kalkışı ${esc(rangeText(j.range))} olan seferler hesaba katılıyor; soluk olanlar aralığın dışında.`
      : 'Bütün seferler hesaba katılıyor. Dolu olanlar için ara istasyonlardan rota aranır.'));
    else if (partOfJourney(ls)) v.appendChild(h('div', 'note', 'Bu bir ara parça araması; sonuçlar rotalara eklendi.'));
    else if (onJourneyLine(ls)) v.appendChild(h('div', 'warnbox', `<b>Farklı gün</b>Bu arama ${esc(fmtDay(ls.day))} için, yolculuğun ${esc(fmtDay(j.day))}. Formdaki tarihi düzeltip tekrar ara.`));
    if (!ls.trains.length) {
      v.appendChild(h('div', 'warnbox', '<b>Bu parçada sefer yok</b>Rota hesabında atlandı.'));
      return seatsBlock(v);
    }
    for (const t of byDep(ls.trains)) v.appendChild(trainRow(t, ls, own && !inRange(depOf(t), j.range)));
    return seatsBlock(v);
  }

  function seatsBlock(v) {
    const ls = state.lastSeat;
    if (!ls) return v;
    const { seats } = ls;
    v.appendChild(h('h3', 'sec', 'Son açılan koltuk haritası'));
    const b = h('div', 'seats');
    b.innerHTML = `<div class="ok"><b>Boş koltuklar (${seats.free})</b></div>` +
      ([...seats.cars.entries()].map(([c, l]) => `<div>Vagon ${esc(c)}: ${l.map(esc).join(', ')}</div>`).join('') || '<div>—</div>') +
      (seats.disabled ? `<div class="bad">Engelli (${seats.disabled}): ${[...seats.dis.entries()].map(([c, l]) => `Vagon ${esc(c)}: ${l.map(esc).join(', ')}`).join(' · ')}</div>` : '') +
      (!seats.free && seats.unknown ? `<div class="bad">${seats.unknown} koltuğun durumu çözümlenemedi.</div>` : '');
    v.appendChild(b);
    return v;
  }

  /* ---------- Geçmiş ---------- */
  function logView() {
    const v = h('div');
    const entries = store.log.slice(-20).reverse();
    if (!entries.length) {
      v.appendChild(h('div', 'empty', '<b>Henüz arama yok</b>Yaptığın her arama burada görünür; aynı parçayı tekrar aradığında açılan ve dolan koltuklar da yazar.'));
      return v;
    }
    for (const e of entries) {
      let res;
      if (e.kind === 'ok') res = e.free ? `${e.n} tren · <span class="ok">yer olan: ${e.free}</span>` : `${e.n} tren · <span class="wait">hepsi dolu</span>`;
      else if (e.kind === 'empty') res = '<span class="bad">sefer yok</span>';
      else if (e.kind === 'missed') res = `<span class="wait">atlandı · ${esc(title(nameOf(e.st)))} ebilet'te bulunamadı</span>`;
      else res = `<span class="bad">${e.skipped ? 'atlandı · ' : ''}hata (HTTP ${esc(e.status)}${e.why ? ` · ${esc(e.why)}` : ''})</span>`;
      const other = liveJ() && e.day !== liveJ().day ? ` <span class="wait">· ${esc(fmtDay(e.day))}</span>` : '';
      const d = h('div', 'log', `<span class="w">${fmtTime(e.ts)}</span>${esc(title(nameOf(e.a)))} → ${esc(title(nameOf(e.b)))}${other}<br><span style="padding-left:44px;display:inline-block">${res}</span>`);
      for (const c of (e.changes || []).slice(0, 5)) {
        const up = c.to > c.from;
        d.appendChild(h('div', 'chg ' + (up ? 'ok' : 'bad'),
          `${fmtTime(c.dep)} kalkış: ${c.from} → ${c.to} boş${up && c.from === 0 ? ' · yer açıldı' : !up && c.to === 0 ? ' · doldu' : ''}`));
      }
      v.appendChild(d);
    }
    return v;
  }

  /* ---------- Ayarlar ---------- */
  function settingsView() {
    const v = h('div', 'set');
    v.appendChild(h('h3', 'sec', 'Ayarlar'));
    const num = (key, label, hint, min, max) => {
      const l = h('label', null, `<span>${label}<small>${hint}</small></span>`);
      const i = document.createElement('input');
      i.type = 'number'; i.min = min; i.max = max; i.step = 5; i.value = CFG[key];
      i.addEventListener('change', () => {
        const n = Math.max(min, Math.min(max, Math.round(Number(i.value) || 0)));
        i.value = n; CFG[key] = n; store.settings[key] = n; save();
      });
      l.appendChild(i);
      v.appendChild(l);
    };
    num('minTransferMin', 'En az aktarma süresi (dk)', 'Başka trene geçerken gereken süre', 0, 120);
    num('maxWaitMin', 'En çok bekleme (dk)', 'Bir istasyonda beklenebilecek en uzun süre', 15, 720);
    const check = (key, label, hint, after) => {
      const l = h('label', null, `<span>${label}<small>${hint}</small></span>`);
      const cb = document.createElement('input');
      cb.type = 'checkbox'; cb.checked = !!CFG[key];
      cb.addEventListener('change', () => { CFG[key] = cb.checked; store.settings[key] = cb.checked; save(); if (after) after(cb.checked); });
      l.appendChild(cb);
      v.appendChild(l);
    };
    check('autoFill', 'Sıradaki aramayı forma yaz', 'Her aramadan sonra formu otomatik doldurur');
    check('includeDisabled', 'Engelli koltuklarını da say',
      'Tekerlekli sandalye (DSB) koltuklarını da boş yer sayar. Bu koltuklar engelli yolcular ve refakatçileri içindir; bilet alırken belge istenebilir',
      (on) => announce(on ? 'Engelli koltukları artık sayılıyor.' : 'Engelli koltukları artık sayılmıyor.'));
    const voice = trVoice();
    check('speak', 'Sesli bildirim', 'Arama sonuçlarını, açılan yerleri ve hataları Türkçe sesle okur',
      (on) => { if (on) say('Sesli bildirim açık.'); });
    if (!voice) {
      v.appendChild(h('div', 'note', 'Bu tarayıcıda cihazda çalışan bir Türkçe ses bulunamadı; sesli bildirim sessiz kalır. ' +
        'Ekran okuyucu kullanıyorsan duyurular yine okunur. Türkçe sesi işletim sisteminin dil ayarlarından ekleyebilirsin.'));
    }
    const a = h('div', 'acts');
    a.style.marginTop = '14px';
    a.appendChild(button('Bitti', 'btn primary', () => { ui.settings = false; render(); }));
    a.appendChild(button('Tüm verileri sil', 'btn', () => {
      store.pairs = {}; store.searched = {}; store.missed = {}; store.failed = {}; store.journey = null; store.log = [];
      state.lastSearch = null; ui.settings = false;
      Object.assign(ui, { fillMsg: '', lastFilledKey: null, live: false, paused: false, fill: null, rangeEdit: null, tab: null });
      save(); render();
      announce('Tüm veriler silindi.');
    }));
    v.appendChild(a);
    v.appendChild(h('div', 'note', 'Kısayol: <b>Alt+Shift+K</b> paneli açar ve klavye odağını panele getirir. Sekmeler arasında ok tuşlarıyla geçilir.'));
    v.appendChild(h('div', 'note', 'Veriler yalnızca bu tarayıcıda, 6 saat tutulur. Script siteye kendisi istek atmaz.'));
    return v;
  }

  /* ------------------------------------------------------------------ */
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', render, { once: true });
  else render();
  console.info('%c[bilet-bul] v0.13.0 yüklendi — siteye istek atmaz; her aramayı sen başlatırsın. Panel: Alt+Shift+K.', 'color:#e30a17');
})();

Siteye istek atmaz

Yalnızca senin ebilet'te yaptığın aramaların yanıtlarını okur. Kendi başına arama yapmaz, Ara'ya basmaz.

Veri sende kalır

Sonuçlar sadece senin tarayıcında 6 saat saklanır, hiçbir yere gönderilmez.

Herkes için

Klavyeyle, ekran okuyucuyla ve sesle kullanılır. Sonuçlar istersen sesli okunur.

Bilet ebilet'ten

Rotayı bulduktan sonra biletleri her zamanki gibi ebilet'te alırsın. Engelli (tekerlekli sandalye) koltukları varsayılan olarak sayılmaz; Ayarlar'dan açılabilir.