"use client";

import Link from "next/link";
import { motion, useReducedMotion } from "framer-motion";
import { Activity, ArrowUpRight, Coins, Hammer, Play, Plus, Radio, Search, Users } from "lucide-react";
import type { CSSProperties, ReactNode } from "react";
import ActivityStream from "./ActivityStream";
import AgentAvatar, { type AgentKey } from "./AgentAvatar";
import { QUICK_LAUNCH_TILES } from "./QuickLaunch";
import { accentVar, type BroadcastPayload } from "@/lib/homeBroadcast";
import { formatCompact } from "@/lib/formatCompact";
import { useHomeStats, type VitalsData } from "@/lib/useHomeStats";

interface Props {
  bc: BroadcastPayload | null;
  onWatchIntro: () => void;
}

interface AgentRow {
  key: AgentKey;
  name: string;
  status: "busy" | "ready" | "idle";
  sub: string;
}

const STATUS_COLOR: Record<AgentRow["status"], string> = {
  busy: "var(--gold)",
  ready: "var(--emerald)",
  idle: "var(--cream-mute)",
};

function agentRows(vitals: VitalsData): AgentRow[] {
  const oc = vitals.openclaw;
  const ocBusy = Boolean(oc?.busy || oc?.degraded);
  return [
    {
      key: "claude", name: "Claude",
      status: vitals.claude?.ok ? "ready" : "idle",
      sub: vitals.claude?.ok ? "senior coding agent" : "not detected",
    },
    {
      key: "openclaw", name: "OpenClaw",
      status: ocBusy ? "busy" : oc?.ok ? "ready" : "idle",
      sub: ocBusy ? "working right now" : oc?.ok ? `${oc.sessions ?? 0} sessions logged` : "not detected",
    },
    {
      key: "hermes", name: "Hermes",
      status: vitals.hermes?.ok ? "ready" : "idle",
      sub: vitals.hermes?.ok ? (vitals.hermes.model ?? "chat + skills") : "not detected",
    },
    {
      key: "antigravity", name: "Antigravity",
      status: vitals.antigravity?.ok ? "ready" : "idle",
      sub: vitals.antigravity?.ok ? "multi-agent harness" : "not detected",
    },
  ];
}

