const { useState, useEffect, useRef, useMemo } = React;

// ─── Icons (inline SVGs) ─────────────────────────────────────────────────────
const Icons = {
  search: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
  ),
  mic: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
  ),
  micOff: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="1" y1="1" x2="23" y2="23"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .76-.13 1.49-.35 2.17"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
  ),
  check: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
  ),
  checkCircle: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  ),
  phone: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
  ),
  mail: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
  ),
  file: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
  ),
  clock: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
  ),
  arrowUp: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
  ),
  arrowDown: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>
  ),
  plus: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
  ),
  flag: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>
  ),
  zap: (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
  ),
  calendar: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
  ),
  reply: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>
  ),
  snooze: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18.73 14C16 16 12 16 12 16s0-4 2.73-6.73a3.86 3.86 0 0 1 5.46 5.46z"/><path d="M12 16c-4-4-8-4-8-4s0 4 4 8c0 0 0-4 4-4z"/><path d="M8 8l4-4 4 4"/></svg>
  ),
  notes: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
  ),
  target: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>
  ),
  chevronRight: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
  ),
  trendUp: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>
  ),
  trendDown: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 18 13.5 8.5 8.5 13.5 1 6"/><polyline points="17 18 23 18 23 12"/></svg>
  ),
  activity: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
  ),
  circle: (
    <svg width="8" height="8" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="12"/></svg>
  ),
};

// ─── Utility Helpers ─────────────────────────────────────────────────────────

function getGreeting() {
  const h = new Date().getHours();
  if (h < 12) return "Good morning";
  if (h < 17) return "Good afternoon";
  return "Good evening";
}

function formatDate(d) {
  return new Date(d).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" });
}

function formatTime(d) {
  return new Date(d).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
}

function formatDuration(seconds) {
  if (!seconds || seconds <= 0) return "0m";
  const totalSec = Math.round(seconds);
  const h = Math.floor(totalSec / 3600);
  const m = Math.floor((totalSec % 3600) / 60);
  const s = totalSec % 60;
  if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
  if (m > 0) return s > 0 ? `${m}m ${s}s` : `${m}m`;
  return `${s}s`;
}

function timeAgo(dateStr) {
  const now = new Date();
  const d = new Date(dateStr);
  const diffMs = now - d;
  const diffMins = Math.floor(diffMs / 60000);
  const diffHrs = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHrs / 24);
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHrs < 24) return `${diffHrs}h ago`;
  if (diffDays === 1) return "Yesterday";
  return `${diffDays}d ago`;
}

function ageLabel(dateStr) {
  const now = new Date();
  const d = new Date(dateStr);
  const diffMs = now - d;
  const diffHrs = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffHrs / 24);
  if (diffHrs < 24) return { text: `${diffHrs} hours`, urgent: false };
  if (diffDays <= 1) return { text: "1 day", urgent: false };
  if (diffDays >= 3) return { text: `${diffDays} days waiting`, urgent: true };
  return { text: `${diffDays} days`, urgent: false };
}

function isOverdue(dateStr) {
  if (!dateStr) return false;
  const d = new Date(dateStr);
  const today = new Date();
  today.setHours(0,0,0,0);
  return d < today;
}

function isDueToday(dateStr) {
  if (!dateStr) return false;
  const d = new Date(dateStr);
  const today = new Date();
  return d.toDateString() === today.toDateString();
}

function dueDateDisplay(dateStr) {
  if (!dateStr) return null;
  const d = new Date(dateStr);
  const today = new Date();
  today.setHours(0,0,0,0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  if (d.toDateString() === today.toDateString()) return "Today";
  if (d.toDateString() === tomorrow.toDateString()) return "Tomorrow";
  if (d < today) {
    const diffDays = Math.floor((today - d) / 86400000);
    return `${diffDays}d overdue`;
  }
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

// ─── Priority Pill ───────────────────────────────────────────────────────────

function PriorityPill({ priority }) {
  const colors = {
    high: "bg-red-100 text-red-700",
    medium: "bg-amber-100 text-amber-700",
    low: "bg-emerald-100 text-emerald-700",
  };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${colors[priority] || colors.medium}`}>
      {priority}
    </span>
  );
}

// ─── Category Badge ──────────────────────────────────────────────────────────

function CategoryBadge({ type }) {
  const config = {
    call: { icon: Icons.phone, label: "Call", cls: "bg-violet-100 text-violet-700" },
    email: { icon: Icons.mail, label: "Email", cls: "bg-sky-100 text-sky-700" },
    document: { icon: Icons.file, label: "Document", cls: "bg-orange-100 text-orange-700" },
    other: { icon: Icons.flag, label: "Other", cls: "bg-slate-100 text-slate-600" },
  };
  const c = config[type] || config.other;
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${c.cls}`}>
      {c.icon} {c.label}
    </span>
  );
}

