package web

import (
	"strings"

	"gitea.d-ma.be/mathias/tapir/internal/adapters/store"
)

// Layout is the shared HTML shell. HTMX drives the progressive interactions
// (filters, action toggles); every interaction also degrades to a plain form
// POST/GET when JS is absent (ui-spec.md §4).
templ Layout(title string) {
	<!DOCTYPE html>
	<html lang="en">
		<head>
			<meta charset="utf-8"/>
			<meta name="viewport" content="width=device-width, initial-scale=1"/>
			<title>{ title }</title>
			<script src="/static/htmx.min.js" defer></script>
			@templ.Raw(styleTag)
		</head>
		<body>
			<header><a href="/" class="brand">Tapir</a></header>
			<main>
				{ children... }
			</main>
		</body>
	</html>
}

// ListPage is the full summary list with the filter form. HTMX swaps only the
// #summary-list region; a non-HTMX request renders the whole page.
templ ListPage(rows []store.SummaryRow, f Filter) {
	@Layout("Tapir — Summaries") {
		@filterForm(f)
		<div id="summary-list">
			@summaryList(rows)
		</div>
	}
}

templ filterForm(f Filter) {
	<form
		class="filters"
		method="get"
		action="/"
		hx-get="/"
		hx-target="#summary-list"
		hx-swap="innerHTML"
		hx-indicator="#filter-indicator"
	>
		<label>Channel <input type="text" name="channel" value={ f.Channel } placeholder="any"/></label>
		<label>From <input type="date" name="from" value={ f.From }/></label>
		<label>To <input type="date" name="to" value={ f.To }/></label>
		<button type="submit" class="btn">Filter</button>
		<span id="filter-indicator" class="htmx-indicator">filtering…</span>
	</form>
}

// summaryList is the swappable list fragment: one card per summary (title link,
// channel · date meta, provider chip, fallback badge, action state). Cards
// reflow to a single column on mobile; an empty list shows a friendly first-run
// state instead of a blank table.
templ summaryList(rows []store.SummaryRow) {
	if len(rows) == 0 {
		<div class="empty">
			<strong>No summaries yet</strong>
			<span>Summaries appear here as your subscriptions are processed — run <code>tapir run</code> to fetch and summarize new videos.</span>
		</div>
	} else {
		<ul class="cards">
			for _, r := range rows {
				<li class="card">
					<div class="card-title"><a href={ videoURL(r.VideoID) }>{ displayTitle(r) }</a></div>
					if cardMeta(r) != "" {
						<div class="card-meta">{ cardMeta(r) }</div>
					}
					if p := previewText(r.Summary, 160); p != "" {
						<div class="card-preview">{ p }</div>
					}
					<div class="card-foot">
						if r.AIProvider != "" {
							<span class="chip">{ r.AIProvider }</span>
						}
						if r.FallbackUsed {
							<span class="badge" title="summarized with the fallback model" aria-label="summarized with the fallback model">fallback</span>
						}
						if len(r.Actions) > 0 {
							<span class="card-state">{ strings.Join(r.Actions, ", ") }</span>
						}
					</div>
				</li>
			}
		</ul>
	}
}

// DetailPage is the full summary view: text, highlights, takeaways, metadata,
// and the action button group.
templ DetailPage(r store.SummaryRow) {
	@Layout("Tapir — " + displayTitle(r)) {
		<article class="detail">
			<h1>{ displayTitle(r) }</h1>
			<p class="meta">
				if detailMeta(r) != "" {
					<span>{ detailMeta(r) }</span>
				}
				if r.FallbackUsed {
					<span class="badge" title="summarized with the fallback model" aria-label="summarized with the fallback model">fallback</span>
				}
			</p>
			if r.URL != "" {
				<p class="source"><a href={ externalURL(r.URL) } rel="noopener noreferrer">watch on source ↗</a></p>
			}
			@ActionButtons(r.VideoID, actionSet(r.Actions))
			<section>
				<h2>Summary</h2>
				<p class="body">{ r.Summary }</p>
			</section>
			if len(r.Highlights) > 0 {
				<section>
					<h2>Highlights</h2>
					<ul>
						for _, h := range r.Highlights {
							<li>{ h }</li>
						}
					</ul>
				</section>
			}
			if len(r.Takeaways) > 0 {
				<section>
					<h2>Takeaways</h2>
					<ul>
						for _, t := range r.Takeaways {
							<li>{ t }</li>
						}
					</ul>
				</section>
			}
		</article>
	}
}

// ActionButtons is the toggle group fragment returned by POST /v/{id}/action.
// Each button submits its verb; HTMX swaps this element in place (outerHTML),
// and without JS the form POSTs and the handler redirects back to the detail
// page. active marks the verbs currently set for (user, video).
templ ActionButtons(videoID string, active map[string]bool) {
	<form
		id="action-buttons"
		class="actions"
		method="post"
		action={ actionURL(videoID) }
		hx-post={ string(actionURL(videoID)) }
		hx-target="#action-buttons"
		hx-swap="outerHTML"
	>
		for _, v := range actionVerbs {
			<button
				type="submit"
				name="action"
				value={ v }
				class={ "action", templ.KV("active", active[v]) }
				aria-pressed={ ariaPressed(active[v]) }
			>
				if active[v] {
					{ "✓ " + actionLabel(v) }
				} else {
					{ actionLabel(v) }
				}
			</button>
		}
	</form>
}
