<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&display=swap');
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--ny:#15507b;--nd:#0e3a5a;--nl:#1d6a9f;--red:#ef4136;--amb:#fbb040;--tl:#0f8b6e;--w:#fff;--g50:#f8f9fa;--g100:#e9ecef;--g200:#dee2e6;--g400:#adb5bd;--g600:#6c757d;--g800:#343a40;--rad:10px}
html{scroll-behavior:smooth}
body{font-family:'DM Sans',sans-serif;background:var(--g50);color:var(--g800);min-height:100vh}
.container{max-width:840px;margin:0 auto;padding:20px}
/* Header */
.header{background:linear-gradient(160deg,var(--nd),var(--nl));padding:28px 32px;border-radius:var(--rad) var(--rad) 0 0;color:#fff;text-align:center}
.header h1{font-size:1.6em;margin-bottom:4px;letter-spacing:-.02em}
.header p{opacity:.75;font-size:.88em}
/* Progress */
.progress-bar{display:flex;background:var(--w);border-bottom:1px solid var(--g200);padding:12px 20px;gap:4px;overflow-x:auto}
.prog-step{flex:1;text-align:center;padding:8px 4px;border-radius:6px;font-size:.7em;font-weight:500;color:var(--g400);cursor:pointer;transition:all .2s;white-space:nowrap;min-width:70px}
.prog-step.active{background:var(--ny);color:#fff}
.prog-step.done{background:#d1fae5;color:#065f46}
.prog-step:hover{opacity:.8}
/* Card */
.card{background:var(--w);border-radius:0 0 var(--rad) var(--rad);padding:28px 32px;box-shadow:0 2px 12px rgba(0,0,0,.06)}
.step{display:none}.step.active{display:block}
h2{font-size:1.3em;color:var(--ny);margin-bottom:.4em;letter-spacing:-.01em}
p.desc{font-size:.88em;color:var(--g600);margin-bottom:1.2em;line-height:1.5}
/* Form inputs */
.form-group{margin-bottom:16px}
.form-group label{display:block;font-weight:600;font-size:.85em;margin-bottom:5px;color:var(--ny)}
.form-group input,.form-group select{width:100%;padding:10px 14px;border:1px solid var(--g200);border-radius:7px;font-family:inherit;font-size:.9em;transition:border .2s}
.form-group input:focus,.form-group select:focus{outline:none;border-color:var(--nl);box-shadow:0 0 0 3px rgba(29,106,159,.12)}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
/* Questions */
.level-group{margin-bottom:20px}
.level-label{font-size:.75em;font-weight:700;text-transform:uppercase;letter-spacing:.06em;padding:5px 12px;border-radius:5px;display:inline-block;margin-bottom:10px;color:#fff}
.ll-1{background:#94a3b8}.ll-2{background:#64748b}.ll-3{background:var(--nl)}.ll-4{background:var(--ny)}.ll-5{background:var(--nd)}
.question{display:flex;align-items:flex-start;gap:12px;padding:12px 14px;border-radius:8px;margin-bottom:6px;background:var(--g50);border:1px solid var(--g200);transition:all .2s}
.question:hover{border-color:var(--nl)}
.question.answered-yes{background:#f0fdf4;border-color:#86efac}
.question.answered-no{background:#fff;border-color:var(--g200)}
.q-text{flex:1;font-size:.84em;line-height:1.45}
.q-tag{font-size:.65em;font-weight:600;padding:2px 7px;border-radius:8px;white-space:nowrap;margin-top:2px}
.q-tag-it{background:#dbeafe;color:#1e40af}.q-tag-ot{background:#fef3c7;color:#92400e}.q-tag-conv{background:#d1fae5;color:#065f46}
.toggle-group{display:flex;gap:0;flex-shrink:0}
.toggle-btn{padding:6px 14px;border:1px solid var(--g200);background:var(--w);font-family:inherit;font-size:.78em;font-weight:600;cursor:pointer;transition:all .15s}
.toggle-btn:first-child{border-radius:6px 0 0 6px}.toggle-btn:last-child{border-radius:0 6px 6px 0}
.toggle-btn.sel-yes{background:var(--tl);color:#fff;border-color:var(--tl)}
.toggle-btn.sel-no{background:var(--g400);color:#fff;border-color:var(--g400)}
/* Buttons */
.btn-row{display:flex;justify-content:space-between;margin-top:24px;gap:12px}
.btn{padding:11px 28px;border:none;border-radius:8px;font-family:inherit;font-size:.9em;font-weight:600;cursor:pointer;transition:all .2s}
.btn-primary{background:var(--ny);color:#fff}.btn-primary:hover{background:var(--nd)}
.btn-secondary{background:var(--g100);color:var(--g800)}.btn-secondary:hover{background:var(--g200)}
.btn-submit{background:linear-gradient(135deg,var(--red),var(--amb));color:#fff;font-size:1em;padding:14px 36px}
.btn-submit:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(239,65,54,.3)}
.btn:disabled{opacity:.4;cursor:not-allowed;transform:none!important;box-shadow:none!important}
/* Results */
.results-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:16px}
.result-card{background:var(--g50);border-radius:var(--rad);padding:18px;border:1px solid var(--g200)}
.result-card h3{font-size:.95em;color:var(--ny);margin-bottom:10px}
.score-big{font-size:3em;font-weight:700;color:var(--ny);text-align:center;margin:12px 0}
.score-label{text-align:center;font-size:.82em;color:var(--g600)}
.dim-score{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--g200);font-size:.85em}
.dim-score:last-child{border:none}
.dim-score .val{font-weight:700;color:var(--ny);font-size:1.1em}
.dim-bar{flex:1;margin:0 12px;height:6px;background:var(--g200);border-radius:3px;overflow:hidden}
.dim-bar-fill{height:100%;border-radius:3px;transition:width .6s}
/* Spider */
.spider-wrap{display:flex;justify-content:center;margin:8px 0}
/* Status messages */
.status{text-align:center;padding:16px;border-radius:8px;margin-top:16px;font-size:.88em;display:none}
.status.success{display:block;background:#d1fae5;color:#065f46}
.status.error{display:block;background:#fee2e2;color:#991b1b}
.status.loading{display:block;background:#dbeafe;color:#1e40af}
/* Privacy */
.privacy{font-size:.72em;color:var(--g400);text-align:center;margin-top:16px;line-height:1.5}
.privacy a{color:var(--nl)}
/* Responsive */
@media(max-width:600px){.container{padding:10px}.card{padding:18px 16px}.form-row{grid-template-columns:1fr}.results-grid{grid-template-columns:1fr}.progress-bar{padding:8px 10px}.header{padding:20px 16px}}
</style>

<body>
<div class="container">
  <div class="header">
    <div style="margin-bottom:8px">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="60 70 3030 1190" style="height:44px;width:auto;" shape-rendering="geometricPrecision"><defs><linearGradient id="lg"><stop stop-color="#ef4136" offset="0"/><stop stop-color="#fbb040" offset="1"/></linearGradient></defs><g transform="scale(7.389) translate(10,10)"><g transform="matrix(1.368,0,0,1.368,-18.615,12.007)" fill="url(#lg)"><path d="M80.11,49.695c.003,5.951,1.481,10.771,3.303,10.771 1.823,0,3.302-4.824,3.305-10.768-.003-5.951-1.479-10.773-3.303-10.773C81.591,38.926,80.107,43.748,80.11,49.695z"/><path d="M39.138,14.154c-15.075,6.26-25.529,19.93-25.529,35.779-.004,15.852,10.454,29.52,25.536,35.777C30.504,78.232,24.764,65,24.764,49.934S30.508,21.637,39.138,14.154z"/><path d="M49.349,10.23c-7.066,0-12.803,17.854-12.803,39.857 0,22.016,5.736,39.859,12.808,39.861 3.491-.002,6.66-4.367,8.969-11.438 1.954,4.756,4.414,7.598,7.084,7.598 6.367.002,11.532-16.066,11.527-35.883.005-19.816-5.156-35.887-11.521-35.879-2.651,0-5.093,2.797-7.041,7.484C56.057,14.668,52.871,10.234,49.349,10.23z M75.225,50.227c.005,11.121-2.764,20.143-6.174,20.143-3.412,0-6.176-9.023-6.176-20.139 0-11.127,2.764-20.146,6.176-20.15C72.465,30.084,75.229,39.102,75.225,50.227z M57.792,23.318c-2.395,6.576-3.907,16.191-3.907,26.908-.001,10.623,1.484,20.166,3.841,26.736-1.15,1.559-2.418,2.424-3.748,2.424-5.202-.004-9.414-13.117-9.414-29.299 0-16.174,4.212-29.293,9.407-29.293C55.333,20.797,56.626,21.701,57.792,23.318z"/></g><g transform="matrix(1.535,0,0,1.535,134.93,22.314)" fill="#fff"><path d="M2 12.04l4.64 0 0 28-4.64 0 0-28z M10.6 40l0-28 4.64 0 0 28-4.64 0z M37.76 12l4.64 0 0 28-5.8 0-17.72-19.04 0-6.12 18.88 20.12 0-22.96z M72.4 16.08c2.48 2.64 3.76 5.92 3.76 9.88s-1.28 7.24-3.8 9.88c-2.84 3.04-6.56 4.52-11.08 4.52-4.48 0-8.24-1.52-11.12-4.56-2.48-2.68-3.76-5.96-3.76-9.84 0-3.92 1.28-7.2 3.76-9.84 2.88-3.04 6.64-4.6 11.12-4.6 4.56 0 8.28 1.56 11.12 4.56z M68.68 33.4c1.96-1.84 2.92-4.32 2.92-7.44s-.96-5.6-2.92-7.44c-1.88-1.88-4.4-2.8-7.4-2.8-3.24 0-5.8 1.08-7.76 3.24-1.72 1.88-2.6 4.2-2.6 7 0 3 1 5.48 2.96 7.4 1.88 1.88 4.4 2.84 7.4 2.84 3.04 0 5.56-.92 7.4-2.8z M80.16 12l5.16 0 9.84 18.32-2.56 4.76z M116.76 12l-15.08 28-5.12 0 15.08-28 5.12 0z M120.76 12.04l4.64 0 0 28-4.64 0 0-28z M129.36 40l5.52-10.48 19.4.04-7.16-13.56-5.28 9.92-5.04 0 7.4-13.92 5.8 0 14.84 28-5.08 0-3.24-6.28-18.84 0-3.24 6.28-5.08 0z"/></g><g transform="matrix(1.094,0,0,1.094,136.906,97.762)" fill="#fff"><path d="M9.58 18c2.34 0 4.18-.74 5.52-2.18l1.88 1.04c-.94 1.1-2.02 1.9-3.22 2.4s-2.64.74-4.3.74c-2.34 0-4.28-.58-5.82-1.76-1.76-1.34-2.64-3.08-2.64-5.24 0-2.14.88-3.88 2.68-5.22 1.56-1.18 3.48-1.78 5.78-1.78 3.32 0 5.84 1.14 7.62 3.44l-2 .7c-1.34-1.42-3.2-2.14-5.62-2.14-1.82 0-3.32.48-4.46 1.42-1.16.94-1.72 2.12-1.72 3.58 0 1.48.56 2.7 1.7 3.62s2.68 1.38 4.6 1.38z M35 8.04c1.24 1.32 1.88 2.96 1.88 4.94s-.64 3.62-1.9 4.94c-1.42 1.52-3.28 2.26-5.54 2.26-2.24 0-4.12-.76-5.56-2.28-1.24-1.34-1.88-2.98-1.88-4.92 0-1.96.64-3.6 1.88-4.92 1.44-1.52 3.32-2.3 5.56-2.3 2.28 0 4.14.78 5.56 2.28z"/></g></g></svg>
    </div>
    <h1>IDAIRA</h1>
    <p>Industrial AI Readiness Assessment — Self-Assessment Tool</p>
  </div>
  <div class="progress-bar" id="progress"></div>
  <div class="card">
    <!-- Steps are generated by JavaScript -->
    <div id="steps"></div>
  </div>
  <p class="privacy">Your data is processed in accordance with GDPR. The assessment results are sent exclusively to INOVIA Consulting for the purpose of providing you with a personalized readiness evaluation. <a href="https://inovia-consulting.com/privacy-policy/" target="_blank">Privacy Policy</a></p>
</div>

<script>
// ═══════ MATURITY DATA ═══════
const MATURITY_DATA = {"People":[{"level":1,"name":"Basic IT skills exist","question":"Do IT staff have foundational technical skills (programming, database, systems administration), even if not AI-specific?","itot":"IT"},{"level":1,"name":"Basic OT skills exist","question":"Do OT/automation staff have foundational technical skills (PLC programming, instrumentation, process control), even if not AI-specific?","itot":"OT"},{"level":1,"name":"Interest in AI exists","question":"Are there individuals in the organization who have self-initiated AI learning or expressed interest in AI adoption?","itot":"\u2014"},{"level":1,"name":"Basic digital literacy","question":"Do employees across the assessed business functions have basic digital literacy (using software tools, working with data)?","itot":"\u2014"},{"level":2,"name":"AI training program (IT)","question":"Does a structured AI/ML training program exist for IT staff (data analysts, developers, architects)?","itot":"IT"},{"level":2,"name":"AI training program (OT)","question":"Does a structured AI training program exist for OT staff (automation engineers, process engineers, maintenance)?","itot":"OT"},{"level":2,"name":"Dedicated AI/data roles (IT)","question":"Have dedicated AI/data science roles been created within the IT organization (e.g., data scientist, ML engineer)?","itot":"IT"},{"level":2,"name":"AI literacy for leadership","question":"Have managers and leaders in the assessed business functions completed AI literacy training?","itot":"\u2014"},{"level":2,"name":"AI skills inventory","question":"Has the organization conducted a baseline inventory of AI-relevant skills across the assessed business functions?","itot":"\u2014"},{"level":3,"name":"Enterprise AI competency framework","question":"Is there an enterprise-wide AI competency framework defining required AI skills by role (IT and OT)?","itot":"\u2014"},{"level":3,"name":"AI Center of Excellence","question":"Does a central AI team, CoE, or equivalent coordination function exist that serves multiple business functions?","itot":"\u2014"},{"level":3,"name":"Cross-functional AI skill development","question":"Are AI skills development programs designed to include both IT and OT personnel working together?","itot":"\u2014"},{"level":3,"name":"AI career paths defined","question":"Are career development paths defined for AI-related roles (data engineer, ML engineer, AI product manager)?","itot":"\u2014"},{"level":3,"name":"Change management for AI","question":"Is there a structured change management approach for AI adoption that addresses workforce concerns and reskilling?","itot":"\u2014"},{"level":4,"name":"AI skills measured with KPIs","question":"Are AI competency levels measured quantitatively across the organization with defined KPIs and tracked over time?","itot":"Converged"},{"level":4,"name":"Converged IT/OT AI workforce planning","question":"Does workforce planning for AI roles treat IT and OT as a single, integrated talent pool?","itot":"Converged"},{"level":4,"name":"AI talent retention program","question":"Is there a dedicated program to retain AI talent (competitive compensation, challenging projects, continuous learning)?","itot":"\u2014"},{"level":4,"name":"External AI ecosystem engagement","question":"Do AI professionals actively participate in external AI communities, research partnerships, or industry working groups?","itot":"\u2014"},{"level":5,"name":"AI innovation culture","question":"Is experimentation with AI encouraged across the organization with dedicated time, resources, and tolerance for failure?","itot":"\u2014"},{"level":5,"name":"AI thought leadership","question":"Does the organization contribute to industry AI standards, publish research, or present at leading conferences?","itot":"\u2014"},{"level":5,"name":"Continuous AI skills adaptation","question":"Does the AI competency framework automatically adapt to emerging AI technologies and methods (e.g., GenAI, AI agents)?","itot":"\u2014"}],"Process":[{"level":1,"name":"Core business processes exist","question":"Are core business processes in the assessed functions documented or at least understood by the people executing them?","itot":"\u2014"},{"level":1,"name":"Data-informed decisions occur","question":"Do decision-makers in the assessed business functions use data (reports, dashboards, spreadsheets) to inform decisions, even if manually?","itot":"\u2014"},{"level":1,"name":"Improvement initiatives exist","question":"Are there ongoing process improvement initiatives (lean, Six Sigma, continuous improvement) in at least some business functions?","itot":"\u2014"},{"level":2,"name":"AI use case identification (IT)","question":"Is there a documented process for identifying AI use cases in IT-supported business processes (ERP, CRM, SCM)?","itot":"IT"},{"level":2,"name":"AI use case identification (OT)","question":"Is there a documented process for identifying AI use cases in OT/manufacturing processes (predictive maintenance, quality, optimization)?","itot":"OT"},{"level":2,"name":"AI project methodology","question":"Is a defined methodology used for AI/ML projects (e.g., CRISP-DM, adapted Agile) at the business function level?","itot":"\u2014"},{"level":2,"name":"AI model validation process","question":"Is there a defined process for validating AI model outputs before deployment in the assessed business functions?","itot":"\u2014"},{"level":2,"name":"Process documentation for AI","question":"Are business processes that are candidates for AI augmentation documented at a level sufficient for AI requirements analysis?","itot":"\u2014"},{"level":3,"name":"Enterprise AI process framework","question":"Is there an enterprise-wide, standardized process for AI initiative lifecycle management (ideation \u2192 deployment \u2192 monitoring)?","itot":"\u2014"},{"level":3,"name":"AI-augmented process design","question":"Are business processes redesigned to incorporate AI capabilities (not just retrofitted), following a standard approach?","itot":"\u2014"},{"level":3,"name":"MLOps process defined","question":"Is there a defined MLOps process for model deployment, versioning, monitoring, and retraining across the enterprise?","itot":"\u2014"},{"level":3,"name":"AI benefit realization process","question":"Is there a standard process for measuring and reporting the business value delivered by AI initiatives against defined objectives?","itot":"\u2014"},{"level":3,"name":"Supply chain AI process integration","question":"Are AI-augmented supply chain processes mapped to SCOR process categories with defined performance attributes?","itot":"\u2014"},{"level":4,"name":"AI process performance measured","question":"Are AI-augmented processes measured quantitatively with defined KPIs and compared against baselines?","itot":"Converged"},{"level":4,"name":"Converged IT/OT AI process management","question":"Are AI processes managed as a single integrated workflow across IT and OT domains (no separate governance)?","itot":"Converged"},{"level":4,"name":"Continuous model monitoring","question":"Is there an automated process for continuous monitoring of AI model performance, data drift, and concept drift in production?","itot":"\u2014"},{"level":4,"name":"AI process benchmarking","question":"Are AI-augmented process outcomes benchmarked against industry peers or standards?","itot":"\u2014"},{"level":5,"name":"AI-driven process optimization","question":"Do AI systems autonomously identify and recommend process improvements based on real-time performance data?","itot":"\u2014"},{"level":5,"name":"Self-improving AI pipelines","question":"Do AI/ML pipelines automatically adapt (retrain, reconfigure) based on detected performance degradation without manual intervention?","itot":"\u2014"},{"level":5,"name":"Cross-enterprise AI process innovation","question":"Does the organization systematically explore AI-driven process innovations that extend beyond enterprise boundaries (e.g., collaborative AI across the supply chain)?","itot":"\u2014"}],"Data":[{"level":1,"name":"IT business data exists","question":"Does structured business data exist in IT systems (ERP, CRM, SCM, PLM), even if not formally governed?","itot":"IT"},{"level":1,"name":"OT operational data exists","question":"Does operational data exist in OT systems (historians, SCADA logs, sensor databases), even if not formally governed?","itot":"OT"},{"level":1,"name":"Reporting capability exists","question":"Can the organization generate reports from its existing data systems, even if manually or with significant effort?","itot":"\u2014"},{"level":1,"name":"Basic data storage infrastructure","question":"Does basic data storage infrastructure exist (databases, file servers, historians), even if fragmented across systems?","itot":"\u2014"},{"level":2,"name":"Data ownership defined (IT)","question":"Are data owners formally assigned for key IT data domains (customer, product, financial, supplier)?","itot":"IT"},{"level":2,"name":"Data ownership defined (OT)","question":"Are data owners formally assigned for key OT data domains (process data, equipment data, quality data, energy data)?","itot":"OT"},{"level":2,"name":"Data quality checks (IT)","question":"Are periodic data quality checks performed on key IT data domains?","itot":"IT"},{"level":2,"name":"Data quality checks (OT)","question":"Are periodic data quality checks performed on key OT data domains (sensor calibration, historian completeness)?","itot":"OT"},{"level":2,"name":"Data dictionary exists","question":"Does a data dictionary or data catalog exist for at least the key data domains used in the assessed business functions?","itot":"\u2014"},{"level":3,"name":"Enterprise data governance","question":"Is there an enterprise-wide data governance framework with a data governance board, policies, and decision rights?","itot":"\u2014"},{"level":3,"name":"IT/OT data integration architecture","question":"Is there a defined architecture for integrating IT and OT data (e.g., through a data lake, integration platform, or unified data model)?","itot":"\u2014"},{"level":3,"name":"Master data management","question":"Is master data management (MDM) implemented for key shared data entities (product, material, customer, asset)?","itot":"\u2014"},{"level":3,"name":"Data lifecycle management","question":"Are data lifecycle policies defined and enforced (creation, storage, retention, archival, deletion)?","itot":"\u2014"},{"level":3,"name":"AI training data management","question":"Is there a defined process for curating, labeling, versioning, and governing data used for AI model training?","itot":"\u2014"},{"level":4,"name":"Data quality measured with KPIs","question":"Is data quality measured continuously with defined KPIs across both IT and OT domains as a converged practice?","itot":"Converged"},{"level":4,"name":"Real-time data pipelines","question":"Do real-time or near-real-time data pipelines exist between OT systems and enterprise analytics/AI platforms?","itot":"Converged"},{"level":4,"name":"Data lineage tracking","question":"Is data lineage tracked end-to-end for AI-relevant data flows, from source systems through transformation to model input?","itot":"\u2014"},{"level":4,"name":"Data sharing readiness","question":"Is the organization capable of sharing data externally through standardized interfaces (e.g., Data Space connectors, APIs)?","itot":"\u2014"},{"level":5,"name":"Predictive data quality management","question":"Does the organization use AI to predict and preemptively address data quality issues before they impact downstream processes?","itot":"\u2014"},{"level":5,"name":"Self-healing data pipelines","question":"Do data integration pipelines automatically detect and correct failures, adapt to schema changes, and self-optimize?","itot":"\u2014"},{"level":5,"name":"Data as a strategic asset","question":"Is data explicitly managed as a strategic asset with quantified business value and treated as an input to competitive strategy?","itot":"\u2014"}],"Digital Landscape":[{"level":1,"name":"Enterprise systems exist","question":"Are core enterprise systems (ERP, PLM, CRM, or equivalent) deployed and operational, even if on older versions?","itot":"IT"},{"level":1,"name":"OT automation systems exist","question":"Are OT automation systems (PLCs, SCADA/DCS, MES, or equivalent) deployed and operational in production?","itot":"OT"},{"level":1,"name":"Basic computing infrastructure","question":"Does computing infrastructure exist (on-premise servers, workstations), even if no cloud or edge capabilities?","itot":"\u2014"},{"level":1,"name":"Basic network connectivity","question":"Does basic network infrastructure exist in both office and production environments, even if IT and OT networks are fully separated?","itot":"\u2014"},{"level":2,"name":"Modern enterprise systems (IT)","question":"Are core enterprise systems (ERP, PLM, CRM) on current versions with API/integration capabilities?","itot":"IT"},{"level":2,"name":"Connected OT systems","question":"Are key OT systems (MES, SCADA, historians) connected to the enterprise network with defined data interfaces?","itot":"OT"},{"level":2,"name":"OPC UA deployed in production","question":"Is OPC UA deployed on production lines for standardized machine-level data access?","itot":"OT"},{"level":2,"name":"Basic AI/ML platform","question":"Is a basic AI/ML platform or toolset available for data scientists (cloud or on-premise)?","itot":"\u2014"},{"level":2,"name":"Network segmentation (IT/OT DMZ)","question":"Is network segmentation in place between IT and OT networks with a defined DMZ per IEC 62443 zones and conduits?","itot":"\u2014"},{"level":3,"name":"Integration platform","question":"Is an enterprise integration platform (iPaaS, ESB, or industrial IoT platform) deployed to connect IT and OT systems?","itot":"\u2014"},{"level":3,"name":"Edge computing infrastructure","question":"Is edge computing infrastructure deployed at plant/production level for real-time data processing and local AI inference?","itot":"\u2014"},{"level":3,"name":"Digital Twin platform","question":"Is a Digital Twin platform deployed or piloted for at least one use case (asset, process, or product twin)?","itot":"\u2014"},{"level":3,"name":"Standardized sensor/data architecture","question":"Is there a standardized approach to sensor deployment, fieldbus protocols, and data acquisition across production environments?","itot":"\u2014"},{"level":3,"name":"AI/ML engineering platform","question":"Is an enterprise AI/ML platform deployed with capabilities for model development, training, deployment, and monitoring (MLOps)?","itot":"\u2014"},{"level":4,"name":"Converged IT/OT architecture","question":"Is there a unified, managed IT/OT architecture with standardized integration patterns, governed by a single architecture function?","itot":"Converged"},{"level":4,"name":"Real-time data streaming","question":"Is real-time data streaming from OT to enterprise analytics/AI platforms operational across multiple production sites?","itot":"Converged"},{"level":4,"name":"Data Space connector deployed","question":"Is an Eclipse Dataspace Connector (EDC) or equivalent deployed for sovereign data exchange with external partners?","itot":"\u2014"},{"level":4,"name":"AI at the edge in production","question":"Are AI/ML models deployed and running at the edge in production environments (inference on edge devices)?","itot":"\u2014"},{"level":5,"name":"Adaptive architecture","question":"Does the digital architecture automatically adapt to changing workloads, new data sources, or new AI model deployments?","itot":"\u2014"},{"level":5,"name":"Full RAMI 4.0 coverage","question":"Is the organization operating across all RAMI 4.0 hierarchy levels (Product through Connected World) with AI-enabled capabilities at each level?","itot":"\u2014"},{"level":5,"name":"Autonomous OT operations","question":"Are there production processes that operate autonomously with AI-driven decision-making and human oversight?","itot":"\u2014"}],"Responsible AI":[{"level":1,"name":"General compliance awareness","question":"Is the organization aware of regulatory requirements relevant to its industry (e.g., product safety, data protection), even if not AI-specific?","itot":"\u2014"},{"level":1,"name":"Basic IT security exists","question":"Are basic IT security measures in place (firewalls, access controls, antivirus), even if not specifically addressing AI threats?","itot":"\u2014"},{"level":1,"name":"Safety culture exists","question":"Does the organization have an existing safety culture and safety management practices (e.g., occupational safety, product safety), even if not covering AI?","itot":"\u2014"},{"level":1,"name":"Awareness of AI regulation","question":"Are senior leaders or compliance functions aware that AI-specific regulation exists (e.g., EU AI Act), even if no action has been taken yet?","itot":"\u2014"},{"level":2,"name":"AI system inventory exists","question":"Has the organization created an inventory of AI systems currently deployed or in development, including their purpose and risk level?","itot":"\u2014"},{"level":2,"name":"Basic AI ethics guidelines","question":"Do basic AI ethics guidelines or principles exist (even if informal) that address fairness, transparency, and accountability?","itot":"\u2014"},{"level":2,"name":"AI risk classification performed","question":"Have AI systems been classified by risk level (e.g., per EU AI Act risk tiers: unacceptable, high, limited, minimal)?","itot":"\u2014"},{"level":2,"name":"AI security awareness","question":"Are development and operations teams aware of AI-specific security threats (adversarial attacks, data poisoning, model extraction)?","itot":"\u2014"},{"level":2,"name":"Functional safety impact screening","question":"Has a screening been performed to identify which AI systems could impact functional safety in OT environments?","itot":"OT"},{"level":3,"name":"AI governance framework","question":"Is a formal AI governance framework in place with defined roles (AI governance board, AI ethics officer or equivalent), policies, and decision rights?","itot":"\u2014"},{"level":3,"name":"AI risk management process","question":"Is there a defined, enterprise-wide process for AI risk assessment, mitigation, and monitoring aligned with NIST AI RMF or equivalent?","itot":"\u2014"},{"level":3,"name":"EU AI Act compliance program","question":"Is there a compliance program in place to address EU AI Act requirements for high-risk AI systems (risk management, data governance, transparency, human oversight)?","itot":"\u2014"},{"level":3,"name":"AI security controls","question":"Are AI-specific security controls implemented (model access controls, training data integrity, adversarial robustness testing)?","itot":"\u2014"},{"level":3,"name":"AI transparency and explainability","question":"Are mechanisms in place to explain AI model decisions to affected stakeholders where required (especially for high-risk use cases)?","itot":"\u2014"},{"level":4,"name":"AI governance measured","question":"Are AI governance effectiveness and compliance measured with defined KPIs and reported to senior leadership regularly?","itot":"Converged"},{"level":4,"name":"Conformity assessment for high-risk AI","question":"Have high-risk AI systems undergone conformity assessment with technical documentation, testing, and CE marking where required?","itot":"\u2014"},{"level":4,"name":"AI functional safety integration","question":"Are AI systems in safety-relevant OT applications formally integrated into the functional safety lifecycle with documented safety cases?","itot":"Converged"},{"level":4,"name":"AI incident management","question":"Is there a formal process for detecting, reporting, and responding to AI-related incidents (including regulatory notification where required)?","itot":"\u2014"},{"level":4,"name":"AI bias monitoring","question":"Are AI systems monitored continuously for bias, fairness, and discrimination with automated detection and alerting?","itot":"\u2014"},{"level":5,"name":"Proactive AI risk anticipation","question":"Does the organization proactively anticipate emerging AI risks (new attack vectors, regulatory changes, societal impacts) and adapt governance accordingly?","itot":"\u2014"},{"level":5,"name":"AI safety by design","question":"Are AI systems designed from the ground up with safety, security, and ethical considerations as first-class requirements (not retrofitted)?","itot":"\u2014"},{"level":5,"name":"Industry leadership in responsible AI","question":"Does the organization contribute to responsible AI standards, share best practices, or participate in regulatory sandboxes?","itot":"\u2014"},{"level":5,"name":"Trustworthy AI certification","question":"Has the organization achieved or is pursuing certification against ISO/IEC 42001 or equivalent AI management system standard?","itot":"\u2014"}]};

const DIM_KEYS = Object.keys(MATURITY_DATA);
const DIM_COLORS = {'People':'#6366f1','Process':'#0ea5e9','Data':'#10b981','Digital Landscape':'#f59e0b','Responsible AI':'#dc2626'};
const LEVEL_NAMES = {1:'Initial',2:'Managed',3:'Defined',4:'Measured',5:'Optimized'};
const SECTORS = ['Automotive','Chemical','Aerospace','Semiconductor','Energy','Other'];
const SIZES = ['250 – 4,999 employees','5,000 – 9,999 employees','10,000+ employees'];

let answers = {}; // {dimKey: {capIndex: true/false}}
let currentStep = 0;
const totalSteps = DIM_KEYS.length + 2; // info + 5 dims + results

// ═══════ BUILD UI ═══════
function init() {
  // Init answers
  DIM_KEYS.forEach(d => { answers[d] = {}; });
  buildProgress();
  buildSteps();
  showStep(0);
}

function buildProgress() {
  const bar = document.getElementById('progress');
  const labels = ['Company Info', ...DIM_KEYS, 'Results'];
  labels.forEach((l, i) => {
    const s = document.createElement('div');
    s.className = 'prog-step';
    s.textContent = l;
    s.onclick = () => { if (i <= getMaxStep()) showStep(i); };
    bar.appendChild(s);
  });
}

function getMaxStep() {
  // Allow navigating to any completed step + 1
  if (currentStep === 0) {
    const f = document.getElementById('company');
    if (f && f.value.trim()) return totalSteps - 1;
  }
  return totalSteps - 1;
}

function buildSteps() {
  const container = document.getElementById('steps');

  // Step 0: Company Info
  let html = `<div class="step" id="step-0">
    <h2>Company Information</h2>
    <p class="desc">Please provide your company details. This information will be included in your assessment report.</p>
    <div class="form-row">
      <div class="form-group"><label>Company Name *</label><input type="text" id="company" required placeholder="Your company name"></div>
      <div class="form-group"><label>Contact Person *</label><input type="text" id="contact" required placeholder="Your name"></div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>Email Address *</label><input type="email" id="email" required placeholder="your@email.com"></div>
      <div class="form-group"><label>Job Title</label><input type="text" id="jobtitle" placeholder="e.g., CDO, Head of Manufacturing"></div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>Industry Sector</label><select id="sector"><option value="">Select sector...</option>${SECTORS.map(s=>`<option>${s}</option>`).join('')}</select></div>
      <div class="form-group"><label>Company Size</label><select id="size"><option value="">Select size...</option>${SIZES.map(s=>`<option>${s}</option>`).join('')}</select></div>
    </div>
    <div class="btn-row"><div></div><button class="btn btn-primary" onclick="nextStep()">Start Assessment →</button></div>
  </div>`;
  container.innerHTML = html;

  // Steps 1-5: Dimensions
  DIM_KEYS.forEach((dim, di) => {
    let stepHtml = `<div class="step" id="step-${di+1}">
      <h2 style="color:${DIM_COLORS[dim]}">${dim}</h2>
      <p class="desc">Answer each question with Yes or No. Your maturity level is the highest level where all capabilities are present.</p>`;

    const caps = MATURITY_DATA[dim];
    let currentLevel = 0;
    caps.forEach((cap, ci) => {
      if (cap.level !== currentLevel) {
        currentLevel = cap.level;
        stepHtml += `<div class="level-group"><span class="level-label ll-${cap.level}">Level ${cap.level} — ${LEVEL_NAMES[cap.level]}</span></div>`;
      }
      const tagClass = cap.itot === 'IT' ? 'q-tag-it' : cap.itot === 'OT' ? 'q-tag-ot' : cap.itot === 'Converged' ? 'q-tag-conv' : '';
      const tagHtml = tagClass ? `<span class="q-tag ${tagClass}">${cap.itot}</span> ` : '';
      stepHtml += `<div class="question" id="q-${dim.replace(/\s/g,'')}-${ci}">
        <div class="q-text">${tagHtml}${cap.question}</div>
        <div class="toggle-group">
          <button class="toggle-btn" onclick="answer('${dim}',${ci},true,this)">Yes</button>
          <button class="toggle-btn" onclick="answer('${dim}',${ci},false,this)">No</button>
        </div>
      </div>`;
    });

    stepHtml += `<div class="btn-row">
      <button class="btn btn-secondary" onclick="prevStep()">← Back</button>
      <button class="btn btn-primary" onclick="nextStep()">${di < DIM_KEYS.length - 1 ? 'Next Dimension →' : 'View Results →'}</button>
    </div></div>`;
    container.innerHTML += stepHtml;
  });

  // Step 6: Results
  container.innerHTML += `<div class="step" id="step-${totalSteps-1}">
    <h2>Your AI Readiness Results</h2>
    <p class="desc">Based on your self-assessment responses, here is your Industrial AI Readiness profile.</p>
    <div class="results-grid">
      <div class="result-card">
        <h3>Overall AI Readiness Score</h3>
        <div class="score-big" id="overall-score">—</div>
        <div class="score-label">out of 5.0</div>
      </div>
      <div class="result-card">
        <h3>Dimension Scores</h3>
        <div id="dim-scores"></div>
      </div>
    </div>
    <div class="result-card" style="margin-top:16px">
      <h3>Maturity Profile</h3>
      <div class="spider-wrap"><canvas id="spider" width="340" height="340"></canvas></div>
    </div>
    <div class="result-card" style="margin-top:16px;text-align:center">
      <h3>Get Your Detailed Assessment Report</h3>
      <p class="desc" style="margin-bottom:12px">Submit your assessment to receive a detailed Excel report from INOVIA Consulting, including recommendations for your next steps.</p>
      <button class="btn btn-submit" id="submit-btn" onclick="submitAssessment()">Submit Assessment to INOVIA</button>
      <div id="status"></div>
    </div>
    <div class="btn-row"><button class="btn btn-secondary" onclick="prevStep()">← Back</button><div></div></div>
  </div>`;
}

function answer(dim, idx, val, btn) {
  answers[dim][idx] = val;
  const siblings = btn.parentElement.children;
  Array.from(siblings).forEach(b => b.classList.remove('sel-yes', 'sel-no'));
  btn.classList.add(val ? 'sel-yes' : 'sel-no');
  const q = btn.closest('.question');
  q.classList.remove('answered-yes', 'answered-no');
  q.classList.add(val ? 'answered-yes' : 'answered-no');
}

function showStep(n) {
  currentStep = n;
  document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
  document.getElementById(`step-${n}`).classList.add('active');
  document.querySelectorAll('.prog-step').forEach((s, i) => {
    s.classList.remove('active', 'done');
    if (i === n) s.classList.add('active');
    else if (i < n) s.classList.add('done');
  });
  if (n === totalSteps - 1) calculateResults();
  window.scrollTo(0, 0);
}

function nextStep() {
  if (currentStep === 0) {
    const c = document.getElementById('company').value.trim();
    const ct = document.getElementById('contact').value.trim();
    const e = document.getElementById('email').value.trim();
    if (!c || !ct || !e) { alert('Please fill in Company Name, Contact Person, and Email.'); return; }
  }
  if (currentStep < totalSteps - 1) showStep(currentStep + 1);
}
function prevStep() { if (currentStep > 0) showStep(currentStep - 1); }

// ═══════ SCORING ═══════
function calcDimLevel(dim) {
  const caps = MATURITY_DATA[dim];
  let maturityLevel = 0;
  for (let level = 1; level <= 5; level++) {
    const levelCaps = caps.filter(c => c.level === level);
    const allYes = levelCaps.every((c, i) => {
      const globalIdx = caps.indexOf(c);
      return answers[dim][globalIdx] === true;
    });
    if (allYes) maturityLevel = level;
    else break;
  }
  return maturityLevel;
}

function calculateResults() {
  const scores = {};
  let total = 0;
  const scoresDiv = document.getElementById('dim-scores');
  scoresDiv.innerHTML = '';
  DIM_KEYS.forEach(dim => {
    const level = calcDimLevel(dim);
    scores[dim] = level;
    total += level;
    const pct = (level / 5 * 100).toFixed(0);
    scoresDiv.innerHTML += `<div class="dim-score">
      <span style="min-width:120px">${dim}</span>
      <div class="dim-bar"><div class="dim-bar-fill" style="width:${pct}%;background:${DIM_COLORS[dim]}"></div></div>
      <span class="val">${level}</span>
    </div>`;
  });
  const overall = (total / DIM_KEYS.length).toFixed(1);
  document.getElementById('overall-score').textContent = overall;
  drawSpider(scores);
}

// ═══════ SPIDER DIAGRAM ═══════
function drawSpider(scores) {
  const canvas = document.getElementById('spider');
  const ctx = canvas.getContext('2d');
  const cx = 170, cy = 170, R = 130;
  const n = DIM_KEYS.length;
  ctx.clearRect(0, 0, 340, 340);

  function pt(level, i) {
    const a = (Math.PI * 2 * i / n) - Math.PI / 2;
    const r = R * level / 5;
    return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
  }

  // Grid
  for (let l = 1; l <= 5; l++) {
    ctx.beginPath();
    for (let i = 0; i <= n; i++) {
      const [x, y] = pt(l, i % n);
      i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
    }
    ctx.strokeStyle = '#dee2e6'; ctx.lineWidth = 0.6; ctx.stroke();
  }
  // Axes
  for (let i = 0; i < n; i++) {
    const [x, y] = pt(5, i);
    ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(x, y);
    ctx.strokeStyle = '#adb5bd'; ctx.lineWidth = 0.5; ctx.stroke();
  }
  // Level numbers
  ctx.font = '9px monospace'; ctx.fillStyle = '#adb5bd'; ctx.textAlign = 'center';
  for (let l = 1; l <= 5; l++) {
    const [x, y] = pt(l, 0);
    ctx.fillText(l, x + 8, y + 3);
  }
  // Data polygon
  ctx.beginPath();
  DIM_KEYS.forEach((dim, i) => {
    const [x, y] = pt(scores[dim], i);
    i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  });
  ctx.closePath();
  ctx.fillStyle = 'rgba(21,80,123,0.15)'; ctx.fill();
  ctx.strokeStyle = '#15507b'; ctx.lineWidth = 2; ctx.stroke();
  // Dots
  DIM_KEYS.forEach((dim, i) => {
    const [x, y] = pt(scores[dim], i);
    ctx.beginPath(); ctx.arc(x, y, 5, 0, Math.PI * 2);
    ctx.fillStyle = DIM_COLORS[dim]; ctx.fill();
    ctx.strokeStyle = '#fff'; ctx.lineWidth = 1.5; ctx.stroke();
  });
  // Labels
  ctx.font = '11px "DM Sans", sans-serif'; ctx.textAlign = 'center';
  DIM_KEYS.forEach((dim, i) => {
    const [x, y] = pt(5.8, i);
    ctx.fillStyle = DIM_COLORS[dim];
    const short = dim === 'Digital Landscape' ? 'Digital' : dim === 'Responsible AI' ? 'Resp. AI' : dim;
    ctx.fillText(short, x, y + 4);
  });
}

// ═══════ EXCEL GENERATION ═══════
function generateExcel() {
  const wb = XLSX.utils.book_new();
  // Summary sheet
  const summaryData = [
    ['IDAIRA — Industrial AI Readiness Self-Assessment'],
    [''],
    ['Company', document.getElementById('company').value],
    ['Contact', document.getElementById('contact').value],
    ['Email', document.getElementById('email').value],
    ['Job Title', document.getElementById('jobtitle').value],
    ['Sector', document.getElementById('sector').value],
    ['Company Size', document.getElementById('size').value],
    ['Date', new Date().toISOString().split('T')[0]],
    [''],
    ['Dimension', 'Maturity Level', 'Level Name'],
  ];
  let total = 0;
  DIM_KEYS.forEach(dim => {
    const level = calcDimLevel(dim);
    total += level;
    summaryData.push([dim, level, LEVEL_NAMES[level]]);
  });
  summaryData.push(['']);
  summaryData.push(['Overall AI Readiness Score', (total / DIM_KEYS.length).toFixed(1)]);
  const ws1 = XLSX.utils.aoa_to_sheet(summaryData);
  ws1['!cols'] = [{wch:30},{wch:18},{wch:16}];
  XLSX.utils.book_append_sheet(wb, ws1, 'Summary');

  // Detail sheets per dimension
  DIM_KEYS.forEach(dim => {
    const caps = MATURITY_DATA[dim];
    const rows = [['Level', 'Capability', 'Question', 'Answer', 'IT/OT']];
    caps.forEach((cap, i) => {
      const ans = answers[dim][i];
      rows.push([
        `Level ${cap.level} - ${LEVEL_NAMES[cap.level]}`,
        cap.name,
        cap.question,
        ans === true ? 'Yes' : ans === false ? 'No' : 'Not answered',
        cap.itot
      ]);
    });
    rows.push([]);
    rows.push(['Maturity Level:', calcDimLevel(dim), LEVEL_NAMES[calcDimLevel(dim)]]);
    const ws = XLSX.utils.aoa_to_sheet(rows);
    ws['!cols'] = [{wch:20},{wch:35},{wch:70},{wch:14},{wch:12}];
    const sheetName = dim.length > 31 ? dim.substring(0, 31) : dim;
    XLSX.utils.book_append_sheet(wb, ws, sheetName);
  });

  return XLSX.write(wb, {bookType: 'xlsx', type: 'base64'});
}

// ═══════ SUBMISSION ═══════
async function submitAssessment() {
  const btn = document.getElementById('submit-btn');
  const statusDiv = document.getElementById('status');
  btn.disabled = true;
  statusDiv.className = 'status loading';
  statusDiv.textContent = 'Generating report and submitting...';
  statusDiv.style.display = 'block';

  try {
    const excelB64 = generateExcel();
    const dimScores = {};
    DIM_KEYS.forEach(d => dimScores[d] = calcDimLevel(d));
    const overallScore = Object.values(dimScores).reduce((a, b) => a + b, 0) / DIM_KEYS.length;

    const payload = {
      company: document.getElementById('company').value,
      contact: document.getElementById('contact').value,
      email: document.getElementById('email').value,
      jobtitle: document.getElementById('jobtitle').value || '',
      sector: document.getElementById('sector').value || '',
      size: document.getElementById('size').value || '',
      overall_score: overallScore,
      dimension_scores: dimScores,
      excel_b64: excelB64
    };

    // POST to WordPress REST endpoint
    const wpApiUrl = window.IDAIRA_API_URL || '/wp-json/idaira/v1/submit';
    const response = await fetch(wpApiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    const result = await response.json();
    if (result.success) {
      statusDiv.className = 'status success';
      statusDiv.textContent = 'Assessment submitted successfully! INOVIA Consulting will review your results and contact you with a personalized evaluation.';
    } else {
      throw new Error(result.message || 'Submission failed');
    }
  } catch (err) {
    statusDiv.className = 'status error';
    statusDiv.textContent = 'Submission encountered an issue. Please try again or contact pk@inovia-consulting.com directly.';
    btn.disabled = false;
    console.error('IDAIRA submission error:', err);
  }
}

// Initialize
init();
</script>