"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  Bell,
  Bot,
  CheckCircle2,
  ClipboardCheck,
  Download,
  ExternalLink,
  FileText,
  Inbox,
  Mail,
  Plus,
  Sparkles,
} from "lucide-react";
import {
  useInvoices,
} from "@/hooks/use-invoices";
import { useIntegrations } from "@/hooks/use-integrations";
import { TaskForm, type TaskFormData } from "@/components/tasks/task-form";
import { useGoals } from "@/hooks/use-goals";
import { useNotes } from "@/hooks/use-notes";
import { useNotifications } from "@/hooks/use-notifications";
import { useOrganizations } from "@/hooks/use-organizations";
import { useProjects } from "@/hooks/use-projects";
import { useTags } from "@/hooks/use-tags";
import { useTasks } from "@/hooks/use-tasks";
import { useTeamPermissions } from "@/hooks/use-team-permissions";
import {
  buildInvoicePdfBlob,
  formatInvoiceMoney,
  getInvoiceDocumentLabel,
  sanitizeInvoiceFileSegment,
} from "@/lib/invoices";
import { formatRelativeDate } from "@/lib/utils";
import { cn } from "@/lib/utils";
import type { Invoice as InvoiceRecord } from "@/types";

function aiPromptHref(prompt: string) {
  return `/ai?prompt=${encodeURIComponent(prompt)}`;
}

function downloadBlob(blob: Blob, fileName: string) {
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = fileName;
  link.click();
  window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}

