(ns ajet.chat.web.layout
  "Hiccup layout templates for the web UI.

   Renders full HTML pages with Tailwind CSS (CDN), Datastar (CDN),
   and a Catppuccin Mocha dark theme.

   Layout is a Discord-style 4-pane design:
     community-strip | sidebar | message-list | (optional thread panel)"
  (:require [hiccup2.core :as h]
            [ajet.chat.web.components :as c]))

;;; ---------------------------------------------------------------------------
;;; Color Palette (Catppuccin Mocha)
;;; ---------------------------------------------------------------------------

(def ^:private colors
  {:base       "#1e1e2e"
   :mantle     "#181825"
   :surface0   "#313244"
   :surface1   "#45475a"
   :surface2   "#585b70"
   :overlay0   "#6c7086"
   :overlay1   "#7f849c"
   :subtext0   "#a6adc8"
   :subtext1   "#bac2de"
   :text       "#cdd6f4"
   :lavender   "#b4befe"
   :blue       "#89b4fa"
   :sapphire   "#74c7ec"
   :sky        "#89dceb"
   :teal       "#94e2d5"
   :green      "#a6e3a1"
   :yellow     "#f9e2af"
   :peach      "#fab387"
   :maroon     "#eba0ac"
   :red        "#f38ba8"
   :mauve      "#cba6f7"
   :pink       "#f5c2e7"
   :flamingo   "#f2cdcd"
   :rosewater  "#f5e0dc"
   :hover      "#2a2a3c"})

;;; ---------------------------------------------------------------------------
;;; Base Page Shell
;;; ---------------------------------------------------------------------------

