<script>
  import { onMount } from 'svelte';
  import { push } from 'svelte-spa-router';
  import { auth } from '../lib/stores/auth.js';
  import { navContext } from '../lib/stores/navContext.js';
  import { createDeck } from '../lib/api/decks.js';
  import { DEFAULT_DECK_CONFIG } from '../lib/deckConfig.js';
  import QuestionEditor from '../lib/QuestionEditor.svelte';

  onMount(() => navContext.set('my-decks'));

  let title = '';
  let description = '';
  let config = { ...DEFAULT_DECK_CONFIG };
  let questions = [
    { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] },
  ];
  let saving = false;
  let error = null;
  let jsonInput = '';
  let jsonError = null;
  $: userId = $auth.user?.id;
  $: view = $auth.loading ? 'loading' : (userId ? 'form' : 'signin');

  const CONFIG_KEYS = Object.keys(DEFAULT_DECK_CONFIG);

  function loadFromJson() {
    jsonError = null;
    let parsed;
    try {
      parsed = JSON.parse(jsonInput);
    } catch (e) {
      jsonError = 'Invalid JSON: ' + (e?.message ?? 'parse error');
      return;
    }
    if (!parsed || typeof parsed !== 'object') {
      jsonError = 'JSON must be an object';
      return;
    }
    const t = (parsed.title ?? '').toString().trim();
    if (!t) {
      jsonError = 'JSON must include a "title"';
      return;
    }
    const rawQuestions = Array.isArray(parsed.questions) ? parsed.questions : [];
    if (rawQuestions.length === 0) {
      jsonError = 'JSON must include a non-empty "questions" array';
      return;
    }
    title = t;
    description = (parsed.description ?? '').toString().trim();
    const rawConfig = parsed.config && typeof parsed.config === 'object' ? parsed.config : {};
    config = CONFIG_KEYS.reduce((acc, key) => {
      if (Object.prototype.hasOwnProperty.call(rawConfig, key)) acc[key] = rawConfig[key];
      else acc[key] = DEFAULT_DECK_CONFIG[key];
      return acc;
    }, { ...DEFAULT_DECK_CONFIG });
    questions = rawQuestions.map((q) => {
      const answers = Array.isArray(q.answers) ? q.answers.map((a) => String(a).trim()) : [''];
      const indices = Array.isArray(q.correctAnswerIndices)
        ? q.correctAnswerIndices
        : Array.isArray(q.correct_answer_indices)
          ? q.correct_answer_indices
          : [0];
      return {
        prompt: (q.prompt ?? '').toString().trim(),
        explanation: (q.explanation ?? '').toString().trim(),
        answers: answers.length ? answers : [''],
        correct_answer_indices: indices.filter((i) => i >= 0 && i < (answers.length || 1)).length ? indices : [0],
      };
    });
  }

  function addQuestion() {
    questions = [...questions, { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }];
  }

  function removeQuestion(i) {
    questions = questions.filter((_, idx) => idx !== i);
    if (questions.length === 0) {
      questions = [{ prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }];
    }
  }

  function normalizeQuestion(q) {
    const answers = (q.answers || []).map((a) => String(a).trim()).filter(Boolean);
    if (answers.length === 0) return null;
    const indices = (q.correct_answer_indices ?? [0]).filter((i) => i >= 0 && i < answers.length);
    return {
      prompt: (q.prompt ?? '').trim(),
      explanation: (q.explanation ?? '').trim() || null,
      answers,
      correct_answer_indices: indices.length ? indices : [0],
    };
  }

  async function save() {
    const t = title.trim();
    if (!t) {
      error = 'Title is required';
      return;
    }
    if (!userId) {
      error = 'You must be signed in to create a deck';
      return;
    }
    const normalized = questions.map(normalizeQuestion).filter(Boolean);
    if (normalized.length === 0) {
      error = 'Add at least one question with at least one answer';
      return;
    }
    saving = true;
    error = null;
    try {
      const id = await createDeck(userId, {
        title: t,
        description: description.trim(),
        config,
        questions: normalized,
      });
      push('/');
    } catch (e) {
      error = e?.message ?? 'Failed to create deck';
    } finally {
      saving = false;
    }
  }

  function cancel() {
    push('/');
  }
</script>