// ─── Due Date Label ──────────────────────────────────────────────────────────

function DueDateLabel({ dateStr }) {
  if (!dateStr) return null;
  const label = dueDateDisplay(dateStr);
  const over = isOverdue(dateStr);
  const today = isDueToday(dateStr);
  let cls = "text-slate-500";
  if (over) cls = "text-red-600 font-semibold";
  else if (today) cls = "text-amber-600 font-semibold";
  return (
    <span className={`flex items-center gap-1 text-xs ${cls}`}>
      {Icons.calendar} {label}
    </span>
  );
}

// ─── Card Wrapper ────────────────────────────────────────────────────────────

function Card({ children, className = "", ...props }) {
  return (
    <div className={`bg-white rounded-xl shadow-sm border border-slate-200/60 ${className}`} {...props}>
      {children}
    </div>
  );
}

function CardHeader({ title, icon, action, count }) {
  return (
    <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
      <div className="flex items-center gap-2">
        {icon && <span className="text-slate-400">{icon}</span>}
        <h3 className="text-sm font-semibold text-slate-800 uppercase tracking-wide">{title}</h3>
        {count !== undefined && (
          <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-blue-100 text-blue-700 text-xs font-bold">{count}</span>
        )}
      </div>
      {action}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// MAIN DASHBOARD COMPONENT
// ═══════════════════════════════════════════════════════════════════════════════

function Dashboard() {
  const [viewMode, setViewMode] = useState("today");
  const [searchQuery, setSearchQuery] = useState("");
  const [recording, setRecording] = useState(false);
  const [recordingSeconds, setRecordingSeconds] = useState(0);
  const timerRef = useRef(null);

  // Browser recording
  const [recordingMode, setRecordingMode] = useState(null); // "wasapi" | "browser" | null
  const [browserRecording, setBrowserRecording] = useState(false);
  const [uploading, setUploading] = useState(false);
  const mediaRecorderRef = useRef(null);
  const chunksRef = useRef([]);

  // ── Live data from backend ───────────────────────────────────────────────
  const [liveData, setLiveData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchDashboardData();
    // Poll recording status
    const statusInterval = setInterval(checkRecordingStatus, 3000);
    return () => clearInterval(statusInterval);
  }, []);

  async function fetchDashboardData() {
    try {
      const resp = await fetch("/api/dashboard/data");
      if (resp.ok) {
        const data = await resp.json();
        setLiveData(data);
      }
    } catch (e) {
      console.warn("Failed to fetch dashboard data, using sample data", e);
    } finally {
      setLoading(false);
    }
  }

  async function checkRecordingStatus() {
    try {
      const resp = await fetch("/api/recording/status");
      if (resp.ok) {
        const data = await resp.json();
        setRecording(data.state === "recording");
      }
    } catch (e) { /* ignore */ }
  }

  // ── Detect recording mode (WASAPI vs browser) ─────────────────────────
  useEffect(() => {
    fetch("/api/recording/status")
      .then(r => r.json())
      .then(data => {
        setRecordingMode(data.state === "unavailable" ? "browser" : "wasapi");
      })
      .catch(() => setRecordingMode("browser"));
  }, []);

  // ── Recording timer ────────────────────────────────────────────────────
  useEffect(() => {
    if (recording || browserRecording) {
      timerRef.current = setInterval(() => {
        setRecordingSeconds(s => s + 1);
      }, 1000);
    } else {
      clearInterval(timerRef.current);
      setRecordingSeconds(0);
    }
    return () => clearInterval(timerRef.current);
  }, [recording, browserRecording]);

  async function toggleRecording() {
    const endpoint = recording ? "/api/recording/stop" : "/api/recording/start";
    try {
      const resp = await fetch(endpoint, { method: "POST" });
      if (resp.ok) {
        setRecording(!recording);
        if (!recording) setRecordingSeconds(0);
      }
    } catch (e) {
      console.error("Recording toggle failed", e);
    }
  }

  // ── Browser recording functions ────────────────────────────────────────
  async function startBrowserRecording() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      // Detect supported MIME type (Safari only supports audio/mp4)
      const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
        ? 'audio/webm;codecs=opus'
        : MediaRecorder.isTypeSupported('audio/mp4')
          ? 'audio/mp4'
          : 'audio/webm';

      const recorder = new MediaRecorder(stream, { mimeType });
      chunksRef.current = [];

      recorder.ondataavailable = (e) => {
        if (e.data.size > 0) chunksRef.current.push(e.data);
      };

      recorder.onstop = async () => {
        stream.getTracks().forEach(t => t.stop());
        const blob = new Blob(chunksRef.current, { type: mimeType });
        await uploadBrowserRecording(blob, mimeType);
      };

      recorder.start(1000); // Collect data every second
      mediaRecorderRef.current = recorder;
      setBrowserRecording(true);
      setRecordingSeconds(0);
    } catch (e) {
      console.error("Mic access denied or unavailable:", e);
      alert("Could not access microphone. Please allow mic access and try again.");
    }
  }

  function stopBrowserRecording() {
    if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
      mediaRecorderRef.current.stop();
    }
    setBrowserRecording(false);
  }

  async function uploadBrowserRecording(blob, mimeType) {
    setUploading(true);
    try {
      const ext = mimeType.includes("mp4") ? ".m4a" : ".webm";
      const formData = new FormData();
      formData.append("audio", blob, `recording${ext}`);

      const resp = await fetch("/api/calls/upload", { method: "POST", body: formData });
      if (resp.ok) {
        const data = await resp.json();
        // Refresh dashboard data after a delay to allow processing
        setTimeout(fetchDashboardData, 3000);
        setTimeout(fetchDashboardData, 10000);
      } else {
        const err = await resp.json();
        alert(`Upload failed: ${err.error || "Unknown error"}`);
      }
    } catch (e) {
      console.error("Upload failed:", e);
      alert("Failed to upload recording. Check your connection.");
    } finally {
      setUploading(false);
    }
  }

  // ── Task actions ───────────────────────────────────────────────────────
  async function handleCompleteTask(taskId) {
    try {
      await fetch(`/tasks/${taskId}/complete`, { method: "POST" });
      fetchDashboardData();
    } catch (e) { console.error(e); }
  }

  async function handleAcceptInsight(insightId) {
    try {
      await fetch(`/api/email/insights/${insightId}/accept`, { method: "POST" });
      fetchDashboardData();
    } catch (e) { console.error(e); }
  }

  async function handleDismissInsight(insightId) {
    try {
      await fetch(`/api/email/insights/${insightId}/dismiss`, { method: "POST" });
      fetchDashboardData();
    } catch (e) { console.error(e); }
  }

  // ── Quick Add ──────────────────────────────────────────────────────────
  const [quickTask, setQuickTask] = useState("");
  const [quickPriority, setQuickPriority] = useState("medium");
  const [quickDue, setQuickDue] = useState("");
  const [quickCategory, setQuickCategory] = useState("other");

  async function handleQuickAdd(e) {
    e.preventDefault();
    if (!quickTask.trim()) return;
    try {
      const resp = await fetch("/api/tasks/quick-add", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: quickTask.trim(),
          priority: quickPriority,
          due_date: quickDue || null,
          source_type: quickCategory,
        }),
      });
      if (resp.ok) {
        setQuickTask("");
        setQuickDue("");
        setQuickPriority("medium");
        setQuickCategory("other");
        fetchDashboardData();
      }
    } catch (e) { console.error(e); }
  }

  // ── Email Sync ─────────────────────────────────────────────────────────
  async function handleEmailSync() {
    try {
      await fetch("/api/email/sync", { method: "POST" });
      setTimeout(fetchDashboardData, 5000);
    } catch (e) { console.error(e); }
  }

  // ── Derive display data from liveData or use sample ────────────────────
  const data = useMemo(() => {
    if (liveData) return transformLiveData(liveData);
    return getSampleData();
  }, [liveData]);

  // ── Render ─────────────────────────────────────────────────────────────
  const recordTimerStr = `${Math.floor(recordingSeconds/60)}:${String(recordingSeconds%60).padStart(2,"0")}`;

  return (
    <div className="min-h-screen bg-slate-50 flex">
      {/* ── SIDEBAR (desktop only — hidden on mobile) ────────────────── */}
      <Sidebar />

      {/* ── MAIN CONTENT ──────────────────────────────────────────────── */}
      <div className="flex-1 md:ml-[200px] min-h-screen pb-20 md:pb-0">
        <div className="max-w-[1440px] mx-auto px-4 md:px-6 py-4 md:py-6 space-y-4 md:space-y-6">

        {/* ── 1. HEADER ─────────────────────────────────────────────────── */}
        <header className="space-y-3">
          {/* Row 1: Greeting + controls */}
          <div className="flex items-center justify-between gap-3">
            <div className="min-w-0">
              <h1 className="text-xl md:text-2xl font-bold text-slate-900 truncate">{getGreeting()}, JD</h1>
              <p className="text-xs md:text-sm text-slate-500 mt-0.5">{formatDate(new Date())}</p>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              {/* View Toggle */}
              <div className="flex items-center bg-white rounded-lg border border-slate-200 p-0.5 shadow-sm">
                <button
                  onClick={() => setViewMode("today")}
                  className={`px-2.5 md:px-3 py-1.5 rounded-md text-xs md:text-sm font-medium transition-colors ${
                    viewMode === "today" ? "bg-blue-600 text-white shadow-sm" : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Today
                </button>
                <button
                  onClick={() => setViewMode("week")}
                  className={`px-2.5 md:px-3 py-1.5 rounded-md text-xs md:text-sm font-medium transition-colors ${
                    viewMode === "week" ? "bg-blue-600 text-white shadow-sm" : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Week
                </button>
              </div>

              {/* Record Button */}
              {recordingMode === "wasapi" ? (
                <button
                  onClick={toggleRecording}
                  className={`flex items-center gap-2 px-3 md:px-4 py-2.5 rounded-lg text-sm font-semibold transition-all shadow-sm ${
                    recording
                      ? "bg-red-600 hover:bg-red-700 text-white animate-pulse"
                      : "bg-blue-600 hover:bg-blue-700 text-white"
                  }`}
                >
                  {recording ? Icons.micOff : Icons.mic}
                  <span className="hidden sm:inline">{recording ? `Stop ${recordTimerStr}` : "Record"}</span>
                </button>
              ) : recordingMode === "browser" ? (
                <button
                  onClick={browserRecording ? stopBrowserRecording : startBrowserRecording}
                  disabled={uploading}
                  className={`flex items-center gap-2 px-3 md:px-4 py-2.5 rounded-lg text-sm font-semibold transition-all shadow-sm ${
                    uploading
                      ? "bg-slate-400 text-white cursor-wait"
                      : browserRecording
                        ? "bg-red-600 hover:bg-red-700 text-white animate-pulse"
                        : "bg-blue-600 hover:bg-blue-700 text-white"
                  }`}
                >
                  {uploading ? Icons.clock : browserRecording ? Icons.micOff : Icons.mic}
                  <span className="hidden sm:inline">{uploading ? "Processing..." : browserRecording ? `Stop ${recordTimerStr}` : "Record"}</span>
                </button>
              ) : null}
            </div>
          </div>

          {/* Row 2: Always-visible search bar */}
          <div className="flex items-center bg-white rounded-lg border border-slate-200 shadow-sm">
            <span className="flex items-center justify-center w-10 h-10 text-slate-400 shrink-0">
              {Icons.search}
            </span>
            <input
              type="text"
              placeholder="Search calls, tasks, emails..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              onKeyDown={e => {
                if (e.key === "Enter" && searchQuery.trim()) {
                  window.location.href = `/search?q=${encodeURIComponent(searchQuery.trim())}`;
                }
                if (e.key === "Escape") { setSearchQuery(""); e.target.blur(); }
              }}
              className="w-full h-10 pr-3 text-base md:text-sm bg-transparent border-none outline-none placeholder-slate-400 text-slate-800"
            />
          </div>
        </header>

        {/* ── QUICK-ADD TASK BAR ──────────────────────────────────────── */}
        <Card className="p-4">
          <form onSubmit={handleQuickAdd} className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
            <div className="flex items-center gap-2 flex-1">
              <span className="text-blue-500">{Icons.plus}</span>
              <input
                type="text"
                placeholder="Add a new task..."
                value={quickTask}
                onChange={e => setQuickTask(e.target.value)}
                className="flex-1 h-10 text-sm bg-transparent border-none outline-none placeholder-slate-400 text-slate-800"
              />
            </div>
            <select
              value={quickPriority}
              onChange={e => setQuickPriority(e.target.value)}
              className="h-10 px-3 text-sm rounded-lg border border-slate-200 bg-white text-slate-700 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
            >
              <option value="high">🔴 High</option>
              <option value="medium">🟡 Medium</option>
              <option value="low">🟢 Low</option>
            </select>
            <select
              value={quickCategory}
              onChange={e => setQuickCategory(e.target.value)}
              className="h-10 px-3 text-sm rounded-lg border border-slate-200 bg-white text-slate-700 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
            >
              <option value="call">📞 Call</option>
              <option value="email">✉️ Email</option>
              <option value="document">📄 Document</option>
              <option value="other">📋 Other</option>
            </select>
            <input
              type="date"
              value={quickDue}
              onChange={e => setQuickDue(e.target.value)}
              className="h-10 px-3 text-sm rounded-lg border border-slate-200 bg-white text-slate-700 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
            />
            <button
              type="submit"
              className="h-10 px-5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
            >
              Add Task
            </button>
          </form>
        </Card>

        {/* ── TWO COLUMN LAYOUT ───────────────────────────────────────── */}
        <div className="grid grid-cols-1 xl:grid-cols-[1.4fr_1fr] gap-6">

          {/* ── LEFT COLUMN ──────────────────────────────────────────────── */}
          <div className="space-y-6">

            {/* ── My Tasks (grouped by category) ────────────────────────── */}
            <Card>
              <CardHeader
                title="My Tasks"
                icon={Icons.target}
                count={data.tasks.length}
                action={
                  <a href="/tasks" className="text-xs text-blue-600 hover:text-blue-700 font-medium">View All →</a>
                }
              />
              <div className="divide-y divide-slate-100">
                {groupTasksByCategory(data.tasks).map(group => (
                  <div key={group.category}>
                    <div className="px-5 py-2.5 bg-slate-50/80">
                      <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">{group.label}</span>
                    </div>
                    {group.items.map(task => (
                      <TaskRow key={task.id} task={task} onComplete={() => handleCompleteTask(task.id)} />
                    ))}
                  </div>
                ))}
                {data.tasks.length === 0 && (
                  <div className="px-5 py-10 text-center text-sm text-slate-400">
                    No open tasks — nice work! 🎉
                  </div>
                )}
              </div>
            </Card>

            {/* ── Completed Today ────────────────────────────────────────── */}
            <Card>
              <CardHeader
                title="Completed Today"
                icon={Icons.checkCircle}
                count={data.completedToday.length}
              />
              <div className="max-h-64 overflow-y-auto">
                {data.completedToday.length > 0 ? (
                  <div className="divide-y divide-slate-100">
                    {data.completedToday.map(item => (
                      <div key={item.id} className="flex items-center gap-3 px-5 py-3">
                        <span className="text-emerald-500 shrink-0">{Icons.checkCircle}</span>
                        <span className="text-sm text-slate-500 line-through flex-1">{item.title}</span>
                        <span className="text-xs text-slate-400">{item.completedTime}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="px-5 py-8 text-center text-sm text-slate-400">
                    Nothing completed yet — let's get started!
                  </div>
                )}
              </div>
            </Card>
          </div>

          {/* ── RIGHT COLUMN ─────────────────────────────────────────────── */}
          <div className="space-y-6">

            {/* ── Email Insights ──────────────────────────────────────────── */}
            <Card>
              <CardHeader
                title="Email Insights"
                icon={Icons.mail}
                count={data.emailInsights.length}
                action={
                  <div className="flex items-center gap-2">
                    <button onClick={handleEmailSync} className="text-xs text-blue-600 hover:text-blue-700 font-medium">Sync</button>
                    <a href="/email/insights" className="text-xs text-blue-600 hover:text-blue-700 font-medium">View All →</a>
                  </div>
                }
              />
              <div className="divide-y divide-slate-100">
                {data.emailInsights.map(insight => (
                  <EmailInsightRow
                    key={insight.id}
                    insight={insight}
                    onAccept={() => handleAcceptInsight(insight.id)}
                    onDismiss={() => handleDismissInsight(insight.id)}
                  />
                ))}
                {data.emailInsights.length === 0 && (
                  <div className="px-5 py-8 text-center text-sm text-slate-400">
                    {data.gmailConnected ? "No new insights" : (
                      <a href="/email/setup" className="text-blue-600 hover:text-blue-700 font-medium">Connect Gmail →</a>
                    )}
                  </div>
                )}
              </div>
            </Card>

            {/* ── Recent Calls ────────────────────────────────────────────── */}
            <Card>
              <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
                <div className="flex items-center gap-2">
                  <span className="text-slate-400">{Icons.phone}</span>
                  <h3 className="text-sm font-semibold text-slate-800 uppercase tracking-wide">Recent Calls</h3>
                  <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-blue-100 text-blue-700 text-xs font-bold">{data.recentCalls.length}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-xs text-slate-400">{data.callStats.callsMade} of {data.callStats.callTarget}</span>
                  <span className="text-xs text-slate-300">·</span>
                  <span className="text-xs text-slate-400">{data.callStats.totalCallTime}</span>
                  <span className="text-xs text-slate-300 ml-1">·</span>
                  <a href="/calls" className="text-xs text-blue-600 hover:text-blue-700 font-medium ml-1">View All →</a>
                </div>
              </div>
              <div className="divide-y divide-slate-100">
                {data.recentCalls.map(call => (
                  <CallRow key={call.id} call={call} />
                ))}
                {data.recentCalls.length === 0 && (
                  <div className="px-5 py-8 text-center text-sm text-slate-400">
                    No calls recorded yet
                  </div>
                )}
              </div>
            </Card>

            {/* ── Today's Timeline ────────────────────────────────────────── */}
            {data.timeline.length > 0 && (
              <Card>
                <CardHeader title="Today's Timeline" icon={Icons.activity} />
                <div className="px-5 py-4">
                  <div className="relative space-y-0">
                    {data.timeline.map((event, i) => (
                      <div key={i} className="flex gap-4 pb-5 last:pb-0">
                        <div className="flex flex-col items-center">
                          <div className={`w-3 h-3 rounded-full border-2 shrink-0 ${
                            event.completed
                              ? "bg-emerald-500 border-emerald-500"
                              : event.current
                                ? "bg-blue-500 border-blue-500 ring-4 ring-blue-100"
                                : "bg-white border-slate-300"
                          }`} />
                          {i < data.timeline.length - 1 && (
                            <div className={`w-px flex-1 min-h-[20px] ${event.completed ? 'bg-emerald-200' : 'bg-slate-200'}`} />
                          )}
                        </div>
                        <div className="flex-1 min-w-0 -mt-1">
                          <p className={`text-sm font-medium ${event.completed ? 'text-slate-500' : 'text-slate-800'}`}>
                            {event.title}
                          </p>
                          <p className="text-xs text-slate-400 mt-0.5">{event.time}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </Card>
            )}
          </div>
        </div>
      </div>
      </div>

      {/* ── BOTTOM NAV BAR (mobile only) ────────────────────────────── */}
      <BottomNav />
    </div>
  );
}

// ─── Sidebar Component ───────────────────────────────────────────────────────

function Sidebar() {
  const currentPath = window.location.pathname;

  const navItems = [
    { href: "/", label: "Dashboard", icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
    )},
    { href: "/tasks", label: "Tasks", icon: (
      <svg width="22" height="22" 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>
    )},
    { href: "/calls", label: "Calls", icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
    )},
    { href: "/email/setup", label: "Email", icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 7l-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
    )},
    { href: "/digests", label: "Digests", icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
    )},
    { href: "/search", label: "Search", icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    )},
  ];

  function isActive(href) {
    if (href === "/") return currentPath === "/";
    return currentPath.startsWith(href);
  }

  return (
    <aside className="hidden md:flex fixed left-0 top-0 bottom-0 w-[200px] bg-white border-r border-slate-200 flex-col py-5 z-50">
      {/* Brand */}
      <a href="/" className="flex items-center gap-2.5 px-5 mb-6 no-underline">
        <div className="flex items-center justify-center w-9 h-9 rounded-lg bg-blue-600 text-white shrink-0 shadow-sm">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
        </div>
        <span className="text-sm font-bold text-slate-800 tracking-tight">Assistant</span>
      </a>

      {/* Nav items */}
      <nav className="flex flex-col gap-0.5 px-3 flex-1">
        {navItems.map(item => (
          <a
            key={item.href}
            href={item.href}
            className={`relative flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all no-underline ${
              isActive(item.href)
                ? "bg-blue-50 text-blue-600"
                : "text-slate-500 hover:text-slate-800 hover:bg-slate-50"
            }`}
          >
            <span className="shrink-0">{item.icon}</span>
            <span>{item.label}</span>
            {isActive(item.href) && (
              <span className="absolute left-0 top-1.5 bottom-1.5 w-[3px] rounded-r-full bg-blue-600" />
            )}
          </a>
        ))}
      </nav>
    </aside>
  );
}