(defn base-page
  "Full HTML document wrapper with Tailwind CDN, Datastar CDN, and dark theme CSS."
  [{:keys [title]} & body]
  (str
    "<!DOCTYPE html>"
    (h/html
      [:html {:lang "en" :class "dark"}
       [:head
        [:meta {:charset "UTF-8"}]
        [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
        [:title (or title "ajet chat")]
        ;; Tailwind CSS via CDN
        [:script {:src "https://cdn.tailwindcss.com"}]
        [:script
         (h/raw
           "tailwind.config = {
              darkMode: 'class',
              theme: {
                extend: {
                  colors: {
                    base: '#1e1e2e',
                    mantle: '#181825',
                    surface0: '#313244',
                    surface1: '#45475a',
                    surface2: '#585b70',
                    overlay0: '#6c7086',
                    overlay1: '#7f849c',
                    subtext0: '#a6adc8',
                    subtext1: '#bac2de',
                    text: '#cdd6f4',
                    blue: '#89b4fa',
                    green: '#a6e3a1',
                    red: '#f38ba8',
                    yellow: '#f9e2af',
                    mauve: '#cba6f7',
                    peach: '#fab387',
                    hover: '#2a2a3c',
                  }
                }
              }
            }")]
        ;; Datastar via CDN
        [:script {:type "module" :src "https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.0-RC.7/bundles/datastar.js"}]
        ;; Custom styles
        [:style
         (h/raw
           "* { box-sizing: border-box; }
            body { margin: 0; padding: 0; font-family: 'Inter', system-ui, -apple-system, sans-serif; }
            ::-webkit-scrollbar { width: 8px; }
            ::-webkit-scrollbar-track { background: #1e1e2e; }
            ::-webkit-scrollbar-thumb { background: #45475a; border-radius: 4px; }
            ::-webkit-scrollbar-thumb:hover { background: #585b70; }
            .spoiler { background: #313244; color: transparent; border-radius: 3px; padding: 0 4px; cursor: pointer; transition: color 0.2s; }
            .spoiler:hover { color: #cdd6f4; }
            code { background: #313244; padding: 2px 6px; border-radius: 3px; font-size: 0.875em; }
            pre code { background: none; padding: 0; }
            pre { background: #313244; padding: 12px; border-radius: 6px; overflow-x: auto; }
            blockquote { border-left: 3px solid #45475a; padding-left: 12px; margin: 4px 0; color: #a6adc8; }
            a { color: #89b4fa; text-decoration: none; }
            a:hover { text-decoration: underline; }
            .toast-enter { animation: slideIn 0.3s ease-out; }
            @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
            .emoji-btn { cursor: pointer; padding: 4px; border-radius: 4px; transition: background 0.15s; }
            .emoji-btn:hover { background: #45475a; }")]]
       [:body {:class "bg-base text-text h-screen overflow-hidden"}
        body]])))

;;; ---------------------------------------------------------------------------
;;; App Layout (4-pane Discord-style)
;;; ---------------------------------------------------------------------------

(defn app-page
  "Full chat application page with all panes populated from initial data."
  [{:keys [user communities community channels channel messages categories unread-count
           dm-view? dms]}]
  (let [community-id (when community (str (:id community)))
        channel-id   (when channel (str (:id channel)))
        oldest-msg-id (when (seq messages) (str (:id (first messages))))]
    (base-page
      {:title (str (when channel (str "#" (:name channel) " - "))
                   (when community (:name community))
                   " - ajet chat")}
      ;; Datastar signals for client state
      [:div {:id "app-state"
             :data-signals (str "{activeCommunity: '" (or community-id "") "',"
                                " activeChannel: '" (or channel-id "") "',"
                                " messageText: '',"
                                " searchQuery: '',"
                                " searchOpen: false,"
                                " emojiOpen: false,"
                                " threadOpen: false,"
                                " threadMessageId: '',"
                                " commandText: '',"
                                " unreadCount: " (or unread-count 0) ","
                                " navCommunity: '',"
                                " navChannel: '',"
                                " navTarget: '',"
                                " oldestMessageId: '" (or oldest-msg-id "") "'}")
             ;; Auto-connect to SSE on page load
             :data-init (str "@get('/sse/events', {openWhenHidden: true})")}]
      ;; Main 4-pane layout
      [:div {:class "flex h-screen"}
       ;; Pane 1: Community strip
       [:div {:id "community-strip"
              :class "w-[72px] flex-shrink-0 bg-mantle flex flex-col items-center py-3 gap-2 overflow-y-auto"}
        (c/community-strip {:communities communities
                            :active-id   community-id
                            :unread-count unread-count})]

       ;; Pane 2: Sidebar
       [:div {:id "sidebar"
              :class "w-60 flex-shrink-0 bg-mantle flex flex-col border-r border-surface1"}
        (if dm-view?
          (c/dm-sidebar {:dms dms :active-dm channel :user user})
          (c/sidebar {:community  community
                      :channels   channels
                      :channel    channel
                      :categories categories
                      :user       user}))]

       ;; Pane 3: Main content area (message list + input)
       [:div {:class "flex-1 flex flex-col min-w-0"}
        ;; Channel header
        [:div {:id "channel-header"}
         (c/channel-header channel)]

        ;; Messages
        [:div {:id "message-list"
               :class "flex-1 overflow-y-auto px-4 py-2"
               "data-on:scroll" "if(evt.target.scrollTop === 0) { @post('/web/messages/older') }"}
         (c/message-list messages user)]

        ;; Message input
        [:div {:id "message-input-area"
               :class "px-4 pb-4"}
         (c/message-input channel)]]

       ;; Pane 4: Thread panel (hidden by default)
       [:div {:id "thread-panel"
              :class "w-96 flex-shrink-0 bg-mantle border-l border-surface1 flex-col hidden"
              "data-class:hidden" "!$threadOpen"}]]

      ;; Notification toast container
      [:div {:id "toast-container"
             :class "fixed top-4 right-4 z-50 flex flex-col gap-2"}]

      ;; Search modal (hidden by default)
      [:div {:id "search-modal"
             :class "fixed inset-0 z-40 hidden"
             "data-class:hidden" "!$searchOpen"}
       (c/search-modal)]

      ;; Emoji picker (hidden by default)
      [:div {:id "emoji-picker"
             :class "fixed z-30 hidden"
             "data-class:hidden" "!$emojiOpen"}
       (c/emoji-picker)])))

;;; ---------------------------------------------------------------------------
;;; Setup Page
;;; ---------------------------------------------------------------------------

(defn setup-page
  "Community creation wizard for first-time users."
  []
  (base-page
    {:title "Create Community - ajet chat"}
    [:div {:class "flex items-center justify-center min-h-screen"}
     [:div {:class "w-full max-w-md p-8 bg-mantle rounded-xl border border-surface1"}
      [:h1 {:class "text-2xl font-bold text-text mb-2 text-center"} "Welcome to ajet chat"]
      [:p {:class "text-subtext0 text-center mb-8"} "Create your first community to get started."]
      [:form {"data-on:submit" "@post('/web/communities')"}
       [:div {:class "mb-4"}
        [:label {:class "block text-sm font-medium text-subtext1 mb-1" :for "community-name"} "Community Name"]
        [:input {:type "text"
                 :id "community-name"
                 :name "name"
                 :data-bind "communityName"
                 "data-signals:communityName" ""
                 :required true
                 :placeholder "My Team"
                 :class "w-full px-3 py-2 bg-surface0 border border-surface1 rounded-lg text-text
                         placeholder-overlay0 focus:outline-none focus:border-blue"}]]
       [:div {:class "mb-6"}
        [:label {:class "block text-sm font-medium text-subtext1 mb-1" :for "community-slug"} "URL Slug"]
        [:input {:type "text"
                 :id "community-slug"
                 :name "slug"
                 :data-bind "communitySlug"
                 "data-signals:communitySlug" ""
                 :required true
                 :pattern "[a-z0-9][a-z0-9-]*[a-z0-9]"
                 :placeholder "my-team"
                 :class "w-full px-3 py-2 bg-surface0 border border-surface1 rounded-lg text-text
                         placeholder-overlay0 focus:outline-none focus:border-blue"}]
        [:p {:class "text-xs text-overlay0 mt-1"} "Lowercase letters, digits, and hyphens only."]]
       [:button {:type "submit"
                 :class "w-full py-2 px-4 bg-blue text-base font-semibold rounded-lg
                         hover:opacity-90 transition-opacity"}
        "Create Community"]
       [:div {:id "setup-error" :class "mt-4 text-red text-sm text-center"}]]]]))
