Parçalı Koltuk

Dolu görünen trende yer bul.

ebilet'te uçtan uca dolu görünen seferler için ara istasyonlardaki boş koltukları birleştirir, rotaları fiyatıyla gösterir.

Nasıl kullanılır
ÜcretsizKurulum gerekmezVeri tarayıcında kalır
TCDD Parçalı Koltuk
Yolculuk: Ankara Gar → Bozüyük YHT • 6 Aralık
Hedefler
18:30 hedefi • ✅ ₺620 • kalkış 18:05, varış 19:46
₺620 • 18:05 → 19:46 • 2 bilet • aynı tren
18:05 Ankara Gar → 18:41 Polatlı YHT • Ekonomi ₺240
⏱ Polatlı YHT: aynı trende koltuk değiştir
18:41 Polatlı YHT → 19:46 Bozüyük YHT • Ekonomi ₺380
₺625 • 17:50 → 19:46 • 1 aktarma
⏱ Polatlı YHT: 15 dk bekle, sonraki trene bin

Örnek görünüm. Panel ebilet sayfasının sağ altında açılır.

Aynı tren, iki bilet

Sistem bir koltuğu yalnızca yolun tamamı boşsa satar. Oysa çoğu zaman yolun parçalarında yer vardır; bunları birleştirince aynı trenle gidebilirsin.

Nasıl kullanılır

İki yol var. Denemek için konsol yeterli; sürekli kullanacaksan Tampermonkey.

  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.

Chrome ilk seferde yapıştırmayı engellerse allow pasting yaz, Enter'a bas. Sayfa yenilenince kodu tekrar yapıştırman gerekir.

Panelde

  1. ebilet'te yolculuğunu ara, örneğin Ankara Gar → Bozüyük YHT.
  2. Panelde ilgilendiğin kalkış saatlerine tik at.
  3. Panel sıradaki aramayı forma yazar; sen sadece Enter'a basarsın.
  4. Rotalar her aramada güncellenir: en ucuz, en erken varış, en az bilet.
