<script lang="ts">
  import { onMount } from 'svelte';
  import Screen from '../components/Screen.svelte';
  import { t } from '../lib/i18n/index.svelte';
  import { app, handleError } from '../lib/app.svelte';
  import { gateway } from '../lib/gateway';
  import { connection } from '../lib/connection.svelte';
  import { clientChannel } from '../lib/channel';
  import { attachmentError, linkify, MAX_BODY } from '../lib/feedback';
  import { onExternalLinkClick } from '../lib/links';
  import type { FeedbackState } from '../lib/model';

  // The feedback screen: a message (+ optional single attachment) the player sends to
  // the operators, plus the operator's last reply. The form is disabled while a
  // previous message is under review or the account is banned from feedback.
  let view = $state<FeedbackState | null>(null);
  let body = $state('');
  let file = $state<File | null>(null);
  let fileError = $state(false);
  let sending = $state(false);
  let sent = $state(false);
  let fileInput: HTMLInputElement;

  const enabled = $derived(view?.canSend ?? false);
  const reason = $derived(view?.blockedReason ?? '');
  const canSend = $derived(enabled && body.trim().length > 0 && !sending && connection.online);
  // The operator reply, split into text + http(s) links for rendering.
  const replySegments = $derived(view?.reply ? linkify(view.reply.body) : []);

  onMount(() => void load());

  async function load() {
    try {
      view = await gateway.feedbackGet();
      // Fetching the screen delivers (reads) any pending reply: clear the badge.
      app.feedbackReplyUnread = false;
    } catch (e) {
      handleError(e);
    }
  }

  function pickFile(e: Event) {
    const input = e.currentTarget as HTMLInputElement;
    const f = input.files?.[0] ?? null;
    if (!f) return;
    if (attachmentError(f.name, f.size) !== '') {
      fileError = true;
      file = null;
      input.value = '';
      return;
    }
    fileError = false;
    file = f;
  }

  function removeFile() {
    file = null;
    fileError = false;
    if (fileInput) fileInput.value = '';
  }

  async function send() {
    if (!canSend) return;
    sending = true;
    try {
      let bytes: Uint8Array | null = null;
      let name = '';
      if (file) {
        bytes = new Uint8Array(await file.arrayBuffer());
        name = file.name;
      }
      await gateway.feedbackSubmit(body.trim(), bytes, name, clientChannel());
      body = '';
      removeFile();
      sent = true;
      // The message is now under review: block resending until the operator handles it.
      // A new message has no reply yet, so the previous operator reply stops showing.
      view = { canSend: false, blockedReason: 'pending', reply: null };
    } catch (e) {
      handleError(e);
    } finally {
      sending = false;
    }
  }
</script>

<Screen title={t('feedback.title')} back="/about">
  <div class="page">
    <textarea
      bind:value={body}
      maxlength={MAX_BODY}
      rows="6"
      placeholder={t('feedback.placeholder')}
      disabled={!enabled}
    ></textarea>

    <div class="row">
      <input bind:this={fileInput} type="file" class="hidden" onchange={pickFile} />
      {#if file}
        <span class="fname">{file.name}</span>
        <button type="button" class="neutral" onclick={removeFile}>{t('feedback.removeFile')}</button>
      {:else}
        <button
          type="button"
          class="neutral attach"
          aria-label={t('feedback.attach')}
          title={t('feedback.attach')}
          onclick={() => fileInput.click()}
          disabled={!enabled}>📎</button>
      {/if}
      <button type="button" class="cta" onclick={send} disabled={!canSend}>{t('feedback.send')}</button>
    </div>

    {#if fileError}<p class="err">{t('feedback.fileRejected')}</p>{/if}

    {#if sent}
      <p class="ok">{t('feedback.sent')}</p>
    {:else if reason === 'pending'}
      <p class="muted">{t('feedback.waiting')}</p>
    {:else if reason === 'banned'}
      <p class="muted">{t('feedback.banned')}</p>
    {/if}

    {#if view?.reply}
      <section class="reply">
        <h2>{t('feedback.replyTitle')}</h2>
        <p class="replybody">{#each replySegments as seg, i (i)}{#if seg.href}<a href={seg.href} target="_blank" rel="noopener noreferrer" onclick={onExternalLinkClick}>{seg.text}</a>{:else}{seg.text}{/if}{/each}</p>
      </section>
    {/if}
  </div>
</Screen>

<style>
  .page {
    padding: var(--pad);
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  textarea {
    width: 100%;
    box-sizing: border-box;
    resize: vertical;
    min-height: 7rem;
    font: inherit;
  }
  .row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }
  .fname {
    flex: 1 1 auto;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: var(--text-muted);
    font-size: 0.9rem;
  }
  .cta {
    margin-left: auto;
    padding: 12px 18px;
    border: 1px solid var(--accent);
    background: var(--accent);
    color: var(--accent-text);
    border-radius: var(--radius);
    font-weight: 600;
  }
  .neutral {
    padding: 12px 14px;
    border: 1px solid var(--border);
    background: var(--surface-2);
    color: var(--text);
    border-radius: var(--radius);
    font-weight: 600;
  }
  .cta:disabled,
  .neutral:disabled {
    opacity: 0.5;
  }
  .attach {
    font-size: 1.15rem;
    line-height: 1;
  }
  .hidden {
    display: none;
  }
  .err {
    color: var(--danger);
    margin: 0;
  }
  .ok {
    color: var(--accent);
    margin: 0;
  }
  .muted {
    color: var(--text-muted);
    margin: 0;
  }
  .reply {
    display: flex;
    flex-direction: column;
    gap: 6px;
    border-top: 1px solid var(--surface-2);
    padding-top: 10px;
  }
  .reply h2 {
    font-size: 1.05rem;
    margin: 0;
    color: var(--text-muted);
  }
  .replybody {
    margin: 0;
    white-space: pre-wrap;
    word-break: break-word;
  }
  .replybody a {
    color: var(--accent);
  }
</style>