export default function InboxPage() {
  const router = useRouter();
  const { tasks, loading: tasksLoading, createTask, toggleTaskStatus } = useTasks();
  const { invoices, loading: invoicesLoading, removeInvoiceFromInbox } = useInvoices();
  const { gmailConnections, loading: integrationsLoading } = useIntegrations();
  const { notes, loading: notesLoading, createNote } = useNotes();
  const { projects, loading: projectsLoading } = useProjects();
  const { goals } = useGoals();
  const { tags, createTag } = useTags();
  const {
    notifications,
    unreadCount,
    loading: notificationsLoading,
    markAsRead,
    markAllAsRead,
  } = useNotifications();
  const {
    organizations,
    incomingInvitations,
    loading: organizationsLoading,
    userId,
    acceptOrganizationInvitation,
    declineOrganizationInvitation,
    updateOrganizationJoinRequest,
  } = useOrganizations();
  const { can } = useTeamPermissions();
  const canEditTasks = can("tasks", "edit");
  const canEditNotes = can("notes", "edit");

  const [formOpen, setFormOpen] = useState(false);
  const [busyActionId, setBusyActionId] = useState<string | null>(null);
  const [draftMessage, setDraftMessage] = useState<string | null>(null);

  const loading =
    tasksLoading ||
    notesLoading ||
    projectsLoading ||
    notificationsLoading ||
    organizationsLoading ||
    invoicesLoading ||
    integrationsLoading;

  const inboxTasks = useMemo(
    () =>
      tasks.filter(
        (task) => task.project_id === null && task.status !== "done" && task.status !== "cancelled"
      ),
    [tasks]
  );

  const inboxNotes = useMemo(
    () => notes.filter((note) => note.project_id === null && note.folder_id === null),
    [notes]
  );

  const inboxDocuments = useMemo(
    () =>
      invoices
        .filter((invoice) => invoice.inbox_at)
        .sort((left, right) => (right.inbox_at || "").localeCompare(left.inbox_at || "")),
    [invoices],
  );

  const activeGmailConnection = gmailConnections.find((connection) => connection.is_active) || null;

  const reviewTasks = useMemo(() => {
    const pending = tasks.filter((task) => task.review_status === "pending_review");
    const assigned = userId ? pending.filter((task) => task.reviewer_id === userId) : [];
    return (assigned.length > 0 ? assigned : pending).slice(0, 6);
  }, [tasks, userId]);

  const approvalProjects = useMemo(() => {
    const pending = projects.filter((project) => project.approval_status === "pending_approval");
    const assigned = userId ? pending.filter((project) => project.approver_id === userId) : [];
    return (assigned.length > 0 ? assigned : pending).slice(0, 6);
  }, [projects, userId]);

  const unreadNotifications = useMemo(
    () => notifications.filter((notification) => !notification.is_read).slice(0, 8),
    [notifications]
  );

  const pendingJoinRequests = useMemo(
    () =>
      organizations.flatMap((organization) =>
        organization.joinRequests
          .filter((request) => request.status === "pending")
          .map((request) => ({
            ...request,
            organizationName: organization.name,
          }))
      ),
    [organizations]
  );

  const actionCount =
    reviewTasks.length +
    approvalProjects.length +
    incomingInvitations.length +
    pendingJoinRequests.length +
    unreadNotifications.length;

  const captureCount = inboxTasks.length + inboxNotes.length + inboxDocuments.length;

  async function handleCreateTask(data: TaskFormData) {
    await createTask({ ...data, project_id: null });
  }

  async function handleQuickNote() {
    const note = await createNote({});
    router.push(`/notes/${note.id}`);
  }

  async function runBusyAction(id: string, action: () => Promise<void>) {
    setBusyActionId(id);
    try {
      await action();
    } finally {
      setBusyActionId(null);
    }
  }

  async function handleDownloadDocument(invoice: InvoiceRecord) {
    const documentLabel = getInvoiceDocumentLabel(invoice);
    const blob = await buildInvoicePdfBlob(invoice);
    const fileName = [
      sanitizeInvoiceFileSegment(invoice.invoice_number || documentLabel),
      sanitizeInvoiceFileSegment(invoice.counterparty_name || ""),
    ]
      .filter(Boolean)
      .join("-");
    downloadBlob(blob, `${fileName || sanitizeInvoiceFileSegment(documentLabel)}.pdf`);
  }

  async function handleCreateGmailDraft(invoice: InvoiceRecord) {
    const documentLabel = getInvoiceDocumentLabel(invoice);
    const response = await fetch(`/api/invoices/${invoice.id}/gmail-draft`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        connectionId: activeGmailConnection?.id,
        to: invoice.counterparty_email,
        subject: `${documentLabel} ${invoice.invoice_number}`,
      }),
    });
    const payload = await response.json();

    if (!response.ok) {
      throw new Error(typeof payload?.error === "string" ? payload.error : "Gmail-Entwurf konnte nicht erstellt werden.");
    }

    setDraftMessage(`Gmail-Entwurf für ${documentLabel} ${invoice.invoice_number} wurde erstellt.`);
    window.open(payload.webUrl || "https://mail.google.com/mail/u/0/#drafts", "_blank", "noopener,noreferrer");
  }

  return (
    <div className="mx-auto max-w-[820px] space-y-6 px-6 py-8">

      {/* ── Hero header ─────────────────────────────────────────────────────── */}
      <div
        className="relative overflow-hidden rounded-[28px] border border-white/[0.07] bg-[#0e0c15] p-8"
        style={{
          backgroundImage:
            "radial-gradient(ellipse at 10% -30%, rgba(14,165,233,0.15) 0%, transparent 55%), radial-gradient(ellipse at 90% 110%, rgba(14,165,233,0.08) 0%, transparent 50%)",
        }}
      >
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-sky-500/20 bg-sky-500/[0.08] px-3 py-1">
              <Inbox className="h-3.5 w-3.5 text-sky-400" />
              <span className="text-[10px] font-bold uppercase tracking-[0.18em] text-sky-300">Inbox</span>
            </div>
            <h1 className="text-[28px] font-bold tracking-tight text-white">
              Command center
            </h1>
            <p className="mt-1 text-[14px] text-white/40">
              Quick captures, reviews, approvals — one calm place to process everything.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={handleQuickNote}
              disabled={!canEditNotes}
              className="inline-flex items-center gap-2 rounded-xl border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-[13px] font-semibold text-white/70 transition-all hover:border-white/[0.14] hover:bg-white/[0.07] hover:text-white disabled:opacity-40"
            >
              <FileText className="h-3.5 w-3.5" />
              Quick note
            </button>
            <button
              onClick={() => setFormOpen(true)}
              disabled={!canEditTasks}
              className="inline-flex items-center gap-2 rounded-xl border border-sky-500/30 bg-sky-500/[0.15] px-4 py-2 text-[13px] font-bold text-sky-200 transition-all hover:border-sky-500/50 hover:bg-sky-500/[0.22] disabled:opacity-40"
            >
              <Plus className="h-3.5 w-3.5" />
              Quick task
            </button>
          </div>
        </div>

        {/* ── Stat strip ────────────────────────────────────────────────── */}
        <div className="mt-6 grid grid-cols-2 gap-3 md:grid-cols-4">
          <StatChip
            icon={<Sparkles className="h-3.5 w-3.5" />}
            label="Action queue"
            value={actionCount}
            accent={actionCount > 0 ? "amber" : "default"}
          />
          <StatChip
            icon={<Inbox className="h-3.5 w-3.5" />}
            label="Captured"
            value={captureCount}
            accent={captureCount > 0 ? "sky" : "default"}
          />
          <StatChip
            icon={<ClipboardCheck className="h-3.5 w-3.5" />}
            label="Needs review"
            value={reviewTasks.length + approvalProjects.length}
            accent={reviewTasks.length + approvalProjects.length > 0 ? "violet" : "default"}
          />
          <StatChip
            icon={<Bell className="h-3.5 w-3.5" />}
            label="Unread"
            value={unreadCount}
            accent={unreadCount > 0 ? "red" : "default"}
          />
        </div>
      </div>

      {/* ── Main content ────────────────────────────────────────────────────── */}
      {loading ? (
        <div className="space-y-5">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-48 rounded-[24px] border border-white/[0.06] bg-white/[0.02] animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="space-y-5">
            <DarkSectionCard
              eyebrow="Action center"
              title="Needs attention"
              description="The few things currently worth deciding, reviewing, or clearing."
              accent="amber"
              action={
                unreadNotifications.length > 0 ? (
                  <button
                    onClick={() => void markAllAsRead()}
                    className="rounded-xl border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] font-semibold text-white/50 transition-all hover:border-white/[0.12] hover:text-white/75"
                  >
                    Mark all read
                  </button>
                ) : undefined
              }
            >
              {actionCount === 0 ? (
                <div className="rounded-2xl border border-dashed border-white/[0.06] bg-white/[0.01] p-8 text-center">
                  <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl border border-white/[0.08] bg-white/[0.04]">
                    <CheckCircle2 className="h-5 w-5 text-emerald-400/50" />
                  </div>
                  <p className="text-[14px] font-semibold text-white/35">All clear</p>
                  <p className="mt-1 text-[12px] text-white/20">
                    Your queue is empty. New reviews, approvals, or notifications will appear here.
                  </p>
                </div>
              ) : (
                <div className="space-y-6">
                  <DarkActionSection title="Task reviews" count={reviewTasks.length} emptyText="No pending task reviews.">
                    {reviewTasks.map((task) => (
                      <DarkActionRow
                        key={task.id}
                        title={task.title}
                        badge={task.priority}
                        badgeAccent="violet"
                        meta={[
                          task.project?.name || "No project",
                          task.reviewer?.full_name || task.reviewer?.email || "Reviewer not set",
                          task.review_requested_at ? `requested ${formatRelativeDate(task.review_requested_at)}` : null,
                        ]}
                        description={task.description || ""}
                        actions={
                          <button
                            onClick={() => router.push(`/tasks?task=${task.id}`)}
                            className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
                          >
                            Open
                          </button>
                        }
                      />
                    ))}
                  </DarkActionSection>

                  <DarkActionSection title="Project approvals" count={approvalProjects.length} emptyText="No pending project approvals.">
                    {approvalProjects.map((project) => (
                      <DarkActionRow
                        key={project.id}
                        title={project.name}
                        badge={project.health}
                        badgeAccent="amber"
                        meta={[
                          project.goal || "No project goal yet",
                          project.approver?.full_name || project.approver?.email || "Approver not set",
                          project.approval_requested_at ? `requested ${formatRelativeDate(project.approval_requested_at)}` : null,
                        ]}
                        description={project.approval_notes || project.description}
                        actions={
                          <button
                            onClick={() => router.push(`/projects/${project.id}`)}
                            className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
                          >
                            Open
                          </button>
                        }
                      />
                    ))}
                  </DarkActionSection>

                  <DarkActionSection
                    title="Organizations"
                    count={incomingInvitations.length + pendingJoinRequests.length}
                    emptyText="No organization invitations or join requests."
                  >
                    {incomingInvitations.map((invitation) => {
                      const organization = organizations.find(
                        (item) => item.id === invitation.organization_id
                      );
                      return (
                        <DarkActionRow
                          key={invitation.id}
                          title={organization?.name || invitation.email}
                          badge={invitation.role}
                          badgeAccent="sky"
                          meta={[
                            "Organization invitation",
                            `sent ${formatRelativeDate(invitation.created_at)}`,
                          ]}
                          description={invitation.message || "You have been invited to join this organization."}
                          actions={
                            <div className="flex gap-2">
                              <button
                                onClick={() => void runBusyAction(invitation.id, () => acceptOrganizationInvitation(invitation.id))}
                                disabled={busyActionId === invitation.id}
                                className="rounded-xl border border-emerald-500/25 bg-emerald-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-emerald-300 transition-all hover:border-emerald-500/40 disabled:opacity-40"
                              >
                                Accept
                              </button>
                              <button
                                onClick={() => void runBusyAction(`decline-${invitation.id}`, () => declineOrganizationInvitation(invitation.id))}
                                disabled={busyActionId === `decline-${invitation.id}`}
                                className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/50 transition-all hover:border-white/[0.14] disabled:opacity-40"
                              >
                                Decline
                              </button>
                            </div>
                          }
                        />
                      );
                    })}

                    {pendingJoinRequests.map((request) => (
                      <DarkActionRow
                        key={request.id}
                        title={request.organizationName}
                        badge="join request"
                        badgeAccent="sky"
                        meta={[request.email, `requested ${formatRelativeDate(request.requested_at)}`]}
                        description={request.message || "No message attached to this join request."}
                        actions={
                          <div className="flex gap-2">
                            <button
                              onClick={() => void runBusyAction(request.id, async () => { await updateOrganizationJoinRequest(request.id, "approved"); })}
                              disabled={busyActionId === request.id}
                              className="rounded-xl border border-emerald-500/25 bg-emerald-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-emerald-300 transition-all hover:border-emerald-500/40 disabled:opacity-40"
                            >
                              Approve
                            </button>
                            <button
                              onClick={() => void runBusyAction(`decline-${request.id}`, async () => { await updateOrganizationJoinRequest(request.id, "declined"); })}
                              disabled={busyActionId === `decline-${request.id}`}
                              className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/50 transition-all hover:border-white/[0.14] disabled:opacity-40"
                            >
                              Decline
                            </button>
                          </div>
                        }
                      />
                    ))}
                  </DarkActionSection>

                  <DarkActionSection title="Notifications" count={unreadNotifications.length} emptyText="No unread notifications.">
                    {unreadNotifications.map((notification) => (
                      <DarkActionRow
                        key={notification.id}
                        title={notification.title}
                        badge={notification.kind.replace(/_/g, " ")}
                        badgeAccent="default"
                        meta={[
                          notification.actor?.full_name || notification.actor?.email || "System",
                          formatRelativeDate(notification.created_at),
                        ]}
                        description={notification.body}
                        actions={
                          <div className="flex gap-2">
                            <button
                              onClick={() => void runBusyAction(`read-${notification.id}`, async () => { await markAsRead(notification.id); })}
                              disabled={busyActionId === `read-${notification.id}`}
                              className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/50 transition-all hover:border-white/[0.14] disabled:opacity-40"
                            >
                              Read
                            </button>
                            <button
                              onClick={() => void runBusyAction(`open-${notification.id}`, async () => {
                                if (!notification.is_read) await markAsRead(notification.id);
                                router.push(notification.link || "/notifications");
                              })}
                              disabled={busyActionId === `open-${notification.id}`}
                              className="rounded-xl border border-sky-500/25 bg-sky-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-sky-300 transition-all hover:border-sky-500/40 disabled:opacity-40"
                            >
                              Open
                            </button>
                          </div>
                        }
                      />
                    ))}
                  </DarkActionSection>
                </div>
              )}
            </DarkSectionCard>

            {/* Quick capture */}
            <DarkSectionCard eyebrow="Capture" title="Quick capture" description="Add first, organize later. The inbox keeps rough ideas moving." accent="sky">
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <button
                  onClick={handleQuickNote}
                  disabled={!canEditNotes}
                  className="flex flex-col items-center gap-2 rounded-[18px] border border-white/[0.07] bg-white/[0.025] p-4 text-center transition-all hover:border-white/[0.12] hover:bg-white/[0.045] disabled:opacity-40"
                >
                  <div className="flex h-9 w-9 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.05]">
                    <FileText className="h-4 w-4 text-white/40" />
                  </div>
                  <span className="text-[12px] font-semibold text-white/55">Quick note</span>
                </button>
                <button
                  onClick={() => setFormOpen(true)}
                  disabled={!canEditTasks}
                  className="flex flex-col items-center gap-2 rounded-[18px] border border-sky-500/15 bg-sky-500/[0.05] p-4 text-center transition-all hover:border-sky-500/25 hover:bg-sky-500/[0.09] disabled:opacity-40"
                >
                  <div className="flex h-9 w-9 items-center justify-center rounded-xl border border-sky-500/20 bg-sky-500/[0.12]">
                    <Plus className="h-4 w-4 text-sky-400" />
                  </div>
                  <span className="text-[12px] font-semibold text-sky-300/70">Quick task</span>
                </button>
              </div>
            </DarkSectionCard>

            {/* Inbox intelligence */}
            <DarkSectionCard
              eyebrow="Inbox Intelligence"
              title="AI Sorter"
              description="Turn loose capture into decisions without manually opening every item."
              accent="violet"
            >
              <div className="grid gap-3">
                <InboxIntelligenceCard
                  icon={<Bot className="h-4 w-4" />}
                  title="Sort my inbox"
                  description={`${captureCount} captured item${captureCount === 1 ? "" : "s"} waiting for structure.`}
                  onClick={() =>
                    router.push(
                      aiPromptHref(
                        "Act as my Mindavio Inbox Sorter. Review my loose inbox tasks and notes. Suggest what should become a task, reminder, note, project, or be archived. Give me a prioritized processing plan and ask for confirmation before changing anything.",
                      ),
                    )
                  }
                />
                <InboxIntelligenceCard
                  icon={<Sparkles className="h-4 w-4" />}
                  title="Extract next actions"
                  description="Find concrete actions hiding inside loose notes and rough captures."
                  onClick={() =>
                    router.push(
                      aiPromptHref(
                        "Analyze my loose notes and captured items. Extract concrete next actions, possible reminders, and project links. Do not create anything yet; first show me a proposed action list and ask for Go.",
                      ),
                    )
                  }
                />
                <InboxIntelligenceCard
                  icon={<ClipboardCheck className="h-4 w-4" />}
                  title="Clear review queue"
                  description={`${actionCount} attention item${actionCount === 1 ? "" : "s"} across reviews, approvals, invites, and notifications.`}
                  onClick={() =>
                    router.push(
                      aiPromptHref(
                        "Help me clear my Mindavio action queue. Look at pending reviews, approvals, invitations, notifications, loose tasks, and loose notes. Give me the fastest safe order to process them and what I should ignore for now.",
                      ),
                    )
                  }
                />
              </div>
            </DarkSectionCard>

            <DarkSectionCard
              eyebrow="Dokumente"
              title="Rechnungen & Angebote"
              description="Dokumente, die du aus Invoicing in die Inbox gelegt hast."
              accent="amber"
              action={
                activeGmailConnection ? (
                  <button
                    onClick={() => window.open("https://mail.google.com/mail/u/0/#drafts", "_blank", "noopener,noreferrer")}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] font-semibold text-white/45 transition-all hover:border-white/[0.12] hover:text-white/70"
                  >
                    <ExternalLink className="h-3.5 w-3.5" />
                    Gmail
                  </button>
                ) : (
                  <button
                    onClick={() => {
                      window.location.href = "/api/integrations/gmail/connect";
                    }}
                    className="inline-flex items-center gap-1.5 rounded-xl border border-sky-500/25 bg-sky-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-sky-300 transition-all hover:border-sky-500/40"
                  >
                    <Mail className="h-3.5 w-3.5" />
                    Mail verbinden
                  </button>
                )
              }
            >
              {draftMessage ? (
                <div className="mb-3 rounded-2xl border border-emerald-500/15 bg-emerald-500/[0.06] px-4 py-3 text-[12px] font-semibold text-emerald-300/75">
                  {draftMessage}
                </div>
              ) : null}

              {inboxDocuments.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-white/[0.06] bg-white/[0.01] px-4 py-5 text-center">
                  <p className="text-[13px] text-white/25">Keine Rechnungen oder Angebote in der Inbox.</p>
                </div>
              ) : (
                <div className="space-y-2.5">
                  {inboxDocuments.slice(0, 8).map((invoice) => {
                    const documentLabel = getInvoiceDocumentLabel(invoice);
                    return (
                      <DarkActionRow
                        key={invoice.id}
                        title={`${documentLabel} ${invoice.invoice_number}`}
                        badge={invoice.status}
                        badgeAccent={invoice.document_type === "quote" ? "violet" : "amber"}
                        meta={[
                          invoice.counterparty_name || "Kein Empfänger",
                          formatInvoiceMoney(invoice.total_cents, invoice.currency),
                          invoice.inbox_at ? `in Inbox ${formatRelativeDate(invoice.inbox_at)}` : null,
                        ]}
                        description={
                          invoice.inbox_note ||
                          `${documentLabel} als PDF vorbereiten, herunterladen oder als Gmail-Entwurf mit Anhang erstellen.`
                        }
                        actions={
                          <div className="flex flex-wrap gap-2">
                            <button
                              onClick={() => router.push(`/invoicing?invoice=${invoice.id}`)}
                              className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/55 transition-all hover:border-white/[0.14] hover:text-white"
                            >
                              Open
                            </button>
                            <button
                              onClick={() => void runBusyAction(`download-${invoice.id}`, () => handleDownloadDocument(invoice))}
                              disabled={busyActionId === `download-${invoice.id}`}
                              className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/55 transition-all hover:border-white/[0.14] hover:text-white disabled:opacity-40"
                            >
                              <Download className="h-3.5 w-3.5" />
                              PDF
                            </button>
                            <button
                              onClick={() => void runBusyAction(`gmail-${invoice.id}`, () => handleCreateGmailDraft(invoice))}
                              disabled={!activeGmailConnection || busyActionId === `gmail-${invoice.id}`}
                              className="inline-flex items-center gap-1.5 rounded-xl border border-sky-500/25 bg-sky-500/[0.10] px-3 py-1.5 text-[12px] font-semibold text-sky-300 transition-all hover:border-sky-500/40 disabled:opacity-40"
                            >
                              <Mail className="h-3.5 w-3.5" />
                              Entwurf
                            </button>
                            <button
                              onClick={() => void runBusyAction(`clear-doc-${invoice.id}`, () => removeInvoiceFromInbox(invoice.id))}
                              disabled={busyActionId === `clear-doc-${invoice.id}`}
                              className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/45 transition-all hover:border-white/[0.14] hover:text-white disabled:opacity-40"
                            >
                              Done
                            </button>
                          </div>
                        }
                      />
                    );
                  })}
                </div>
              )}
            </DarkSectionCard>

            {/* Inbox tasks */}
            <DarkSectionCard
              eyebrow="Tasks"
              title="Inbox tasks"
              description="Tasks that still need a project, structure, or a clearer home."
              accent="indigo"
              action={
                inboxTasks.length > 0 ? (
                  <button
                    onClick={() => router.push("/tasks")}
                    className="rounded-xl border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] font-semibold text-white/45 transition-all hover:border-white/[0.12] hover:text-white/70"
                  >
                    View all
                  </button>
                ) : undefined
              }
            >
              {inboxTasks.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-white/[0.06] bg-white/[0.01] px-4 py-5 text-center">
                  <p className="text-[13px] text-white/25">No open inbox tasks right now.</p>
                </div>
              ) : (
                <div className="space-y-2.5">
                  {inboxTasks.slice(0, 8).map((task) => (
                    <DarkActionRow
                      key={task.id}
                      title={task.title}
                      badge={task.priority}
                      badgeAccent="violet"
                      meta={[
                        task.deadline ? `due ${formatRelativeDate(task.deadline)}` : "No deadline",
                        task.status.replace("_", " "),
                      ]}
                      description={task.description || ""}
                      actions={
                        <div className="flex gap-2">
                          <button
                            onClick={() => router.push(`/tasks?task=${task.id}`)}
                            className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/55 transition-all hover:border-white/[0.14] hover:text-white"
                          >
                            Open
                          </button>
                          <button
                            onClick={() => void toggleTaskStatus(task.id, task.status)}
                            disabled={!canEditTasks}
                            className="rounded-xl border border-emerald-500/20 bg-emerald-500/[0.07] px-3 py-1.5 text-[12px] font-semibold text-emerald-300/70 transition-all hover:border-emerald-500/35 disabled:opacity-40"
                          >
                            Done
                          </button>
                        </div>
                      }
                    />
                  ))}
                </div>
              )}
            </DarkSectionCard>

            {/* Loose notes */}
            <DarkSectionCard
              eyebrow="Notes"
              title="Loose notes"
              description="Notes still waiting for a folder, project, or stronger context."
              accent="teal"
              action={
                inboxNotes.length > 0 ? (
                  <button
                    onClick={() => router.push("/notes")}
                    className="rounded-xl border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] font-semibold text-white/45 transition-all hover:border-white/[0.12] hover:text-white/70"
                  >
                    View all
                  </button>
                ) : undefined
              }
            >
              {inboxNotes.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-white/[0.06] bg-white/[0.01] px-4 py-5 text-center">
                  <p className="text-[13px] text-white/25">No loose notes right now.</p>
                </div>
              ) : (
                <div className="space-y-2.5">
                  {inboxNotes.slice(0, 8).map((note) => (
                    <DarkActionRow
                      key={note.id}
                      title={note.title || "Untitled"}
                      badge={note.is_pinned ? "pinned" : undefined}
                      badgeAccent="teal"
                      meta={[
                        note.linked_task_id ? "Linked to task" : "Not linked yet",
                        `updated ${formatRelativeDate(note.updated_at)}`,
                      ]}
                      description="Open this note and file it into the right project or folder when ready."
                      actions={
                        <button
                          onClick={() => router.push(`/notes/${note.id}`)}
                          className="rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[12px] font-semibold text-white/55 transition-all hover:border-white/[0.14] hover:text-white"
                        >
                          Open
                        </button>
                      }
                    />
                  ))}
                </div>
              )}
            </DarkSectionCard>
        </div>
      )}

      {formOpen && (
        <TaskForm
          open={formOpen}
          onClose={() => setFormOpen(false)}
          onSubmit={handleCreateTask}
          projects={projects}
          goals={goals}
          tags={tags}
          onCreateTag={createTag}
        />
      )}
    </div>
  );
}

