<?php
declare(strict_types=1);

/**
 * seller/mesajlar.php
 * - WhatsApp benzeri: Sol sohbet listesi + Sağ sohbet
 * - Mobil: list/chat tek sayfa geçiş (view=chat) + geri
 * - ✅ Sidebar yüzünden sağa taşmayı otomatik çözer (sol offset ölçüp width ayarlar)
 * - ✅ Emoji picker + Dosya ekleme
 * - ✅ MOBİL FIX: Mesaj yazma alanı (compose) her zaman ekranda kalır + klavye açılınca yukarı çıkar
 * - Sade / net / tam yükseklik
 */

$base   = $base   ?? (function_exists('app_base') ? app_base('seller/') : '/seller/');
$active = 'mesajlar';

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

include __DIR__ . '/../app/sidebar.php';

/* =========================
   DEMO DATA
========================= */
$threads = [
  ['id'=>11,'name'=>'Elif Y.','avatar'=>'https://i.pravatar.cc/100?img=32','last'=>'Tablo ölçüsü 50×70 uygun mu?','last_at'=>'10:24','unread'=>2,'online'=>true],
  ['id'=>12,'name'=>'Mert A.','avatar'=>'https://i.pravatar.cc/100?img=12','last'=>'Kargoya ne zaman verilir?','last_at'=>'Dün','unread'=>0,'online'=>false],
  ['id'=>13,'name'=>'Zeynep K.','avatar'=>'https://i.pravatar.cc/100?img=47','last'=>'İmzalı baskı seçenekli mi?','last_at'=>'Pzt','unread'=>1,'online'=>true],
  ['id'=>14,'name'=>'Can S.','avatar'=>'https://i.pravatar.cc/100?img=5','last'=>'Renk tonu fotoğraftaki gibi mi?','last_at'=>'Cmt','unread'=>0,'online'=>false],
];

$messagesByThread = [
  11 => [
    ['from'=>'customer','text'=>'Merhaba! Vandavil tabloyu çok beğendim 😍', 'at'=>'10:12'],
    ['from'=>'seller',  'text'=>'Merhaba Elif! Çok sevindim. Dilersen ölçü seçenekleri de önerebilirim.', 'at'=>'10:13'],
    ['from'=>'customer','text'=>'Tablo ölçüsü 50×70 uygun mu?', 'at'=>'10:24'],
    ['from'=>'seller',  'text'=>'Evet, 50×70 en popüler. Duvarın genişse 70×100 de çok iyi durur.', 'at'=>'10:26'],
    ['from'=>'customer','text'=>'Harika, çerçevesiz mi gönderiyorsun?', 'at'=>'10:28'],
  ],
  12 => [
    ['from'=>'customer','text'=>'Merhaba, “Eski Şehir” baskı sipariş versem kargo ne zaman?', 'at'=>'Dün 16:08'],
    ['from'=>'seller',  'text'=>'Merhaba Mert! Bugün 18:00’e kadar verilen siparişler yarın kargoda.', 'at'=>'Dün 16:10'],
    ['from'=>'customer','text'=>'Süper, teşekkürler.', 'at'=>'Dün 16:12'],
  ],
  13 => [
    ['from'=>'customer','text'=>'Selam! İmzalı baskı seçenekli mi?', 'at'=>'Pzt 13:02'],
    ['from'=>'seller',  'text'=>'Selam Zeynep! Evet, imza + sertifika opsiyonu var.', 'at'=>'Pzt 13:05'],
    ['from'=>'customer','text'=>'Seri numarası da ekleniyor mu?', 'at'=>'Pzt 13:06'],
  ],
  14 => [
    ['from'=>'customer','text'=>'Renk tonu fotoğraftaki gibi mi? Bir tık daha sıcak mı?', 'at'=>'Cmt 11:41'],
    ['from'=>'seller',  'text'=>'Ekrana göre ufak farklılık olur ama baskı tonu çok yakın. İstersen ek foto atabilirim.', 'at'=>'Cmt 11:45'],
  ],
];

$selectedId = (int)($_GET['t'] ?? ($threads[0]['id'] ?? 0));
if (!isset($messagesByThread[$selectedId])) $selectedId = (int)($threads[0]['id'] ?? 0);

