<script lang="ts">
  // Hidden on-device debug panel, opened by tapping the header title ten times (Header.svelte) and
  // closed by tapping anywhere except the Share control. It shows a privacy-safe client diagnostic
  // snapshot (no secrets, no initData values, no IP) and shares it through the OS share sheet (or a
  // clipboard copy on desktop) — a support aid for reproducing client-specific issues, e.g. the
  // Telegram Android presentation quirks. Drawn from the top, just under the app header.
  import { onMount } from 'svelte';
  import { app, closeDebug, resetOnboarding } from '../lib/app.svelte';
  import { connection } from '../lib/connection.svelte';
  import { shareText } from '../lib/share';
  import { telegramChromeDiag } from '../lib/telegram';

  // The local move-preview snapshot — the feature flag, the bad-connection breaker and the
  // dictionaries cached in IndexedDB with their sizes — loads async so a report about the
  // preview is precise. Dynamically imported so the debug panel keeps the dict code lazy.
  let dictInfo = $state('local eval: …');
  onMount(() => {
    void (async () => {
      try {
        const m = await import('../lib/dict');
        const list = await m.listCachedDicts();
        const cached = list.length ? list.map((d) => `${d.key}=${(d.bytes / 1024).toFixed(0)}KB`).join(' ') : 'none';
        dictInfo = `dict breaker: ${m.dictLoadingDisabled() ? 'TRIPPED' : 'ok'}\ndicts cached: ${cached}`;
      } catch {
        dictInfo = 'local eval: n/a';
      }
    })();
  });

  const report = $derived(
    [
      `app: ${__APP_VERSION__}`,
      `locale: ${app.locale}  theme: ${app.theme}  reduceMotion: ${app.reduceMotion}`,
      `online: ${connection.online}  streamAlive: ${app.streamAlive}`,
      `userId: ${app.session?.userId ?? '—'}  guest: ${app.profile?.isGuest ?? '—'}`,
      telegramChromeDiag(),
      dictInfo,
    ].join('\n'),
  );

  let label = $state('Share');
  async function share(e: MouseEvent): Promise<void> {
    e.stopPropagation(); // a tap on Share shares; it must not also close the panel
    const r = await shareText(report, `Scrabble debug ${__APP_VERSION__}`);
    if (r === 'copied') {
      label = 'Copied';
      setTimeout(() => (label = 'Share'), 1500);
    }
  }

  // Clear the first-run coachmark "seen" flags so the onboarding replays on the next launch — a
  // manual re-test aid. Stops the click from also closing the panel, like the Share control.
  let resetLabel = $state('Reset visited');
  function resetVisited(e: MouseEvent): void {
    e.stopPropagation();
    resetOnboarding();
    // Also clear the local move-preview dictionary cache (safe — it re-downloads).
    // Dynamically imported so the debug panel keeps the dict code out of the app bundle.
    void import('../lib/dict').then((m) => {
      m.clearDictCache();
      m.clearDictInstances();
      m.bustDictHttpCache(); // also bypass the browser HTTP cache on the next load (a true cold test)
    });
    resetLabel = 'Cleared — relaunch';
    setTimeout(() => (resetLabel = 'Reset visited'), 1800);
  }
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="overlay" onclick={closeDebug}>
  <div class="actions">
    <button class="share" onclick={share}>{label}</button>
    <button class="reset" onclick={resetVisited}>{resetLabel}</button>
  </div>
  <pre class="body">{report}</pre>
</div>

<style>
  .overlay {
    position: fixed;
    inset: 0;
    z-index: 10000;
    /* Drawn from the top; the content clears the app header (~56px + the device safe-area). */
    padding: calc(var(--tg-safe-top, 0px) + 56px) 12px 16px;
    background: rgba(0, 0, 0, 0.82);
    overflow: auto;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  .actions {
    flex: 0 0 auto;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
  .share {
    flex: 0 0 auto;
    padding: 7px 16px;
    border: 1px solid var(--accent);
    background: var(--accent);
    color: var(--accent-text);
    border-radius: var(--radius-sm);
    font-size: 0.95rem;
  }
  /* Secondary (outline) styling so it reads as a utility next to the primary Share action. */
  .reset {
    flex: 0 0 auto;
    padding: 7px 16px;
    border: 1px solid var(--accent);
    background: transparent;
    color: var(--accent);
    border-radius: var(--radius-sm);
    font-size: 0.95rem;
  }
  .body {
    margin: 0;
    width: 100%;
    white-space: pre-wrap;
    overflow-wrap: anywhere;
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    font-size: 11px;
    line-height: 1.45;
    color: #d6e6ff;
  }
</style>
