const { useState: useFlowState } = React;

const catAccent = {
  knowledge: { dot: '#cf9f3f', soft: 'bg-brand-50', text: 'text-brand-700', ring: 'border-brand-200' },
  agile: { dot: '#b9842a', soft: 'bg-brand-50', text: 'text-brand-700', ring: 'border-brand-200' },
  workflow: { dot: '#423d33', soft: 'bg-slate-100', text: 'text-slate-700', ring: 'border-slate-300' }
};

const FlowchartView = ({ industry, industryData }) => {
  const [selectedIntent, setSelectedIntent] = useFlowState(null);
  const grouped = industryData.reduce((acc, item) => {
    (acc[item.category] = acc[item.category] || []).push(item);
    return acc;
  }, {});

  return (
    <div className="animate-fade-in-up w-full max-w-6xl mx-auto">
      <div className="surface-card rounded-3xl p-6 md:p-10">
        <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-9">
          <div>
            <Kicker className="mb-3">Architecture · 流转机制</Kicker>
            <h2 className="font-display text-[28px] font-semibold text-slate-900 tracking-tight">业务系统处理流转全景</h2>
            <p className="text-sm text-slate-500 mt-1.5 font-medium inline-flex items-center gap-1.5">
              <Icon name="mouse-pointer-click" className="w-3.5 h-3.5 text-gold" /> 点击任一意图，查看 AI 执行流转树
            </p>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <Badge variant="outline">{industryData.length} 类意图</Badge>
            <Badge variant="gold">实时演示</Badge>
          </div>
        </div>

        {/* 全渠道接入 */}
        <div className="rounded-2xl border border-slate-200 bg-slate-50/60 p-5 mb-4">
          <div className="text-[11px] font-bold uppercase tracking-kicker text-slate-400 mb-3">全渠道统一接入 · Omnichannel</div>
          <div className="flex flex-wrap gap-2.5">
            {channels.map(ch => (
              <div key={ch.name} className="flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3.5 py-2 shadow-sm">
                <Icon name={ch.icon} className="w-4 h-4 text-slate-500" />
                <span className="text-[13px] font-bold text-slate-800">{ch.name}</span>
                <span className="text-[11px] font-bold text-slate-400 tnum">{ch.share}%</span>
              </div>
            ))}
          </div>
        </div>

        <VerticalEdge height="h-7" />

        {/* AI 语义网关 */}
        <div className="relative rounded-2xl ink-panel text-slate-50 px-6 py-5 overflow-hidden">
          <span className="absolute inset-0 ring-1 ring-inset ring-white/10 rounded-2xl" />
          <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-white/10 border border-white/10 flex items-center justify-center">
                <Icon name="brain-circuit" className="w-6 h-6 text-brand-300" />
              </div>
              <div>
                <div className="flex items-center gap-2">
                  <span className="font-display text-[19px] font-semibold">AI 语义网关</span>
                  <LiveDot tone="gold" />
                </div>
                <div className="text-[12px] text-slate-400 font-medium mt-0.5">意图识别 · 实体抽取 · 风控判级 · 动作编排</div>
              </div>
            </div>
            <div className="flex gap-6">
              {[['平均时延', '0.6s'], ['识别准确率', '97.4%'], ['自动闭环', '79%']].map(([k, v]) => (
                <div key={k}>
                  <div className="font-display text-[20px] font-semibold text-brand-300 tnum">{v}</div>
                  <div className="text-[11px] text-slate-400 font-medium mt-0.5">{k}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="md:hidden"><VerticalEdge height="h-7" /></div>
        <FanConnector />

        {/* 三类能力分发 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {['knowledge', 'agile', 'workflow'].map(catKey => {
            const catInfo = categoryMap[catKey];
            const catItems = grouped[catKey] || [];
            const ac = catAccent[catKey];
            return (
              <div key={catKey} className="rounded-2xl border border-slate-200 bg-slate-50/50 p-5 flex flex-col">
                <div className="flex items-center gap-3.5 mb-5 px-1">
                  <div className="w-11 h-11 bg-white rounded-xl shadow-sm border border-slate-200 flex items-center justify-center text-slate-700 shrink-0 relative">
                    <Icon name={catInfo.icon} className="w-5 h-5" />
                    <span className="absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full border-2 border-slate-50" style={{ background: ac.dot }} />
                  </div>
                  <div className="flex flex-col min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="font-bold text-slate-900 text-[16px] tracking-tight truncate">{catInfo.title}</h3>
                      <span className="text-[10px] font-mono font-semibold text-slate-400">{catInfo.tag}</span>
                    </div>
                    <div className="text-xs text-slate-500 mt-0.5 font-medium">{catInfo.desc} · {catItems.length} 项</div>
                  </div>
                </div>

                <div className="space-y-3 stagger flex-1">
                  {catItems.map(item => (
                    <div
                      key={item.id}
                      onClick={() => setSelectedIntent(item)}
                      className="bg-white border border-slate-200 p-4 rounded-xl shadow-sm hover:border-brand-300 hover:shadow-md hover:-translate-y-0.5 transition-all cursor-pointer group relative overflow-hidden"
                    >
                      <div className="flex items-start gap-3">
                        <div className="w-9 h-9 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center text-slate-600 shrink-0 group-hover:text-gold transition-colors">
                          <Icon name={item.icon} className="w-4 h-4" />
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="font-bold text-[14px] text-slate-900 truncate">{item.title}</div>
                          <div className="text-[11px] text-slate-500 font-medium mt-0.5 truncate">{item.desc}</div>
                        </div>
                        <Icon name="arrow-up-right" className="w-4 h-4 text-slate-300 group-hover:text-gold transition-colors shrink-0" />
                      </div>
                      <div className="mt-3 pt-3 border-t border-slate-100 flex items-center justify-between text-[11px] font-semibold">
                        <span className="text-slate-400">{item.volume}</span>
                        <span className={`inline-flex items-center gap-1 ${item.auto === '—' ? 'text-red-500' : 'text-emerald-600'}`}>
                          <Icon name={item.auto === '—' ? 'shield-alert' : 'bot'} className="w-3 h-3" />
                          {item.auto === '—' ? '强制人工' : `自动 ${item.auto}`}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
                <ColumnSummary items={catItems} />
              </div>
            );
          })}
        </div>

        <div className="mt-6 flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-[11px] font-semibold text-slate-400">
          <span className="inline-flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-emerald-500" /> 系统自动闭环</span>
          <span className="inline-flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-brand-500" /> 敏捷库存联动</span>
          <span className="inline-flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-500" /> 风控强制升级</span>
        </div>
      </div>

      {selectedIntent && (
        <Portal>
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-slate-900/45 backdrop-blur-sm animate-dialog-overlay" onClick={() => setSelectedIntent(null)} />
          <div className="relative bg-white rounded-3xl shadow-2xl border border-slate-200 w-full max-w-3xl max-h-[86vh] flex flex-col animate-dialog-content overflow-hidden z-10">
            <div className="px-7 py-5 border-b border-slate-200 flex items-center justify-between">
              <div className="flex gap-4 items-center">
                <div className="w-11 h-11 rounded-xl bg-slate-50 border border-slate-200 shadow-sm flex items-center justify-center shrink-0">
                  <Icon name={selectedIntent.icon || 'git-branch'} className="w-5 h-5 text-slate-700" />
                </div>
                <div>
                  <div className="flex items-center gap-2.5">
                    <h2 className="font-display text-[20px] font-semibold text-slate-900">{selectedIntent.title}</h2>
                    <Badge variant="gold">{categoryMap[selectedIntent.category].tag}</Badge>
                  </div>
                  <div className="text-[12px] text-slate-500 font-medium mt-0.5">执行流转树 · {selectedIntent.volume} · 自动化 {selectedIntent.auto}</div>
                </div>
              </div>
              <button aria-label="关闭弹窗" onClick={() => setSelectedIntent(null)} className="w-9 h-9 rounded-xl bg-slate-100 hover:bg-slate-200 border border-slate-200 flex items-center justify-center text-slate-600 transition-colors cursor-pointer">
                <Icon name="x" className="w-4 h-4" />
              </button>
            </div>

            <div className="p-8 overflow-y-auto bg-slate-50/70 flex-1 flex flex-col items-center w-full dot-grid">
              {selectedIntent.logic.type === 'linear'
                ? <LinearFlow steps={selectedIntent.logic.steps} />
                : <BranchFlow logic={selectedIntent.logic} />}
            </div>

            <div className="px-7 py-3.5 border-t border-slate-200 bg-white flex items-center justify-between text-[11px] font-semibold text-slate-400">
              <span className="inline-flex items-center gap-1.5"><Icon name="info" className="w-3.5 h-3.5" /> 该流转由 AI 语义网关自动编排</span>
              <span>{categoryMap[selectedIntent.category].title}</span>
            </div>
          </div>
        </div>
        </Portal>
      )}
    </div>
  );
};

const FanConnector = () => (
  <div className="hidden md:block h-12 w-full" aria-hidden="true">
    <svg viewBox="0 0 100 48" preserveAspectRatio="none" className="h-full w-full">
      <defs>
        <marker id="fanArrow" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="6" markerHeight="6" orient="auto">
          <path d="M1 1 L7 4 L1 7" fill="none" stroke="#b9842a" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        </marker>
      </defs>
      <path d="M50 0 V20 M16.7 20 H83.3 M16.7 20 V42 M50 20 V42 M83.3 20 V42"
        fill="none" stroke="#ddba6c" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
        vectorEffect="non-scaling-stroke" />
      <path d="M16.7 30 V42" stroke="#ddba6c" strokeWidth="1.5" markerEnd="url(#fanArrow)" vectorEffect="non-scaling-stroke" />
      <path d="M50 30 V42" stroke="#ddba6c" strokeWidth="1.5" markerEnd="url(#fanArrow)" vectorEffect="non-scaling-stroke" />
      <path d="M83.3 30 V42" stroke="#ddba6c" strokeWidth="1.5" markerEnd="url(#fanArrow)" vectorEffect="non-scaling-stroke" />
      <circle cx="50" cy="0" r="1.6" fill="#b9842a" vectorEffect="non-scaling-stroke" />
    </svg>
  </div>
);

const ColumnSummary = ({ items }) => {
  const totalVol = items.reduce((s, it) => s + (parseInt(String(it.volume).replace(/[^\d]/g, ''), 10) || 0), 0);
  const autos = items.filter(it => it.auto !== '—').map(it => parseInt(it.auto, 10));
  const avgAuto = autos.length ? Math.round(autos.reduce((a, b) => a + b, 0) / autos.length) : null;
  const hasManual = items.some(it => it.auto === '—');
  return (
    <div className="mt-4 pt-4 border-t border-slate-200/70 flex items-center justify-between text-[11px] font-semibold">
      <span className="text-slate-400 tnum">合计日均 {totalVol.toLocaleString()}</span>
      {hasManual
        ? <span className="inline-flex items-center gap-1 text-red-500"><Icon name="shield-alert" className="w-3 h-3" /> 含强制人工</span>
        : <span className="text-slate-500 tnum">自动化 ≈ {avgAuto}%</span>}
    </div>
  );
};

const LinearFlow = ({ steps }) => (
  <div className="linear-flow relative flex w-full max-w-[440px] flex-col items-center py-2">
    <div className="absolute top-8 bottom-8 left-1/2 w-px -translate-x-1/2 bg-brand-200" aria-hidden="true" />
    <div className="relative z-10 flex w-full flex-col gap-8 stagger">
      {steps.map((step, idx) => (
        <div key={idx} className="relative mx-auto flex w-full items-center justify-center">
          {idx < steps.length - 1 && <div className="absolute left-1/2 top-full h-8 w-px -translate-x-1/2 bg-brand-200" />}
          <div className="relative w-full rounded-2xl border border-slate-200 bg-white px-6 py-4 text-center text-[15px] font-bold text-slate-800 shadow-sm">
            <span className="absolute left-4 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-lg bg-slate-900 text-xs font-bold text-brand-300 font-mono">
              {idx + 1}
            </span>
            <span className="block pl-9">{step.label}</span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const BranchFlow = ({ logic }) => (
  <div className="branch-flow relative w-full max-w-[720px] mx-auto h-[324px]">
    <svg className="absolute inset-0 h-full w-full pointer-events-none" viewBox="0 0 720 324" preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <marker id="flowArrow" viewBox="0 0 8 8" refX="6.5" refY="4" markerWidth="7" markerHeight="7" orient="auto">
          <path d="M1 1 L7 4 L1 7" fill="none" stroke="#b9842a" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </marker>
      </defs>
      <path d="M360 74 V118 H180 V152" fill="none" stroke="#ddba6c" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" markerEnd="url(#flowArrow)" />
      <path d="M360 74 V118 H540 V152" fill="none" stroke="#ddba6c" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" markerEnd="url(#flowArrow)" />
      <path d="M180 202 V230" fill="none" stroke="#ddba6c" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" markerEnd="url(#flowArrow)" />
      <path d="M540 202 V230" fill="none" stroke="#ddba6c" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" markerEnd="url(#flowArrow)" />
    </svg>

    <div className="absolute top-2 left-1/2 -translate-x-1/2 z-10 w-[340px] max-w-[78%] rounded-2xl border border-slate-300 bg-slate-900 px-5 py-3.5 text-center shadow-md">
      <div className="text-[10px] font-bold uppercase tracking-widest text-brand-300 mb-1">决策判定</div>
      <div className="text-[14px] font-bold text-slate-50">{logic.condition}</div>
    </div>

    <BranchLane className="left-0" label="否 / 不满足条件" tone="danger" steps={logic.falsePath} />
    <BranchLane className="right-0" label="是 / 条件匹配" tone="default" steps={logic.truePath} />
  </div>
);

const BranchLane = ({ className, label, tone, steps }) => (
  <div className={`absolute top-[156px] z-10 flex w-[47%] flex-col items-center ${className}`}>
    <span className="mb-8 inline-flex items-center rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-bold text-slate-700 shadow-sm">
      <span className={`mr-2 h-1.5 w-1.5 rounded-full ${tone === 'danger' ? 'bg-red-500' : 'bg-emerald-500'}`} />
      {label}
    </span>
    <div className="flex w-full flex-col items-center gap-4">
      {steps.map((step, idx) => (
        <div key={idx} className="w-full rounded-xl border border-slate-200 bg-white p-4 text-center text-[14px] font-bold text-slate-800 shadow-sm">
          {step.label}
        </div>
      ))}
    </div>
  </div>
);
