/* global React */
const { useState, useMemo, useEffect } = React;

// Helper to parse dates robustly (dd/mm/yyyy, dd.mm.yyyy, or yyyy-mm-dd)
const parseDate = (dStr) => {
  if (!dStr) return 0;
  const s = String(dStr).trim();
  if (s.includes('/') || s.includes('.')) {
    const parts = s.split(/[./]/);
    if (parts.length === 3) {
      if (parts[2].length === 4) {
        return new Date(parts[2], parts[1] - 1, parts[0]).getTime();
      }
    }
  }
  const t = Date.parse(s);
  return isNaN(t) ? 0 : t;
};

function EditorialDirectory() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "density": "compact",
    "showWatermark": true,
    "showOwner": true,
    "showVersion": true,
    "showDate": true,
    "showNumbering": true,
    "accentItalicQuote": true,
    "compactSidebar": false
  }/*EDITMODE-END*/;

  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // Dynamic state loaded from backend APIs
  const [departments, setDepartments] = useState([]);
  const [processes, setProcesses] = useState([]);
  const [notifications, setNotifications] = useState([]);
  const [showNotifications, setShowNotifications] = useState(false);
  const [loading, setLoading] = useState(true);

  // Directory filters
  const [activeDept, setActiveDept] = useState("ALL");
  const [query, setQuery] = useState("");
  const [sort, setSort] = useState("recent");
  const [sortDir, setSortDir] = useState("desc");

  const handleSortClick = (k) => {
    if (sort === k) {
      setSortDir(prev => prev === "asc" ? "desc" : "asc");
    } else {
      setSort(k);
      setSortDir(k === "recent" ? "desc" : "asc");
    }
  };

  const [showCmdK, setShowCmdK] = useState(false);

  // AI Chat widget states
  const [showAiChat, setShowAiChat] = useState(false);
  const [aiExpanded, setAiExpanded] = useState(false);
  const [aiMessages, setAiMessages] = useState([
    { role: "assistant", text: "Xin chào! Tôi là Trợ lý AI của Tập đoàn Kim Liên. Tôi có thể giúp bạn tra cứu thông tin về bất kỳ quy trình nào được phân quyền cho tài khoản của bạn. Bạn cần tìm hiểu quy trình nào hôm nay?\n\n💡 Bạn có thể gõ /del hoặc /clear để xóa lịch sử cuộc trò chuyện." }
  ]);
  const [aiInput, setAiInput] = useState("");
  const [aiLoading, setAiLoading] = useState(false);
  const [aiError, setAiError] = useState("");
  const [aiScrollTarget, setAiScrollTarget] = useState(null);
  const user = window.__klg_auth || { company: "guest", scope: [] };
  
  // Load chat history from localStorage on mount
  useEffect(() => {
    if (!user || !user.company) return;
    const key = `klg_chat_history_${user.company}`;
    try {
      const stored = localStorage.getItem(key);
      if (stored) {
        const parsed = JSON.parse(stored);
        const twentyFourHoursMs = 24 * 60 * 60 * 1000;
        // Check if history is within the 24-hour retention period
        if (parsed && parsed.timestamp && (Date.now() - parsed.timestamp < twentyFourHoursMs)) {
          if (Array.isArray(parsed.messages) && parsed.messages.length > 0) {
            setAiMessages(parsed.messages);
          }
        } else {
          localStorage.removeItem(key); // Clear expired history
        }
      }
    } catch (e) {
      console.error("Lỗi khi tải lịch sử chat:", e);
    }
  }, [user.company]);

  // Save chat history to localStorage whenever aiMessages changes
  useEffect(() => {
    if (!user || !user.company) return;
    const key = `klg_chat_history_${user.company}`;
    try {
      // Don't save if there's only the default greeting message
      if (aiMessages.length > 1) {
        localStorage.setItem(key, JSON.stringify({
          timestamp: Date.now(),
          messages: aiMessages
        }));
      }
    } catch (e) {
      console.error("Lỗi khi lưu lịch sử chat:", e);
    }
  }, [aiMessages, user.company]);

  // Fetch dynamic data from Express Backend
  const fetchData = () => {
    setLoading(true);
    const token = localStorage.getItem("klg_token");
    
    Promise.all([
      fetch("/api/departments", {
        headers: { "Authorization": `Bearer ${token}` }
      }).then(res => res.json()),
      fetch("/api/processes", {
        headers: { "Authorization": `Bearer ${token}` }
      }).then(res => res.json()),
      fetch("/api/notifications", {
        headers: { "Authorization": `Bearer ${token}` }
      }).then(res => res.json())
    ])
    .then(([depts, procs, notifs]) => {
      setDepartments(depts);
      setProcesses(procs);
      if (Array.isArray(notifs)) setNotifications(notifs);
      setLoading(false);
    })
    .catch(err => {
      console.warn("API fallback to static data:", err);
      if (window.KLG_DATA) {
        setDepartments(window.KLG_DATA.DEPARTMENTS);
        setProcesses(window.KLG_DATA.PROCESSES);
      }
      setLoading(false);
    });
  };

  const fetchNotificationsOnly = () => {
    const token = localStorage.getItem("klg_token");
    fetch("/api/notifications", {
      headers: { "Authorization": `Bearer ${token}` }
    })
    .then(res => res.json())
    .then(data => {
      if (Array.isArray(data)) setNotifications(data);
    })
    .catch(err => console.error("Lỗi tải thông báo:", err));
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchNotificationsOnly, 20000);
    return () => clearInterval(interval);
  }, []);

  const handleSendAiMessage = (e) => {
    if (e) e.preventDefault();
    if (!aiInput.trim() || aiLoading) return;

    const userMsg = aiInput.trim();
    setAiInput("");
    setAiError("");

    if (userMsg.toLowerCase() === "/del" || userMsg.toLowerCase() === "/clear") {
      setAiMessages([
        { role: "assistant", text: "Xin chào! Tôi là Trợ lý AI của Tập đoàn Kim Liên. Tôi có thể giúp bạn tra cứu thông tin về bất kỳ quy trình nào được phân quyền cho tài khoản của bạn. Bạn cần tìm hiểu quy trình nào hôm nay?\n\n💡 Bạn có thể gõ /del hoặc /clear để xóa lịch sử cuộc trò chuyện." }
      ]);
      const key = `klg_chat_history_${user.company}`;
      localStorage.removeItem(key);
      
      // Clear server-side session context in background
      const token = localStorage.getItem("klg_token");
      fetch("/api/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${token}`
        },
        body: JSON.stringify({ message: userMsg })
      }).catch(err => console.warn("Failed to clear backend context:", err));
      
      return;
    }

    setAiLoading(true);

    // Append user message immediately
    setAiMessages(prev => [...prev, { role: "user", text: userMsg }]);

    const token = localStorage.getItem("klg_token");
    fetch("/api/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify({ message: userMsg })
    })
    .then(async res => {
      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "Có lỗi xảy ra khi kết nối AI.");
      }
      return data;
    })
    .then(data => {
      // Multi-bubble: use parts[] if available, otherwise fallback to answer
      const parts = (data.parts && data.parts.length > 0) ? data.parts : [data.answer];
      setAiMessages(prev => {
        const scrollIdx = prev.length; // Index of first new bot message
        setAiScrollTarget(scrollIdx);
        return [...prev, ...parts.map(p => ({ role: "assistant", text: p }))];
      });
      setAiLoading(false);
    })
    .catch(err => {
      setAiError(err.message);
      setAiLoading(false);
    });
  };

  // Smart scroll: scroll to the first new bot message (not the bottom)
  useEffect(() => {
    if (aiScrollTarget !== null) {
      const targetEl = document.getElementById(`ai-msg-${aiScrollTarget}`);
      if (targetEl) {
        setTimeout(() => {
          targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
      }
      setAiScrollTarget(null);
    }
  }, [aiScrollTarget, aiMessages.length]);

  const filtered = useMemo(() => {
    let list = processes.slice();
    if (activeDept !== "ALL") list = list.filter((p) => p.dept === activeDept);
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter(
        (p) =>
          p.code.toLowerCase().includes(q) ||
          p.title.toLowerCase().includes(q) ||
          (p.owner && p.owner.toLowerCase().includes(q))
      );
    }
    if (sort === "recent") {
      list.sort((a, b) => {
        const cmp = parseDate(a.updated) - parseDate(b.updated);
        return sortDir === "asc" ? cmp : -cmp;
      });
    } else if (sort === "code") {
      list.sort((a, b) => {
        const cmp = (a.code || "").localeCompare(b.code || "", undefined, { numeric: true, sensitivity: 'base' });
        return sortDir === "asc" ? cmp : -cmp;
      });
    } else if (sort === "az") {
      list.sort((a, b) => {
        const cmp = (a.title || "").localeCompare(b.title || "", "vi", { sensitivity: 'base' });
        return sortDir === "asc" ? cmp : -cmp;
      });
    }
    return list;
  }, [processes, activeDept, query, sort, sortDir]);

  const featured = useMemo(() => {
    return processes
      .filter(p => p.status === 'active')
      .sort((a, b) => parseDate(b.updated) - parseDate(a.updated))
      .slice(0, 3);
  }, [processes]);

  const cmdResults = useMemo(() => {
    if (!query.trim()) return processes.slice(0, 8);
    const q = query.toLowerCase();
    return processes.filter(
      (p) => p.code.toLowerCase().includes(q) || p.title.toLowerCase().includes(q)
    ).slice(0, 10);
  }, [processes, query]);

  const unreadCount = useMemo(() => {
    return notifications.filter(n => !n.is_read).length;
  }, [notifications]);

  const handleMarkNotifRead = (id, e) => {
    e.stopPropagation();
    const token = localStorage.getItem("klg_token");
    fetch(`/api/notifications/${id}/read`, {
      method: "POST",
      headers: { "Authorization": `Bearer ${token}` }
    })
    .then(() => fetchNotificationsOnly());
  };

  const handleMarkAllNotifsRead = () => {
    const token = localStorage.getItem("klg_token");
    fetch(`/api/notifications/read-all`, {
      method: "POST",
      headers: { "Authorization": `Bearer ${token}` }
    })
    .then(() => fetchNotificationsOnly());
  };

  const density = t.density;
  const rowPad = density === "compact" ? "12px" : density === "comfy" ? "28px" : "20px";
  const titleSize = density === "compact" ? 16 : density === "comfy" ? 22 : 19;

  return (
    <div style={S.root}>
      {/* Header */}
      <header className="user-header" style={S.header}>
        <div className="user-header-inner" style={S.headerInner}>
          <div style={S.brandRow}>
            <img src={window.__resources?.logoMark || "assets/kimlien-logo-mark.png"} alt="" style={{ width: 42, height: 42 }} />
            <div>
              <div style={S.wm}>KIMLIEN GROUP</div>
              <div style={S.wmSub}>HỆ THỐNG QUY TRÌNH NỘI BỘ</div>
            </div>
          </div>
          <div className="user-header-actions" style={S.headerActions}>
            <button onClick={() => setShowCmdK(true)} className="user-search-trigger" style={S.searchTrigger}>
              <SvgSearch />
              <span style={{ flex: 1, textAlign: "left" }}>Tìm kiếm quy trình…</span>
              <span className="user-kbd" style={S.kbd}>⌘K</span>
            </button>

            {/* Notification Bell Icon */}
            <div style={{ position: "relative" }}>
              <button onClick={() => setShowNotifications(!showNotifications)} className="user-bell-btn" style={S.bellBtn}>
                <SvgBell />
                {unreadCount > 0 && (
                  <span style={S.bellBadge}>{unreadCount}</span>
                )}
              </button>

              {showNotifications && (
                <div className="user-notif-dropdown" style={S.notifDropdown}>
                  <div style={S.notifHeader}>
                    <span>Thông báo mới</span>
                    {unreadCount > 0 && (
                      <button onClick={handleMarkAllNotifsRead} style={S.notifCleanAll}>Đọc tất cả</button>
                    )}
                  </div>
                  <div style={S.notifList}>
                    {notifications.length === 0 ? (
                      <div style={S.notifEmpty}>Không có thông báo mới nào.</div>
                    ) : (
                      notifications.map(n => (
                        <div key={n.id} style={{ ...S.notifItem, opacity: n.is_read ? 0.6 : 1 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                            <span style={{ fontWeight: 600, color: "var(--kl-navy)" }}>{n.title}</span>
                            {!n.is_read && (
                              <button onClick={(e) => handleMarkNotifRead(n.id, e)} style={S.notifCheckBtn}>✓</button>
                            )}
                          </div>
                          <div style={{ fontSize: 12, marginTop: 4 }}>{n.message}</div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* Account fixed info panel */}
      {window.__klg_auth && (
        <div className="user-acct-fixed" style={S.acctFixed}>
          <div style={S.acctFixedText}>
            <div style={S.acctLabel}>Đang đăng nhập</div>
            <div style={S.acctName}>{window.__klg_auth.name}</div>
          </div>
          <button
            type="button"
            onClick={() => window.__klg_logout && window.__klg_logout()}
            style={S.logoutBtn}
            title="Đăng xuất"
          >Đăng xuất</button>
        </div>
      )}

      {/* Masthead */}
      <section className="user-masthead" style={S.masthead}>
        {t.showWatermark && (
          <div style={S.watermark}>
            <img src={window.__resources?.logoMarkWhite || "assets/kimlien-logo-mark-white.png"} alt="" style={{ width: 720, height: 720, opacity: 0.05 }} />
          </div>
        )}
        <div className="user-masthead-inner" style={S.mastheadInner}>
          <div className="user-masthead-left" style={S.mastheadLeft}>
            <div className="kl-eyebrow">TÀI LIỆU NỘI BỘ · KHÔNG PHỔ BIẾN</div>
            <h1 style={S.mastheadTitle}>
              Hệ thống Quy trình<br/>
              <em style={S.mastheadEm}>Tập đoàn Kim Liên</em>
            </h1>
            {t.accentItalicQuote && (
              <p style={S.mastheadLede}>
                "Mỗi quy trình là một cam kết chuẩn mực — được ban hành cẩn trọng,
                kiểm soát phiên bản chặt chẽ và áp dụng nhất quán trong toàn hệ thống."
              </p>
            )}
            <div style={S.mastheadMeta}>
              <span><b>{processes.length}</b> quy trình</span>
              <span style={S.metaDot} />
              <span><b>{departments.length}</b> phòng ban</span>
              <span style={S.metaDot} />
              <span>Cập nhật <b>Hôm nay</b></span>
            </div>
          </div>
          <div className="user-masthead-right" style={S.mastheadRight}>
            <div style={S.featuredLabel}>QUY TRÌNH MỚI CẬP NHẬT</div>
            {featured.map((p, i) => (
              <a key={p.code} href={p.href} target="_blank" rel="noopener" style={S.featuredItem}>
                <span style={S.featuredIdx}>{String(i + 1).padStart(2, "0")}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={S.featuredCode}>{p.code}</div>
                  <div style={S.featuredTitle}>{p.title}</div>
                  <div style={S.featuredDate}>{formatDate(p.updated)} · {p.version}</div>
                </div>
                <SvgArrowOut />
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Body */}
      <section className="user-body" style={S.body}>
        <aside className="user-sidebar" style={S.sidebar}>
          <div className="kl-eyebrow user-sidebar-title" style={{ marginBottom: 16 }}>MỤC LỤC</div>

          <button
            onClick={() => setActiveDept("ALL")}
            className={`dept-btn ${activeDept === "ALL" ? "active" : ""}`}
            style={{ ...S.deptBtn, ...(activeDept === "ALL" ? S.deptBtnActive : {}) }}
          >
            <span>Tất cả phòng ban</span>
            <span className="user-dept-count" style={S.deptCount}>{processes.length}</span>
          </button>

          <div className="user-sidebar-divider" style={S.sidebarDivider} />
          <div className="kl-eyebrow user-sidebar-title" style={{ marginBottom: 12, fontSize: 10 }}>PHÒNG BAN</div>
          {departments.filter(d => d.code !== 'PUBLIC').map((d) => {
            const count = processes.filter((p) => p.dept === d.code).length;
            const isActive = d.code === activeDept;
            return (
              <button
                key={d.code}
                onClick={() => setActiveDept(d.code)}
                className={`dept-btn ${isActive ? "active" : ""}`}
                style={{ ...S.deptBtn, ...(isActive ? S.deptBtnActive : {}) }}
              >
                <span className="dept-btn-label" style={S.deptBtnLabel}>
                  <span className="dept-btn-code" style={S.deptBtnCode}>{d.code}</span>
                  <span className="dept-btn-name" style={{ overflow: "hidden", textOverflow: "ellipsis" }}>
                    {t.compactSidebar ? d.short : d.name}
                  </span>
                </span>
                <span className="user-dept-count" style={S.deptCount}>{count}</span>
              </button>
            );
          })}

          <div className="user-sidebar-divider" style={S.sidebarDivider} />
          <p className="user-sidebar-hint" style={S.sidebarHint}>
            Mỗi quy trình mở trong tab mới. Phiên bản đang hiển thị là phiên bản hiện hành.
          </p>
        </aside>

        <main className="user-main" style={S.main}>
          {loading ? (
            <div style={S.empty}>Đang đồng bộ dữ liệu...</div>
          ) : (
            <>
              <div className="user-main-head" style={S.mainHead}>
                <div>
                  <h2 style={S.mainTitle}>
                    {activeDept === "ALL"
                      ? "Toàn bộ quy trình"
                      : departments.find((d) => d.code === activeDept)?.name}
                  </h2>
                  <div style={S.mainSub}>
                    {filtered.length} kết quả
                    {query && <> · tìm "<em>{query}</em>"</>}
                  </div>
                </div>
                <div className="user-sort-row" style={S.sortRow}>
                  <span className="user-sort-label" style={S.sortLabel}>Sắp xếp</span>
                  {[
                    ["recent", "Mới cập nhật"],
                    ["code", "Theo mã"],
                    ["az", "A → Z"],
                  ].map(([k, l]) => (
                    <button
                      key={k}
                      onClick={() => handleSortClick(k)}
                      className={`user-sort-btn ${sort === k ? "active" : ""}`}
                      style={{ ...S.sortBtn, ...(sort === k ? S.sortBtnActive : {}) }}
                    >
                      {l} {sort === k && (sortDir === "asc" ? "↑" : "↓")}
                    </button>
                  ))}
                </div>
              </div>

              {/* Active filter chips */}
              {(activeDept !== "ALL" || query) && (
                <div style={S.chipRow}>
                  <span style={S.chipLabel}>Bộ lọc đang áp dụng:</span>
                  {activeDept !== "ALL" && (
                    <Chip onRemove={() => setActiveDept("ALL")}>
                      {departments.find((d) => d.code === activeDept)?.name}
                    </Chip>
                  )}
                  {query && <Chip onRemove={() => setQuery("")}>Tìm: {query}</Chip>}
                  <button onClick={() => { setActiveDept("ALL"); setQuery(""); }} style={S.clearAll}>
                    Xóa tất cả
                  </button>
                </div>
              )}

              <div className="user-list" style={S.list}>
                {filtered.length === 0 ? (
                  <div style={S.empty}>Không có quy trình nào khớp tiêu chí.</div>
                ) : (
                  filtered.map((p, idx) => {
                    const dept = p.dept === 'PUBLIC'
                      ? { short: 'Công khai' }
                      : (departments.find((d) => d.code === p.dept) || { short: p.dept });
                    return (
                      <div key={p.code} className="user-row" style={{ ...S.row, padding: `${rowPad} 0` }}>
                        {t.showNumbering && (
                          <div className="user-row-idx" style={S.rowIdx}>{String(idx + 1).padStart(3, "0")}</div>
                        )}
                        <a href={p.href} target="_blank" rel="noopener" style={S.rowMid}>
                          <h3 className="user-row-title" style={{ ...S.rowTitle, fontSize: titleSize }}>
                            <span style={S.rowCodeInline}>{p.code}</span>
                            <span style={S.rowTitleSep}>—</span>
                            <span>{p.title}</span>
                          </h3>
                          <div style={S.rowMeta}>
                            <span style={S.rowDeptInline}>{dept.short}</span>
                            <span style={S.rowMetaDot} />
                            {t.showOwner && <><span>{p.owner}</span><span style={S.rowMetaDot} /></>}
                            {t.showVersion && <><span>{p.version}</span><span style={S.rowMetaDot} /></>}
                            {t.showDate && <span>Cập nhật {formatDate(p.updated)}</span>}
                          </div>
                        </a>
                        <div style={S.rowActions}>
                          <a href={p.href} target="_blank" rel="noopener" style={S.iconBtn} title="Mở">
                            <SvgArrowOut />
                          </a>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </>
          )}
        </main>
      </section>

      {/* Footer */}
      <footer className="user-footer" style={S.footer}>
        <div className="user-footer-inner" style={S.footerInner}>
          <span>TÀI LIỆU NỘI BỘ — KHÔNG CHIA SẺ RA NGOÀI</span>
          <span>© 2026 KIMLIEN GROUP · Văn phòng Hội đồng Quản trị · v2.6</span>
        </div>
      </footer>

      {/* Cmd-K palette */}
      {showCmdK && (
        <div style={S.cmdkOverlay} onClick={() => setShowCmdK(false)}>
          <div style={S.cmdk} onClick={(e) => e.stopPropagation()}>
            <div style={S.cmdkHead}>
              <SvgSearch />
              <input
                autoFocus
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Tìm theo mã, tên hoặc đơn vị phụ trách…"
                style={S.cmdkInput}
              />
              <span style={S.cmdkEsc}>ESC</span>
            </div>
            <div style={S.cmdkResults}>
              {cmdResults.length === 0 ? (
                <div style={S.empty}>Không có kết quả.</div>
              ) : cmdResults.map((p) => {
                const dept = p.dept === 'PUBLIC'
                  ? { name: 'Tất cả phòng ban' }
                  : (departments.find((d) => d.code === p.dept) || { name: p.dept });
                return (
                  <a key={p.code} href={p.href} target="_blank" rel="noopener" style={S.cmdkItem}>
                    <span style={S.cmdkCode}>{p.code}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={S.cmdkTitle}>{p.title}</div>
                      <div style={S.cmdkSub}>{dept.name} · {p.owner}</div>
                    </div>
                    <SvgArrowOut />
                  </a>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {/* Tweaks Panel */}
      <window.TweaksPanel>
        <window.TweakSection label="Mật độ & Layout" />
        <window.TweakRadio
          label="Mật độ danh sách"
          value={t.density}
          options={["compact", "regular", "comfy"]}
          onChange={(v) => setTweak("density", v)}
        />
        <window.TweakToggle
          label="Sidebar gọn"
          value={t.compactSidebar}
          onChange={(v) => setTweak("compactSidebar", v)}
        />

        <window.TweakSection label="Hiển thị" />
        <window.TweakToggle label="Watermark huy hiệu" value={t.showWatermark} onChange={(v) => setTweak("showWatermark", v)} />
        <window.TweakToggle label="Câu trích dẫn (italic)" value={t.accentItalicQuote} onChange={(v) => setTweak("accentItalicQuote", v)} />
        <window.TweakToggle label="Số thứ tự dòng" value={t.showNumbering} onChange={(v) => setTweak("showNumbering", v)} />

        <window.TweakSection label="Cột metadata" />
        <window.TweakToggle label="Đơn vị phụ trách" value={t.showOwner} onChange={(v) => setTweak("showOwner", v)} />
        <window.TweakToggle label="Phiên bản" value={t.showVersion} onChange={(v) => setTweak("showVersion", v)} />
        <window.TweakToggle label="Ngày cập nhật" value={t.showDate} onChange={(v) => setTweak("showDate", v)} />
      </window.TweaksPanel>

      {/* Floating AI Chat Bubble Button */}
      <button 
        onClick={() => { setShowAiChat(!showAiChat); if (showAiChat) setAiExpanded(false); }} 
        className="ai-bubble-btn"
        style={S.aiBubble} 
        title="Trợ lý AI Tra cứu Quy trình"
      >
        {showAiChat ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        ) : (
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2a8.5 8.5 0 0 0-8.5 8.5c0 2.5 1 4.7 2.7 6.3L4 22l5.2-2.2c.9.2 1.8.3 2.8.3A8.5 8.5 0 0 0 12 2z"/><circle cx="9" cy="10.5" r="1"/><circle cx="15" cy="10.5" r="1"/><path d="M9.5 14.5c.8.8 2.2 1 3 1s2.2-.2 3-1"/></svg>
        )}
      </button>

      {/* AI Chat Drawer Container */}
      {showAiChat && (
        <div className={`user-chat-drawer ${aiExpanded ? 'ai-expanded' : ''}`} style={aiExpanded ? S.aiDrawerExpanded : S.aiDrawer}>
          {/* Fullscreen overlay backdrop */}
          {aiExpanded && <div style={S.aiExpandedOverlay} onClick={() => setAiExpanded(false)} />}
          
          <div style={{ ...S.aiDrawerHead, position: 'relative', zIndex: 2 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={S.aiBotAvatarSmall}>AI</div>
              <div>
                <div style={{ fontWeight: 700, color: "#fff", fontSize: 14, letterSpacing: "0.04em" }}>Trợ lý Kim Liên</div>
                <div style={{ fontSize: 10, color: "rgba(255,255,255,0.6)", marginTop: 1 }}>Hỏi đáp quy trình nội bộ</div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <button onClick={() => setAiExpanded(!aiExpanded)} style={S.aiDrawerHeaderBtn} title={aiExpanded ? "Thu nhỏ" : "Phóng to"}>
                {aiExpanded ? (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"/></svg>
                ) : (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
                )}
              </button>
              <button onClick={() => { setShowAiChat(false); setAiExpanded(false); }} style={S.aiDrawerHeaderBtn} title="Ẩn">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
          </div>

          <div className="ai-chat-body" style={{ ...S.aiDrawerBody, position: 'relative', zIndex: 2 }}>
            {aiMessages.map((msg, idx) => {
              if (!msg || !msg.role || !msg.text) return null;
              return (
                <div key={idx} id={`ai-msg-${idx}`} style={msg.role === 'user' ? S.aiMsgUserRow : S.aiMsgBotRow}>
                  {msg.role !== 'user' && <div style={S.aiBotAvatar}>AI</div>}
                  <div style={msg.role === 'user' ? S.aiMsgUser : S.aiMsgBot}
                    dangerouslySetInnerHTML={msg.role !== 'user' ? { __html: renderMarkdown(msg.text) } : undefined}
                  >
                    {msg.role === 'user' ? msg.text : undefined}
                  </div>
                </div>
              );
            })}
            {aiLoading && (
              <div style={S.aiMsgBotRow}>
                <div style={S.aiBotAvatar}>AI</div>
                <div style={{ ...S.aiMsgBot, display: "flex", alignItems: "center", gap: 4, padding: "12px 16px" }}>
                  <span className="ai-typing-dot" style={{ ...S.typingDot, animationDelay: "0s" }}>●</span>
                  <span className="ai-typing-dot" style={{ ...S.typingDot, animationDelay: "0.2s" }}>●</span>
                  <span className="ai-typing-dot" style={{ ...S.typingDot, animationDelay: "0.4s" }}>●</span>
                </div>
              </div>
            )}
            {aiError && (
              <div style={S.aiErrorBox}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
                {aiError}
              </div>
            )}
          </div>

          <form onSubmit={handleSendAiMessage} style={{ ...S.aiDrawerFoot, position: 'relative', zIndex: 2 }}>
            <div style={S.aiInputWrap}>
              <input
                type="text"
                value={aiInput}
                onChange={(e) => setAiInput(e.target.value)}
                placeholder="Hỏi bất kỳ điều gì về quy trình…"
                style={S.aiDrawerInput}
                disabled={aiLoading}
                autoFocus
              />
              <button type="submit" style={{ ...S.aiDrawerSend, opacity: (aiLoading || !aiInput.trim()) ? 0.4 : 1 }} disabled={aiLoading || !aiInput.trim()}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}

function Chip({ children, onRemove }) {
  return (
    <span style={S.chip}>
      {children}
      <button onClick={onRemove} style={S.chipX}>×</button>
    </span>
  );
}

function formatDate(iso) {
  if (!iso) return "N/A";
  const [y, m, d] = iso.split("-");
  return `${d}.${m}.${y}`;
}

// Simple Markdown to HTML renderer — strips *, **, *** noise from AI output
function renderMarkdown(text) {
  if (!text) return '';
  let html = text
    // Escape HTML entities first
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
  
  // Convert bold: **text** or __text__
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  html = html.replace(/__(.+?)__/g, '<strong>$1</strong>');
  // Convert italic: *text* or _text_ (but not inside words with underscores)
  html = html.replace(/(?<![\w*])\*([^*\n]+?)\*(?![\w*])/g, '<em>$1</em>');
  // Convert bullet lists: lines starting with - or *
  html = html.replace(/^[\s]*[-*]\s+(.+)$/gm, '<li style="margin:2px 0;list-style:disc;margin-left:18px;">$1</li>');
  // Convert numbered lists: lines starting with 1. 2. etc
  html = html.replace(/^[\s]*(\d+)\.\s+(.+)$/gm, '<li style="margin:2px 0;list-style:decimal;margin-left:18px;">$2</li>');
  // Convert inline code: `code`
  html = html.replace(/`([^`]+)`/g, '<code style="background:rgba(0,0,0,0.06);padding:1px 4px;border-radius:3px;font-size:0.9em;">$1</code>');
  // Convert newlines to <br> (but not consecutive ones inside lists)
  html = html.replace(/\n/g, '<br/>');
  // Clean up: remove excess <br/> around <li> elements
  html = html.replace(/<br\/><li/g, '<li');
  html = html.replace(/<\/li><br\/>/g, '</li>');
  
  return html;
}

// ── icons ──
const svgProps = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
function SvgSearch() { return <svg width="16" height="16" viewBox="0 0 24 24" {...svgProps}><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.5" y2="16.5"/></svg>; }
function SvgArrowOut() { return <svg width="14" height="14" viewBox="0 0 24 24" {...svgProps}><path d="M7 17L17 7M9 7h8v8"/></svg>; }
function SvgBell() { return <svg width="18" height="18" viewBox="0 0 24 24" {...svgProps}><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>; }

const S = {
  root: { fontFamily: "var(--font-body)", background: "#fff", color: "var(--fg-2)", minHeight: "100vh" },

  header: { borderBottom: "1px solid var(--line-1)", background: "#fff", position: "sticky", top: 0, zIndex: 20 },
  headerInner: { maxWidth: 1440, margin: "0 auto", padding: "10px 32px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, flexWrap: "wrap" },
  brandRow: { display: "flex", alignItems: "center", gap: 14 },
  wm: { fontFamily: "var(--font-display)", color: "var(--kl-gold)", letterSpacing: "0.18em", fontSize: 16 },
  wmSub: { fontFamily: "var(--font-accent)", fontSize: 10, letterSpacing: "0.14em", color: "var(--fg-3)", marginTop: 3 },

  headerActions: { display: "flex", alignItems: "center", gap: 16 },
  searchTrigger: {
    display: "flex", alignItems: "center", gap: 10,
    border: "1px solid var(--line-2)", padding: "7px 12px",
    width: "clamp(220px, 32vw, 380px)",
    color: "var(--fg-3)", background: "#fff", cursor: "pointer",
    fontFamily: "var(--font-body)", fontSize: 13,
  },
  kbd: { fontFamily: "var(--font-accent)", fontSize: 11, color: "var(--fg-3)", border: "1px solid var(--line-2)", padding: "2px 6px" },
  acctBox: { display: "flex", alignItems: "center", gap: 12, paddingLeft: 14, borderLeft: "1px solid var(--line-1)", marginLeft: 4 },
  acctFixed: { position: "fixed", top: 12, right: 16, zIndex: 50, display: "flex", alignItems: "center", gap: 12, background: "#fff", border: "1px solid var(--line-1)", padding: "6px 6px 6px 14px", boxShadow: "0 2px 12px rgba(11,32,53,0.06)" },
  acctFixedText: { display: "flex", flexDirection: "column", lineHeight: 1.1 },
  acctLabel: { fontFamily: "var(--font-accent)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--fg-3)", lineHeight: 1.2 },
  acctName: { fontFamily: "var(--font-accent)", fontSize: 12, color: "var(--fg-1)", fontWeight: 600, lineHeight: 1.2, marginTop: 2, maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
  logoutBtn: { background: "var(--kl-bg-blue)", border: "1px solid var(--kl-bg-blue)", padding: "8px 14px", fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "#fff", fontWeight: 600, cursor: "pointer" },
  bellBtn: { background: "transparent", border: "none", cursor: "pointer", position: "relative", display: "flex", alignItems: "center", justifyContent: "center", width: 36, height: 36, color: "var(--kl-gold-deep)", transition: "all 150ms ease" },
  bellBadge: { position: "absolute", top: 2, right: 2, background: "#8a2c2c", color: "#fff", fontSize: 9, fontFamily: "var(--font-accent)", fontWeight: "600", width: 15, height: 15, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center" },

  // Notification Drawer Dropdown style
  notifDropdown: { position: "absolute", top: 40, right: 0, width: 340, background: "#fff", border: "1px solid var(--line-2)", boxShadow: "var(--shadow-3)", zIndex: 60, maxHeight: 420, overflowY: "auto" },
  notifHeader: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 14px", borderBottom: "1px solid var(--line-1)", fontWeight: 600, color: "var(--kl-navy)", background: "var(--kl-platinum)", fontFamily: "var(--font-accent)", fontSize: 12 },
  notifCleanAll: { background: "transparent", border: "none", color: "var(--kl-gold-deep)", fontSize: 11, cursor: "pointer", textDecoration: "underline" },
  notifList: { display: "flex", flexDirection: "column" },
  notifItem: { padding: "12px 14px", borderBottom: "1px solid var(--line-1)", fontSize: 13, lineHeight: 1.45, color: "var(--fg-2)", transition: "background 150ms ease" },
  notifCheckBtn: { background: "transparent", border: "1px solid var(--line-2)", width: 18, height: 18, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", fontSize: 10, color: "var(--kl-moss)", fontWeight: "bold" },
  notifEmpty: { padding: "30px 14px", textAlign: "center", color: "var(--fg-3)", fontStyle: "italic" },

  masthead: { background: "var(--kl-bg-blue)", color: "var(--fg-on-dark)", position: "relative", overflow: "hidden" },
  watermark: { position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none" },
  mastheadInner: {
    position: "relative", maxWidth: 1440, margin: "0 auto", padding: "40px 40px 36px",
    display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(360px, 1fr))",
    gap: 40, alignItems: "start",
  },
  mastheadTitle: { fontFamily: "var(--font-display)", fontSize: "clamp(34px, 4.6vw, 58px)", lineHeight: 1.05, color: "var(--fg-on-dark)", fontWeight: 400, marginTop: 16, letterSpacing: "-0.015em" },
  mastheadEm: { fontStyle: "italic", color: "var(--kl-gold)" },
  mastheadLede: { fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 16, lineHeight: 1.55, color: "var(--fg-on-dark-2)", marginTop: 22, maxWidth: 560, borderLeft: "2px solid var(--kl-gold)", paddingLeft: 20 },
  mastheadMeta: { marginTop: 24, paddingTop: 18, borderTop: "1px solid var(--line-on-dark-gold)", display: "flex", gap: 14, alignItems: "center", color: "var(--fg-on-dark-2)", fontSize: 12, fontFamily: "var(--font-accent)", flexWrap: "wrap" },
  metaDot: { width: 4, height: 4, background: "var(--kl-gold)", borderRadius: "50%" },

  mastheadRight: { border: "1px solid var(--line-on-dark-gold)", padding: 20, background: "rgba(229,161,36,0.04)" },
  featuredLabel: { fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.14em", color: "var(--kl-gold)", marginBottom: 14, paddingBottom: 12, borderBottom: "1px solid var(--line-on-dark-gold)" },
  featuredItem: { display: "flex", gap: 14, alignItems: "flex-start", padding: "11px 0", borderBottom: "1px solid var(--line-on-dark)", color: "var(--fg-on-dark)", textDecoration: "none" },
  featuredIdx: { fontFamily: "var(--font-display)", fontSize: 20, color: "var(--kl-gold)", width: 32 },
  featuredCode: { fontFamily: "var(--font-accent)", fontSize: 10, letterSpacing: "0.08em", color: "var(--kl-gold)" },
  featuredTitle: { fontFamily: "var(--font-display)", fontSize: 15, lineHeight: 1.3, color: "var(--fg-on-dark)", marginTop: 3 },
  featuredDate: { fontFamily: "var(--font-accent)", fontSize: 10, color: "var(--fg-on-dark-2)", marginTop: 4, letterSpacing: "0.04em" },

  body: { maxWidth: 1440, margin: "0 auto", padding: "36px 32px", display: "grid", gridTemplateColumns: "240px minmax(0, 1fr)", gap: 32 },
  sidebar: { position: "sticky", top: 76, alignSelf: "start", maxHeight: "calc(100vh - 100px)", overflowY: "auto", minWidth: 0 },
  deptBtn: {
    width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center",
    padding: "8px 14px", border: "none", background: "transparent", cursor: "pointer",
    fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-2)", textAlign: "left",
    borderLeft: "2px solid transparent",
  },
  deptBtnActive: { background: "var(--kl-platinum)", color: "var(--kl-black)", borderLeft: "2px solid var(--kl-gold)", fontWeight: 600 },
  deptBtnLabel: { display: "flex", flexDirection: "column", gap: 2, alignItems: "flex-start" },
  deptBtnCode: { fontFamily: "var(--font-accent)", fontSize: 10, letterSpacing: "0.1em", color: "var(--kl-gold-deep)" },
  deptCount: { fontFamily: "var(--font-display)", fontSize: 14, color: "var(--fg-3)" },
  sidebarDivider: { margin: "24px 0", height: 1, background: "var(--line-1)" },
  sidebarHint: { fontSize: 12, lineHeight: 1.6, color: "var(--fg-3)", fontStyle: "italic", padding: "0 8px" },

  main: { minWidth: 0 },
  mainHead: { display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 14, paddingBottom: 14, borderBottom: "2px solid var(--kl-black)", gap: 24, flexWrap: "wrap" },
  mainTitle: { fontFamily: "var(--font-display)", fontSize: "clamp(22px, 2.4vw, 30px)", color: "var(--kl-black)", fontWeight: 400, lineHeight: 1.1 },
  mainSub: { fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-3)", marginTop: 6 },
  sortRow: { display: "flex", alignItems: "center", gap: 8 },
  sortLabel: { fontFamily: "var(--font-accent)", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-3)", marginRight: 4 },
  sortBtn: { border: "1px solid var(--line-2)", padding: "6px 11px", background: "#fff", fontFamily: "var(--font-accent)", fontSize: 11, color: "var(--fg-2)", cursor: "pointer", letterSpacing: "0.04em" },
  sortBtnActive: { background: "var(--kl-black)", color: "#fff", borderColor: "var(--kl-black)" },

  chipRow: { display: "flex", alignItems: "center", gap: 10, marginBottom: 12, flexWrap: "wrap" },
  chipLabel: { fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-3)" },
  chip: { display: "inline-flex", alignItems: "center", gap: 8, background: "var(--kl-platinum)", border: "1px solid var(--line-1)", padding: "6px 8px 6px 12px", fontSize: 12, color: "var(--fg-2)" },
  chipX: { background: "transparent", border: "none", color: "var(--fg-3)", cursor: "pointer", fontSize: 16, lineHeight: 1, padding: "0 4px" },
  clearAll: { background: "transparent", border: "none", color: "var(--kl-gold-deep)", cursor: "pointer", fontFamily: "var(--font-accent)", fontSize: 12, letterSpacing: "0.04em", textDecoration: "underline" },

  list: { display: "flex", flexDirection: "column" },
  row: {
    display: "grid",
    gridTemplateColumns: "36px minmax(0, 1fr) auto",
    gridTemplateAreas: '"idx mid actions"',
    columnGap: 12,
    padding: "24px 0", borderBottom: "1px solid var(--line-1)",
    alignItems: "center",
  },
  rowIdx: { gridArea: "idx", fontFamily: "var(--font-display)", fontSize: 18, color: "var(--kl-gold)", fontWeight: 400 },
  rowCodeInline: { fontFamily: "var(--font-accent)", fontSize: "0.7em", letterSpacing: "0.04em", color: "var(--kl-gold-deep)", fontWeight: 600, textTransform: "none", marginRight: 6 },
  rowTitleSep: { color: "var(--kl-gold)", margin: "0 8px", fontWeight: 300 },
  rowDeptInline: { fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-3)" },
  rowMid: { gridArea: "mid", minWidth: 0, textDecoration: "none", color: "inherit" },
  rowTitle: { fontFamily: "var(--font-accent)", lineHeight: 1.3, color: "var(--kl-black)", fontWeight: 500, margin: 0, letterSpacing: "-0.005em" },
  rowMeta: { display: "flex", alignItems: "center", gap: 8, marginTop: 4, fontSize: 11, color: "var(--fg-3)", fontFamily: "var(--font-accent)", flexWrap: "wrap" },
  rowMetaDot: { width: 3, height: 3, borderRadius: "50%", background: "var(--line-2)" },
  rowActions: { gridArea: "actions", display: "flex", justifyContent: "flex-end", gap: 4 },
  iconBtn: {
    width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center",
    background: "transparent", border: "1px solid var(--line-1)", color: "var(--fg-2)",
    cursor: "pointer", textDecoration: "none",
  },

  empty: { padding: 80, textAlign: "center", color: "var(--fg-3)", fontStyle: "italic" },

  footer: { background: "var(--kl-black)", padding: "32px 40px" },
  footerInner: { maxWidth: 1440, margin: "0 auto", display: "flex", justifyContent: "space-between", color: "var(--fg-on-dark-2)", fontFamily: "var(--font-accent)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" },

  cmdkOverlay: { position: "fixed", inset: 0, background: "rgba(10, 42, 74, 0.55)", display: "flex", alignItems: "flex-start", justifyContent: "center", paddingTop: "10vh", zIndex: 100, backdropFilter: "blur(4px)" },
  cmdk: { width: 640, maxWidth: "90vw", background: "#fff", border: "1px solid var(--line-2)", boxShadow: "var(--shadow-3)" },
  cmdkHead: { display: "flex", alignItems: "center", gap: 12, padding: "18px 20px", borderBottom: "1px solid var(--line-1)", color: "var(--fg-3)" },
  cmdkInput: { flex: 1, border: "none", outline: "none", fontSize: 16, fontFamily: "var(--font-body)", color: "var(--fg-1)", background: "transparent" },
  cmdkEsc: { fontFamily: "var(--font-accent)", fontSize: 11, color: "var(--fg-3)", border: "1px solid var(--line-2)", padding: "2px 6px" },
  cmdkResults: { maxHeight: 480, overflowY: "auto" },
  cmdkItem: { display: "flex", alignItems: "center", gap: 16, padding: "14px 20px", borderBottom: "1px solid var(--line-1)", textDecoration: "none", color: "inherit" },
  cmdkCode: { fontFamily: "var(--font-accent)", fontSize: 12, color: "var(--kl-gold-deep)", fontWeight: 600, minWidth: 92 },
  cmdkTitle: { fontFamily: "var(--font-display)", fontSize: 16, color: "var(--kl-black)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" },
  cmdkSub: { fontSize: 12, color: "var(--fg-3)", marginTop: 4, fontFamily: "var(--font-accent)" },

  aiBubble: {
    position: "fixed", bottom: 24, right: 24, zIndex: 99999,
    width: 56, height: 56, borderRadius: "50%",
    background: "linear-gradient(135deg, #0a2a4a 0%, #122567 100%)",
    border: "2px solid var(--kl-gold)",
    color: "var(--kl-gold)", fontSize: 24, cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center",
    boxShadow: "0 4px 20px rgba(10, 42, 74, 0.35), 0 0 0 0 rgba(229,161,36,0.3)",
    transition: "transform 200ms ease, box-shadow 200ms ease",
    outline: "none",
    animation: "ai-pulse 2.5s ease-in-out infinite"
  },
  aiDrawer: {
    position: "fixed", bottom: 92, right: 24, zIndex: 99999,
    width: 400, height: 560, borderRadius: 16,
    background: "#fff", border: "none",
    boxShadow: "0 20px 60px rgba(10, 42, 74, 0.2), 0 4px 16px rgba(0,0,0,0.08)",
    display: "flex", flexDirection: "column",
    overflow: "hidden",
    transition: "all 300ms cubic-bezier(0.4, 0, 0.2, 1)"
  },
  aiDrawerExpanded: {
    position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
    width: "100%", height: "100%",
    zIndex: 99999, borderRadius: 0,
    background: "transparent", border: "none",
    display: "flex", flexDirection: "column",
    overflow: "hidden"
  },
  aiExpandedOverlay: {
    position: "absolute", inset: 0,
    background: "rgba(10, 42, 74, 0.4)",
    backdropFilter: "blur(4px)",
    zIndex: 1
  },
  aiDrawerHead: {
    background: "linear-gradient(135deg, #0a2a4a 0%, #122567 70%, #1a3577 100%)",
    color: "#fff",
    padding: "16px 16px", display: "flex", justifyContent: "space-between",
    alignItems: "center",
    borderBottom: "2px solid var(--kl-gold)"
  },
  aiDrawerHeaderBtn: {
    background: "rgba(255,255,255,0.1)", border: "none", color: "rgba(255,255,255,0.8)",
    width: 28, height: 28, borderRadius: 6, cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center",
    transition: "background 150ms ease"
  },
  aiBotAvatarSmall: {
    width: 32, height: 32, borderRadius: 8,
    background: "linear-gradient(135deg, var(--kl-gold) 0%, #d4a96a 100%)",
    color: "#fff", fontSize: 11, fontWeight: 800,
    display: "flex", alignItems: "center", justifyContent: "center",
    fontFamily: "var(--font-accent)", letterSpacing: "0.05em",
    flexShrink: 0
  },
  aiBotAvatar: {
    width: 26, height: 26, borderRadius: 6,
    background: "linear-gradient(135deg, var(--kl-gold) 0%, #d4a96a 100%)",
    color: "#fff", fontSize: 9, fontWeight: 800,
    display: "flex", alignItems: "center", justifyContent: "center",
    fontFamily: "var(--font-accent)",
    flexShrink: 0, marginTop: 2
  },
  aiDrawerBody: {
    flex: 1, overflowY: "auto", padding: "16px 14px",
    display: "flex", flexDirection: "column", gap: 14,
    background: "#f8f8fa"
  },
  aiMsgUserRow: {
    display: "flex", justifyContent: "flex-end", gap: 8
  },
  aiMsgBotRow: {
    display: "flex", justifyContent: "flex-start", gap: 8, alignItems: "flex-start"
  },
  aiMsgUser: {
    background: "linear-gradient(135deg, #0a2a4a 0%, #122567 100%)", color: "#fff",
    padding: "10px 14px", borderRadius: "16px 16px 4px 16px",
    fontSize: 13, lineHeight: 1.55, maxWidth: "78%",
    boxShadow: "0 2px 8px rgba(10,42,74,0.15)"
  },
  aiMsgBot: {
    background: "#fff", color: "var(--fg-2)",
    padding: "10px 14px", borderRadius: "4px 16px 16px 16px",
    fontSize: 13, lineHeight: 1.6, maxWidth: "82%",
    boxShadow: "0 1px 4px rgba(0,0,0,0.04)",
    border: "1px solid rgba(0,0,0,0.06)",
    wordBreak: "break-word"
  },
  typingDot: {
    fontSize: 14, color: "var(--kl-gold)",
    animation: "ai-typing 1.2s ease-in-out infinite"
  },
  aiErrorBox: {
    padding: "10px 14px", background: "rgba(138,44,44,0.06)",
    color: "#8a2c2c", fontSize: 12, borderRadius: 10,
    margin: "4px 0", display: "flex", alignItems: "center", gap: 8,
    border: "1px solid rgba(138,44,44,0.12)"
  },
  aiDrawerFoot: {
    padding: "10px 14px 14px", borderTop: "1px solid rgba(0,0,0,0.06)",
    background: "#fff"
  },
  aiInputWrap: {
    display: "flex", gap: 8, alignItems: "center",
    background: "#f4f4f6", borderRadius: 24,
    padding: "4px 4px 4px 16px",
    border: "1px solid rgba(0,0,0,0.08)",
    transition: "border-color 200ms ease, box-shadow 200ms ease"
  },
  aiDrawerInput: {
    flex: 1, border: "none", background: "transparent",
    padding: "8px 0", fontSize: 13, outline: "none",
    fontFamily: "var(--font-body)", color: "var(--fg-1)"
  },
  aiDrawerSend: {
    width: 34, height: 34, borderRadius: "50%",
    background: "linear-gradient(135deg, var(--kl-gold) 0%, #d4a96a 100%)",
    border: "none",
    color: "#fff", fontSize: 14, cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center",
    transition: "opacity 150ms ease, transform 150ms ease",
    flexShrink: 0
  }
};

window.EditorialDirectory = EditorialDirectory;