// ─── Bottom Nav Bar (mobile only) ─────────────────────────────────────────────

function BottomNav() {
  const currentPath = window.location.pathname;

  const tabs = [
    { href: "/", label: "Home", icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
    )},
    { href: "/tasks", label: "Tasks", icon: (
      <svg width="20" height="20" 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>
    )},
    { href: "/calls", label: "Calls", icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
    )},
    { href: "/email/setup", label: "Email", icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 7l-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
    )},
    { href: "/digests", label: "Digests", icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
    )},
  ];

  function isActive(href) {
    if (href === "/") return currentPath === "/";
    return currentPath.startsWith(href);
  }

  return (
    <nav className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-white border-t border-slate-200 px-2 pb-[env(safe-area-inset-bottom)]">
      <div className="flex items-center justify-around h-14">
        {tabs.map(tab => (
          <a
            key={tab.href}
            href={tab.href}
            className={`flex flex-col items-center gap-0.5 px-3 py-1.5 rounded-lg no-underline transition-colors ${
              isActive(tab.href)
                ? "text-blue-600"
                : "text-slate-400"
            }`}
          >
            <span>{tab.icon}</span>
            <span className="text-[10px] font-medium">{tab.label}</span>
          </a>
        ))}
      </div>
    </nav>
  );
}

