<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/helpers.php';

require_login();

$c    = cfg();
$base = base_url_dir(); // örn: "/tahta"

// Logo URL
$logoUrl = 'https://noth.wanyweb.com/tahta/img/nothlo.png';
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <title>Tahtalar</title>

  <!-- PWA -->
  <link rel="manifest" href="/tahta/pwa/manifest.json">
  <meta name="theme-color" content="#8fb3ff">

  <!-- ✅ Poppins -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

  <!-- ✅ Lucide Icons -->
  <script defer src="https://unpkg.com/lucide@latest"></script>

  <style>
    :root{
      /* Reference görsel paleti (mavi + beyaz) */
      --bg1:#cfe0ff;
      --bg2:#7aa0cc;
      --bg3:#4d86cc;

      --card:#ffffff;
      --text:#0b1b2b;
      --muted:rgba(11,27,43,.62);
      --muted2:rgba(11,27,43,.42);

      --line:rgba(11,27,43,.10);
      --shadow: 0 16px 44px rgba(11,27,43,.12);

      --blue:#4d86cc;
      --blue2:#2f63c8;

      --r:22px;
      --r2:18px;

      --tap:46px;
    }

    *{box-sizing:border-box}
    html,body{height:100%}

    body{
      margin:0;
      font-family:'Poppins', ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
      color:var(--text);
      -webkit-font-smoothing:antialiased;
      -moz-osx-font-smoothing:grayscale;

      /* iOS-style soft blue background */
      background:
        radial-gradient(1000px 520px at 20% -10%, rgba(255,255,255,.85), rgba(255,255,255,0) 55%),
        radial-gradient(900px 520px at 90% 10%, rgba(255,255,255,.55), rgba(255,255,255,0) 60%),
        linear-gradient(180deg, var(--bg1), var(--bg2));
      min-height:100vh;

      padding:
        max(14px, env(safe-area-inset-top))
        14px
        calc(92px + env(safe-area-inset-bottom))
        14px;
    }

    .app{max-width:520px;margin:0 auto;}

    /* ===== Preloader (minimal, premium) ===== */
    .preloader{
      position:fixed; inset:0;
      background:linear-gradient(180deg, var(--bg1), var(--bg2));
      display:flex; align-items:center; justify-content:center;
      z-index:99999;
      transition:opacity .28s ease, transform .28s ease;
    }
    .preloader.hide{opacity:0;transform:scale(1.01);pointer-events:none}
    .preWrap{
      width:min(320px, 84vw);
      display:flex;flex-direction:column;align-items:center;gap:14px;
    }
    .preLogo{
      width:min(170px, 56vw);
      height:auto; display:block; object-fit:contain;
      filter: drop-shadow(0 18px 30px rgba(11,27,43,.18));
    }
    .preDots{display:flex;gap:8px}
    .preDot{
      width:7px;height:7px;border-radius:999px;
      background:rgba(255,255,255,.92);
      opacity:.28;
      animation:dot 1.05s infinite ease-in-out;
    }
    .preDot:nth-child(2){animation-delay:.16s}
    .preDot:nth-child(3){animation-delay:.32s}
    @keyframes dot{0%,100%{transform:translateY(0);opacity:.28}50%{transform:translateY(-6px);opacity:.98}}
    .preText{font-size:12px;font-weight:600;color:rgba(255,255,255,.88)}

    /* ===== Header ===== */
    .header{
      display:flex;align-items:center;justify-content:space-between;gap:12px;
      padding:4px 2px 10px;
    }
    .hello{min-width:0}
    .helloTop{
      font-size:12px;
      font-weight:600;
      color:rgba(11,27,43,.62);
      letter-spacing:.01em;
    }
    .helloTitle{
      margin-top:3px;
      font-size:20px;
      font-weight:700;
      letter-spacing:-.02em;
      white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
    }

    .headActions{display:flex;align-items:center;gap:10px}
    .iconBtn{
      width:44px;height:44px;border-radius:16px;
      border:1px solid rgba(255,255,255,.55);
      background:rgba(255,255,255,.72);
      box-shadow:0 10px 22px rgba(11,27,43,.10);
      display:grid;place-items:center;
      color:var(--text);
      cursor:pointer;
      -webkit-tap-highlight-color:transparent;
      transition:transform .12s ease, background .12s ease, border-color .12s ease;
      text-decoration:none;
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
    }
    .iconBtn:hover{background:rgba(255,255,255,.84)}
    .iconBtn:active{transform:translateY(1px)}
    .iconBtn i{width:20px;height:20px;opacity:.92}

    /* ===== Cards ===== */
    .card{
      background:rgba(255,255,255,.88);
      border:1px solid rgba(255,255,255,.55);
      border-radius:var(--r);
      box-shadow:var(--shadow);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      overflow:hidden;
    }

    .section{
      margin-top:10px;
    }
    .sectionHead{
      display:flex;align-items:center;justify-content:space-between;gap:10px;
      padding:14px 14px 10px;
    }
    .sectionTitle{
      font-size:13px;
      font-weight:700;
      letter-spacing:-.01em;
    }
    .sectionMeta{
      font-size:12px;
      color:var(--muted2);
      font-weight:500;
      white-space:nowrap;
    }

    /* ===== Board list (kompakt) ===== */
    .list{padding:0 8px 10px}
    .boardItem{
      display:flex;align-items:center;justify-content:space-between;gap:12px;
      padding:10px 10px;            /* ✅ yükseklik düşük */
      border-radius:18px;
      margin:8px 6px;
      border:1px solid rgba(11,27,43,.08);
      background:rgba(255,255,255,.78);
      cursor:pointer;
      -webkit-tap-highlight-color:transparent;
      transition:transform .12s ease, background .12s ease, border-color .12s ease;
    }
    .boardItem:active{transform:translateY(1px)}
    .boardLeft{min-width:0;display:flex;align-items:center;gap:10px}
    .dot{
      width:10px;height:10px;border-radius:999px;
      background:#9aa8b5;
      box-shadow:0 0 0 6px rgba(77,134,204,.08);
    }
    .dot.ok{background:#22c55e; box-shadow:0 0 0 6px rgba(34,197,94,.12)}
    .dot.bad{background:#ef4444; box-shadow:0 0 0 6px rgba(239,68,68,.12)}
    .bTexts{min-width:0}
    .bName{
      font-size:13.5px;
      font-weight:700;
      letter-spacing:-.01em;
      white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
      max-width:240px;
    }
    .bSub{
      margin-top:1px;
      font-size:11.5px;
      color:var(--muted2);
      font-weight:500;
      white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
      max-width:240px;
    }

    .boardRight{display:flex;align-items:center;gap:8px}
    .miniPill{
      display:inline-flex;align-items:center;gap:6px;
      padding:7px 10px;
      border-radius:999px;
      border:1px solid rgba(11,27,43,.10);
      background:rgba(255,255,255,.70);
      font-size:11px;
      font-weight:700;
      color:rgba(11,27,43,.78);
      white-space:nowrap;
    }

    .actBtn{
      width:40px;height:40px;border-radius:14px;
      border:1px solid rgba(11,27,43,.10);
      background:rgba(255,255,255,.72);
      display:grid;place-items:center;
      cursor:pointer;
      -webkit-tap-highlight-color:transparent;
      transition:transform .12s ease, background .12s ease;
    }
    .actBtn:active{transform:translateY(1px)}
    .actBtn i{width:18px;height:18px;opacity:.92}
    .actBtn.primary{
      border-color: rgba(77,134,204,.22);
      background: rgba(77,134,204,.12);
      color: var(--blue2);
    }

    /* ===== Empty state ===== */
    .empty{
      padding:16px 14px 18px;
      text-align:left;
    }
    .emptyTitle{
      font-size:14px;
      font-weight:700;
      letter-spacing:-.01em;
    }
    .emptyText{
      margin-top:6px;
      color:var(--muted);
      font-size:12.5px;
      line-height:1.6;
      font-weight:500;
    }
    .emptyCta{
      margin-top:12px;
      display:inline-flex;
      align-items:center;
      gap:10px;
      padding:12px 14px;
      border-radius:16px;
      border:1px solid rgba(77,134,204,.25);
      background:rgba(77,134,204,.14);
      color:var(--blue2);
      font-weight:700;
      font-size:12px;
      text-decoration:none;
      -webkit-tap-highlight-color:transparent;
    }
    .emptyCta i{width:18px;height:18px}

    /* ===== Toast ===== */
    .toast{
      position:fixed;
      left:50%;
      bottom:calc(92px + env(safe-area-inset-bottom));
      transform:translateX(-50%);
      min-width:min(520px, calc(100vw - 28px));
      max-width:520px;
      display:none;
      padding:12px 14px;
      border-radius:18px;
      border:1px solid rgba(255,255,255,.55);
      background:rgba(255,255,255,.82);
      box-shadow:0 18px 60px rgba(11,27,43,.16);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      color:rgba(11,27,43,.86);
      font-size:12.5px;
      font-weight:600;
      line-height:1.45;
      z-index:9999;
    }

    @media (min-width:520px){
      body{padding-left:16px;padding-right:16px}
      .bName,.bSub{max-width:320px}
    }

    /* ===== Sidebar override (antrasitliği öldür) ===== */
    /* sidebar.php kendi CSS'ini de getiriyor ama burada baskın bir şekilde uyum sağlıyoruz */
    .bn, .bottom-nav, nav.bottom-nav{
      background:rgba(255,255,255,.82)!important;
      border-top:1px solid rgba(11,27,43,.10)!important;
      backdrop-filter: blur(14px)!important;
      -webkit-backdrop-filter: blur(14px)!important;
    }
  </style>
</head>

<body>

  <!-- PRELOADER -->
  <div class="preloader" id="preloader">
    <div class="preWrap">
      <?php if (!empty($logoUrl)): ?>
        <img class="preLogo" src="<?= htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="Logo">
      <?php else: ?>
        <div class="preText">Yükleniyor…</div>
      <?php endif; ?>
      <div class="preDots" aria-hidden="true">
        <span class="preDot"></span><span class="preDot"></span><span class="preDot"></span>
      </div>
      <div class="preText">Yükleniyor…</div>
    </div>
  </div>

  <div class="app">

    <!-- HEADER -->
    <div class="header">
      <div class="hello">
        <div class="helloTop">Kontrol Paneli</div>
        <div class="helloTitle">Tahtalar</div>
      </div>

      <div class="headActions">
        <a class="iconBtn" href="logout.php" title="Çıkış" aria-label="Çıkış">
          <i data-lucide="log-out"></i>
        </a>
      </div>
    </div>

    <!-- BOARDS -->
    <div class="section card">
      <div class="sectionHead">
        <div class="sectionTitle">Tahta Listesi</div>
        <div class="sectionMeta" id="lastUpdate">—</div>
      </div>

      <div class="list" id="boardsList" aria-live="polite">
        <!-- JS doldurur -->
      </div>

      <div class="empty" id="emptyState" style="display:none">
        <div class="emptyTitle">Henüz bağlı tahta yok</div>
        <div class="emptyText">
          Tahta eklemek için QR okutma ekranına geç.
        </div>
        <a class="emptyCta" href="qrscan.php">
          <i data-lucide="qr-code"></i>
          QR ile Tahta Ekle
        </a>
      </div>
    </div>

  </div>

  <div class="toast" id="toast"></div>

<script>
(function(){
  const BASE = <?= json_encode($base) ?>;
  const POLL = Number(<?= json_encode((int)($c['poll_ms'] ?? 3000)) ?>) || 3000;

  const DEFAULT_CLASS_NAME = 'Tahta';
  const NAME_KEY_PREFIX = 'noth_board_name__';

  const preloader = document.getElementById('preloader');
  let preHidden = false;
  function hidePreloader(){
    if(preHidden) return;
    preHidden = true;
    preloader.classList.add('hide');
    setTimeout(()=>{ try{ preloader.remove(); }catch(e){} }, 360);
  }
  setTimeout(hidePreloader, 1200);
  window.addEventListener('load', ()=> setTimeout(hidePreloader, 420));

  const boardsList = document.getElementById('boardsList');
  const emptyState = document.getElementById('emptyState');
  const lastUpdate = document.getElementById('lastUpdate');
  const toastEl    = document.getElementById('toast');

  function iconsRefresh(){
    try{ window.lucide?.createIcons?.(); }catch(e){}
  }

  function vibrate(ms=10){
    try{ navigator.vibrate?.(ms); }catch(e){}
  }

  let toastT = null;
  function toast(msg){
    if(!msg) return;
    toastEl.textContent = msg;
    toastEl.style.display = 'block';
    clearTimeout(toastT);
    toastT = setTimeout(()=>{ toastEl.style.display='none'; }, 1800);
  }

  function setLastUpdate(){
    const d = new Date();
    const hh = String(d.getHours()).padStart(2,'0');
    const mm = String(d.getMinutes()).padStart(2,'0');
    lastUpdate.textContent = `${hh}:${mm}`;
  }

  function storageKeyForBoard(boardId){
    return NAME_KEY_PREFIX + String(boardId || '').trim();
  }
  function getSavedName(boardId){
    if(!boardId) return '';
    try { return (localStorage.getItem(storageKeyForBoard(boardId)) || '').trim(); }
    catch(e){ return ''; }
  }
  function setSavedName(boardId, name){
    if(!boardId) return;
    const v = (name || '').trim();
    try{
      if(v) localStorage.setItem(storageKeyForBoard(boardId), v);
      else localStorage.removeItem(storageKeyForBoard(boardId));
    }catch(e){}
  }
  function ensureName(boardId){
    let n = getSavedName(boardId);
    if(!n){
      n = DEFAULT_CLASS_NAME + ' • ' + String(boardId).slice(-6);
      setSavedName(boardId, n);
    }
    return n;
  }

  async function fetchJson(url, opts){
    const res = await fetch(url, Object.assign({
      cache:'no-store',
      credentials:'same-origin'
    }, opts||{}));
    const text = await res.text();
    try { return JSON.parse(text); }
    catch(e){ throw new Error('JSON değil: ' + url + ' | ' + text.slice(0,160)); }
  }

  async function post(action, data){
    const form = new URLSearchParams(data||{});
    return await fetchJson(`${BASE}/api.php?action=${encodeURIComponent(action)}`,{
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: form.toString()
    });
  }

  // ✅ önce my_boards dene; yoksa my_board’a düş (mevcut sistem bozulmaz)
  async function loadBoards(){
    // 1) my_boards
    try{
      const j = await fetchJson(`${BASE}/api.php?action=my_boards`);
      if(j && j.ok && Array.isArray(j.boards)) return j.boards;
    }catch(e){ /* ignore */ }

    // 2) fallback my_board
    const j2 = await fetchJson(`${BASE}/api.php?action=my_board`);
    if(!j2.ok) throw new Error(j2.error || 'my_board ok=false');
    const b = j2.board ? [j2.board] : [];
    return b;
  }

  // status cache
  const state = new Map(); // board -> {is_frozen, connected, last}

  async function refreshStatuses(boards){
    await Promise.all(boards.map(async (board)=>{
      try{
        const j = await fetchJson(`${BASE}/api.php?action=status&board=${encodeURIComponent(board)}`);
        if(j && j.ok){
          state.set(board, {
            is_frozen: (j.is_frozen===1),
            connected: true,
            last: Date.now()
          });
        }
      }catch(e){
        const old = state.get(board) || {};
        state.set(board, {
          is_frozen: old.is_frozen ?? true,
          connected: false,
          last: old.last ?? Date.now()
        });
      }
    }));
  }

  function render(boards){
    boardsList.innerHTML = '';

    if(!boards || boards.length === 0){
      emptyState.style.display = 'block';
      return;
    }
    emptyState.style.display = 'none';

    boards.forEach((board)=>{
      const st = state.get(board) || {is_frozen:true, connected:false};

      const name = ensureName(board);

      const item = document.createElement('div');
      item.className = 'boardItem';
      item.setAttribute('data-board', board);

      const dotCls = st.connected ? (st.is_frozen ? 'dot bad' : 'dot ok') : 'dot';
      const pillText = st.connected ? (st.is_frozen ? 'Kilitli' : 'Açık') : 'Offline';

      item.innerHTML = `
        <div class="boardLeft">
          <span class="${dotCls}"></span>
          <div class="bTexts">
            <div class="bName">${escapeHtml(name)}</div>
            <div class="bSub">ID: ${escapeHtml(String(board))}</div>
          </div>
        </div>
        <div class="boardRight">
          <span class="miniPill">${pillText}</span>
          <button class="actBtn ${st.is_frozen ? 'primary' : ''}" type="button" aria-label="${st.is_frozen ? 'Aktifleştir' : 'Kilitle'}">
            <i data-lucide="${st.is_frozen ? 'unlock' : 'lock'}"></i>
          </button>
        </div>
      `;

      // toggle action
      const btn = item.querySelector('.actBtn');
      btn.addEventListener('click', async (ev)=>{
        ev.stopPropagation();
        vibrate(12);

        try{
          btn.disabled = true;

          if(st.is_frozen){
            const j = await post('unfreeze', {board});
            if(!j.ok) throw new Error(j.error || 'unfreeze ok=false');
            toast('Tahta aktifleştirildi');
          }else{
            const j = await post('freeze', {board});
            if(!j.ok) throw new Error(j.error || 'freeze ok=false');
            toast('Tahta kilitlendi');
          }

          await refreshStatuses([board]);
          render(boards);
          iconsRefresh();
          setLastUpdate();
        }catch(e){
          toast('İşlem başarısız');
        }finally{
          btn.disabled = false;
        }
      });

      // tap to edit name (premium küçük detay)
      item.addEventListener('click', ()=>{
        vibrate(8);
        const current = ensureName(board);
        const v = prompt('Tahta adı', current);
        if(v !== null){
          setSavedName(board, v.trim() || current);
          render(boards);
          iconsRefresh();
        }
      });

      boardsList.appendChild(item);
    });

    iconsRefresh();
  }

  function escapeHtml(s){
    return String(s)
      .replaceAll('&','&amp;')
      .replaceAll('<','&lt;')
      .replaceAll('>','&gt;')
      .replaceAll('"','&quot;')
      .replaceAll("'","&#039;");
  }

  let boards = [];

  async function bootstrap(){
    try{
      boards = await loadBoards();
      await refreshStatuses(boards);
      render(boards);
      setLastUpdate();
    }catch(e){
      emptyState.style.display = 'block';
      toast('Tahtalar alınamadı');
    }finally{
      hidePreloader();
    }
  }

  bootstrap();
  setInterval(async ()=>{
    if(!boards || boards.length===0) return;
    await refreshStatuses(boards);
    render(boards);
    setLastUpdate();
  }, POLL);

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/tahta/pwa/sw.js').catch(()=>{});
  }

  iconsRefresh();
  setTimeout(iconsRefresh, 120);
})();
</script>

<?php
  // ✅ Bottom bar include
  $active = 'boards';
  include __DIR__ . '/sidebar.php';
?>
</body>
</html>
