/**
 * VS Code Welcome Panel  -  Pioneer Release
 *
 * Three-state onboarding experience per Pioneer Release Mold §3.2:
 *   1. EXTENSION_INSTALLED  -  setup progress (CLI detect, daemon start)
 *   2. SCANNING  -  real-time workspace analysis with early discoveries
 *   3. SCAN_COMPLETE  -  Recovery Risk Profile with insights
 *
 * Architecture fence: thin client only. All data comes from daemon via messages.
 * Privacy line always visible. Auth CTA is soft, never blocking.
 */

import type React from "react";
import { useCallback, useEffect, useReducer } from "react";
import vrekoIcon from "../assets/vreko-icon.png";
import { getVSCodeAPI } from "../vscode-api";

// ── Types ────────────────────────────────────────────────────────

type WelcomePhase = "EXTENSION_INSTALLED" | "SCANNING" | "SCAN_COMPLETE";

interface SetupStep {
	id: string;
	label: string;
	status: "pending" | "active" | "done" | "failed";
}

interface ScanProgress {
	commitHistory: number; // 0-100
	reflogEntries: number; // 0-100
}

interface EarlyDiscovery {
	id: string;
	message: string;
}

interface RiskDimension {
	label: string;
	value: number; // 0-100
}

interface Finding {
	observation: string;
	action: string;
	severity: "info" | "notable" | "warning" | "critical";
}

interface WelcomeState {
	phase: WelcomePhase;
	steps: SetupStep[];
	scanProgress: ScanProgress;
	earlyDiscoveries: EarlyDiscovery[];
	riskDimensions: RiskDimension[];
	findings: Finding[];
	lockedInsightTeaser: string | null;
}

type WelcomeAction =
	| { type: "STEP_UPDATE"; stepId: string; status: SetupStep["status"] }
	| { type: "PHASE_CHANGE"; phase: WelcomePhase }
	| { type: "SCAN_PROGRESS"; commitHistory: number; reflogEntries: number }
	| { type: "EARLY_DISCOVERY"; discovery: EarlyDiscovery }
	| {
			type: "SCAN_RESULTS";
			riskDimensions: RiskDimension[];
			findings: Finding[];
			lockedInsightTeaser: string | null;
	  };

// ── Brand ────────────────────────────────────────────────────────

const BRAND_GREEN = "#4ADE80";

// ── Reducer ──────────────────────────────────────────────────────

function welcomeReducer(state: WelcomeState, action: WelcomeAction): WelcomeState {
	switch (action.type) {
		case "STEP_UPDATE":
			return {
				...state,
				steps: state.steps.map((s) => (s.id === action.stepId ? { ...s, status: action.status } : s)),
			};
		case "PHASE_CHANGE":
			return { ...state, phase: action.phase };
		case "SCAN_PROGRESS":
			return {
				...state,
				scanProgress: {
					commitHistory: action.commitHistory,
					reflogEntries: action.reflogEntries,
				},
			};
		case "EARLY_DISCOVERY":
			return {
				...state,
				earlyDiscoveries: [...state.earlyDiscoveries, action.discovery],
			};
		case "SCAN_RESULTS":
			return {
				...state,
				riskDimensions: action.riskDimensions,
				findings: action.findings,
				lockedInsightTeaser: action.lockedInsightTeaser,
			};
		default:
			return state;
	}
}

const INITIAL_STATE: WelcomeState = {
	phase: "EXTENSION_INSTALLED",
	steps: [
		{ id: "extension", label: "Extension activated", status: "done" },
		{ id: "cli", label: "CLI detected", status: "pending" },
		{ id: "daemon", label: "Starting daemon...", status: "pending" },
	],
	scanProgress: { commitHistory: 0, reflogEntries: 0 },
	earlyDiscoveries: [],
	riskDimensions: [],
	findings: [],
	lockedInsightTeaser: null,
};

// ── Score bar color mapping ──────────────────────────────────────

function scoreColor(value: number): string {
	if (value <= 30) {
		return "#4ADE80"; // green
	}
	if (value <= 60) {
		return "#FACC15"; // yellow
	}
	if (value <= 80) {
		return "#FB923C"; // orange
	}
	return "#EF4444"; // red
}

// ── Components ───────────────────────────────────────────────────

const PrivacyLine: React.FC = () => (
	<div
		style={{
			padding: "8px 16px",
			fontSize: "12px",
			color: "#71717a",
			borderTop: "1px solid #27272a",
			textAlign: "center",
		}}
	>
		No code content read. Metadata only.
	</div>
);