$view = (string)($_GET['view'] ?? ''); // 'chat' | ''
$mobileOpenChat = ($view === 'chat');

$flash = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ((string)($_POST['action'] ?? '') === 'send') {
    $tid = (int)($_POST['thread_id'] ?? 0);
    $txt = trim((string)($_POST['message'] ?? ''));
    if ($tid <= 0 || $txt === '') {
      $flash = 'Mesaj boş olamaz.';
    } else {
      $flash = 'Mesaj gönderildi (demo).';
      $messagesByThread[$tid][] = ['from'=>'seller','text'=>$txt,'at'=>date('H:i')];
      $selectedId = $tid;
      $mobileOpenChat = true;
      $view = 'chat';
    }
  }
}

$selectedThread = null;
foreach ($threads as $t) { if ((int)$t['id'] === $selectedId) { $selectedThread = $t; break; } }
$selectedThread = $selectedThread ?? ($threads[0] ?? ['id'=>0,'name'=>'Müşteri','avatar'=>'https://i.pravatar.cc/100?img=1','online'=>false]);

$q = trim((string)($_GET['q'] ?? ''));
$filteredThreads = $threads;
if ($q !== '') {
  $filteredThreads = array_values(array_filter($threads, fn($x)=> mb_stripos((string)$x['name'], $q) !== false));
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8" />
  <title>Mesajlar</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <script defer src="https://unpkg.com/lucide@latest"></script>

  <style>
    :root{
      --bg:#f6f7f9;
      --card:#fff;
      --line: rgba(17,24,39,.10);
      --muted:#6b7280;
      --text:#111827;
      --danger:#ef4444;
      --danger2:#dc2626;
      --chatbg:#f3f4f6;
      --main-left: 0px; /* ✅ JS ile ölçülüp set edilecek */
      --compose-h: 92px; /* ✅ mobilde chat alt boşluk */
      --kb-bottom: 0px;  /* ✅ klavye açılınca compose bottom */
    }

    *,*::before,*::after{ box-sizing:border-box; }
    html,body{ height:100%; margin:0; overflow-x:hidden; }
    body{
      font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
      background: var(--bg);
      color: var(--text);
    }

    /* ✅ Kritik: sidebar yüzünden sağa itiliyorsa genişliği otomatik daralt */
    .content-with-sidebar{
      overflow-x: clip;
      width: calc(100vw - var(--main-left));
      max-width: calc(100vw - var(--main-left));
    }

    .page{
      width:100%;
      max-width:100%;
      height:100dvh;
      padding: 12px;
    }

    .shell{
      height: calc(100dvh - 24px);
      width:100%;
      max-width:100%;
      display:grid;
      grid-template-columns: 360px minmax(0,1fr); /* ✅ minmax(0,1fr) taşmayı keser */
      background: var(--card);
      border: 1px solid var(--line);
      overflow:hidden;
    }

    .left{
      min-width:0;
      display:flex;
      flex-direction:column;
      border-right:1px solid var(--line);
      background:#fff;
    }

    .leftbar{
      padding:10px 12px;
      border-bottom:1px solid var(--line);
      min-width:0;
    }

    .search{
      display:flex;
      align-items:center;
      gap:8px;
      border:1px solid rgba(17,24,39,.12);
      padding:10px 12px;
      border-radius:14px;
      background:#fff;
      min-width:0;
    }
    .search input{
      width:100%;
      min-width:0;
      border:0;
      outline:0;
      font-weight:800;
      font-size:13px;
      background:transparent;
    }

    .threads{
      flex:1 1 auto;
      overflow:auto;
      padding:6px;
      min-width:0;
    }

    .thread{
      display:flex;
      gap:12px;
      padding:10px;
      border-radius:14px;
      text-decoration:none;
      color:inherit;
      min-width:0;
      cursor:pointer;
    }
    .thread:hover{ background: rgba(17,24,39,.04); }
    .thread.active{ background: rgba(17,24,39,.06); }

    .avatar{
      width:44px; height:44px;
      flex:0 0 44px;
      border-radius:14px;
      overflow:hidden;
      border:1px solid rgba(17,24,39,.08);
      background:#eef2f7;
      position:relative;
    }
    .avatar img{ width:100%; height:100%; object-fit:cover; display:block; }
    .dot{
      position:absolute; right:6px; bottom:6px;
      width:10px; height:10px; border-radius:999px;
      background:#22c55e; border:2px solid #fff;
    }

    .tmeta{ min-width:0; flex:1 1 auto; }
    .ttop{ display:flex; align-items:center; justify-content:space-between; gap:10px; }
    .tname{ font-weight:950; font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .ttime{ font-weight:900; font-size:12px; color:var(--muted); flex:0 0 auto; }
    .tlast{
      margin-top:3px;
      font-weight:800;
      font-size:12px;
      color:var(--muted);
      white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
    }
    .thread.unread .tlast{ font-weight:950; color:var(--text); }

    .badge{
      display:inline-flex; align-items:center; justify-content:center;
      min-width:22px; height:22px; padding:0 8px;
      border-radius:999px;
      background:var(--danger);
      border:1px solid var(--danger2);
      color:#fff;
      font-weight:950;
      font-size:12px;
      margin-left:8px;
    }

    .right{
      min-width:0;
      display:flex;
      flex-direction:column;
      background:var(--chatbg);
      position:relative;
    }

    .topbar{
      background:#fff;
      border-bottom:1px solid var(--line);
      padding:10px 12px;
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:10px;
      min-width:0;
    }

    .person{ display:flex; align-items:center; gap:10px; min-width:0; }
    .pname{ font-weight:950; font-size:14px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .psub{ font-weight:850; font-size:12px; color:var(--muted); margin-top:1px; }

    .iconbtn{
      width:40px; height:40px;
      border-radius:14px;
      border:1px solid rgba(17,24,39,.10);
      background:#fff;
      display:flex; align-items:center; justify-content:center;
      cursor:pointer;
      flex:0 0 40px;
    }

    .backbtn{ display:none; }

    .flash{
      margin:10px 12px 0 12px;
      padding:10px 12px;
      border:1px solid var(--line);
      background:#fff;
      font-weight:900;
      font-size:13px;
    }

    .chat{
      flex:1 1 auto;
      overflow:auto;
      padding:14px 12px;
      min-width:0;
    }

    .row{ display:flex; margin:8px 0; min-width:0; }
    .row.mine{ justify-content:flex-end; }
    .bubble{
      max-width:78%;
      background:#fff;
      border:1px solid rgba(17,24,39,.10);
      border-radius:16px;
      padding:10px 12px;
      min-width:0;
    }
    .mine .bubble{
      background:rgba(17,24,39,.92);
      border-color:rgba(17,24,39,.92);
    }
    .txt{
      font-weight:850;
      font-size:13px;
      line-height:1.35;
      white-space:pre-wrap;
      word-break:break-word;
      color:var(--text);
    }
    .mine .txt{ color:#fff; }
    .meta{
      margin-top:6px;
      display:flex;
      justify-content:flex-end;
      gap:6px;
      align-items:center;
      font-weight:950;
      font-size:11px;
      color:var(--muted);
    }
    .mine .meta{ color:rgba(255,255,255,.70); }

    .compose{
      background:#fff;
      border-top:1px solid var(--line);
      padding:10px;
      display:flex;
      gap:10px;
      align-items:flex-end;
      min-width:0;
      position:relative; /* desktop */
    }

    .tools{
      display:flex;
      gap:8px;
      align-items:center;
      flex:0 0 auto;
    }

    .inputwrap{
      flex:1 1 auto;
      min-width:0;
      border:1px solid rgba(17,24,39,.12);
      border-radius:18px;
      padding:10px 12px;
      display:flex;
      gap:10px;
      align-items:flex-end;
      background:#fff;
    }

    textarea{
      width:100%;
      min-width:0;
      border:0; outline:0;
      resize:none;
      min-height:22px;
      max-height:140px;
      font-weight:850;
      font-size:13px;
      background:transparent;
      line-height:1.35;
    }

    .send{
      width:44px; height:44px;
      border-radius:18px;
      border:1px solid #111827;
      background:#111827;
      display:flex; align-items:center; justify-content:center;
      cursor:pointer;
      flex:0 0 44px;
    }

    /* ✅ Emoji panel (minimal) */
    .emoji-panel{
      position:absolute;
      left:10px;
      bottom:64px;
      background:#fff;
      border:1px solid var(--line);
      border-radius:14px;
      padding:10px;
      display:none;
      gap:6px;
      flex-wrap:wrap;
      width: 280px;
      max-width: calc(100% - 20px);
      box-shadow: 0 18px 40px rgba(0,0,0,.10);
      z-index:20;
    }
    .emoji-panel.open{ display:flex; }
    .emoji-btn{
      width:36px; height:36px;
      border-radius:12px;
      border:1px solid rgba(17,24,39,.08);
      background:#fff;
      font-size:18px;
      cursor:pointer;
      display:flex; align-items:center; justify-content:center;
    }
    .emoji-btn:hover{ background: rgba(17,24,39,.04); }

    .file-pill{
      margin: 8px 12px 0 12px;
      display:none;
      gap:8px;
      align-items:center;
      font-weight:900;
      font-size:12px;
      color:#111827;
    }
    .file-pill.show{ display:flex; }

    /* ✅ Mobil: list/chat tek ekran + compose fixed */
    @media (max-width: 980px){
      .page{ padding:0; height:100dvh; }
      .shell{ height:100dvh; grid-template-columns:1fr; border-left:0; border-right:0; }
      .backbtn{ display:flex; }
      .left{ display: <?= $mobileOpenChat ? 'none' : 'flex' ?>; }
      .right{ display: <?= $mobileOpenChat ? 'flex' : 'none' ?>; }
      .bubble{ max-width:86%; }
      .topbar{ position:sticky; top:0; z-index:5; }

      /* ✅ FIX: compose her zaman ekranda + safe-area + klavye */
      .compose{
        position:fixed;
        left:0;
        right:0;
        bottom: var(--kb-bottom);
        z-index:50;
        padding-bottom: calc(10px + env(safe-area-inset-bottom));
      }

      /* ✅ Chat alanı compose altında kalmasın */
      .chat{
        padding-bottom: calc(var(--compose-h) + env(safe-area-inset-bottom));
      }
    }

    ::-webkit-scrollbar{ width:6px; height:6px; }
    ::-webkit-scrollbar-track{ background:#eee; }
    ::-webkit-scrollbar-thumb{ background:#bdbdbd; border-radius:10px; }
  </style>
</head>

<body>
<main class="content-with-sidebar" id="mainWrap">
  <div class="page">
    <section class="shell">

      <!-- SOL -->
      <aside class="left">
        <div class="leftbar">
          <form method="get" class="w-full" style="min-width:0;">
            <input type="hidden" name="t" value="<?= (int)$selectedId ?>">
            <div class="search">
              <i data-lucide="search" class="w-4 h-4" style="color:#6b7280;"></i>
              <input type="text" name="q" value="<?= h($q) ?>" placeholder="Müşteri ara..." />
            </div>
          </form>
        </div>

        <div class="threads">
          <?php if (empty($filteredThreads)): ?>
            <div style="padding:16px; text-align:center; color:#6b7280; font-weight:900;">Sonuç bulunamadı.</div>
          <?php else: ?>
            <?php foreach ($filteredThreads as $t): ?>
              <?php
                $isActive = ((int)$t['id'] === (int)$selectedId);
                $isUnread = ((int)($t['unread'] ?? 0) > 0);
                $threadHref = '?t='.(int)$t['id'].'&q='.urlencode($q).'&view=chat';
              ?>
              <a class="thread <?= $isActive ? 'active' : '' ?> <?= $isUnread ? 'unread' : '' ?>" href="<?= h($threadHref) ?>">
                <div class="avatar">
                  <img src="<?= h($t['avatar']) ?>" alt="<?= h($t['name']) ?>">
                  <?php if (!empty($t['online'])): ?><span class="dot"></span><?php endif; ?>
                </div>

                <div class="tmeta">
                  <div class="ttop">
                    <div class="tname"><?= h($t['name']) ?></div>
                    <div class="flex items-center">
                      <span class="ttime"><?= h($t['last_at']) ?></span>
                      <?php if ($isUnread): ?><span class="badge"><?= (int)$t['unread'] ?></span><?php endif; ?>
                    </div>
                  </div>
                  <div class="tlast"><?= h($t['last']) ?></div>
                </div>
              </a>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </aside>

      <!-- SAĞ -->
      <section class="right">
        <div class="topbar">
          <div class="person">
            <a class="iconbtn backbtn" href="?q=<?= urlencode($q) ?>" title="Sohbetlere dön">
              <i data-lucide="arrow-left" class="w-5 h-5"></i>
            </a>

            <div class="avatar">
              <img src="<?= h((string)$selectedThread['avatar']) ?>" alt="<?= h((string)$selectedThread['name']) ?>">
              <?php if (!empty($selectedThread['online'])): ?><span class="dot"></span><?php endif; ?>
            </div>

            <div style="min-width:0;">
              <div class="pname"><?= h((string)$selectedThread['name']) ?></div>
              <div class="psub"><?= !empty($selectedThread['online']) ? 'Çevrimiçi' : 'Çevrimdışı' ?></div>
            </div>
          </div>

          <button class="iconbtn" type="button" title="Sohbet bilgisi (demo)" onclick="alert('Sohbet bilgisi (demo)')">
            <i data-lucide="info" class="w-5 h-5"></i>
          </button>
        </div>

        <?php if ($flash): ?>
          <div class="flash"><?= h($flash) ?></div>
        <?php endif; ?>

        <div class="chat" id="chatBody" aria-label="Mesajlar">
          <?php $msgs = $messagesByThread[$selectedId] ?? []; ?>
          <?php if (empty($msgs)): ?>
            <div style="padding:18px; text-align:center; color:#6b7280; font-weight:900;">Bu sohbet henüz boş.</div>
          <?php else: ?>
            <?php foreach ($msgs as $m): ?>
              <?php $mine = (($m['from'] ?? '') === 'seller'); ?>
              <div class="row <?= $mine ? 'mine' : '' ?>">
                <div class="bubble">
                  <div class="txt"><?= h((string)($m['text'] ?? '')) ?></div>
                  <div class="meta">
                    <span><?= h((string)($m['at'] ?? '')) ?></span>
                    <?php if ($mine): ?><span style="opacity:.9;">✓✓</span><?php endif; ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <div class="file-pill" id="filePill">
          <i data-lucide="paperclip" class="w-4 h-4"></i>
          <span id="fileName">Dosya seçildi</span>
          <button type="button" class="iconbtn" style="width:34px;height:34px;border-radius:12px;" onclick="clearFile()" title="Kaldır">
            <i data-lucide="x" class="w-4 h-4"></i>
          </button>
        </div>

        <form method="post" class="compose" id="composeBar" onsubmit="return sendGuard();">
          <input type="hidden" name="action" value="send">
          <input type="hidden" name="thread_id" value="<?= (int)$selectedId ?>">

          <!-- Emoji panel -->
          <div class="emoji-panel" id="emojiPanel" aria-label="Emoji">
            <?php
              $emojis = ['😀','😁','😂','🤣','😊','😍','😘','😎','😇','😅','😢','😡','👍','👏','🙏','🔥','❤️','✨','🎉','📦','📌','✅','⭐','📷'];
              foreach ($emojis as $e):
            ?>
              <button type="button" class="emoji-btn" onclick="insertEmoji('<?= h($e) ?>')"><?= h($e) ?></button>
            <?php endforeach; ?>
          </div>

          <!-- Sol araçlar: Dosya + Emoji -->
          <div class="tools">
            <button class="iconbtn" type="button" title="Dosya ekle" onclick="triggerFile()">
              <i data-lucide="paperclip" class="w-5 h-5"></i>
            </button>
            <button class="iconbtn" type="button" title="Emoji" onclick="toggleEmoji()">
              <i data-lucide="smile" class="w-5 h-5"></i>
            </button>
            <input id="fileInput" type="file" style="display:none" onchange="fileChosen(event)" />
          </div>

          <div class="inputwrap">
            <textarea id="msgInput" name="message" rows="1" placeholder="Mesaj yaz..."></textarea>
          </div>

          <button type="submit" class="send" title="Gönder">
            <i data-lucide="send" class="w-5 h-5" style="color:#fff;"></i>
          </button>
        </form>
      </section>

    </section>
  </div>
</main>

<script>
  function applySidebarOffsetFix(){
    const main = document.getElementById('mainWrap');
    if(!main) return;
    const rect = main.getBoundingClientRect();
    const left = Math.max(0, Math.round(rect.left));
    const val = (left < 2) ? 0 : left;
    document.documentElement.style.setProperty('--main-left', val + 'px');
  }

  function updateComposeHeights(){
    // mobilde chat alt boşluğu compose yüksekliğine göre ayarla
    const compose = document.getElementById('composeBar');
    if(!compose) return;
    const h = Math.round(compose.getBoundingClientRect().height || 92);
    document.documentElement.style.setProperty('--compose-h', h + 'px');
  }

  function applyKeyboardFix(){
    // Mobil klavye açılınca compose aşağıda kalmasın (VisualViewport)
    const compose = document.getElementById('composeBar');
    if(!compose) return;
    if (window.innerWidth > 980) {
      document.documentElement.style.setProperty('--kb-bottom', '0px');
      return;
    }
    const vv = window.visualViewport;
    if(!vv){
      document.documentElement.style.setProperty('--kb-bottom', '0px');
      return;
    }
    const gap = Math.max(0, (window.innerHeight - vv.height - vv.offsetTop));
    document.documentElement.style.setProperty('--kb-bottom', gap + 'px');
  }

  window.addEventListener('DOMContentLoaded', () => {
    if (window.lucide) window.lucide.createIcons();

    applySidebarOffsetFix();
    window.addEventListener('resize', () => {
      applySidebarOffsetFix();
      updateComposeHeights();
      applyKeyboardFix();
    });

    const body = document.getElementById('chatBody');
    if (body) body.scrollTop = body.scrollHeight;

    const ta = document.getElementById('msgInput');
    if (ta) {
      const resize = () => {
        ta.style.height = 'auto';
        ta.style.height = Math.min(ta.scrollHeight, 140) + 'px';
        updateComposeHeights();
      };
      ta.addEventListener('input', resize);
      resize();
    }

    updateComposeHeights();
    applyKeyboardFix();

    if (window.visualViewport){
      window.visualViewport.addEventListener('resize', () => {
        applyKeyboardFix();
        updateComposeHeights();
      });
      window.visualViewport.addEventListener('scroll', applyKeyboardFix);
    }

    // dışarı tıklayınca emoji kapat
    document.addEventListener('click', (e) => {
      const panel = document.getElementById('emojiPanel');
      if(!panel) return;
      const isBtn = e.target.closest('[onclick="toggleEmoji()"]');
      const inside = e.target.closest('#emojiPanel');
      if(!isBtn && !inside) panel.classList.remove('open');
    });
  });

  function sendGuard(){
    const ta = document.getElementById('msgInput');
    if(!ta) return true;
    const v = (ta.value || '').trim();
    if(!v){ ta.focus(); return false; }
    return true;
  }

  // ✅ Emoji
  function toggleEmoji(){
    const p = document.getElementById('emojiPanel');
    if(!p) return;
    p.classList.toggle('open');
  }
  function insertEmoji(ch){
    const ta = document.getElementById('msgInput');
    if(!ta) return;

    const start = (typeof ta.selectionStart === 'number') ? ta.selectionStart : ta.value.length;
    const end   = (typeof ta.selectionEnd === 'number') ? ta.selectionEnd : ta.value.length;

    const before = ta.value.slice(0, start);
    const after  = ta.value.slice(end);
    ta.value = before + ch + after;

    const pos = start + ch.length;
    ta.focus();
    try { ta.setSelectionRange(pos, pos); } catch(e){}

    // yükseklik güncelle
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 140) + 'px';
    updateComposeHeights();
  }

  // ✅ Dosya
  function triggerFile(){
    const inp = document.getElementById('fileInput');
    if(inp) inp.click();
  }
  function fileChosen(ev){
    const f = ev.target.files && ev.target.files[0];
    const pill = document.getElementById('filePill');
    const name = document.getElementById('fileName');
    if(!pill || !name) return;

    if(f){
      name.textContent = f.name;
      pill.classList.add('show');
      if(window.lucide) window.lucide.createIcons();
      updateComposeHeights();
    } else {
      pill.classList.remove('show');
      updateComposeHeights();
    }
  }
  function clearFile(){
    const inp = document.getElementById('fileInput');
    const pill = document.getElementById('filePill');
    if(inp) inp.value = '';
    if(pill) pill.classList.remove('show');
    updateComposeHeights();
  }
</script>
</body>
</html>