// HomeCockpit — the bento "Cockpit" home layout. Same data + remote-driven
// layer as the Classic home (both are fed by the <Home/> wrapper), arranged
// as a 12-column bento grid: hero, live stat tiles, agent cluster, broadcast
// card, dense quick launch and the activity feed. Every tile degrades
// gracefully: any endpoint may be down on a fresh install and nothing here
// may ever blank-screen.
export default function HomeCockpit({ bc, onWatchIntro }: Props) {
  const { vitals, tokens, userName, agentsOnline, tasksToday } = useHomeStats();
  const reduceMotion = useReducedMotion();
  const displayName = userName ?? "Operator";
  const grand = tokens?.grand;
  const builds = vitals?.openclaw?.sessions;

  // Cosmetic doorway to the existing palette — it listens for ⌘K on window.
  const openPalette = () => {
    window.dispatchEvent(new KeyboardEvent("keydown", { key: "k", metaKey: true, cancelable: true }));
  };

  return (
    <div className="space-y-4">
      <motion.button
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: reduceMotion ? 0.01 : 0.35 }}
        onClick={openPalette}
        aria-label="Open the command palette"
        className="focus-ring hidden md:flex w-full items-center gap-3 rounded-xl border px-4 py-3 text-left hover:border-[var(--line)]"
        style={{
          borderColor: "var(--line-soft)",
          background: "color-mix(in srgb, var(--bg-card) 70%, transparent)",
          boxShadow: "var(--shadow-1)",
        }}
      >
        <Search size={15} style={{ color: "var(--gold)" }} />
        <span className="flex-1 text-[13.5px]" style={{ color: "var(--cream-mute)" }}>
          Ask anything, or run a command
        </span>
        <span className="pill">⌘K</span>
      </motion.button>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-4">
        {/* ── Hero ─────────────────────────────────────────────── */}
        <Tile
          label="Welcome"
          delay={0}
          className="sm:col-span-2 lg:col-span-8 lg:row-span-2 flex flex-col justify-center p-6! md:p-8!"
          style={{
            borderColor: "var(--line)",
            background:
              "radial-gradient(ellipse 65% 100% at 92% 0%, color-mix(in srgb, var(--gold) 10%, transparent), transparent 62%), " +
              "radial-gradient(ellipse 50% 90% at 4% 100%, color-mix(in srgb, var(--plum) 7%, transparent), transparent 60%), " +
              "linear-gradient(180deg, var(--bg-elev), var(--bg-card))",
            boxShadow: "var(--shadow-1), 0 30px 80px -50px color-mix(in srgb, var(--gold) 35%, transparent)",
          }}
        >
          <div className="action-tag mb-3" style={{ color: "var(--gold)" }}>Mission Control · Live</div>
          <h1 className="text-[clamp(1.9rem,3.4vw,2.8rem)] leading-[1.05]" style={{ letterSpacing: "-0.03em" }}>
            Welcome back, <em>{displayName}</em>
          </h1>
          <p className="mt-3 status-meta flex items-center gap-2 flex-wrap">
            <span className="heartbeat" style={{ color: "var(--emerald)" }} />
            <span>
              {agentsOnline === null ? "Checking your systems" : `${agentsOnline} agent${agentsOnline === 1 ? "" : "s"} online`}
              <span className="mx-2 opacity-40">·</span>
              {tasksToday === null ? "counting tasks" : `${tasksToday} task${tasksToday === 1 ? "" : "s"} today`}
              <span className="mx-2 opacity-40">·</span>
              all local on your machine
            </span>
          </p>
          <div className="mt-6 flex items-center gap-2.5 flex-wrap">
            <Link href="/room" className="copy-btn focus-ring inline-flex items-center gap-2">
              <Plus size={13} /> New Agent
            </Link>
            <button
              onClick={onWatchIntro}
              className="focus-ring inline-flex items-center gap-2 rounded-full border px-4 py-2 text-[11px] font-bold uppercase tracking-[0.16em] transition-transform hover:-translate-y-px active:translate-y-0"
              style={{ borderColor: "var(--line)", color: "var(--cream-soft)", background: "color-mix(in srgb, var(--cream) 3%, transparent)" }}
            >
              <Play size={12} style={{ color: "var(--gold)" }} /> Watch intro
            </button>
          </div>
        </Tile>

        <StatTile
          className="lg:col-span-4" delay={0.05}
          label="Agents Online" icon={<Users size={13} />} accent="var(--emerald)"
          value={agentsOnline === null ? "—" : String(agentsOnline)}
          sub={agentsOnline === null ? "checking…" : "of 4 wired agents"}
        />
        <StatTile
          className="lg:col-span-4" delay={0.08}
          label="Tasks Today" icon={<Activity size={13} />} accent="var(--gold)"
          value={tasksToday === null ? "—" : formatCompact(tasksToday)}
          sub={tasksToday === null ? "no data yet" : "agent calls since midnight"}
        />

        <AgentsTile vitals={vitals} delay={0.1} className="sm:col-span-2 lg:col-span-5 lg:row-span-3" />
        <BroadcastTile bc={bc} delay={0.12} className="sm:col-span-2 lg:col-span-7" />

        <StatTile
          className="lg:col-span-4" delay={0.14}
          label="Tokens Spent" icon={<Coins size={13} />} accent="var(--rust)"
          value={grand ? formatCompact(grand.totalTokens) : "—"}
          sub={grand ? `${formatCompact(grand.todayTokens)} today · $${grand.costUsd.toFixed(2)} all time` : "no usage recorded yet"}
        />
        <StatTile
          className="lg:col-span-3" delay={0.16}
          label="Builds" icon={<Hammer size={13} />} accent="var(--plum)"
          value={builds === undefined ? "—" : formatCompact(builds)}
          sub={builds === undefined ? "no sessions yet" : "agent sessions logged"}
        />

        <QuickTile delay={0.18} className="sm:col-span-2 lg:col-span-7" />

        <motion.section
          aria-label="Recent activity"
          initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: reduceMotion ? 0.01 : 0.4, delay: reduceMotion ? 0 : 0.2 }}
          className="sm:col-span-2 lg:col-span-12"
        >
          <ActivityStream />
        </motion.section>
      </div>
    </div>
  );
}

