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

  // 服务者详情 / 主页
  function ProviderDetailPage({ providerId }) {
    const { getProvider, items, services, favProviders, toggleFavProvider, showToast } = useApp();
    const p = getProvider(providerId);
    if (!p) return null;
    const providerItems = items.filter(i => i.providerId === providerId);
    const saved = favProviders.includes(p.id);
    const [tab, setTab] = useState('items');

    const IMAGE_BG = ['#FFE9B0','#D6F0FB','#EBDDF6','#FFDCE4','#D8F0D8','#FFE0C2'];
    const IMAGE_ICONS = ['paw','sparkle','home','star','heart','bone'];

    return (
      <div className="h-full overflow-y-auto no-scrollbar pb-32">
        {/* HERO */}
        <div className="relative h-56 overflow-hidden"
             style={{ background: 'linear-gradient(135deg, #FFE9B0 0%, #FFD58F 50%, #FFB877 100%)' }}>
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="opacity-60 text-bark-900" style={{filter: 'drop-shadow(0 8px 16px rgba(93,58,31,0.3))'}}>
              <Avatar name={p.name} size={120} square className="!rounded-3xl"/>
            </div>
          </div>

          {/* 状态条 */}
          <div className="absolute bottom-3 left-5 right-5 flex items-center justify-between">
            <div className="px-2 py-1 rounded-full bg-white/80 backdrop-blur text-[10px] font-bold text-bark-900 flex items-center gap-1">
              <span className={`w-1.5 h-1.5 rounded-full ${p.status === '营业中' ? 'bg-leaf-500 animate-pulse' : 'bg-amber-400'}`}></span>
              {p.status}
            </div>
            <div className="text-[10px] text-white font-bold bg-bark-900/40 backdrop-blur rounded-full px-2 py-1 flex items-center gap-1">
              <Icon name="image" size={11}/>{p.images.length} 张展示图
            </div>
          </div>
        </div>

        {/* 主页信息卡 */}
        <div className="px-5 -mt-6 relative z-10">
          <div className="bg-white rounded-3xl border-2 border-cream-200 shadow-2xl p-4">
            <div className="flex items-start gap-3">
              <div className="-mt-10 shrink-0 rounded-2xl shadow-lg border-2 border-white">
                <Avatar name={p.name} size={64} square/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5 flex-wrap">
                  <div className="font-display text-lg text-bark-900 truncate">{p.name}</div>
                  {p.authStatus === 'verified' && (
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-leaf-400 text-white font-bold shrink-0 flex items-center gap-0.5">
                      <Icon name="check" size={9} strokeWidth={3}/>认证
                    </span>
                  )}
                  {p.featured && <span className="text-[10px] px-1.5 py-0.5 rounded bg-shiba-500 text-white font-bold shrink-0">优选</span>}
                </div>
                <div className="text-[11px] text-bark-700 font-bold mt-0.5">{p.tag} · {p.authType}</div>
              </div>
              <button onClick={() => toggleFavProvider(p.id)}
                      className={`w-9 h-9 rounded-full flex items-center justify-center shrink-0 ${
                        saved ? 'bg-pink-cheek/20 text-pink-cheek' : 'bg-cream-100 text-bark-700'
                      }`}>
                <Icon name="heart" size={18} filled={saved}/>
              </button>
            </div>

            {/* 数据 */}
            <div className="grid grid-cols-4 gap-2 mt-3 pt-3 border-t border-dashed border-cream-200 text-center">
              <div>
                <div className="font-display text-base text-amber-500 leading-none flex items-center justify-center gap-0.5">
                  <Icon name="star" size={11} filled/>{p.rating}
                </div>
                <div className="text-[9px] text-bark-700 font-bold mt-0.5">{p.reviews}评价</div>
              </div>
              <div>
                <div className="font-display text-base text-bark-900 leading-none">{p.served}</div>
                <div className="text-[9px] text-bark-700 font-bold mt-0.5">已服务</div>
              </div>
              <div>
                <div className="font-display text-base text-leaf-500 leading-none">{p.responseTime}min</div>
                <div className="text-[9px] text-bark-700 font-bold mt-0.5">平均响应</div>
              </div>
              <div>
                <div className="font-display text-base text-shiba-600 leading-none">{p.repeatRate}</div>
                <div className="text-[9px] text-bark-700 font-bold mt-0.5">回头率</div>
              </div>
            </div>

            {/* 地址 */}
            <div className="mt-3 flex items-start gap-2 bg-cream-50 rounded-2xl p-3">
              <Icon name="location" size={16} className="mt-0.5 shrink-0 text-shiba-500"/>
              <div className="flex-1">
                <div className="text-[10px] text-bark-700 font-bold">{p.area} · {p.distance}</div>
                <div className="text-xs text-bark-900 font-bold mt-0.5">{p.address}</div>
              </div>
              <button className="text-[11px] font-bold text-shiba-600 flex items-center gap-0.5">
                导航<Icon name="chevronRight" size={10} strokeWidth={2.5}/>
              </button>
            </div>

            {/* 简介 */}
            <div className="mt-3 text-xs text-bark-800 leading-relaxed">"{p.intro}"</div>
          </div>
        </div>

        {/* 展示图片 */}
        <div className="px-5 mt-4">
          <div className="font-kuaile text-base text-bark-900 mb-2">主页展示</div>
          <div className="grid grid-cols-3 gap-2">
            {p.images.map((_, i) => (
              <div key={i} className="aspect-square rounded-2xl border-2 border-cream-200 flex items-center justify-center"
                   style={{ background: IMAGE_BG[i % IMAGE_BG.length] }}>
                <Icon name={IMAGE_ICONS[i % IMAGE_ICONS.length]} size={28} className="text-bark-700/60"/>
              </div>
            ))}
          </div>
        </div>

        {/* Tab */}
        <div className="px-5 mt-5">
          <div className="flex items-center gap-1 bg-cream-100 rounded-full p-1">
            {[
              { k: 'items',   l: `服务项目 ${providerItems.length}` },
              { k: 'reviews', l: `评价 ${p.reviews}` },
            ].map(t => (
              <button key={t.k} onClick={() => setTab(t.k)}
                      className={`flex-1 py-2 rounded-full text-xs font-bold transition-all ${
                        tab === t.k ? 'bg-white text-shiba-600 shadow' : 'text-bark-700'
                      }`}>{t.l}</button>
            ))}
          </div>
        </div>

        {tab === 'items' && (
          <div className="px-5 mt-4 space-y-3">
            {providerItems.map(it => {
              const svc = services[it.type];
              return (
                <div key={it.id} className="bg-white rounded-2xl p-3 border-2 border-cream-200 lift-card">
                  <div className="flex items-center gap-3">
                    <div className="w-14 h-14 rounded-xl flex items-center justify-center shrink-0" style={{ background: svc.bg, color: svc.color }}>
                      <ServiceIcon type={it.type} size={24} color={svc.color}/>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-bold text-sm text-bark-900 truncate">{it.name}</div>
                      <div className="text-[11px] text-bark-700 mt-0.5 line-clamp-2" style={{display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden'}}>{it.desc}</div>
                      <div className="flex items-center gap-2 mt-1 text-[11px]">
                        <span className="font-bold text-shiba-600">{it.price}</span>
                        <span className="text-bark-700">·</span>
                        <span className="text-bark-700 flex items-center gap-0.5"><Icon name="eye" size={10}/>{it.views}</span>
                        <span className="text-bark-700 flex items-center gap-0.5"><Icon name="heart" size={10} filled className="text-pink-cheek"/>{it.favs}</span>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
            {providerItems.length === 0 && (
              <div className="text-center py-8 text-bark-700 text-xs">暂无服务项目</div>
            )}
          </div>
        )}

        {tab === 'reviews' && (
          <div className="px-5 mt-4 space-y-3">
            <div className="bg-white rounded-2xl border-2 border-cream-200 p-4 text-center">
              <div className="font-display text-4xl text-amber-500 flex items-center justify-center gap-1">
                <Icon name="star" size={32} filled/>{p.rating}
              </div>
              <div className="text-[11px] text-bark-700 font-bold mt-1">{p.reviews} 条真实评价 · 好评率 {p.repeatRate}</div>
            </div>
            {[
              { name: '林女士', stars: 5, content: '态度超好,可乐很喜欢,会回头预约!', time: '2小时前', tag: '回头客' },
              { name: '张先生', stars: 5, content: '服务很专业,把汤圆照顾得很好,每天都拍照打卡', time: '昨天', tag: '已沟通' },
              { name: '王女士', stars: 4, content: '价格略高,但服务质量确实在线,值得', time: '3天前', tag: '已沟通' },
            ].map((r, i) => (
              <div key={i} className="bg-white rounded-2xl p-3 border-2 border-cream-200">
                <div className="flex items-center gap-2 mb-1">
                  <Avatar name={r.name} size={32}/>
                  <div className="flex-1">
                    <div className="text-xs font-bold text-bark-900">{r.name}</div>
                    <div className="text-[10px] text-amber-500 font-bold flex items-center gap-0.5">
                      {Array.from({length: r.stars}).map((_, j) => <Icon key={j} name="star" size={9} filled/>)}
                    </div>
                  </div>
                  <span className="text-[10px] text-bark-700 font-bold">{r.time}</span>
                </div>
                <div className="text-xs text-bark-800 leading-snug">{r.content}</div>
                <div className="mt-1 text-[10px] inline-block px-1.5 py-0.5 rounded bg-cream-100 text-bark-700 font-bold">{r.tag}</div>
              </div>
            ))}
          </div>
        )}

        {/* 底部固定 CTA */}
        <div className="fixed bottom-0 left-0 right-0 z-30 bg-white border-t-2 border-cream-200 p-3 px-5 flex gap-2"
             style={{boxShadow: '0 -8px 24px -8px rgba(93, 58, 31, 0.12)'}}>
          <button onClick={() => showToast('举报', '24h 内人工处理', 'warn')}
                  className="w-11 h-11 rounded-full bg-cream-100 text-bark-800 flex items-center justify-center">
            <Icon name="flag" size={16}/>
          </button>
          <button onClick={() => showToast(`已开始沟通 · ${p.name}`, '通常 5 分钟内回复', 'success')}
                  className="flex-1 py-3 rounded-full bg-white border-2 border-shiba-400 text-shiba-600 text-sm font-bold flex items-center justify-center gap-1">
            <Icon name="message" size={14}/>私信
          </button>
          <button onClick={() => showToast(`联系: ${p.contact}`, p.address, 'success')}
                  className="flex-1 bone-btn !py-3 text-sm flex items-center justify-center gap-1">
            <Icon name="phone" size={14}/>立即联系
          </button>
        </div>
      </div>
    );
  }

  // 聊天详情页
  function ChatPage({ convId }) {
    const { getConv, chatMessages, showToast } = useApp();
    const c = getConv(convId);
    const [input, setInput] = useState('');
    const [msgs, setMsgs] = useState(chatMessages[convId] || [
      { id: 1, type: 'time', text: '今天 14:00' },
      { id: 2, from: 'them', text: '您好~ 请问还在吗?' },
    ]);

    if (!c) return null;

    const send = () => {
      if (!input.trim()) return;
      setMsgs([...msgs, { id: Date.now(), from: 'me', text: input }]);
      setInput('');
      setTimeout(() => {
        setMsgs(prev => [...prev, { id: Date.now() + 1, from: 'them', text: '收到啦!稍等我回复~' }]);
      }, 1500);
    };

    return (
      <div className="h-full flex flex-col">
        {/* 头部 */}
        <div className="shrink-0 pt-12 pb-3 px-14 bg-cream-50 border-b border-cream-200">
          <div className="text-center">
            <div className="font-bold text-sm text-bark-900">{c.providerName}</div>
            <div className="text-[10px] text-bark-700 font-bold flex items-center justify-center gap-1">
              <span className={`w-1.5 h-1.5 rounded-full ${c.online ? 'bg-leaf-500' : 'bg-bark-700/40'}`}></span>
              {c.online ? '在线' : '离线'}
            </div>
          </div>
        </div>

        {/* 消息流 */}
        <div className="flex-1 overflow-y-auto no-scrollbar px-4 py-4 space-y-3 pattern-paws">
          {msgs.map(m => {
            if (m.type === 'time') {
              return <div key={m.id} className="text-center text-[10px] text-bark-700 font-bold">{m.text}</div>;
            }
            const isMe = m.from === 'me';
            return (
              <div key={m.id} className={`flex gap-2 ${isMe ? 'flex-row-reverse' : ''}`}>
                <Avatar name={isMe ? '我' : c.providerName} size={32}/>
                <div className={`max-w-[70%] ${isMe ? 'items-end' : 'items-start'} flex flex-col`}>
                  {m.isImg ? (
                    <div className="rounded-2xl border-2 border-cream-200 bg-white p-3 text-center text-bark-700">
                      <Icon name="image" size={32}/>
                      <div className="text-[10px] mt-1">汤圆撒娇.jpg</div>
                    </div>
                  ) : (
                    <div className={`px-3 py-2 rounded-2xl text-sm leading-snug ${
                      isMe
                        ? 'bg-gradient-to-br from-shiba-400 to-shiba-500 text-white rounded-br-md'
                        : 'bg-white border border-cream-200 text-bark-900 rounded-bl-md'
                    }`}>
                      {m.text}
                    </div>
                  )}
                  {m.read && <div className="text-[9px] text-bark-700 font-bold mt-0.5 mr-1">已读</div>}
                </div>
              </div>
            );
          })}
        </div>

        {/* 输入区 */}
        <div className="shrink-0 bg-white border-t border-cream-200 p-3 pb-7 flex items-end gap-2">
          <button onClick={() => showToast('图片上传', '支持 ≤5MB', 'success')}
                  className="w-9 h-9 rounded-full bg-cream-100 flex items-center justify-center text-bark-800">
            <Icon name="camera" size={16}/>
          </button>
          <div className="flex-1 bg-cream-100 rounded-2xl px-3 py-2 flex items-center gap-2">
            <input value={input}
                   onChange={(e) => setInput(e.target.value.slice(0, 500))}
                   onKeyDown={(e) => e.key === 'Enter' && send()}
                   className="flex-1 bg-transparent outline-none text-sm text-bark-900 placeholder:text-bark-700/50 min-w-0"
                   placeholder="输入消息(限 500 字)..."/>
            <span className="text-[9px] text-bark-700 shrink-0">{input.length}/500</span>
          </div>
          <button onClick={send}
                  className="px-4 h-9 rounded-full bg-shiba-500 text-white text-xs font-bold flex items-center gap-1">
            <Icon name="send" size={12}/>发送
          </button>
        </div>
      </div>
    );
  }

  // 认证申请页
  function AuthApplyPage() {
    const { me, showToast, popRoute } = useApp();
    const [type, setType] = useState(me.authType === '宠物店' ? 'shop' : 'personal');

    return (
      <div className="h-full overflow-y-auto no-scrollbar pb-24">
        <div className="px-5 pt-14 pb-6"
             style={{ background: 'linear-gradient(180deg, #D8F0D8 0%, #C8E8C8 50%, #FFF4D6 100%)' }}>
          <div className="text-xs font-bold text-leaf-500 tracking-wider mb-1">AUTH</div>
          <div className="font-kuaile text-2xl text-bark-900">身份认证</div>
          <div className="text-xs text-bark-700 font-bold mt-1">通过后即可发布服务,信息将展示给用户</div>
        </div>

        {me.authStatus === 'verified' && (
          <div className="px-5 mt-4">
            <div className="bg-gradient-to-br from-leaf-400 to-leaf-500 rounded-3xl p-4 text-white">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-2xl bg-white/20 flex items-center justify-center">
                  <Icon name="check" size={28} strokeWidth={3}/>
                </div>
                <div>
                  <div className="font-display text-lg">{me.authType}认证已通过</div>
                  <div className="text-xs opacity-90 mt-0.5">有效期至 {me.authExpire}</div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 认证类型选择 */}
        <div className="px-5 mt-4">
          <div className="font-kuaile text-base text-bark-900 mb-2">认证类型</div>
          <div className="grid grid-cols-2 gap-3">
            {[
              { k: 'shop',     icon: 'home',   l: '宠物店认证',     s: '需上传营业执照' },
              { k: 'personal', icon: 'user',   l: '个人服务者认证', s: '需上传身份证' },
            ].map(t => (
              <button key={t.k} onClick={() => setType(t.k)}
                      className={`rounded-2xl p-4 border-2 transition-all ${
                        type === t.k ? 'border-shiba-500 bg-cream-50 scale-105' : 'border-cream-200 bg-white'
                      }`}>
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center mb-2 ${
                  type === t.k ? 'bg-shiba-500 text-white' : 'bg-cream-100 text-bark-700'
                }`}>
                  <Icon name={t.icon} size={20} strokeWidth={2.5}/>
                </div>
                <div className="font-bold text-sm text-bark-900">{t.l}</div>
                <div className="text-[10px] text-bark-700 font-bold mt-1">{t.s}</div>
              </button>
            ))}
          </div>
        </div>

        {/* 表单 */}
        <div className="px-5 mt-4 space-y-3">
          <div className="bg-white rounded-2xl border-2 border-cream-200 p-3">
            <div className="text-[10px] font-bold text-bark-700 mb-1">{type === 'shop' ? '店铺' : '真实'}名称</div>
            <input className="w-full outline-none text-sm font-bold text-bark-900 bg-transparent" readOnly value={type === 'shop' ? '橘橘宠物生活馆' : '木木'}/>
          </div>
          <div className="bg-white rounded-2xl border-2 border-cream-200 p-3">
            <div className="text-[10px] font-bold text-bark-700 mb-1">联系电话</div>
            <input className="w-full outline-none text-sm font-bold text-bark-900 bg-transparent" readOnly value="155****8888"/>
          </div>
          <div className="bg-white rounded-2xl border-2 border-cream-200 p-3">
            <div className="text-[10px] font-bold text-bark-700 mb-2">{type === 'shop' ? '上传营业执照' : '上传身份证(正反面)'}</div>
            <div className="grid grid-cols-2 gap-2">
              {[1, 2].map(i => (
                <div key={i} className="aspect-square rounded-xl bg-cream-100 border-2 border-dashed border-cream-200 flex items-center justify-center text-bark-700">
                  <Icon name="camera" size={28}/>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* 提示 */}
        <div className="px-5 mt-4">
          <div className="bg-cream-100 border-2 border-dashed border-shiba-400 rounded-2xl p-3">
            <div className="text-xs font-bold text-shiba-600 mb-1 flex items-center gap-1">
              <Icon name="warn" size={12}/>认证规则
            </div>
            <div className="text-[11px] text-bark-800 leading-relaxed">
              • 提交后 24h 内完成审核 → 通过 / 驳回<br/>
              • 通过后有效期 1 年,到期前 30 天可申请续期<br/>
              • 连续被驳回 ≥3 次需等待 7 天后再次提交
            </div>
          </div>
        </div>

        {/* 底部 CTA */}
        <div className="px-5 mt-6">
          <button onClick={() => { showToast('已提交认证申请', '24h 内人工审核', 'success'); popRoute(); }}
                  className="w-full bone-btn flex items-center justify-center gap-2">
            提交认证申请 <Icon name="chevronRight" size={14} strokeWidth={2.5}/>
          </button>
        </div>
      </div>
    );
  }

  window.__SHAPE__.pages = window.__SHAPE__.pages || {};
  window.__SHAPE__.pages.ProviderDetailPage = ProviderDetailPage;
  window.__SHAPE__.pages.ChatPage = ChatPage;
  window.__SHAPE__.pages.AuthApplyPage = AuthApplyPage;
})();