const SetupPhase: React.FC<{ steps: SetupStep[] }> = ({ steps }) => (
	<div style={{ padding: "32px 24px" }}>
		<h2 style={{ fontSize: "16px", color: "#e4e4e7", marginBottom: "24px" }}>Setting up your workspace...</h2>
		<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
			{steps.map((step) => (
				<div key={step.id} style={{ display: "flex", alignItems: "center", gap: "10px" }}>
					<span style={{ width: "18px", textAlign: "center" }}>
						{step.status === "done" && <span style={{ color: BRAND_GREEN }}>&#10003;</span>}
						{step.status === "active" && <span style={{ color: "#FACC15" }}>&#9679;</span>}
						{step.status === "pending" && <span style={{ color: "#52525b" }}>&#9675;</span>}
						{step.status === "failed" && <span style={{ color: "#EF4444" }}>&#10007;</span>}
					</span>
					<span style={{ fontSize: "14px", color: step.status === "pending" ? "#71717a" : "#e4e4e7" }}>
						{step.label}
					</span>
				</div>
			))}
		</div>
	</div>
);

const ProgressBar: React.FC<{ label: string; value: number }> = ({ label, value }) => (
	<div style={{ marginBottom: "12px" }}>
		<div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "4px" }}>
			<span style={{ color: "#a1a1aa" }}>{label}</span>
			<span style={{ color: "#a1a1aa" }}>{value}%</span>
		</div>
		<div style={{ width: "100%", height: "6px", background: "#27272a", borderRadius: "3px" }}>
			<div
				style={{
					width: `${value}%`,
					height: "6px",
					background: BRAND_GREEN,
					borderRadius: "3px",
					transition: "width 300ms ease",
				}}
			/>
		</div>
	</div>
);

const ScanningPhase: React.FC<{
	progress: ScanProgress;
	discoveries: EarlyDiscovery[];
}> = ({ progress, discoveries }) => (
	<div style={{ padding: "32px 24px" }}>
		<h2 style={{ fontSize: "16px", color: "#e4e4e7", marginBottom: "24px" }}>Analyzing your workspace</h2>
		<ProgressBar label="Commit history" value={progress.commitHistory} />
		<ProgressBar label="Reflog entries" value={progress.reflogEntries} />

		{discoveries.length > 0 && (
			<div style={{ marginTop: "24px", borderTop: "1px solid #27272a", paddingTop: "16px" }}>
				<div style={{ fontSize: "12px", color: "#71717a", marginBottom: "8px" }}>Early findings</div>
				{discoveries.map((d) => (
					<div
						key={d.id}
						style={{
							fontSize: "13px",
							color: "#e4e4e7",
							padding: "6px 0",
						}}
					>
						{d.message}
					</div>
				))}
			</div>
		)}
	</div>
);

const ScoreBar: React.FC<{ label: string; value: number }> = ({ label, value }) => (
	<div style={{ marginBottom: "16px" }}>
		<div style={{ display: "flex", justifyContent: "space-between", fontSize: "13px", marginBottom: "4px" }}>
			<span style={{ color: "#d4d4d8", fontWeight: 500 }}>{label}</span>
			<span style={{ color: "#a1a1aa" }}>{value}</span>
		</div>
		<div style={{ width: "100%", height: "8px", background: "#27272a", borderRadius: "4px" }}>
			<div
				style={{
					width: `${value}%`,
					height: "8px",
					background: scoreColor(value),
					borderRadius: "4px",
					transition: "width 500ms ease",
				}}
			/>
		</div>
	</div>
);

const ScanCompletePhase: React.FC<{
	dimensions: RiskDimension[];
	findings: Finding[];
	lockedTeaser: string | null;
	onConnect: () => void;
	onDismiss: () => void;
}> = ({ dimensions, findings, lockedTeaser, onConnect, onDismiss }) => (
	<div style={{ padding: "32px 24px" }}>
		<h2 style={{ fontSize: "16px", color: "#e4e4e7", marginBottom: "24px" }}>Your Recovery Risk Profile</h2>

		{/* Score bars */}
		{dimensions.map((dim) => (
			<ScoreBar key={dim.label} label={dim.label} value={dim.value} />
		))}

		{/* Findings table */}
		{findings.length > 0 && (
			<div style={{ marginTop: "24px" }}>
				<div
					style={{
						display: "grid",
						gridTemplateColumns: "1fr 1fr",
						gap: "8px",
						fontSize: "13px",
					}}
				>
					<div style={{ color: "#71717a", fontWeight: 600, paddingBottom: "8px" }}>What we found</div>
					<div style={{ color: "#71717a", fontWeight: 600, paddingBottom: "8px" }}>What we will do</div>
					{findings.map((f, i) => (
						<>
							<div key={`obs-${i}`} style={{ color: "#d4d4d8", padding: "4px 0" }}>
								{f.severity === "warning" ? "\u26A0 " : ""}
								{f.observation}
							</div>
							<div key={`act-${i}`} style={{ color: "#a1a1aa", padding: "4px 0" }}>
								{f.action}
							</div>
						</>
					))}
				</div>
			</div>
		)}

		{/* Locked insight teaser (Zeigarnik effect) */}
		{lockedTeaser && (
			<div
				style={{
					marginTop: "20px",
					padding: "12px",
					background: "#18181b",
					borderRadius: "6px",
					border: "1px solid #27272a",
					fontSize: "13px",
					color: "#71717a",
				}}
			>
				{lockedTeaser}
			</div>
		)}

		{/* CTAs  -  soft, never blocking */}
		<div style={{ display: "flex", gap: "12px", marginTop: "24px" }}>
			<button
				type="button"
				onClick={onConnect}
				style={{
					padding: "8px 16px",
					background: BRAND_GREEN,
					color: "#09090b",
					border: "none",
					borderRadius: "6px",
					fontSize: "13px",
					fontWeight: 600,
					cursor: "pointer",
				}}
			>
				Connect Account
			</button>
			<button
				type="button"
				onClick={onDismiss}
				style={{
					padding: "8px 16px",
					background: "transparent",
					color: "#71717a",
					border: "1px solid #27272a",
					borderRadius: "6px",
					fontSize: "13px",
					cursor: "pointer",
				}}
			>
				Dismiss
			</button>
		</div>
	</div>
);

// ── Main Panel ───────────────────────────────────────────────────

export const WelcomePanel: React.FC = () => {
	const vscode = getVSCodeAPI();
	const [state, dispatch] = useReducer(welcomeReducer, INITIAL_STATE);

	const handleMessage = useCallback((event: MessageEvent) => {
		const msg = event.data;

		switch (msg.type) {
			case "cli:status":
			case "cliStatus": {
				const installed = msg.installed || msg.payload?.installed;
				dispatch({
					type: "STEP_UPDATE",
					stepId: "cli",
					status: installed ? "done" : "pending",
				});
				break;
			}
			case "cli:installComplete":
				dispatch({ type: "STEP_UPDATE", stepId: "cli", status: "done" });
				break;
			case "daemon:status": {
				const connected = msg.payload?.connected;
				dispatch({
					type: "STEP_UPDATE",
					stepId: "daemon",
					status: connected ? "done" : "active",
				});
				if (connected) {
					dispatch({ type: "PHASE_CHANGE", phase: "SCANNING" });
				}
				break;
			}
			case "scan:progress":
				dispatch({
					type: "SCAN_PROGRESS",
					commitHistory: msg.payload?.commitHistory ?? 0,
					reflogEntries: msg.payload?.reflogEntries ?? 0,
				});
				break;
			case "scan:discovery":
				dispatch({
					type: "EARLY_DISCOVERY",
					discovery: {
						id: msg.payload?.id ?? crypto.randomUUID(),
						message: msg.payload?.message ?? "",
					},
				});
				break;
			case "scan:complete":
				dispatch({
					type: "SCAN_RESULTS",
					riskDimensions: msg.payload?.dimensions ?? [],
					findings: msg.payload?.findings ?? [],
					lockedInsightTeaser: msg.payload?.lockedTeaser ?? null,
				});
				dispatch({ type: "PHASE_CHANGE", phase: "SCAN_COMPLETE" });
				break;
		}
	}, []);

	useEffect(() => {
		window.addEventListener("message", handleMessage);
		vscode?.postMessage({ type: "webviewReady" });
		return () => window.removeEventListener("message", handleMessage);
	}, [handleMessage, vscode]);

	const handleConnect = () => {
		vscode?.postMessage({ type: "oauth:start" });
	};

	const handleDismiss = () => {
		vscode?.postMessage({ type: "close" });
	};

	return (
		<div
			style={{
				display: "flex",
				flexDirection: "column",
				height: "100vh",
				background: "#09090b",
				color: "#e4e4e7",
				fontFamily: "var(--vscode-font-family, system-ui, sans-serif)",
			}}
		>
			{/* Header */}
			<div
				style={{
					display: "flex",
					alignItems: "center",
					gap: "12px",
					padding: "16px 24px",
					borderBottom: "1px solid #27272a",
				}}
			>
				<img src={vrekoIcon} alt="" width={28} height={28} />
				<span style={{ fontSize: "15px", fontWeight: 600 }}>Vreko</span>
			</div>

			{/* Content  -  phase-dependent */}
			<div style={{ flex: 1, overflow: "auto" }}>
				{state.phase === "EXTENSION_INSTALLED" && <SetupPhase steps={state.steps} />}
				{state.phase === "SCANNING" && (
					<ScanningPhase progress={state.scanProgress} discoveries={state.earlyDiscoveries} />
				)}
				{state.phase === "SCAN_COMPLETE" && (
					<ScanCompletePhase
						dimensions={state.riskDimensions}
						findings={state.findings}
						lockedTeaser={state.lockedInsightTeaser}
						onConnect={handleConnect}
						onDismiss={handleDismiss}
					/>
				)}
			</div>

			{/* Privacy line  -  always visible */}
			<PrivacyLine />
		</div>
	);
};