<div class="page">
  <header class="page-header">
    <h1>Create deck</h1>
    <div class="header-actions">
      <button type="button" class="btn btn-secondary" onclick={cancel} disabled={saving}>Cancel</button>
      <button type="button" class="btn btn-primary" onclick={save} disabled={saving}>
        {saving ? 'Saving…' : 'Save deck'}
      </button>
    </div>
  </header>

  {#if view === 'loading'}
    <p class="auth-required">Loading…</p>
  {:else if view === 'signin'}
    <p class="auth-required">Sign in to create a deck.</p>
  {:else}
    <form class="deck-form" onsubmit={(e) => { e.preventDefault(); save(); }}>
        <details class="import-json">
          <summary>Import from JSON</summary>
          <div class="form-group">
            <label for="json-input">Paste deck JSON</label>
            <textarea
              id="json-input"
              class="input textarea json-textarea"
              bind:value={jsonInput}
              placeholder="Paste deck JSON (title, description, config, questions)"
              rows="8"
           ></textarea>
            <button type="button" class="btn btn-secondary" onclick={loadFromJson}>Load from JSON</button>
            {#if jsonError}
              <p class="error">{jsonError}</p>
            {/if}
          </div>
        </details>

        <div class="form-group">
          <label for="title">Title</label>
          <input id="title" type="text" class="input" bind:value={title} placeholder="Deck title" required />
        </div>
        <div class="form-group">
          <label for="description">Description</label>
          <textarea id="description" class="input textarea" bind:value={description} placeholder="Optional description" rows="2"></textarea>
        </div>

        <h2 class="section-title">Questions</h2>
        {#each questions as question, i}
          <QuestionEditor bind:question index={i} onRemove={() => removeQuestion(i)} />
        {/each}
        <button type="button" class="btn btn-add-q" onclick={addQuestion}>+ Add question</button>

        {#if error}
          <p class="error">{error}</p>
        {/if}
    </form>
  {/if}
</div>

<style>
  .page {
    padding: 1.5rem;
    max-width: 700px;
    margin: 0 auto;
  }

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.5rem;
  }

  .page-header h1 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--text-primary, #f0f0f0);
  }

  .header-actions {
    display: flex;
    gap: 0.5rem;
  }

  .auth-required {
    margin: 0;
    color: var(--text-muted, #a0a0a0);
  }

  .deck-form {
    display: flex;
    flex-direction: column;
  }

  .import-json {
    margin-bottom: 1rem;
    padding: 0.75rem;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
  }

  .import-json summary {
    cursor: pointer;
    font-weight: 500;
    color: var(--text-muted, #a0a0a0);
  }

  .import-json summary:hover {
    color: var(--text-primary, #f0f0f0);
  }

  .json-textarea {
    font-family: ui-monospace, monospace;
    font-size: 0.85rem;
    margin-bottom: 0.5rem;
  }

  .form-group {
    margin-bottom: 1rem;
  }

  .form-group label {
    display: block;
    font-size: 0.9rem;
    font-weight: 500;
    color: var(--text-muted, #a0a0a0);
    margin-bottom: 0.35rem;
  }

  .input {
    width: 100%;
    padding: 0.6rem 0.75rem;
    font-size: 0.95rem;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
    color: var(--text-primary, #f0f0f0);
  }

  .textarea {
    resize: vertical;
    min-height: 2.5rem;
  }

  .section-title {
    margin: 1.5rem 0 0.75rem 0;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-primary, #f0f0f0);
  }

  .btn-add-q {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    border: 1px dashed var(--border, #333);
    border-radius: 6px;
    background: transparent;
    color: var(--text-muted, #a0a0a0);
    cursor: pointer;
    margin-bottom: 1rem;
  }

  .btn-add-q:hover {
    color: var(--text-primary, #f0f0f0);
    border-color: var(--border-hover, #444);
  }

  .error {
    margin: 0 0 1rem 0;
    font-size: 0.9rem;
    color: #ef4444;
  }

  .btn {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    font-weight: 500;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
    color: var(--text-primary, #f0f0f0);
    cursor: pointer;
  }

  .btn:hover:not(:disabled) {
    background: var(--hover-bg, #2a2a2a);
  }

  .btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .btn-primary {
    background: var(--accent, #3b82f6);
    border-color: var(--accent, #3b82f6);
  }

  .btn-primary:hover:not(:disabled) {
    background: #2563eb;
  }

  .btn-secondary {
    background: transparent;
  }
</style>