parcali-koltuk.user.js
// ==UserScript==
// @name         TCDD Parçalı Koltuk Bulucu (Split-Seat Finder)
// @namespace    tcdd-split-seat
// @version      0.6.1
// @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ı siz Enter ile başlatırsınız.
// @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ığı:
 *   - sizin yaptığınız 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 → siz Enter'a basın.
 *
 * KULLANIM
 * --------
 * 1. Yolculuğunuzu arayın (ör. Ankara Gar → Bozüyük YHT).
 * 2. Paneldeki listede ilgilendiğiniz kalkış saatlerine tik atın.
 * 3. Script sıradaki aramayı forma yazar → Enter. Her aramadan sonra rota
 *    listesi güncellenir. İstediğiniz an durabilirsiniz.
 * 4. Rotalar: en ucuz / en erken varış / en az bilet sıralaması.
 *
 * Engelli (tekerlekli sandalye) koltukları hesaba katılmaz.
 * 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
    windowMin: 120,       // tik atılan kalkışın ± bu kadar dakikasındaki trenler de ilk bacak olabilir
    autoFill: true,       // her aramadan sonra sıradakini forma yaz
    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)      *
   *  journey:  { o, d, day, ticks:[trainId], trainStops:{id:[stops]} }  *
   * ------------------------------------------------------------------ */
  function emptyStore() { return { pairs: {}, searched: {}, names: {}, journey: null }; }
  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];
      if (s.journey && now - (s.journey.ts || 0) > CFG.maxAgeMs) s.journey = null;
      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 };
  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, bodyText, respText) {
    try {
      if (CFG.searchMatch.test(url) && method === 'POST') onSearch(JSON.parse(bodyText), JSON.parse(respText));
      else if (CFG.seatMatch.test(url) && !/availability/i.test(url)) onSeatMap(JSON.parse(respText));
    } catch (e) { log('parse fail', url, e); }
  }

  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', () => {
        if (this.status === 200) handle(t.u, t.m, 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 (res.ok && (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, 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;
    for (const [name, b] of Object.entries(best)) {
      if (isIgnored(b.cc)) { disabled += b.n; continue; }
      usable += b.n;
      if (b.n > 0) {
        per[name] = b.n;
        if (b.price != null && (price == null || b.price < price)) { price = b.price; cls = name; }
      }
    }
    return { usable, disabled, per, price, cls };
  }

  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 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 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();
    for (const t of trains) {
      for (const s of stopsOf(t)) store.names[s.id] = s.name;
      store.pairs[pairKey(t.id, a, b)] = Object.assign(availOf(t), { dep: depOf(t), arr: arrOf(t), ts: now });
    }
    store.searched[searchedKey(a, b, day)] = now;
    save();
    state.lastSearch = { a, b, day, trains };
    ui.fillMsg = '';
    log('search', a, '>', b, day, trains.length);
    render();
  }

  /* ------------------------------------------------------------------ *
   *  JOURNEY                                                            *
   * ------------------------------------------------------------------ */
  const J = () => store.journey;
  const isJourneySearch = (ls) => !J() || (J().o === ls.a && J().d === ls.b && J().day === ls.day);

  // Ordered station list of the journey, merged from all ticked trains.
  function journeyStations() {
    const j = J();
    let list = [];
    for (const id of j.ticks) {
      const stops = j.trainStops[id] || [];
      if (stops.length > list.length) list = stops.map((s) => s.id);
    }
    for (const id of j.ticks) {
      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;
  }

  function toggleTick(t) {
    const ls = state.lastSearch;
    if (!J()) store.journey = { o: ls.a, d: ls.b, day: ls.day, ticks: [], trainStops: {}, ts: Date.now() };
    const j = J();
    const i = j.ticks.indexOf(t.id);
    j.tickDep = j.tickDep || {};
    if (i >= 0) { j.ticks.splice(i, 1); delete j.trainStops[t.id]; delete j.tickDep[t.id]; }
    else {
      j.ticks.push(t.id);
      j.trainStops[t.id] = stopsOf(t).map((s) => ({ id: s.id, name: s.name }));
      j.tickDep[t.id] = depOf(t);
    }
    if (!j.ticks.length) store.journey = null;
    ui.lastFilledKey = null;
    save(); render();
  }

  /* ------------------------------------------------------------------ *
   *  ROUTES — all itineraries from known pairs                          *
   *  First ticket must be on a ticked departure. A train 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, p] of Object.entries(store.pairs)) {
      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 };
      if (!from.has(a)) from.set(a, []);
      from.get(a).push(e);
    }
    return from;
  }

  // Departure time of a ticked train at the journey origin.
  function tickDep(id) {
    const j = J();
    if (j.tickDep && j.tickDep[id] != null) return j.tickDep[id];
    const p = Object.entries(store.pairs).find(([k]) => k.startsWith(id + '|' + j.o + '>'));
    return p ? p[1].dep : null;
  }
  // A first leg is allowed if it leaves the origin within ±windowMin of any
  // ticked departure (or is the ticked train itself).
  function firstLegOk(e) {
    const j = J();
    if (j.ticks.includes(e.train)) return true;
    const w = CFG.windowMin * 60000;
    return j.ticks.some((id) => { const t0 = tickDep(id); return t0 != null && Math.abs(e.dep - t0) <= w; });
  }

  function findRoutes() {
    const j = J();
    const stations = journeyStations();
    const edges = buildEdges(stations);
    const routes = [];
    const reached = new Set([j.o]);
    const sameTrainDirect = (x, y) => {
      const p = store.pairs[pairKey(x.train, x.a, y.b)];
      return p && p.usable > 0;
    };
    const dfs = (st, arrT, last, legs) => {
      if (legs.length) reached.add(st);
      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, reached, 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)),
    };
  }

  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) },
  };

  // Next search: an unsearched pair starting at a reachable station,
  // earliest station first, farthest destination first.
  function nextSearch(found) {
    const j = J();
    const st = found.stations;
    const todo = [];
    for (let i = 0; i < st.length - 1; i++) {
      if (!found.reached.has(st[i])) continue;
      for (let k = st.length - 1; k > i; k--) {
        if (!store.searched[searchedKey(st[i], st[k], j.day)]) todo.push({ a: st[i], b: st[k] });
      }
    }
    return { next: todo[0] || null, left: todo.length };
  }

  /* ------------------------------------------------------------------ *
   *  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;
  }
  async function pickStation(kind, name) {
    const toggle = findToggle(kind);
    if (!toggle) return false;
    if (normName(toggle.value).startsWith(normName(name) + ' ,')) return true;
    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 false;
    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 true; }
    }
    return false;
  }
  async function prefill(a, b) {
    ui.fillMsg = 'Form dolduruluyor…'; render();
    const ok = (await pickStation('from', nameOf(a))) && (await pickStation('to', nameOf(b)));
    const sb = ok && findSearchButton();
    if (sb) {
      sb.focus();
      sb.style.outline = '3px solid #38d39f';
      sb.style.outlineOffset = '2px';
      sb.addEventListener('blur', () => { sb.style.outline = ''; }, { once: true });
    }
    ui.fillMsg = ok
      ? `Form hazır: ${title(nameOf(a))} → ${title(nameOf(b))}. Enter'a basın${J() ? ` (tarih ${fmtDay(J().day)} olmalı)` : ''}.`
      : 'Form bulunamadı ya da istasyon seçilemedi — bu aramayı elle yapın.';
    render();
  }
  function maybeAutoFill(nx) {
    if (!CFG.autoFill || !nx) return;
    const key = `${nx.a}>${nx.b}|${J().day}`;
    if (ui.lastFilledKey === key) return;
    ui.lastFilledKey = key;
    setTimeout(() => prefill(nx.a, nx.b), 900);
  }

  /* ------------------------------------------------------------------ *
   *  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                                                              *
   * ------------------------------------------------------------------ */
  const C = { bg: '#101418', line: '#2a3440', dim: '#9fb3c8', ok: '#38d39f', warn: '#e0b34c', txt: '#e8eef4', mute: '#5b6b7b' };
  function el(tag, css, html) { const e = document.createElement(tag); if (css) e.style.cssText = css; if (html != null) e.innerHTML = html; return e; }
  function btn(label, fn, primary) {
    const b = el('button',
      `padding:3px 9px;border:1px solid ${primary ? C.ok : '#3a4756'};border-radius:6px;` +
      `background:${primary ? '#13362a' : '#182028'};color:${primary ? C.ok : '#cfe3f5'};cursor:pointer;font:11px system-ui;white-space:nowrap;`, label);
    b.onclick = (e) => { e.stopPropagation(); fn(); };
    return b;
  }
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));

  let panel, body, collapsed = false;
  function ensurePanel() {
    if (panel && document.body && document.body.contains(panel)) return true;
    if (!document.body) return false;
    panel = el('div', `position:fixed;right:12px;bottom:12px;z-index:2147483647;width:410px;max-height:80vh;overflow:auto;background:${C.bg};color:${C.txt};font:12px/1.5 system-ui,sans-serif;border:1px solid ${C.line};border-radius:10px;box-shadow:0 8px 30px rgba(0,0,0,.45);`);
    panel.id = 'tcdd-split-panel';
    const head = el('div', `display:flex;justify-content:space-between;align-items:center;padding:8px 10px;border-bottom:1px solid ${C.line};font-weight:600;cursor:pointer;position:sticky;top:0;background:${C.bg};z-index:1;`,
      `TCDD Parçalı Koltuk <span style="font-weight:400;color:${C.dim}">v0.6.1</span>`);
    const tog = el('span', 'opacity:.7;padding:0 4px;', '–');
    head.appendChild(tog);
    head.onclick = () => { collapsed = !collapsed; body.style.display = collapsed ? 'none' : ''; tog.textContent = collapsed ? '+' : '–'; };
    body = el('div', 'padding:8px 10px;');
    panel.append(head, body);
    document.body.appendChild(panel);
    return true;
  }
  function section(titleHtml) {
    const s = el('div', `margin-bottom:10px;padding-bottom:8px;border-bottom:1px dashed ${C.line};`);
    if (titleHtml) s.appendChild(el('div', `color:${C.dim};margin-bottom:4px;`, titleHtml));
    body.appendChild(s);
    return s;
  }

  function render() {
    if (!ensurePanel()) { document.addEventListener('DOMContentLoaded', render, { once: true }); return; }
    const scroll = panel.scrollTop;
    body.innerHTML = '';
    if (J() && J().ticks.length) renderJourney();
    renderLastSearch();
    renderSeat();
    if (!body.children.length) body.appendChild(el('div', `color:${C.dim}`, 'Hazır. Sitede yolculuğunuzu arayın.'));
    panel.scrollTop = scroll;
  }

  function renderJourney() {
    const j = J();
    const found = findRoutes();
    const { next, left } = nextSearch(found);
    const routes = found.routes.slice().sort(SORTS[ui.sort].fn);

    const s = section(`Yolculuk: <b style="color:${C.txt}">${esc(title(nameOf(j.o)))} → ${esc(title(nameOf(j.d)))}</b> • ${esc(fmtDay(j.day))} • ${j.ticks.length} kalkış seçili`);

    // next search
    if (next) {
      const box = el('div', `margin:2px 0 8px;padding:6px 8px;border:1px solid ${C.ok};border-radius:6px;`);
      const line = el('div', 'display:flex;align-items:center;justify-content:space-between;gap:6px;');
      line.appendChild(el('div', '',
        `Sıradaki arama: <b>${esc(title(nameOf(next.a)))} → ${esc(title(nameOf(next.b)))}</b><br>` +
        `<span style="color:${C.dim}">${left} arama kaldı • istediğiniz an durabilirsiniz</span>`));
      line.appendChild(btn('Formu doldur', () => { ui.lastFilledKey = `${next.a}>${next.b}|${j.day}`; prefill(next.a, next.b); }, true));
      box.appendChild(line);
      if (ui.fillMsg) box.appendChild(el('div', `margin-top:4px;color:${C.dim}`, esc(ui.fillMsg)));
      s.appendChild(box);
      maybeAutoFill(next);
    } else {
      s.appendChild(el('div', `margin-bottom:8px;color:${C.ok}`, 'Gerekli tüm aramalar yapıldı.'));
    }

    // targets: one line per ticked departure, best route that starts on it
    const tgBox = el('div', 'margin-bottom:8px;');
    tgBox.appendChild(el('div', `color:${C.dim};margin-bottom:2px;`, 'Hedefler'));
    const w = CFG.windowMin * 60000;
    for (const id of j.ticks.slice().sort((x, y) => (tickDep(x) || 0) - (tickDep(y) || 0))) {
      const t0 = tickDep(id);
      const mine = routes.filter((r) => r.legs.some((l) => l.train === id) || (t0 != null && Math.abs(r.dep - t0) <= w));
      let status;
      if (mine.length) {
        const b = mine[0];
        const how = b.tickets === 1 ? 'tek bilet' : b.changes ? `${b.tickets} bilet, ${b.changes} aktarma` : `${b.tickets} bilet, aynı tren`;
        const leave = b.dep !== t0 ? `kalkış ${fmtTime(b.dep)}, ` : '';
        status = `<span style="color:${C.ok}">✅ ${fmtPrice(b.price)} • ${leave}varış ${fmtTime(b.arr)} • ${how}</span>` +
          (mine.length > 1 ? ` <span style="color:${C.dim}">(+${mine.length - 1} seçenek)</span>` : '');
      } else if (next) {
        status = `<span style="color:${C.dim}">⏳ aramalar sürüyor</span>`;
      } else {
        status = `<span style="color:${C.warn}">⚠ rota yok</span>`;
      }
      const row = el('div', 'display:flex;align-items:center;justify-content:space-between;gap:6px;padding:1px 0;');
      row.appendChild(el('div', '', `<b>${fmtTime(tickDep(id))}</b> hedefi • ${status}`));
      row.appendChild(btn('×', () => {
        j.ticks = j.ticks.filter((x) => x !== id); delete j.trainStops[id];
        if (!j.ticks.length) store.journey = null;
        ui.lastFilledKey = null; save(); render();
      }));
      tgBox.appendChild(row);
    }
    s.appendChild(tgBox);

    // routes
    if (!routes.length) {
      s.appendChild(el('div', `color:${C.dim}`, next ? 'Henüz rota yok — aramalar geldikçe burada belirecek.' : 'Seçili kalkışlarla bu gün için satılabilir koltuklu rota bulunamadı.'));
    } else {
      const priced = routes.filter((r) => r.price != null).map((r) => r.price);
      const range = priced.length ? ` • ${fmtPrice(Math.min(...priced))} – ${fmtPrice(Math.max(...priced))}` : '';
      const bar = el('div', 'display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:6px;');
      bar.appendChild(el('span', `color:${C.dim}`, `${routes.length} rota${range}`));
      for (const [k, v] of Object.entries(SORTS)) {
        const b = btn(v.label, () => { ui.sort = k; render(); }, ui.sort === k);
        bar.appendChild(b);
      }
      s.appendChild(bar);
      const shown = ui.showAll ? routes : routes.slice(0, 5);
      for (const r of shown) s.appendChild(routeCard(r));
      if (routes.length > 5) {
        s.appendChild(btn(ui.showAll ? 'Daha az göster' : `Tümünü göster (${routes.length})`, () => { ui.showAll = !ui.showAll; render(); }));
      }
    }

    const foot = el('div', 'margin-top:8px;');
    foot.appendChild(btn('Yeni yolculuk', () => { store.journey = null; ui.lastFilledKey = null; save(); render(); }));
    s.appendChild(foot);
  }

  function routeCard(r) {
    const c = el('div', `margin:0 0 6px;padding:6px 8px;border:1px solid ${C.line};border-radius:6px;`);
    const kind = r.tickets === 1 ? 'tek bilet' : `${r.tickets} bilet${r.changes ? ` • ${r.changes} aktarma` : ' • aynı tren'}`;
    c.appendChild(el('div', '',
      `<b style="color:${C.ok}">${fmtPrice(r.price)}</b> • <b>${fmtTime(r.dep)} → ${fmtTime(r.arr)}</b> ` +
      `<span style="color:${C.dim}">(${fmtDur(r.arr - r.dep)}) • ${kind} • ${r.seats} koltuk</span>`));
    r.legs.forEach((l, i) => {
      if (i) {
        const prev = r.legs[i - 1];
        const where = esc(title(nameOf(l.a)));
        const msg = l.train === prev.train
          ? `${where}: aynı trende koltuk değiştir`
          : `${where}: ${fmtDur(l.dep - prev.arr)} bekle, sonraki trene bin`;
        c.appendChild(el('div', `color:${C.warn};padding-left:10px;`, '⏱ ' + msg));
      }
      c.appendChild(el('div', 'padding-left:10px;',
        `${fmtTime(l.dep)} ${esc(title(nameOf(l.a)))} → ${fmtTime(l.arr)} ${esc(title(nameOf(l.b)))} ` +
        `<span style="color:${C.dim}">• ${esc(title(l.cls || ''))} ${fmtPrice(l.price)}</span>`));
    });
    return c;
  }

  function renderLastSearch() {
    const ls = state.lastSearch;
    if (!ls) return;
    const tickable = isJourneySearch(ls);
    const s = section(`Son arama: ${esc(title(nameOf(ls.a)))} → ${esc(title(nameOf(ls.b)))} • ${esc(fmtDay(ls.day))}` +
      (tickable ? '' : ' <span style="color:#5b6b7b">(ara arama — rotalara eklendi)</span>'));
    if (tickable && (!J() || !J().ticks.length)) {
      s.appendChild(el('div', `color:${C.dim};margin-bottom:4px;font-size:11px`, 'İlgilendiğiniz kalkışlara tik atın; dolu olanlar için ara istasyonlardan rota aranır.'));
    }
    const ticks = new Set(J() ? J().ticks : []);
    for (const t of ls.trains.slice().sort((x, y) => (depOf(x) || 0) - (depOf(y) || 0))) {
      const p = store.pairs[pairKey(t.id, ls.a, ls.b)] || {};
      const row = el('label', `display:flex;align-items:center;gap:8px;padding:2px 0;${tickable ? 'cursor:pointer;' : ''}`);
      if (tickable) {
        const cb = el('input');
        cb.type = 'checkbox';
        cb.checked = ticks.has(t.id);
        cb.onchange = () => toggleTick(t);
        row.appendChild(cb);
      }
      const seats = p.usable > 0
        ? `<span style="color:${C.ok}">${p.usable} boş</span> • ${fmtPrice(p.price)}`
        : `<span style="color:${C.mute}">dolu</span>`;
      row.appendChild(el('span', '', `<b>${fmtTime(depOf(t))} → ${fmtTime(arrOf(t))}</b> • ${seats}`));
      s.appendChild(row);
    }
  }

  function renderSeat() {
    const ls = state.lastSeat;
    if (!ls) return;
    const { seats } = ls;
    const s = section('Son açılan koltuk haritası');
    let h = `<div style="color:${C.ok}">Boş koltuklar (${seats.free}):</div>`;
    h += [...seats.cars.entries()].map(([c, l]) => `Vagon ${esc(c)}: ${l.map(esc).join(', ')}`).join('<br>') || '—';
    if (seats.disabled) {
      h += `<div style="color:${C.warn}">Engelli (${seats.disabled}): ` +
        [...seats.dis.entries()].map(([c, l]) => `Vagon ${esc(c)}: ${l.map(esc).join(', ')}`).join(' · ') + '</div>';
    }
    if (!seats.free && seats.unknown) {
      h += `<div style="color:${C.warn}">${seats.unknown} koltuğun durumu çözümlenemedi — CFG.debug = true yapıp window.__tcddSplit.lastSeat.raw içeriğini paylaşın.</div>`;
    }
    s.appendChild(el('div', '', h));
  }

  /* ------------------------------------------------------------------ */
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', render, { once: true });
  else render();
  console.info('%c[tcdd-split] v0.6.1 yüklendi — siteye istek atmaz; her aramayı siz başlatırsınız.', 'color:#38d39f');
})();

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.

Bilet ebilet'ten

Rotayı bulduktan sonra biletleri her zamanki gibi ebilet'te alırsın. Engelli koltukları hesaba katılmaz.