// ─── Sub-Components ──────────────────────────────────────────────────────────

function TaskRow({ task, onComplete }) {
  return (
    <div className="group flex items-start gap-3 px-5 py-3.5 hover:bg-slate-50/80 transition-colors">
      <button
        onClick={onComplete}
        className="mt-0.5 w-8 h-8 min-w-[32px] rounded-md border-2 border-slate-300 hover:border-blue-500 hover:bg-blue-50 flex items-center justify-center shrink-0 transition-colors"
      >
        <span className="hidden group-hover:block text-blue-500">{Icons.check}</span>
      </button>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <a href={`/tasks/${task.id}`} className="text-sm font-medium text-slate-800 hover:text-blue-600 transition-colors">
            {task.title}
          </a>
          <PriorityPill priority={task.priority} />
        </div>
        <div className="flex items-center gap-3 mt-1.5 flex-wrap">
          {task.contact && <span className="text-xs text-slate-500">{task.contact}</span>}
          <DueDateLabel dateStr={task.dueDate} />
          <CategoryBadge type={task.sourceType} />
        </div>
      </div>
    </div>
  );
}

function EmailInsightRow({ insight, onAccept, onDismiss }) {
  const age = ageLabel(insight.emailDate);
  return (
    <div className="group px-5 py-4 hover:bg-slate-50/80 transition-colors">
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-slate-800 truncate">{insight.subject}</p>
          <p className="text-xs text-slate-400 mt-0.5 truncate">{insight.sender}</p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <span className={`text-xs font-medium ${age.urgent ? 'text-red-600' : 'text-slate-400'}`}>
            {age.text}
          </span>
          <PriorityPill priority={insight.priority} />
        </div>
      </div>
      <p className="text-xs text-slate-600 mt-2 leading-relaxed">{insight.suggestedTask}</p>
      <div className="flex items-center gap-2 mt-3">
        <button
          onClick={onAccept}
          className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-blue-600 hover:bg-blue-50 rounded-md transition-colors"
        >
          {Icons.plus} Create Task
        </button>
        <button
          onClick={onDismiss}
          className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-md transition-colors"
        >
          Dismiss
        </button>
      </div>
    </div>
  );
}

