<script lang="ts">
	import Icon from '@iconify/svelte';
	import { getSegmentStyle, getLinePrefix, getSegmentsUpToChar } from './utils';
	import { user } from '$lib/config';
	import TuiButton from './TuiButton.svelte';
	import TuiLink from './TuiLink.svelte';
	import TuiCard from './TuiCard.svelte';
	import TuiProgress from './TuiProgress.svelte';
	import TuiAccordion from './TuiAccordion.svelte';
	import TuiTable from './TuiTable.svelte';
	import TuiTooltip from './TuiTooltip.svelte';
	import TuiCardGrid from './TuiCardGrid.svelte';
	import type { DisplayedLine } from './types';

	export let displayedLines: DisplayedLine[] = [];
	export let currentLineIndex = 0;
	export let isTyping = false;
	export let selectedIndex = -1;
	export let ref: HTMLDivElement | undefined;
	export let onButtonClick: (idx: number) => void;
	export let onHoverButton: (idx: number) => void;
	export let onLinkClick: (idx: number) => void;
	export let terminalSettings: any;

	// Group displayed lines into regular items and inline groups
	type GroupedItem = 
		| { type: 'single'; index: number; displayed: DisplayedLine }
		| { type: 'inline-group'; indices: number[]; items: DisplayedLine[] };

	$: groupedLines = (() => {
		const result: GroupedItem[] = [];
		let i = 0;
		
		while (i < displayedLines.length) {
			const displayed = displayedLines[i];
			const line = displayed.parsed.line;
			
			if (line.inline) {
				// Start an inline group
				const group: GroupedItem = { type: 'inline-group', indices: [], items: [] };
				while (i < displayedLines.length && displayedLines[i].parsed.line.inline) {
					group.indices.push(i);
					group.items.push(displayedLines[i]);
					i++;
				}
				result.push(group);
			} else {
				result.push({ type: 'single', index: i, displayed });
				i++;
			}
		}
		
		return result;
	})();
</script>

