<!-- @format -->
<script lang="ts">
  export let openDocumentId = "";
  export let openDocumentName = "";
  export let openDocumentContent = "";
  export let onDocumentContentChange: (content: string) => void = () => {};

  type SimpleListItem = {
    id: number;
    text: string;
  };

  let items: SimpleListItem[] = [];
  let nextItemId = 1;
  let lastDocumentId = "";
  let newItemText = "";
  let editingItemId: number | null = null;
  let editingItemText = "";

  function parseListItems(content: string): SimpleListItem[] {
    const lines = (content ?? "").split(/\r?\n/);
    const parsed: SimpleListItem[] = [];

    for (const line of lines) {
      const bullet = line.match(/^\s*(?:[-*+]|\d+\.)\s+(.+)$/);
      if (bullet) {
        parsed.push({ id: parsed.length + 1, text: bullet[1].trim() });
        continue;
      }

      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      parsed.push({ id: parsed.length + 1, text: trimmed });
    }

    return parsed;
  }

  function serializeList(title: string, listItems: SimpleListItem[]): string {
    const heading = (title ?? "").trim() || "Untitled List";
    if (!listItems.length) {
      return `# ${heading}\n\n`;
    }

    const body = listItems
      .map((item) => item.text.trim())
      .filter(Boolean)
      .map((text) => `- ${text}`)
      .join("\n");

    return `# ${heading}\n\n${body}`;
  }

  function persist() {
    onDocumentContentChange(serializeList(openDocumentName, items));
  }

  function resetForDocument() {
    items = parseListItems(openDocumentContent);
    nextItemId = (items[items.length - 1]?.id ?? 0) + 1;
    newItemText = "";
    editingItemId = null;
    editingItemText = "";
  }

  function addItem() {
    const text = newItemText.trim();
    if (!text) return;
    items = [{ id: nextItemId, text }, ...items];
    nextItemId += 1;
    newItemText = "";
    persist();
  }

  function startEditItem(id: number) {
    const existing = items.find((item) => item.id === id);
    if (!existing) return;
    editingItemId = id;
    editingItemText = existing.text;
  }

  function saveEditItem() {
    if (editingItemId === null) return;
    const text = editingItemText.trim();
    if (!text) return;
    const id = editingItemId;
    items = items.map((item) => (item.id === id ? { ...item, text } : item));
    editingItemId = null;
    editingItemText = "";
    persist();
  }

  function cancelEditItem() {
    editingItemId = null;
    editingItemText = "";
  }

  function removeItem(id: number) {
    if (editingItemId === id) {
      cancelEditItem();
    }
    items = items.filter((item) => item.id !== id);
    persist();
  }

  $: if (openDocumentId !== lastDocumentId) {
    resetForDocument();
    lastDocumentId = openDocumentId;
  }
</script>

<section class="list-surface">
  <div class="list-card">
    <form class="list-create" on:submit|preventDefault={addItem}>
      <input
        type="text"
        placeholder="Add a list item"
        bind:value={newItemText}
        aria-label="Add list item"
      />
      <button type="submit" class="list-add-btn">Add</button>
    </form>

    <ul class="list-items">
      {#each items as item}
        <li class="list-item">
          {#if editingItemId === item.id}
            <input
              type="text"
              class="list-edit-input"
              bind:value={editingItemText}
              on:keydown={(event) => {
                if (event.key === "Enter") saveEditItem();
                if (event.key === "Escape") cancelEditItem();
              }}
            />
            <div class="list-actions">
              <button
                type="button"
                class="list-btn save"
                on:click={saveEditItem}>Save</button
              >
              <button
                type="button"
                class="list-btn ghost"
                on:click={cancelEditItem}>Cancel</button
              >
            </div>
          {:else}
            <span class="list-text">{item.text}</span>
            <div class="list-actions">
              <button
                type="button"
                class="list-btn ghost"
                on:click={() => startEditItem(item.id)}>Edit</button
              >
              <button
                type="button"
                class="list-btn danger"
                on:click={() => removeItem(item.id)}>Remove</button
              >
            </div>
          {/if}
        </li>
      {/each}
    </ul>
  </div>
</section>

<style>
  .list-surface {
    min-height: 0;
    flex: 1;
    overflow: auto;
    padding: 0 14px 14px;
  }

  .list-card {
    width: min(100%, 920px);
    margin: 0 auto;
    border: none;
    border-radius: 0;
    background: transparent;
    padding: 28px 36px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    max-height: 100%;
    overflow: visible;
  }

  .list-create {
    display: flex;
    gap: 8px;
  }

  .list-create input,
  .list-edit-input {
    width: 100%;
    border: 1px solid var(--border-soft);
    border-radius: 8px;
    background: color-mix(in srgb, var(--surface-1) 88%, var(--bg-editor) 12%);
    color: var(--text-primary);
    padding: 10px 11px;
    font-size: 0.88rem;
  }

  .list-add-btn {
    border-radius: 8px;
    border: 1px solid var(--border-strong);
    background: color-mix(in srgb, var(--surface-2) 84%, var(--bg-hover) 16%);
    color: var(--text-primary);
    padding: 9px 14px;
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
  }

  .list-add-btn:hover {
    background: var(--bg-hover);
  }

  .list-items {
    list-style: none;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .list-item {
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto;
    align-items: center;
    gap: 10px;
    border: 1px solid var(--border-soft);
    border-radius: 8px;
    padding: 10px 12px;
    background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
  }

  .list-text {
    font-size: 0.9rem;
    color: var(--text-primary);
    line-height: 1.45;
    word-break: break-word;
  }

  .list-actions {
    display: flex;
    gap: 6px;
  }

  .list-btn {
    border-radius: 7px;
    border: 1px solid var(--border-soft);
    background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
    color: var(--text-muted);
    padding: 6px 10px;
    font-size: 0.78rem;
    cursor: pointer;
  }

  .list-btn.save {
    border-color: var(--border-strong);
    background: color-mix(in srgb, var(--surface-2) 84%, var(--bg-hover) 16%);
    color: var(--text-primary);
  }

  .list-btn.danger:hover,
  .list-btn.ghost:hover,
  .list-btn.save:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
  }

  @media (max-width: 980px) {
    .list-surface {
      padding: 4px 8px 10px;
    }

    .list-card {
      width: 100%;
      padding: 18px 16px;
    }

    .list-create {
      flex-wrap: wrap;
    }

    .list-add-btn {
      width: 100%;
    }

    .list-item {
      grid-template-columns: minmax(0, 1fr);
      row-gap: 8px;
    }

    .list-actions {
      justify-content: flex-end;
    }
  }
</style>