// Tile — shared bento cell: layered surface, soft border, fade-up entrance.
function Tile({ label, className, style, delay = 0, children }: {
  label: string; className?: string; style?: CSSProperties; delay?: number; children: ReactNode;
}) {
  const reduceMotion = useReducedMotion();
  return (
    <motion.section
      aria-label={label}
      initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: reduceMotion ? 0.01 : 0.4, delay: reduceMotion ? 0 : delay }}
      className={`relative overflow-hidden rounded-xl border p-5 ${className ?? ""}`}
      style={{
        borderColor: "var(--line-soft)",
        background: "linear-gradient(180deg, var(--bg-card), color-mix(in srgb, var(--bg-mid) 88%, transparent))",
        boxShadow: "var(--shadow-1)",
        ...style,
      }}
    >
      {children}
    </motion.section>
  );
}

function StatTile({ label, icon, value, sub, accent, className, delay }: {
  label: string; icon: ReactNode; value: string; sub: string; accent: string; className?: string; delay: number;
}) {
  return (
    <Tile label={label} className={`flex flex-col justify-center ${className ?? ""}`} delay={delay}>
      <div
        aria-hidden
        className="pointer-events-none absolute -top-12 -right-12 w-32 h-32 rounded-full blur-3xl opacity-15"
        style={{ background: accent }}
      />
      <span
        className="relative flex items-center gap-1.5 text-[0.66rem] uppercase font-bold"
        style={{ letterSpacing: "0.2em", color: "var(--cream-mute)", fontFamily: "'Manrope', sans-serif" }}
      >
        <span style={{ color: accent }}>{icon}</span>
        {label}
      </span>
      <div
        className="relative mt-1.5 metric text-[30px] leading-none"
        style={{ fontFamily: "'Bricolage Grotesque', sans-serif", fontWeight: 500, letterSpacing: "-0.02em", color: "var(--cream)" }}
      >
        {value}
      </div>
      <div className="relative mt-1.5 text-[0.7rem]" style={{ fontFamily: "'JetBrains Mono', monospace", color: "var(--cream-dim)" }}>
        {sub}
      </div>
    </Tile>
  );
}

function AgentsTile({ vitals, className, delay }: { vitals: VitalsData | null; className?: string; delay: number }) {
  const rows = vitals ? agentRows(vitals) : null;
  return (
    <Tile label="Your agents" className={className} delay={delay}>
      <div className="flex items-center justify-between mb-4">
        <h2 className="action-tag" style={{ color: "var(--cream-dim)" }}>Your agents</h2>
        <span className="pill pill-info"><span className="heartbeat" /> live</span>
      </div>
      {rows === null ? (
        <div className="space-y-2.5" aria-label="Checking your agents">
          {[0, 1, 2, 3].map((i) => <div key={i} className="skeleton h-[58px] rounded-lg" />)}
        </div>
      ) : (
        <ul className="space-y-2.5">
          {rows.map((a) => (
            <li
              key={a.key}
              className="flex items-center gap-3 rounded-lg border px-3 py-2.5"
              style={{ borderColor: "var(--line-soft)", background: "color-mix(in srgb, var(--bg-deep) 55%, transparent)" }}
            >
              <AgentAvatar agent={a.key} size={30} />
              <div className="min-w-0 flex-1">
                <div className="text-[13.5px] leading-tight" style={{ fontFamily: "'Bricolage Grotesque', sans-serif", fontWeight: 500, color: "var(--cream)" }}>
                  {a.name}
                </div>
                <div className="text-[11px] truncate" style={{ color: "var(--cream-mute)" }}>{a.sub}</div>
              </div>
              <span
                aria-hidden
                className="w-[7px] h-[7px] rounded-full shrink-0"
                style={{
                  background: STATUS_COLOR[a.status],
                  boxShadow: a.status === "idle" ? "none" : `0 0 8px ${STATUS_COLOR[a.status]}`,
                }}
              />
              <span className="sr-only">{a.status}</span>
            </li>
          ))}
        </ul>
      )}
      <Link
        href="/room"
        className="focus-ring mt-4 inline-flex items-center gap-1 action-tag hover:opacity-100 transition-opacity"
        style={{ color: "var(--gold)", opacity: 0.85 }}
      >
        All agents, one room <ArrowUpRight size={12} />
      </Link>
    </Tile>
  );
}

