import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Link } from "react-router-dom";
import api from "../../api/client";
import ComposeEmailModal from "../components/ComposeEmailModal";
import MailViewModal from "../components/MailViewModal";

const TABS = ["inbound", "outbound"];
const CLIENT_FILTER_TABS = ["all", "clients"];
const MAILBOX_TABS = ["sales", "support", "both"];
const READ_FILTER_TABS = ["all", "unread", "read", "important"];

const FILTER_COLORS = {
  inbound: "var(--mail-filter-green)",
  outbound: "var(--mail-filter-blue)",
  all_messages: "var(--mail-filter-yellow)",
  clients_only: "var(--mail-filter-green)",
  sales: "var(--mail-filter-orange)",
  support: "var(--mail-filter-red)",
  mailbox_all: "var(--mail-filter-green)",
  read_all: "var(--mail-filter-yellow)",
  unread: "var(--mail-filter-green)",
  read: "var(--mail-filter-blue)",
  important: "var(--mail-filter-red)",
};

// Fixed pixel width of the identity (sender/recipient) column
const ID_COL_W = 210;

const DEFAULT_POLL_INTERVAL = 30; // seconds

function getPollInterval() {
  const stored = parseInt(localStorage.getItem("mail_poll_interval"), 10);
  if (!isNaN(stored) && stored >= 15 && stored <= 300) return stored;
  return DEFAULT_POLL_INTERVAL;
}