/* ── Sub-components ─────────────────────────────────────────────────────────── */

type AccentKey = "default" | "amber" | "sky" | "violet" | "indigo" | "teal" | "red";

const ACCENT_CFG: Record<AccentKey, { border: string; dot: string; eyebrow: string }> = {
  default: {
    border: "border-l-white/[0.10]",
    dot:    "bg-white/20",
    eyebrow:"text-white/25",
  },
  amber: {
    border: "border-l-sky-500/40",
    dot:    "bg-sky-400",
    eyebrow:"text-sky-400/60",
  },
  sky: {
    border: "border-l-sky-500/40",
    dot:    "bg-sky-400",
    eyebrow:"text-sky-400/60",
  },
  violet: {
    border: "border-l-sky-500/40",
    dot:    "bg-sky-400",
    eyebrow:"text-sky-400/60",
  },
  indigo: {
    border: "border-l-sky-500/40",
    dot:    "bg-sky-400",
    eyebrow:"text-sky-400/60",
  },
  teal: {
    border: "border-l-sky-500/40",
    dot:    "bg-sky-400",
    eyebrow:"text-sky-400/60",
  },
  red: {
    border: "border-l-red-500/40",
    dot:    "bg-red-400",
    eyebrow:"text-red-400/60",
  },
};

