"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { usePathname } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import CalendarView from "@/components/execution-hub/calendar-view";
import PipelineBoard from "@/components/execution-hub/pipeline-board";

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

type TaskCategory = "seo" | "llmo" | "gbp" | "schema" | "content" | "technical" | "web-dev";
type TaskPriority = "critical" | "high" | "medium" | "low";
type TaskStatus = "todo" | "in-progress" | "done";

interface Task {
  id: string;
  title: string;
  category: TaskCategory;
  priority: TaskPriority;
  status: TaskStatus;
  assignee: string;
  dueDate: string;
  anticipatedCompletion: string;
  liveDate: string | null;
  completedAt: string | null;
  createdAt: string;
}

// ─── Constants ──────────────────────────────────────────────────────────────

const CATEGORIES: TaskCategory[] = ["seo", "llmo", "gbp", "schema", "content", "technical", "web-dev"];

const CATEGORY_CFG: Record<TaskCategory, { label: string; color: string; bg: string; dot: string }> = {
  seo:       { label: "SEO",        color: "text-blue-700",    bg: "bg-blue-50 border-blue-200",    dot: "bg-blue-500" },
  llmo:      { label: "LLMO",       color: "text-violet-700",  bg: "bg-violet-50 border-violet-200",dot: "bg-violet-500" },
  gbp:       { label: "GBP",        color: "text-emerald-700", bg: "bg-emerald-50 border-emerald-200", dot: "bg-emerald-500" },
  schema:    { label: "Schema",     color: "text-cyan-700",    bg: "bg-cyan-50 border-cyan-200",    dot: "bg-cyan-500" },
  content:   { label: "Content",    color: "text-amber-700",   bg: "bg-amber-50 border-amber-200",  dot: "bg-amber-500" },
  technical: { label: "Technical",  color: "text-rose-700",    bg: "bg-rose-50 border-rose-200",    dot: "bg-rose-500" },
  "web-dev": { label: "Website Development", color: "text-indigo-700", bg: "bg-indigo-50 border-indigo-200", dot: "bg-indigo-500" },
};

const PRIORITY_CFG: Record<TaskPriority, { label: string; color: string; bg: string }> = {
  critical: { label: "Critical", color: "text-red-700",    bg: "bg-red-50 border-red-200" },
  high:     { label: "High",     color: "text-orange-700", bg: "bg-orange-50 border-orange-200" },
  medium:   { label: "Medium",   color: "text-amber-700",  bg: "bg-amber-50 border-amber-200" },
  low:      { label: "Low",      color: "text-gray-600",   bg: "bg-gray-50 border-gray-200" },
};

const STATUS_CFG: Record<TaskStatus, { label: string; color: string; icon: string }> = {
  "todo":        { label: "To Do",       color: "text-gray-500",  icon: "○" },
  "in-progress": { label: "In Progress", color: "text-blue-600",  icon: "◐" },
  "done":        { label: "Done",        color: "text-green-600", icon: "●" },
};

const PRIORITIES: TaskPriority[] = ["critical", "high", "medium", "low"];
const STATUSES: TaskStatus[] = ["todo", "in-progress", "done"];


interface AiExplanation {
  seoLlmoReason: string;
  expectedImpact: string;
  priorityReasoning: string;
}

interface TaskDetail {
  description: string;
  whyItMatters: string;
  relatedPage: string;
  actionSteps: string[];
  ai: AiExplanation;
}

const TASK_DETAILS: Record<string, TaskDetail> = {};


function getTaskDetail(id: string): TaskDetail {
  return TASK_DETAILS[id] ?? {
    description: "Task details are being generated. Check back shortly for a full description and action plan.",
    whyItMatters: "This task contributes to overall SEO and LLMO performance improvements for the site.",
    relatedPage: "—",
    actionSteps: ["Review task requirements", "Implement changes", "Verify and deploy"],
    ai: {
      seoLlmoReason: "This task addresses an optimization gap that affects how search engines and AI models evaluate and reference your content. Completing it will strengthen your visibility in both traditional search results and AI-generated responses.",
      expectedImpact: "Impact assessment will be available once the task details are fully analyzed. Typical tasks in this category yield measurable improvements within 2-6 weeks of implementation.",
      priorityReasoning: "Priority was assigned based on the task's potential impact relative to effort required, its dependencies on other tasks, and the urgency of the underlying issue.",
    },
  };
}

// ─── Recommended Actions ────────────────────────────────────────────────────

type RecommendationSource = "conversion-intelligence" | "site-performance-audit" | "content-briefs";

interface RecommendedAction {
  id: string;
  title: string;
  description: string;
  source: RecommendationSource;
  suggestedCategory: TaskCategory;
  suggestedPriority: TaskPriority;
  page: string;
}

const SOURCE_CFG: Record<RecommendationSource, { label: string; color: string; bg: string; icon: string }> = {
  "conversion-intelligence":  { label: "Conversion Intelligence",  color: "text-teal-700",   bg: "bg-teal-50 border-teal-200",   icon: "↗" },
  "site-performance-audit":   { label: "Core Web Intelligence",    color: "text-blue-700",   bg: "bg-blue-50 border-blue-200",   icon: "⚡" },
  "content-briefs":           { label: "Content Briefs",           color: "text-purple-700",  bg: "bg-purple-50 border-purple-200", icon: "✎" },
};

