/* OK ITHAKI V249400 — one file chooser transaction, reliable preview return.
 * Loaded last. It replaces the competing legacy chooser handlers without changing upload/send logic.
 */
(function(){
  'use strict';
  if (window.__ITHAKI_V249400_PREVIEW__) return;
  window.__ITHAKI_V249400_PREVIEW__ = true;

  const VERSION = 'V249400-preview-friendship-consistency';
  const $ = id => document.getElementById(id);
  const esc = value => String(value == null ? '' : value).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  const stateNow = () => { try { return window.state || state || {}; } catch (_) { return window.state || {}; } };
  const mb = n => ((Number(n) || 0) / 1048576).toFixed((Number(n) || 0) > 104857600 ? 0 : 1) + ' MB';

  let objectUrl = '';
  let sequence = 0;
  let transaction = null;
  let lastOpenedFile = null;
  let lastOpenedAt = 0;
  let closeInstalled = false;

  function notify(text, ms){
    try { if (typeof window.toast === 'function') return window.toast(String(text), ms || 7000); } catch (_) {}
    try { if (window.ITH && typeof window.ITH.notifyAppEvent === 'function') return window.ITH.notifyAppEvent(String(text)); } catch (_) {}
    console.log(text);
  }
  function bodyRecovery(){
    try {
      document.documentElement.style.visibility = 'visible';
      document.documentElement.style.opacity = '1';
      if (document.body) {
        document.body.style.visibility = 'visible';
        document.body.style.opacity = '1';
        document.body.style.display = '';
        document.body.classList.add('ithPreviewStable400');
      }
    } catch (_) {}
  }
  function kindFor(file, requested){
    const type = String(file && file.type || '').toLowerCase();
    const name = String(file && file.name || '').toLowerCase();
    if (type.startsWith('image/') || /\.(jpg|jpeg|png|webp|gif|heic|heif)$/.test(name)) return 'photo';
    if (type.startsWith('video/') || /\.(mp4|mov|m4v|webm|3gp|avi|mkv)$/.test(name)) return 'video';
    if (type.startsWith('audio/') || /\.(mp3|m4a|aac|wav|ogg|opus)$/.test(name)) return 'audio';
    return requested || 'file';
  }
  function destination(ctx){
    return ctx === 'feed' ? 'στη Ροή' : ctx === 'dm' ? 'στα Μηνύματα' : ctx === 'space' ? 'στο Δωμάτιο / Κοινότητα' : (ctx === 'comment' || ctx === 'comment_frame') ? 'στα σχόλια' : 'στην επιλεγμένη συνομιλία';
  }
  function icon(kind){ return kind === 'photo' ? '🖼️' : kind === 'video' ? '🎬' : kind === 'audio' ? '🎵' : '📎'; }
  function revoke(){ if (objectUrl) { try { URL.revokeObjectURL(objectUrl); } catch (_) {} objectUrl = ''; } }
  function cleanModal(modal){
    if (!modal) return;
    modal.className = 'previewModal';
    modal.removeAttribute('style');
    modal.classList.remove('fullscreen','callCompactV249218','voiceCallV249218','videoCallV249218','callFullV249223','videoCallV249223','voiceCallV249223','liveRelayBoxV249289');
  }
  function shell(ctx, file, kind){
    return `<div class="previewBox previewScrollable ithPreviewBox400">
      <div class="row ithPreviewHead400">
        <button class="icon" type="button" onclick="ITH.closePreview()">‹</button>
        <b>Προεπισκόπηση ${esc(destination(ctx))}</b>
        <button class="btn gold" style="margin-left:auto" type="button" onclick="ITH.openPreviewStudio&&ITH.openPreviewStudio()">✦ Studio</button>
        <button class="btn" type="button" onclick="ITH.closePreview()">Άκυρο</button>
      </div>
      <div id="previewStage" class="previewStage ithPreviewStage400">
        <div class="ithPreviewPreparing400"><strong>${icon(kind)}</strong><b>Το αρχείο επιλέχθηκε</b><span>Η προεπισκόπηση ανοίγει με ασφάλεια…</span></div>
      </div>
      <div class="card previewFileCard"><b id="previewFileName">${esc(file && file.name || 'Αρχείο')}</b><div id="previewFileMeta" class="date">${esc(file && file.type || kind || 'file')} · ${mb(file && file.size)}</div></div>
      <div id="previewStudioMount"></div>
      <textarea id="previewCaption" rows="1" class="previewOneLineDescV249287" placeholder="Περιγραφή δημοσίευσης"></textarea>
      <input id="previewKeywords" class="previewKeywordsV249287" placeholder="Λέξεις κλειδιά για αναζήτηση">
      ${ctx === 'feed' ? '<label class="card row anonymousRow"><input id="previewAnonymous" type="checkbox"><span class="anonBadge">🕶️ Ανώνυμη δημοσίευση</span></label>' : ''}
      <div class="progress"><span id="progressBar"></span></div>
      <div id="progressText" class="date">Έτοιμο · ${mb(file && file.size)}</div>
      <div class="row"><button id="previewSend" class="btn green" type="button" onclick="ITH.sendPreview()">Αποστολή / Δημοσίευση</button><button class="btn" type="button" onclick="ITH.closePreview()">Άκυρο</button></div>
    </div>`;
  }
  function fallback(file, kind, message){
    const stage = $('previewStage');
    if (!stage) return;
    stage.innerHTML = `<div class="ithPreviewFallback400"><strong>${icon(kind)}</strong><b>${esc(file && file.name || 'Αρχείο')}</b><span>${esc(message || 'Το αρχείο παραμένει έτοιμο για αποστολή.')}</span>${kind !== 'file' ? '<button id="ithTryMediaPreview400" class="btn" type="button">Δοκιμή προβολής αρχείου</button>' : ''}</div>`;
    const button = $('ithTryMediaPreview400');
    if (button) button.onclick = () => attachMedia(file, kind, true);
  }
  function attachMedia(file, kind, forced){
    const stage = $('previewStage');
    if (!stage || !file) return;
    revoke();
    const size = Number(file.size || 0);
    if (!forced && ((kind === 'photo' && size > 45*1024*1024) || (kind === 'video' && size > 260*1024*1024) || (kind === 'audio' && size > 120*1024*1024))) {
      fallback(file, kind, 'Μεγάλο αρχείο: δεν γίνεται αυτόματη αποκωδικοποίηση για να αποφευχθεί λευκή οθόνη. Μπορείς να το δημοσιεύσεις κανονικά.');
      return;
    }
    if (kind === 'file') { fallback(file, kind, 'Το αρχείο θα δημοσιευτεί ως κάρτα και θα ανοίγει εξωτερικά.'); return; }
    try { objectUrl = URL.createObjectURL(file); } catch (_) { fallback(file, kind, 'Δεν δημιουργήθηκε τοπική εικόνα, αλλά το αρχείο είναι έτοιμο για αποστολή.'); return; }
    stage.innerHTML = '';
    let media;
    if (kind === 'photo') { media = document.createElement('img'); media.alt = file.name || 'photo'; media.decoding = 'async'; }
    else if (kind === 'video') { media = document.createElement('video'); media.controls = true; media.playsInline = true; media.preload = 'metadata'; media.muted = true; }
    else { media = document.createElement('audio'); media.controls = true; media.preload = 'metadata'; }
    media.className = 'ithSafeMedia400';
    let settled = false;
    const fail = () => { if (settled) return; settled = true; fallback(file, kind, 'Η συσκευή δεν μπόρεσε να εμφανίσει το αρχείο. Η αποστολή παραμένει διαθέσιμη.'); };
    media.addEventListener(kind === 'photo' ? 'load' : 'loadedmetadata', () => { settled = true; }, {once:true});
    media.addEventListener('error', fail, {once:true});
    stage.appendChild(media);
    requestAnimationFrame(() => { try { media.src = objectUrl; } catch (_) { fail(); } });
    setTimeout(() => { if (!settled && kind !== 'video') fail(); }, 8000);
  }
  function safeOpenPreview(ctx, file, requestedKind, target){
    if (!file) { notify('Δεν παραδόθηκε αρχείο από τη συσκευή. Δοκίμασε ξανά.'); return false; }
    const stamp = Date.now();
    if (file === lastOpenedFile && stamp - lastOpenedAt < 1200) return false;
    lastOpenedFile = file; lastOpenedAt = stamp;
    transaction = null;
    bodyRecovery();
    const kind = kindFor(file, requestedKind);
    const appState = stateNow();
    appState.preview = {ctx:ctx || 'feed', file:file, kind:kind, target:target || '', originalFile:file, studio:(typeof window.studioDefaults === 'function' ? window.studioDefaults() : {})};
    const modal = $('previewModal');
    if (!modal) { notify('Το παράθυρο προεπισκόπησης δεν βρέθηκε.'); return false; }
    cleanModal(modal);
    modal.innerHTML = shell(ctx || 'feed', file, kind);
    modal.classList.add('show','ithPreviewStableModal400');
    if (document.body) document.body.classList.add('previewOpenV249400');
    requestAnimationFrame(() => requestAnimationFrame(() => attachMedia(file, kind, false)));
    setTimeout(() => { bodyRecovery(); modal.classList.add('show','ithPreviewStableModal400'); }, 300);
    return false;
  }
  function completeChooser(source){
    const tx = transaction;
    if (!tx || tx.done) return false;
    const input = $('globalFile');
    const file = input && input.files && input.files[0];
    if (!file) return false;
    tx.done = true;
    transaction = null;
    if (input) input.removeAttribute('capture');
    setTimeout(() => safeOpenPreview(tx.ctx, file, kindFor(file, tx.kind), tx.target), source === 'change' ? 40 : 120);
    return true;
  }
  function nativeReturned(){
    bodyRecovery();
    [0,40,100,180,320,600,1000].forEach(delay => setTimeout(() => completeChooser('native'), delay));
    return true;
  }
  function beginChooser(ctx, kind, target, capture){
    const input = $('globalFile');
    if (!input) { notify('Η εισαγωγή αρχείου δεν φορτώθηκε.'); return false; }
    try { input.value = ''; } catch (_) {}
    input.accept = kind === 'video' ? 'video/*' : kind === 'photo' ? 'image/*' : kind === 'audio' ? 'audio/*' : '*/*';
    if (capture) input.setAttribute('capture','environment'); else input.removeAttribute('capture');
    transaction = {id:++sequence, ctx:ctx || 'feed', kind:kind || 'file', target:target || '', capture:!!capture, done:false, startedAt:Date.now()};
    input.onchange = () => {
      if (!completeChooser('change')) setTimeout(() => completeChooser('change-late'), 100);
    };
    try { input.click(); } catch (error) { transaction = null; input.removeAttribute('capture'); notify('Δεν άνοιξε η επιλογή αρχείου: ' + String(error && error.message || error)); }
    return false;
  }
  function safeChooseFile(ctx, kind, target){ return beginChooser(ctx, kind, target, false); }
  function safeCaptureMedia(ctx, kind, target){ return beginChooser(ctx, kind, target, true); }

  function installClose(){
    if (closeInstalled) return;
    window.ITH = window.ITH || {};
    const base = typeof window.ITH.closePreview === 'function' ? window.ITH.closePreview : (typeof window.closePreview === 'function' ? window.closePreview : null);
    const close = function(){
      revoke(); transaction = null;
      if (document.body) document.body.classList.remove('previewOpenV249400');
      const modal = $('previewModal');
      try { if (base) return base.apply(this, arguments); }
      finally { if (modal) { cleanModal(modal); modal.classList.remove('show','ithPreviewStableModal400'); modal.innerHTML = ''; } bodyRecovery(); }
    };
    close.__v249400 = true;
    window.ITH.closePreview = close;
    closeInstalled = true;
  }
  function patchProfessionalInput(){
    const input = $('ithPublicationFile387');
    if (!input || input.dataset.previewStable400) return;
    input.dataset.previewStable400 = '1';
    input.addEventListener('change', () => {
      const file = input.files && input.files[0];
      if (file) setTimeout(() => safeOpenPreview('feed', file, kindFor(file,'file'), ''), 80);
    }, true);
  }
  function injectCss(){
    if ($('ithV249400PreviewCss')) return;
    const style = document.createElement('style');
    style.id = 'ithV249400PreviewCss';
    style.textContent = `html,body{min-height:100%!important}body.ithPreviewStable400{visibility:visible!important;opacity:1!important}.ithPreviewStableModal400{z-index:2147483647!important;background:rgba(0,0,0,.82)!important}.ithPreviewBox400{overflow-y:auto!important;-webkit-overflow-scrolling:touch!important;max-height:94dvh!important}.ithPreviewStage400{min-height:180px!important}.ithPreviewPreparing400,.ithPreviewFallback400{display:grid;place-items:center;gap:8px;text-align:center;padding:22px;color:#eaf7ff}.ithPreviewPreparing400 strong,.ithPreviewFallback400 strong{font-size:58px}.ithPreviewPreparing400 span,.ithPreviewFallback400 span{max-width:540px;color:rgba(234,247,255,.72);line-height:1.45}.ithSafeMedia400{display:block;max-width:100%;max-height:42dvh;object-fit:contain}.ithPreviewHead400{position:sticky;top:0;z-index:5;background:rgba(8,22,38,.98);padding:4px;border-radius:14px}`;
    document.head.appendChild(style);
  }
  function install(){
    injectCss(); bodyRecovery();
    window.ITH = window.ITH || {};
    window.openPreview = safeOpenPreview;
    window.ITH.openPreview = safeOpenPreview;
    window.ITH.openPreviewV249400 = safeOpenPreview;
    window.ITH.chooseFile = safeChooseFile;
    window.ITH.chooseFileV249400 = safeChooseFile;
    window.ITH.captureMedia = safeCaptureMedia;
    window.ITH.captureMediaV249400 = safeCaptureMedia;
    window.ITH.previewChooserReturnedV249400 = nativeReturned;
    window.ITH.previewChooserReturnedV249399 = nativeReturned;
    installClose(); patchProfessionalInput();
    document.documentElement.setAttribute('data-ithaki-preview-stability','V249400-single-chooser-native-return');
  }

  window.addEventListener('focus', () => { bodyRecovery(); setTimeout(() => { completeChooser('focus'); patchProfessionalInput(); }, 80); }, true);
  window.addEventListener('pageshow', () => { bodyRecovery(); setTimeout(() => completeChooser('pageshow'), 80); }, true);
  window.addEventListener('error', bodyRecovery, true);
  window.addEventListener('unhandledrejection', bodyRecovery, true);
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', install, {once:true}); else install();
  [100,400,1000,2200].forEach(delay => setTimeout(install, delay));
})();
