const app = document.querySelector('#site-app');
const toastRoot = document.querySelector('#site-toast');
const number = new Intl.NumberFormat('tr-TR');
const moneyFormatter = new Intl.NumberFormat('tr-TR', { maximumFractionDigits: 6 });
const money = (value) => moneyFormatter.format(Number(value || 0));
const esc = (value) => String(value ?? '').replace(/[&<>'"]/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[char]));
const icon = (name = 'spark') => ({
  secure: '◆', fast: 'ϟ', community: '♟', web3: '◎', server: '⌁', ledger: '⇄', telegram: '➤', admin: '⚙',
  payments: '▣', staking: '◫', governance: '♜', ecosystem: '⬡', wallet: '▰', partner: '∞',
  vision: '◉', technology: '⌘', utility: 'ϟ', security: '◇', transparency: '◌', strategy: '⌁', confidence: '♢',
  flag: '⚑', shield: '◇', rocket: '▲', chart: '▥', crown: '♛', idea: '✦', blocks: '⬡', pie: '◕', scale: '⚖',
  summary: '▤', document: '▥', spark: '✦'
}[String(name).toLowerCase()] || '✦');

let site;
let config;
let authConfig;
let presaleRuntime;
let authMode = 'login';
let verificationEmail = '';
let verificationCode = '';
let countdownTimer;

function notify(message, type = 'info') {
  toastRoot.textContent = message;
  toastRoot.className = `site-toast show ${type}`;
  setTimeout(() => { toastRoot.className = 'site-toast'; }, 3500);
}

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

function routeSlug() {
  const preview = window.__ONLYCOIN_PREVIEW_PAGE || new URLSearchParams(location.search).get('preview');
  if (preview) return preview;
  const path = location.pathname.replace(/^\/+|\/+$/g, '');
  return ['presale', 'tokenomics', 'roadmap', 'whitepaper'].includes(path) ? path : 'home';
}

function page(slug) {
  return site.pages.find((item) => item.slug === slug) || site.pages[0] || {};
}

function section(slug, key, fallback = {}) {
  return site.sections.find((item) => item.page_slug === slug && item.section_key === key)?.content || fallback;
}

function safeRich(html) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(`<div>${html || ''}</div>`, 'text/html');
  const allowed = new Set(['DIV', 'P', 'UL', 'OL', 'LI', 'STRONG', 'EM', 'B', 'I', 'BR', 'H2', 'H3', 'H4', 'A', 'CODE']);
  doc.body.querySelectorAll('*').forEach((node) => {
    if (!allowed.has(node.tagName)) {
      node.replaceWith(...node.childNodes);
      return;
    }
    [...node.attributes].forEach((attr) => node.removeAttribute(attr.name));
    if (node.tagName === 'A') {
      const href = String(node.getAttribute('href') || '');
      if (/^(https?:\/\/|\/|#)/.test(href)) node.setAttribute('href', href);
      else node.removeAttribute('href');
    }
  });
  return doc.body.firstElementChild?.innerHTML || '';
}

function countdownMarkup(compact = false) {
  return `<div class="launch-clock ${compact ? 'compact' : ''}"><span>${esc(site.branding.launchMessage || 'Lansmana kalan süre')}</span><div data-countdown><b>--</b><small>GÜN</small><b>--</b><small>SAAT</small><b>--</b><small>DAKİKA</small><b>--</b><small>SANİYE</small></div></div>`;
}

function updateCountdown() {
  const target = new Date(site?.branding?.launchAt || Date.now()).getTime();
  const diff = Math.max(0, target - Date.now());
  const total = Math.floor(diff / 1000);
  const parts = diff <= 0 ? [0, 0, 0, 0] : [Math.floor(total / 86400), Math.floor((total % 86400) / 3600), Math.floor((total % 3600) / 60), total % 60];
  document.querySelectorAll('[data-countdown]').forEach((node) => {
    if (diff <= 0) {
      node.innerHTML = '<strong class="launched">Lansman Başladı</strong>';
      return;
    }
    node.innerHTML = parts.map((value, index) => `<b>${String(value).padStart(2, '0')}</b><small>${['GÜN', 'SAAT', 'DAKİKA', 'SANİYE'][index]}</small>`).join('');
  });
}

function header(active) {
  const navPages = site.pages.filter((item) => item.enabled !== 0);
  return `<header class="site-header"><div class="header-inner"><a class="brand" href="/"><span class="brand-mark"><img src="/game/assets/onlycoin-token.png" alt=""></span><span><strong>ONLYCOIN</strong><small>DIGITAL VALUE ECOSYSTEM</small></span></a><button class="mobile-menu" data-menu aria-label="Menüyü aç">☰</button><nav class="site-nav" data-nav>${navPages.map((item) => `<a class="${active === item.slug ? 'active' : ''}" href="/${item.slug === 'home' ? '' : item.slug}">${esc(item.nav_label)}</a>`).join('')}<a href="/game/">Tap to Earn</a></nav><div class="header-actions"><button class="outline-button header-login" data-site-auth>Giriş / Kayıt</button><a class="gold-button header-cta" href="/game/">Oyunu Aç <span>↗</span></a></div></div></header>`;
}

function footer() {
  return `<footer class="site-footer"><div class="footer-grid"><div><a class="brand" href="/"><span class="brand-mark"><img src="/game/assets/onlycoin-token.png" alt=""></span><span><strong>ONLYCOIN</strong><small>DIGITAL VALUE ECOSYSTEM</small></span></a><p>Güvenlik, şeffaflık ve topluluk odağında geliştirilen çok kanallı OnlyCoin ekosistemi.</p><div class="socials"><a href="${esc(site.branding.social.telegram || '#')}" aria-label="Telegram">➤</a><a href="${esc(site.branding.social.x || '#')}" aria-label="X">𝕏</a><a href="${esc(site.branding.social.discord || '#')}" aria-label="Discord">◉</a><a href="${esc(site.branding.social.youtube || '#')}" aria-label="YouTube">▶</a></div></div><div><h4>Hızlı Bağlantılar</h4>${site.pages.map((item) => `<a href="/${item.slug === 'home' ? '' : item.slug}">${esc(item.nav_label)}</a>`).join('')}</div><div><h4>Platform</h4><a href="/game/">Tap-to-Earn</a><a href="/presale">Presale</a><a href="/tokenomics">Tokenomics</a><a href="/roadmap">Roadmap</a></div><div><h4>Yasal & Destek</h4><a href="/privacy.html">Gizlilik Politikası</a><a href="/terms.html">Kullanım Koşulları</a><a href="mailto:${esc(site.branding.supportEmail)}">${esc(site.branding.supportEmail)}</a><span class="contract-line">Contract: ${site.branding.tokenContract ? esc(site.branding.tokenContract) : 'Lansman öncesi açıklanacak'}</span></div></div><div class="footer-bottom"><span>© 2026 OnlyCoin. Tüm hakları saklıdır.</span><span>${esc(site.branding.networkName || 'Web3')} · ${esc(site.branding.tokenSymbol || 'OC')}</span></div></footer>`;
}

function coinVisual(extra = '') {
  return `<div class="coin-scene ${extra}"><div class="coin-orbit orbit-a"></div><div class="coin-orbit orbit-b"></div><div class="coin-rays"></div><div class="coin-halo"></div><img class="hero-coin" src="/game/assets/onlycoin-token.png" alt="OnlyCoin token"><div class="coin-platform"><i></i><i></i><i></i></div><span class="particle p1"></span><span class="particle p2"></span><span class="particle p3"></span></div>`;
}

function hero(pageData, variant, aside = coinVisual()) {
  return `<section class="hero hero-${variant}"><div class="hero-grid"><div class="hero-copy"><span class="eyebrow">ONLYCOIN · ${esc(pageData.nav_label || variant.toUpperCase())}</span><h1><span>${esc(pageData.hero_title || 'OnlyCoin')}</span><em>${esc(pageData.hero_accent || '')}</em></h1><h2>${esc(pageData.hero_subtitle || '')}</h2><p>${esc(pageData.hero_description || '')}</p><div class="hero-actions"><a class="gold-button" href="${esc(pageData.primary_cta_url || '/game/')}">${esc(pageData.primary_cta_label || 'Başla')} <span>→</span></a><a class="outline-button" href="${esc(pageData.secondary_cta_url || '/whitepaper')}">${esc(pageData.secondary_cta_label || 'Detaylar')}</a></div><div class="hero-trust"><span>✓ Sunucu Otoriteli</span><span>✓ Şeffaf Ledger</span><span>✓ Topluluk Odaklı</span></div></div><div class="hero-aside">${aside}</div></div>${countdownMarkup(true)}</section>`;
}

function metricCards(items) {
  return `<div class="metric-grid">${items.map((item) => `<article class="metric-card"><span class="metric-icon">${icon(item.icon)}</span><div><small>${esc(item.label)}</small><strong>${esc(item.value)}</strong>${item.note ? `<em>${esc(item.note)}</em>` : ''}</div></article>`).join('')}</div>`;
}

function featureCards(items, className = '') {
  return `<div class="feature-grid ${className}">${items.map((item, index) => `<article class="feature-card"><span>${icon(item.icon || item.title)}</span><small>${String(index + 1).padStart(2, '0')}</small><h3>${esc(item.title)}</h3><p>${esc(item.text || item.description || '')}</p></article>`).join('')}</div>`;
}

function sectionHeading(kicker, title, text = '') {
  return `<div class="section-heading"><span class="eyebrow">${esc(kicker)}</span><h2>${esc(title)}</h2>${text ? `<p>${esc(text)}</p>` : ''}</div>`;
}

function allocationGradient(rows) {
  let cursor = 0;
  const stops = rows.map((row) => {
    const start = cursor;
    cursor += Number(row.percentage_bps || 0) / 100;
    return `${row.color || '#d6a62b'} ${start}% ${cursor}%`;
  });
  return `conic-gradient(${stops.join(',')})`;
}

function tokenomicsBlock(compact = false) {
  const rows = site.tokenomics.allocations;
  return `<div class="tokenomics-layout ${compact ? 'compact' : ''}"><div class="donut-wrap"><div class="donut" style="background:${allocationGradient(rows)}"><div><img src="/game/assets/onlycoin-token.png" alt=""><b>${number.format(site.tokenomics.totalSupply)}</b><span>TOPLAM ARZ</span></div></div></div><div class="allocation-list">${rows.map((row) => `<div><i style="background:${esc(row.color)}"></i><span><b>${esc(row.label)}</b><small>${esc(row.description)}</small></span><strong>${(Number(row.percentage_bps) / 100).toFixed(0)}%</strong><em>${number.format(row.token_amount)} OC</em></div>`).join('')}</div></div>`;
}

function roadmapStrip(limit = 5) {
  return `<div class="roadmap-strip">${site.roadmap.slice(0, limit).map((row, index) => `<article class="roadmap-node ${esc(row.status)}"><div class="node-top"><span>${icon(row.icon)}</span><i></i></div><small>PHASE ${row.phase_no}</small><h3>${esc(row.title)}</h3><p>${esc(row.subtitle)}</p><ul>${(row.items || []).slice(0, 4).map((item) => `<li>${esc(item)}</li>`).join('')}</ul><div class="progress"><i style="width:${Number(row.completion_percent)}%"></i></div><b>${row.completion_percent}%</b></article>${index < Math.min(site.roadmap.length, limit) - 1 ? '<div class="roadmap-link"></div>' : ''}`).join('')}</div>`;
}

function ctaBanner(title, text, primary = ['/game/', 'Oyunu Aç'], secondary = ['/whitepaper', 'Whitepaper']) {
  return `<section class="cta-banner"><div class="cta-coin"><img src="/game/assets/onlycoin-token.png" alt=""></div><div><span class="eyebrow">ONLYCOIN ECOSYSTEM</span><h2>${esc(title)}</h2><p>${esc(text)}</p></div><div class="hero-actions"><a class="gold-button" href="${esc(primary[0])}">${esc(primary[1])} →</a><a class="outline-button" href="${esc(secondary[0])}">${esc(secondary[1])}</a></div></section>`;
}

function homePage() {
  const p = page('home');
  const statsSection = section('home', 'stats', { items: [] });
  const features = section('home', 'features', { items: [] }).items || [];
  const statItems = [
    { icon: 'chart', label: 'ONLYCOIN PRICE', value: site.presale.enabled && site.presale.activeStage ? `$${money(Number(site.presale.activeStage.price_usdt_micros || 0) / 1e6)}` : 'YAPILANDIRILMADI', note: site.presale.enabled ? 'Aktif presale fiyatı' : 'Presale kapalı' },
    { icon: 'community', label: 'TOPLULUK', value: number.format(site.stats.users || 0), note: `${number.format(site.stats.activeUsers || 0)} bugün aktif` },
    { icon: 'ledger', label: 'TOKEN HOLDERS', value: number.format(site.stats.holders || 0), note: 'Doğrulanmış ledger bakiyesi' },
    { icon: 'rocket', label: 'PRESALE', value: site.presale.enabled ? `${money((site.stats.raisedUsdtMicros || 0) / 1e6)} USDT` : 'KAPALI', note: site.presale.enabled ? `${number.format(site.stats.presaleTokens || 0)} OC tahsis` : 'Yönetim panelinden yapılandırılır' }
  ];
  return `${hero(p, 'home')}<section class="page-section stat-section">${metricCards(statItems)}</section><section class="page-section"><div class="split-heading">${sectionHeading('NEDEN ONLYCOIN?', 'Güçlü teknoloji, temiz deneyim.', 'Tap-to-earn oyunundan token ekonomisine kadar her işlem aynı güvenli çekirdek üzerinde çalışır.')}<p class="side-copy">Telegram, PWA, Android ve iOS kullanıcıları aynı kurallara, aynı bakiyeye ve aynı lansman sayacına bağlanır.</p></div>${featureCards(features.map((item, i) => ({ ...item, icon: ['server', 'ledger', 'telegram', 'admin'][i] })))}</section><section class="page-section dark-band">${sectionHeading('TOKENOMICS', 'Şeffaf dağılım, uzun vadeli büyüme.', 'Toplam arz ve vesting modeli yönetim panelinden güncellenir; canlı siteye anında yansır.')}${tokenomicsBlock(true)}<div class="center-action"><a class="outline-button" href="/tokenomics">Tokenomics Detayları →</a></div></section><section class="page-section">${sectionHeading('ROADMAP', 'Bir sonraki kilometre taşına birlikte.', 'Tamamlanan, mevcut ve yaklaşan aşamaları canlı olarak takip edin.')}${roadmapStrip()}<div class="center-action"><a class="outline-button" href="/roadmap">Tüm Yol Haritası →</a></div></section>${ctaBanner('Dijital değerin geleceğini birlikte inşa ediyoruz.', 'OnlyCoin oyununa katılın, görevleri tamamlayın ve lansman yolculuğunu canlı takip edin.')}`;
}

function presaleWidget() {
  if (!site.presale.enabled) return '<div class="presale-widget empty-state"><span>ONLYCOIN PRESALE</span><h3>Ön satış henüz etkin değil</h3><p>Arz, fiyat, ödeme ve uyum ayarları yönetim panelinde tamamlandığında katılım açılacaktır.</p></div>';
  const stage = site.presale.activeStage || site.presale.stages[0];
  if (!stage) return '<div class="presale-widget empty-state">Aktif satış aşaması bulunmuyor.</div>';
  const runtime = presaleRuntime || {};
  const displayPriceMicros = runtime.policy === 'fixed_at_deposit' ? Number(stage.price_usdt_micros || runtime.referencePriceUsdtMicros || 1) : Number(runtime.launchPriceUsdtMicros || stage.price_usdt_micros || 1);
  const price = displayPriceMicros / 1e6;
  const deposit = 100;
  const estimated = price > 0 ? deposit / price * (1 + Number(stage.bonus_bps || 0) / 10000) : 0;
  return `<div class="presale-widget"><div class="widget-head"><span>ONLYCOIN PRESALE</span><b>${esc(stage.name)}</b></div><div class="stage-price"><small>${runtime.policy === 'pro_rata_pool' ? 'HAVUZ POLİTİKASI' : 'GÜNCEL TAHMİNİ FİYAT'}</small><strong>$${money(price)}</strong><em>+${(Number(stage.bonus_bps) / 100).toFixed(0)}% BONUS</em></div><div class="sale-progress"><div><span>Doğrulanmış Deposit</span><b>${money(Number(runtime.totalPaidUsdtMicros || 0) / 1e6)} USDT</b></div><div><span>Presale Havuzu</span><b>${esc(runtime.poolTokenBase ? 'Admin Yönetimli' : '-')}</b></div><div class="progress"><i style="width:${Math.min(100, Number(runtime.totalPaidUsdtMicros || 0) / Math.max(1, Number(site.presale.hardCapUsdtMicros || 1)) * 100)}%"></i></div><strong>Deposit Esaslı</strong></div><div class="buy-box"><label>YATIRILACAK DEPOSIT</label><div><input id="site-presale-amount" value="${deposit}" inputmode="decimal" aria-label="USDT tutarı"><span>USDT</span></div><label>GÜNCEL TAHMİNİ HAKEDİŞ</label><div class="receive"><b id="site-presale-estimate">${number.format(Math.floor(estimated))}</b><span>OC</span></div><button class="gold-button full" data-site-presale>Hesap Oluştur ve Katıl →</button><small>Esas kayıt USDT deposit miktarıdır. Tahmini OC, finalizasyona kadar arz/fiyat politikasına göre değişebilir.</small></div></div>`;
}

function presalePage() {
  const p = page('presale');
  const trust = section('presale', 'trust', { items: [] }).items || [];
  const steps = section('presale', 'how-to-buy', { items: [] }).items || [];
  const faq = section('presale', 'faq', { items: [] }).items || [];
  const aside = `<div class="presale-aside">${coinVisual('small')}${presaleWidget()}</div>`;
  const raised = (site.presale.totals.raised_usdt_micros || 0) / 1e6;
  return `${hero(p, 'presale', aside)}<section class="page-section stat-section">${metricCards([{ icon: 'payments', label: 'TOPLANAN', value: `${money(raised)} USDT`, note: `Hard Cap ${money(site.presale.hardCapUsdtMicros / 1e6)} USDT` }, { icon: 'community', label: 'KATILIMCI', value: number.format(site.presale.totals.buyers || 0), note: 'Doğrulanmış satın alma' }, { icon: 'pie', label: 'SATILAN TOKEN', value: number.format(site.presale.totals.sold_token_base || 0), note: 'Bonuslar dahil' }, { icon: 'security', label: 'AĞ', value: esc(site.presale.network || site.branding.networkName || 'Yapılandırılmadı'), note: 'Doğrulanmış ödeme akışı' }])}</section><section class="page-section">${sectionHeading('GÜVEN & ŞEFFAFLIK', 'Presale akışı baştan sona izlenebilir.', 'Sipariş, transfer doğrulaması ve token tahsisi tek platform üzerinde yönetilir.')}${featureCards(trust)}</section><section class="page-section dark-band" id="how-to-buy">${sectionHeading('NASIL ALINIR?', 'Dört adımda OnlyCoin.', 'Kullanıcı akışı Telegram ve web istemcilerinde aynı şekilde çalışır.')}<div class="steps-grid">${steps.map((item, index) => `<article><b>${String(index + 1).padStart(2, '0')}</b><span>${icon(['telegram','payments','security','wallet'][index])}</span><h3>${esc(item.title)}</h3><p>${esc(item.text)}</p></article>`).join('')}</div></section><section class="page-section">${sectionHeading('TOKEN DAĞILIMI', 'Sürdürülebilir ekosistem için dengeli tahsisat.')}${tokenomicsBlock(true)}</section><section class="page-section dark-band">${sectionHeading('LANSMA GİDEN YOL', 'Presale’den global ekosisteme.')}${roadmapStrip()}</section><section class="page-section faq-section">${sectionHeading('SIK SORULAN SORULAR', 'Presale hakkında merak edilenler.')}<div class="faq-list">${faq.map((item, index) => `<details ${index === 0 ? 'open' : ''}><summary>${esc(item.q)}<span>+</span></summary><p>${esc(item.a)}</p></details>`).join('')}</div></section>${ctaBanner('Presale aşamasına katılmaya hazır mısınız?', 'Aktif fiyatı, bonusu ve ödeme seçeneklerini oyun cüzdanından görüntüleyin.', ['/game/#presale', 'Presale Katıl'], ['/whitepaper', 'Whitepaper Oku'])}`;
}

function tokenomicsPage() {
  const p = page('tokenomics');
  const utility = section('tokenomics', 'utility', { items: [] }).items || [];
  const why = section('tokenomics', 'why', { items: [] }).items || [];
  return `${hero(p, 'tokenomics')}<section class="page-section stat-section">${metricCards([{ icon: 'ledger', label: 'TOPLAM ARZ', value: `${number.format(site.tokenomics.totalSupply)} OC`, note: 'Sabit tahsisat modeli' }, { icon: 'community', label: 'TOPLULUK', value: `${(Number(site.tokenomics.allocations[0]?.percentage_bps || 0) / 100).toFixed(0)}%`, note: 'Community & Ecosystem' }, { icon: 'payments', label: 'PRESALE FİYATI', value: `$${money(Number(site.presale.activeStage?.price_usdt_micros || 0) / 1e6)}`, note: esc(site.presale.activeStage?.name || '') }, { icon: 'web3', label: 'AĞ', value: esc(site.branding.networkName || 'Multi-chain'), note: 'Sağlayıcı adaptörleri' }])}</section><section class="page-section">${sectionHeading('TOKEN ALLOCATION', 'Her tokenın kullanım amacı açık.', 'Tahsisat, yüzde ve vesting verileri yönetim panelindeki Tokenomics bölümünden yönetilir.')}${tokenomicsBlock()}</section><section class="page-section dark-band">${sectionHeading('TOKEN UTILITY', 'OC ekosistem içinde ne işe yarar?', 'Kullanım alanları teknik, bölgesel ve hukuki uygunluk çerçevesinde açılır.')}${featureCards(utility, 'four')}</section><section class="page-section">${sectionHeading('VESTING SCHEDULE', 'Uzun vadeli hizalanma için kontrollü açılım.')}<div class="vesting-table"><div class="vesting-head"><span>KATEGORİ</span><span>TAHSİSAT</span><span>TOKEN</span><span>VESTING</span></div>${site.tokenomics.allocations.map((row) => `<div><span><i style="background:${esc(row.color)}"></i>${esc(row.label)}</span><b>${(Number(row.percentage_bps) / 100).toFixed(0)}%</b><span>${number.format(row.token_amount)} OC</span><span>${esc(row.vesting)}</span></div>`).join('')}</div></section><section class="page-section dark-band">${sectionHeading('RELEASE ROADMAP', 'Arz emisyonu ürün kilometre taşlarıyla ilerler.')}${roadmapStrip()}</section><section class="page-section">${sectionHeading('NEDEN ÇALIŞIR?', 'Topluluk, likidite ve disiplinli vesting dengesi.')}${featureCards(why, 'four')}</section>${ctaBanner('Token modelinin tüm ayrıntılarını inceleyin.', 'Teknik mimari, riskler, vesting ve uzun vadeli strateji whitepaper içinde yer alır.', ['/whitepaper', 'Whitepaper Oku'], ['/presale', 'Presale'])}`;
}

function roadmapPage() {
  const p = page('roadmap');
  const eco = section('roadmap', 'ecosystem', { items: [] }).items || [];
  const current = site.roadmap.find((row) => row.status === 'current') || site.roadmap[0];
  const completion = site.roadmap.length ? Math.round(site.roadmap.reduce((sum, x) => sum + Number(x.completion_percent || 0), 0) / site.roadmap.length) : 0;
  return `${hero(p, 'roadmap')}<section class="page-section stat-section">${metricCards([{ icon: 'flag', label: 'MEVCUT AŞAMA', value: current ? `Phase ${current.phase_no}` : '-', note: current?.title || '' }, { icon: 'chart', label: 'GENEL TAMAMLANMA', value: `${completion}%`, note: 'Aşama ortalaması' }, { icon: 'rocket', label: 'SONRAKİ HEDEF', value: site.roadmap.find((x) => x.status === 'upcoming')?.title || 'Global Expansion', note: 'Planlanan kilometre taşı' }, { icon: 'community', label: 'TOPLULUK', value: `${number.format(site.stats.users || 0)}+`, note: 'Kayıtlı kullanıcı' }])}</section><section class="page-section">${sectionHeading('STRATEGIC ROADMAP', 'Beş aşamada kalıcı ekosistem.', 'Her aşamanın durumu, ilerlemesi ve görevleri yönetim panelinden canlı güncellenir.')}${roadmapStrip()}</section><section class="page-section dark-band">${sectionHeading('ROADMAP BY QUARTER', 'Aşamaları teslimat takvimine dönüştürüyoruz.')}<div class="quarter-grid">${site.roadmap.slice(0, 4).map((row, index) => `<article><span>Q${index + 1} 2026</span><h3>${esc(row.title)}</h3><ul>${(row.items || []).map((item) => `<li>${esc(item)}</li>`).join('')}</ul><div class="progress"><i style="width:${row.completion_percent}%"></i></div><b>${row.completion_percent}%</b></article>`).join('')}</div></section><section class="page-section">${sectionHeading('KEY MILESTONES', 'Tamamlanan ve yaklaşan temel teslimatlar.')}<div class="milestone-grid">${site.roadmap.flatMap((row) => (row.items || []).slice(0, 1).map((item) => ({ ...row, item }))).map((item) => `<article><span>${icon(item.icon)}</span><div><small>${esc(item.status)}</small><h3>${esc(item.item)}</h3><p>${esc(item.title)} · ${item.completion_percent}%</p></div></article>`).join('')}</div></section><section class="page-section dark-band">${sectionHeading('ECOSYSTEM DEVELOPMENT', 'Yol haritasını destekleyen ürün modülleri.')}${featureCards(eco, 'four')}</section><section class="page-section">${sectionHeading('GROWTH TRAJECTORY', 'Lansmandan yönetişime yükselen gelişim eğrisi.')}<div class="trajectory"><svg viewBox="0 0 1000 260" preserveAspectRatio="none" aria-hidden="true"><defs><linearGradient id="area" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f4c755" stop-opacity=".38"/><stop offset="1" stop-color="#f4c755" stop-opacity="0"/></linearGradient></defs><path class="area" d="M20 230 C180 220 230 190 350 178 S550 130 650 120 S840 70 980 25 L980 260 L20 260Z"/><path class="line" d="M20 230 C180 220 230 190 350 178 S550 130 650 120 S840 70 980 25"/></svg><div class="trajectory-labels">${site.roadmap.map((row) => `<span><i>${icon(row.icon)}</i><b>${esc(row.title)}</b><small>${row.completion_percent}%</small></span>`).join('')}</div></div></section>${ctaBanner('OnlyCoin yolculuğuna katılın.', 'Geliştirme ilerlemesini takip edin, topluluğa katılın ve bir sonraki aşamayı birlikte şekillendirin.', ['/game/', 'Topluluğa Katıl'], ['/whitepaper', 'Whitepaper'])}`;
}

function bookVisual() {
  return `<div class="book-scene"><div class="book-glow"></div><div class="book"><div class="book-spine"><span>ONLYCOIN</span></div><div class="book-cover"><img src="/game/assets/onlycoin-token.png" alt=""><small>ONLYCOIN</small><strong>WHITEPAPER</strong><p>THE COMPLETE GUIDE TO THE FUTURE OF DIGITAL VALUE</p><em>VERSION ${esc(site.whitepaper.version)}</em></div></div><div class="coin-platform"><i></i><i></i><i></i></div></div>`;
}

function whitepaperPage() {
  const p = page('whitepaper');
  const summary = section('whitepaper', 'summary', { text: '' });
  const highlights = section('whitepaper', 'highlights', { items: [] }).items || [];
  const technology = section('whitepaper', 'technology', { items: [] }).items || [];
  const why = section('whitepaper', 'why', { items: [] }).items || [];
  return `${hero(p, 'whitepaper', bookVisual())}<section class="page-section stat-section">${metricCards([{ icon: 'document', label: 'VERSİYON', value: site.whitepaper.version, note: 'Yönetilebilir metadata' }, { icon: 'strategy', label: 'SON GÜNCELLEME', value: site.whitepaper.updatedAt, note: 'Canlı içerik' }, { icon: 'summary', label: 'TOPLAM SAYFA', value: String(site.whitepaper.totalPages), note: 'PDF metadata' }, { icon: 'web3', label: 'AĞ', value: site.branding.networkName || 'Web3', note: 'Multi-chain hazırlığı' }])}</section><section class="page-section executive"><div>${sectionHeading('EXECUTIVE SUMMARY', 'OnlyCoin modelinin özeti.')}<p class="lead">${esc(summary.text)}</p><div class="hero-actions"><a class="gold-button" href="${esc(site.whitepaper.downloadUrl || '#chapters')}">PDF İndir ↓</a><a class="outline-button" href="#chapters">Bölümleri İncele</a></div></div><div class="document-preview"><span>${icon('document')}</span><h3>Şeffaf ve modüler dokümantasyon</h3><p>Vizyon, ürün mimarisi, token ekonomisi, güvenlik sınırları ve aşamalı büyüme planı tek belgede.</p></div></section><section class="page-section dark-band" id="chapters">${sectionHeading('WHAT’S INSIDE', 'Whitepaper bölümleri.', 'Her bölüm yönetim panelinden başlık, özet ve güvenli HTML içerikle düzenlenebilir.')}<div class="chapter-grid">${site.whitepaper.chapters.map((chapter) => `<article><span>${String(chapter.chapter_no).padStart(2, '0')}</span><i>${icon(chapter.icon)}</i><h3>${esc(chapter.title)}</h3><p>${esc(chapter.summary)}</p><details><summary>Bölümü Oku →</summary><div>${safeRich(chapter.content_html)}</div></details></article>`).join('')}</div></section><section class="page-section">${sectionHeading('WHITEPAPER HIGHLIGHTS', 'Modelin beş temel yapı taşı.')}${featureCards(highlights, 'five')}</section><section class="page-section dark-band">${sectionHeading('TOKEN MODEL SNAPSHOT', 'Arz, fiyat ve topluluk tahsisatı tek bakışta.')}<div class="snapshot-grid">${metricCards([{ icon: 'ledger', label: 'TOPLAM ARZ', value: number.format(site.tokenomics.totalSupply) }, { icon: 'payments', label: 'PRESALE FİYATI', value: `$${money(Number(site.presale.activeStage?.price_usdt_micros || 0) / 1e6)}` }, { icon: 'community', label: 'TOPLULUK', value: `${(Number(site.tokenomics.allocations[0]?.percentage_bps || 0) / 100).toFixed(0)}%` }])}${tokenomicsBlock(true)}</div></section><section class="page-section">${sectionHeading('TECHNOLOGY OVERVIEW', 'Tek platform, çok istemci, güvenli çekirdek.')}${featureCards(technology, 'five')}</section><section class="page-section dark-band">${sectionHeading('ROADMAP PREVIEW', 'Teknik belgeden uygulama aşamalarına.')}${roadmapStrip()}</section><section class="page-section">${sectionHeading('WHY READ?', 'Karar vermeden önce modelin tamamını değerlendirin.')}${featureCards(why, 'four')}</section>${ctaBanner('Gelecek birlikte inşa edilir.', 'OnlyCoin whitepaper dokümanını indirin veya çalışan ekosistemi incelemek için oyuna katılın.', [site.whitepaper.downloadUrl || '#chapters', 'Whitepaper İndir'], ['/game/', 'Oyunu Aç'])}`;
}

function authModal() {
  const root = document.querySelector('#site-modal');
  const providers = authConfig?.providers || [];
  const verify = verificationEmail ? `<form id="site-verify-form" class="site-auth-form"><h2>E-posta Doğrulama</h2><p>${esc(verificationEmail)} adresine gönderilen kodu girin.</p><input name="code" maxlength="6" inputmode="numeric" value="${esc(verificationCode)}" placeholder="6 haneli kod" required><button class="gold-button">Doğrula ve Devam Et</button><button type="button" class="outline-button" data-site-resend>Doğrulama Kodunu Yeniden Gönder</button></form>` : '';
  const form = authMode === 'register' ? `<form id="site-register-form" class="site-auth-form"><h2>OnlyCoin Hesabı Oluştur</h2><input name="displayName" placeholder="Ad Soyad" required><input name="username" placeholder="Kullanıcı adı" required><input name="email" type="email" placeholder="E-posta" required><input name="password" type="password" minlength="12" placeholder="Güçlü parola (en az 12 karakter)" required><input name="confirmPassword" type="password" minlength="12" placeholder="Parolayı tekrar girin" required><label><input name="terms" type="checkbox" required> Presale koşullarını ve risk açıklamasını okudum.</label><button class="gold-button">Kayıt Ol</button></form>` : `<form id="site-login-form" class="site-auth-form"><h2>OnlyCoin Girişi</h2><input name="email" type="email" placeholder="E-posta" required><input name="password" type="password" placeholder="Parola" required><button class="gold-button">Giriş Yap</button></form>`;
  root.innerHTML = `<div class="site-modal-backdrop"><div class="site-auth-card"><button class="site-modal-close" data-site-close>×</button><div class="auth-logo"><img src="/game/assets/onlycoin-token.png" alt=""><strong>ONLYCOIN</strong></div>${verify || `<div class="site-auth-tabs"><button class="${authMode==='login'?'active':''}" data-site-auth-mode="login">Giriş</button><button class="${authMode==='register'?'active':''}" data-site-auth-mode="register">Kayıt</button></div>${form}<div class="site-auth-social">${providers.map((provider)=>`<button data-site-social="${esc(provider.id)}">${provider.id==='google'?'G':provider.id==='apple'?'':provider.id==='facebook'?'f':provider.id==='x'?'𝕏':'OC'} · ${esc(provider.name)}</button>`).join('')}</div>`}<small>Cüzdan parolası ve private key e-posta ile gönderilmez.</small></div></div>`;
}

async function siteLoginResult(result) {
  location.href = '/game/#wallet';
}

async function siteSocial(provider) {
  const result = await api(`/api/auth/oauth/${encodeURIComponent(provider)}/start?redirect=${encodeURIComponent('/game/#wallet')}`);
  location.href = result.url;
}

function render() {
  const slug = routeSlug();
  const pageData = page(slug);
  document.title = pageData.meta_title || `${pageData.title || 'OnlyCoin'} · OnlyCoin`;
  const meta = document.querySelector('meta[name="description"]');
  if (meta) meta.content = pageData.meta_description || site.branding.appName;
  const body = ({ home: homePage, presale: presalePage, tokenomics: tokenomicsPage, roadmap: roadmapPage, whitepaper: whitepaperPage }[slug] || homePage)();
  app.innerHTML = `${header(slug)}<main>${body}</main>${footer()}`;
  clearInterval(countdownTimer);
  updateCountdown();
  countdownTimer = setInterval(updateCountdown, 1000);
  document.querySelector('[data-menu]')?.addEventListener('click', () => document.querySelector('[data-nav]')?.classList.toggle('open'));
  document.querySelector('[data-site-auth]')?.addEventListener('click', authModal);
  document.querySelector('[data-site-presale]')?.addEventListener('click', authModal);
  document.querySelector('#site-presale-amount')?.addEventListener('input', (event) => {
    const stage = site.presale.activeStage || site.presale.stages[0];
    const priceMicros = presaleRuntime?.policy === 'fixed_at_deposit' ? Number(stage?.price_usdt_micros || presaleRuntime?.referencePriceUsdtMicros || 1) : Number(presaleRuntime?.launchPriceUsdtMicros || stage?.price_usdt_micros || 1);
    const estimate = priceMicros > 0 ? Number(event.target.value || 0) * 1e6 / priceMicros * (1 + Number(stage?.bonus_bps || 0) / 10000) : 0;
    const target = document.querySelector('#site-presale-estimate'); if (target) target.textContent = number.format(Math.floor(estimate));
  });
}

async function boot() {
  try {
    [site, config, authConfig, presaleRuntime] = await Promise.all([
      api('/api/public/site'),
      api('/api/public/config').catch(() => ({})),
      api('/api/public/auth').catch(() => ({ providers: [] })),
      api('/api/public/presale').catch(() => ({}))
    ]);
    render();
  } catch (error) {
    app.innerHTML = `<div class="error-screen"><img src="/game/assets/onlycoin-token.png" alt=""><h1>OnlyCoin yüklenemedi</h1><p>${esc(error.message)}</p><button class="gold-button" onclick="location.reload()">Tekrar Dene</button></div>`;
    notify(error.message, 'error');
  }
}


document.addEventListener('click', async (event) => {
  const close = event.target.closest('[data-site-close]');
  if (close) return document.querySelector('#site-modal').innerHTML = '';
  const mode = event.target.closest('[data-site-auth-mode]');
  if (mode) { authMode = mode.dataset.siteAuthMode; verificationEmail = ''; return authModal(); }
  const social = event.target.closest('[data-site-social]');
  if (social) { try { await siteSocial(social.dataset.siteSocial); } catch (error) { notify(error.message,'error'); } }
  if (event.target.closest('[data-site-resend]')) { try { const result = await api('/api/auth/email/resend', { method:'POST', body:{ email:verificationEmail } }); notify(result.emailDelivery?.delivered ? 'Yeni doğrulama kodu gönderildi.' : 'E-posta teslim edilemedi. SMTP ayarlarını kontrol etmek için destek birimine başvurun.', result.emailDelivery?.delivered ? 'info' : 'error'); } catch (error) { notify(error.message,'error'); } }
});

document.addEventListener('submit', async (event) => {
  if (!['site-login-form','site-register-form','site-verify-form'].includes(event.target.id)) return;
  event.preventDefault();
  try {
    const data = Object.fromEntries(new FormData(event.target));
    if (event.target.id === 'site-login-form') return siteLoginResult(await api('/api/auth/email/login', { method:'POST', body:data }));
    if (event.target.id === 'site-register-form') {
      delete data.terms;
      const result = await api('/api/auth/register', { method:'POST', body:data });
      if (result.verificationRequired) { verificationEmail = data.email; verificationCode = ''; authModal(); return notify(result.emailDelivery?.delivered ? 'Doğrulama kodu e-posta adresinize gönderildi.' : 'Hesabınız oluşturuldu ancak doğrulama e-postası teslim edilemedi. Kodu yeniden göndermeyi deneyin veya destek birimine başvurun.', result.emailDelivery?.delivered ? 'info' : 'error'); }
      return siteLoginResult(result);
    }
    if (event.target.id === 'site-verify-form') return siteLoginResult(await api('/api/auth/email/verify', { method:'POST', body:{ email:verificationEmail, code:data.code } }));
  } catch (error) { notify(error.message,'error'); }
});

boot();