function InboxIntelligenceCard({
  description,
  icon,
  onClick,
  title,
}: {
  description: string;
  icon: React.ReactNode;
  onClick: () => void;
  title: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="group flex items-center gap-3 rounded-2xl border border-sky-400/10 bg-sky-400/[0.035] p-3 text-left transition-all hover:border-sky-400/20 hover:bg-sky-400/[0.065]"
    >
      <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-sky-400/15 bg-sky-400/[0.10] text-sky-300">
        {icon}
      </div>
      <div className="min-w-0 flex-1">
        <p className="text-[13px] font-semibold text-white/72">{title}</p>
        <p className="mt-0.5 line-clamp-2 text-[12px] leading-relaxed text-white/32">{description}</p>
      </div>
      <span className="text-[11px] font-bold uppercase tracking-[0.14em] text-sky-300/45 transition group-hover:text-sky-200/70">
        Ask AI
      </span>
    </button>
  );
}

function StatChip({
  icon,
  label,
  value,
  accent = "default",
}: {
  icon: React.ReactNode;
  label: string;
  value: number;
  accent?: AccentKey;
}) {
  const cfg = ACCENT_CFG[accent];
  return (
    <div className={cn(
      "rounded-2xl border border-white/[0.05] bg-white/[0.025] p-4 transition-all",
      value > 0 && accent !== "default" && "border-white/[0.08] bg-white/[0.04]",
    )}>
      <div className={cn("mb-1 flex items-center gap-1.5", cfg.eyebrow)}>
        {icon}
        <span className="text-[10px] font-bold uppercase tracking-[0.14em]">{label}</span>
      </div>
      <p className={cn(
        "text-[26px] font-bold",
        value > 0 && accent === "red" ? "text-red-400" :
        value > 0 && accent !== "default" ? "text-sky-400" :
        "text-white",
      )}>
        {value}
      </p>
    </div>
  );
}

