"use client";
import { useEffect, useState, useCallback, useRef, useMemo } from "react";

interface Ship {
  id: number;
  title: string;
  status: "shipped" | "shipping" | "planned";
  metric?: string | null;
  created_at: string;
  updated_at: string;
  member: string;
}

/* ─────────────────────────────────────────
   Animated counter — springs to target
───────────────────────────────────────── */
function useCountUp(target: number, duration = 1200) {
  const [val, setVal] = useState(0);
  const from = useRef(0);
  useEffect(() => {
    const start = from.current;
    const delta = target - start;
    if (delta === 0) return;
    const t0 = performance.now();
    let raf: number;
    const step = (now: number) => {
      const p = Math.min((now - t0) / duration, 1);
      const ease = 1 - Math.pow(1 - p, 4); // quartic ease-out
      setVal(Math.round(start + delta * ease));
      if (p < 1) raf = requestAnimationFrame(step);
      else from.current = target;
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return val;
}

/* ─────────────────────────────────────────
   Project detection from title prefix
───────────────────────────────────────── */
const PROJECTS: Record<string, { name: string; emoji: string; color: string; glow: string }> = {
  clinera:   { name: "Clinera",         emoji: "🏥", color: "#6366f1", glow: "#6366f130" },
  glass:     { name: "Glass Inventory", emoji: "🔲", color: "#06b6d4", glow: "#06b6d430" },
  gymnastic: { name: "Gymnastic",       emoji: "🤸", color: "#f43f5e", glow: "#f43f5e30" },
  quikcue:   { name: "QuikCue",         emoji: "⚡", color: "#10b981", glow: "#10b98130" },
  infra:     { name: "Infra / DevOps",  emoji: "🖥️", color: "#8b5cf6", glow: "#8b5cf630" },
  other:     { name: "Other",           emoji: "🔧", color: "#f59e0b", glow: "#f59e0b30" },
};

function detectProject(title: string): string {
  const t = title.toLowerCase();
  if (t.startsWith("clinera")) return "clinera";
  if (t.includes("glass")) return "glass";
  if (t.includes("gymnastic") || t.includes("gym")) return "gymnastic";
  if (t.includes("quikcue") || t.includes("quik cue") || t.includes("live feed")) return "quikcue";
  if (t.includes("infra") || t.includes("server") || t.includes("deploy") || t.includes("docker") || t.includes("devops")) return "infra";
  return "other";
}

/* ─────────────────────────────────────────
   Time helpers
───────────────────────────────────────── */
function timeAgo(d: string) {
  const diff = Date.now() - new Date(d).getTime();
  const m = Math.floor(diff / 60000);
  const h = Math.floor(diff / 3600000);
  const dy = Math.floor(diff / 86400000);
  if (m < 1) return "just now";
  if (m < 60) return `${m}m ago`;
  if (h < 24) return `${h}h ago`;
  return `${dy}d ago`;
}

/* ─────────────────────────────────────────
   Big hero counter card
───────────────────────────────────────── */
function HeroCounter({ total }: { total: number }) {
  const count = useCountUp(total, 1800);
  return (
    <div style={{
      textAlign: "center",
      padding: "56px 24px 48px",
      position: "relative",
    }}>
      {/* Glow ring behind number */}
      <div style={{
        position: "absolute", top: "50%", left: "50%",
        transform: "translate(-50%,-50%)",
        width: 260, height: 260, borderRadius: "50%",
        background: "radial-gradient(circle, #6366f122 0%, transparent 70%)",
        animation: "breathe 4s ease-in-out infinite",
        pointerEvents: "none",
      }} />

      <div style={{
        fontSize: "clamp(80px, 18vw, 140px)",
        fontWeight: 900,
        lineHeight: 1,
        letterSpacing: "-6px",
        fontVariantNumeric: "tabular-nums",
        fontFamily: "'SF Pro Display', -apple-system, sans-serif",
        background: "linear-gradient(135deg, #fff 30%, #a5b4fc 70%, #818cf8)",
        WebkitBackgroundClip: "text",
        WebkitTextFillColor: "transparent",
        filter: "drop-shadow(0 0 40px #6366f160)",
        animation: "countPop 0.6s cubic-bezier(.34,1.56,.64,1) both",
      }}>
        {count}
      </div>

      <div style={{
        fontSize: "clamp(16px, 3vw, 22px)",
        fontWeight: 800, color: "#94a3b8",
        letterSpacing: "0.15em", textTransform: "uppercase",
        marginTop: 8,
        animation: "fadeUp 0.8s ease 0.3s both",
      }}>
        tasks completed
      </div>

      <div style={{
        display: "inline-flex", alignItems: "center", gap: 8,
        marginTop: 20,
        background: "#ffffff0d", border: "1px solid #ffffff18",
        borderRadius: 99, padding: "8px 20px",
        animation: "fadeUp 0.8s ease 0.5s both",
      }}>
        <span style={{
          width: 8, height: 8, borderRadius: "50%", background: "#22c55e",
          display: "inline-block", animation: "pulse 1.2s ease-in-out infinite",
        }} />
        <span style={{ fontSize: 12, fontWeight: 700, color: "#86efac", letterSpacing: "0.06em" }}>
          LIVE — AUTO-UPDATES
        </span>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────
   Project section
───────────────────────────────────────── */
function ProjectSection({
  projectKey, ships, delay,
}: {
  projectKey: string; ships: Ship[]; delay: number;
}) {
  const [open, setOpen] = useState(true);
  const proj = PROJECTS[projectKey] || PROJECTS.other;
  const done = ships.filter(s => s.status === "shipped").length;
  const live = ships.filter(s => s.status === "shipping").length;
  const count = useCountUp(done, 1000);

  return (
    <div style={{
      background: "#ffffff08",
      border: `1px solid #ffffff12`,
      borderRadius: 24,
      overflow: "hidden",
      animation: `fadeUp 0.6s ease ${delay}ms both`,
    }}>
      {/* Project header */}
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          all: "unset", cursor: "pointer", display: "flex",
          alignItems: "center", gap: 14, width: "100%",
          padding: "20px 24px",
          borderBottom: open ? "1px solid #ffffff10" : "none",
          transition: "background 0.2s",
        }}
      >
        <div style={{
          width: 44, height: 44, borderRadius: 14, fontSize: 22,
          display: "flex", alignItems: "center", justifyContent: "center",
          background: `${proj.color}20`,
          border: `1px solid ${proj.color}30`,
          flexShrink: 0,
        }}>
          {proj.emoji}
        </div>

        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: 16, color: "#fff" }}>{proj.name}</div>
          <div style={{ fontSize: 12, color: "#64748b", marginTop: 2 }}>
            {done} shipped · {ships.length} total
            {live > 0 && <span style={{ color: "#f59e0b", marginLeft: 8 }}>⚡ {live} in flight</span>}
          </div>
        </div>

        {/* Count badge */}
        <div style={{
          fontSize: 32, fontWeight: 900, color: proj.color,
          fontVariantNumeric: "tabular-nums",
          letterSpacing: "-1px",
          filter: `drop-shadow(0 0 12px ${proj.color}60)`,
        }}>
          {count}
        </div>

        <div style={{
          fontSize: 12, color: "#475569",
          transform: open ? "rotate(180deg)" : "none",
          transition: "transform 0.3s",
        }}>▼</div>
      </button>

      {/* Task list */}
      {open && (
        <div style={{ padding: "8px 16px 16px" }}>
          {ships.length === 0 ? (
            <div style={{ textAlign: "center", padding: "24px 0", color: "#334155", fontSize: 13 }}>
              No tasks logged yet
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
              {ships.map((ship, i) => (
                <TaskRow key={ship.id} ship={ship} index={i} projectColor={proj.color} />
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────
   Task row
───────────────────────────────────────── */
function TaskRow({ ship, index, projectColor }: { ship: Ship; index: number; projectColor: string }) {
  const [hovered, setHovered] = useState(false);
  const isLive = ship.status === "shipping";
  const isDone = ship.status === "shipped";

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: "flex", gap: 12, alignItems: "flex-start",
        padding: "12px 14px", borderRadius: 14,
        background: hovered ? "#ffffff08" : "transparent",
        border: `1px solid ${hovered ? "#ffffff14" : "transparent"}`,
        transition: "all 0.2s",
        animation: `slideIn 0.4s ease ${index * 30}ms both`,
        cursor: "default",
      }}
    >
      {/* Icon */}
      <div style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0, marginTop: 1,
        display: "flex", alignItems: "center", justifyContent: "center",
        background: isDone ? "#10b98118" : isLive ? "#f59e0b18" : "#6366f118",
        border: `1px solid ${isDone ? "#10b98130" : isLive ? "#f59e0b30" : "#6366f130"}`,
        fontSize: 13,
      }}>
        {isDone ? "✓" : isLive ? "⚡" : "○"}
      </div>

      {/* Text */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13.5, fontWeight: 600,
          color: isDone ? "#cbd5e1" : "#e2e8f0",
          lineHeight: 1.4,
          textDecoration: isDone ? "none" : "none",
        }}>
          {/* Strip project prefix */}
          {ship.title.replace(/^[^:]+:\s*/, "")}
        </div>

        {ship.metric && (
          <div style={{
            fontSize: 11.5, color: "#475569", marginTop: 4,
            lineHeight: 1.5,
          }}>
            {ship.metric}
          </div>
        )}
      </div>

      {/* Time */}
      <div style={{ flexShrink: 0, textAlign: "right" }}>
        {isLive ? (
          <span style={{
            fontSize: 10, fontWeight: 800, padding: "3px 8px",
            borderRadius: 99, background: "#f59e0b20",
            color: "#f59e0b", border: "1px solid #f59e0b30",
            display: "flex", alignItems: "center", gap: 4,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#f59e0b", animation: "pulse 1s infinite" }} />
            LIVE
          </span>
        ) : (
          <span style={{ fontSize: 11, color: "#334155" }}>{timeAgo(ship.updated_at)}</span>
        )}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────
   Main page
───────────────────────────────────────── */
function ProjectStatCard({ proj, count, index }: { proj: { name: string; emoji: string; color: string; glow: string }; count: number; index: number }) {
  const animated = useCountUp(count, 1200);
  return (
    <div style={{
      background:"#ffffff06", border:"1px solid #ffffff0d",
      borderRadius:18, padding:"18px 16px", textAlign:"center",
      animation:`fadeUp 0.5s ease ${index*100+900}ms both`,
    }}>
      <div style={{ fontSize:26 }}>{proj.emoji}</div>
      <div style={{
        fontSize:36, fontWeight:900, color:proj.color,
        letterSpacing:"-1.5px", marginTop:6,
        filter:`drop-shadow(0 0 12px ${proj.color}50)`,
        fontVariantNumeric:"tabular-nums",
      }}>
        {animated}
      </div>
      <div style={{ fontSize:11, color:"#475569", fontWeight:700, marginTop:4, textTransform:"uppercase", letterSpacing:"0.06em" }}>
        {proj.name}
      </div>
    </div>
  );
}

export default function LivePage() {
  const [ships, setShips] = useState<Ship[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchShips = useCallback(async () => {
    try {
      const res = await fetch("https://quikcue.com/api/ships?member=obaidalahsaleh&limit=200");
      if (!res.ok) return;
      const data = await res.json();
      setShips(Array.isArray(data) ? data : []);
    } catch { /* silent */ } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchShips();
    const t = setInterval(fetchShips, 15000);
    return () => clearInterval(t);
  }, [fetchShips]);

  const grouped = useMemo(() => {
    const map: Record<string, Ship[]> = {};
    ships.forEach(s => {
      const k = detectProject(s.title);
      if (!map[k]) map[k] = [];
      map[k].push(s);
    });
    return map;
  }, [ships]);

  const totalDone = ships.filter(s => s.status === "shipped").length;
  const totalLive = ships.filter(s => s.status === "shipping").length;

  const projectOrder = ["clinera", "glass", "gymnastic", "quikcue", "infra", "other"].filter(
    k => grouped[k]?.length
  );

  return (
    <div style={{
      minHeight: "100vh",
      background: "#080c14",
      fontFamily: "-apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', sans-serif",
      color: "#e2e8f0",
    }}>
      <style>{`
        @keyframes fadeUp {
          from { opacity: 0; transform: translateY(20px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes slideIn {
          from { opacity: 0; transform: translateX(-8px); }
          to   { opacity: 1; transform: translateX(0); }
        }
        @keyframes countPop {
          from { opacity: 0; transform: scale(0.7); }
          to   { opacity: 1; transform: scale(1); }
        }
        @keyframes pulse {
          0%,100% { opacity:1; } 50% { opacity:0.3; }
        }
        @keyframes breathe {
          0%,100% { transform:translate(-50%,-50%) scale(1); opacity:0.6; }
          50%      { transform:translate(-50%,-50%) scale(1.15); opacity:1; }
        }
        @keyframes float {
          0%,100% { transform:translateY(0); }
          50%      { transform:translateY(-12px); }
        }
        @keyframes shimmer {
          0%   { background-position: -200% 0; }
          100% { background-position:  200% 0; }
        }
        @keyframes orb1 {
          0%,100% { transform:translate(0,0); }
          50%      { transform:translate(60px,-40px); }
        }
        @keyframes orb2 {
          0%,100% { transform:translate(0,0); }
          50%      { transform:translate(-40px,30px); }
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        ::-webkit-scrollbar { width: 4px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 99px; }
        button:focus { outline: none; }
      `}</style>

      {/* Background orbs */}
      <div style={{ position:"fixed", inset:0, overflow:"hidden", pointerEvents:"none", zIndex:0 }}>
        <div style={{
          position:"absolute", top:"-20%", left:"-10%",
          width:700, height:700, borderRadius:"50%",
          background:"radial-gradient(circle, #6366f118 0%, transparent 65%)",
          animation:"orb1 15s ease-in-out infinite",
        }} />
        <div style={{
          position:"absolute", bottom:"-20%", right:"-10%",
          width:600, height:600, borderRadius:"50%",
          background:"radial-gradient(circle, #06b6d412 0%, transparent 65%)",
          animation:"orb2 18s ease-in-out infinite",
        }} />
        <div style={{
          position:"absolute", top:"40%", right:"20%",
          width:400, height:400, borderRadius:"50%",
          background:"radial-gradient(circle, #f43f5e0a 0%, transparent 65%)",
          animation:"orb1 12s ease-in-out infinite 3s",
        }} />
      </div>

      {/* Header */}
      <header style={{
        position:"relative", zIndex:10,
        borderBottom:"1px solid #ffffff08",
        padding:"18px 24px",
        display:"flex", alignItems:"center", justifyContent:"space-between",
        backdropFilter:"blur(12px)",
        background:"#080c14cc",
      }}>
        <div style={{ display:"flex", alignItems:"center", gap:12 }}>
          <div style={{
            width:36, height:36, borderRadius:10,
            background:"linear-gradient(135deg,#6366f1,#8b5cf6)",
            display:"flex", alignItems:"center", justifyContent:"center",
            fontSize:18, fontWeight:900, color:"#fff",
            boxShadow:"0 4px 16px #6366f140",
          }}>O</div>
          <div>
            <div style={{ fontWeight:800, fontSize:15, color:"#f1f5f9" }}>Obaid Al-Ahsaleh</div>
            <div style={{ fontSize:11, color:"#475569" }}>Build log · All projects</div>
          </div>
        </div>

        {totalLive > 0 && (
          <div style={{
            display:"flex", alignItems:"center", gap:7,
            background:"#f59e0b15", border:"1px solid #f59e0b30",
            borderRadius:99, padding:"6px 14px",
          }}>
            <span style={{
              width:7, height:7, borderRadius:"50%", background:"#f59e0b",
              animation:"pulse 1s infinite",
            }} />
            <span style={{ fontSize:12, fontWeight:700, color:"#f59e0b" }}>
              {totalLive} in flight
            </span>
          </div>
        )}
      </header>

      {/* Hero */}
      <div style={{ position:"relative", zIndex:1 }}>
        {loading ? (
          <div style={{ textAlign:"center", padding:"100px 0", color:"#334155", fontSize:14 }}>
            Loading...
          </div>
        ) : (
          <HeroCounter total={totalDone} />
        )}
      </div>

      {/* Project breakdown */}
      <div style={{ position:"relative", zIndex:1, maxWidth:680, margin:"0 auto", padding:"0 20px 80px" }}>

        {/* Sub-stats */}
        <div style={{
          display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:12,
          marginBottom:32,
          animation:"fadeUp 0.6s ease 0.8s both",
        }}>
          {Object.entries(PROJECTS).filter(([k]) => k !== "other").map(([key, proj], i) => {
            const count = (grouped[key] || []).filter(s => s.status === "shipped").length;
            return (
              <ProjectStatCard key={key} proj={proj} count={count} index={i} />
            );
          })}
        </div>

        {/* Per-project task lists */}
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
          {projectOrder.map((key, i) => (
            <ProjectSection
              key={key}
              projectKey={key}
              ships={grouped[key] || []}
              delay={i * 120 + 400}
            />
          ))}
        </div>

        {/* Footer */}
        <div style={{ textAlign:"center", marginTop:56, animation:"fadeUp 1s ease 1.5s both" }}>
          <div style={{
            display:"inline-flex", alignItems:"center", gap:8,
            fontSize:12, color:"#334155",
            background:"#ffffff06", border:"1px solid #ffffff0d",
            borderRadius:99, padding:"8px 20px",
          }}>
            <span style={{ width:6, height:6, borderRadius:"50%", background:"#22c55e", animation:"pulse 2s infinite" }} />
            Refreshes every 15 seconds
          </div>
        </div>
      </div>
    </div>
  );
}
