/* site-extras.js — плитка, статьи, панели и работы */
(function(){
  if(window.__siteExtras) return; window.__siteExtras = 1;

  function $(i){ return document.getElementById(i); }
  function q(s, r){ return (r || document).querySelector(s); }
  function esc(s){ return String(s == null ? '' : s).replace(/[&<>"']/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]; }); }
  var BAD = 'Сервер вернул не тот ответ. Проверьте, что файлы tiles-api.php, articles-api.php и admin-config.php загружены.';
  function parse(t){ try { return JSON.parse(t); } catch(e){ throw new Error(BAD); } }

  var st = document.createElement('style');
  st.textContent =
    '.sx-box{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:24px;margin-bottom:24px}' +
    '.sx-row{display:flex;gap:14px;align-items:center;padding:12px 0;border-bottom:1px solid var(--line);flex-wrap:wrap}' +
    '.sx-row:last-child{border-bottom:0}' +
    '.sx-th{width:72px;height:54px;background:#fff;border-radius:4px;flex-shrink:0;overflow:hidden;display:flex;align-items:center;justify-content:center;font-size:10px;color:#8fa3c8}' +
    '.sx-th img{width:100%;height:100%;object-fit:contain}' +
    '.sx-info{flex:1;min-width:140px}.sx-info b{display:block}.sx-info span{font-size:13px;color:var(--muted)}' +
    '.sx-hint{font-size:12px;color:var(--muted);margin:-4px 0 0}' +
    '.tile-photo{aspect-ratio:4/3;background:#fff;display:flex;align-items:center;justify-content:center;color:#8fa3c8;font-size:13px}' +
    '.tile-photo img{width:100%;height:100%;object-fit:contain;display:block}' +
    '.tile-size{font-size:13px;color:var(--muted);margin-bottom:8px}';
  document.head.appendChild(st);

  function shrink(file, max){
    return new Promise(function(res, rej){
      var bad = function(){ rej(new Error('Не удалось прочитать фото. Используйте JPG или PNG.')); };
      var r = new FileReader(); r.onerror = bad;
      r.onload = function(){
        var im = new Image(); im.onerror = bad;
        im.onload = function(){
          var k = Math.min(1, max / Math.max(im.width, im.height));
          var w = Math.max(1, Math.round(im.width * k)), h = Math.max(1, Math.round(im.height * k));
          var c = document.createElement('canvas'); c.width = w; c.height = h;
          var x = c.getContext('2d'); x.fillStyle = '#fff'; x.fillRect(0, 0, w, h); x.drawImage(im, 0, 0, w, h);
          c.toBlob(function(b){ b ? res(b) : bad(); }, 'image/jpeg', 0.85);
        };
        im.src = r.result;
      };
      r.readAsDataURL(file);
    });
  }

  function base(root, file, mainHtml, key, onData){
    root.innerHTML =
      '<div class="sx-msg"></div>' +
      '<div class="sx-box sx-login" style="display:none"><h3>Пароль</h3><form class="lead-form sx-lf"><input type="password" class="sx-pw" placeholder="Пароль" required autocomplete="current-password"><button class="btn btn-primary" type="submit">Войти</button></form></div>' +
      '<div class="sx-main" style="display:none">' + mainHtml + '<button type="button" class="btn btn-ghost sx-out">Выйти</button></div>';
    var P = {csrf: ''};
    var m = q('.sx-msg', root), lg = q('.sx-login', root), mn = q('.sx-main', root);
    P.msg = function(t, ok){
      if(!t){ m.style.display = 'none'; return; }
      m.textContent = t;
      m.style.cssText = 'display:block;margin:0 0 16px;padding:12px 16px;border-radius:6px;font-size:14px;line-height:1.6;word-break:break-word;' +
        (ok ? 'background:rgba(34,197,94,.12);border:1px solid rgba(34,197,94,.4);color:#86efac' : 'background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.4);color:#fca5a5');
    };
    P.show = function(a){ lg.style.display = a ? 'none' : ''; mn.style.display = a ? '' : 'none'; };
    P.call = function(action, fields, files){
      var fd = new FormData(); fd.append('a', action); fd.append('csrf', P.csrf);
      Object.keys(fields || {}).forEach(function(k){
        var v = fields[k];
        if(Array.isArray(v)) v.forEach(function(x){ fd.append(k + '[]', x); }); else fd.append(k, v);
      });
      (files || []).forEach(function(f){ fd.append(f.field, f.blob, 'photo.jpg'); });
      return fetch(file, {method:'POST', body:fd, credentials:'same-origin', cache:'no-store'}).then(function(r){ return r.text(); }).then(parse);
    };
    P.apply = function(r, okText){
      if(r.csrf) P.csrf = r.csrf;
      if(!r.ok){ if(r.auth === false) P.show(false); P.msg(r.error || 'Ошибка', false); return false; }
      if(r[key]) onData(r[key]);
      if(okText) P.msg(okText, true);
      return true;
    };
    q('.sx-lf', root).addEventListener('submit', function(e){
      e.preventDefault(); P.msg('');
      P.call('login', {password: q('.sx-pw', root).value}).then(function(r){
        if(P.apply(r)){ P.show(true); q('.sx-pw', root).value = ''; }
      }).catch(function(x){ P.msg(x.message, false); });
    });
    q('.sx-out', root).onclick = function(){ P.call('logout').then(function(){ P.csrf = ''; P.show(false); P.msg(''); }); };
    P.open = function(){
      P.msg('Загрузка…', true);
      fetch(file + '?a=status', {credentials:'same-origin', cache:'no-store'}).then(function(r){ return r.text(); }).then(parse).then(function(r){
        P.msg(''); P.csrf = r.csrf || ''; P.show(!!r.auth);
        if(r.auth) return P.call('list').then(function(x){ P.apply(x); });
      }).catch(function(e){ P.msg(e.message, false); });
    };
    return P;
  }

  /* =====================================================
     АДМИНКА
     ===================================================== */
  var objs = {};
  var tabsBox = q('.admin-tabs');
  var statsBox = q('.admin-stats');

  if(tabsBox && statsBox){
    (function(){
      var tiles = [], editId = null;
      var root = $('tilesAdmin');
      if(!root) return;
      var P = base(root, 'tiles-api.php',
        '<div class="sx-box"><h3 class="t-title">Добавить товар</h3>' +
          '<form class="lead-form sx-form t-form">' +
          '<input type="text" class="t-name" placeholder="Название (например, Плитка «Тучка»)" required>' +
          '<input type="text" class="t-size" placeholder="Размер (300 × 300 × 30 мм)">' +
          '<input type="text" class="t-price" placeholder="Цена (от 700 ₽ / м²)">' +
          '<input type="file" class="t-file" accept="image/*">' +
          '<p class="sx-hint">Фото уменьшится автоматически.</p>' +
          '<button type="submit" class="btn btn-primary t-save">Сохранить</button>' +
          '<button type="button" class="btn btn-ghost t-cancel" style="display:none">Отменить</button></form></div>' +
        '<div class="sx-box t-list"></div>',
        'tiles', function(d){ tiles = d; render(); });
      function render(){
        var l = q('.t-list', root);
        if(!tiles.length){ l.innerHTML = '<p>Список пуст.</p>'; return; }
        l.innerHTML = tiles.map(function(t){
          return '<div class="sx-row"><div class="sx-th">' + (t.image ? '<img src="' + esc(t.image) + '" alt="">' : 'нет фото') + '</div>' +
            '<div class="sx-info"><b>' + esc(t.name) + '</b><span>' + esc(t.size || '') + ' ' + esc(t.price || '') + '</span></div>' +
            '<div class="admin-actions"><button class="admin-btn" data-act="edit" data-id="' + esc(t.id) + '">Изменить</button><button class="admin-btn danger" data-act="del" data-id="' + esc(t.id) + '">Удалить</button></div></div>';
        }).join('');
      }
      function reset(){ editId = null; q('.t-form', root).reset(); q('.t-title', root).textContent = 'Добавить товар'; q('.t-cancel', root).style.display = 'none'; }
      q('.t-cancel', root).onclick = reset;
      q('.t-form', root).addEventListener('submit', function(e){
        e.preventDefault();
        var btn = q('.t-save', root); btn.disabled = true; btn.textContent = 'Сохранение…'; P.msg('');
        var f = q('.t-file', root).files[0];
        (f ? shrink(f, 900).then(function(b){ return [{field:'photo', blob:b}]; }) : Promise.resolve([]))
          .then(function(files){
            return P.call(editId ? 'edit' : 'add', {id: editId || '', name: q('.t-name', root).value, size: q('.t-size', root).value, price: q('.t-price', root).value}, files);
          })
          .then(function(r){ if(P.apply(r, 'Сохранено.')) reset(); })
          .catch(function(err){ P.msg(err.message, false); })
          .then(function(){ btn.disabled = false; btn.textContent = 'Сохранить'; });
      });
      q('.t-list', root).addEventListener('click', function(e){
        var act = e.target.getAttribute('data-act'), id = e.target.getAttribute('data-id');
        if(!act) return;
        if(act === 'edit'){
          var t = tiles.filter(function(x){ return x.id === id; })[0]; if(!t) return;
          editId = id; q('.t-name', root).value = t.name || ''; q('.t-size', root).value = t.size || ''; q('.t-price', root).value = t.price || '';
          q('.t-title', root).textContent = 'Редактирование: ' + t.name; q('.t-cancel', root).style.display = '';
        } else if(act === 'del'){
          if(!confirm('Удалить товар?')) return;
          P.call('delete', {id: id}).then(function(r){ P.apply(r, 'Товар удалён.'); }).catch(function(x){ P.msg(x.message, false); });
        }
      });
      objs.tiles = P;
    })();

    (function(){
      var arts = [], editId = null;
      var root = $('articlesAdmin');
      if(!root) return;
      var P = base(root, 'articles-api.php',
        '<div class="sx-box"><h3 class="a-title">Новая статья</h3>' +
          '<form class="lead-form sx-form a-form">' +
          '<input type="text" class="a-t" placeholder="Заголовок" required>' +
          '<input type="text" class="a-ex" placeholder="Короткое описание">' +
          '<textarea class="a-body" placeholder="Текст статьи" required></textarea>' +
          '<input type="file" class="a-files" accept="image/*" multiple>' +
          '<button type="submit" class="btn btn-primary a-save">Опубликовать</button>' +
          '<button type="button" class="btn btn-ghost a-cancel" style="display:none">Отменить</button></form></div>' +
        '<div class="sx-box a-list"></div>',
        'articles', function(d){ arts = d; render(); });
      function imgs(a){ return (a.images && a.images.length) ? a.images : (a.image ? [a.image] : []); }
      function render(){
        var l = q('.a-list', root);
        if(!arts.length){ l.innerHTML = '<p>Пока нет статей.</p>'; return; }
        l.innerHTML = arts.map(function(a){
          var im = imgs(a)[0];
          return '<div class="sx-row"><div class="sx-th">' + (im ? '<img src="' + esc(im) + '" alt="">' : 'нет фото') + '</div>' +
            '<div class="sx-info"><b>' + esc(a.title) + '</b><span>' + esc(a.date || '') + '</span></div>' +
            '<div class="admin-actions"><button class="admin-btn" data-act="edit" data-id="' + esc(a.id) + '">Изменить</button><button class="admin-btn danger" data-act="del" data-id="' + esc(a.id) + '">Удалить</button></div></div>';
        }).join('');
      }
      function reset(){ editId = null; q('.a-form', root).reset(); q('.a-title', root).textContent = 'Новая статья'; q('.a-save', root).textContent = 'Опубликовать'; q('.a-cancel', root).style.display = 'none'; }
      q('.a-cancel', root).onclick = reset;
      q('.a-form', root).addEventListener('submit', function(e){
        e.preventDefault();
        var btn = q('.a-save', root); btn.disabled = true; btn.textContent = 'Сохранение…'; P.msg('');
        var list = Array.prototype.slice.call(q('.a-files', root).files, 0, 10);
        Promise.all(list.map(function(f){ return shrink(f, 1200).then(function(b){ return {field:'photos[]', blob:b}; }); }))
          .then(function(files){
            return P.call(editId ? 'edit' : 'add', {id: editId || '', title: q('.a-t', root).value, excerpt: q('.a-ex', root).value, body: q('.a-body', root).value}, files);
          })
          .then(function(r){ if(P.apply(r, editId ? 'Сохранено.' : 'Опубликовано.')) reset(); })
          .catch(function(err){ P.msg(err.message, false); })
          .then(function(){ btn.disabled = false; btn.textContent = editId ? 'Сохранить' : 'Опубликовать'; });
      });
      q('.a-list', root).addEventListener('click', function(e){
        var act = e.target.getAttribute('data-act'), id = e.target.getAttribute('data-id');
        if(!act) return;
        if(act === 'edit'){
          var a = arts.filter(function(x){ return x.id === id; })[0]; if(!a) return;
          editId = id; q('.a-t', root).value = a.title || ''; q('.a-ex', root).value = a.excerpt || ''; q('.a-body', root).value = a.body || '';
          q('.a-title', root).textContent = 'Редактирование: ' + a.title; q('.a-save', root).textContent = 'Сохранить'; q('.a-cancel', root).style.display = '';
        } else if(act === 'del'){
          if(!confirm('Удалить статью?')) return;
          P.call('delete', {id: id}).then(function(r){ P.apply(r, 'Статья удалена.'); }).catch(function(x){ P.msg(x.message, false); });
        }
      });
      objs.articles = P;
    })();
  }

  /* =====================================================
     САЙТ
     ===================================================== */
  var tilesData = [], tilesState = 'loading';
  function renderTilesGrid(){
    var g = $('tilesGrid'); if(!g) return;
    if(tilesState === 'loading'){ g.innerHTML = '<p>Загрузка…</p>'; return; }
    if(tilesState === 'error'){ g.innerHTML = '<p>Каталог временно недоступен.</p>'; return; }
    if(!tilesData.length){ g.innerHTML = '<p>Каталог скоро пополнится.</p>'; return; }
    g.innerHTML = tilesData.map(function(t){
      return '<div class="card"><div class="tile-photo">' + (t.image ? '<img src="' + esc(t.image) + '" alt="' + esc(t.name) + '" loading="lazy">' : 'Фото скоро') + '</div>' +
        '<div class="card-body"><h3>' + esc(t.name) + '</h3>' + (t.size ? '<div class="tile-size">' + esc(t.size) + '</div>' : '') +
        (t.price ? '<div class="card-price">' + esc(t.price) + '</div>' : '') +
        '<a class="btn-card" data-open-lead="Заявка: ' + esc(t.name) + '">Заказать</a></div></div>';
    }).join('');
  }
  function loadTilesData(){
    return fetch('tiles.json?' + Date.now(), {cache:'no-store'})
      .then(function(r){ if(r.status === 404) return []; if(!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
      .then(function(d){ tilesData = Array.isArray(d) ? d : []; tilesState = 'ok'; })
      .catch(function(e){ console.error(e); tilesState = 'error'; })
      .then(renderTilesGrid);
  }
  window.loadTiles = loadTilesData;
  window.renderTilesPublic = renderTilesGrid;
  loadTilesData();

  if(!$('page-article')){
    var list = [];
    var pg = document.createElement('div');
    pg.className = 'page'; pg.id = 'page-article';
    pg.innerHTML = '<section class="section"><div class="container article-content">' +
      '<div class="breadcrumbs"><a data-page="home">Главная</a><span>›</span><a data-page="blog">Статьи</a><span>›</span><em id="artCrumb" style="font-style:normal"></em></div>' +
      '<h1 id="artTitle"></h1><p id="artDate" style="color:var(--muted);font-size:14px;margin-bottom:24px"></p><div id="artBody"></div>' +
      '<div style="margin-top:40px"><a class="back-link" data-page="blog">К списку статей</a></div></div></section>';
    document.querySelector('main').appendChild(pg);

    var imgsOf = function(a){ return (a.images && a.images.length) ? a.images : (a.image ? [a.image] : []); };
    var bodyHtml = function(text){
      var out = [], buf = [];
      function flush(){ if(buf.length){ out.push('<p>' + buf.map(esc).join('<br>') + '</p>'); buf = []; } }
      String(text || '').split(/\r?\n/).forEach(function(line){
        if(!line.trim()) flush();
        else if(line.indexOf('## ') === 0){ flush(); out.push('<h2>' + esc(line.slice(3).trim()) + '</h2>'); }
        else buf.push(line);
      });
      flush();
      return out.join('');
    };
    var renderList = function(){
      var bl = q('#page-blog .blog-list'); if(!bl) return;
      bl.querySelectorAll('.blog-card[data-dyn]').forEach(function(n){ n.remove(); });
      bl.insertAdjacentHTML('afterbegin', list.map(function(a){
        var im = imgsOf(a)[0];
        return '<div class="blog-card" data-dyn="1" data-page="article-' + esc(a.id) + '">' +
          (im ? '<img src="' + esc(im) + '" alt="" loading="lazy" style="width:100%;height:160px;object-fit:cover;border-radius:6px;margin-bottom:12px">' : '') +
          '<div class="date">' + esc(a.date) + '</div><h3>' + esc(a.title) + '</h3>' + (a.excerpt ? '<p>' + esc(a.excerpt) + '</p>' : '') + '</div>';
      }).join(''));
    };
    var showArticle = function(aid){
      var a = list.filter(function(x){ return x.id === aid; })[0];
      if(!a){
        $('artCrumb').textContent = 'Статья не найдена'; $('artTitle').textContent = 'Статья не найдена'; $('artDate').textContent = '';
        $('artBody').innerHTML = '<p>Возможно, статья была удалена. <a data-page="blog" style="color:var(--accent-2);cursor:pointer">Перейти к списку статей</a></p>';
        return;
      }
      var im = imgsOf(a), rest = im.slice(1);
      document.title = a.title + ' — Онежские фасады';
      $('artCrumb').textContent = a.title; $('artTitle').textContent = a.title; $('artDate').textContent = a.date || '';
      $('artBody').innerHTML =
        (im[0] ? '<div class="work-photo" style="margin:0 0 24px"><img src="' + esc(im[0]) + '" alt="' + esc(a.title) + '"></div>' : '') +
        bodyHtml(a.body) +
        (rest.length ? '<div class="work-grid">' + rest.map(function(p){ return '<div class="work-item"><img src="' + esc(p) + '" alt="' + esc(a.title) + '" loading="lazy"></div>'; }).join('') + '</div>' : '');
    };
    var ready = fetch('articles.json?' + Date.now(), {cache:'no-store'})
      .then(function(r){ return r.ok ? r.json() : []; })
      .then(function(d){ list = Array.isArray(d) ? d : []; renderList(); })
      .catch(function(e){ console.error(e); });

    var origNav = window.navigateTo;
    window.navigateTo = function(id){
      id = String(id);
      if(id.indexOf('article-') !== 0) return origNav(id);
      var aid = id.slice(8);
      origNav('article');
      history.replaceState(null, '', '#page-article-' + aid);
      ready.then(function(){ showArticle(aid); });
    };
  }
})();