function BroadcastTile({ bc, className, delay }: { bc: BroadcastPayload | null; className?: string; delay: number }) {
  const data = bc?.broadcast;
  const accent = accentVar(data?.accent);
  const live = Boolean(data?.show);
  return (
    <Tile
      label="Announcement"
      className={`flex items-center ${className ?? ""}`}
      delay={delay}
      style={live ? {
        borderColor: `color-mix(in srgb, ${accent} 26%, transparent)`,
        background:
          `radial-gradient(ellipse 45% 130% at 0% 50%, color-mix(in srgb, ${accent} 12%, transparent), transparent 62%), ` +
          "linear-gradient(180deg, var(--bg-card), color-mix(in srgb, var(--bg-mid) 88%, transparent))",
        boxShadow: `var(--shadow-1), 0 16px 50px -30px color-mix(in srgb, ${accent} 55%, transparent)`,
      } : undefined}
    >
      {live && data ? (
        <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-5 w-full">
          <span
            className="pill shrink-0 self-start sm:self-center"
            style={{ color: accent, borderColor: `color-mix(in srgb, ${accent} 35%, transparent)`, background: `color-mix(in srgb, ${accent} 8%, transparent)` }}
          >
            {data.badge ?? "News"}
          </span>
          <div className="min-w-0 flex-1">
            {data.headline && (
              <h2 className="text-[15px] leading-snug" style={{ letterSpacing: "-0.015em" }}>{data.headline}</h2>
            )}
            {data.body && (
              <p className="mt-0.5 text-[12.5px] leading-relaxed" style={{ color: "var(--cream-soft)" }}>{data.body}</p>
            )}
          </div>
          {data.ctaUrl && data.ctaLabel && (
            <a
              href={data.ctaUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="focus-ring shrink-0 inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-[11px] font-bold uppercase tracking-[0.16em] transition-transform hover:-translate-y-px active:translate-y-0"
              style={{ background: accent, color: "var(--bg-deep)", boxShadow: `0 6px 18px -8px ${accent}` }}
            >
              {data.ctaLabel} <ArrowUpRight size={13} />
            </a>
          )}
        </div>
      ) : (
        <div className="flex items-center gap-3 w-full">
          <span
            className="grid place-items-center w-8 h-8 rounded-md shrink-0"
            style={{ color: "var(--cream-mute)", border: "1px solid var(--line-soft)" }}
          >
            <Radio size={14} />
          </span>
          <div className="min-w-0">
            <p className="text-[13px]" style={{ color: "var(--cream-soft)" }}>Nothing on the wire right now.</p>
            <p className="text-[11.5px]" style={{ color: "var(--cream-mute)" }}>
              Announcements from HQ land here when you are online.
            </p>
          </div>
        </div>
      )}
    </Tile>
  );
}

function QuickTile({ className, delay }: { className?: string; delay: number }) {
  const tiles = QUICK_LAUNCH_TILES.filter((t) => t.href !== "/seo");
  return (
    <Tile label="Quick launch" className={className} delay={delay}>
      <div className="flex items-center justify-between mb-3.5">
        <h2 className="action-tag" style={{ color: "var(--cream-dim)" }}>Quick launch</h2>
        <span
          className="text-[9.5px] uppercase"
          style={{ letterSpacing: "0.18em", color: "var(--cream-mute)", fontFamily: "'JetBrains Mono', monospace" }}
        >
          jump anywhere
        </span>
      </div>
      <div className="grid grid-cols-4 gap-2">
        {tiles.map((t) => (
          <Link
            key={t.href}
            href={t.href}
            title={t.desc}
            className="focus-ring group flex flex-col items-center justify-center gap-1.5 rounded-lg border px-2 py-3 transition-transform hover:-translate-y-0.5 active:translate-y-0 hover:border-[var(--line)]"
            style={{ borderColor: "var(--line-soft)", background: "color-mix(in srgb, var(--bg-deep) 55%, transparent)" }}
          >
            <span
              className="grid place-items-center w-8 h-8 rounded-md"
              style={{ color: t.accent, background: `color-mix(in srgb, ${t.accent} 10%, transparent)` }}
            >
              {t.icon}
            </span>
            <span className="text-[10.5px] text-center" style={{ color: "var(--cream-soft)", fontFamily: "'Manrope', sans-serif", fontWeight: 600 }}>
              {t.label}
            </span>
          </Link>
        ))}
      </div>
    </Tile>
  );
}