const RECOMMENDED_ACTIONS: RecommendedAction[] = [
  {
    id: "ra1",
    title: "Fix slow page performance on /pricing",
    description: "LCP is 5.1s and INP is 420ms. Compress images, defer render-blocking scripts, and enable text compression to bring page into green thresholds.",
    source: "site-performance-audit",
    suggestedCategory: "technical",
    suggestedPriority: "critical",
    page: "/pricing",
  },
  {
    id: "ra2",
    title: "Add internal links to service page",
    description: "The /services page has only 1 internal link pointing to it. Add contextual links from blog posts, the homepage, and the about page to improve crawlability and authority flow.",
    source: "conversion-intelligence",
    suggestedCategory: "seo",
    suggestedPriority: "high",
    page: "/services",
  },
  {
    id: "ra3",
    title: "Improve FAQ section for AI visibility",
    description: "Current FAQ uses generic questions. Rewrite with entity-rich, conversational Q&A that LLMs are more likely to cite. Add FAQ-Page schema markup.",
    source: "content-briefs",
    suggestedCategory: "llmo",
    suggestedPriority: "high",
    page: "/pricing",
  },
  {
    id: "ra4",
    title: "Optimize GBP listing with updated photos and hours",
    description: "Google Business Profile has outdated photos (last updated 8 months ago) and missing holiday hours. Refresh photos, verify hours, and respond to 4 unanswered reviews.",
    source: "conversion-intelligence",
    suggestedCategory: "gbp",
    suggestedPriority: "high",
    page: "GBP",
  },
  {
    id: "ra5",
    title: "Reduce CLS on /products page",
    description: "CLS score is 0.12 due to images without explicit dimensions and late-loading ad slots. Add width/height attributes and reserve layout space.",
    source: "site-performance-audit",
    suggestedCategory: "technical",
    suggestedPriority: "medium",
    page: "/products",
  },
  {
    id: "ra6",
    title: "Write comparison content brief: Us vs. Competitor X",
    description: "Search data shows rising queries for brand comparisons. Create a detailed, factual comparison page to capture this traffic and improve LLM brand mentions.",
    source: "content-briefs",
    suggestedCategory: "content",
    suggestedPriority: "medium",
    page: "/blog",
  },
  {
    id: "ra7",
    title: "Add Product schema to all product detail pages",
    description: "8 product pages are missing structured data. Adding Product schema with price, availability, and reviews will enable rich snippets in SERPs.",
    source: "site-performance-audit",
    suggestedCategory: "schema",
    suggestedPriority: "medium",
    page: "/products/*",
  },
  {
    id: "ra8",
    title: "Improve exit-intent conversion on /demo page",
    description: "Bounce rate is 72% with average time-on-page of 18s. Add a clearer value proposition above the fold, simplify the form, and test an exit-intent modal.",
    source: "conversion-intelligence",
    suggestedCategory: "web-dev",
    suggestedPriority: "high",
    page: "/demo",
  },
];

// ─── Helpers ────────────────────────────────────────────────────────────────

function formatTimestamp(iso: string): string {
  const d = new Date(iso);
  const date = d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  const time = d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true });
  return `${date}, ${time}`;
}

