component TreeView {
  outputs {
    select(payload: { item: object; value: string; sourceEvent?: Event })
    toggle(payload: { item: object; value: string; expanded: boolean; sourceEvent?: Event })
    expand(payload: { item: object; value: string; sourceEvent?: Event })
    collapse(payload: { item: object; value: string; sourceEvent?: Event })
  }

  props {
    title: string = "Tree View"
    description: string = ""
    items: unknown[] = []
    valueKey: string = "value"
    labelKey: string = "label"
    defaultExpanded: unknown[] = []
    selected: string = ""
    size: string = "default"
    color: string = "primary"
    class: string = ""
  }

  state expandedValues = defaultExpanded
  state selectedValue = selected

  functions {
    shared function nodeValue(item, index, parent) { return String(item[valueKey] || item.id || parent + index) }
    shared function isExpanded(value) { return expandedValues.includes(value) }

    client function toggleNode(item, value, sourceEvent, next, expanded) {
      next = expandedValues.slice()
      expanded = !next.includes(value)
      if (expanded) {
        next.push(value)
      } else {
        next = next.filter(function (entry) { return entry !== value })
      }
      expandedValues = next
      output.toggle({ item: item, value: value, expanded: expanded, sourceEvent: sourceEvent })
      if (expanded) {
        output.expand({ item: item, value: value, sourceEvent: sourceEvent })
      } else {
        output.collapse({ item: item, value: value, sourceEvent: sourceEvent })
      }
    }

    client function selectNode(item, value, sourceEvent) {
      selectedValue = value
      output.select({ item: item, value: value, sourceEvent: sourceEvent })
    }
  }

  view {
    <section {...attrs} data-ui-component="TreeView" class='wrn-tree-view {class}'>
      {#if title}<strong class="wrn-tree-view__title">{title}</strong>{/if}
      {#if description}<p class="wrn-tree-view__description">{description}</p>{/if}
      <div class="wrn-tree-view__tree" role="tree" aria-label='{title}' data-wrn-roving="vertical">
        {#each items as item, index}
          <div class="wrn-tree-view__branch" role="none">
            <div class="wrn-tree-view__row" role="treeitem" aria-level="1" aria-expanded='{item.children && item.children.length ? isExpanded(nodeValue(item, index, "root-")) : ""}' aria-selected='{selectedValue === nodeValue(item, index, "root-") ? "true" : "false"}'>
              {#if item.children && item.children.length}
                <button type="button" class="wrn-tree-view__toggle" aria-label='{isExpanded(nodeValue(item, index, "root-")) ? "Collapse " + item[labelKey] : "Expand " + item[labelKey]}' @click='toggleNode(item, nodeValue(item, index, "root-"), event)'><span class="icon-[lucide--chevron-right]" aria-hidden="true"></span></button>
              {:else}<span class="wrn-tree-view__toggle" aria-hidden="true"></span>{/if}
              <button type="button" class="wrn-tree-view__node" data-wrn-roving-item @click='selectNode(item, nodeValue(item, index, "root-"), event)'>
                {#if item.icon}<span class='{item.icon}' aria-hidden="true"></span>{/if}<span>{item[labelKey]}</span>
              </button>
            </div>
            {#if item.children && item.children.length}
              <div class="wrn-tree-view__group" role="group" data-show='isExpanded(nodeValue(item, index, "root-"))'>
                {#each item.children as child, childIndex}
                  <div class="wrn-tree-view__row" role="treeitem" aria-level="2" aria-selected='{selectedValue === nodeValue(child, childIndex, nodeValue(item, index, "root-") + "-") ? "true" : "false"}'>
                    <span class="wrn-tree-view__toggle" aria-hidden="true"></span>
                    <button type="button" class="wrn-tree-view__node" data-wrn-roving-item @click='selectNode(child, nodeValue(child, childIndex, nodeValue(item, index, "root-") + "-"), event)'>
                      {#if child.icon}<span class='{child.icon}' aria-hidden="true"></span>{/if}<span>{child[labelKey]}</span>
                    </button>
                  </div>
                {/each}
              </div>
            {/if}
          </div>
        {:empty}<p class="wrn-tree-view__empty">No tree items available.</p>{/each}
      </div>
      <slot />
    </section>
  }

  style {
    .wrn-tree-view { display: grid; gap: 0.5rem; color: var(--wrn-color-text); }
    .wrn-tree-view__title { font-size: 0.95rem; }
    .wrn-tree-view__description, .wrn-tree-view__empty { margin: 0; color: var(--wrn-color-muted); font-size: 0.8rem; }
    .wrn-tree-view__tree { display: grid; gap: 0.15rem; padding: 0.4rem; border: 1px solid var(--wrn-color-border); border-radius: var(--wrn-radius); background: var(--wrn-color-surface); }
    .wrn-tree-view__row { display: flex; min-width: 0; align-items: center; gap: 0.2rem; border-radius: var(--wrn-radius-sm); }
    .wrn-tree-view__row[aria-selected="true"] { background: var(--wrn-color-primary-soft); }
    .wrn-tree-view__toggle { display: inline-grid; width: 1.8rem; height: 1.8rem; flex: none; padding: 0; place-items: center; border: 0; border-radius: 0.35rem; color: var(--wrn-color-muted); background: transparent; }
    button.wrn-tree-view__toggle { cursor: pointer; }
    .wrn-tree-view__toggle > span { width: 0.9rem; height: 0.9rem; transition: transform var(--wrn-motion-fast); }
    .wrn-tree-view__row[aria-expanded="true"] > .wrn-tree-view__toggle > span { transform: rotate(90deg); }
    .wrn-tree-view__node { display: flex; min-width: 0; flex: 1; align-items: center; gap: 0.45rem; padding: 0.45rem 0.5rem; border: 0; border-radius: var(--wrn-radius-sm); color: inherit; background: transparent; font: inherit; text-align: left; cursor: pointer; }
    .wrn-tree-view__node:hover, button.wrn-tree-view__toggle:hover { background: var(--wrn-color-surface-2); }
    .wrn-tree-view__node:focus-visible, button.wrn-tree-view__toggle:focus-visible { outline: 2px solid var(--wrn-color-focus); outline-offset: -2px; }
    .wrn-tree-view__node > [class*="icon-"] { width: 1rem; height: 1rem; flex: none; color: var(--wrn-color-primary); }
    .wrn-tree-view__group { display: grid; margin-left: 1.8rem; padding-left: 0.45rem; border-left: 1px solid var(--wrn-color-border); }
  }
}