function CallRow({ call }) {
  return (
    <a href={`/calls/${call.id}`} className="flex items-start gap-3 px-5 py-4 hover:bg-slate-50/80 transition-colors block">
      <div className="w-10 h-10 rounded-full bg-violet-50 flex items-center justify-center text-violet-600 shrink-0">
        {Icons.phone}
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <p className="text-sm font-semibold text-slate-800 truncate">{call.title}</p>
          {call.hasFollowUp && <span className="text-amber-500">{Icons.flag}</span>}
        </div>
        <p className="text-xs text-slate-400 mt-0.5">
          {call.time} · {call.duration}
        </p>
        {call.summary && (
          <p className="text-xs text-slate-500 mt-1.5 leading-relaxed">{call.summary}</p>
        )}
      </div>
    </a>
  );
}

// ─── Data Transformation ─────────────────────────────────────────────────────

function groupTasksByCategory(tasks) {
  const groups = {
    call: { label: "Calls to Make", items: [] },
    email: { label: "Emails to Send", items: [] },
    document: { label: "Documents to Prepare", items: [] },
    other: { label: "Other Tasks", items: [] },
  };
  tasks.forEach(t => {
    const cat = t.sourceType || "other";
    if (groups[cat]) groups[cat].items.push(t);
    else groups.other.items.push(t);
  });
  return Object.entries(groups)
    .filter(([_, g]) => g.items.length > 0)
    .map(([category, g]) => ({ category, ...g }));
}

