<?php
$template = __DIR__ . '/index.html';
if (!is_file($template)) {
  http_response_code(500);
  exit('index.html not found');
}

$html = file_get_contents($template);
$jsonFlags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;

function extract_js_initializer(string $source, string $name): string {
  $marker = 'const ' . $name . ' =';
  $start = strpos($source, $marker);
  if ($start === false) return '';
  $index = $start + strlen($marker);
  $length = strlen($source);
  while ($index < $length && preg_match('/\s/', $source[$index])) $index++;
  $open = $source[$index] ?? '';
  $close = $open === '{' ? '}' : ']';
  $depth = 0;
  $quote = '';
  $escaped = false;

  for ($cursor = $index; $cursor < $length; $cursor++) {
    $char = $source[$cursor];
    if ($quote !== '') {
      if ($escaped) $escaped = false;
      else if ($char === '\\') $escaped = true;
      else if ($char === $quote) $quote = '';
      continue;
    }
    if ($char === '"' || $char === "'") {
      $quote = $char;
      continue;
    }
    if ($char === $open) $depth++;
    if ($char === $close) {
      $depth--;
      if ($depth === 0) return substr($source, $index, $cursor - $index + 1);
    }
  }

  return '';
}

function js_object_to_array(string $literal): array {
  if ($literal === '') return [];
  $json = preg_replace('/([\{,]\s*)([A-Za-z_$][A-Za-z0-9_$]*)\s*:/u', '$1"$2":', $literal);
  $decoded = json_decode($json, true);
  return is_array($decoded) ? $decoded : [];
}

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

function normalize_language(?string $code, array $supported): string {
  if (!$code) return 'en';
  $clean = str_replace('_', '-', trim($code));
  if (in_array($clean, $supported, true)) return $clean;
  $base = strtolower(explode('-', $clean)[0]);
  if (in_array($base, $supported, true)) return $base;
  if ($base === 'zh') {
    $lower = strtolower($clean);
    if ((strpos($lower, 'tw') !== false || strpos($lower, 'hant') !== false || strpos($lower, 'hk') !== false) && in_array('zh-TW', $supported, true)) return 'zh-TW';
    if (in_array('zh-CN', $supported, true)) return 'zh-CN';
  }
  return 'en';
}

function detect_language(array $supported): string {
  $queryLang = isset($_GET['lang']) ? normalize_language($_GET['lang'], $supported) : '';
  if ($queryLang) return $queryLang;

  $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
  preg_match_all('/([a-zA-Z-]+)(?:;q=([0-9.]+))?/', $header, $matches, PREG_SET_ORDER);
  $candidates = [];
  foreach ($matches as $match) {
    $candidates[] = [$match[1], isset($match[2]) ? (float)$match[2] : 1.0];
  }
  usort($candidates, function ($a, $b) {
    if ($a[1] === $b[1]) return 0;
    return $a[1] < $b[1] ? 1 : -1;
  });
  foreach ($candidates as $candidate) {
    $lang = normalize_language($candidate[0], $supported);
    if ($lang !== 'en') return $lang;
  }
  return 'en';
}

function load_server_pack(string $language, array $data): array {
  if (isset($data[$language]) && is_array($data[$language])) return $data[$language];
  $packPath = __DIR__ . '/ssr-lang/' . $language . '.json';
  if (is_file($packPath)) {
    $pack = json_decode(file_get_contents($packPath), true);
    if (is_array($pack)) return array_replace_recursive($data['en'], $pack);
  }
  return $data['en'];
}

function site_info(): array {
  $host = $_SERVER['HTTP_HOST'] ?? 'qj00.com';
  $host = preg_replace('/:\d+$/', '', $host);
  $parts = array_values(array_filter(explode('.', $host)));
  $siteName = isset($parts[0]) && $parts[0] === 'www' && isset($parts[1]) ? $parts[1] : ($parts[0] ?? $host);
  return ['host' => $host, 'siteName' => $siteName, 'email' => 'hello@' . $host];
}

function fill_legal_template(string $text): string {
  $site = site_info();
  return str_replace(['{siteName}', '{domain}', '{email}'], [$site['siteName'], $site['host'], $site['email']], $text);
}

