const state = {
  token: '',
  section: location.hash.replace('#', '') || 'dashboard',
  settingsTab: new URLSearchParams(location.search).get('settingsTab') || sessionStorage.getItem('oc_settings_tab') || 'general',
  dashboard: null,
  settings: null,
  paymentSettings: null,
  siteContent: null,
  presaleAdmin: null,
  vip: [],
  wheel: [],
  quests: [],
  users: [],
  ledger: [],
  audit: [],
  authProviders: [],
  managedWallets: [],
  presaleAllocation: null,
  distributions: null,
  emailOutbox: [],
  secrets: []
};

const app = document.querySelector('#admin-app');
const toastRoot = document.querySelector('#admin-toast');
const fmt = new Intl.NumberFormat('tr-TR');
const money = (value) => fmt.format(Number(value || 0));
const esc = (value) => String(value ?? '').replace(/[&<>'"]/g, (char) => ({
  '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;'
}[char]));
const idem = () => crypto.randomUUID();
const jsonPretty = (value) => JSON.stringify(value ?? {}, null, 2);
const toDateTimeLocal = (value) => {
  if (!value) return '';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  const offset = date.getTimezoneOffset() * 60000;
  return new Date(date.getTime() - offset).toISOString().slice(0, 16);
};
const fromDateTimeLocal = (value) => value ? new Date(value).toISOString() : null;

function baseToDecimal(value, decimals = 18, maxFraction = 8) {
  try {
    const n = BigInt(String(value || '0'));
    const scale = 10n ** BigInt(decimals);
    const whole = n / scale;
    const frac = String(n % scale).padStart(decimals, '0').slice(0, maxFraction).replace(/0+$/, '');
    return `${whole}${frac ? `.${frac}` : ''}`;
  } catch { return '0'; }
}

function decimalToBase(value, decimals = 18) {
  const text = String(value ?? '0').trim();
  if (!/^\d+(?:\.\d+)?$/.test(text)) throw new Error('Token miktarı geçersiz.');
  const [whole, fraction = ''] = text.split('.');
  const padded = (fraction + '0'.repeat(decimals)).slice(0, decimals);
  return (BigInt(whole) * (10n ** BigInt(decimals)) + BigInt(padded || '0')).toString();
}

function statusTag(value) {
  const normalized = String(value || '');
  const ok = ['active','paid','finalized','confirmed','sent','completed','configured','verified','email_confirmed'].includes(normalized);
  const bad = ['failed','rejected','cancelled','disabled','error'].includes(normalized);
  return `<span class="tag ${ok ? 'ok' : bad ? 'bad' : 'warning'}">${esc(normalized || '-')}</span>`;
}

function toast(message, type = 'success') {
  const el = document.createElement('div');
  el.className = `toast ${type}`;
  el.textContent = message;
  toastRoot.appendChild(el);
  setTimeout(() => el.remove(), 4200);
}

async function api(path, { method = 'GET', body, idempotencyKey } = {}) {
  const headers = { 'Content-Type': 'application/json', 'X-Request-ID': crypto.randomUUID() };
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
  const response = await fetch(path, { method, headers, credentials: 'same-origin', body: body == null ? undefined : JSON.stringify(body) });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(data.message || 'İşlem başarısız.');
    error.code = data.code;
    error.details = data.details;
    throw error;
  }
  return data;
}

function loginView() {
  app.className = '';
  app.innerHTML = `<div class="login-page"><form id="login-form" class="login-card"><img src="/game/assets/onlycoin-token.png" alt="OnlyCoin"><h1>ONLYCOIN ADMIN</h1><p>Yetkili yönetici hesabınızla güvenli oturum açın.</p><input class="input" id="admin-email" type="email" autocomplete="username" placeholder="Yönetici e-posta adresi" required><input class="input" id="admin-password" type="password" autocomplete="current-password" placeholder="Yönetici parolası" required><button class="primary full" style="margin-top:10px">Giriş Yap</button><small>İlk yönetici hesabı dört aşamalı kurulum sırasında oluşturulur.</small></form></div>`;
}

async function login(email, password) {
  const result = await api('/api/admin/login', { method: 'POST', body: { email, password } });
  state.token = '';
  await navigate(state.section, true);
}

function countdownText() {
  const target = new Date(state.settings?.launch_at || Date.now()).getTime();
  const diff = Math.max(0, target - Date.now());
  if (diff <= 0) return 'Lansman başladı';
  const total = Math.floor(diff / 1000);
  const days = Math.floor(total / 86400);
  const hours = Math.floor((total % 86400) / 3600);
  const minutes = Math.floor((total % 3600) / 60);
  const seconds = total % 60;
  return `${days}G ${String(hours).padStart(2, '0')}S ${String(minutes).padStart(2, '0')}D ${String(seconds).padStart(2, '0')}SN`;
}

function updateCountdown() {
  document.querySelectorAll('[data-countdown]').forEach((el) => { el.textContent = countdownText(); });
}

function layout(content, title) {
  const nav = [
    ['dashboard', 'Genel Bakış'],
    ['settings', 'Ayarlar & Entegrasyonlar'],
    ['cms', 'Site & Sayfa CMS'],
    ['tokenomics', 'Tokenomics'],
    ['roadmap', 'Roadmap'],
    ['whitepaper', 'Whitepaper'],
    ['presale', 'Presale Aşamaları'],
    ['allocation', 'Presale Tahsisat & Finalizasyon'],
    ['access', 'Üyelik & Sosyal Giriş'],
    ['wallet-admin', 'Kullanıcı Cüzdanları'],
    ['distributions', 'Lansman Dağıtımı'],
    ['mail', 'E-posta & SMTP'],
    ['vip', 'VIP Paketleri'],
    ['wheel', 'Şans Çarkı'],
    ['quests', 'Görevler'],
    ['users', 'Kullanıcılar'],
    ['ledger', 'Ledger'],
    ['audit', 'Audit Log']
  ];
  app.className = 'admin-layout';
  app.innerHTML = `<aside class="sidebar"><div class="side-brand"><img src="/game/assets/onlycoin-token.png" alt=""><div><strong>ONLYCOIN</strong><small>Yönetim Merkezi</small></div></div><div class="countdown-box">Lansmana kalan süre<b data-countdown>${countdownText()}</b></div><nav class="side-nav">${nav.map(([id, label]) => `<button class="${state.section === id ? 'active' : ''}" data-section="${id}">${label}</button>`).join('')}</nav><div class="side-footer">Platform v1.1.0 · Canlı üretim kurulumu<br><a href="/game/" target="_blank" style="color:var(--gold)">Oyunu Aç ↗</a> · <a href="/" target="_blank" style="color:var(--gold)">Siteyi Aç ↗</a></div></aside><section class="main"><header class="topbar"><h1>${esc(title)}</h1><div class="actions"><button class="secondary" data-action="refresh">Yenile</button><button class="danger" data-action="logout">Çıkış</button></div></header><main class="page"><div class="notice">🔐 Sağlayıcı gizli anahtarları veritabanında AES-256-GCM ile şifrelenir; panelde yalnızca maskeli gösterilir. Mainnet cüzdan özel anahtarları bu panele veya ZIP paketine yazılmamalıdır.</div>${content}</main></section>`;
  updateCountdown();
}

function dashboardView() {
  const d = state.dashboard;
  if (!d) return layout('<div class="empty card">Dashboard yükleniyor…</div>', 'Genel Bakış');
  const max = Math.max(1, ...d.vipDistribution.map((x) => x.users));
  return layout(`<section class="grid metrics"><div class="metric"><small>Toplam Kullanıcı</small><strong>${money(d.users)}</strong><em>Web + Telegram</em></div><div class="metric"><small>Bugün Aktif</small><strong>${money(d.activeToday)}</strong><em>Domain event bazlı</em></div><div class="metric"><small>Bugünkü Tap</small><strong>${money(d.tapsToday)}</strong><em>Sunucuda doğrulandı</em></div><div class="metric"><small>Ledger Durumu</small><strong class="${d.ledger.ok ? 'status-ok' : 'status-bad'}">${d.ledger.ok ? 'Dengeli' : 'HATA'}</strong><em>${d.ledger.accountIssues.length + d.ledger.transactionIssues.length} fark</em></div></section>
  <section class="grid two-col" style="margin-top:14px"><article class="card"><div class="card-head"><h2>VIP Dağılımı</h2></div><div class="card-body chart-bars">${d.vipDistribution.map((v) => `<div class="bar-row"><span>VIP ${v.vip_tier}</span><div class="bar"><i style="width:${Math.round(v.users / max * 100)}%"></i></div><b>${v.users}</b></div>`).join('')}</div></article><article class="card"><div class="card-head"><h2>Dönüşüm Özeti</h2></div><div class="card-body"><p>Yakılan OC_POINTS</p><strong style="font-size:28px;color:var(--gold)">${money(d.conversions.points)}</strong><p>Dağıtılan OC_TOKEN</p><strong style="font-size:28px;color:var(--gold)">${money(d.conversions.tokens)}</strong></div></article></section>
  <section class="grid two-col" style="margin-top:14px"><article class="card"><div class="card-head"><h2>En Yüksek Bakiyeler</h2></div><div class="table-wrap"><table class="table"><thead><tr><th>#</th><th>Kullanıcı</th><th>VIP</th><th>OC_POINTS</th></tr></thead><tbody>${d.topUsers.map((u) => `<tr><td>${u.rank}</td><td>${esc(u.display_name)}<br><small>@${esc(u.username)}</small></td><td><span class="tag">VIP ${u.vip_tier}</span></td><td>${money(u.points)}</td></tr>`).join('')}</tbody></table></div></article><article class="card"><div class="card-head"><h2>Sistem Hesapları</h2></div><div class="table-wrap"><table class="table"><thead><tr><th>Hesap</th><th>Varlık</th><th>Bakiye</th></tr></thead><tbody>${d.systemAccounts.map((a) => `<tr><td>${esc(a.code)}</td><td>${a.asset}</td><td>${money(a.balance)}</td></tr>`).join('')}</tbody></table></div></article></section>`, 'Genel Bakış');
}

function toLocalInput(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  const pad = (n) => String(n).padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

function boolField(key, label, hint = '') {
  return `<label class="check"><input type="checkbox" data-setting="${key}" ${state.settings?.[key] ? 'checked' : ''}><span>${esc(label)}${hint ? `<small>${esc(hint)}</small>` : ''}</span></label>`;
}

function field(key, label, type = 'number', options = {}) {
  const value = type === 'datetime-local' ? toLocalInput(state.settings?.[key]) : (state.settings?.[key] ?? '');
  const span = options.span ? ` span-${options.span}` : '';
  const attrs = [
    options.min != null ? `min="${options.min}"` : '',
    options.max != null ? `max="${options.max}"` : '',
    options.step != null ? `step="${options.step}"` : '',
    options.placeholder ? `placeholder="${esc(options.placeholder)}"` : '',
    options.dataType ? `data-type="${options.dataType}"` : ''
  ].filter(Boolean).join(' ');
  if (options.textarea) return `<div class="field${span}"><label>${esc(label)}</label><textarea class="textarea" data-setting="${key}" ${attrs}>${esc(Array.isArray(value) ? value.join(',') : value)}</textarea>${options.hint ? `<small>${esc(options.hint)}</small>` : ''}</div>`;
  if (options.select) return `<div class="field${span}"><label>${esc(label)}</label><select class="input" data-setting="${key}" ${attrs}>${options.select.map(([v, text]) => `<option value="${esc(v)}" ${String(value) === String(v) ? 'selected' : ''}>${esc(text)}</option>`).join('')}</select>${options.hint ? `<small>${esc(options.hint)}</small>` : ''}</div>`;
  return `<div class="field${span}"><label>${esc(label)}</label><input class="input" type="${type}" data-setting="${key}" value="${esc(Array.isArray(value) ? value.join(',') : value)}" ${attrs}>${options.hint ? `<small>${esc(options.hint)}</small>` : ''}</div>`;
}

function settingsSection(title, content, description = '') {
  return `<section class="card settings-card"><div class="card-head"><div><h2>${esc(title)}</h2>${description ? `<p class="card-description">${esc(description)}</p>` : ''}</div></div><div class="card-body form-grid">${content}</div></section>`;
}

function settingsTabs() {
  const tabs = [
    ['general', 'Genel & Lansman'],
    ['economy', 'Oyun Ekonomisi'],
    ['conversion', 'Dönüşüm & Transfer'],
    ['network', 'Contract & Presale'],
    ['fiat', 'Döviz & Kur'],
    ['providers', 'Ödeme Sağlayıcıları'],
    ['banks', 'Banka / SWIFT'],
    ['crypto', 'Kripto Varlıklar'],
    ['vip-prices', 'VIP Fiyatları'],
    ['messaging', 'Telegram & Bildirim'],
    ['security', 'Güvenlik & Uyum'],
    ['company', 'Şirket / SEO / Sistem']
  ];
  return `<div class="settings-tabs" role="tablist">${tabs.map(([id, label]) => `<button type="button" role="tab" class="${state.settingsTab === id ? 'active' : ''}" data-action="settings-tab" data-tab="${id}">${esc(label)}</button>`).join('')}</div>`;
}

function pane(id, content) {
  return `<div class="settings-pane ${state.settingsTab === id ? 'active' : ''}" data-settings-pane="${id}">${content}</div>`;
}

function rateDisplay(rateE8) {
  return (Number(rateE8 || 0) / 1e8).toFixed(6).replace(/0+$/, '').replace(/\.$/, '') || '0';
}

function currencyTable() {
  const rows = state.paymentSettings?.currencies || [];
  return `<section class="card settings-card"><div class="card-head"><div><h2>Fiat Para Birimleri ve Kurlar</h2><p class="card-description">Kur, 1 birim dövizin Türk lirası karşılığıdır. TCMB senkronu yalnızca TCMB tarafından yayımlanan kurları günceller.</p></div><div class="head-actions"><button type="button" class="secondary" data-action="sync-tcmb">TCMB Kurlarını Güncelle</button></div></div><div class="table-wrap"><table class="table currency-table"><thead><tr><th>Kod</th><th>Ad</th><th>Sembol</th><th>Ondalık</th><th>1 Birim = TRY</th><th>Kaynak</th><th>Aktif</th><th>Baz</th><th>Sıra</th><th></th></tr></thead><tbody>${rows.map((row) => `<tr data-currency-row="${esc(row.code)}"><td><b>${esc(row.code)}</b></td><td><input data-k="name" value="${esc(row.name)}"></td><td><input class="tiny" data-k="symbol" value="${esc(row.symbol)}"></td><td><input class="tiny" type="number" data-k="decimals" min="0" max="8" value="${row.decimals}"></td><td><input type="number" step="0.000001" min="0.000001" data-rate value="${rateDisplay(row.rate_to_try_e8)}"></td><td><span class="tag">${esc(row.source || 'tanımsız')}</span></td><td><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}></td><td><input type="checkbox" data-k="is_base" ${row.is_base ? 'checked' : ''}></td><td><input class="tiny" type="number" data-k="sort_order" value="${row.sort_order}"></td><td><button type="button" class="primary" data-action="save-currency" data-id="${esc(row.code)}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section>`;
}