<div class="tui-body" bind:this={ref}>
	{#each groupedLines as group}
		{#if group.type === 'inline-group'}
			<!-- Inline group container -->
			<div class="tui-inline-group">
				{#each group.items as displayed, j}
					{@const line = displayed.parsed.line}
					{@const idx = group.indices[j]}
					{@const visibleSegments = getSegmentsUpToChar(displayed.parsed.segments, displayed.charIndex)}
					{#if line.type === 'button'}
						<TuiButton {line} index={idx} selected={selectedIndex === idx} onClick={onButtonClick} onHover={onHoverButton} inline={true} />
					{:else if line.type === 'link'}
						<TuiLink {line} onClick={() => onLinkClick(idx)} />
					{:else if line.type === 'tooltip'}
						<TuiTooltip {line} />
					{:else if line.type === 'progress'}
						<TuiProgress {line} inline={true} />
					{:else}
						<span class="inline-content {line.type}">
							{getLinePrefix(line.type)}{#each visibleSegments as segment}{#if segment.icon}<Icon icon={segment.icon} width="14" class="inline-icon" />{:else if getSegmentStyle(segment)}<span style={getSegmentStyle(segment)}>{segment.text}</span>{:else}{segment.text}{/if}{/each}
						</span>
					{/if}
				{/each}
			</div>
		{:else if group.type === 'single'}
			{@const i = group.index}
			{@const displayed = group.displayed}
			{@const line = displayed.parsed.line}
			{@const visibleSegments = getSegmentsUpToChar(displayed.parsed.segments, displayed.charIndex)}
			{@const complete = displayed.complete}
			{@const showImage = displayed.showImage}
			{#if line.type === 'divider'}
				<div class="tui-divider" id={line.id}>
					<span class="divider-line"></span>
					{#if line.content}
						<span class="divider-text">{line.content}</span>
					{/if}
					<span class="divider-line"></span>
				</div>
			{:else if line.type === 'button'}
				<TuiButton {line} index={i} selected={selectedIndex === i} onClick={onButtonClick} onHover={onHoverButton} />
			{:else if line.type === 'link'}
				<div class="tui-line link">
					<TuiLink {line} onClick={() => onLinkClick(i)} />
				</div>
			{:else if line.type === 'card'}
				<TuiCard {line} />
			{:else if line.type === 'cardgrid'}
				<TuiCardGrid {line} />
			{:else if line.type === 'progress'}
				<TuiProgress {line} />
			{:else if line.type === 'accordion'}
				<TuiAccordion {line} />
			{:else if line.type === 'table'}
				<TuiTable {line} />
			{:else if line.type === 'tooltip'}
				<div class="tui-line">
					<TuiTooltip {line} />
				</div>
			{:else}
				<div class="tui-line {line.type}" class:complete id={line.id}>
					{#if line.type === 'command' || line.type === 'prompt'}
						<span class="prompt">
							<span class="user">{user.username}</span><span class="at">@</span><span class="host">{user.hostname}</span>
							<span class="separator">:</span><span class="path">~</span><span class="symbol">$</span>
						</span>
					{/if}

					{#if line.type === 'image' && showImage}
						<div class="tui-image">
							<img src={line.image} alt={line.imageAlt || 'Image'} style="max-width: {line.imageWidth || 300}px" />
							{#if line.content}
								<span class="image-caption">{line.content}</span>
							{/if}
						</div>
					{:else if line.type === 'header'}
						<span class="content header-text">
							<Icon icon="mdi:pound" width="14" class="header-icon" />
							{#each visibleSegments as segment}
								{#if segment.icon}
									<Icon icon={segment.icon} width="16" class="inline-icon" />
								{:else if getSegmentStyle(segment)}
									<span style={getSegmentStyle(segment)}>{segment.text}</span>
								{:else}
									{segment.text}
								{/if}
							{/each}
						</span>
					{:else if line.type !== 'blank'}
						<span class="content">
							{getLinePrefix(line.type)}{#each visibleSegments as segment}{#if segment.icon}<Icon icon={segment.icon} width="14" class="inline-icon" />{:else if getSegmentStyle(segment)}<span style={getSegmentStyle(segment)}>{segment.text}</span>{:else}{segment.text}{/if}{/each}
						</span>
					{/if}

					{#if terminalSettings.showCursor && i === currentLineIndex && !complete && isTyping && line.type !== 'image' && line.type !== 'blank'}
						<span class="cursor"></span>
					{/if}
				</div>
			{/if}
		{/if}
	{/each}

	{#if terminalSettings.showCursor && !isTyping && displayedLines.length > 0}
		<div class="tui-line prompt">
			<span class="prompt">
				<span class="user">{user.username}</span><span class="at">@</span><span class="host">{user.hostname}</span>
				<span class="separator">:</span><span class="path">~</span><span class="symbol">$</span>
			</span>
			<span class="cursor"></span>
		</div>
	{/if}
</div>

<style>
	.tui-body {
		flex: 1;
		padding: 1rem 1.25rem 2rem 1.25rem;
		overflow-y: auto;
		overflow-x: hidden;
		font-size: 0.9rem;
		line-height: 1.7;
		min-height: 0;
	}

	/* Inline group wrapper - groups consecutive inline elements */
	.tui-inline-group {
		display: flex;
		flex-wrap: wrap;
		gap: 0.5rem;
		margin-bottom: 0.2rem;
		animation: lineSlideIn 0.15s ease-out;
	}

	.inline-content {
		display: inline;
		white-space: pre-wrap;
	}

	.inline-content.output {
		color: var(--terminal-muted);
	}

	.inline-content.info {
		color: var(--terminal-primary);
	}

	.inline-content.success {
		color: #a6e3a1;
	}

	.inline-content.error {
		color: #f38ba8;
	}

	.inline-content.warning {
		color: #f9e2af;
	}

	/* Lines */
	.tui-line {
		display: flex;
		align-items: flex-start;
		flex-wrap: wrap;
		margin-bottom: 0.2rem;
		animation: lineSlideIn 0.15s ease-out;
		min-height: 1.7em;
	}

	.tui-line.blank {
		min-height: 0.5em;
	}

	@keyframes lineSlideIn {
		from {
			opacity: 0;
			transform: translateX(-5px);
		}
		to {
			opacity: 1;
			transform: translateX(0);
		}
	}

	/* Prompt styling */
	.prompt {
		display: inline-flex;
		margin-right: 0.5rem;
		flex-shrink: 0;
	}

	.prompt .user {
		color: var(--terminal-user);
	}

	.prompt .at {
		color: var(--terminal-muted);
	}

	.prompt .host {
		color: var(--terminal-accent);
	}

	.prompt .separator {
		color: var(--terminal-muted);
	}

	.prompt .path {
		color: var(--terminal-path);
	}

	.prompt .symbol {
		color: var(--terminal-muted);
		margin-left: 0.25rem;
	}

	/* Content */
	.content {
		color: var(--terminal-text);
		word-break: break-word;
		white-space: pre-wrap;
	}

	.tui-line.output .content {
		color: var(--terminal-muted);
	}

	.tui-line.error .content {
		color: #f38ba8;
	}

	.tui-line.success .content {
		color: #a6e3a1;
	}

	.tui-line.info .content {
		color: var(--terminal-primary);
	}

	.tui-line.warning .content {
		color: #f9e2af;
	}

	.header-text {
		color: var(--terminal-accent);
		font-weight: 600;
		font-size: 1rem;
		display: flex;
		align-items: center;
		gap: 0.5rem;
	}

	:global(.header-icon) {
		opacity: 0.7;
	}

	:global(.inline-icon) {
		display: inline-block;
		vertical-align: middle;
		margin: 0 0.15em;
	}

	/* Divider */
	.tui-divider {
		display: flex;
		align-items: center;
		gap: 1rem;
		margin: 0.75rem 0;
	}

	.divider-line {
		flex: 1;
		height: 1px;
		background: linear-gradient(
			to right,
			transparent,
			var(--terminal-border),
			transparent
		);
	}

	.divider-text {
		color: var(--terminal-muted);
		font-size: 0.75rem;
		text-transform: uppercase;
		letter-spacing: 0.1em;
	}

	/* Images */
	.tui-image {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
		padding: 0.5rem 0;
	}

	.tui-image img {
		border-radius: 6px;
		border: 1px solid var(--terminal-border);
		background: var(--terminal-bg-light);
		object-fit: contain;
	}

	.image-caption {
		color: var(--terminal-muted);
		font-size: 0.8rem;
		font-style: italic;
	}

	/* Cursor */
	.cursor {
		display: inline-block;
		width: 8px;
		height: 1.2em;
		background: var(--terminal-primary);
		animation: cursorBlink 1s step-end infinite;
		margin-left: 2px;
		vertical-align: middle;
	}

	@keyframes cursorBlink {
		0%, 100% { opacity: 1; }
		50% { opacity: 0; }
	}

	/* Scrollbar */
	.tui-body::-webkit-scrollbar {
		width: 6px;
	}

	.tui-body::-webkit-scrollbar-track {
		background: transparent;
	}

	.tui-body::-webkit-scrollbar-thumb {
		background: var(--terminal-border);
		border-radius: 3px;
	}

	.tui-body::-webkit-scrollbar-thumb:hover {
		background: var(--terminal-muted);
	}
</style>
