"use client";

import Link from "next/link";
import { motion, useReducedMotion } from "framer-motion";
import { Activity, ArrowUpRight, Coins, Play, Plus, Radio, Users } from "lucide-react";
import type { ReactNode } from "react";
import ActivityStream from "./ActivityStream";
import BroadcastStrip from "./BroadcastStrip";
import DailyBriefCard from "./DailyBriefCard";
import QuickLaunch from "./QuickLaunch";
import SetupChecklist from "./SetupChecklist";
import type { BroadcastPayload } from "@/lib/homeBroadcast";
import { formatCompact } from "@/lib/formatCompact";
import { useHomeStats } from "@/lib/useHomeStats";

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

// HomeDashboard — the "Classic" MissionMate home. The remote-driven layer
// (broadcast payload + welcome-video modal) is owned by the <Home/> wrapper
// and shared with the Cockpit layout; this component receives the payload and
// an open-the-intro callback. Every block degrades gracefully: any endpoint
// may be down on a fresh install and nothing here may ever blank-screen.
export default function HomeDashboard({ bc, onWatchIntro }: Props) {
  const { tokens, userName, agentsOnline, tasksToday } = useHomeStats();
  const reduceMotion = useReducedMotion();

  const displayName = userName ?? "Operator";
  const fade = { duration: reduceMotion ? 0.01 : 0.4 };

  return (
    <div className="space-y-8">
      <BroadcastStrip data={bc?.broadcast} version={bc?.version ?? "0"} />

      {/* ── Hero ─────────────────────────────────────────────── */}
      <motion.section
        initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={fade}
        className="flex flex-col md:flex-row md:items-end md:justify-between gap-5"
      >
        <div className="min-w-0">
          <h1 className="page-title">
            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>
          </p>
        </div>
        <div className="flex items-center gap-2.5 shrink-0">
          <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>
          <Link href="/room" className="copy-btn focus-ring inline-flex items-center gap-2">
            <Plus size={13} /> New Agent
          </Link>
        </div>
      </motion.section>

      {/* ── KPI row ──────────────────────────────────────────── */}
      <section aria-label="Key numbers" className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <KpiTile
          label="Agents Online"
          icon={<Users size={13} />}
          value={agentsOnline === null ? "—" : String(agentsOnline)}
          sub={agentsOnline === null ? "checking…" : "of 4 wired agents"}
          accent="var(--emerald)"
        />
        <KpiTile
          label="Tasks Today"
          icon={<Activity size={13} />}
          value={tasksToday === null ? "—" : formatCompact(tasksToday)}
          sub={tasksToday === null ? "no data yet" : "agent calls since midnight"}
          accent="var(--gold)"
        />
        <KpiTile
          label="Tokens Spent"
          icon={<Coins size={13} />}
          value={tokens?.grand ? formatCompact(tokens.grand.totalTokens) : "—"}
          sub={tokens?.grand ? `${formatCompact(tokens.grand.todayTokens)} today · $${tokens.grand.costUsd.toFixed(2)} all time` : "no usage recorded yet"}
          accent="var(--rust)"
        />
      </section>

      <div className="divider my-2!" aria-hidden>
        <span className="rule" /><span className="ornament">✦</span><span className="rule" />
      </div>

      {/* ── Quick launch ─────────────────────────────────────── */}
      <section aria-label="Quick launch">
        <div className="eyebrow mb-4">
          <span className="num">II.</span><span className="line" />
          <span className="label">Quick launch · jump anywhere</span>
        </div>
        <QuickLaunch />
      </section>

      <div className="divider my-2!" aria-hidden>
        <span className="rule" /><span className="ornament">✦</span><span className="rule" />
      </div>

      {/* ── Lower two-column ─────────────────────────────────── */}
      <section className="grid grid-cols-1 lg:grid-cols-5 gap-5 items-start">
        <div className="lg:col-span-3 space-y-5 min-w-0">
          <div className="eyebrow mb-1">
            <span className="num">III.</span><span className="line" />
            <span className="label">Getting started · live activity</span>
          </div>
          <SetupChecklist />
          <div className="flex items-center gap-2 pt-1">
            <Radio size={12} style={{ color: "var(--gold)" }} />
            <span className="action-tag">Recent activity</span>
          </div>
          <ActivityStream />
        </div>

        <div className="lg:col-span-2 space-y-5 min-w-0">
          <div className="eyebrow mb-1">
            <span className="num">IV.</span><span className="line" />
            <span className="label">Daily brief · community</span>
          </div>
          <DailyBriefCard />
          <LinksBlock bc={bc} />
        </div>
      </section>
    </div>
  );
}

function KpiTile({ label, icon, value, sub, accent }: {
  label: string; icon: ReactNode; value: string; sub: string; accent: string;
}) {
  return (
    <div className="vital-tile relative overflow-hidden">
      <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 }}
      />
      <div className="relative flex items-center justify-between">
        <span className="k flex items-center gap-1.5">
          <span style={{ color: accent }}>{icon}</span>
          {label}
        </span>
      </div>
      <div className="relative text-[30px] leading-none mt-1 metric" style={{ fontFamily: "'Bricolage Grotesque', sans-serif", fontWeight: 500, letterSpacing: "-0.02em", color: "var(--cream)" }}>
        {value}
      </div>
      <div className="relative sub">{sub}</div>
    </div>
  );
}

function LinksBlock({ bc }: { bc: BroadcastPayload | null }) {
  const links = bc?.links ?? [];
  return (
    <div className="panel p-5">
      <div className="action-tag mb-3" style={{ color: "var(--gold)" }}>Community + help</div>
      {links.length === 0 ? (
        <p className="text-[12.5px] leading-relaxed" style={{ color: "var(--cream-mute)" }}>
          Community links land here automatically when you are online.
        </p>
      ) : (
        <ul className="space-y-1">
          {links.map((l, i) => (
            <li key={i}>
              <a
                href={l.url}
                target="_blank"
                rel="noopener noreferrer"
                className="focus-ring group flex items-center justify-between gap-3 rounded-md px-2.5 py-2 transition-colors hover:bg-[color-mix(in_srgb,var(--gold)_5%,transparent)]"
              >
                <span className="text-[13.5px]" style={{ color: "var(--cream)" }}>{l.label}</span>
                <ArrowUpRight size={13} className="opacity-40 group-hover:opacity-100 transition-opacity" style={{ color: "var(--cream-dim)" }} />
              </a>
            </li>
          ))}
        </ul>
      )}
      {bc?.latest?.version && (
        <div className="mt-4 pt-3 border-t" style={{ borderColor: "var(--line-soft)" }}>
          <span className="text-[11px]" style={{ color: "var(--cream-mute)" }}>
            Latest pack: <span className="mono" style={{ color: "var(--cream-dim)" }}>{bc.latest.version}</span>
          </span>
        </div>
      )}
    </div>
  );
}
