/**
 * @name 业务条线说明
 * ONE-OS 多业务条线运作说明：租赁 / 能源 / 运维 / 安全 / 自营
 */
import './style.css';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ArrowRight,
  BarChart3,
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  Flag,
  GitBranch,
  Layers,
  MonitorPlay,
  Sparkles,
  Target,
  Users,
  X,
} from 'lucide-react';
import {
  scrollToSection,
  usePresentationStep,
  useScrollSpy,
  useScrolledPast,
} from './hooks';
import {
  BUSINESS_LINES,
  BUSINESS_LINE_MAP,
  DEFAULT_BUSINESS_LINE_ID,
  LINE_ACCENTS,
  LINE_TAB_ICONS,
  SYSTEM_INTRO,
  type BusinessLineConfig,
  type BusinessLineId,
  type LineModule,
} from './lines';
import {
  DATA_FOUNDATION_INTRO,
  DATA_FOUNDATION_PILLARS,
  type DataFoundationPillar,
} from './data-foundations';

function parseLineIdFromHash(): BusinessLineId {
  const raw = window.location.hash.replace(/^#/, '').split(/[/?]/)[0];
  if (raw && raw in BUSINESS_LINE_MAP) return raw as BusinessLineId;
  return DEFAULT_BUSINESS_LINE_ID;
}

function outcomeClass(tone: 'ok' | 'warn' | 'danger') {
  return `lblo-outcome lblo-outcome--${tone}`;
}

interface ModuleCardProps {
  module: LineModule;
  active: boolean;
  index: number;
  moduleCount: number;
  lineId: BusinessLineId;
}

function ModuleCard({ module, active, index, moduleCount, lineId }: ModuleCardProps) {
  const Icon = module.icon;
  const sectionId = `${lineId}-${module.id}`;

  return (
    <article
      className={`lblo-module lblo-module--${module.accent}${active ? ' is-active' : ''}`}
      id={sectionId}
      data-annotation-id={`lblo-mod-${module.id}`}
      style={{ '--lblo-index': index } as React.CSSProperties}
    >
      <div className="lblo-module-rail" aria-hidden>
        <span className="lblo-module-rail-dot" />
        {index < moduleCount - 1 && <span className="lblo-module-rail-line" />}
      </div>

      <div className="lblo-module-panel">
        <header className="lblo-module-header">
          <div className="lblo-module-icon-wrap">
            <Icon size={22} aria-hidden />
          </div>
          <div className="lblo-module-titles">
            <span className="lblo-module-step">第 {module.step} 步</span>
            <h2>{module.title}</h2>
            <p className="lblo-module-subtitle">{module.subtitle}</p>
          </div>
        </header>

        <div className="lblo-roles" aria-label="责任部门">
          {module.roles.map((role) => (
            <span key={role} className="lblo-role-tag">{role}</span>
          ))}
        </div>

        <div className="lblo-module-body">
          <section className="lblo-block lblo-block--start" aria-labelledby={`${sectionId}-start`}>
            <h3 className="lblo-block-label" id={`${sectionId}-start`}>
              <span className="lblo-block-icon"><Flag size={15} aria-hidden /></span>
              起点
            </h3>
            <p>{module.start}</p>
          </section>

          <section className="lblo-block lblo-block--process" aria-labelledby={`${sectionId}-process`}>
            <h3 className="lblo-block-label" id={`${sectionId}-process`}>
              <span className="lblo-block-icon"><GitBranch size={15} aria-hidden /></span>
              怎么运作
            </h3>
            <ol className="lblo-process-steps">
              {module.process.map((item, stepIdx) => (
                <li key={item}>
                  <span className="lblo-process-num">{stepIdx + 1}</span>
                  <span>{item}</span>
                </li>
              ))}
            </ol>
            {module.outcomes && (
              <div className="lblo-outcomes" aria-label="关键结果">
                {module.outcomes.map((item) => (
                  <span key={item.label} className={outcomeClass(item.tone)}>{item.label}</span>
                ))}
              </div>
            )}
          </section>

          <section className="lblo-block lblo-block--closure" aria-labelledby={`${sectionId}-closure`}>
            <h3 className="lblo-block-label" id={`${sectionId}-closure`}>
              <span className="lblo-block-icon"><CheckCircle2 size={15} aria-hidden /></span>
              闭环
            </h3>
            <p>{module.closure}</p>
          </section>
        </div>

        {module.prototypeHref ? (
          <footer className="lblo-module-footer">
            <p className="lblo-closure-note">演示时可进入系统查看该模块实际操作界面。</p>
            <a className="lblo-link-btn" href={module.prototypeHref}>
              {module.prototypeLabel}
              <ArrowRight size={16} aria-hidden />
            </a>
          </footer>
        ) : (
          <footer className="lblo-module-footer lblo-module-footer--muted">
            <p className="lblo-closure-note">该模块将随 ONE-OS 后续迭代接入独立操作界面。</p>
          </footer>
        )}
      </div>
    </article>
  );
}

function DataFoundationCard({ pillar }: { pillar: DataFoundationPillar }) {
  const Icon = pillar.icon;

  return (
    <article className={`lblo-data-pillar lblo-data-pillar--${pillar.accent}`}>
      <header className="lblo-data-pillar-header">
        <span className="lblo-data-pillar-icon" aria-hidden>
          <Icon size={22} />
        </span>
        <div>
          <h3>{pillar.title}</h3>
          <p className="lblo-data-pillar-subtitle">{pillar.subtitle}</p>
        </div>
      </header>
      <p className="lblo-data-pillar-summary">{pillar.summary}</p>
      <div className="lblo-data-pillar-block">
        <h4>
          <Target size={14} aria-hidden />
          决策看板关注
        </h4>
        <ul>
          {pillar.indicators.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      </div>
      <div className="lblo-data-pillar-block">
        <h4>
          <BarChart3 size={14} aria-hidden />
          支持管理决策
        </h4>
        <ul>
          {pillar.decisions.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      </div>
      <p className="lblo-data-pillar-sources">{pillar.sources}</p>
      {pillar.prototypeHref && (
        <a className="lblo-data-pillar-link" href={pillar.prototypeHref}>
          {pillar.prototypeLabel}
          <ArrowRight size={16} aria-hidden />
        </a>
      )}
    </article>
  );
}

function DataFoundationSection() {
  return (
    <section className="lblo-data-foundations" id="lblo-data-foundations" data-annotation-id="lblo-data-foundations">
      <header className="lblo-data-foundations-header">
        <h2>{DATA_FOUNDATION_INTRO.title}</h2>
        <p className="lblo-data-foundations-tagline">{DATA_FOUNDATION_INTRO.tagline}</p>
        <p className="lblo-data-foundations-summary">{DATA_FOUNDATION_INTRO.summary}</p>
      </header>
      <div className="lblo-data-pillar-grid">
        {DATA_FOUNDATION_PILLARS.map((pillar) => (
          <DataFoundationCard key={pillar.id} pillar={pillar} />
        ))}
      </div>
    </section>
  );
}

function SystemIntro({
  activeLineId,
  onSelectLine,
}: {
  activeLineId: BusinessLineId;
  onSelectLine: (id: BusinessLineId) => void;
}) {
  return (
    <section className="lblo-system-intro" data-annotation-id="lblo-system-intro">
      <div className="lblo-system-intro-inner">
        <header className="lblo-system-intro-header">
          <p className="lblo-system-intro-eyebrow">
            <Sparkles size={16} aria-hidden />
            {SYSTEM_INTRO.eyebrow}
          </p>
          <h1>{SYSTEM_INTRO.title}</h1>
          <p className="lblo-system-intro-tagline">{SYSTEM_INTRO.tagline}</p>
          <p className="lblo-system-intro-summary">{SYSTEM_INTRO.summary}</p>
        </header>

        {SYSTEM_INTRO.evolution && (
          <EvolutionBanner
            evolution={SYSTEM_INTRO.evolution}
            heading="业财一体演进"
            annotationId="lblo-system-evolution"
          />
        )}

        <div className="lblo-system-hub" aria-hidden>
          <span className="lblo-system-hub-core">
            <Layers size={22} />
            ONE-OS
          </span>
          <span className="lblo-system-hub-ring" />
        </div>

        <div
          className="lblo-line-grid"
          role="tablist"
          aria-label="业务条线选择"
          data-annotation-id="lblo-line-switcher"
        >
          {BUSINESS_LINES.map((item) => {
            const TabIcon = LINE_TAB_ICONS[item.id];
            const accent = LINE_ACCENTS[item.id];
            const isActive = item.id === activeLineId;
            const moduleCount = item.modules.length;

            return (
              <button
                key={item.id}
                type="button"
                role="tab"
                id={`lblo-line-tab-${item.id}`}
                aria-selected={isActive}
                aria-controls="lblo-line-detail"
                className={`lblo-line-card lblo-line-card--${accent}${isActive ? ' is-active' : ''}${item.placeholder ? ' is-placeholder' : ''}`}
                onClick={() => onSelectLine(item.id)}
              >
                <span className="lblo-line-card-icon" aria-hidden>
                  <TabIcon size={20} />
                </span>
                <span className="lblo-line-card-body">
                  <span className="lblo-line-card-title-row">
                    <span className="lblo-line-card-title">{item.label}</span>
                    {item.placeholder && <span className="lblo-line-card-badge">待补充</span>}
                  </span>
                  <span className="lblo-line-card-tagline">{item.hero.tagline}</span>
                </span>
                <span className="lblo-line-card-meta">
                  {moduleCount > 0 ? (
                    <span className="lblo-line-card-stat">{moduleCount} 个模块</span>
                  ) : (
                    <span className="lblo-line-card-stat">筹备中</span>
                  )}
                  <ArrowRight size={16} aria-hidden />
                </span>
              </button>
            );
          })}
        </div>

        <p className="lblo-system-intro-footnote">
          不是点击下方条线卡片，而是点击上方条线卡片，查看该条线的模块说明与闭环路径；下方为管理层决策数据底座。
        </p>

        <DataFoundationSection />
      </div>
    </section>
  );
}

function EvolutionBanner({
  evolution,
  heading = '条线演进路径',
  annotationId = 'lblo-evolution',
}: {
  evolution: NonNullable<BusinessLineConfig['evolution']>;
  heading?: string;
  annotationId?: string;
}) {
  return (
    <div className="lblo-evolution" data-annotation-id={annotationId}>
      <p className="lblo-evolution-heading">{heading}</p>
      <div className="lblo-evolution-track">
        <div className="lblo-evolution-phase">
          <span className="lblo-evolution-label">{evolution.currentLabel}</span>
          <p>{evolution.currentText}</p>
        </div>
        <div className="lblo-evolution-arrow" aria-hidden>
          <ChevronRight size={22} />
        </div>
        <div className="lblo-evolution-phase lblo-evolution-phase--target">
          <span className="lblo-evolution-label">{evolution.targetLabel}</span>
          <p>{evolution.targetText}</p>
        </div>
      </div>
    </div>
  );
}

function PipelineNodeButton({
  module,
  lineId,
  activeId,
  compact = false,
}: {
  module: LineModule;
  lineId: BusinessLineId;
  activeId: string;
  compact?: boolean;
}) {
  const Icon = module.icon;
  const sectionId = `${lineId}-${module.id}`;

  return (
    <button
      type="button"
      className={`lblo-pipeline-node lblo-pipeline-node--${module.accent}${compact ? ' lblo-pipeline-node--compact' : ''}${activeId === sectionId ? ' is-active' : ''}`}
      onClick={() => scrollToSection(sectionId)}
      aria-current={activeId === sectionId ? 'step' : undefined}
    >
      <span className="lblo-pipeline-icon"><Icon size={18} aria-hidden /></span>
      <span className="lblo-pipeline-label">{module.shortLabel}</span>
    </button>
  );
}

function PipelineOverview({
  line,
  activeId,
}: {
  line: BusinessLineConfig;
  activeId: string;
}) {
  const mainModules = line.modules.filter((m) => m.pipelineTrack === 'main');
  const supportModules = line.modules.filter((m) => m.pipelineTrack === 'support');
  const useDualLayout = mainModules.length > 0 && supportModules.length > 0;

  if (useDualLayout) {
    return (
      <div className="lblo-pipeline-dual" aria-label="业务链路总览">
        <div className="lblo-pipeline-section">
          <p className="lblo-pipeline-section-label">生命周期主线</p>
          <div className="lblo-pipeline lblo-pipeline--main">
            {mainModules.map((module, idx) => (
              <React.Fragment key={module.id}>
                <PipelineNodeButton module={module} lineId={line.id} activeId={activeId} />
                {idx < mainModules.length - 1 && (
                  <span className="lblo-pipeline-connector" aria-hidden>
                    <ChevronRight size={14} />
                  </span>
                )}
              </React.Fragment>
            ))}
          </div>
        </div>
        <div className="lblo-pipeline-section">
          <p className="lblo-pipeline-section-label">并行支撑能力</p>
          <p className="lblo-pipeline-section-note">全生命周期内随时可能触发，无固定先后顺序</p>
          <div className="lblo-pipeline-support">
            {supportModules.map((module) => (
              <PipelineNodeButton
                key={module.id}
                module={module}
                lineId={line.id}
                activeId={activeId}
                compact
              />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="lblo-pipeline" aria-label="业务链路总览">
      {line.modules.map((module, idx) => (
        <React.Fragment key={module.id}>
          <PipelineNodeButton module={module} lineId={line.id} activeId={activeId} />
          {idx < line.modules.length - 1 && (
            <span className="lblo-pipeline-connector" aria-hidden>
              <ChevronRight size={14} />
            </span>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

function PlaceholderPanel({ line }: { line: BusinessLineConfig }) {
  const Icon = LINE_TAB_ICONS[line.id];
  return (
    <div className="lblo-placeholder" data-annotation-id={`lblo-placeholder-${line.id}`}>
      <div className="lblo-placeholder-icon">
        <Icon size={32} aria-hidden />
      </div>
      <h2>内容筹备中</h2>
      <p>{line.placeholderHint}</p>
      <p className="lblo-placeholder-note">切换至「租赁业务条线」可查看完整演示内容。</p>
    </div>
  );
}

interface LineContentProps {
  line: BusinessLineConfig;
  presentMode: boolean;
  setPresentMode: React.Dispatch<React.SetStateAction<boolean>>;
}

function LineContent({ line, presentMode, setPresentMode }: LineContentProps) {
  const sectionIds = useMemo(
    () => line.modules.map((m) => `${line.id}-${m.id}`),
    [line.id, line.modules],
  );
  const activeId = useScrollSpy(sectionIds, 72);
  const headerPinned = useScrolledPast(96);
  const {
    stepIndex,
    next,
    prev,
    isFirst,
    isLast,
  } = usePresentationStep(line.modules.length);

  const activeIndex = line.modules.findIndex((m) => `${line.id}-${m.id}` === activeId);
  const progress = line.modules.length
    ? ((activeIndex >= 0 ? activeIndex : 0) + 1) / line.modules.length
    : 0;

  useEffect(() => {
    if (!presentMode || !line.modules.length) return;
    scrollToSection(`${line.id}-${line.modules[stepIndex].id}`);
  }, [presentMode, stepIndex, line.id, line.modules]);

  const hasModules = line.modules.length > 0;

  return (
    <>
      <header
        className={`lblo-topbar lblo-topbar--line${headerPinned ? ' is-pinned' : ''}`}
        data-annotation-id="lblo-nav"
      >
        <div className="lblo-topbar-inner">
          <span className="lblo-topbar-brand">
            <Layers size={18} aria-hidden />
            {line.label}
          </span>
          {hasModules && (
            <div className="lblo-topbar-progress" aria-hidden>
              <span className="lblo-topbar-progress-fill" style={{ width: `${progress * 100}%` }} />
            </div>
          )}
          {hasModules && (
            <button
              type="button"
              className={`lblo-present-toggle${presentMode ? ' is-on' : ''}`}
              onClick={() => setPresentMode((v) => !v)}
              aria-pressed={presentMode}
            >
              {presentMode ? <X size={16} aria-hidden /> : <MonitorPlay size={16} aria-hidden />}
              {presentMode ? '退出演示' : '演示模式'}
            </button>
          )}
        </div>
      </header>

      <section className="lblo-hero" data-annotation-id="lblo-hero">
        <div className="lblo-hero-inner">
          <p className="lblo-eyebrow">
            <Sparkles size={16} aria-hidden />
            ONE-OS · {line.shortLabel}条线
          </p>
          <h1>{line.hero.title}</h1>
          <p className="lblo-tagline">{line.hero.tagline}</p>
          <p className="lblo-summary">{line.hero.summary}</p>

          {line.evolution && <EvolutionBanner evolution={line.evolution} />}

          <div className="lblo-stats">
            {line.hero.stats.map((stat) => (
              <div key={stat.label} className="lblo-stat">
                <span className="lblo-stat-value">{stat.value}</span>
                <span className="lblo-stat-label">{stat.label}</span>
              </div>
            ))}
          </div>

          {hasModules && (
            <PipelineOverview line={line} activeId={activeId} />
          )}
        </div>
      </section>

      {line.placeholder ? (
        <div className="lblo-shell lblo-shell--placeholder">
          <PlaceholderPanel line={line} />
        </div>
      ) : (
        <div className="lblo-shell">
          <aside className="lblo-sidebar" aria-label="模块导航">
            <p className="lblo-sidebar-title">浏览进度</p>
            <nav className="lblo-sidebar-nav">
              {line.modules.map((module) => {
                const Icon = module.icon;
                const sectionId = `${line.id}-${module.id}`;
                const isActive = activeId === sectionId;
                return (
                  <button
                    key={module.id}
                    type="button"
                    className={`lblo-sidebar-link lblo-sidebar-link--${module.accent}${isActive ? ' is-active' : ''}`}
                    onClick={() => scrollToSection(sectionId)}
                    aria-current={isActive ? 'step' : undefined}
                  >
                    <span className="lblo-sidebar-num">{module.step}</span>
                    <span className="lblo-sidebar-text">
                      <Icon size={16} aria-hidden />
                      {module.title}
                    </span>
                  </button>
                );
              })}
            </nav>
          </aside>

          <main id="lblo-main" className="lblo-main">
            {line.modules.map((module, index) => (
              <ModuleCard
                key={module.id}
                module={module}
                active={activeId === `${line.id}-${module.id}`}
                index={index}
                moduleCount={line.modules.length}
                lineId={line.id}
              />
            ))}

            <aside className="lblo-loop-card" data-annotation-id="lblo-full-loop" aria-label="全链路闭环">
              <div className="lblo-loop-icon" aria-hidden>
                <Users size={20} />
                <ArrowRight size={16} />
                <CheckCircle2 size={20} />
              </div>
              <div className="lblo-loop-content">
                <h3>{line.loopTitle}</h3>
                <p>{line.loopSummary} 全链路数据自动串联，减少人工重复录入。</p>
              </div>
              <button
                type="button"
                className="lblo-loop-btn"
                onClick={() => scrollToSection(`${line.id}-${line.modules[0].id}`)}
              >
                回到第一步
              </button>
            </aside>
          </main>
        </div>
      )}

      {hasModules && (
        <nav className="lblo-mobile-nav" aria-label="模块快速跳转">
          {line.modules.map((module) => (
            <button
              key={module.id}
              type="button"
              className={`lblo-mobile-chip${activeId === `${line.id}-${module.id}` ? ' is-active' : ''}`}
              onClick={() => scrollToSection(`${line.id}-${module.id}`)}
              aria-label={module.title}
            >
              {module.step}
            </button>
          ))}
        </nav>
      )}

      {presentMode && hasModules && (
        <div className="lblo-present-bar" role="toolbar" aria-label="演示控制">
          <button type="button" className="lblo-present-btn" disabled={isFirst} onClick={prev}>
            <ChevronLeft size={18} aria-hidden />
            上一模块
          </button>
          <span className="lblo-present-indicator">
            {stepIndex + 1}
            {' / '}
            {line.modules.length}
            {' · '}
            {line.modules[stepIndex].title}
          </span>
          <button
            type="button"
            className="lblo-present-btn lblo-present-btn--primary"
            disabled={isLast}
            onClick={next}
          >
            下一模块
            <ChevronRight size={18} aria-hidden />
          </button>
        </div>
      )}
    </>
  );
}

export default function LeaseBusinessLineOverviewApp() {
  const [lineId, setLineId] = useState<BusinessLineId>(parseLineIdFromHash);
  const [presentMode, setPresentMode] = useState(false);
  const lineDetailRef = useRef<HTMLElement>(null);
  const line = BUSINESS_LINE_MAP[lineId];

  const switchLine = useCallback((id: BusinessLineId) => {
    setLineId(id);
    setPresentMode(false);
    window.history.replaceState(null, '', `#${id}`);
    requestAnimationFrame(() => {
      lineDetailRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  }, []);

  useEffect(() => {
    const onHashChange = () => {
      setLineId(parseLineIdFromHash());
      setPresentMode(false);
    };
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  return (
    <div className={`lblo-page${presentMode ? ' lblo-page--present' : ''}`} data-annotation-id="lblo-page">
      <a className="lblo-skip" href="#lblo-line-detail">跳到条线详情</a>

      <div className="lblo-bg" aria-hidden>
        <span className="lblo-bg-orb lblo-bg-orb--1" />
        <span className="lblo-bg-orb lblo-bg-orb--2" />
        <span className="lblo-bg-grid" />
      </div>

      <SystemIntro activeLineId={lineId} onSelectLine={switchLine} />

      <section
        ref={lineDetailRef}
        id="lblo-line-detail"
        className="lblo-line-detail"
        role="tabpanel"
        aria-labelledby={`lblo-line-tab-${lineId}`}
      >
        <LineContent
          key={lineId}
          line={line}
          presentMode={presentMode}
          setPresentMode={setPresentMode}
        />
      </section>
    </div>
  );
}