function secretInput(key, label, value = '') {
  return `<div class="field"><label>${esc(label)}</label><input class="input" type="password" autocomplete="new-password" data-provider-secret="${esc(key)}" value="${esc(value)}" placeholder="Değiştirmek için yeni değer girin"><small>Boş bırakırsanız mevcut gizli değer korunur.</small></div>`;
}

function providerCard(provider) {
  const secretMap = provider.adapter === 'paytr_link'
    ? [['merchantId', 'Merchant ID'], ['merchantKey', 'Merchant Key'], ['merchantSalt', 'Merchant Salt']]
    : provider.adapter === 'iyzico_link'
      ? [['apiKey', 'API Key'], ['secretKey', 'Secret Key'], ['webhookSecret', 'Webhook Secret']]
      : provider.adapter === 'generic_hosted'
        ? [['apiKey', 'API Key / Merchant ID'], ['secretKey', 'Secret Key'], ['webhookSecret', 'Webhook Secret']]
        : [];
  const config = provider.config || {};
  const currencies = provider.currencies || [];
  return `<article class="provider-card card" data-provider-card="${esc(provider.id)}"><div class="provider-head"><div><div class="provider-title"><h3>${esc(provider.name)}</h3><span class="tag ${provider.status === 'verified' || provider.status === 'configured' ? 'ok' : provider.status === 'error' ? 'bad' : ''}">${esc(provider.status)}</span></div><p>${esc(provider.description)}</p><code>${esc(provider.adapter)}</code></div><div class="provider-switches"><label class="mini-check"><input type="checkbox" data-provider-field="enabled" ${provider.enabled ? 'checked' : ''}>Aktif</label></div></div>
    <div class="form-grid provider-config"><div class="field"><label>Görünen Ad</label><input class="input" data-provider-field="name" value="${esc(provider.name)}"></div><div class="field span-2"><label>Açıklama</label><input class="input" data-provider-field="description" value="${esc(provider.description)}"></div>${provider.adapter === 'generic_hosted' || provider.adapter === 'iyzico_link' ? `<div class="field span-2"><label>Checkout URL Şablonu</label><input class="input" data-provider-config="checkoutUrl" value="${esc(config.checkoutUrl || '')}" placeholder="https://provider.example/pay?order={orderId}&amount={amount}&currency={currency}"><small>Kullanılabilir değişkenler: {orderId}, {reference}, {amount}, {currency}, {callbackUrl}, {sessionId}</small></div><div class="field"><label>Durum API URL</label><input class="input" data-provider-config="statusUrl" value="${esc(config.statusUrl || '')}"></div>` : ''}${provider.adapter === 'paytr_link' ? `<div class="field"><label>Maksimum Taksit</label><input class="input" type="number" min="1" max="12" data-provider-config="maxInstallment" value="${esc(config.maxInstallment ?? 1)}"></div><div class="field"><label>Dil</label><select class="input" data-provider-config="lang"><option value="tr" ${(config.lang || 'tr') === 'tr' ? 'selected' : ''}>Türkçe</option><option value="en" ${config.lang === 'en' ? 'selected' : ''}>English</option></select></div><label class="check"><input type="checkbox" data-provider-config="getQr" ${config.getQr !== false ? 'checked' : ''}><span>QR kod iste</span></label>` : ''}${secretMap.map(([key, label]) => secretInput(key, label, provider.secrets?.[key] || '')).join('')}</div>
    ${currencies.length ? `<div class="provider-currencies"><h4>Para Birimleri ve Limitler</h4><div class="currency-chip-grid">${currencies.map((item) => `<div class="currency-chip" data-provider-currency="${esc(item.currency_code)}"><label><input type="checkbox" data-k="enabled" ${item.enabled ? 'checked' : ''}><b>${esc(item.currency_code)}</b></label><input type="number" data-k="min_amount_minor" value="${item.min_amount_minor}" title="Minimum alt birim"><input type="number" data-k="max_amount_minor" value="${item.max_amount_minor}" title="Maksimum alt birim"><input type="number" data-k="fee_bps" value="${item.fee_bps}" title="Komisyon BPS"><input type="number" data-k="fixed_fee_minor" value="${item.fixed_fee_minor}" title="Sabit komisyon alt birim"></div>`).join('')}</div><p class="small-note">Alan sırası: aktif · para birimi · minimum alt birim · maksimum alt birim · komisyon BPS · sabit komisyon.</p></div>` : ''}
    <div class="provider-footer"><div><b>Callback:</b> <code>${esc(state.paymentSettings?.callbackUrls?.[provider.id] || state.paymentSettings?.callbackUrls?.generic?.replace('{providerId}', provider.id) || '')}</code>${provider.last_error ? `<p class="error-text">${esc(provider.last_error)}</p>` : ''}</div><div class="head-actions"><button type="button" class="secondary" data-action="test-provider" data-id="${esc(provider.id)}">Yapılandırmayı Test Et</button><button type="button" class="primary" data-action="save-provider" data-id="${esc(provider.id)}">Sağlayıcıyı Kaydet</button></div></div></article>`;
}

function providerSettings() {
  const providers = state.paymentSettings?.providers || [];
  return `<div class="compliance-callout"><strong>Türkiye bölgesel güvenlik modu</strong><p>Kart/banka sağlayıcılarını merchant sözleşmenize göre etkinleştirin. Döviz kabulü, her sağlayıcının size tanımladığı para birimleriyle sınırlıdır. Gerçek callback adresi herkese açık HTTPS olmalıdır.</p></div><div class="provider-list">${providers.map(providerCard).join('')}</div>`;
}