// Relative time helper
function relativeTime(dateStr) {
  if (!dateStr) return "";
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diff = now - then;
  if (diff < 0) return "just now";
  const secs = Math.floor(diff / 1000);
  if (secs < 60) return "just now";
  const mins = Math.floor(secs / 60);
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}d ago`;
  const weeks = Math.floor(days / 7);
  if (weeks < 5) return `${weeks}w ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months}mo ago`;
  return `${Math.floor(months / 12)}y ago`;
}

function segmentedButtonStyle(active, color, borderRight = "none", inactiveTextColor = "var(--text-white)") {
  return {
    backgroundColor: active ? color : "var(--bg-card)",
    color: active ? "var(--text-white)" : inactiveTextColor,
    borderRight,
    fontWeight: active ? 600 : 500,
  };
}

function BookmarkButton({ important, onClick }) {
  return (
    <button
      type="button"
      onClick={(e) => { e.stopPropagation(); onClick(); }}
      title={important ? "Remove bookmark" : "Bookmark"}
      style={{
        background: "none",
        border: "none",
        padding: "0 2px",
        cursor: "pointer",
        lineHeight: 1,
        color: important ? "#f59e0b" : "var(--border-primary)",
        opacity: important ? 1 : 0.35,
        flexShrink: 0,
        transition: "opacity 0.15s, color 0.15s",
        display: "flex",
        alignItems: "center",
      }}
      className="row-star"
    >
      <svg width="13" height="16" viewBox="0 0 13 16" fill={important ? "#f59e0b" : "currentColor"} xmlns="http://www.w3.org/2000/svg">
        <path d="M1.5 1C1.22386 1 1 1.22386 1 1.5V14.5C1 14.7652 1.14583 14.9627 1.35217 15.0432C1.55851 15.1237 1.78462 15.0693 1.93301 14.9045L6.5 9.81L11.067 14.9045C11.2154 15.0693 11.4415 15.1237 11.6478 15.0432C11.8542 14.9627 12 14.7652 12 14.5V1.5C12 1.22386 11.7761 1 11.5 1H1.5Z"/>
      </svg>
    </button>
  );
}

// Settings / Signature Modal
function SettingsModal({ open, onClose }) {
  const [signature, setSignature] = useState(() => localStorage.getItem("mail_signature") || "");
  const [saved, setSaved] = useState(false);
  const [pollInterval, setPollInterval] = useState(() => getPollInterval());
  const editorRef = useRef(null);
  const quillRef = useRef(null);
  const [quillLoaded, setQuillLoaded] = useState(!!window.Quill);

  // ESC to close
  useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  // Load Quill (reuse global loader pattern)
  useEffect(() => {
    if (!open) return;
    if (window.Quill) { setQuillLoaded(true); return; }
    if (!document.getElementById("__quill_js__")) {
      const link = document.createElement("link");
      link.id = "__quill_css__";
      link.rel = "stylesheet";
      link.href = "https://cdn.quilljs.com/1.3.7/quill.snow.css";
      document.head.appendChild(link);
      const script = document.createElement("script");
      script.id = "__quill_js__";
      script.src = "https://cdn.quilljs.com/1.3.7/quill.min.js";
      script.onload = () => setQuillLoaded(true);
      document.head.appendChild(script);
    }
  }, [open]);

  useEffect(() => {
    if (!open || !quillLoaded || !editorRef.current || quillRef.current) return;
    const q = new window.Quill(editorRef.current, {
      theme: "snow",
      placeholder: "Your signature...",
      modules: {
        toolbar: [
          ["bold", "italic", "underline"],
          [{ color: [] }],
          ["link"],
          ["clean"],
        ],
      },
    });
    // Load existing signature HTML
    const saved = localStorage.getItem("mail_signature") || "";
    if (saved) q.clipboard.dangerouslyPasteHTML(saved);
    quillRef.current = q;
    return () => { quillRef.current = null; };
  }, [open, quillLoaded]);

  const handleSave = () => {
    const html = quillRef.current ? quillRef.current.root.innerHTML : signature;
    localStorage.setItem("mail_signature", html);
    const interval = Math.min(300, Math.max(15, parseInt(pollInterval, 10) || DEFAULT_POLL_INTERVAL));
    localStorage.setItem("mail_poll_interval", String(interval));
    setSaved(true);
    setTimeout(() => { setSaved(false); onClose(); }, 800);
  };

  if (!open) return null;

  return (
    <div
      style={{ position: "fixed", inset: 0, zIndex: 1100, backgroundColor: "rgba(0,0,0,0.55)", display: "flex", alignItems: "center", justifyContent: "center", padding: 60 }}
      onClick={onClose}
    >
      <div
        style={{ backgroundColor: "var(--bg-card)", border: "1px solid var(--border-primary)", borderRadius: 12, width: "min(700px, 94vw)", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "0 20px 60px rgba(0,0,0,0.4)", maxHeight: "85vh" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: "1px solid var(--border-primary)", flexShrink: 0 }}>
          <h2 className="text-base font-semibold" style={{ color: "var(--text-heading)" }}>Mail Settings</h2>
          <button type="button" onClick={onClose} style={{ color: "var(--text-muted)", background: "none", border: "none", fontSize: 22, cursor: "pointer", lineHeight: 1 }}>×</button>
        </div>

        {/* Polling Rate */}
        <div className="px-5 pt-4 pb-3 flex-shrink-0" style={{ borderBottom: "1px solid var(--border-secondary)" }}>
          <p className="text-xs font-semibold uppercase tracking-wide mb-2" style={{ color: "var(--text-secondary)" }}>Auto-Check Interval</p>
          <div className="flex items-center gap-3">
            <input
              type="number"
              min={15}
              max={300}
              value={pollInterval}
              onChange={(e) => setPollInterval(e.target.value)}
              className="px-3 py-1.5 text-sm rounded-md border"
              style={{ backgroundColor: "var(--bg-input)", borderColor: "var(--border-primary)", color: "var(--text-primary)", width: 90 }}
            />
            <span className="text-sm" style={{ color: "var(--text-muted)" }}>seconds <span style={{ fontSize: 11 }}>(min 15, max 300)</span></span>
          </div>
          <p className="text-xs mt-1.5" style={{ color: "var(--text-muted)" }}>
            How often to check if new emails are available on the server. A banner will appear if new mail is found.
          </p>
        </div>

        <div className="px-5 pt-4 pb-2 flex-shrink-0">
          <p className="text-xs font-semibold uppercase tracking-wide mb-3" style={{ color: "var(--text-secondary)" }}>Email Signature</p>
        </div>

        <div className="flex-1 overflow-auto quill-sig-wrapper" style={{ minHeight: 200, paddingBottom: 0 }}>
          {quillLoaded ? (
            <div ref={editorRef} style={{ minHeight: 160, backgroundColor: "var(--bg-input)", color: "var(--text-primary)" }} />
          ) : (
            <div className="flex items-center justify-center py-12" style={{ color: "var(--text-muted)" }}>Loading editor...</div>
          )}
        </div>

        <div className="flex items-center justify-end gap-3 px-5 py-4" style={{ borderTop: "1px solid var(--border-primary)", flexShrink: 0 }}>
          {saved && <span className="text-xs" style={{ color: "var(--success-text)" }}>Saved!</span>}
          <button type="button" onClick={onClose} className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80" style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card)" }}>
            Cancel
          </button>
          <button type="button" onClick={handleSave} className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90" style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>
            Save Settings
          </button>
        </div>
      </div>

      <style>{`
        .quill-sig-wrapper .ql-toolbar { background: var(--bg-card-hover); border-color: var(--border-primary) !important; border-top: none !important; }
        .quill-sig-wrapper .ql-toolbar button, .quill-sig-wrapper .ql-toolbar .ql-picker-label { color: var(--text-secondary) !important; }
        .quill-sig-wrapper .ql-toolbar .ql-stroke { stroke: var(--text-secondary) !important; }
        .quill-sig-wrapper .ql-toolbar button:hover .ql-stroke, .quill-sig-wrapper .ql-toolbar button.ql-active .ql-stroke { stroke: var(--accent) !important; }
        .quill-sig-wrapper .ql-container { border-color: var(--border-secondary) !important; }
        .quill-sig-wrapper .ql-editor { color: var(--text-primary) !important; background: var(--bg-input) !important; min-height: 160px; }
        .quill-sig-wrapper .ql-editor.ql-blank::before { color: var(--text-muted) !important; font-style: normal !important; }
      `}</style>
    </div>
  );
}

export default function MailPage() {
  const [entries, setEntries]         = useState([]);
  const [customers, setCustomers]     = useState({});
  const [loading, setLoading]         = useState(true);
  const [error, setError]             = useState("");
  const [activeTab, setActiveTab]     = useState("inbound");
  const [clientFilter, setClientFilter] = useState("all");
  const [readFilter, setReadFilter]   = useState("all");
  const [search, setSearch]           = useState("");
  const [syncing, setSyncing]         = useState(false);
  const [syncResult, setSyncResult]   = useState(null);

  // New-mail banner
  const [newMailCount, setNewMailCount] = useState(0);
  const [bannerDismissed, setBannerDismissed] = useState(false);

  // Polling
  const pollIntervalRef = useRef(null);

  // Multi-select
  const [selected, setSelected]       = useState(new Set());
  const [hoveredId, setHoveredId]     = useState(null);
  const [deleting, setDeleting]       = useState(false);

  // Modals
  const [viewEntry, setViewEntry]     = useState(null);
  const [composeOpen, setComposeOpen] = useState(false);
  const [composeTo, setComposeTo]     = useState("");
  const [composeFromAccount, setComposeFromAccount] = useState("");
  const [mailboxFilter, setMailboxFilter] = useState("both");
  const [settingsOpen, setSettingsOpen] = useState(false);

  const loadAll = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const [mailData, custsData] = await Promise.all([
        api.get(`/crm/comms/email/all?limit=500&mailbox=${encodeURIComponent(mailboxFilter)}`),
        api.get("/crm/customers"),
      ]);
      setEntries(mailData.entries || []);
      const map = {};
      for (const c of custsData.customers || []) map[c.id] = c;
      setCustomers(map);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [mailboxFilter]);

  useEffect(() => { loadAll(); }, [loadAll]);

  // Clear selection when tab changes
  useEffect(() => { setSelected(new Set()); setReadFilter("all"); }, [activeTab]);

  // Auto-poll: check for new emails on server
  const startPolling = useCallback(() => {
    if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
    const intervalMs = getPollInterval() * 1000;
    pollIntervalRef.current = setInterval(async () => {
      try {
        const data = await api.get("/crm/comms/email/check");
        if (data.new_count > 0) {
          setNewMailCount(data.new_count);
          setBannerDismissed(false);
        }
      } catch {
        // silently ignore poll errors
      }
    }, intervalMs);
  }, []);

  useEffect(() => {
    startPolling();
    return () => { if (pollIntervalRef.current) clearInterval(pollIntervalRef.current); };
  }, [startPolling]);

  const syncEmails = async () => {
    setSyncing(true);
    setSyncResult(null);
    setNewMailCount(0);
    setBannerDismissed(false);
    try {
      const data = await api.post("/crm/comms/email/sync", {});
      setSyncResult(data);
      await loadAll();
    } catch (err) {
      setSyncResult({ error: err.message });
    } finally {
      setSyncing(false);
    }
  };

  const openReply = (toAddr, sourceAccount = "") => {
    setViewEntry(null);
    setComposeTo(toAddr || "");
    setComposeFromAccount(sourceAccount || "");
    setComposeOpen(true);
  };

  const toggleSelect = (id) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const deleteSelected = async () => {
    if (selected.size === 0) return;
    setDeleting(true);
    try {
      await api.post("/crm/comms/bulk-delete", { ids: [...selected] });
      setSelected(new Set());
      await loadAll();
    } catch (err) {
      setError(err.message);
    } finally {
      setDeleting(false);
    }
  };

  const toggleImportant = async (entry) => {
    const newVal = !entry.is_important;
    setEntries((prev) =>
      prev.map((e) => e.id === entry.id ? { ...e, is_important: newVal } : e)
    );
    try {
      await api.patch(`/crm/comms/${entry.id}/important`, { important: newVal });
    } catch {
      setEntries((prev) =>
        prev.map((e) => e.id === entry.id ? { ...e, is_important: !newVal } : e)
      );
    }
  };

  const openEntry = async (entry) => {
    setViewEntry(entry);
    // Mark inbound as read if not already
    if (entry.direction === "inbound" && !entry.is_read) {
      setEntries((prev) =>
        prev.map((e) => e.id === entry.id ? { ...e, is_read: true } : e)
      );
      try {
        await api.patch(`/crm/comms/${entry.id}/read`, { read: true });
      } catch {
        // non-critical — don't revert
      }
    }
  };

  const q = search.trim().toLowerCase();
  const customerEmailMap = useMemo(() => {
    const map = {};
    Object.values(customers).forEach((c) => {
      (c.contacts || []).forEach((ct) => {
        if (ct?.type === "email" && ct?.value) map[String(ct.value).toLowerCase()] = c.id;
      });
    });
    return map;
  }, [customers]);

  const resolveCustomerId = useCallback((entry) => {
    if (entry.customer_id && customers[entry.customer_id]) return entry.customer_id;
    const candidates = [];
    if (entry.from_addr) candidates.push(String(entry.from_addr).toLowerCase());
    const toList = Array.isArray(entry.to_addrs) ? entry.to_addrs : (entry.to_addrs ? [entry.to_addrs] : []);
    toList.forEach((addr) => candidates.push(String(addr).toLowerCase()));
    for (const addr of candidates) {
      if (customerEmailMap[addr]) return customerEmailMap[addr];
    }
    return null;
  }, [customerEmailMap, customers]);

  const tabEntries = entries.filter((e) => e.direction === activeTab);
  const clientFiltered = clientFilter === "clients"
    ? tabEntries.filter((e) => !!resolveCustomerId(e))
    : tabEntries;
  const readFiltered = readFilter === "unread"
    ? clientFiltered.filter((e) => !e.is_read)
    : readFilter === "read"
      ? clientFiltered.filter((e) => !!e.is_read)
      : readFilter === "important"
        ? clientFiltered.filter((e) => !!e.is_important)
      : clientFiltered;
  const filtered = readFiltered.filter((e) => {
    if (!q) return true;
    const custId = resolveCustomerId(e);
    const cust = custId ? customers[custId] : null;
    return (
      (e.subject || "").toLowerCase().includes(q) ||
      (e.body || "").toLowerCase().includes(q) ||
      (e.from_addr || "").toLowerCase().includes(q) ||
      (cust?.name || "").toLowerCase().includes(q) ||
      (cust?.organization || "").toLowerCase().includes(q)
    );
  });

  const unreadInboundCount = entries.filter((e) => e.direction === "inbound" && !e.is_read).length;
  const anySelected = selected.size > 0;
  const showBanner = newMailCount > 0 && !bannerDismissed;

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-5">
        <div>
          <h1 className="text-xl font-bold" style={{ color: "var(--text-heading)" }}>Mailbox</h1>
          <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>All synced emails</p>
        </div>
        <div className="flex items-center gap-2">
          {syncResult && (
            <span className="text-xs" style={{ color: syncResult.error ? "var(--danger-text)" : "var(--success-text)" }}>
              {syncResult.error ? syncResult.error : `${syncResult.new_count} new email${syncResult.new_count !== 1 ? "s" : ""}`}
            </span>
          )}
          <button
            onClick={() => { setComposeTo(""); setComposeFromAccount(""); setComposeOpen(true); }}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90"
            style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
          >
            ✉ Compose
          </button>
          <button
            onClick={syncEmails}
            disabled={syncing || loading}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid", borderColor: "var(--border-primary)", color: "var(--text-secondary)", opacity: (syncing || loading) ? 0.6 : 1 }}
          >
            {syncing ? "Syncing..." : "Sync Mail"}
          </button>
          <button
            onClick={loadAll}
            disabled={loading}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid", borderColor: "var(--border-primary)", color: "var(--text-secondary)", opacity: loading ? 0.6 : 1 }}
          >
            Refresh
          </button>
          <button
            onClick={() => setSettingsOpen(true)}
            title="Mail Settings"
            className="px-2 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid", borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
          >
            ⚙
          </button>
        </div>
      </div>

      {/* New-mail banner */}
      {showBanner && (
        <div
          className="flex items-center justify-between px-4 py-2.5 rounded-lg mb-4 text-sm"
          style={{ backgroundColor: "color-mix(in srgb, var(--accent) 12%, var(--bg-card))", border: "1px solid var(--accent)", color: "var(--text-heading)" }}
        >
          <span>
            <span style={{ fontWeight: 600 }}>{newMailCount} new email{newMailCount !== 1 ? "s" : ""}</span> available on server
          </span>
          <div className="flex items-center gap-2">
            <button
              onClick={syncEmails}
              disabled={syncing}
              className="px-3 py-1 text-xs rounded-md cursor-pointer hover:opacity-90"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: syncing ? 0.6 : 1 }}
            >
              {syncing ? "Syncing..." : "Sync Now"}
            </button>
            <button
              onClick={() => setBannerDismissed(true)}
              style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-muted)", fontSize: 18, lineHeight: 1, padding: "0 2px" }}
            >
              ×
            </button>
          </div>
        </div>
      )}

      {/* Tabs + Filters + Search + Bulk actions */}
      <div className="flex items-center gap-3 mb-4 flex-wrap">
        {/* Direction Tabs */}
        <div className="flex rounded-lg overflow-hidden" style={{ border: "1px solid var(--border-primary)" }}>
          {TABS.map((tab) => {
            const count = entries.filter((e) => e.direction === tab).length;
            const active = tab === activeTab;
            const unread = tab === "inbound" ? unreadInboundCount : 0;
            const color = tab === "inbound" ? FILTER_COLORS.inbound : FILTER_COLORS.outbound;
            return (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className="px-4 py-1.5 text-sm cursor-pointer capitalize"
                style={segmentedButtonStyle(
                  active,
                  color,
                  tab === "inbound" ? "1px solid var(--border-primary)" : "none",
                  color
                )}
              >
                {tab}{" "}
                <span style={{ opacity: 0.7, fontSize: 11 }}>({count})</span>
                {unread > 0 && (
                  <span
                    style={{
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      backgroundColor: active ? "rgba(255,255,255,0.25)" : "var(--accent)",
                      color: active ? "var(--text-white)" : "#fff",
                      borderRadius: 10, fontSize: 10, fontWeight: 700,
                      minWidth: 16, height: 16, padding: "0 4px", marginLeft: 5,
                    }}
                  >
                    {unread}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        {/* Client filter */}
        <div className="flex rounded-lg overflow-hidden" style={{ border: "1px solid var(--border-primary)" }}>
          {[["all", "All Messages"], ["clients", "Clients Only"]].map(([val, label]) => {
            const active = clientFilter === val;
            const color = val === "all" ? FILTER_COLORS.all_messages : FILTER_COLORS.clients_only;
            return (
              <button
                key={val}
                onClick={() => setClientFilter(val)}
                className="px-4 py-1.5 text-sm cursor-pointer"
                style={segmentedButtonStyle(active, color, val === "all" ? "1px solid var(--border-primary)" : "none")}
              >
                {label}
              </button>
            );
          })}
        </div>
        <div className="flex rounded-lg overflow-hidden" style={{ border: "1px solid var(--border-primary)" }}>
          {MAILBOX_TABS.map((tab) => {
            const active = mailboxFilter === tab;
            const label = tab === "both" ? "ALL" : tab[0].toUpperCase() + tab.slice(1);
            const color = tab === "sales" ? FILTER_COLORS.sales : tab === "support" ? FILTER_COLORS.support : FILTER_COLORS.mailbox_all;
            return (
              <button
                key={tab}
                onClick={() => setMailboxFilter(tab)}
                className="px-4 py-1.5 text-sm cursor-pointer"
                style={segmentedButtonStyle(active, color, tab !== "both" ? "1px solid var(--border-primary)" : "none")}
              >
                {label}
              </button>
            );
          })}
        </div>

        {/* Read status filter */}
        <div className="flex rounded-lg overflow-hidden" style={{ border: "1px solid var(--border-primary)" }}>
          {READ_FILTER_TABS.map((val) => {
            const active = readFilter === val;
            const label = val === "all" ? "All" : val === "unread" ? "Unread" : val === "read" ? "Read" : "Importants";
            const color = val === "all"
              ? FILTER_COLORS.read_all
              : val === "unread"
                ? FILTER_COLORS.unread
                : val === "read"
                  ? FILTER_COLORS.read
                  : FILTER_COLORS.important;
            return (
              <button
                key={val}
                onClick={() => setReadFilter(val)}
                className="px-4 py-1.5 text-sm cursor-pointer"
                style={segmentedButtonStyle(active, color, val !== "important" ? "1px solid var(--border-primary)" : "none")}
              >
                {label}
              </button>
            );
          })}
        </div>

        {/* Search */}
        <div style={{ flex: "1 1 320px", minWidth: 220, maxWidth: 800, display: "flex", gap: 8 }}>
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search subject, sender, customer..."
            className="px-3 text-sm rounded-md border"
            style={{
              height: 34,
              width: "100%",
              minWidth: 220,
              backgroundColor: "var(--bg-input)",
              borderColor: "var(--border-primary)",
              color: "var(--text-primary)",
            }}
          />
          {search && (
            <button
              onClick={() => setSearch("")}
              className="px-3 text-sm rounded-md cursor-pointer hover:opacity-80"
              style={{ height: 34, color: "var(--danger-text)", backgroundColor: "var(--danger-bg)", borderRadius: 6 }}
            >
              Clear
            </button>
          )}
        </div>

        {/* Bulk delete */}
        {anySelected && (
          <button
            onClick={deleteSelected}
            disabled={deleting}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80 ml-auto"
            style={{ backgroundColor: "var(--danger)", color: "#fff", opacity: deleting ? 0.6 : 1 }}
          >
            {deleting ? "Deleting..." : `Delete ${selected.size} selected`}
          </button>
        )}
      </div>

      {error && (
        <div className="text-sm rounded-md p-3 mb-4 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-12" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : filtered.length === 0 ? (
        <div className="rounded-lg p-10 text-center text-sm border" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}>
          {tabEntries.length === 0 ? `No ${activeTab} emails yet.` : "No emails match your search."}
        </div>
      ) : (
        <div>
          <div className="text-xs mb-3" style={{ color: "var(--text-muted)" }}>
            {filtered.length} email{filtered.length !== 1 ? "s" : ""}
            {anySelected && <span style={{ color: "var(--accent)", marginLeft: 8 }}>{selected.size} selected</span>}
          </div>

          <div className="rounded-lg border overflow-hidden" style={{ borderColor: "var(--border-primary)" }}>
            {filtered.map((entry, idx) => {
              const resolvedCustomerId = resolveCustomerId(entry);
              const customer = resolvedCustomerId ? customers[resolvedCustomerId] : null;
              const addrLine = activeTab === "inbound"
                ? (entry.from_addr || "")
                : (Array.isArray(entry.to_addrs) ? entry.to_addrs[0] : (entry.to_addrs || ""));
              const isSelected = selected.has(entry.id);
              const isKnownCustomer = !!customer;
              const isUnread = entry.direction === "inbound" && !entry.is_read;

              return (
                <div
                  key={entry.id}
                  className={idx > 0 ? "border-t" : ""}
                  style={{ borderColor: "var(--border-secondary)" }}
                  onMouseEnter={() => setHoveredId(entry.id)}
                  onMouseLeave={() => setHoveredId(null)}
                >
                  <div
                    className="flex items-center gap-3 px-3 py-3 cursor-pointer"
                    style={{
                      backgroundColor: isSelected
                        ? "color-mix(in srgb, var(--btn-primary) 10%, var(--bg-card))"
                        : isUnread
                          ? "color-mix(in srgb, var(--accent) 5%, var(--bg-card))"
                          : "var(--bg-card)",
                      transition: "background-color 0.1s",
                    }}
                    onClick={() => {
                      if (anySelected) toggleSelect(entry.id);
                      else openEntry(entry);
                    }}
                  >
                    {/* Unread dot */}
                    <div style={{ width: 8, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                      {isUnread && (
                        <span style={{ width: 7, height: 7, borderRadius: "50%", backgroundColor: "var(--accent)", display: "block", flexShrink: 0 }} />
                      )}
                    </div>

                    {/* Bookmark */}
                    <BookmarkButton important={entry.is_important} onClick={() => toggleImportant(entry)} />

                    {/* Identity column */}
                    <div style={{ width: ID_COL_W, flexShrink: 0, minWidth: 0, overflow: "hidden" }}>
                      {isKnownCustomer ? (
                        <>
                          <Link
                            to={`/crm/customers/${resolvedCustomerId}`}
                            className="hover:underline block text-xs leading-tight"
                            style={{ color: "var(--accent)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: isUnread ? 700 : 500 }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            {customer.name}
                          </Link>
                          {customer.organization && (
                            <span
                              className="block text-xs leading-tight"
                              style={{ color: "var(--accent)", opacity: 0.75, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
                            >
                              {customer.organization}
                            </span>
                          )}
                        </>
                      ) : (
                        <span
                          className="block text-xs leading-tight"
                          style={{ color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: isUnread ? 700 : 500 }}
                        >
                          {addrLine}
                        </span>
                      )}
                    </div>

                    {/* Subject + preview */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span
                          className="text-sm"
                          style={{ color: "var(--text-heading)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", display: "block", fontWeight: isUnread ? 700 : 400 }}
                        >
                          {entry.subject || <span style={{ color: "var(--text-muted)", fontStyle: "italic", fontWeight: 400 }}>(no subject)</span>}
                        </span>
                        {Array.isArray(entry.attachments) && entry.attachments.length > 0 && (
                          <span className="text-xs flex-shrink-0" style={{ color: "var(--text-muted)" }}>
                            📎 {entry.attachments.length}
                          </span>
                        )}
                      </div>
                      {entry.body && (
                        <p
                          className="text-xs mt-0.5"
                          style={{ color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
                        >
                          {entry.body}
                        </p>
                      )}
                    </div>

                    {/* Date + checkbox + chevron */}
                    <div className="flex-shrink-0 text-right flex items-center gap-2" style={{ minWidth: 80 }}>
                      <span
                        className="text-xs"
                        title={entry.occurred_at ? new Date(entry.occurred_at).toLocaleString() : ""}
                        style={{ color: "var(--text-muted)", cursor: "default", fontWeight: isUnread ? 600 : 400 }}
                      >
                        {relativeTime(entry.occurred_at)}
                      </span>
                      <div style={{ width: 20, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                        {(anySelected || hoveredId === entry.id) ? (
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={() => toggleSelect(entry.id)}
                            onClick={(e) => e.stopPropagation()}
                            style={{ cursor: "pointer", accentColor: "var(--btn-primary)", width: 14, height: 14 }}
                          />
                        ) : (
                          <span className="text-xs" style={{ color: "var(--text-muted)" }}>›</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Hover CSS for star visibility */}
      <style>{`
        .row-star { opacity: 0.35; transition: opacity 0.15s, color 0.15s; }
        div:hover > div > .row-star { opacity: 0.6; }
        .row-star[title="Mark as normal"] { opacity: 1 !important; color: #f59e0b !important; }
      `}</style>

      <MailViewModal
        open={!!viewEntry}
        onClose={() => setViewEntry(null)}
        entry={viewEntry}
        customer={viewEntry ? customers[resolveCustomerId(viewEntry)] : null}
        onReply={openReply}
      />

      <ComposeEmailModal
        open={composeOpen}
        onClose={() => setComposeOpen(false)}
        defaultTo={composeTo}
        defaultFromAccount={composeFromAccount}
        requireFromAccount={true}
        onSent={() => loadAll()}
      />

      <SettingsModal
        open={settingsOpen}
        onClose={() => {
          setSettingsOpen(false);
          startPolling(); // restart poll with potentially new interval
        }}
      />
    </div>
  );
}
