const ASSET_DETAILS = {
  ingestion: {
    stage: '01 / Field signals',
    title: 'Field Data Ingestion Runtime',
    copy: 'Captures heterogeneous operational events from fleet, onboard, edge, planning, maintenance, lab and shift systems while preserving source context and delivery uncertainty.',
    input: 'sensor feeds, dispatch events, shift logs, batch exports, delayed payloads, manual corrections',
    output: 'canonical event envelope, source metadata, validation state, idempotency key, replayable raw event',
    fit: 'reduces integration drag and gives downstream systems a dependable intake layer for mixed operational data',
    link: '#asset-ingestion',
  },
  reference: {
    stage: '02 / Operational identity',
    title: 'Equipment Reference Graph',
    copy: 'Connects machine, operator, shift, location, material and maintenance identities so the same real-world object does not split across disconnected systems.',
    input: 'equipment hierarchy, operator rosters, geo zones, route names, maintenance codes, material codes',
    output: 'stable canonical ids, source-of-record rules, relationship graph, lineage and conflict hints',
    fit: 'removes manual identity reconciliation and makes plan-vs-actual comparisons consistent across the shift',
    link: '#asset-reference',
  },
  chrono: {
    stage: '03 / Temporal truth',
    title: 'ChronoState',
    copy: 'Reconstructs equipment and process state over time, including late telemetry, backfills, changing confidence and bounded recomputation.',
    input: 'normalized events, event time, ingestion time, corrections, state transitions, quality flags',
    output: 'latest states, historical intervals, point-in-time views, freshness signals, recomputation windows',
    fit: 'helps supervisors trust the current state and audit how that state changed after late or corrected data arrived',
    link: '#asset-chronostate',
  },
  patterns: {
    stage: '04 / Durable work',
    title: 'PatternWorks',
    copy: 'Runs operational workflows that span retries, human handoffs, external calls and long-running checks without depending on a single request cycle.',
    input: 'workflow request, read-model delta, exception event, maintenance signal, safety escalation',
    output: 'durable run, progress log, retry lifecycle, outbox delivery, exception queue, audit trail',
    fit: 'keeps reconciliation, triage, maintenance review and shift handover work moving even when systems or networks degrade',
    link: '#asset-patternworks',
  },
  readmodels: {
    stage: '05 / Operational projections',
    title: 'Operational Read Models',
    copy: 'Materializes the views that teams need during a shift: fleet state, plan-vs-actual, queues, delays, material movement, risk and reporting context.',
    input: 'state intervals, quality flags, workflow outputs, exception events, target model snapshots',
    output: 'fleet status view, compliance view, delay queue, material balance, risk list, management table',
    fit: 'turns trusted events into fast, role-specific operating information instead of forcing teams to query raw histories',
    link: '#asset-readmodels',
  },
  liveui: {
    stage: '06 / Human operating surface',
    title: 'LiveUI',
    copy: 'Builds contextual cockpit surfaces for dispatchers, supervisors, maintenance teams and operators from the same operational state and workflow progress.',
    input: 'user role, location, active exception, read model state, workflow progress, confirmation need',
    output: 'dynamic cockpit, action card, review surface, escalation form, operator instruction, handover view',
    fit: 'moves insight into the working moment so people can confirm, explain and act without hunting across screens',
    link: '#asset-liveui',
  },
};

const ASSET_LAYERS = [
  {
    id: 'ingestion',
    index: '01 / Field signals',
    name: 'Field Data Ingestion Runtime',
    desc: 'Captures raw telemetry, events and operational updates from mixed mine sources.',
    tags: ['intake', 'quality', 'replay'],
  },
  {
    id: 'reference',
    index: '02 / Operational identity',
    name: 'Equipment Reference Graph',
    desc: 'Keeps equipment, people, areas, materials and shift entities consistent across systems.',
    tags: ['identity', 'lineage', 'context'],
  },
  {
    id: 'chrono',
    index: '03 / Temporal truth',
    name: 'ChronoState',
    desc: 'Repairs time-based state under late, duplicated, missing and corrected operational events.',
    tags: ['intervals', 'freshness', 'recompute'],
  },
  {
    id: 'patterns',
    index: '04 / Durable work',
    name: 'PatternWorks',
    desc: 'Runs shift routines, exception handling and action delivery through resilient workflows.',
    tags: ['workflows', 'retries', 'outbox'],
  },
  {
    id: 'readmodels',
    index: '05 / Operational projections',
    name: 'Operational Read Models',
    desc: 'Turns state and workflow outputs into fast plan-vs-actual, fleet, material and risk views.',
    tags: ['views', 'KPIs', 'handover'],
  },
  {
    id: 'liveui',
    index: '06 / Human operating surface',
    name: 'LiveUI',
    desc: 'Presents the right cockpit, action card or review surface for the current role and context.',
    tags: ['cockpit', 'actions', 'roles'],
  },
];