function formatDate(dateStr: string | null | undefined): string {
  if (!dateStr) return "—";
  // Handle both ISO timestamps and date-only strings
  const d = new Date(dateStr.includes("T") ? dateStr : dateStr + "T00:00:00");
  if (isNaN(d.getTime())) return "—";
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

// ─── Component ──────────────────────────────────────────────────────────────

// ─── Helpers for mapping backend → frontend shapes ──────────────────────────

function mapCategory(cat: string): TaskCategory {
  const map: Record<string, TaskCategory> = {
    seo: "seo", llmo: "llmo", gbp: "gbp", content: "content",
    technical: "technical", schema: "schema", "web-dev": "web-dev",
  };
  return map[cat] ?? "seo";
}

function mapStatus(status: string): TaskStatus {
  const map: Record<string, TaskStatus> = {
    todo: "todo", in_progress: "in-progress", completed: "done",
  };
  return map[status] ?? "todo";
}

function mapStatusToBackend(status: TaskStatus): string {
  const map: Record<TaskStatus, string> = {
    "todo": "todo", "in-progress": "in_progress", "done": "completed",
  };
  return map[status] ?? "todo";
}

// ─── Page Component ─────────────────────────────────────────────────────────
export default function ExecutionHubPage() {
  const { brand } = useBrand();
  const pathname = usePathname();
  const loadCount = useRef(0);

  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(false);
  const [filterCategory, setFilterCategory] = useState<TaskCategory | "all">("all");
  const [filterPriority, setFilterPriority] = useState<TaskPriority | "all">("all");
  const [filterStatus, setFilterStatus] = useState<TaskStatus | "all">("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [showAddModal, setShowAddModal] = useState(false);
  const [expandedRow, setExpandedRow] = useState<string | null>(null);
  const [detailTaskId, setDetailTaskId] = useState<string | null>(null);
  const [aiRegenerating, setAiRegenerating] = useState(false);
  const [dismissedRecs, setDismissedRecs] = useState<Set<string>>(new Set());
  const [recSourceFilter, setRecSourceFilter] = useState<RecommendationSource | "all">("all");
  const [viewMode, setViewMode] = useState<"list" | "board" | "calendar" | "pipeline">("list");
  const [pipelineData, setPipelineData] = useState<Record<string, Array<{ id: string; title: string; pipelineStage: string | null; contentType: string | null; targetKeyword: string | null; priority: string; dueDate: string | null; assignedTo: string | null; status: string }>>>({});
  const [teamMembers, setTeamMembers] = useState<Array<{ id: string; name: string; email: string; image: string | null; role: string }>>([]);

  // Load team members for assignee selection
  useEffect(() => {
    if (!brand.id) return;
    fetch(`/api/team?brandId=${brand.id}`)
      .then(r => r.ok ? r.json() : [])
      .then(data => { if (Array.isArray(data)) setTeamMembers(data); })
      .catch(() => {});
  }, [brand.id]);

  // Fetch tasks from backend
  const loadTasks = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/tasks?brandId=${brand.id}`, { cache: "no-store" });
      if (!res.ok) throw new Error("Failed to fetch");
      const data = await res.json();

      // Map backend data to frontend Task shape
      const mapped: Task[] = data.map((t: Record<string, unknown>) => ({
        id: t.id as string,
        title: t.title as string,
        category: mapCategory(t.category as string),
        priority: (t.priority as string) || "medium",
        status: mapStatus(t.status as string),
        assignee: (t.assignee as Record<string, string>)?.name || "Unassigned",
        dueDate: t.dueDate ? new Date(t.dueDate as string).toISOString().split("T")[0] : "",
        anticipatedCompletion: t.dueDate ? new Date(t.dueDate as string).toISOString().split("T")[0] : "",
        liveDate: t.completedAt ? new Date(t.completedAt as string).toISOString().split("T")[0] : null,
        completedAt: t.completedAt ? (t.completedAt as string) : null,
        createdAt: t.createdAt as string,
      }));

      setTasks(mapped);
    } catch {
      /* network error */
    }
    setLoading(false);
  }, [brand.id]);

  // Reload on mount, brand change, and when page becomes visible
  useEffect(() => {
    loadTasks();

    // Re-fetch when user returns to this tab/page
    function handleVisibility() {
      if (document.visibilityState === "visible") loadTasks();
    }
    document.addEventListener("visibilitychange", handleVisibility);

    // Re-fetch periodically while page is active (every 10s)
    const interval = setInterval(() => {
      if (document.visibilityState === "visible") loadTasks();
    }, 10000);

    return () => {
      document.removeEventListener("visibilitychange", handleVisibility);
      clearInterval(interval);
    };
  }, [loadTasks]);

  // New task form state
  const [newTitle, setNewTitle] = useState("");
  const [newCategory, setNewCategory] = useState<TaskCategory>("seo");
  const [newPriority, setNewPriority] = useState<TaskPriority>("medium");
  const [newAssignee, setNewAssignee] = useState("");
  const [newDueDate, setNewDueDate] = useState("");
  const [newAnticipated, setNewAnticipated] = useState("");

  // Load pipeline data when pipeline view is active
  useEffect(() => {
    if (viewMode !== "pipeline" || !brand.id) return;
    fetch(`/api/tasks/pipeline?brandId=${brand.id}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => { if (d?.pipeline) setPipelineData(d.pipeline); })
      .catch(() => {});
  }, [viewMode, brand.id]);

  async function handleReschedule(taskId: string, date: string) {
    await fetch(`/api/tasks/${taskId}/reschedule`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ dueDate: date }) });
    loadTasks();
  }

  async function handleStageChange(taskId: string, stage: string) {
    await fetch(`/api/tasks/${taskId}/stage`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pipelineStage: stage }) });
    // Reload pipeline
    const res = await fetch(`/api/tasks/pipeline?brandId=${brand.id}`);
    if (res.ok) { const d = await res.json(); if (d?.pipeline) setPipelineData(d.pipeline); }
  }

  // Filter
  const filtered = tasks.filter((t) => {
    if (filterCategory !== "all" && t.category !== filterCategory) return false;
    if (filterPriority !== "all" && t.priority !== filterPriority) return false;
    if (filterStatus !== "all" && t.status !== filterStatus) return false;
    if (searchQuery && !t.title.toLowerCase().includes(searchQuery.toLowerCase())) return false;
    return true;
  });

  // Stats
  const total = tasks.length;
  const todo = tasks.filter((t) => t.status === "todo").length;
  const inProgress = tasks.filter((t) => t.status === "in-progress").length;
  const done = tasks.filter((t) => t.status === "done").length;

  async function handleAddTask() {
    if (!newTitle.trim() || !newDueDate) return;

    // Capture values before clearing
    const assigneeId = newAssignee;
    const assigneeName = teamMembers.find(m => m.id === assigneeId)?.name || "Unassigned";

    // Optimistic local add
    const now = new Date().toISOString();
    const tempId = `t${Date.now()}`;
    const task: Task = {
      id: tempId,
      title: newTitle.trim(),
      category: newCategory,
      priority: newPriority,
      status: "todo",
      assignee: assigneeName,
      dueDate: newDueDate,
      anticipatedCompletion: newAnticipated || newDueDate,
      liveDate: null,
      completedAt: null,
      createdAt: now,
    };
    setTasks((prev) => [task, ...prev]);
    setNewTitle("");
    setNewCategory("seo");
    setNewPriority("medium");
    setNewAssignee("");
    setNewDueDate("");
    setNewAnticipated("");
    setShowAddModal(false);

    // Save to backend
    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId: brand.id,
          title: task.title,
          category: task.category,
          priority: task.priority,
          effort: "medium",
          dueDate: task.dueDate,
          assignedTo: assigneeId || undefined,
        }),
      });
      if (res.ok) {
        const created = await res.json();
        // Replace temp ID with real ID
        setTasks((prev) => prev.map((t) => (t.id === tempId ? { ...t, id: created.id } : t)));
      }
    } catch {
      // Task already added locally — will sync on next load
    }
  }

  // Recommended actions
  const visibleRecs = RECOMMENDED_ACTIONS
    .filter((r) => !dismissedRecs.has(r.id))
    .filter((r) => recSourceFilter === "all" || r.source === recSourceFilter);

  function addRecAsTask(rec: RecommendedAction) {
    const now = new Date().toISOString();
    const task: Task = {
      id: `t${Date.now()}`,
      title: rec.title,
      category: rec.suggestedCategory,
      priority: rec.suggestedPriority,
      status: "todo",
      assignee: "",
      dueDate: "",
      anticipatedCompletion: "",
      liveDate: null,
      completedAt: null,
      createdAt: now,
    };
    setTasks((prev) => [task, ...prev]);
    setDismissedRecs((prev) => new Set(prev).add(rec.id));
  }

  function dismissRec(id: string) {
    setDismissedRecs((prev) => new Set(prev).add(id));
  }

  function cycleStatus(id: string) {
    const task = tasks.find((t) => t.id === id);
    if (!task) return;

    const next: TaskStatus = task.status === "todo" ? "in-progress" : task.status === "in-progress" ? "done" : "todo";

    // Optimistic update
    setTasks((prev) =>
      prev.map((t) => {
        if (t.id !== id) return t;
        return {
          ...t,
          status: next,
          liveDate: next === "done" ? new Date().toISOString().slice(0, 10) : null,
          completedAt: next === "done" ? new Date().toISOString() : null,
        };
      })
    );

    // Sync to backend
    fetch("/api/tasks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        action: "update",
        taskId: id,
        status: mapStatusToBackend(next),
      }),
    }).catch(() => {
      // Revert on failure
      setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, status: task.status, liveDate: task.liveDate } : t)));
    });
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-6 py-10 space-y-6">
        {/* ── Header ── */}
        <div>
          <div className="flex items-start justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-violet-500 flex items-center justify-center shrink-0">
                <svg className="w-5 h-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 11l3 3L22 4" /><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
                </svg>
              </div>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">Execution Hub</h1>
                <p className="text-gray-500 text-sm mt-0.5">
                  Track and manage optimization tasks across SEO, LLMO, and local.
                </p>
              </div>
            </div>
            <button
              onClick={() => setShowAddModal(true)}
              className="px-4 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-violet-600 text-white text-sm font-semibold hover:from-blue-700 hover:to-violet-700 transition-colors flex items-center gap-2 shadow-sm shrink-0"
            >
              <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 5v14" /><path d="M5 12h14" />
              </svg>
              Add Task
            </button>
          </div>
        </div>

        {/* ── Stats bar ── */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {[
            { label: "Total", value: total, color: "text-gray-900", bg: "bg-white" },
            { label: "To Do", value: todo, color: "text-gray-500", bg: "bg-white" },
            { label: "In Progress", value: inProgress, color: "text-blue-600", bg: "bg-blue-50" },
            { label: "Done", value: done, color: "text-green-600", bg: "bg-green-50" },
          ].map((stat) => (
            <div key={stat.label} className={`${stat.bg} rounded-xl border border-gray-200 px-4 py-3 shadow-sm`}>
              <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400">{stat.label}</p>
              <p className={`text-2xl font-bold mt-1 ${stat.color}`}>{stat.value}</p>
            </div>
          ))}
        </div>

        {/* ── Recommended Actions ── */}
        {visibleRecs.length > 0 && (
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
            {/* Section header */}
            <div className="px-6 py-4 border-b border-gray-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div className="flex items-center gap-2.5">
                <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center">
                  <svg className="w-3.5 h-3.5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 1 1 7.072 0l-.548.547A3.374 3.374 0 0 0 14 18.469V19a2 2 0 1 1-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                  </svg>
                </div>
                <div>
                  <h2 className="font-semibold text-gray-800 text-sm">Recommended Actions</h2>
                  <p className="text-[11px] text-gray-400">AI-generated tasks from your audits and analytics</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <select
                  value={recSourceFilter}
                  onChange={(e) => setRecSourceFilter(e.target.value as RecommendationSource | "all")}
                  className="px-2.5 py-1.5 rounded-lg border border-gray-200 text-xs text-gray-600 focus:outline-none focus:ring-2 focus:ring-amber-500/30"
                >
                  <option value="all">All Sources</option>
                  {(Object.keys(SOURCE_CFG) as RecommendationSource[]).map((s) => (
                    <option key={s} value={s}>{SOURCE_CFG[s].label}</option>
                  ))}
                </select>
                <span className="text-[10px] text-gray-400 font-medium">{visibleRecs.length} pending</span>
              </div>
            </div>

            {/* Cards grid */}
            <div className="px-5 py-4 grid grid-cols-1 md:grid-cols-2 gap-3">
              {visibleRecs.map((rec) => {
                const src = SOURCE_CFG[rec.source];
                const cat = CATEGORY_CFG[rec.suggestedCategory];
                const pri = PRIORITY_CFG[rec.suggestedPriority];
                return (
                  <div
                    key={rec.id}
                    className="border border-gray-150 rounded-xl px-4 py-3.5 hover:border-gray-300 hover:shadow-sm transition-all bg-gray-50/30"
                  >
                    {/* Source + page */}
                    <div className="flex items-center gap-2 mb-2">
                      <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border ${src.bg} ${src.color}`}>
                        {src.icon} {src.label}
                      </span>
                      <span className="text-[10px] text-gray-400 font-mono ml-auto">{rec.page}</span>
                    </div>

                    {/* Title */}
                    <h3 className="text-sm font-semibold text-gray-800 leading-snug mb-1">{rec.title}</h3>

                    {/* Description */}
                    <p className="text-xs text-gray-500 leading-relaxed mb-3 line-clamp-2">{rec.description}</p>

                    {/* Suggested tags + actions */}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded-full border ${cat.bg} ${cat.color}`}>
                          {cat.label}
                        </span>
                        <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded-full border ${pri.bg} ${pri.color}`}>
                          {pri.label}
                        </span>
                      </div>
                      <div className="flex items-center gap-1.5">
                        <button
                          onClick={() => dismissRec(rec.id)}
                          className="px-2.5 py-1 rounded-md text-[11px] font-medium text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
                        >
                          Dismiss
                        </button>
                        <button
                          onClick={() => addRecAsTask(rec)}
                          className="px-2.5 py-1 rounded-md text-[11px] font-semibold text-blue-600 bg-blue-50 hover:bg-blue-100 transition-colors flex items-center gap-1"
                        >
                          <svg className="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M12 5v14" /><path d="M5 12h14" />
                          </svg>
                          Add to Tasks
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* ── Filters ── */}
        <div className="bg-white rounded-xl border border-gray-200 px-5 py-3.5 shadow-sm">
          <div className="flex flex-col md:flex-row items-stretch md:items-center gap-3">
            {/* Search */}
            <div className="relative flex-1">
              <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
              </svg>
              <input
                type="text"
                placeholder="Search tasks..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-9 pr-3 py-2 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-300"
              />
            </div>

            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value as TaskCategory | "all")}
              className="px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
            >
              <option value="all">All Categories</option>
              {CATEGORIES.map((c) => (
                <option key={c} value={c}>{CATEGORY_CFG[c].label}</option>
              ))}
            </select>

            <select
              value={filterPriority}
              onChange={(e) => setFilterPriority(e.target.value as TaskPriority | "all")}
              className="px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
            >
              <option value="all">All Priorities</option>
              {PRIORITIES.map((p) => (
                <option key={p} value={p}>{PRIORITY_CFG[p].label}</option>
              ))}
            </select>

            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value as TaskStatus | "all")}
              className="px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
            >
              <option value="all">All Statuses</option>
              {STATUSES.map((s) => (
                <option key={s} value={s}>{STATUS_CFG[s].label}</option>
              ))}
            </select>

            {/* View toggle */}
            <div className="flex items-center bg-gray-100 rounded-lg p-1 gap-1 shrink-0">
              <button
                onClick={() => setViewMode("list")}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                  viewMode === "list" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"
                }`}
              >
                <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="8" x2="21" y1="6" y2="6" /><line x1="8" x2="21" y1="12" y2="12" /><line x1="8" x2="21" y1="18" y2="18" /><line x1="3" x2="3.01" y1="6" y2="6" /><line x1="3" x2="3.01" y1="12" y2="12" /><line x1="3" x2="3.01" y1="18" y2="18" />
                </svg>
                List
              </button>
              <button
                onClick={() => setViewMode("board")}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                  viewMode === "board" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"
                }`}
              >
                <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect width="7" height="18" x="3" y="3" rx="1" /><rect width="7" height="18" x="14" y="3" rx="1" />
                </svg>
                Board
              </button>
              <button
                onClick={() => setViewMode("calendar")}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                  viewMode === "calendar" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"
                }`}
              >
                <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect width="18" height="18" x="3" y="4" rx="2" ry="2" /><line x1="16" x2="16" y1="2" y2="6" /><line x1="8" x2="8" y1="2" y2="6" /><line x1="3" x2="21" y1="10" y2="10" />
                </svg>
                Calendar
              </button>
              <button
                onClick={() => setViewMode("pipeline")}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${
                  viewMode === "pipeline" ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"
                }`}
              >
                <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 3v18" /><rect width="6" height="8" x="3" y="8" rx="1" /><rect width="6" height="12" x="15" y="6" rx="1" />
                </svg>
                Pipeline
              </button>
            </div>
          </div>
        </div>

        {/* ── List View ── */}
        {viewMode === "list" && (
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50/80 border-b border-gray-200">
                    <th className="text-left px-5 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400 w-8"></th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Task Name</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Category</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Priority</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Status</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Assignee</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Created</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Due</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Anticipated</th>
                    <th className="text-left px-3 py-3 text-[10px] font-bold uppercase tracking-widest text-gray-400">Completed</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {filtered.map((task) => {
                    const cat = CATEGORY_CFG[task.category];
                    const pri = PRIORITY_CFG[task.priority];
                    const st = STATUS_CFG[task.status];
                    const isExpanded = expandedRow === task.id;

                    // Urgency calculation
                    const now = new Date();
                    const dueDate = task.dueDate ? new Date(task.dueDate.includes("T") ? task.dueDate : task.dueDate + "T23:59:59") : null;
                    const daysUntilDue = dueDate ? Math.ceil((dueDate.getTime() - now.getTime()) / 86400000) : null;
                    const isOverdue = task.status !== "done" && daysUntilDue !== null && daysUntilDue < 0;
                    const isDueSoon = task.status !== "done" && daysUntilDue !== null && daysUntilDue >= 0 && daysUntilDue <= 3;
                    const isCompleted = task.status === "done";

                    const rowBg = isOverdue ? "bg-red-50/40 hover:bg-red-50/60" :
                                  isDueSoon ? "bg-orange-50/30 hover:bg-orange-50/50" :
                                  isCompleted ? "bg-green-50/20 hover:bg-green-50/40" :
                                  "hover:bg-gray-50/50";

                    const urgencyTag = isOverdue ? { label: "Overdue", cls: "text-red-700 bg-red-100 border-red-200" } :
                                       isDueSoon ? { label: daysUntilDue === 0 ? "Due today" : `Due in ${daysUntilDue}d`, cls: "text-orange-700 bg-orange-100 border-orange-200" } :
                                       isCompleted ? { label: "Done", cls: "text-green-700 bg-green-100 border-green-200" } :
                                       null;

                    return (
                      <tr
                        key={task.id}
                        className={`group transition-colors cursor-pointer ${rowBg} ${isOverdue ? "border-l-2 border-l-red-400" : isDueSoon ? "border-l-2 border-l-orange-400" : isCompleted ? "border-l-2 border-l-green-400" : ""}`}
                        onClick={() => { setDetailTaskId(task.id); setExpandedRow(isExpanded ? null : task.id); }}
                      >
                        {/* Status toggle */}
                        <td className="px-5 py-3">
                          <button
                            onClick={(e) => { e.stopPropagation(); cycleStatus(task.id); }}
                            className={`text-base leading-none hover:scale-110 transition-transform ${isOverdue ? "text-red-500" : isCompleted ? "text-green-500" : st.color}`}
                            title={`Click to change status (${st.label})`}
                          >
                            {st.icon}
                          </button>
                        </td>

                        {/* Task name + urgency tag */}
                        <td className="px-3 py-3 min-w-[220px]">
                          <div className="flex items-center gap-2">
                            <p className={`font-semibold leading-snug ${isCompleted ? "line-through text-gray-400" : isOverdue ? "text-red-800" : "text-gray-800"}`}>
                              {task.title}
                            </p>
                            {urgencyTag && (
                              <span className={`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${urgencyTag.cls}`}>
                                {urgencyTag.label}
                              </span>
                            )}
                          </div>
                          {isExpanded && (
                            <p className="text-[10px] text-gray-400 mt-1">
                              Created: {formatTimestamp(task.createdAt)}
                            </p>
                          )}
                        </td>

                        {/* Category */}
                        <td className="px-3 py-3">
                          <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border whitespace-nowrap ${cat.bg} ${cat.color}`}>
                            {cat.label}
                          </span>
                        </td>

                        {/* Priority */}
                        <td className="px-3 py-3">
                          <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border whitespace-nowrap ${pri.bg} ${pri.color}`}>
                            {pri.label}
                          </span>
                        </td>

                        {/* Status */}
                        <td className="px-3 py-3">
                          <span className={`text-xs font-semibold whitespace-nowrap ${st.color}`}>
                            {st.label}
                          </span>
                        </td>

                        {/* Assignee */}
                        <td className="px-3 py-3">
                          <div className="flex items-center gap-1.5">
                            <div className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-[10px] font-bold text-gray-500 shrink-0">
                              {task.assignee.charAt(0)}
                            </div>
                            <span className="text-xs text-gray-700">{task.assignee}</span>
                          </div>
                        </td>

                        {/* Created */}
                        <td className="px-3 py-3">
                          <span className="text-xs text-gray-400 whitespace-nowrap">{formatDate(task.createdAt)}</span>
                        </td>

                        {/* Due date — inline editable */}
                        <td className="px-3 py-3">
                          <input
                            type="date"
                            value={task.dueDate || ""}
                            onChange={(e) => {
                              const val = e.target.value;
                              setTasks(prev => prev.map(t => t.id === task.id ? { ...t, dueDate: val } : t));
                              fetch("/api/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "update", taskId: task.id, dueDate: val }) });
                            }}
                            className="text-xs text-gray-600 bg-transparent border-0 p-0 focus:outline-none focus:ring-0 cursor-pointer w-24"
                          />
                        </td>

                        {/* Anticipated — inline editable */}
                        <td className="px-3 py-3">
                          <input
                            type="date"
                            value={task.anticipatedCompletion || ""}
                            onChange={(e) => {
                              const val = e.target.value;
                              setTasks(prev => prev.map(t => t.id === task.id ? { ...t, anticipatedCompletion: val } : t));
                            }}
                            className="text-xs text-gray-500 bg-transparent border-0 p-0 focus:outline-none focus:ring-0 cursor-pointer w-24"
                          />
                        </td>

                        {/* Completed / Live date — editable */}
                        <td className="px-3 py-3">
                          <input
                            type="date"
                            value={(task.completedAt ? task.completedAt.split("T")[0] : task.liveDate) || ""}
                            onChange={(e) => {
                              const val = e.target.value;
                              setTasks(prev => prev.map(t => t.id === task.id ? { ...t, completedAt: val, liveDate: val } : t));
                              fetch("/api/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "update", taskId: task.id, status: "completed" }) });
                            }}
                            className={`text-xs bg-transparent border-0 p-0 focus:outline-none focus:ring-0 cursor-pointer w-24 ${(task.completedAt || task.liveDate) ? "text-green-600 font-semibold" : "text-gray-300"}`}
                          />
                        </td>
                      </tr>
                    );
                  })}
                  {filtered.length === 0 && (
                    <tr>
                      <td colSpan={9} className="px-6 py-12 text-center text-sm text-gray-400">
                        No tasks match your filters.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
            {/* Footer count */}
            <div className="px-5 py-2.5 border-t border-gray-100 bg-gray-50/50">
              <p className="text-xs text-gray-400">
                Showing {filtered.length} of {tasks.length} tasks
              </p>
            </div>
          </div>
        )}

        {/* ── Board View (Kanban) ── */}
        {viewMode === "board" && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            {STATUSES.map((status) => {
              const cfg = STATUS_CFG[status];
              const columnTasks = filtered.filter((t) => t.status === status);
              const colBorder = status === "todo" ? "border-t-gray-300" : status === "in-progress" ? "border-t-blue-500" : "border-t-green-500";
              return (
                <div key={status} className="flex flex-col">
                  {/* Column header */}
                  <div className={`bg-white rounded-t-xl border border-gray-200 border-t-[3px] ${colBorder} px-4 py-3 flex items-center justify-between`}>
                    <div className="flex items-center gap-2">
                      <span className={`text-sm ${cfg.color}`}>{cfg.icon}</span>
                      <span className="text-sm font-semibold text-gray-800">{cfg.label}</span>
                    </div>
                    <span className="text-xs text-gray-400 bg-gray-100 rounded-full px-2 py-0.5 font-semibold tabular-nums">{columnTasks.length}</span>
                  </div>

                  {/* Cards */}
                  <div className="bg-gray-50/50 border border-t-0 border-gray-200 rounded-b-xl p-2.5 space-y-2.5 min-h-[200px] flex-1">
                    {columnTasks.map((task) => {
                      const cat = CATEGORY_CFG[task.category];
                      const pri = PRIORITY_CFG[task.priority];
                      return (
                        <div key={task.id} onClick={() => setDetailTaskId(task.id)} className="bg-white rounded-lg border border-gray-200 px-3.5 py-3 shadow-sm hover:shadow-md transition-shadow cursor-pointer">
                          {/* Badges row */}
                          <div className="flex items-center gap-1.5 mb-2">
                            <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded-full border ${cat.bg} ${cat.color}`}>
                              {cat.label}
                            </span>
                            <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded-full border ${pri.bg} ${pri.color}`}>
                              {pri.label}
                            </span>
                          </div>

                          {/* Title */}
                          <h3 className={`text-sm font-semibold leading-snug mb-2 ${task.status === "done" ? "line-through text-gray-400" : "text-gray-800"}`}>
                            {task.title}
                          </h3>

                          {/* Meta */}
                          <div className="flex items-center justify-between text-[11px] text-gray-400 mb-2.5">
                            {task.assignee ? (
                              <div className="flex items-center gap-1">
                                <div className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-[9px] font-bold text-gray-500">
                                  {task.assignee.charAt(0)}
                                </div>
                                <span>{task.assignee}</span>
                              </div>
                            ) : (
                              <span className="text-gray-300">Unassigned</span>
                            )}
                            {task.dueDate && (
                              <span>Due {formatDate(task.dueDate)}</span>
                            )}
                          </div>

                          {/* Dates row */}
                          <div className="flex items-center gap-3 pt-2 border-t border-gray-50 text-[10px] text-gray-400">
                            {task.anticipatedCompletion && (
                              <span>Est. {formatDate(task.anticipatedCompletion)}</span>
                            )}
                            {task.liveDate && (
                              <span className="text-green-600 font-semibold">Live {formatDate(task.liveDate)}</span>
                            )}
                          </div>

                          {/* Status action */}
                          <div className="mt-2.5">
                            <button
                              onClick={() => cycleStatus(task.id)}
                              className="w-full text-center text-[11px] font-semibold py-1.5 rounded-md border border-gray-150 text-gray-500 hover:bg-gray-50 hover:text-gray-700 transition-colors"
                            >
                              {task.status === "todo" ? "Start Task →" : task.status === "in-progress" ? "Mark Complete ✓" : "Reopen ↩"}
                            </button>
                          </div>
                        </div>
                      );
                    })}
                    {columnTasks.length === 0 && (
                      <div className="flex items-center justify-center h-full min-h-[120px]">
                        <p className="text-xs text-gray-400">No tasks</p>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ── Calendar View ── */}
        {viewMode === "calendar" && (
          <CalendarView
            tasks={filtered.map((t) => ({ id: t.id, title: t.title, status: t.status, dueDate: t.dueDate ?? null, priority: t.priority }))}
            onReschedule={handleReschedule}
            onClickTask={(id) => setDetailTaskId(id)}
            onClickDate={(date) => { setNewDueDate(date); setShowAddModal(true); }}
          />
        )}

        {/* ── Pipeline View ── */}
        {viewMode === "pipeline" && (
          <PipelineBoard
            pipeline={pipelineData}
            onStageChange={handleStageChange}
            onClickTask={(id) => setDetailTaskId(id)}
          />
        )}

        {/* ── Category breakdown ── */}
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
          {CATEGORIES.map((cat) => {
            const cfg = CATEGORY_CFG[cat];
            const catTasks = tasks.filter((t) => t.category === cat);
            const catDone = catTasks.filter((t) => t.status === "done").length;
            const pct = catTasks.length > 0 ? Math.round((catDone / catTasks.length) * 100) : 0;
            return (
              <div key={cat} className="bg-white rounded-xl border border-gray-200 px-4 py-3 shadow-sm">
                <div className="flex items-center gap-1.5 mb-2">
                  <div className={`w-2 h-2 rounded-full ${cfg.dot}`} />
                  <span className="text-xs font-semibold text-gray-700 truncate">{cfg.label}</span>
                </div>
                <div className="w-full h-1.5 bg-gray-100 rounded-full overflow-hidden">
                  <div className={`h-full rounded-full ${cfg.dot}`} style={{ width: `${pct}%` }} />
                </div>
                <p className="text-[10px] text-gray-400 mt-1.5">{catDone}/{catTasks.length} done</p>
              </div>
            );
          })}
        </div>
      </div>

      {/* ══════════════════════════════════════════════════════════════════════
          ADD TASK MODAL
          ══════════════════════════════════════════════════════════════════════ */}
      {showAddModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* Backdrop */}
          <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => setShowAddModal(false)} />

          {/* Modal */}
          <div className="relative bg-white rounded-2xl shadow-xl border border-gray-200 w-full max-w-lg mx-4 overflow-hidden">
            {/* Header */}
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
              <h2 className="font-semibold text-gray-900">New Task</h2>
              <button onClick={() => setShowAddModal(false)} className="text-gray-400 hover:text-gray-600 transition-colors">
                <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M18 6 6 18" /><path d="m6 6 12 12" />
                </svg>
              </button>
            </div>

            {/* Body */}
            <div className="px-6 py-5 space-y-4">
              {/* Task name */}
              <div>
                <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Task Name</label>
                <input
                  type="text"
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                  placeholder="e.g., Fix broken canonical tags"
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-300"
                />
              </div>

              {/* Category + Priority */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Category</label>
                  <select
                    value={newCategory}
                    onChange={(e) => setNewCategory(e.target.value as TaskCategory)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                  >
                    {CATEGORIES.map((c) => (
                      <option key={c} value={c}>{CATEGORY_CFG[c].label}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Priority</label>
                  <select
                    value={newPriority}
                    onChange={(e) => setNewPriority(e.target.value as TaskPriority)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                  >
                    {PRIORITIES.map((p) => (
                      <option key={p} value={p}>{PRIORITY_CFG[p].label}</option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Assignee */}
              <div>
                <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Assigned To</label>
                {teamMembers.length > 0 ? (
                  <select
                    value={newAssignee}
                    onChange={(e) => setNewAssignee(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-300 bg-white"
                  >
                    <option value="">Select assignee...</option>
                    {teamMembers.map((m) => (
                      <option key={m.id} value={m.id}>{m.name} ({m.email})</option>
                    ))}
                  </select>
                ) : (
                  <p className="text-xs text-slate-400 py-2">No team members found. <a href="/settings" className="text-brand-600 hover:text-brand-700 font-semibold">Add people →</a></p>
                )}
              </div>

              {/* Due date + Anticipated */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Due Date</label>
                  <input
                    type="date"
                    value={newDueDate}
                    onChange={(e) => setNewDueDate(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1 block">Anticipated Completion</label>
                  <input
                    type="date"
                    value={newAnticipated}
                    onChange={(e) => setNewAnticipated(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                  />
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="px-6 py-4 border-t border-gray-100 bg-gray-50/50 flex items-center justify-between">
              <p className="text-[10px] text-gray-400">
                Will be created with timestamp and &quot;To Do&quot; status
              </p>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowAddModal(false)}
                  className="px-4 py-2 rounded-lg border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-100 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleAddTask}
                  disabled={!newTitle.trim() || !newDueDate}
                  className="px-4 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-violet-600 text-white text-sm font-semibold hover:from-blue-700 hover:to-violet-700 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
                >
                  Add Task
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════════════════════
          TASK DETAIL PANEL (slide-over)
          ══════════════════════════════════════════════════════════════════════ */}
      {detailTaskId && (() => {
        const task = tasks.find((t) => t.id === detailTaskId);
        if (!task) return null;
        const detail = getTaskDetail(task.id);
        const cat = CATEGORY_CFG[task.category];
        const pri = PRIORITY_CFG[task.priority];
        const st = STATUS_CFG[task.status];

        return (
          <>
            {/* Backdrop */}
            <div className="fixed inset-0 z-40 bg-black/30 backdrop-blur-sm" onClick={() => setDetailTaskId(null)} />

            {/* Panel */}
            <div className="fixed inset-y-0 right-0 z-50 w-full max-w-lg bg-white shadow-2xl border-l border-gray-200 flex flex-col">
              {/* Header */}
              <div className="px-6 py-4 border-b border-gray-100 flex items-start justify-between shrink-0">
                <div className="flex-1 min-w-0 pr-4">
                  <div className="flex items-center gap-2 mb-2">
                    <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border ${cat.bg} ${cat.color}`}>
                      {cat.label}
                    </span>
                    <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border ${pri.bg} ${pri.color}`}>
                      {pri.label}
                    </span>
                    <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full border ${st.color === "text-gray-500" ? "bg-gray-50 border-gray-200 text-gray-600" : st.color === "text-blue-600" ? "bg-blue-50 border-blue-200 text-blue-700" : "bg-green-50 border-green-200 text-green-700"}`}>
                      {st.icon} {st.label}
                    </span>
                  </div>
                  <h2 className="text-lg font-bold text-gray-900 leading-snug">{task.title}</h2>
                </div>
                <button onClick={() => setDetailTaskId(null)} className="text-gray-400 hover:text-gray-600 transition-colors mt-1 shrink-0">
                  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M18 6 6 18" /><path d="m6 6 12 12" />
                  </svg>
                </button>
              </div>

              {/* Scrollable body */}
              <div className="flex-1 overflow-y-auto px-6 py-5 space-y-6">
                {/* Meta bar */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1">Assigned To</p>
                    {task.assignee ? (
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-gradient-to-br from-blue-500 to-violet-500 flex items-center justify-center text-[11px] font-bold text-white">
                          {task.assignee.charAt(0)}
                        </div>
                        <span className="text-sm font-semibold text-gray-800">{task.assignee}</span>
                      </div>
                    ) : (
                      <span className="text-sm text-gray-400">Unassigned</span>
                    )}
                  </div>
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1">Related Page</p>
                    <span className="text-sm font-mono font-semibold text-blue-600">{detail.relatedPage}</span>
                  </div>
                </div>

                {/* Dates — editable */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1.5">Due Date</p>
                    <input
                      type="date"
                      value={task.dueDate || ""}
                      onChange={(e) => {
                        const val = e.target.value;
                        setTasks(prev => prev.map(t => t.id === task.id ? { ...t, dueDate: val } : t));
                        fetch("/api/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "update", taskId: task.id, dueDate: val }) });
                      }}
                      className="w-full px-2 py-1.5 rounded border border-gray-200 text-xs text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                    />
                  </div>
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1.5">Anticipated Completion</p>
                    <input
                      type="date"
                      value={task.anticipatedCompletion || ""}
                      onChange={(e) => {
                        const val = e.target.value;
                        setTasks(prev => prev.map(t => t.id === task.id ? { ...t, anticipatedCompletion: val } : t));
                      }}
                      className="w-full px-2 py-1.5 rounded border border-gray-200 text-xs text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                    />
                  </div>
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1">Created</p>
                    <span className="text-xs font-semibold text-gray-500">{formatDate(task.createdAt)}</span>
                  </div>
                  <div className="bg-gray-50 rounded-lg px-3.5 py-2.5">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-1.5">Completed / Live Date</p>
                    <input
                      type="date"
                      value={(task.completedAt ? task.completedAt.split("T")[0] : task.liveDate) || ""}
                      onChange={(e) => {
                        const val = e.target.value;
                        setTasks(prev => prev.map(t => t.id === task.id ? { ...t, completedAt: val, liveDate: val } : t));
                        fetch("/api/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "update", taskId: task.id, status: "completed" }) });
                      }}
                      className="w-full px-2 py-1.5 rounded border border-gray-200 text-xs text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
                    />
                  </div>
                </div>

                {/* Description */}
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-2">Description</h3>
                  <p className="text-sm text-gray-700 leading-relaxed">{detail.description}</p>
                </div>

                {/* Why It Matters */}
                <div className="bg-gradient-to-br from-blue-50 to-violet-50 rounded-xl border border-blue-100 px-5 py-4">
                  <div className="flex items-center gap-2 mb-2">
                    <svg className="w-4 h-4 text-blue-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 1 1 7.072 0l-.548.547A3.374 3.374 0 0 0 14 18.469V19a2 2 0 1 1-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                    <h3 className="text-xs font-bold uppercase tracking-widest text-blue-700">Why It Matters</h3>
                  </div>
                  <p className="text-sm text-gray-700 leading-relaxed">{detail.whyItMatters}</p>
                </div>

                {/* AI Explanation */}
                <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
                  <div className="px-5 py-3.5 border-b border-gray-100 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-lg bg-gradient-to-br from-blue-500 to-violet-500 flex items-center justify-center">
                        <svg className="w-3 h-3 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M12 3v2m0 14v2M5.6 5.6l1.4 1.4m10 10 1.4 1.4M3 12h2m14 0h2M5.6 18.4l1.4-1.4m10-10 1.4-1.4" />
                        </svg>
                      </div>
                      <h3 className="text-xs font-bold uppercase tracking-widest text-gray-700">AI Explanation</h3>
                      <span className="text-[9px] text-gray-400 font-medium">Powered by AI</span>
                    </div>
                    <button
                      onClick={() => {
                        setAiRegenerating(true);
                        setTimeout(() => setAiRegenerating(false), 1500);
                      }}
                      disabled={aiRegenerating}
                      className="flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-semibold text-gray-500 hover:text-gray-700 hover:bg-gray-50 border border-gray-200 transition-colors disabled:opacity-50"
                    >
                      <svg className={`w-3 h-3 ${aiRegenerating ? "animate-spin" : ""}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" />
                      </svg>
                      {aiRegenerating ? "Regenerating..." : "Regenerate"}
                    </button>
                  </div>
                  <div className={`px-5 py-4 space-y-4 ${aiRegenerating ? "opacity-40" : ""} transition-opacity`}>
                    {/* Why this improves SEO / LLMO */}
                    <div>
                      <div className="flex items-center gap-1.5 mb-1.5">
                        <div className="w-1.5 h-1.5 rounded-full bg-blue-500" />
                        <p className="text-[10px] font-bold uppercase tracking-widest text-blue-600">Why This Improves SEO / LLMO</p>
                      </div>
                      <p className="text-sm text-gray-700 leading-relaxed">{detail.ai.seoLlmoReason}</p>
                    </div>

                    {/* Expected Impact */}
                    <div>
                      <div className="flex items-center gap-1.5 mb-1.5">
                        <div className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                        <p className="text-[10px] font-bold uppercase tracking-widest text-emerald-600">Expected Impact</p>
                      </div>
                      <p className="text-sm text-gray-700 leading-relaxed">{detail.ai.expectedImpact}</p>
                    </div>

                    {/* Priority Reasoning */}
                    <div>
                      <div className="flex items-center gap-1.5 mb-1.5">
                        <div className="w-1.5 h-1.5 rounded-full bg-amber-500" />
                        <p className="text-[10px] font-bold uppercase tracking-widest text-amber-600">Priority Reasoning</p>
                      </div>
                      <p className="text-sm text-gray-700 leading-relaxed">{detail.ai.priorityReasoning}</p>
                    </div>
                  </div>
                </div>

                {/* Recommended Action Steps */}
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-3">Recommended Action Steps</h3>
                  <div className="space-y-2">
                    {detail.actionSteps.map((step, i) => (
                      <div key={i} className="flex items-start gap-3">
                        <div className="w-5 h-5 rounded-full bg-gray-100 border border-gray-200 flex items-center justify-center shrink-0 mt-0.5">
                          <span className="text-[10px] font-bold text-gray-500">{i + 1}</span>
                        </div>
                        <p className="text-sm text-gray-700 leading-relaxed">{step}</p>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Created timestamp */}
                <div className="pt-4 border-t border-gray-100">
                  <p className="text-[11px] text-gray-400">Created: {formatTimestamp(task.createdAt)}</p>
                </div>
              </div>

              {/* Footer actions */}
              <div className="px-6 py-4 border-t border-gray-100 bg-gray-50/50 flex items-center justify-between shrink-0">
                <button
                  onClick={() => setDetailTaskId(null)}
                  className="px-4 py-2 rounded-lg border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-100 transition-colors"
                >
                  Close
                </button>
                <button
                  onClick={() => { cycleStatus(task.id); }}
                  className="px-4 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-violet-600 text-white text-sm font-semibold hover:from-blue-700 hover:to-violet-700 transition-colors"
                >
                  {task.status === "todo" ? "Start Task →" : task.status === "in-progress" ? "Mark Complete ✓" : "Reopen ↩"}
                </button>
              </div>
            </div>
          </>
        );
      })()}
    </div>
  );
}