function transformLiveData(d) {
  // Transform API data to component format
  const tasks = (d.tasks || []).map(t => ({
    id: t.id,
    title: t.title,
    priority: t.priority || "medium",
    dueDate: t.due_date,
    sourceType: t.source_type || "other",
    contact: t.assignee || null,
  }));

  const completedToday = (d.completed_today || []).map(t => ({
    id: t.id,
    title: t.title,
    completedTime: t.completed_at ? formatTime(t.completed_at) : "",
  }));

  const emailInsights = (d.email_insights || []).map(i => ({
    id: i.id,
    subject: i.email_subject || "(no subject)",
    sender: i.email_sender || "unknown",
    emailDate: i.email_date || i.created_at,
    suggestedTask: i.suggested_task,
    priority: i.suggested_priority || "medium",
  }));

  const recentCalls = (d.recent_calls || []).map(c => ({
    id: c.id,
    title: d.call_titles?.[c.id] || "Untitled Call",
    time: c.started_at ? formatTime(c.started_at) : "",
    duration: formatDuration(c.duration_seconds),
    summary: c.notes || null,
    hasFollowUp: false,
  }));

  const timeline = (d.timeline || []).map(e => ({
    title: e.title,
    time: e.time,
    completed: e.completed,
    current: e.current || false,
  }));

  return {
    callStats: {
      callsMade: d.stats?.call_count || 0,
      callTarget: 8,
      totalCallTime: d.stats?.total_duration ? formatDuration(d.stats.total_duration) : "0m",
    },
    tasks,
    completedToday,
    emailInsights,
    recentCalls,
    timeline,
    gmailConnected: d.gmail_connected || false,
  };
}

