const CEndDemoView = ({ industry }) => {
  const currentScenarios = scenarios[industry];
  const [activeScenario, setActiveScenario] = React.useState(currentScenarios[0]);
  const [screenState, setScreenState] = React.useState('appHome');
  const [chatHistory, setChatHistory] = React.useState([]);
  const [parseState, setParseState] = React.useState('idle');
  const [pipeStep, setPipeStep] = React.useState(0);
  const timeoutRefs = React.useRef([]);

  const clearTimeouts = () => timeoutRefs.current.forEach(clearTimeout);
  const push = (fn, ms) => { const t = setTimeout(fn, ms); timeoutRefs.current.push(t); };

  const startChatScenario = (scenario) => {
    clearTimeouts();
    setActiveScenario(scenario);
    setScreenState('chat');
    setChatHistory([]);
    setParseState('idle');
    setPipeStep(0);

    push(() => {
      setChatHistory([{ role: 'user', text: scenario.userMsg }]);
      setParseState('analyzing');
      scenario.pipeline.forEach((_, i) => push(() => setPipeStep(i + 1), 350 + i * 360));
      push(() => {
        setParseState('done');
        setChatHistory(prev => [...prev, { role: 'ai', text: scenario.aiReply, richCard: scenario.richCard }]);
      }, 1850);
    }, 400);
  };

  React.useEffect(() => {
    clearTimeouts();
    setScreenState('appHome');
    setActiveScenario(currentScenarios[0]);
    setChatHistory([]);
    setParseState('idle');
    setPipeStep(0);
    const t = setTimeout(() => startChatScenario(currentScenarios[0]), 1200);
    timeoutRefs.current.push(t);
    return clearTimeouts;
  }, [industry]);

  return (
    <div className="animate-fade-in-up w-full max-w-6xl mx-auto flex flex-col lg:flex-row items-center lg:items-start gap-10">
      <div className="flex-1 flex flex-col gap-5 w-full order-2 lg:order-1">
        <div className="surface-card rounded-2xl p-6">
          <Kicker className="mb-4">Customer Journey · 测试用例</Kicker>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {currentScenarios.map(sc => {
              const on = activeScenario.id === sc.id && screenState === 'chat';
              return (
                <div
                  key={sc.id}
                  onClick={() => startChatScenario(sc)}
                  className={`relative p-4 rounded-xl border cursor-pointer transition-all ${on ? 'bg-slate-900 text-slate-50 border-slate-900 shadow-md' : 'bg-white border-slate-200 hover:border-brand-300 hover:shadow-sm'}`}
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className={`p-1.5 rounded-lg ${on ? 'bg-white/10 text-brand-300' : 'bg-slate-50 text-slate-500 border border-slate-200'}`}>
                      <Icon name={sc.icon} className="w-4 h-4" />
                    </div>
                    <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${sc.priority === '紧急' ? 'bg-red-50 text-red-600 border border-red-200' : on ? 'bg-white/10 text-slate-300' : 'bg-slate-50 text-slate-400 border border-slate-200'}`}>{sc.priority}</span>
                  </div>
                  <div className={`font-bold text-[15px] ${on ? 'text-slate-50' : 'text-slate-900'}`}>{sc.title}</div>
                  <div className={`text-[11px] font-medium mt-1 ${on ? 'text-slate-400' : 'text-slate-500'}`}>{sc.shortDesc}</div>
                  <div className={`mt-2.5 inline-flex items-center gap-1 text-[10px] font-semibold ${on ? 'text-slate-400' : 'text-slate-400'}`}>
                    <Icon name="radio" className="w-3 h-3" /> 来源 · {sc.channel}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="rounded-3xl ink-panel shadow-xl text-slate-50 p-7 min-h-[440px] flex flex-col relative overflow-hidden flex-1 border border-slate-800">
          <div className="flex items-center justify-between mb-1 relative z-10">
            <div className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-kicker text-slate-400">
              <span className="h-[14px] w-[3px] rounded-full bg-gold" /> AI 语义网关 · 实时解析
            </div>
            <span className="inline-flex items-center gap-1.5 text-[11px] font-semibold text-slate-400">
              <LiveDot tone={parseState === 'idle' ? 'gold' : 'emerald'} />
              {parseState === 'idle' ? 'Standby' : parseState === 'analyzing' ? 'Processing' : 'Resolved'}
            </span>
          </div>

          <div className="flex-1 flex flex-col justify-center relative z-10">
            {screenState === 'appHome' || parseState === 'idle' ? (
              <div className="flex flex-col items-center text-slate-500 text-center py-8">
                <div className="w-16 h-16 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center mb-5">
                  <Icon name="brain-circuit" className="w-8 h-8 opacity-50 text-brand-300" />
                </div>
                <p className="text-sm font-bold text-slate-300">AI 语义网关 · 就绪</p>
                <p className="text-xs mt-2 opacity-70 inline-flex items-center gap-1.5"><Icon name="loader" className="w-3 h-3 animate-spin" /> 实时解析演示即将开始</p>
              </div>
            ) : parseState === 'analyzing' ? (
              <div className="animate-fade-in w-full">
                <div className="flex items-center gap-3 mb-6">
                  <div className="w-10 h-10 rounded-xl bg-white/10 border border-white/10 flex items-center justify-center animate-spin" style={{ animationDuration: '2s' }}>
                    <Icon name="loader" className="w-5 h-5 text-brand-300" />
                  </div>
                  <div>
                    <div className="text-[11px] text-slate-400 font-bold uppercase tracking-widest">NLP Gateway Processing</div>
                    <div className="text-sm font-bold text-slate-100 mt-0.5">语义网关解析管线运行中…</div>
                  </div>
                </div>
                <div className="space-y-2.5">
                  {activeScenario.pipeline.map((p, i) => {
                    const done = pipeStep > i, active = pipeStep === i;
                    return (
                      <div key={i} className={`flex items-center gap-3 rounded-xl border px-4 py-2.5 transition-all ${done ? 'border-emerald-500/30 bg-emerald-500/10' : active ? 'border-brand-400/40 bg-brand-500/10' : 'border-white/5 bg-white/[0.02]'}`}>
                        <div className={`w-6 h-6 rounded-lg flex items-center justify-center shrink-0 ${done ? 'bg-emerald-500/20 text-emerald-300' : active ? 'bg-brand-500/20 text-brand-300' : 'bg-white/5 text-slate-500'}`}>
                          {done ? <Icon name="check" className="w-3.5 h-3.5" /> : <span className="text-[11px] font-bold font-mono">{i + 1}</span>}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className={`text-[13px] font-bold ${done || active ? 'text-slate-100' : 'text-slate-500'}`}>{p.stage}</div>
                          <div className="text-[11px] text-slate-400 font-medium truncate">{p.detail}</div>
                        </div>
                        {active && <Icon name="loader" className="w-3.5 h-3.5 text-brand-300 animate-spin" />}
                      </div>
                    );
                  })}
                </div>
              </div>
            ) : (
              <div className="animate-fade-in-up space-y-4 relative z-10">
                <div className="flex items-center justify-between border-b border-white/10 pb-4">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-emerald-500/15 rounded-xl flex items-center justify-center border border-emerald-500/20">
                      <Icon name="check-circle" className="w-5 h-5 text-emerald-300" />
                    </div>
                    <div>
                      <div className="text-[11px] text-slate-400 font-bold uppercase tracking-widest">Analysis Complete</div>
                      <div className="font-bold text-[15px] text-slate-50">系统级拦截与解析成功</div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="font-display text-[20px] font-semibold text-brand-300 tnum">{activeScenario.config.confidence}%</div>
                    <div className="text-[10px] text-slate-500 font-medium">置信度 · {activeScenario.config.latency}ms</div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-white/[0.04] p-4 rounded-xl border border-white/10">
                    <div className="text-[11px] text-slate-400 mb-2 font-semibold">匹配路由引擎</div>
                    <div className="font-bold text-slate-100 text-[13px]">{activeScenario.config.intent}</div>
                  </div>
                  <div className="bg-white/[0.04] p-4 rounded-xl border border-white/10">
                    <div className="text-[11px] text-slate-400 mb-2 font-semibold">提取特征 Entities</div>
                    <div className="flex flex-wrap gap-1.5">
                      {activeScenario.config.entities.map((e, i) => (
                        <span key={i} className={`text-[10px] px-2 py-0.5 rounded font-bold ${e.type === 'danger' ? 'bg-red-500/20 text-red-300' : e.type === 'warning' ? 'bg-amber-500/20 text-amber-300' : e.type === 'gold' ? 'bg-brand-500/20 text-brand-300' : 'bg-white/10 text-slate-300'}`}>{e.value}</span>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="bg-black/30 p-4 rounded-xl border border-white/10">
                  <div className="text-[11px] text-slate-400 mb-2 font-semibold flex items-center gap-1.5">
                    <Icon name="terminal" className="w-3.5 h-3.5" /> B 端系统 Action 执行指令
                  </div>
                  <div className="font-mono text-[12px] text-brand-300 leading-relaxed break-all">{activeScenario.config.routingAction}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="phone-stage phone-stage-customer flex justify-center shrink-0 order-1 lg:order-2">
        <div className="phone-shell-customer bg-white rounded-[3rem] border-[12px] border-slate-900 shadow-2xl relative flex flex-col overflow-hidden">
          <div className="absolute top-0 inset-x-0 h-7 bg-slate-900 rounded-b-3xl w-36 mx-auto z-30 flex justify-center items-end pb-2">
            <div className="w-12 h-1 bg-slate-700 rounded-full" />
          </div>
          <PhoneStatusBar dark={screenState !== 'appHome'} />
          {screenState === 'appHome'
            ? <CustomerHome industry={industry} onOpenChat={() => setScreenState('chat')} />
            : <CustomerChat chatHistory={chatHistory} parseState={parseState} onBack={() => setScreenState('appHome')} />}
        </div>
      </div>
    </div>
  );
};

const PhoneStatusBar = ({ dark }) => (
  <div className={`absolute top-0 inset-x-0 h-11 px-7 flex items-end justify-between pb-1.5 z-20 pointer-events-none ${dark ? 'text-slate-700' : 'text-slate-900'}`}>
    <span className="text-[12px] font-bold tnum">9:41</span>
    <div className="flex items-center gap-1.5">
      <Icon name="signal" className="w-3.5 h-3.5" />
      <Icon name="wifi" className="w-3.5 h-3.5" />
      <Icon name="battery-full" className="w-4 h-4" />
    </div>
  </div>
);

const CustomerHome = ({ industry, onOpenChat }) => (
  <div className="flex-1 flex flex-col bg-[#f4f1ea] relative animate-fade-in overflow-hidden">
    <div className="px-6 pt-12 pb-5 bg-white border-b border-slate-200/70 relative">
      <div className="flex items-start justify-between mb-6">
        <div>
          <div className="text-[11px] font-bold text-gold tracking-widest uppercase mb-1.5">NextGen 旗舰品牌</div>
          <h2 className="font-display text-[27px] leading-tight font-semibold tracking-tight text-slate-900">{industry === 'restaurant' ? '尊享美食体验' : '欢迎下榻本酒店'}</h2>
        </div>
        <div className="w-10 h-10 rounded-xl ink-panel flex items-center justify-center text-brand-300 shadow-sm">
          <Icon name={industry === 'restaurant' ? 'utensils' : 'building-2'} className="w-5 h-5" />
        </div>
      </div>
      <div className="bg-white border border-slate-200 rounded-2xl p-3 flex justify-between items-center shadow-sm">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 ink-panel rounded-xl flex items-center justify-center text-brand-300"><Icon name="crown" className="w-5 h-5" /></div>
          <div>
            <div className="text-sm font-bold text-slate-900">王先生 · <span className="text-gold">尊贵金卡</span></div>
            <div className="text-[11px] font-medium text-slate-500 tnum">积分 12,500 · 距铂金 2,500</div>
          </div>
        </div>
        <div className="w-8 h-8 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center text-slate-500"><Icon name="qr-code" className="w-4 h-4" /></div>
      </div>
    </div>

    <div className="flex-1 px-5 py-4 relative z-10 space-y-4 overflow-y-auto no-scrollbar">
      {industry === 'restaurant' ? <RestaurantHomeCards /> : <HotelHomeCards />}
    </div>

    <div
      onClick={onOpenChat}
      className="absolute bottom-7 right-5 flex items-center gap-2 ink-panel pl-3 pr-4 py-2.5 rounded-2xl shadow-xl cursor-pointer hover:scale-105 transition-transform pulse-glow"
    >
      <div className="w-7 h-7 rounded-xl bg-brand-500/20 flex items-center justify-center"><Icon name="sparkles" className="w-4 h-4 text-brand-300" /></div>
      <div className="leading-none">
        <div className="text-[12px] font-bold text-slate-50">AI 管家</div>
        <div className="text-[9px] text-slate-400 font-medium mt-0.5">随时为您服务</div>
      </div>
    </div>
  </div>
);

const RestaurantHomeCards = () => (
  <>
    <div className="relative rounded-2xl overflow-hidden ink-panel p-5 text-slate-50 shadow-md">
      <div className="relative z-10">
        <div className="text-[10px] font-bold uppercase tracking-widest text-brand-300 mb-1.5">秋季限定 · 主厨臻选</div>
        <div className="font-display text-[20px] font-semibold leading-tight">松露和牛盲盒菜单</div>
        <div className="text-[12px] text-slate-300 mt-1.5 font-medium">早鸟 8 折 · 每日限量 30 席</div>
        <button className="mt-3.5 inline-flex items-center gap-1.5 bg-brand-500 text-slate-950 text-[12px] font-bold px-4 py-2 rounded-xl">立即预订 <Icon name="arrow-right" className="w-3.5 h-3.5" /></button>
      </div>
      <Icon name="utensils-crossed" className="absolute -right-2 -bottom-3 w-24 h-24 text-white/5" />
    </div>

    <div className="grid grid-cols-4 gap-2 bg-white p-4 rounded-2xl shadow-sm border border-slate-200">
      {[['utensils', '堂食点餐'], ['ticket-check', '取号排队'], ['door-closed', '预订包间'], ['shopping-bag', '外卖自提']].map(([icon, label]) => (
        <div key={label} className="flex flex-col items-center gap-1.5">
          <div className="w-11 h-11 bg-slate-50 text-slate-700 rounded-xl border border-slate-200 flex items-center justify-center"><Icon name={icon} className="w-5 h-5" /></div>
          <span className="text-[10px] font-bold text-slate-700">{label}</span>
        </div>
      ))}
    </div>

    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
      <div className="px-4 pt-3.5 pb-2 flex items-center justify-between">
        <span className="text-[13px] font-bold text-slate-900">招牌热销 · 今日推荐</span>
        <span className="text-[11px] font-semibold text-gold">查看全部</span>
      </div>
      {[['波士顿龙虾两吃', '¥328 / 斤 · 时价', 'star', '热销'], ['古法佛跳墙', '¥588 / 位 · 需预约', 'flame', '招牌'], ['脆皮乳鸽', '¥68 / 位', 'award', '人气']].map(([n, p, ic, t]) => (
        <div key={n} className="flex items-center gap-3 px-4 py-3 border-t border-slate-100">
          <div className="w-10 h-10 rounded-xl bg-brand-50 border border-brand-100 flex items-center justify-center text-brand-600"><Icon name={ic} className="w-4 h-4" /></div>
          <div className="flex-1 min-w-0">
            <div className="text-[13px] font-bold text-slate-900 truncate">{n}</div>
            <div className="text-[11px] text-slate-500 font-medium tnum">{p}</div>
          </div>
          <span className="text-[10px] font-bold text-brand-700 bg-brand-50 border border-brand-100 px-1.5 py-0.5 rounded">{t}</span>
        </div>
      ))}
    </div>
  </>
);

const HotelHomeCards = () => (
  <>
    <div className="bg-white p-4 rounded-2xl shadow-sm border border-slate-200">
      <div className="flex justify-between items-center pb-3 mb-3 border-b border-slate-100">
        <div><div className="text-[10px] text-slate-500 mb-0.5 font-semibold">入住</div><div className="font-bold text-slate-900 text-[15px]">10月24日</div></div>
        <div className="text-[11px] text-slate-400 font-semibold">2 晚</div>
        <div className="text-right"><div className="text-[10px] text-slate-500 mb-0.5 font-semibold">离店</div><div className="font-bold text-slate-900 text-[15px]">10月26日</div></div>
      </div>
      <button className="w-full bg-slate-900 text-slate-50 font-bold py-2.5 rounded-xl text-sm flex items-center justify-center gap-2">查询空房 <Icon name="search" className="w-4 h-4 text-brand-300" /></button>
    </div>

    <div className="relative rounded-2xl overflow-hidden ink-panel p-5 text-slate-50 shadow-md">
      <div className="relative z-10">
        <div className="text-[10px] font-bold uppercase tracking-widest text-brand-300 mb-1.5">行政楼层 · 江景</div>
        <div className="font-display text-[20px] font-semibold leading-tight">尊享行政套房</div>
        <div className="text-[12px] text-slate-300 mt-1.5 font-medium">含双早 + 行政酒廊 + 延迟退房</div>
        <div className="mt-3 flex items-baseline gap-1.5"><span className="font-display text-[22px] font-semibold text-brand-300 tnum">¥1,680</span><span className="text-[11px] text-slate-400">/ 晚起</span></div>
      </div>
      <Icon name="bed-double" className="absolute -right-2 -bottom-3 w-24 h-24 text-white/5" />
    </div>

    <div className="grid grid-cols-4 gap-2 bg-white p-4 rounded-2xl shadow-sm border border-slate-200">
      {[['key-round', '手机开门'], ['waves', '设施预约'], ['concierge-bell', '客房送餐'], ['car-front', '接送服务']].map(([icon, label]) => (
        <div key={label} className="flex flex-col items-center gap-1.5">
          <div className="w-11 h-11 bg-slate-50 text-slate-700 rounded-xl border border-slate-200 flex items-center justify-center"><Icon name={icon} className="w-5 h-5" /></div>
          <span className="text-[10px] font-bold text-slate-700">{label}</span>
        </div>
      ))}
    </div>

    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-4 flex items-center gap-3">
      <div className="w-10 h-10 rounded-xl bg-brand-50 border border-brand-100 flex items-center justify-center text-brand-600"><Icon name="sparkles" className="w-5 h-5" /></div>
      <div className="flex-1">
        <div className="text-[13px] font-bold text-slate-900">无边泳池 · 今日开放</div>
        <div className="text-[11px] text-slate-500 font-medium">07:00 – 22:00 · 当前空闲</div>
      </div>
      <Icon name="chevron-right" className="w-4 h-4 text-slate-400" />
    </div>
  </>
);

const CustomerChat = ({ chatHistory, parseState, onBack }) => (
  <div className="flex-1 flex flex-col relative animate-slide-in-right bg-[#f1ede4]">
    <div className="glass-panel px-4 pt-11 pb-3 border-b border-slate-200/70 flex items-center justify-between z-10 relative shadow-sm">
      <div className="w-8 h-8 flex items-center justify-center text-slate-700 cursor-pointer bg-white/70 border border-slate-200 rounded-full" onClick={onBack}><Icon name="chevron-left" className="w-4 h-4" /></div>
      <div className="text-sm font-bold flex items-center gap-2 text-slate-900"><LiveDot tone="emerald" /> 品牌智能管家</div>
      <div className="w-8 h-8 flex items-center justify-center text-slate-500 cursor-pointer"><Icon name="more-horizontal" className="w-4 h-4" /></div>
    </div>
    <div className="flex-1 p-4 overflow-y-auto flex flex-col gap-4 text-sm no-scrollbar">
      <div className="text-center text-[10px] text-slate-400 font-semibold my-1 tnum">12:30 PM</div>
      <ChatBubble role="ai" text="您好！我是您的专属智能管家，预订、咨询、需求处理都可以直接告诉我～" />
      {chatHistory.map((msg, idx) => <ChatBubble key={idx} {...msg} />)}
      {parseState === 'analyzing' && <TypingBubble />}
    </div>
    <div className="bg-white border-t border-slate-200 p-4 pb-6 flex gap-3 items-center shadow-lg">
      <div className="flex-1 bg-slate-50 rounded-full h-10 px-4 flex items-center text-slate-400 text-[13px] font-medium border border-slate-200">在此输入需求…</div>
      <div className="w-10 h-10 bg-slate-900 rounded-full flex items-center justify-center shadow-md"><Icon name="mic" className="w-4 h-4 text-brand-300" /></div>
    </div>
  </div>
);

const ChatBubble = ({ role, text, richCard }) => (
  <div className={`flex gap-2 animate-fade-in-up ${role === 'user' ? 'flex-row-reverse' : ''}`}>
    <div className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 shadow-sm ${role === 'user' ? 'bg-white text-slate-600 border border-slate-200' : 'ink-panel text-brand-300'}`}>
      <Icon name={role === 'user' ? 'user' : 'sparkles'} className="w-4 h-4" />
    </div>
    <div className="flex flex-col gap-2 max-w-[80%]">
      <div className={`p-3.5 rounded-2xl shadow-sm text-[13px] leading-relaxed font-medium ${role === 'user' ? 'bg-slate-900 text-slate-50 rounded-tr-sm' : 'bg-white text-slate-800 border border-slate-200 rounded-tl-sm'}`}>
        <span style={{ whiteSpace: 'pre-line' }}>{text}</span>
      </div>
      {richCard && <RichCard card={richCard} />}
    </div>
  </div>
);

const RichCard = ({ card }) => {
  const warn = card.type === 'warning';
  return (
    <div className={`bg-white border rounded-2xl overflow-hidden shadow-md animate-scale-in ${warn ? 'border-red-200' : 'border-brand-200'}`}>
      <div className={`px-4 py-2.5 text-xs font-bold flex items-center gap-2 ${warn ? 'bg-red-50 text-red-700' : 'bg-brand-50 text-brand-700 border-b border-brand-100'}`}>
        <Icon name={warn ? 'alert-triangle' : card.type === 'booking' ? 'calendar-check' : 'badge-check'} className="w-3.5 h-3.5" />{card.title}
      </div>
      <div className="p-4 flex flex-col gap-2">
        {card.date && <div className="text-[13px] font-bold text-slate-900">{card.date}</div>}
        <div className="text-[11px] text-slate-500 font-medium whitespace-pre-line leading-relaxed">{card.detail}</div>
        {card.price && <div className="font-display text-[17px] font-semibold text-slate-900 mt-1 tnum">{card.price}</div>}
        <button className={`mt-2 w-full py-2.5 rounded-xl text-xs font-bold shadow-sm transition-colors ${warn ? 'bg-red-500 hover:bg-red-600 text-white' : 'bg-slate-900 hover:bg-slate-800 text-slate-50'}`}>{card.action}</button>
      </div>
    </div>
  );
};

const TypingBubble = () => (
  <div className="flex gap-2 animate-fade-in">
    <div className="w-8 h-8 rounded-full ink-panel text-brand-300 flex items-center justify-center shrink-0 shadow-sm"><Icon name="sparkles" className="w-4 h-4" /></div>
    <div className="bg-white p-3.5 rounded-2xl rounded-tl-sm shadow-sm flex items-center gap-1.5 w-16 h-11 border border-slate-200">
      <div className="w-1.5 h-1.5 bg-brand-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
      <div className="w-1.5 h-1.5 bg-brand-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
      <div className="w-1.5 h-1.5 bg-brand-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
    </div>
  </div>
);