const ASSET_CARDS = [
  {
    id: 'asset-ingestion',
    panel: 'Data intake',
    title: 'Field Data Ingestion Runtime',
    copy: 'A reusable intake layer for heterogeneous mine events: telemetry, shift logs, planning exports, maintenance updates, lab data and operational corrections.',
    facts: [
      'Normalizes raw event shape without hiding source quality or delivery gaps.',
      'Supports replay, idempotency and validation so downstream state can be rebuilt with confidence.',
    ],
  },
  {
    id: 'asset-reference',
    panel: 'Canonical operations model',
    title: 'Equipment Reference Graph',
    copy: 'A graph of equipment, crews, zones, routes, materials, shifts and maintenance context that gives the operating loop stable identities.',
    facts: [
      'Aligns the same equipment or location when different systems use different codes.',
      'Creates a practical foundation for lineage, audit, role access and cross-system comparison.',
    ],
  },
  {
    id: 'asset-chronostate',
    panel: 'Temporal state',
    title: 'ChronoState',
    copy: 'A temporal processing package for operational telemetry: latest state, historical intervals, quality signals, recomputation windows and processing reports.',
    facts: [
      'Explains current state when connectivity gaps, late payloads or corrected events change the truth.',
      'Works as the reliable state layer for fleet, plant, material movement and safety context.',
    ],
  },
  {
    id: 'asset-patternworks',
    panel: 'Operational workflow runtime',
    title: 'PatternWorks',
    copy: 'A self-hosted workflow runtime for durable runs, progress tracking, retries, recovery, serial keys, fan-out batches, outbox delivery and worker runners.',
    facts: [
      'Fits reconciliation, delay triage, maintenance review, safety follow-up and shift handover routines.',
      'Keeps work auditable when execution crosses systems, people and unstable network windows.',
    ],
  },
  {
    id: 'asset-readmodels',
    panel: 'Fast operating views',
    title: 'Operational Read Models',
    copy: 'Projection patterns for the views that operations teams repeatedly need: plan-vs-actual, fleet status, material flow, delay clusters, risk queues and reports.',
    facts: [
      'Gives supervisors and managers fast operational information without querying raw histories.',
      'Keeps dashboards explainable because each view is backed by lineage, quality flags and workflow state.',
    ],
  },
  {
    id: 'asset-liveui',
    panel: 'Role-specific surfaces',
    title: 'LiveUI',
    copy: 'A cockpit layer that turns operational state and workflow progress into the surface a role needs right now: warning, review, form, action card or handover view.',
    facts: [
      'Helps dispatchers, supervisors, maintenance teams and operators work from the same trusted context.',
      'Reduces screen hunting by placing explanation, confirmation and next action in one surface.',
    ],
  },
];

function AssetMapSection() {
  const [activeAsset, setActiveAsset] = useState('ingestion');
  const detail = ASSET_DETAILS[activeAsset] || ASSET_DETAILS.ingestion;

  return (
    <section className="pa-page section" id="map" aria-labelledby="map-title">
      <SectionHeader
        eyebrow="Operations map"
        titleId="map-title"
        title="Prophecta strengthens the mining loop from field signal to action surface."
        kicker="Select a layer to see what it receives, what it produces and how it improves the operating routine."
      />

      <div className="map-shell">
        <div className="pa-card map-board">
          <div className="asset-lanes" aria-label="Prophecta operational layers">
            {ASSET_LAYERS.map((asset) => {
              const isActive = activeAsset === asset.id;
              return (
                <button
                  className={isActive ? 'asset-node active' : 'asset-node'}
                  type="button"
                  data-asset={asset.id}
                  aria-pressed={isActive}
                  aria-controls="detail-panel"
                  key={asset.id}
                  onClick={() => setActiveAsset(asset.id)}
                >
                  <span className="node-top">
                    <span className="node-index">{asset.index}</span>
                    <span className="node-name">{asset.name}</span>
                    <span className="node-desc">{asset.desc}</span>
                  </span>
                  <span className="node-tags">
                    {asset.tags.map((tag) => <span className="tag" key={tag}>{tag}</span>)}
                  </span>
                </button>
              );
            })}
          </div>
        </div>

        <aside className="pa-card detail-panel" id="detail-panel" aria-live="polite" aria-busy="false">
          <div>
            <span className="pa-panel-title" id="detailStage">{detail.stage}</span>
            <h3 className="detail-title" id="detailTitle">{detail.title}</h3>
            <p className="detail-copy" id="detailCopy">{detail.copy}</p>
          </div>
          <div className="detail-matrix">
            <div className="detail-row">
              <span className="detail-label">Input</span>
              <span id="detailInput">{detail.input}</span>
            </div>
            <div className="detail-row">
              <span className="detail-label">Output</span>
              <span id="detailOutput">{detail.output}</span>
            </div>
            <div className="detail-row">
              <span className="detail-label">Improves</span>
              <span id="detailFit">{detail.fit}</span>
            </div>
          </div>
          <a className="pa-button pa-button-primary" id="detailLink" href={detail.link}>Review this asset</a>
        </aside>
      </div>
    </section>
  );
}

function AssetCardsSection() {
  return (
    <section className="pa-page section" id="assets" aria-labelledby="assets-title">
      <SectionHeader
        eyebrow="Prophecta assets"
        titleId="assets-title"
        title="Each asset improves a specific part of mining operations modernization."
        kicker="Together they create a practical operating layer: ingest the field, align identities, repair time, run durable work, project trusted views and surface action."
      />

      <div className="asset-grid">
        {ASSET_CARDS.map((asset) => (
          <article className="pa-card asset-card" id={asset.id} key={asset.id}>
            <header>
              <Chip>{asset.panel}</Chip>
            </header>
            <h3>{asset.title}</h3>
            <p>{asset.copy}</p>
            <ul className="fact-list">
              {asset.facts.map((fact) => <li key={fact}>{fact}</li>)}
            </ul>
          </article>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { AssetMapSection, AssetCardsSection });