function DarkSectionCard({
  eyebrow,
  title,
  description,
  accent = "default",
  action,
  children,
}: {
  eyebrow: string;
  title: string;
  description: string;
  accent?: AccentKey;
  action?: React.ReactNode;
  children: React.ReactNode;
}) {
  const cfg = ACCENT_CFG[accent];
  return (
    <section className="rounded-[24px] border border-white/[0.07] bg-[#0e0c15] p-6">
      <div className="mb-5 flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <span className={cn("h-1.5 w-1.5 rounded-full", cfg.dot)} />
            <p className={cn("text-[10px] font-bold uppercase tracking-[0.18em]", cfg.eyebrow)}>
              {eyebrow}
            </p>
          </div>
          <h2 className="mt-1.5 text-[18px] font-bold tracking-tight text-white">{title}</h2>
          <p className="mt-0.5 text-[12px] text-white/35">{description}</p>
        </div>
        {action}
      </div>
      {children}
    </section>
  );
}

function DarkActionSection({
  title,
  count,
  emptyText,
  children,
}: {
  title: string;
  count: number;
  emptyText: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between gap-3">
        <p className="text-[13px] font-semibold text-white/60">{title}</p>
        <span className="rounded-full border border-white/[0.07] bg-white/[0.04] px-2 py-0.5 text-[10px] font-bold text-white/35">
          {count}
        </span>
      </div>
      {count === 0 ? (
        <div className="rounded-2xl border border-dashed border-white/[0.05] px-4 py-3.5 text-[12px] text-white/25">
          {emptyText}
        </div>
      ) : (
        <div className="space-y-2.5">{children}</div>
      )}
    </div>
  );
}

