(function () {
  const { useState } = React;
  const { MascotShiba, Icon, Avatar, OnlineDot, useApp } = window.__SHAPE__;

  const NOTIF_ICONS = {
    comment:  { name: 'message', color: 'text-shiba-600',  bg: '#FFE9B0' },
    review:   { name: 'star',    color: 'text-amber-500',  bg: '#FFEEC2' },
    favorite: { name: 'heart',   color: 'text-pink-cheek', bg: '#FFDCE4' },
    auth:     { name: 'check',   color: 'text-leaf-500',   bg: '#D8F0D8' },
  };

  function MessagesPage() {
    const { conversations, notifications, pushRoute, showToast } = useApp();
    const [tab, setTab] = useState('chats');

    const sortedConvs = [...conversations].sort((a, b) => {
      if (a.pinned && !b.pinned) return -1;
      if (!a.pinned && b.pinned) return 1;
      return 0;
    });

    const unreadCount = conversations.reduce((s, c) => s + c.unread, 0);
    const unreadNotif = notifications.filter(n => n.unread).length;

    return (
      <div className="h-full overflow-y-auto no-scrollbar pb-28">
        {/* 顶栏 */}
        <div className="relative px-5 pt-14 pb-4 overflow-hidden"
             style={{ background: 'linear-gradient(180deg, #D6F0FB 0%, #C2E8F8 50%, #FFF4D6 100%)' }}>
          <div className="absolute top-16 right-6 opacity-20">
            <Icon name="message" size={48} className="text-bark-700"/>
          </div>

          <div className="text-xs font-bold text-bark-700 tracking-wider mb-1">MESSAGES</div>
          <div className="flex items-end justify-between">
            <div>
              <div className="font-kuaile text-2xl text-bark-900 leading-tight">消息中心</div>
              <div className="text-[11px] text-bark-700 font-bold mt-1">{unreadCount} 条未读私信 · {unreadNotif} 条新通知</div>
            </div>
            <div className="mascot-float">
              <MascotShiba mood="happy" size={64}/>
            </div>
          </div>

          {/* Tab */}
          <div className="mt-4 flex items-center gap-1 bg-white/60 backdrop-blur rounded-full p-1">
            {[
              { k: 'chats', l: '私信', badge: unreadCount, i: 'message' },
              { k: 'notif', l: '通知', badge: unreadNotif, i: 'bell' },
            ].map(t => (
              <button key={t.k}
                      onClick={() => setTab(t.k)}
                      className={`relative flex-1 flex items-center justify-center gap-1 py-2 rounded-full text-xs font-bold transition-all ${
                        tab === t.k ? 'bg-white text-shiba-600 shadow' : 'text-bark-700'
                      }`}>
                <Icon name={t.i} size={13}/>{t.l}
                {t.badge > 0 && (
                  <span className="min-w-[16px] h-4 px-1 rounded-full bg-shiba-500 text-white text-[9px] font-bold flex items-center justify-center">{t.badge}</span>
                )}
              </button>
            ))}
          </div>
        </div>

        {/* 操作条 */}
        <div className="px-5 pt-3 pb-2 flex items-center justify-between">
          <div className="text-[11px] text-bark-700 font-bold">{tab === 'chats' ? `${sortedConvs.length} 个会话` : `${notifications.length} 条通知`}</div>
          <div className="flex gap-2 text-[11px] font-bold text-bark-700">
            <button>全部已读</button>
            <span className="opacity-30">|</span>
            <button>免打扰</button>
          </div>
        </div>

        {/* 私信会话 */}
        {tab === 'chats' && (
          <>
            <div className="px-5 space-y-2">
              {sortedConvs.map(c => (
                <button key={c.id}
                        onClick={() => pushRoute('chat', { convId: c.id })}
                        className={`w-full flex items-center gap-3 p-3 text-left rounded-2xl border-2 transition-all hover:scale-[1.01] ${
                          c.pinned
                            ? 'bg-cream-100 border-shiba-400/30'
                            : 'bg-white border-cream-200'
                        }`}>
                  {/* 头像 */}
                  <div className="relative shrink-0">
                    <Avatar name={c.providerName} size={44} square/>
                    {c.online && (
                      <div className="absolute -bottom-0.5 -right-0.5">
                        <OnlineDot online size={10}/>
                      </div>
                    )}
                    {c.unread > 0 && (
                      <div className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 rounded-full bg-shiba-500 text-white text-[10px] font-bold flex items-center justify-center border-2 border-white">{c.unread}</div>
                    )}
                  </div>

                  {/* 内容 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5 mb-0.5">
                      <div className="font-bold text-sm text-bark-900 truncate">{c.providerName}</div>
                      {c.pinned && <Icon name="pin" size={11} className="text-shiba-500 shrink-0"/>}
                    </div>
                    <div className={`text-xs truncate ${c.unread > 0 ? 'text-bark-900 font-bold' : 'text-bark-700'}`}>
                      {c.lastMsg}
                    </div>
                  </div>

                  <div className="text-[10px] text-bark-700 font-bold shrink-0 self-start">{c.time}</div>
                </button>
              ))}
            </div>

            {/* 私信规则 */}
            <div className="px-5 mt-4">
              <div className="bg-cream-100 border-2 border-dashed border-cream-200 rounded-2xl p-3">
                <div className="text-xs font-bold text-bark-800 mb-1 flex items-center gap-1">
                  <Icon name="help" size={12}/> 私信规则
                </div>
                <div className="text-[11px] text-bark-700 leading-relaxed">
                  • 每分钟全局最多 30 条,单会话最多 10 条<br/>
                  • 消息可在发送后 2 分钟内撤回<br/>
                  • 消息记录保留 1 年,支持举报和拉黑
                </div>
              </div>
            </div>
          </>
        )}

        {/* 系统通知 */}
        {tab === 'notif' && (
          <div className="px-5 space-y-2">
            {notifications.map(n => {
              const ic = NOTIF_ICONS[n.type] || NOTIF_ICONS.auth;
              return (
                <div key={n.id}
                     onClick={() => showToast(n.title, n.content, 'success')}
                     className="flex items-start gap-3 p-3 rounded-2xl border-2 border-cream-200 bg-white hover:bg-cream-50 transition-colors cursor-pointer">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${ic.color}`} style={{ background: ic.bg }}>
                    <Icon name={ic.name} size={18} filled={n.type === 'favorite'}/>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <div className="font-bold text-sm text-bark-900 truncate">{n.title}</div>
                      {n.unread && <span className="w-1.5 h-1.5 rounded-full bg-shiba-500 shrink-0"></span>}
                    </div>
                    <div className="text-xs text-bark-700 mt-0.5 leading-snug">{n.content}</div>
                    <div className="text-[10px] text-bark-700 font-bold mt-1 opacity-60">{n.time}</div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  window.__SHAPE__.pages = window.__SHAPE__.pages || {};
  window.__SHAPE__.pages.MessagesPage = MessagesPage;
})();