function story_html(array $item, bool $compact = false): string {
  $meta = $item['meta'] ?? 'Global Desk';
  return '<div class="story-image"><img src="' . h($item['img'] ?? '') . '" alt="' . h($item['title'] ?? '') . '" loading="lazy"></div>' .
    '<div class="story-body"><span class="tag">' . h($item['tag'] ?? '') . '</span><h3>' . h($item['title'] ?? '') . '</h3><p>' . h($item['text'] ?? '') . '</p>' .
    ($compact ? '' : '<div class="story-meta"><span>' . h($meta) . '</span><span>FX · Crypto · Policy</span></div>') . '</div>';
}

function render_pack_html(array $pack, string $language, array $languageRows): array {
  $currencies = [
    ['USD', '89.2%', 'United States'], ['EUR', '28.9%', 'Eurozone'], ['JPY', '16.8%', 'Japan'], ['GBP', '10.2%', 'United Kingdom'], ['CNY', '8.5-8.8%', 'China'],
    ['CHF', '6.4%', 'Switzerland'], ['AUD', '~6.0%', 'Australia'], ['CAD', '~6.0%', 'Canada'], ['HKD', '3.6-3.8%', 'Hong Kong'], ['SGD', 'Top 10', 'Singapore']
  ];

  $tape = '';
  foreach (($pack['tape'] ?? []) as $item) {
    $parts = preg_split('/\s+/', (string)$item);
    $code = array_shift($parts);
    $cls = strpos((string)$item, '-') !== false ? 'down' : 'up';
    $tape .= '<span class="tape-chip"><b>' . h($code) . '</b> <span class="' . $cls . '">' . h(implode(' ', $parts)) . '</span></span>';
  }

  $news = $pack['news'] ?? [];
  $features = $pack['features'] ?? [];
  $policies = $pack['policies'] ?? [];
  $crypto = $pack['crypto'] ?? [];
  $quotes = $pack['quotes'] ?? [];
  $currencyLabels = $pack['currencyLabel'] ?? [];
  $regionLabels = $pack['regionLabel'] ?? [];

  $sideStories = '';
  foreach (array_slice($news, 1, 3) as $item) $sideStories .= '<article>' . story_html($item, true) . '</article>';
  $hotRiver = '';
  foreach (array_slice($news, 4) as $item) $hotRiver .= '<article>' . story_html($item) . '</article>';
  $newsGrid = '';
  foreach ($features as $item) $newsGrid .= '<article class="feature-card">' . story_html($item) . '</article>';
  $policyBoard = '';
  foreach ($policies as $item) {
    $policyBoard .= '<article class="policy-card"><img src="' . h($item['img'] ?? '') . '" alt="' . h($item['title'] ?? '') . '" loading="lazy"><span class="tag">' . h($item['tag'] ?? '') . '</span><h3>' . h($item['title'] ?? '') . '</h3><p>' . h($item['text'] ?? '') . '</p></article>';
  }
  $cryptoList = '';
  foreach ($crypto as $item) {
    $cryptoList .= '<article class="crypto-card"><span class="tag">' . h($item['tag'] ?? '') . '</span><h3>' . h($item['title'] ?? '') . '</h3><p>' . h($item['text'] ?? '') . '</p></article>';
  }
  $quoteWall = '';
  foreach ($quotes as $item) $quoteWall .= '<div class="quote"><strong>' . h($item[0] ?? '') . '</strong><span>' . h($item[1] ?? '') . '</span></div>';
  $rankList = '';
  foreach ($currencies as $index => $item) {
    [$code, $share, $region] = $item;
    $rankList .= '<div class="rank-item"><span class="rank-no">' . ($index + 1) . '</span><span class="rank-name"><b>' . h($code) . ' · ' . h($currencyLabels[$code] ?? $code) . '</b><span>' . h($regionLabels[$code] ?? $region) . '</span></span><span class="rank-share">' . h($share) . '</span></div>';
  }
  $options = '';
  foreach ($languageRows as $item) {
    $selected = ($item['code'] ?? '') === $language ? ' selected' : '';
    $options .= '<option value="' . h($item['code'] ?? '') . '"' . $selected . '>' . h($item['name'] ?? '') . '</option>';
  }

  $site = site_info();
  return [
    'marketTape' => $tape,
    'languageOptions' => $options,
    'leadStory' => isset($news[0]) ? story_html($news[0]) : '',
    'sideStories' => $sideStories,
    'hotRiver' => $hotRiver,
    'newsGrid' => $newsGrid,
    'rankList' => $rankList,
    'policyBoard' => $policyBoard,
    'cryptoList' => $cryptoList,
    'quoteWall' => $quoteWall,
    'copyrightText' => '© ' . date('Y') . ' ' . $site['siteName'] . ' · ' . ($pack['footerText'] ?? ''),
  ];
}