function bankSettings() {
  const banks = state.paymentSettings?.bankAccounts || [];
  return `<section class="card settings-card"><div class="card-head"><div><h2>TRY / USD / EUR / GBP Banka Hesapları</h2><p class="card-description">Havale, EFT ve SWIFT yönergelerinde kullanıcıya sipariş referansı gösterilir; kredi manuel incelemeden sonra verilir.</p></div></div><div class="table-wrap"><table class="table"><thead><tr><th>Para</th><th>Banka</th><th>Hesap Sahibi</th><th>IBAN</th><th>SWIFT/BIC</th><th>Hesap No</th><th>Talimat</th><th>Aktif</th><th></th></tr></thead><tbody>${banks.map((b) => `<tr data-bank-row="${esc(b.id)}"><td><input class="tiny" data-k="currency_code" value="${esc(b.currency_code)}"></td><td><input data-k="bank_name" value="${esc(b.bank_name)}"></td><td><input data-k="account_holder" value="${esc(b.account_holder)}"></td><td><input data-k="iban" value="${esc(b.iban)}"></td><td><input data-k="swift_bic" value="${esc(b.swift_bic)}"></td><td><input data-k="account_number" value="${esc(b.account_number)}"></td><td><input data-k="instructions" value="${esc(b.instructions)}"></td><td><input type="checkbox" data-k="enabled" ${b.enabled ? 'checked' : ''}></td><td><button type="button" class="primary" data-action="save-bank" data-id="${esc(b.id)}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section>
  <section class="card settings-card"><div class="card-head"><h2>Yeni Banka / SWIFT Hesabı</h2></div><div class="card-body form-grid" id="new-bank-form"><div class="field"><label>Kimlik</label><input class="input" data-k="id" placeholder="bank-usd-2"></div><div class="field"><label>Para Birimi</label><input class="input" data-k="currency_code" value="USD"></div><div class="field"><label>Banka Adı</label><input class="input" data-k="bank_name"></div><div class="field"><label>Hesap Sahibi</label><input class="input" data-k="account_holder"></div><div class="field"><label>IBAN</label><input class="input" data-k="iban"></div><div class="field"><label>SWIFT / BIC</label><input class="input" data-k="swift_bic"></div><div class="field"><label>Hesap Numarası</label><input class="input" data-k="account_number"></div><div class="field span-2"><label>Ödeme Talimatı</label><input class="input" data-k="instructions" value="Ödeme açıklamasına sipariş referansını yazın."></div><label class="check"><input type="checkbox" data-k="enabled"><span>Aktif</span></label></div><div class="form-actions"><button type="button" class="primary" data-action="create-bank">Banka Hesabı Ekle</button></div></section>`;
}

function cryptoSettings() {
  const assets = state.paymentSettings?.cryptoAssets || [];
  return `<div class="compliance-callout warning"><strong>Kripto ödeme güvenlik sınırı</strong><p>Türkiye bölgesinde kripto ile mal/hizmet ödemesi varsayılan olarak kapalıdır. USDT, BTC ve diğer varlıkları yalnızca presale/deposit veya hukukça onaylanmış bölgelerde etkinleştirin. Özel anahtar/seed phrase bu alana girilmez.</p></div><div class="crypto-grid">${assets.map((a) => `<article class="card crypto-card" data-crypto-row="${esc(a.id)}"><div class="crypto-head"><div><strong>${esc(a.symbol)}</strong><span>${esc(a.name)} · ${esc(a.network)}</span></div><span class="tag ${a.enabled ? 'ok' : ''}">${a.enabled ? 'aktif' : 'kapalı'}</span></div><div class="form-grid"><div class="field"><label>Sembol</label><input class="input" data-k="symbol" value="${esc(a.symbol)}"></div><div class="field"><label>Ad</label><input class="input" data-k="name" value="${esc(a.name)}"></div><div class="field"><label>Ağ</label><input class="input" data-k="network" value="${esc(a.network)}"></div><div class="field"><label>Chain Ailesi</label><select class="input" data-k="chain_family">${['EVM', 'BITCOIN', 'TRON', 'TON', 'OTHER'].map((v) => `<option ${v === a.chain_family ? 'selected' : ''}>${v}</option>`).join('')}</select></div><div class="field"><label>Varlık Tipi</label><select class="input" data-k="asset_type">${['native', 'token'].map((v) => `<option ${v === a.asset_type ? 'selected' : ''}>${v}</option>`).join('')}</select></div><div class="field"><label>Ondalık</label><input class="input" type="number" data-k="decimals" value="${a.decimals}"></div><div class="field span-3"><label>Contract Adresi</label><input class="input" data-k="contract_address" value="${esc(a.contract_address)}"></div><div class="field span-3"><label>Tahsilat / Treasury Adresi</label><input class="input" data-k="deposit_address" value="${esc(a.deposit_address)}"></div><div class="field span-2"><label>RPC URL</label><input class="input" data-k="rpc_url" value="${esc(a.rpc_url)}"></div><div class="field"><label>Onay Sayısı</label><input class="input" type="number" data-k="confirmations_required" value="${a.confirmations_required}"></div><div class="field"><label>USD Fiyatı</label><input class="input" type="number" step="0.00000001" data-crypto-price value="${rateDisplay(a.manual_price_usd_e8)}"></div><div class="field"><label>Explorer URL</label><input class="input" data-k="explorer_url" value="${esc(a.explorer_url)}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${a.sort_order}"></div><label class="check"><input type="checkbox" data-k="enabled" ${a.enabled ? 'checked' : ''}><span>Varlık aktif</span></label><label class="check"><input type="checkbox" data-k="purchase_enabled" ${a.purchase_enabled ? 'checked' : ''}><span>Ödemede kullanılabilir</span></label><label class="check"><input type="checkbox" data-k="deposit_enabled" ${a.deposit_enabled ? 'checked' : ''}><span>Deposit aktif</span></label><label class="check"><input type="checkbox" data-k="withdrawal_enabled" ${a.withdrawal_enabled ? 'checked' : ''}><span>Withdrawal aktif</span></label></div><div class="form-actions"><button type="button" class="primary" data-action="save-crypto" data-id="${esc(a.id)}">${esc(a.symbol)} Ayarını Kaydet</button></div></article>`).join('')}</div>`;
}

function vipPriceSettings() {
  const rows = state.paymentSettings?.vipPrices || [];
  const display = (row) => {
    const decimals = row.currency_code === 'USDT' ? 6 : Number(state.paymentSettings?.currencies?.find((c) => c.code === row.currency_code)?.decimals ?? 2);
    return { decimals, value: Number(row.amount_minor || 0) / (10 ** decimals) };
  };
  return `<section class="card settings-card"><div class="card-head"><div><h2>VIP 1–VIP 5 Çoklu Para Birimi Fiyatları</h2><p class="card-description">Kart sağlayıcısında seçilen dövizle ödeme alınabilir. USDT fiyatı mevcut VIP ödeme emrinin settlement tutarı olarak kullanılır.</p></div></div><div class="table-wrap"><table class="table"><thead><tr><th>VIP</th><th>Para Birimi</th><th>Fiyat</th><th>Alt Birim</th><th>Aktif</th><th></th></tr></thead><tbody>${rows.map((row) => { const d = display(row); return `<tr data-vip-price-row="${row.tier}:${esc(row.currency_code)}"><td><span class="tag">VIP ${row.tier}</span><br>${esc(row.vip_name)}</td><td><b>${esc(row.currency_code)}</b></td><td><input type="number" min="0" step="${d.decimals ? 1 / (10 ** Math.min(d.decimals, 8)) : 1}" data-price-display value="${d.value}"></td><td>${d.decimals} ondalık</td><td><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}></td><td><button type="button" class="primary" data-action="save-vip-price" data-tier="${row.tier}" data-currency="${esc(row.currency_code)}" data-decimals="${d.decimals}">Kaydet</button></td></tr>`; }).join('')}</tbody></table></div></section>`;
}

function settingsView() {
  const s = state.settings;
  if (!s || !state.paymentSettings) return layout('<div class="empty card">Ayarlar ve ödeme altyapısı yükleniyor…</div>', 'Ayarlar & Entegrasyonlar');
  const general = settingsSection('Lansman ve Genel Ayarlar', `${field('app_name', 'Uygulama Adı', 'text')}${field('launch_at', 'Lansman Tarihi', 'datetime-local')}${field('launch_message', 'Sayaç Başlığı', 'text')}${field('announcement', 'Global Duyuru', 'text', { textarea: true, span: 3 })}${field('maintenance_message', 'Bakım Mesajı', 'text', { span: 3 })}${boolField('maintenance_mode', 'Bakım modu')}${boolField('site_enabled', 'Web sitesi aktif')}${boolField('telegram_enabled', 'Telegram Mini App aktif')}${boolField('pwa_enabled', 'PWA aktif')}${boolField('android_enabled', 'Android aktif')}${boolField('ios_enabled', 'iOS aktif')}${boolField('purchases_enabled', 'Satın alma modülleri aktif')}`);
  const economy = settingsSection('Tap-to-Earn Ekonomisi', `${field('initial_points', 'Kayıt Başlangıç Puanı')}${field('tap_reward_points', 'Tap Başına Puan')}${field('tap_batch_limit', 'Maksimum Tap Batch')}${field('energy_capacity', 'Temel Enerji Kapasitesi')}${field('energy_refill_per_minute', 'Dakikada Enerji')}${field('auto_points_per_hour', 'Saatlik Otomatik Puan')}${field('auto_offline_cap_hours', 'Offline Kazanç Üst Sınırı (Saat)')}${field('paid_spin_cost_points', 'Ücretli Çark Maliyeti')}${field('wheel_daily_free_spins', 'Günlük Ücretsiz Çark Hakkı')}${field('wheel_daily_total_limit', 'Günlük Toplam Çark Limiti')}${field('wheel_spin_cooldown_seconds', 'İki Çevirme Arası Bekleme (sn)', 'number', { hint: 'Sunucu bu değeri animasyon süresinden kısa kabul etmez.' })}${field('wheel_animation_ms', 'Çark Animasyonu (ms)')}${boolField('wheel_prevent_immediate_repeat', 'Aynı ödülün peş peşe gelmesini engelle')}`) + settingsSection('Arkadaş Daveti', `${field('referral_reward_points', 'Nitelikli Davet Ödülü')}${field('referral_qualifying_taps', 'Nitelik İçin Tap Sayısı')}${field('referral_level_1_bps', '1. Seviye BPS')}${field('referral_level_2_bps', '2. Seviye BPS')}${field('referral_level_3_bps', '3. Seviye BPS')}${boolField('referral_multilevel_enabled', '2. ve 3. seviye aktif', 'Hukuki ve mağaza politikası incelemesi sonrası etkinleştirin.')}`);
  const conversion = settingsSection('OC_POINTS → OC_TOKEN Dönüşümü', `${boolField('conversion_enabled', 'Dönüşüm aktif')}${boolField('conversion_unlock_at_launch', 'Lansmana kadar kilitle')}<div class="field"><label>Dönüşüm Yüzdesi</label><input class="input" type="number" step="0.01" min="0.01" data-setting-display="conversion_rate_bps" value="${Number(s.conversion_rate_bps) / 100}"><small>Örnek %10: 1000 puan → 100 token</small></div>${field('conversion_min_points', 'Minimum OC_POINTS')}${field('conversion_daily_limit_points', 'Günlük Kullanıcı Limiti')}`) + settingsSection('Oyuncular Arası OC_POINTS Transferi', `${boolField('points_transfer_enabled', 'Point transferi aktif')}${field('points_transfer_min', 'Minimum Transfer')}${field('points_transfer_max', 'Maksimum Transfer')}${field('points_transfer_daily_limit', 'Günlük Transfer Limiti')}${field('points_transfer_fee_bps', 'Komisyon (BPS)', 'number', { hint: '100 BPS = %1' })}`);
  const network = settingsSection('Contract ve Ağ', `${field('project_token_symbol', 'Token Sembolü', 'text')}${field('project_token_decimals', 'Token Ondalık')}${field('project_token_contract', 'OC_TOKEN Contract Adresi', 'text', { span: 3 })}${field('usdt_network_name', 'USDT Ağ Adı', 'text')}${field('usdt_chain_id', 'Chain ID')}${field('usdt_decimals', 'USDT Ondalık')}${field('usdt_contract_address', 'USDT Contract Adresi', 'text', { span: 3 })}${field('treasury_deposit_address', 'Treasury / Tahsilat Adresi', 'text', { span: 3 })}${field('blockchain_explorer_url', 'Explorer URL', 'url', { span: 2 })}${field('blockchain_rpc_mode', 'RPC Modu', 'text')}`) + settingsSection('Presale Ayarları', `${boolField('presale_enabled', 'Presale aktif')}${boolField('presale_require_launch', 'Lansman tarihine kadar satış kilitli')}${field('presale_min_usdt_micros', 'Minimum USDT (mikro)')}${field('presale_max_usdt_micros', 'Maksimum USDT (mikro)')}${field('presale_soft_cap_usdt_micros', 'Soft Cap USDT (mikro)')}${field('presale_hard_cap_usdt_micros', 'Hard Cap USDT (mikro)')}${field('presale_total_token_base_units', 'Presale Token Tahsisi')}`);
  const fiat = settingsSection('Fiat ve Döviz Politikası', `${boolField('fiat_payments_enabled', 'Fiat/kart ödemeleri aktif')}${boolField('bank_transfer_enabled', 'Banka havalesi / SWIFT aktif')}${field('base_currency', 'Baz Para Birimi', 'text')}${field('display_currency', 'Varsayılan Gösterim Para Birimi', 'text')}${field('settlement_currency', 'Muhasebe Settlement Para Birimi', 'text')}${field('enabled_fiat_currencies', 'Etkin Fiat Kodları', 'text', { dataType: 'csv', span: 2, hint: 'Virgülle ayırın: TRY,USD,EUR,GBP' })}${field('fx_rate_source', 'Kur Kaynağı', 'text')}${boolField('fx_auto_update_enabled', 'Otomatik kur güncellemesi')}${field('fx_update_interval_minutes', 'Kur Güncelleme Aralığı (dk)')}${field('fx_rate_margin_bps', 'Kur Marjı (BPS)')}${field('payment_order_expiry_minutes', 'Ödeme Emri Süresi (dk)')}${field('payment_callback_base_url', 'Public HTTPS Callback Temeli', 'url', { span: 2, hint: 'Örnek: https://onlycoin.example' })}${field('payment_success_url', 'Başarı Yönlendirmesi', 'text')}${field('payment_failure_url', 'Hata Yönlendirmesi', 'text')}${field('payment_max_installment', 'Maksimum Taksit')}${boolField('payment_3d_secure_required', '3D Secure zorunlu')}${field('payment_provider_timeout_seconds', 'Sağlayıcı Timeout (sn)')}`) + currencyTable();
  const cryptoGlobal = settingsSection('Kripto Fonlama Politikası', `${boolField('crypto_funding_enabled', 'Kripto fonlama kataloğu aktif')}${boolField('crypto_payment_for_goods_enabled', 'Kripto ile VIP/dijital ürün ödemesi aktif', 'Türkiye için varsayılan kapalı kalmalıdır.')}${field('crypto_payment_region_mode', 'Bölgesel Mod', 'text', { select: [['presale_deposit_only', 'Yalnızca Presale / Deposit'], ['regulated_only', 'Yalnızca Uyum Onaylı Bölgeler'], ['all_enabled', 'Tüm Kullanım Alanları']] })}${boolField('deposit_enabled', 'Deposit aktif')}${boolField('withdrawal_enabled', 'Withdrawal aktif')}${field('withdrawal_min_token', 'Minimum OC_TOKEN Çekim')}${field('withdrawal_fee_token', 'OC_TOKEN Çekim Ücreti')}${field('withdrawal_daily_limit_token', 'Günlük OC_TOKEN Çekim Limiti')}${field('withdrawal_min_usdt_micros', 'Minimum USDT Çekim (mikro)')}${field('withdrawal_fee_usdt_micros', 'USDT Çekim Ücreti (mikro)')}${field('withdrawal_daily_limit_usdt_micros', 'Günlük USDT Çekim Limiti (mikro)')}`) + cryptoSettings();
  const messaging = settingsSection('Telegram Kimliği', `${boolField('telegram_login_enabled', 'Telegram web girişi aktif')}${field('telegram_bot_username', 'Bot Kullanıcı Adı', 'text')}${boolField('telegram_phone_collection_enabled', 'İzinli telefon paylaşımı aktif')}${field('support_email', 'Destek E-posta', 'email')}${field('support_phone', 'Destek Telefonu', 'text')}`) + settingsSection('E-posta, SMS ve Push', `${boolField('smtp_enabled', 'SMTP aktif')}${field('smtp_host', 'SMTP Sunucusu', 'text')}${field('smtp_port', 'SMTP Port')}${boolField('smtp_secure', 'SMTP TLS/SSL')}${field('smtp_username', 'SMTP Kullanıcı Adı', 'text')}${field('smtp_from_email', 'Gönderen E-posta', 'email')}${field('smtp_from_name', 'Gönderen Adı', 'text')}${field('sms_provider', 'SMS Sağlayıcısı', 'text')}${field('sms_sender', 'SMS Başlığı', 'text')}${boolField('push_enabled', 'Push bildirimleri aktif')}${field('firebase_project_id', 'Firebase Project ID', 'text', { span: 2 })}`);
  const security = settingsSection('KYC / AML / Bölge Kuralları', `${boolField('kyc_required_for_crypto', 'Kripto işlemlerinde KYC zorunlu')}${boolField('kyc_required_for_withdrawal', 'Çekimde KYC zorunlu')}${boolField('aml_screening_enabled', 'AML risk taraması aktif')}${boolField('sanctions_screening_enabled', 'Yaptırım listesi taraması aktif')}${field('min_user_age', 'Minimum Yaş')}${field('country_code', 'Varsayılan Ülke', 'text')}${field('allowed_country_codes', 'İzinli Ülkeler', 'text', { dataType: 'csv', span: 2 })}${field('blocked_country_codes', 'Engelli Ülkeler', 'text', { dataType: 'csv', span: 2 })}`) + settingsSection('Oturum, Audit ve Hız Limitleri', `${field('session_duration_minutes', 'Kullanıcı Oturumu (dk)')}${field('admin_session_duration_minutes', 'Admin Oturumu (dk)')}${field('rate_limit_profile', 'Rate Limit Profili', 'text')}${field('audit_retention_days', 'Audit Saklama (gün)')}${field('payment_webhook_replay_window_seconds', 'Webhook Replay Penceresi (sn)')}`);
  const company = settingsSection('Şirket ve Yasal Bilgiler', `${field('company_legal_name', 'Şirket Ünvanı', 'text', { span: 2 })}${field('company_tax_office', 'Vergi Dairesi', 'text')}${field('company_tax_number', 'Vergi Numarası', 'text')}${field('company_mersis_number', 'MERSİS Numarası', 'text')}${field('privacy_contact_email', 'Gizlilik E-postası', 'email')}${field('company_address', 'Şirket Adresi', 'text', { textarea: true, span: 3 })}`) + settingsSection('Dil, SEO ve Analitik', `${field('default_language', 'Varsayılan Dil', 'text')}${field('enabled_languages', 'Etkin Diller', 'text', { dataType: 'csv' })}${field('timezone', 'Saat Dilimi', 'text')}${field('seo_default_title', 'SEO Varsayılan Başlık', 'text', { span: 2 })}${field('seo_default_description', 'SEO Varsayılan Açıklama', 'text', { textarea: true, span: 3 })}${boolField('analytics_enabled', 'Analitik aktif')}${field('analytics_provider', 'Analitik Sağlayıcısı', 'text')}${field('analytics_measurement_id', 'Measurement ID', 'text')}`) + settingsSection('Yedekleme ve Sistem', `${boolField('backup_enabled', 'Otomatik yedekleme aktif')}${field('backup_retention_days', 'Yedek Saklama (gün)')}`);

  const content = `${settingsTabs()}<form id="settings-form" class="settings-form">${pane('general', general)}${pane('economy', economy)}${pane('conversion', conversion)}${pane('network', network)}${pane('fiat', fiat)}${pane('providers', providerSettings())}${pane('banks', bankSettings())}${pane('crypto', cryptoGlobal)}${pane('vip-prices', vipPriceSettings())}${pane('messaging', messaging)}${pane('security', security)}${pane('company', company)}<div class="sticky-save"><span>Genel ayarlar için değişiklikleri kaydedin. Sağlayıcı, kur, banka, kripto ve VIP fiyat kartları kendi Kaydet düğmelerini kullanır.</span><button type="submit" class="primary">Genel Ayarları Kaydet</button></div></form>`;
  return layout(content, 'Ayarlar & Entegrasyonlar');
}

function vipView() {
  return layout(`<section class="card"><div class="card-head"><h2>VIP Planları</h2><span class="tag">Tap · Enerji · Otomatik · Çark · Referans</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Seviye</th><th>Ad</th><th>Fiyat Puan</th><th>Tap BPS</th><th>Enerji BPS</th><th>Auto BPS</th><th>VIP Ek Ücretsiz Çark</th><th>Referans BPS</th><th>Aktif</th><th></th></tr></thead><tbody>${state.vip.map((v) => `<tr data-vip-row="${v.tier}"><td><span class="tag">VIP ${v.tier}</span></td><td><input data-k="name" value="${esc(v.name)}"><br><input data-k="subtitle" value="${esc(v.subtitle)}"></td><td><input class="tiny" type="number" data-k="price_points" value="${v.price_points}"></td><td><input class="tiny" type="number" data-k="tap_multiplier_bps" value="${v.tap_multiplier_bps}"></td><td><input class="tiny" type="number" data-k="energy_multiplier_bps" value="${v.energy_multiplier_bps}"></td><td><input class="tiny" type="number" data-k="auto_multiplier_bps" value="${v.auto_multiplier_bps}"></td><td><input class="tiny" type="number" data-k="daily_free_spins" value="${v.daily_free_spins}"></td><td><input class="tiny" type="number" data-k="referral_multiplier_bps" value="${v.referral_multiplier_bps}"></td><td><input type="checkbox" data-k="enabled" ${v.enabled ? 'checked' : ''}></td><td><button class="primary" data-action="save-vip" data-id="${v.tier}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section>`, 'VIP Paketleri');
}

function wheelView() {
  const total = state.wheel.reduce((sum, item) => sum + (item.enabled ? item.weight : 0), 0);
  const s = state.settings || {};
  return layout(`<section class="grid two-col wheel-admin-grid"><article class="card"><div class="card-head"><div><h2>Çark Genel Kuralları</h2><p class="card-description">Günlük hak, toplam limit, bekleme süresi ve animasyon burada yönetilir.</p></div><span class="tag">Sunucu Otoriteli</span></div><div class="card-body form-grid" id="wheel-rules-form">
    <div class="field"><label>Temel Günlük Ücretsiz Hak</label><input class="input" type="number" min="0" max="100" data-setting="wheel_daily_free_spins" value="${Number(s.wheel_daily_free_spins ?? 3)}"></div>
    <div class="field"><label>Günlük Toplam Çevirme Limiti</label><input class="input" type="number" min="1" max="1000" data-setting="wheel_daily_total_limit" value="${Number(s.wheel_daily_total_limit ?? 10)}"></div>
    <div class="field"><label>İki Çevirme Arası Bekleme</label><input class="input" type="number" min="1" max="600" data-setting="wheel_spin_cooldown_seconds" value="${Number(s.wheel_spin_cooldown_seconds ?? 5)}"><small>Saniye. Hızlı ardışık istekleri ödül oluşmadan reddeder.</small></div>
    <div class="field"><label>Animasyon Süresi</label><input class="input" type="number" min="1500" max="15000" step="100" data-setting="wheel_animation_ms" value="${Number(s.wheel_animation_ms ?? 4600)}"><small>Milisaniye.</small></div>
    <div class="field"><label>Ücretli Çevirme Maliyeti</label><input class="input" type="number" min="0" data-setting="paid_spin_cost_points" value="${Number(s.paid_spin_cost_points ?? 50)}"></div>
    <label class="check"><input type="checkbox" data-setting="wheel_prevent_immediate_repeat" ${s.wheel_prevent_immediate_repeat !== false ? 'checked' : ''}><span>Peş peşe aynı ödülü engelle<small>Aktif dilim sayısı birden fazlaysa uygulanır.</small></span></label>
  </div><div class="form-actions wheel-rule-actions"><button class="primary" data-action="save-wheel-rules">Çark Kurallarını Kaydet</button></div></article>
  <article class="card"><div class="card-head"><h2>Güvenlik Özeti</h2></div><div class="card-body"><div class="compliance-callout"><strong>Hızlı tıklama koruması</strong><p>İstemci düğmeyi kilitler; sunucu aynı anda gelen istekleri transaction, cooldown ve Idempotency-Key ile ayrıca engeller.</p></div><div class="compliance-callout"><strong>Sabit çark iğnesi</strong><p>İğne çarkın dışındadır. Yalnızca disk döner; sunucu sonucuna göre doğru dilim iğnenin altında durur.</p></div><div class="compliance-callout warning"><strong>Günlük limit</strong><p>Ücretsiz hak ve günlük toplam hak birbirinden bağımsızdır. VIP ek hakları temel ücretsiz haklara eklenir.</p></div></div></article></section>
  <section class="card" style="margin-top:14px"><div class="card-head"><div><h2>Şans Çarkı Dilimleri</h2><p class="card-description">Renk, ağırlık ve ödül değerleri gerçek oyun çarkına doğrudan yansır.</p></div><span class="tag">Toplam Ağırlık ${total}</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Dilim</th><th>Renk</th><th>Ödül Türü</th><th>Değer</th><th>Ağırlık</th><th>Olasılık</th><th>Sıra</th><th>Aktif</th><th></th></tr></thead><tbody>${state.wheel.map((w) => `<tr data-wheel-row="${esc(w.id)}"><td><input data-k="label" value="${esc(w.label)}"></td><td><input class="color-input" type="color" data-k="color" value="${esc(w.color || '#17140d')}"></td><td><select data-k="reward_type">${['points', 'energy', 'booster', 'vip_trial', 'ad_spin'].map((t) => `<option ${t === w.reward_type ? 'selected' : ''}>${t}</option>`).join('')}</select></td><td><input class="tiny" type="number" data-k="reward_value" value="${w.reward_value}"></td><td><input class="tiny" type="number" data-k="weight" value="${w.weight}"></td><td>${total ? ((w.enabled ? w.weight : 0) / total * 100).toFixed(2) : 0}%</td><td><input class="tiny" type="number" data-k="sort_order" value="${w.sort_order}"></td><td><input type="checkbox" data-k="enabled" ${w.enabled ? 'checked' : ''}></td><td><button class="primary" data-action="save-wheel" data-id="${esc(w.id)}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section><div class="notice" style="margin-top:14px">Çark sonucu, hak tüketimi ve ödül kredisi tek veritabanı transaction’ında gerçekleşir. Aynı idempotency anahtarı ikinci kez ödül üretemez.</div>`, 'Şans Çarkı');
}

function cmsView() {
  const data = state.siteContent || { pages: [], sections: [] };
  return layout(`<section class="section-intro"><div><span class="eyebrow">CANLI SİTE İÇERİĞİ</span><h2>Site & Sayfa CMS</h2><p>Ana sayfa, Presale, Tokenomics, Roadmap ve Whitepaper hero alanlarını ve bölüm içeriklerini buradan düzenleyin.</p></div><a class="secondary preview-link" href="/" target="_blank">Canlı Siteyi Aç ↗</a></section>
  <div class="editor-grid">${data.pages.map((page) => `<article class="card editor-card" data-page-editor="${esc(page.slug)}"><div class="card-head"><div><h2>${esc(page.nav_label)} Sayfası</h2><p class="card-description">/${page.slug === 'home' ? '' : esc(page.slug)}</p></div><label class="mini-check"><input type="checkbox" data-k="enabled" ${page.enabled ? 'checked' : ''}>Aktif</label></div><div class="card-body form-grid"><div class="field"><label>Menü Etiketi</label><input class="input" data-k="nav_label" value="${esc(page.nav_label)}"></div><div class="field"><label>Sayfa Başlığı</label><input class="input" data-k="title" value="${esc(page.title)}"></div><div class="field"><label>Hero Başlık</label><input class="input" data-k="hero_title" value="${esc(page.hero_title)}"></div><div class="field"><label>Altın Vurgu</label><input class="input" data-k="hero_accent" value="${esc(page.hero_accent)}"></div><div class="field span-3"><label>Hero Alt Başlık</label><input class="input" data-k="hero_subtitle" value="${esc(page.hero_subtitle)}"></div><div class="field span-3"><label>Hero Açıklama</label><textarea class="input" data-k="hero_description">${esc(page.hero_description)}</textarea></div><div class="field"><label>Birincil Buton</label><input class="input" data-k="primary_cta_label" value="${esc(page.primary_cta_label)}"></div><div class="field"><label>Birincil URL</label><input class="input" data-k="primary_cta_url" value="${esc(page.primary_cta_url)}"></div><div class="field"><label>İkincil Buton</label><input class="input" data-k="secondary_cta_label" value="${esc(page.secondary_cta_label)}"></div><div class="field"><label>İkincil URL</label><input class="input" data-k="secondary_cta_url" value="${esc(page.secondary_cta_url)}"></div><div class="field span-2"><label>Meta Başlık</label><input class="input" data-k="meta_title" value="${esc(page.meta_title)}"></div><div class="field span-3"><label>Meta Açıklama</label><textarea class="input" data-k="meta_description">${esc(page.meta_description)}</textarea></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${page.sort_order}"></div></div><div class="form-actions"><button class="primary" data-action="save-site-page" data-id="${esc(page.slug)}">Sayfayı Kaydet</button></div></article>`).join('')}</div>
  <section class="card" style="margin-top:14px"><div class="card-head"><div><h2>Sayfa Bölümleri</h2><p class="card-description">Kartlar, adımlar, SSS ve özel içerikler JSON olarak yönetilir. Geçerli JSON zorunludur.</p></div></div><div class="editor-grid section-editor-grid">${data.sections.map((section) => `<article class="editor-card compact" data-section-editor="${esc(section.id)}"><div class="editor-title"><div><span class="tag">${esc(section.page_slug)} / ${esc(section.section_key)}</span><h3>${esc(section.title)}</h3></div><label class="mini-check"><input type="checkbox" data-k="enabled" ${section.enabled ? 'checked' : ''}>Aktif</label></div><div class="form-grid"><div class="field span-2"><label>Başlık</label><input class="input" data-k="title" value="${esc(section.title)}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${section.sort_order}"></div><div class="field span-3"><label>Alt Başlık</label><input class="input" data-k="subtitle" value="${esc(section.subtitle)}"></div><div class="field span-3"><label>İçerik JSON</label><textarea class="input code-area" data-json-content>${esc(jsonPretty(section.content))}</textarea></div></div><div class="form-actions"><button class="primary" data-action="save-site-section" data-id="${esc(section.id)}">Bölümü Kaydet</button></div></article>`).join('')}</div></section>`, 'Site & Sayfa CMS');
}

function tokenomicsView() {
  const rows = state.siteContent?.allocations || [];
  const total = rows.reduce((sum, row) => sum + Number(row.percentage_bps || 0), 0);
  return layout(`<section class="section-intro"><div><span class="eyebrow">TOKEN MODELİ</span><h2>Tokenomics Yönetimi</h2><p>Tahsisat, yüzde, miktar, açıklama, vesting ve görsel renkleri düzenleyin.</p></div><a class="secondary preview-link" href="/tokenomics" target="_blank">Tokenomics Sayfası ↗</a></section><div class="notice">Toplam dağılım: <b>${(total / 100).toFixed(2)}%</b>. Üretim yayını öncesi toplamın %100 olması önerilir.</div><section class="card" style="margin-top:14px"><div class="table-wrap"><table class="table"><thead><tr><th>Kategori</th><th>Yüzde</th><th>Token</th><th>Açıklama</th><th>Vesting</th><th>Renk</th><th>Sıra</th><th>Aktif</th><th></th></tr></thead><tbody>${rows.map((row) => `<tr data-allocation-row="${esc(row.id)}"><td><input data-k="label" value="${esc(row.label)}"></td><td><input class="tiny" type="number" step="0.01" data-percent value="${Number(row.percentage_bps) / 100}"></td><td><input type="number" data-k="token_amount" value="${row.token_amount}"></td><td><textarea data-k="description">${esc(row.description)}</textarea></td><td><textarea data-k="vesting">${esc(row.vesting)}</textarea></td><td><input class="color-input" type="color" data-k="color" value="${esc(row.color)}"></td><td><input class="tiny" type="number" data-k="sort_order" value="${row.sort_order}"></td><td><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}></td><td><button class="primary" data-action="save-allocation" data-id="${esc(row.id)}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section>`, 'Tokenomics');
}

function roadmapView() {
  const rows = state.siteContent?.roadmap || [];
  return layout(`<section class="section-intro"><div><span class="eyebrow">STRATEJİK PLAN</span><h2>Roadmap Yönetimi</h2><p>Aşamaları, ilerleme yüzdesini, durumu ve kilometre taşlarını yönetin.</p></div><a class="secondary preview-link" href="/roadmap" target="_blank">Roadmap Sayfası ↗</a></section><div class="editor-grid">${rows.map((row) => `<article class="card editor-card" data-roadmap-row="${esc(row.id)}"><div class="card-head"><div><span class="tag ${row.status === 'current' ? 'ok' : ''}">PHASE ${row.phase_no} · ${esc(row.status)}</span><h2>${esc(row.title)}</h2></div><label class="mini-check"><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}>Aktif</label></div><div class="card-body form-grid"><div class="field"><label>Aşama No</label><input class="input" type="number" data-k="phase_no" value="${row.phase_no}"></div><div class="field"><label>Başlık</label><input class="input" data-k="title" value="${esc(row.title)}"></div><div class="field"><label>Alt Başlık</label><input class="input" data-k="subtitle" value="${esc(row.subtitle)}"></div><div class="field"><label>Durum</label><select class="input" data-k="status">${['completed','current','upcoming','paused'].map((v) => `<option ${v === row.status ? 'selected' : ''}>${v}</option>`).join('')}</select></div><div class="field"><label>Tamamlanma %</label><input class="input" type="number" min="0" max="100" data-k="completion_percent" value="${row.completion_percent}"></div><div class="field"><label>İkon</label><input class="input" data-k="icon" value="${esc(row.icon)}"></div><div class="field"><label>Başlangıç</label><input class="input" type="datetime-local" data-date-k="start_at" value="${toDateTimeLocal(row.start_at)}"></div><div class="field"><label>Bitiş</label><input class="input" type="datetime-local" data-date-k="end_at" value="${toDateTimeLocal(row.end_at)}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${row.sort_order}"></div><div class="field span-3"><label>Kilometre Taşları (her satır bir madde)</label><textarea class="input tall" data-items>${esc((row.items || []).join('\n'))}</textarea></div></div><div class="form-actions"><button class="primary" data-action="save-roadmap" data-id="${esc(row.id)}">Aşamayı Kaydet</button></div></article>`).join('')}</div>`, 'Roadmap');
}

function whitepaperView() {
  const wp = state.siteContent || { chapters: [] };
  const settings = state.settings || {};
  return layout(`<section class="section-intro"><div><span class="eyebrow">TEKNİK BELGE</span><h2>Whitepaper Yönetimi</h2><p>Belge metadatasını, indirme bağlantısını ve tüm bölümleri düzenleyin.</p></div><a class="secondary preview-link" href="/whitepaper" target="_blank">Whitepaper Sayfası ↗</a></section><section class="card"><div class="card-head"><h2>Belge Bilgileri</h2></div><div class="card-body form-grid" id="whitepaper-settings"><div class="field"><label>Versiyon</label><input class="input" data-setting="whitepaper_version" value="${esc(settings.whitepaper_version || '1.0')}"></div><div class="field"><label>Son Güncelleme</label><input class="input" data-setting="whitepaper_updated_at" value="${esc(settings.whitepaper_updated_at || '')}"></div><div class="field"><label>Toplam Sayfa</label><input class="input" type="number" data-setting="whitepaper_total_pages" value="${Number(settings.whitepaper_total_pages || 42)}"></div><div class="field span-3"><label>PDF İndirme URL</label><input class="input" data-setting="whitepaper_download_url" value="${esc(settings.whitepaper_download_url || '')}" placeholder="/documents/onlycoin-whitepaper.pdf"></div></div><div class="form-actions"><button class="primary" data-action="save-whitepaper-settings">Belge Bilgilerini Kaydet</button></div></section><div class="editor-grid" style="margin-top:14px">${(wp.chapters || []).map((row) => `<article class="card editor-card" data-chapter-row="${esc(row.id)}"><div class="card-head"><div><span class="tag">BÖLÜM ${row.chapter_no}</span><h2>${esc(row.title)}</h2></div><label class="mini-check"><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}>Aktif</label></div><div class="card-body form-grid"><div class="field"><label>Bölüm No</label><input class="input" type="number" data-k="chapter_no" value="${row.chapter_no}"></div><div class="field"><label>Başlık</label><input class="input" data-k="title" value="${esc(row.title)}"></div><div class="field"><label>İkon</label><input class="input" data-k="icon" value="${esc(row.icon)}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${row.sort_order}"></div><div class="field span-3"><label>Özet</label><textarea class="input" data-k="summary">${esc(row.summary)}</textarea></div><div class="field span-3"><label>İçerik (Güvenli HTML)</label><textarea class="input code-area tall" data-k="content_html">${esc(row.content_html)}</textarea></div></div><div class="form-actions"><button class="primary" data-action="save-chapter" data-id="${esc(row.id)}">Bölümü Kaydet</button></div></article>`).join('')}</div>`, 'Whitepaper');
}

function presaleView() {
  const data = state.presaleAdmin || { stages: [], totals: {}, purchases: [] };
  return layout(`<section class="section-intro"><div><span class="eyebrow">TOKEN SATIŞI</span><h2>Presale Aşamaları</h2><p>Fiyat, bonus, tahsisat, limitler, tarihler ve aktif aşamayı yönetin.</p></div><a class="secondary preview-link" href="/presale" target="_blank">Presale Sayfası ↗</a></section><section class="grid metrics"><div class="metric"><small>Toplanan USDT</small><strong>${(Number(data.totals?.usdt_micros || 0) / 1e6).toLocaleString('tr-TR')}</strong></div><div class="metric"><small>Tahsis Edilen Token</small><strong>${money(data.totals?.tokens || 0)}</strong></div><div class="metric"><small>Onaylı Satın Alma</small><strong>${money(data.totals?.purchases || 0)}</strong></div></section><div class="editor-grid" style="margin-top:14px">${(data.stages || []).map((row) => `<article class="card editor-card" data-stage-row="${esc(row.id)}"><div class="card-head"><div><span class="tag ${row.status === 'active' ? 'ok' : ''}">STAGE ${row.stage_no} · ${esc(row.status)}</span><h2>${esc(row.name)}</h2></div><label class="mini-check"><input type="checkbox" data-k="enabled" ${row.enabled ? 'checked' : ''}>Aktif</label></div><div class="card-body form-grid"><div class="field"><label>Ad</label><input class="input" data-k="name" value="${esc(row.name)}"></div><div class="field"><label>Aşama No</label><input class="input" type="number" data-k="stage_no" value="${row.stage_no}"></div><div class="field"><label>Fiyat (USDT)</label><input class="input" type="number" step="0.000001" data-micros-k="price_usdt_micros" value="${Number(row.price_usdt_micros) / 1e6}"></div><div class="field"><label>Bonus %</label><input class="input" type="number" step="0.01" data-bps-k="bonus_bps" value="${Number(row.bonus_bps) / 100}"></div><div class="field"><label>Tahsisat Token</label><input class="input" type="number" data-k="allocation_token_base" value="${row.allocation_token_base}"></div><div class="field"><label>Satılan Token</label><input class="input" disabled value="${row.sold_token_base}"></div><div class="field"><label>Minimum USDT</label><input class="input" type="number" step="0.01" data-micros-k="min_usdt_micros" value="${Number(row.min_usdt_micros) / 1e6}"></div><div class="field"><label>Maksimum USDT</label><input class="input" type="number" step="0.01" data-micros-k="max_usdt_micros" value="${Number(row.max_usdt_micros) / 1e6}"></div><div class="field"><label>Durum</label><select class="input" data-k="status">${['draft','upcoming','active','completed','paused'].map((v) => `<option ${v === row.status ? 'selected' : ''}>${v}</option>`).join('')}</select></div><div class="field"><label>Başlangıç</label><input class="input" type="datetime-local" data-date-k="starts_at" value="${toDateTimeLocal(row.starts_at)}"></div><div class="field"><label>Bitiş</label><input class="input" type="datetime-local" data-date-k="ends_at" value="${toDateTimeLocal(row.ends_at)}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sort_order" value="${row.sort_order}"></div></div><div class="form-actions"><button class="primary" data-action="save-stage" data-id="${esc(row.id)}">Aşamayı Kaydet</button></div></article>`).join('')}</div>`, 'Presale Yönetimi');
}

function authProviderCard(provider) {
  const callbackOrigin = location.origin && location.origin !== 'null' ? location.origin : 'https://app.onlycoin.example';
  const callback = `${callbackOrigin}/api/auth/oauth/${encodeURIComponent(provider.id)}/callback`;
  return `<article class="card integration-card" data-auth-provider="${esc(provider.id)}"><div class="card-head"><div><h2>${esc(provider.name)}</h2><p class="card-description">${esc(provider.id)} OAuth/OIDC sağlayıcısı · Callback: <code>${esc(callback)}</code></p></div>${statusTag(provider.configured ? 'configured' : 'not_configured')}</div><div class="card-body form-grid"><div class="field"><label>Görünen Ad</label><input class="input" data-k="name" value="${esc(provider.name)}"></div><div class="field"><label>Client ID</label><input class="input" data-k="clientId" value="${esc(provider.clientId || '')}"></div><div class="field"><label>Scope</label><input class="input" data-k="scopes" value="${esc(provider.scopes || '')}"></div><div class="field span-2"><label>Authorize URL</label><input class="input" data-k="authorizeUrl" value="${esc(provider.authorizeUrl || '')}"></div><div class="field span-2"><label>Token URL</label><input class="input" data-k="tokenUrl" value="${esc(provider.tokenUrl || '')}"></div><div class="field span-2"><label>Profil / UserInfo URL</label><input class="input" data-k="profileUrl" value="${esc(provider.profileUrl || '')}"></div><div class="field"><label>Issuer</label><input class="input" data-k="issuer" value="${esc(provider.issuer || '')}"></div><div class="field"><label>Sıra</label><input class="input" type="number" data-k="sortOrder" value="${Number(provider.sortOrder || 0)}"></div><div class="field"><label>Client Secret</label><input class="input" type="password" data-secret-k="clientSecret" placeholder="${esc(provider.secrets?.clientSecret || 'Değiştirmek için girin')}"></div>${provider.id === 'apple' ? `<div class="field"><label>Apple Team ID</label><input class="input" type="password" data-secret-k="teamId" placeholder="${esc(provider.secrets?.teamId || '')}"></div><div class="field"><label>Apple Key ID</label><input class="input" type="password" data-secret-k="keyId" placeholder="${esc(provider.secrets?.keyId || '')}"></div><div class="field span-3"><label>Apple Private Key (.p8 içeriği)</label><textarea class="textarea" data-secret-k="privateKey" placeholder="${esc(provider.secrets?.privateKey || 'Değiştirmek için yeni anahtar girin')}"></textarea></div>` : ''}<label class="check"><input type="checkbox" data-k="enabled" ${provider.enabled ? 'checked' : ''}><span>Sağlayıcı aktif</span></label></div><div class="form-actions"><button class="primary" data-action="save-auth-provider" data-id="${esc(provider.id)}">Sağlayıcıyı Kaydet</button></div></article>`;
}

function accessView() {
  return layout(`<form id="access-settings-form">${settingsSection('Kayıt ve Oturum Politikası', `${boolField('email_registration_enabled','E-posta ile kayıt aktif')}${boolField('email_verification_required','E-posta doğrulaması zorunlu')}${boolField('social_login_enabled','Sosyal giriş aktif')}${field('session_duration_minutes','Kullanıcı oturum süresi (dk)')}${field('admin_session_duration_minutes','Admin oturum süresi (dk)')}`)}<div class="form-actions"><button class="primary" data-action="save-access-settings">Kayıt Ayarlarını Kaydet</button></div></form><div class="section-head"><h2>Google · Apple · Facebook · X</h2><span>${state.authProviders.length} sağlayıcı</span></div><div class="editor-grid">${state.authProviders.map(authProviderCard).join('')}</div><div class="notice">Gerçek sosyal giriş için ilgili geliştirici panelinde bu sunucunun HTTPS callback adresini yetkilendirin. Secret değerleri şifreli saklanır ve yeniden açık gösterilmez.</div>`, 'Üyelik & Sosyal Giriş');
}

function walletsAdminView() {
  return layout(`<section class="card"><div class="card-head"><div><h2>Kullanıcı Dağıtım Cüzdanları</h2><p class="card-description">Testnet cüzdanlarında private key şifreli saklanır; panelde hiçbir zaman gösterilmez. Mainnet adresleri e-posta doğrulaması ve cooldown durumuyla izlenir.</p></div><span class="tag">${state.managedWallets.length} kayıt</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Kullanıcı</th><th>Tip / Ağ</th><th>Adres</th><th>Doğrulama</th><th>Durum</th><th>Kullanılabilir</th><th>Oluşturma</th></tr></thead><tbody>${state.managedWallets.map((row) => `<tr><td>${esc(row.display_name || row.login_id || row.user_id)}<br><small>${esc(row.email || '')}</small></td><td>${statusTag(row.wallet_type)}<br><small>${esc(row.network)} · ${row.chain_id}</small></td><td><code class="break-all">${esc(row.address)}</code></td><td>${statusTag(row.verification_status)}</td><td>${statusTag(row.status)}</td><td>${row.available_at ? new Date(Number(row.available_at) * 1000).toLocaleString('tr-TR') : '-'}</td><td>${new Date(row.created_at).toLocaleString('tr-TR')}</td></tr>`).join('') || '<tr><td colspan="7">Henüz kullanıcı cüzdanı yok.</td></tr>'}</tbody></table></div></section>`, 'Kullanıcı Cüzdanları');
}

function allocationView() {
  const data = state.presaleAllocation || {};
  const cfg = data.config || {};
  const preview = data.preview || { rows: [] };
  const decimals = Number(cfg.decimals || 18);
  return layout(`<section class="grid metrics"><div class="metric"><small>Toplam Deposit</small><strong>${money(Number(preview.totalPaidUsdtMicros || 0) / 1e6)} USDT</strong></div><div class="metric"><small>Katılımcı</small><strong>${money(preview.purchaseCount || 0)}</strong></div><div class="metric"><small>Tahmini Dağıtım</small><strong>${baseToDecimal(preview.totalTokenBase || '0', decimals)} OC</strong></div><div class="metric"><small>Durum</small><strong>${cfg.locked ? 'KİLİTLİ' : 'DÜZENLENEBİLİR'}</strong></div></section><form id="presale-allocation-form" class="card settings-card" style="margin-top:14px"><div class="card-head"><div><h2>Arz, Fiyat ve Tahsisat Politikası</h2><p class="card-description">Esas kayıt onaylanmış USDT deposit miktarıdır. Tahmini OC hakedişi finalizasyona kadar bu politikalara göre yeniden hesaplanır.</p></div>${statusTag(cfg.policy)}</div><div class="card-body form-grid"><div class="field"><label>Toplam Proje Arzı (OC)</label><input class="input" name="totalSupplyTokens" value="${baseToDecimal(cfg.totalSupplyTokenBase || '0', decimals)}" ${cfg.locked ? 'disabled' : ''}></div><div class="field"><label>Presale Havuzu (OC)</label><input class="input" name="poolTokens" value="${baseToDecimal(cfg.poolTokenBase || '0', decimals)}" ${cfg.locked ? 'disabled' : ''}></div><div class="field"><label>Politika</label><select class="input" name="policy" ${cfg.locked ? 'disabled' : ''}>${[['fixed_at_deposit','Deposit anındaki fiyat'],['launch_price','Lansman/final fiyatı'],['pro_rata_pool','Deposit oranında havuz']].map(([v,l])=>`<option value="${v}" ${cfg.policy===v?'selected':''}>${l}</option>`).join('')}</select></div><div class="field"><label>Referans Fiyat (USDT)</label><input class="input" type="number" step="0.000001" name="referencePrice" value="${Number(cfg.referencePriceUsdtMicros || 0)/1e6}" ${cfg.locked ? 'disabled' : ''}></div><div class="field"><label>Lansman / Final Fiyatı (USDT)</label><input class="input" type="number" step="0.000001" name="launchPrice" value="${Number(cfg.launchPriceUsdtMicros || 0)/1e6}" ${cfg.locked ? 'disabled' : ''}></div><div class="field"><label>Koşullar Versiyonu</label><input class="input" name="termsVersion" value="${esc(cfg.termsVersion || '1.0')}" ${cfg.locked ? 'disabled' : ''}></div><label class="check"><input type="checkbox" name="autoFinalizeAtLaunch" ${cfg.autoFinalizeAtLaunch ? 'checked' : ''} ${cfg.locked ? 'disabled' : ''}><span>Lansman anında otomatik finalizasyon</span></label></div><div class="form-actions"><button class="secondary" type="button" data-action="launch-tick">Lansman Otomasyonunu Çalıştır</button><button class="primary" ${cfg.locked ? 'disabled' : ''}>Arz ve Fiyatı Kaydet</button></div></form><section class="card" style="margin-top:14px"><div class="card-head"><div><h2>Canlı Tahsisat Ön İzlemesi</h2><p class="card-description">Finalizasyon yapılmadan kullanıcı başına tahmini dağıtımı inceleyin.</p></div><button class="primary" data-action="create-snapshot" ${cfg.locked || !preview.purchaseCount ? 'disabled' : ''}>Snapshot Oluştur</button></div><div class="table-wrap"><table class="table"><thead><tr><th>Kullanıcı</th><th>Deposit</th><th>Ağırlıklı USDT</th><th>Tahmini OC</th><th>Politika</th></tr></thead><tbody>${(preview.rows || []).map((row)=>`<tr><td>${esc(row.displayName || row.username || row.userId)}<br><small>${esc(row.loginId || '')}</small></td><td>${money(Number(row.depositUsdtMicros || 0)/1e6)} USDT</td><td>${money(Number(row.weightedUsdtMicros || 0)/1e6)}</td><td><b>${baseToDecimal(row.tokenBase || '0',decimals)} OC</b></td><td>${statusTag(preview.policy)}</td></tr>`).join('') || '<tr><td colspan="5">Onaylanmış deposit bulunmuyor.</td></tr>'}</tbody></table></div></section><section class="card" style="margin-top:14px"><div class="card-head"><h2>Finalizasyon Snapshotları</h2></div><div class="table-wrap"><table class="table"><thead><tr><th>Versiyon</th><th>Politika</th><th>Deposit</th><th>Token</th><th>Onay</th><th>Durum</th><th>İşlem</th></tr></thead><tbody>${(data.snapshots || []).map((row)=>`<tr><td>v${row.version}<br><code>${esc(row.id.slice(0,8))}</code></td><td>${esc(row.policy)}</td><td>${money(Number(row.total_usdt_micros || 0)/1e6)} USDT</td><td>${baseToDecimal(row.total_token_base || '0',decimals)} OC</td><td>${row.approval_count || 0}</td><td>${statusTag(row.status)}</td><td><button class="secondary" data-action="approve-snapshot" data-id="${esc(row.id)}" ${!['preview','pending_approval'].includes(row.status)?'disabled':''}>Onayla</button><button class="primary" data-action="finalize-snapshot" data-id="${esc(row.id)}" ${!['preview','pending_approval'].includes(row.status)?'disabled':''}>Finalleştir</button></td></tr>`).join('') || '<tr><td colspan="7">Snapshot bulunmuyor.</td></tr>'}</tbody></table></div></section>`, 'Presale Tahsisat & Finalizasyon');
}

function distributionsView() {
  const data = state.distributions || { settings:{}, campaigns:[], recentItems:[] };
  const settings = data.settings || {};
  return layout(`<section class="grid metrics"><div class="metric"><small>Dağıtım Modu</small><strong>${esc(settings.mode || '-')}</strong></div><div class="metric"><small>Contract</small><strong>${settings.contractAddress ? 'TANIMLI' : 'YOK'}</strong></div><div class="metric"><small>Signer</small><strong>${esc(settings.signerMode || '-')}</strong></div><div class="metric"><small>Son Snapshot</small><strong>${settings.latestSnapshot ? `v${settings.latestSnapshot.version}` : '-'}</strong></div></section><form id="distribution-settings-form" class="card settings-card" style="margin-top:14px"><div class="card-head"><div><h2>Lansman Dağıtım Ayarları</h2><p class="card-description">Contract tanımlıysa harici signer/custody ile otomatik dağıtım; contract yoksa manuel withdrawal akışı kullanılır.</p></div></div><div class="card-body form-grid"><label class="check"><input type="checkbox" data-setting="distribution_enabled" ${state.settings?.distribution_enabled ? 'checked':''}><span>Dağıtım sistemi aktif</span></label><label class="check"><input type="checkbox" data-setting="distribution_auto_start" ${state.settings?.distribution_auto_start ? 'checked':''}><span>Lansmanda otomatik başlat</span></label><div class="field"><label>Dağıtım Modu</label><select class="input" data-setting="distribution_mode"><option value="auto_contract" ${state.settings?.distribution_mode==='auto_contract'?'selected':''}>Contract ile otomatik</option><option value="manual_withdrawal" ${state.settings?.distribution_mode==='manual_withdrawal'?'selected':''}>Manuel withdrawal</option></select></div><div class="field"><label>Signer Modu</label><select class="input" data-setting="distribution_signer_mode"><option value="webhook" ${state.settings?.distribution_signer_mode==='webhook'?'selected':''}>Harici MPC/HSM / Custody Webhook</option></select></div><div class="field span-2"><label>Signer Webhook URL</label><input class="input" data-setting="distribution_signer_url" value="${esc(state.settings?.distribution_signer_url || '')}"></div><div class="field"><label>Batch Büyüklüğü</label><input class="input" type="number" data-setting="distribution_batch_size" value="${Number(state.settings?.distribution_batch_size || 100)}"></div><div class="field"><label>Gerekli Onay</label><input class="input" type="number" data-setting="distribution_confirmations_required" value="${Number(state.settings?.distribution_confirmations_required || 12)}"></div><div class="field span-2"><label>Signer Secret</label><input class="input" type="password" id="distribution-secret" placeholder="Değiştirmek için yeni değer girin"></div></div><div class="form-actions"><button class="secondary" type="button" data-action="launch-tick">Otomasyon Tick</button><button class="primary">Ayarları Kaydet</button></div></form><section class="card" style="margin-top:14px"><div class="card-head"><h2>Dağıtım Kampanyaları</h2><button class="primary" data-action="create-distribution" ${!settings.latestSnapshot?'disabled':''}>Yeni Kampanya Oluştur</button></div><div class="table-wrap"><table class="table"><thead><tr><th>Kampanya</th><th>Mod</th><th>Alıcı</th><th>İşlenen</th><th>Durum</th><th>İşlem</th></tr></thead><tbody>${(data.campaigns||[]).map((row)=>`<tr><td>${esc(row.name || 'Lansman Dağıtımı')}<br><code>${esc(row.id.slice(0,8))}</code></td><td>${esc(row.mode)}</td><td>${row.total_recipients}</td><td>${row.processed_recipients}</td><td>${statusTag(row.status)}</td><td><button class="secondary" data-action="refresh-distribution-wallets" data-id="${esc(row.id)}">Cüzdanları Yenile</button><button class="primary" data-action="run-distribution" data-id="${esc(row.id)}" ${!['ready','running','paused'].includes(row.status)?'disabled':''}>Çalıştır</button></td></tr>`).join('') || '<tr><td colspan="6">Henüz kampanya yok.</td></tr>'}</tbody></table></div></section><section class="card" style="margin-top:14px"><div class="card-head"><h2>Son Dağıtım Kayıtları</h2></div><div class="table-wrap"><table class="table"><thead><tr><th>Kullanıcı</th><th>Adres</th><th>Kaynak</th><th>Toplam</th><th>Tx Hash</th><th>Durum</th><th></th></tr></thead><tbody>${(data.recentItems||[]).map((row)=>`<tr><td>${esc(row.display_name || row.user_id)}</td><td><code class="break-all">${esc(row.address || '-')}</code></td><td><small>Presale: ${baseToDecimal(row.presale_token_base || '0', Number(state.settings?.project_token_decimals || 18))} OC</small><br><small>Biriken: ${money(row.game_token_whole || 0)} OC</small></td><td>${baseToDecimal(row.amount_token_base || '0', Number(state.settings?.project_token_decimals || 18))} OC</td><td><code class="break-all">${esc(row.tx_hash || '-')}</code></td><td>${statusTag(row.status)}</td><td>${row.status==='manual'?`<button class="secondary" data-action="broadcast-manual-distribution" data-id="${esc(row.id)}">Tx Gir</button>`:''}<button class="primary" data-action="confirm-distribution-item" data-id="${esc(row.id)}" ${row.status!=='broadcast'?'disabled':''}>Onayla</button></td></tr>`).join('') || '<tr><td colspan="7">Dağıtım kaydı yok.</td></tr>'}</tbody></table></div></section>`, 'Lansman Dağıtımı');
}

function mailView() {
  const secret = state.secrets.find((item)=>item.key==='smtp_password');
  return layout(`<form id="smtp-settings-form">${settingsSection('SMTP ve Gönderici', `${boolField('smtp_enabled','SMTP aktif')}${field('smtp_host','SMTP Host','text')}${field('smtp_port','SMTP Port')}${boolField('smtp_secure','Doğrudan TLS')}${boolField('smtp_starttls','STARTTLS')}${field('smtp_username','SMTP Kullanıcı','text')}${field('smtp_from_email','Gönderen E-posta','email')}${field('smtp_from_name','Gönderen Adı','text')}${field('smtp_ehlo_name','EHLO Adı','text')}<div class="field span-2"><label>SMTP Parolası</label><input class="input" type="password" id="smtp-password" placeholder="${esc(secret?.masked || 'Değiştirmek için girin')}"><small>Boş bırakırsanız mevcut secret korunur.</small></div>`)}<div class="form-actions"><button class="primary">SMTP Ayarlarını Kaydet</button><button type="button" class="secondary" data-action="deliver-email-queue">Kuyruğu Gönder</button></div></form><section class="card" style="margin-top:14px"><div class="card-head"><div><h2>E-posta Kuyruğu</h2><p class="card-description">Doğrulama, parola sıfırlama, cüzdan bildirimi ve mainnet adres kodları.</p></div><span class="tag">${state.emailOutbox.length}</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Tarih</th><th>Alıcı</th><th>Şablon</th><th>Konu</th><th>Durum</th><th>Deneme</th><th>Hata</th><th></th></tr></thead><tbody>${state.emailOutbox.map((row)=>`<tr><td>${new Date(row.created_at).toLocaleString('tr-TR')}</td><td>${esc(row.to_email)}</td><td>${esc(row.template)}</td><td>${esc(row.subject)}</td><td>${statusTag(row.status)}</td><td>${row.attempts}</td><td>${esc(row.last_error || '')}</td><td><button class="secondary" data-action="deliver-email" data-id="${esc(row.id)}" ${row.status==='sent'?'disabled':''}>Gönder</button></td></tr>`).join('') || '<tr><td colspan="8">Kuyruk boş.</td></tr>'}</tbody></table></div></section>`, 'E-posta & SMTP');
}

function questsView() {
  return layout(`<section class="card"><div class="card-head"><h2>Görev Tanımları</h2></div><div class="table-wrap"><table class="table"><thead><tr><th>ID / Event</th><th>Başlık</th><th>Açıklama</th><th>Hedef</th><th>Ödül</th><th>Tekrar</th><th>Sıra</th><th>Aktif</th><th></th></tr></thead><tbody>${state.quests.map((q) => `<tr data-quest-row="${esc(q.id)}"><td><code>${esc(q.id)}</code><br><span class="tag">${esc(q.event_type)}</span></td><td><input data-k="title" value="${esc(q.title)}"></td><td><input data-k="description" value="${esc(q.description)}"></td><td><input class="tiny" type="number" data-k="target_count" value="${q.target_count}"></td><td><input class="tiny" type="number" data-k="reward_points" value="${q.reward_points}"></td><td><select data-k="repeat_type">${['daily', 'weekly', 'once'].map((t) => `<option ${t === q.repeat_type ? 'selected' : ''}>${t}</option>`).join('')}</select></td><td><input class="tiny" type="number" data-k="sort_order" value="${q.sort_order}"></td><td><input type="checkbox" data-k="enabled" ${q.enabled ? 'checked' : ''}></td><td><button class="primary" data-action="save-quest" data-id="${esc(q.id)}">Kaydet</button></td></tr>`).join('')}</tbody></table></div></section>`, 'Görevler');
}

function usersView() {
  return layout(`<section class="card"><div class="card-head"><h2>Kullanıcı Yönetimi</h2><div class="searchbar"><input id="user-search" class="input" placeholder="Kullanıcı, ad veya davet kodu"><button class="secondary" data-action="search-users">Ara</button></div></div><div class="table-wrap"><table class="table"><thead><tr><th>Kullanıcı</th><th>Durum</th><th>Seviye / VIP</th><th>Tap</th><th>OC_POINTS</th><th>OC_TOKEN</th><th>Davet Kodu</th><th>İşlemler</th></tr></thead><tbody>${state.users.map((u) => `<tr><td>${esc(u.display_name)}<br><small>@${esc(u.username)}</small><br><code>${u.id.slice(0, 8)}</code></td><td><span class="tag">${esc(u.status)}</span></td><td>Lv ${u.level}<br>VIP ${u.vip_tier}</td><td>${money(u.tap_total)}</td><td>${money(u.points)}</td><td>${money(u.tokens)}</td><td>${esc(u.referral_code)}</td><td><div class="user-actions"><button class="secondary" data-action="grant" data-id="${u.id}">Puan Ver</button><button class="secondary" data-action="set-vip" data-id="${u.id}" data-current="${u.vip_tier}">VIP Ata</button></div></td></tr>`).join('')}</tbody></table></div></section>`, 'Kullanıcılar');
}

function ledgerView() {
  return layout(`<section class="card"><div class="card-head"><h2>Double-Entry Ledger</h2><span class="tag">Son ${state.ledger.length} işlem</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Tarih</th><th>Tür</th><th>Referans</th><th>Girişler</th><th>Metadata</th></tr></thead><tbody>${state.ledger.map((l) => `<tr><td>${new Date(l.created_at).toLocaleString('tr-TR')}</td><td><span class="tag">${esc(l.type)}</span></td><td>${esc(l.ref)}</td><td class="ledger-entry">${esc(l.entries)}</td><td class="json">${esc(JSON.stringify(l.metadata))}</td></tr>`).join('')}</tbody></table></div></section>`, 'Ledger');
}

function auditView() {
  return layout(`<section class="card"><div class="card-head"><h2>Yönetici İşlem İzleri</h2><span class="tag">Son ${state.audit.length}</span></div><div class="table-wrap"><table class="table"><thead><tr><th>Tarih</th><th>Aktör</th><th>Aksiyon</th><th>Hedef</th><th>Önce</th><th>Sonra</th><th>IP</th></tr></thead><tbody>${state.audit.map((a) => `<tr><td>${new Date(a.created_at).toLocaleString('tr-TR')}</td><td>${esc(a.actor_id)}</td><td><span class="tag">${esc(a.action)}</span></td><td>${esc(a.target_type)}:${esc(a.target_id)}</td><td class="json">${esc(JSON.stringify(a.before))}</td><td class="json">${esc(JSON.stringify(a.after))}</td><td>${esc(a.ip)}</td></tr>`).join('')}</tbody></table></div></section>`, 'Audit Log');
}

function render() {
  const renderer = {
    dashboard: dashboardView,
    settings: settingsView,
    cms: cmsView,
    tokenomics: tokenomicsView,
    roadmap: roadmapView,
    whitepaper: whitepaperView,
    presale: presaleView,
    allocation: allocationView,
    access: accessView,
    'wallet-admin': walletsAdminView,
    distributions: distributionsView,
    mail: mailView,
    vip: vipView,
    wheel: wheelView,
    quests: questsView,
    users: usersView,
    ledger: ledgerView,
    audit: auditView
  }[state.section] || dashboardView;
  renderer();
}

async function loadSection(section, force = false) {
  if (section === 'dashboard' || !state.settings || force) {
    state.dashboard = await api('/api/admin/dashboard');
    state.settings = state.dashboard.settings;
  }
  if (section === 'settings' && (!state.paymentSettings || force)) {
    state.paymentSettings = await api('/api/admin/payment-settings');
    state.settings = { ...(state.settings || {}), ...(state.paymentSettings.settings || {}) };
  }
  if (['cms','tokenomics','roadmap','whitepaper'].includes(section) && (!state.siteContent || force)) {
    state.siteContent = await api('/api/admin/site');
    if (!state.settings || force) state.settings = (await api('/api/admin/dashboard')).settings;
  }
  if (section === 'presale' && (!state.presaleAdmin || force)) state.presaleAdmin = await api('/api/admin/presale');
  if (section === 'access' && (!state.authProviders.length || force)) state.authProviders = await api('/api/admin/auth-providers');
  if (section === 'wallet-admin' && (!state.managedWallets.length || force)) state.managedWallets = await api('/api/admin/wallets?limit=1000');
  if (section === 'allocation' && (!state.presaleAllocation || force)) state.presaleAllocation = await api('/api/admin/presale-allocation');
  if (section === 'distributions' && (!state.distributions || force)) state.distributions = await api('/api/admin/distributions');
  if (section === 'mail' && (!state.emailOutbox.length || force)) {
    [state.emailOutbox, state.secrets] = await Promise.all([api('/api/admin/email-outbox?limit=500'), api('/api/admin/secrets')]);
  }
  if (section === 'vip' && (!state.vip.length || force)) state.vip = await api('/api/admin/vip');
  if (section === 'wheel' && (!state.wheel.length || force)) state.wheel = await api('/api/admin/wheel');
  if (section === 'quests' && (!state.quests.length || force)) state.quests = await api('/api/admin/quests');
  if (section === 'users' && (!state.users.length || force)) state.users = await api('/api/admin/users?limit=200');
  if (section === 'ledger' && (!state.ledger.length || force)) state.ledger = await api('/api/admin/ledger?limit=300');
  if (section === 'audit' && (!state.audit.length || force)) state.audit = await api('/api/admin/audit?limit=300');
}

async function navigate(section, force = false) {
  state.section = section;
  location.hash = section;
  try {
    await loadSection(section, force);
    render();
  } catch (error) {
    if (['SESSION_EXPIRED', 'SESSION_REVOKED', 'AUTH_REQUIRED'].includes(error.code)) {
      state.token = '';
      loginView();
    } else toast(error.message, 'error');
  }
}

function rowData(selector) {
  const row = document.querySelector(selector);
  const result = {};
  row?.querySelectorAll('[data-k]').forEach((el) => {
    result[el.dataset.k] = el.type === 'checkbox' ? el.checked : (el.type === 'number' ? Number(el.value) : el.value);
  });
  return result;
}

function collectGlobalSettings(form) {
  const changes = {};
  form.querySelectorAll('[data-setting]').forEach((el) => {
    let value = el.type === 'checkbox' ? el.checked : el.value;
    if (el.type === 'number') value = Number(value);
    if (el.type === 'datetime-local' && value) value = new Date(value).toISOString();
    if (el.dataset.type === 'csv') value = String(value).split(',').map((item) => item.trim()).filter(Boolean);
    changes[el.dataset.setting] = value;
  });
  const percent = form.querySelector('[data-setting-display="conversion_rate_bps"]');
  if (percent) changes.conversion_rate_bps = Math.round(Number(percent.value) * 100);
  return changes;
}

async function saveSettings(form) {
  const changes = collectGlobalSettings(form);
  const core = await api('/api/admin/settings', { method: 'PUT', body: changes });
  const platform = await api('/api/admin/platform-settings', { method: 'PUT', body: changes });
  state.settings = { ...core, ...platform };
  state.dashboard = null;
  state.paymentSettings = await api('/api/admin/payment-settings');
  toast('Genel ayarlar kaydedildi.');
  render();
}

function collectProvider(card) {
  const body = { secrets: {}, config: {}, currencies: [] };
  card.querySelectorAll('[data-provider-field]').forEach((el) => {
    body[el.dataset.providerField] = el.type === 'checkbox' ? el.checked : (el.type === 'number' ? Number(el.value) : el.value);
  });
  card.querySelectorAll('[data-provider-secret]').forEach((el) => { body.secrets[el.dataset.providerSecret] = el.value; });
  card.querySelectorAll('[data-provider-config]').forEach((el) => {
    body.config[el.dataset.providerConfig] = el.type === 'checkbox' ? el.checked : (el.type === 'number' ? Number(el.value) : el.value);
  });
  card.querySelectorAll('[data-provider-currency]').forEach((row) => {
    body.currencies.push({ currency_code: row.dataset.providerCurrency, ...rowData(`[data-provider-card="${CSS.escape(card.dataset.providerCard)}"] [data-provider-currency="${CSS.escape(row.dataset.providerCurrency)}"]`) });
  });
  return body;
}

async function reloadPaymentSettings() {
  state.paymentSettings = await api('/api/admin/payment-settings');
  state.settings = { ...(state.settings || {}), ...(state.paymentSettings.settings || {}) };
  render();
}


function collectAuthProvider(card) {
  const body = { secrets: {}, config: {} };
  card.querySelectorAll('[data-k]').forEach((el) => {
    body[el.dataset.k] = el.type === 'checkbox' ? el.checked : (el.type === 'number' ? Number(el.value) : el.value);
  });
  card.querySelectorAll('[data-secret-k]').forEach((el) => {
    if (el.value) body.secrets[el.dataset.secretK] = el.value;
  });
  return body;
}

async function reloadFinalAdminSection(section = state.section) {
  if (section === 'access') state.authProviders = await api('/api/admin/auth-providers');
  if (section === 'wallet-admin') state.managedWallets = await api('/api/admin/wallets?limit=1000');
  if (section === 'allocation') state.presaleAllocation = await api('/api/admin/presale-allocation');
  if (section === 'distributions') state.distributions = await api('/api/admin/distributions');
  if (section === 'mail') [state.emailOutbox, state.secrets] = await Promise.all([api('/api/admin/email-outbox?limit=500'), api('/api/admin/secrets')]);
  render();
}

async function handleAction(el) {
  const action = el.dataset.action;
  if (action === 'refresh') return navigate(state.section, true);
  if (action === 'logout') {
    try { await api('/api/auth/logout', { method: 'POST', body: {} }); } catch {}
    state.token = '';
    return loginView();
  }
  if (action === 'settings-tab') {
    state.settingsTab = el.dataset.tab;
    sessionStorage.setItem('oc_settings_tab', state.settingsTab);
    document.querySelectorAll('[data-settings-pane]').forEach((paneEl) => paneEl.classList.toggle('active', paneEl.dataset.settingsPane === state.settingsTab));
    document.querySelectorAll('[data-action="settings-tab"]').forEach((button) => button.classList.toggle('active', button.dataset.tab === state.settingsTab));
    window.scrollTo({ top: 0, behavior: 'smooth' });
    return;
  }
  if (action === 'save-wheel-rules') {
    const form = document.querySelector('#wheel-rules-form');
    const body = collectGlobalSettings(form);
    state.settings = await api('/api/admin/settings', { method: 'PUT', body });
    toast('Çark hakları ve güvenlik kuralları kaydedildi.');
    return render();
  }
  if (action === 'save-access-settings') {
    const changes = collectGlobalSettings(document.querySelector('#access-settings-form'));
    state.settings = { ...(state.settings || {}), ...(await api('/api/admin/platform-settings', { method: 'PUT', body: changes })) };
    toast('Kayıt ve oturum ayarları kaydedildi.');
    return render();
  }
  if (action === 'save-auth-provider') {
    const card = el.closest('[data-auth-provider]');
    await api(`/api/admin/auth-providers/${encodeURIComponent(el.dataset.id)}`, { method: 'PUT', body: collectAuthProvider(card) });
    toast(`${el.dataset.id} sosyal giriş ayarı kaydedildi.`);
    return reloadFinalAdminSection('access');
  }
  if (action === 'create-snapshot') {
    const result = await api('/api/admin/presale-allocation/snapshots', { method: 'POST', body: {} });
    toast(`Presale snapshot v${result.snapshot.version} oluşturuldu.`);
    return reloadFinalAdminSection('allocation');
  }
  if (action === 'approve-snapshot') {
    const note = prompt('Onay notu:', 'Dağılım kontrol edildi') || '';
    const result = await api(`/api/admin/presale-allocation/snapshots/${encodeURIComponent(el.dataset.id)}/approve`, { method: 'POST', body: { note } });
    toast(`Snapshot onaylandı (${result.approvals}/${result.required}).`);
    return reloadFinalAdminSection('allocation');
  }
  if (action === 'finalize-snapshot') {
    if (!confirm('Bu işlem arz ve fiyat ayarlarını kilitler. Presale dağılımını kesinleştirmek istiyor musunuz?')) return;
    await api(`/api/admin/presale-allocation/snapshots/${encodeURIComponent(el.dataset.id)}/finalize`, { method: 'POST', body: {} });
    toast('Presale dağılımı kesinleştirildi.');
    state.settings = (await api('/api/admin/dashboard')).settings;
    return reloadFinalAdminSection('allocation');
  }
  if (action === 'launch-tick') {
    const result = await api('/api/admin/launch/tick', { method: 'POST', body: {} });
    toast(`Lansman otomasyonu çalıştırıldı: ${result.skipped || 'tamamlandı'}.`);
    if (state.section === 'allocation') return reloadFinalAdminSection('allocation');
    if (state.section === 'distributions') return reloadFinalAdminSection('distributions');
    return;
  }
  if (action === 'create-distribution') {
    const result = await api('/api/admin/distributions', { method: 'POST', body: { name: 'OnlyCoin Lansman Dağıtımı' } });
    toast(result.duplicate ? 'Mevcut kampanya açıldı.' : 'Dağıtım kampanyası oluşturuldu.');
    return reloadFinalAdminSection('distributions');
  }
  if (action === 'refresh-distribution-wallets') {
    const result = await api(`/api/admin/distributions/${encodeURIComponent(el.dataset.id)}/refresh-wallets`, { method: 'POST', body: {} });
    toast(`${result.updated} cüzdan dağıtım kuyruğuna bağlandı.`);
    return reloadFinalAdminSection('distributions');
  }
  if (action === 'run-distribution') {
    const result = await api(`/api/admin/distributions/${encodeURIComponent(el.dataset.id)}/run`, { method: 'POST', body: {} });
    toast(`${result.processed || 0} transfer broadcast edildi.`);
    return reloadFinalAdminSection('distributions');
  }
  if (action === 'broadcast-manual-distribution') {
    const txHash = prompt('Dış cüzdandan yapılan transferin transaction hash değeri:', '') || '';
    if (!txHash) return;
    await api(`/api/admin/distribution-items/${encodeURIComponent(el.dataset.id)}/broadcast`, { method: 'POST', body: { txHash } });
    toast('Manuel dağıtım transaction hash ile broadcast durumuna alındı.');
    return reloadFinalAdminSection('distributions');
  }
  if (action === 'confirm-distribution-item') {
    const txHash = prompt('Transaction hash:', '') || '';
    if (!txHash) return;
    const confirmations = Number(prompt('Confirmation sayısı:', String(state.distributions?.settings?.confirmationsRequired || 12)) || 0);
    await api(`/api/admin/distribution-items/${encodeURIComponent(el.dataset.id)}/confirm`, { method: 'POST', body: { txHash, confirmations } });
    toast('Dağıtım işlemi onaylandı.');
    return reloadFinalAdminSection('distributions');
  }
  if (action === 'deliver-email-queue') {
    const result = await api('/api/admin/email-outbox/deliver', { method: 'POST', body: {} });
    toast(result.skipped ? 'SMTP kapalı; kuyruk gönderilmedi.' : `${result.delivered} e-posta gönderildi.`);
    return reloadFinalAdminSection('mail');
  }
  if (action === 'deliver-email') {
    const result = await api(`/api/admin/email-outbox/${encodeURIComponent(el.dataset.id)}/deliver`, { method: 'POST', body: {} });
    toast(result.delivered ? 'E-posta gönderildi.' : (result.error || 'Gönderim başarısız.'), result.delivered ? 'success' : 'error');
    return reloadFinalAdminSection('mail');
  }
  if (action === 'save-site-page') {
    const slug = el.dataset.id;
    await api(`/api/admin/site/pages/${encodeURIComponent(slug)}`, { method: 'PUT', body: rowData(`[data-page-editor="${CSS.escape(slug)}"]`) });
    state.siteContent = await api('/api/admin/site');
    toast(`${slug} sayfası kaydedildi.`);
    return render();
  }
  if (action === 'save-site-section') {
    const id = el.dataset.id;
    const row = document.querySelector(`[data-section-editor="${CSS.escape(id)}"]`);
    let content;
    try { content = JSON.parse(row.querySelector('[data-json-content]').value); }
    catch { throw Object.assign(new Error('İçerik JSON biçimi geçersiz.'), { code: 'INVALID_JSON' }); }
    const body = { ...rowData(`[data-section-editor="${CSS.escape(id)}"]`), content };
    await api(`/api/admin/site/sections/${encodeURIComponent(id)}`, { method: 'PUT', body });
    state.siteContent = await api('/api/admin/site');
    toast('Site bölümü kaydedildi.');
    return render();
  }
  if (action === 'save-allocation') {
    const id = el.dataset.id;
    const row = document.querySelector(`[data-allocation-row="${CSS.escape(id)}"]`);
    const body = rowData(`[data-allocation-row="${CSS.escape(id)}"]`);
    body.percentage_bps = Math.round(Number(row.querySelector('[data-percent]').value) * 100);
    await api(`/api/admin/tokenomics/allocations/${encodeURIComponent(id)}`, { method: 'PUT', body });
    state.siteContent = await api('/api/admin/site');
    toast('Token tahsisatı kaydedildi.');
    return render();
  }
  if (action === 'save-roadmap') {
    const id = el.dataset.id;
    const row = document.querySelector(`[data-roadmap-row="${CSS.escape(id)}"]`);
    const body = rowData(`[data-roadmap-row="${CSS.escape(id)}"]`);
    row.querySelectorAll('[data-date-k]').forEach((field) => { body[field.dataset.dateK] = fromDateTimeLocal(field.value); });
    body.items = row.querySelector('[data-items]').value.split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
    await api(`/api/admin/roadmap/${encodeURIComponent(id)}`, { method: 'PUT', body });
    state.siteContent = await api('/api/admin/site');
    toast('Roadmap aşaması kaydedildi.');
    return render();
  }
  if (action === 'save-whitepaper-settings') {
    const body = collectGlobalSettings(document.querySelector('#whitepaper-settings'));
    state.settings = { ...(state.settings || {}), ...(await api('/api/admin/platform-settings', { method: 'PUT', body })) };
    toast('Whitepaper belge bilgileri kaydedildi.');
    return render();
  }
  if (action === 'save-chapter') {
    const id = el.dataset.id;
    await api(`/api/admin/whitepaper/chapters/${encodeURIComponent(id)}`, { method: 'PUT', body: rowData(`[data-chapter-row="${CSS.escape(id)}"]`) });
    state.siteContent = await api('/api/admin/site');
    toast('Whitepaper bölümü kaydedildi.');
    return render();
  }
  if (action === 'save-stage') {
    const id = el.dataset.id;
    const row = document.querySelector(`[data-stage-row="${CSS.escape(id)}"]`);
    const body = rowData(`[data-stage-row="${CSS.escape(id)}"]`);
    row.querySelectorAll('[data-date-k]').forEach((field) => { body[field.dataset.dateK] = fromDateTimeLocal(field.value); });
    row.querySelectorAll('[data-micros-k]').forEach((field) => { body[field.dataset.microsK] = Math.round(Number(field.value) * 1e6); });
    row.querySelectorAll('[data-bps-k]').forEach((field) => { body[field.dataset.bpsK] = Math.round(Number(field.value) * 100); });
    await api(`/api/admin/presale/stages/${encodeURIComponent(id)}`, { method: 'PUT', body });
    state.presaleAdmin = await api('/api/admin/presale');
    toast('Presale aşaması kaydedildi.');
    return render();
  }
  if (action === 'save-vip') {
    const id = el.dataset.id;
    await api(`/api/admin/vip/${id}`, { method: 'PUT', body: rowData(`[data-vip-row="${CSS.escape(id)}"]`) });
    state.vip = await api('/api/admin/vip');
    toast(`VIP ${id} kaydedildi.`);
    return render();
  }
  if (action === 'save-wheel') {
    const id = el.dataset.id;
    await api(`/api/admin/wheel/${encodeURIComponent(id)}`, { method: 'PUT', body: rowData(`[data-wheel-row="${CSS.escape(id)}"]`) });
    state.wheel = await api('/api/admin/wheel');
    toast('Çark dilimi kaydedildi.');
    return render();
  }
  if (action === 'save-quest') {
    const id = el.dataset.id;
    await api(`/api/admin/quests/${encodeURIComponent(id)}`, { method: 'PUT', body: rowData(`[data-quest-row="${CSS.escape(id)}"]`) });
    state.quests = await api('/api/admin/quests');
    toast('Görev kaydedildi.');
    return render();
  }
  if (action === 'search-users') {
    const query = document.querySelector('#user-search')?.value || '';
    state.users = await api(`/api/admin/users?limit=200&search=${encodeURIComponent(query)}`);
    return render();
  }
  if (action === 'grant') {
    const amount = Number(prompt('Dağıtılacak OC_POINTS miktarı:', '1000'));
    if (!amount) return;
    const reason = prompt('Dağıtım gerekçesi:', 'Kampanya ödülü') || 'Admin dağıtımı';
    const result = await api(`/api/admin/users/${el.dataset.id}/grant-points`, { method: 'POST', body: { amount, reason }, idempotencyKey: idem() });
    toast(`Yeni bakiye: ${money(result.balance)} OC_POINTS`);
    state.users = await api('/api/admin/users?limit=200');
    return render();
  }
  if (action === 'set-vip') {
    const tier = Number(prompt('VIP seviyesi (0-5):', el.dataset.current || '0'));
    if (!Number.isInteger(tier) || tier < 0 || tier > 5) return;
    await api(`/api/admin/users/${el.dataset.id}/vip`, { method: 'PUT', body: { tier } });
    toast(`VIP ${tier} atandı.`);
    state.users = await api('/api/admin/users?limit=200');
    return render();
  }
  if (action === 'save-provider') {
    const card = el.closest('[data-provider-card]');
    await api(`/api/admin/payment-providers/${encodeURIComponent(el.dataset.id)}`, { method: 'PUT', body: collectProvider(card) });
    toast(`${el.dataset.id} sağlayıcısı kaydedildi.`);
    return reloadPaymentSettings();
  }
  if (action === 'test-provider') {
    const result = await api(`/api/admin/payment-providers/${encodeURIComponent(el.dataset.id)}/test`, { method: 'POST', body: {} });
    toast(result.message, result.ok ? 'success' : 'error');
    return reloadPaymentSettings();
  }
  if (action === 'save-currency') {
    const row = el.closest('[data-currency-row]');
    const body = rowData(`[data-currency-row="${CSS.escape(el.dataset.id)}"]`);
    body.rate_to_try_e8 = Math.round(Number(row.querySelector('[data-rate]').value) * 1e8);
    body.source = 'manual';
    await api(`/api/admin/currencies/${encodeURIComponent(el.dataset.id)}`, { method: 'PUT', body });
    toast(`${el.dataset.id} kuru kaydedildi.`);
    return reloadPaymentSettings();
  }
  if (action === 'sync-tcmb') {
    const result = await api('/api/admin/fx/sync-tcmb', { method: 'POST', body: {} });
    toast(`${result.updated} döviz kuru TCMB'den güncellendi.`);
    return reloadPaymentSettings();
  }
  if (action === 'save-bank') {
    await api(`/api/admin/bank-accounts/${encodeURIComponent(el.dataset.id)}`, { method: 'PUT', body: rowData(`[data-bank-row="${CSS.escape(el.dataset.id)}"]`) });
    toast('Banka hesabı kaydedildi.');
    return reloadPaymentSettings();
  }
  if (action === 'create-bank') {
    await api('/api/admin/bank-accounts', { method: 'POST', body: rowData('#new-bank-form') });
    toast('Yeni banka hesabı eklendi.');
    return reloadPaymentSettings();
  }
  if (action === 'save-crypto') {
    const row = el.closest('[data-crypto-row]');
    const body = rowData(`[data-crypto-row="${CSS.escape(el.dataset.id)}"]`);
    body.manual_price_usd_e8 = Math.round(Number(row.querySelector('[data-crypto-price]').value) * 1e8);
    body.price_source = 'manual';
    await api(`/api/admin/crypto-assets/${encodeURIComponent(el.dataset.id)}`, { method: 'PUT', body });
    toast(`${el.dataset.id} kripto ayarı kaydedildi.`);
    return reloadPaymentSettings();
  }
  if (action === 'save-vip-price') {
    const selector = `[data-vip-price-row="${CSS.escape(`${el.dataset.tier}:${el.dataset.currency}`)}"]`;
    const row = document.querySelector(selector);
    const decimals = Number(el.dataset.decimals || 2);
    const amountMinor = Math.round(Number(row.querySelector('[data-price-display]').value) * (10 ** decimals));
    const enabled = row.querySelector('[data-k="enabled"]').checked;
    await api(`/api/admin/vip-prices/${el.dataset.tier}/${encodeURIComponent(el.dataset.currency)}`, { method: 'PUT', body: { amount_minor: amountMinor, enabled } });
    toast(`VIP ${el.dataset.tier} ${el.dataset.currency} fiyatı kaydedildi.`);
    return reloadPaymentSettings();
  }
}

document.addEventListener('submit', async (event) => {
  event.preventDefault();
  try {
    if (event.target.id === 'login-form') return await login(document.querySelector('#admin-email').value, document.querySelector('#admin-password').value);
    if (event.target.id === 'settings-form') return await saveSettings(event.target);
    if (event.target.id === 'presale-allocation-form') {
      const form = event.target;
      const cfg = state.presaleAllocation?.config || {};
      const decimals = Number(cfg.decimals || 18);
      const body = {
        policy: form.elements.policy.value,
        totalSupplyTokenBase: decimalToBase(form.elements.totalSupplyTokens.value, decimals),
        poolTokenBase: decimalToBase(form.elements.poolTokens.value, decimals),
        referencePriceUsdtMicros: Math.round(Number(form.elements.referencePrice.value) * 1e6),
        launchPriceUsdtMicros: Math.round(Number(form.elements.launchPrice.value) * 1e6),
        termsVersion: form.elements.termsVersion.value,
        autoFinalizeAtLaunch: form.elements.autoFinalizeAtLaunch.checked
      };
      await api('/api/admin/presale-allocation/settings', { method: 'PUT', body });
      toast('Presale arz, fiyat ve tahsisat ayarları kaydedildi.');
      return reloadFinalAdminSection('allocation');
    }
    if (event.target.id === 'distribution-settings-form') {
      const changes = collectGlobalSettings(event.target);
      state.settings = { ...(state.settings || {}), ...(await api('/api/admin/platform-settings', { method: 'PUT', body: changes })) };
      const secret = document.querySelector('#distribution-secret')?.value || '';
      if (secret) await api('/api/admin/secrets', { method: 'PUT', body: { key: 'distribution_signer_secret', value: secret } });
      toast('Dağıtım ayarları kaydedildi.');
      return reloadFinalAdminSection('distributions');
    }
    if (event.target.id === 'smtp-settings-form') {
      const changes = collectGlobalSettings(event.target);
      state.settings = { ...(state.settings || {}), ...(await api('/api/admin/platform-settings', { method: 'PUT', body: changes })) };
      const password = document.querySelector('#smtp-password')?.value || '';
      if (password) await api('/api/admin/secrets', { method: 'PUT', body: { key: 'smtp_password', value: password } });
      toast('SMTP ayarları kaydedildi.');
      return reloadFinalAdminSection('mail');
    }
  } catch (error) { toast(error.message, 'error'); }
});

document.addEventListener('click', async (event) => {
  const section = event.target.closest('[data-section]');
  if (section) {
    event.preventDefault();
    return navigate(section.dataset.section);
  }
  const action = event.target.closest('[data-action]');
  if (!action) return;
  event.preventDefault();
  try { await handleAction(action); }
  catch (error) { toast(error.message, 'error'); }
});

window.addEventListener('hashchange', () => navigate(location.hash.replace('#', '') || 'dashboard'));
setInterval(updateCountdown, 1000);

async function boot() {
  try {
    await api('/api/admin/me');
    await navigate(state.section, true);
  } catch {
    loginView();
  }
}

boot();