function getSampleData() {
  return {
    callStats: {
      callsMade: 2,
      callTarget: 8,
      totalCallTime: "47m",
    },
    tasks: [
      { id: "1", title: "Call Marcus Greene — finalize flatbed trailer quote", priority: "high", dueDate: new Date().toISOString().slice(0,10), sourceType: "call", contact: "Greene Construction" },
      { id: "2", title: "Call Hank's Excavation — schedule equipment return", priority: "high", dueDate: new Date(Date.now() - 86400000).toISOString().slice(0,10), sourceType: "call", contact: "Hank's Excavation" },
      { id: "3", title: "Return follow-up call to Riverside Paving", priority: "medium", dueDate: new Date(Date.now() + 86400000).toISOString().slice(0,10), sourceType: "call", contact: "Riverside Paving" },
      { id: "4", title: "Reply to Jenny at BlueLine about insurance cert", priority: "high", dueDate: new Date().toISOString().slice(0,10), sourceType: "email", contact: "BlueLine Logistics" },
      { id: "5", title: "Send updated rental agreement to Metro Builders", priority: "medium", dueDate: new Date(Date.now() + 172800000).toISOString().slice(0,10), sourceType: "email", contact: "Metro Builders" },
      { id: "6", title: "Prepare Q1 fleet utilization report", priority: "medium", dueDate: new Date(Date.now() + 432000000).toISOString().slice(0,10), sourceType: "document", contact: null },
      { id: "7", title: "Update maintenance log for Unit #TR-4422", priority: "low", dueDate: null, sourceType: "document", contact: null },
      { id: "8", title: "Review vendor pricing from AllState Equipment", priority: "low", dueDate: new Date(Date.now() + 604800000).toISOString().slice(0,10), sourceType: "other", contact: "AllState Equipment" },
    ],
    completedToday: [
      { id: "c1", title: "Called Dave at Summit Cranes — confirmed delivery", completedTime: "9:15 AM" },
      { id: "c2", title: "Sent invoice #4455 to Tri-County Excavating", completedTime: "8:30 AM" },
      { id: "c3", title: "Updated fleet availability spreadsheet", completedTime: "8:05 AM" },
    ],
    emailInsights: [
      {
        id: "e1",
        subject: "RE: Flatbed Availability for March",
        sender: "Marcus Greene <marcus@greeneconstruction.com>",
        emailDate: new Date(Date.now() - 7200000).toISOString(),
        suggestedTask: "Reply to Marcus with updated flatbed availability and 6-month pricing",
        priority: "high",
      },
      {
        id: "e2",
        subject: "Insurance Certificate Renewal",
        sender: "Jenny Park <jenny@bluelinelogistics.com>",
        emailDate: new Date(Date.now() - 259200000).toISOString(),
        suggestedTask: "Send renewed insurance certificate to BlueLine — their current one expires Friday",
        priority: "high",
      },
      {
        id: "e3",
        subject: "Equipment Return Scheduling",
        sender: "accounting@hanksexcavation.com",
        emailDate: new Date(Date.now() - 86400000).toISOString(),
        suggestedTask: "Schedule pickup for 2 backhoes from Hank's Excavation job site",
        priority: "medium",
      },
      {
        id: "e4",
        subject: "2025 Vendor Pricing Update",
        sender: "sales@allstateequipment.com",
        emailDate: new Date(Date.now() - 172800000).toISOString(),
        suggestedTask: "Review updated vendor pricing and compare against current fleet costs",
        priority: "low",
      },
    ],
    recentCalls: [
      { id: "r1", title: "Dave Mitchell — Summit Cranes", time: "9:12 AM", duration: "12m 34s", summary: "Confirmed delivery of 60-ton crane for Monday. Access route cleared.", hasFollowUp: true },
      { id: "r2", title: "Sarah Chen — Riverside Paving", time: "Yesterday", duration: "8m 22s", summary: "Left voicemail — follow up Thursday about roller rental extension", hasFollowUp: true },
      { id: "r3", title: "Tom Barrett — Metro Builders", time: "Yesterday", duration: "22m 15s", summary: "Discussed Q2 equipment needs. Wants proposal for 3 excavators + 2 dump trucks.", hasFollowUp: false },
    ],
    timeline: [
      { title: "Updated fleet availability", time: "8:05 AM", completed: true },
      { title: "Sent invoice to Tri-County", time: "8:30 AM", completed: true },
      { title: "Called Dave at Summit Cranes", time: "9:12 AM", completed: true },
      { title: "Follow up with Marcus Greene", time: "10:30 AM", completed: false, current: true },
      { title: "Lunch with regional sales team", time: "12:00 PM", completed: false },
      { title: "Review vendor proposals", time: "2:00 PM", completed: false },
      { title: "Daily digest review", time: "6:00 PM", completed: false },
    ],
    gmailConnected: true,
  };
}

// ─── Mount ───────────────────────────────────────────────────────────────────

const root = ReactDOM.createRoot(document.getElementById("dashboard-root"));
root.render(React.createElement(Dashboard));