function replace_element_inner(string $html, string $id, string $content): string {
  return preg_replace('/(<[^>]+id="' . preg_quote($id, '/') . '"[^>]*>)(.*?)(<\/[^>]+>)/su', '$1' . str_replace('$', '\\$', $content) . '$3', $html, 1);
}

function replace_i18n_text(string $html, string $key, string $value): string {
  return preg_replace('/(<([a-z0-9]+)\b[^>]*data-i18n="' . preg_quote($key, '/') . '"[^>]*>)(.*?)(<\/\2>)/isu', '$1' . str_replace('$', '\\$', h($value)) . '$4', $html, 1);
}

$data = js_object_to_array(extract_js_initializer($html, 'data'));
$languageRows = js_object_to_array(extract_js_initializer($html, 'supportedLanguages'));
if (!isset($data['en']) || !$languageRows) {
  http_response_code(500);
  exit('language data parse failed');
}

$supported = array_values(array_filter(array_map(function ($row) { return $row['code'] ?? null; }, $languageRows)));
$htmlLangs = [
  'en' => 'en-US', 'zh-CN' => 'zh-CN', 'zh-TW' => 'zh-TW', 'ja' => 'ja-JP', 'ko' => 'ko-KR',
  'es' => 'es-ES', 'fr' => 'fr-FR', 'de' => 'de-DE', 'pt' => 'pt-PT', 'ru' => 'ru-RU',
  'ar' => 'ar', 'hi' => 'hi-IN', 'id' => 'id-ID', 'vi' => 'vi-VN', 'th' => 'th-TH',
  'tr' => 'tr-TR', 'it' => 'it-IT', 'uk' => 'uk-UA',
];
foreach ($supported as $code) if (!isset($htmlLangs[$code])) $htmlLangs[$code] = $code;

$initialLang = detect_language($supported);
$pack = load_server_pack($initialLang, $data);
$data[$initialLang] = $pack;
$ssr = render_pack_html($pack, $initialLang, $languageRows);
$rtlLanguages = ['ar', 'dv', 'fa', 'he', 'ps', 'sd', 'ug', 'ur', 'yi', 'ckb'];
$direction = in_array(explode('-', $initialLang)[0], $rtlLanguages, true) ? 'rtl' : 'ltr';

$html = preg_replace('/<html\s+lang="[^"]*"/i', '<html lang="' . h($htmlLangs[$initialLang] ?? $initialLang) . '" dir="' . $direction . '"', $html, 1);
$html = preg_replace('/<title>.*?<\/title>/su', '<title>' . h($pack['brand'] ?? 'Global FX Radar') . '</title>', $html, 1);
foreach ($pack as $key => $value) {
  if (is_string($value)) $html = replace_i18n_text($html, $key, $value);
}
$html = preg_replace('/<select id="languageSelect"([^>]*)>.*?<\/select>/su', '<select id="languageSelect"$1>' . $ssr['languageOptions'] . '</select>', $html, 1);
foreach (['marketTape', 'leadStory', 'sideStories', 'hotRiver', 'newsGrid', 'rankList', 'policyBoard', 'cryptoList', 'quoteWall', 'copyrightText'] as $id) {
  $html = replace_element_inner($html, $id, $ssr[$id] ?? '');
}

$bootstrap = '<script>window.__INITIAL_LANG__=' . json_encode($initialLang, $jsonFlags) . ';window.__LANGUAGE_NAMES__=' . json_encode(array_column($languageRows, 'name', 'code'), $jsonFlags) . ';window.__HTML_LANGS__=' . json_encode($htmlLangs, $jsonFlags) . ';window.__SSR_DATA__=' . json_encode($data, $jsonFlags) . ';</script>';
$html = str_replace('</head>', "  $bootstrap\n  </head>", $html);
$html = preg_replace('/const data = \{[\s\S]*?\n      \};/u', 'const data = window.__SSR_DATA__ || { en: {} };', $html, 1);
$html = preg_replace('/languageSelect\.addEventListener\("change", \(\) => setLanguage\(languageSelect\.value\)\);/u', 'languageSelect.addEventListener("change", () => { window.location.href = `?lang=${encodeURIComponent(languageSelect.value)}`; });', $html, 1);

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
echo $html;