function DarkActionRow({
  title,
  meta,
  description,
  badge,
  badgeAccent = "default",
  actions,
}: {
  title: string;
  meta: Array<string | null | undefined>;
  description?: string;
  badge?: string;
  badgeAccent?: AccentKey;
  actions?: React.ReactNode;
}) {
  const filteredMeta = meta.filter(Boolean) as string[];
  const badgeCfg: Record<AccentKey, string> = {
    default: "border-white/[0.07] bg-white/[0.04] text-white/35",
    amber:   "border-sky-500/20 bg-sky-500/[0.08] text-sky-300/70",
    sky:     "border-sky-500/20 bg-sky-500/[0.08] text-sky-300/70",
    violet:  "border-sky-500/20 bg-sky-500/[0.08] text-sky-300/70",
    indigo:  "border-sky-500/20 bg-sky-500/[0.08] text-sky-300/70",
    teal:    "border-sky-500/20 bg-sky-500/[0.08] text-sky-300/70",
    red:     "border-red-500/20 bg-red-500/[0.08] text-red-300/70",
  };

  return (
    <div className="flex flex-wrap items-start justify-between gap-3 rounded-[18px] border border-white/[0.06] bg-white/[0.02] px-4 py-3 transition-all hover:border-white/[0.09] hover:bg-white/[0.035]">
      <div className="min-w-0 flex-1">
        <div className="flex flex-wrap items-center gap-2">
          <p className="truncate text-[13px] font-semibold text-white/80">{title}</p>
          {badge && (
            <span className={cn("rounded-full border px-2 py-0.5 text-[10px] font-semibold", badgeCfg[badgeAccent])}>
              {badge}
            </span>
          )}
        </div>
        {filteredMeta.length > 0 && (
          <p className="mt-0.5 text-[11px] text-white/30">{filteredMeta.join(" · ")}</p>
        )}
        {description && (
          <p className="mt-1.5 line-clamp-2 text-[12px] leading-relaxed text-white/35">{description}</p>
        )}
      </div>
      {actions && <div className="flex shrink-0 items-center gap-2">{actions}</div>}
    </div>
  );
}
