// EvaluationISO42001.jsx — Verigo Global: ISO 42001 online readiness evaluation (live, gated)
const { V: E2V, MAXW: E2MW, FONT: E2FT } = window;

const PREVIEW_THEMES42 = [
  ['briefcase', 'Policy & Organization', 68],
  ['target', 'Impact Assessment', 54],
  ['layers', 'AI System Life Cycle', 61],
  ['doc', 'Data & Transparency', 47],
];

/* ── PREVIEW DASHBOARD (illustrative, intro only) ────────── */
const ScorePreview42 = () => (
  <div style={{ background: '#fff', border: `1px solid ${E2V.g200}`, boxShadow: '0 20px 48px rgba(63,30,104,0.18)', overflow: 'hidden' }}>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px', borderBottom: `1px solid ${E2V.g200}`, background: E2V.g50 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <window.BrandMark size={22} />
        <span style={{ fontSize: 13, fontWeight: 700, color: E2V.g700, fontFamily: E2FT }}>Readiness report</span>
      </div>
      <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: E2V.g400, fontFamily: "'JetBrains Mono', monospace" }}>Sample</span>
    </div>
    <div style={{ padding: '24px 22px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 22 }}>
        <div style={{ width: 92, height: 92, borderRadius: '50%', background: `conic-gradient(${E2V.purple} 0% 58%, ${E2V.g100} 58% 100%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <div style={{ width: 70, height: 70, borderRadius: '50%', background: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ fontSize: 26, fontWeight: 800, color: E2V.black, fontFamily: E2FT, letterSpacing: '-0.02em', lineHeight: 1 }}>58</span>
            <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: E2V.g400 }}>/ 100</span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: E2V.g400, marginBottom: 4 }}>Overall maturity</div>
          <div style={{ fontSize: 19, fontWeight: 800, color: E2V.black, fontFamily: E2FT, letterSpacing: '-0.01em' }}>Developing</div>
          <div style={{ fontSize: 12.5, color: E2V.g500, marginTop: 2 }}>16 of 38 controls need work before audit.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {PREVIEW_THEMES42.map(([ic, name, pct], i) => (
          <div key={i}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, fontWeight: 600, color: E2V.g700 }}>
                <window.Icon name={ic} size={15} color={E2V.purple} />{name}
              </span>
              <span style={{ fontSize: 12, fontWeight: 700, color: pct < 60 ? E2V.orange : E2V.purple, fontFamily: "'JetBrains Mono', monospace" }}>{pct}%</span>
            </div>
            <div style={{ height: 7, background: E2V.g100, borderRadius: 9999, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: pct < 60 ? E2V.orange : E2V.purple, borderRadius: 9999 }}></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

/* ── INTRO STAGE ─────────────────────────────────────────── */
const EvalIntro42 = ({ onStart, onNav }) => {
  const steps = [
    ['clipboard', 'Self-assessment', 'Answer 13 scoped statements across the ISO 42001 clauses and all five Annex A themes — about 10 minutes, no prep needed.'],
    ['gauge', 'Instant scoring', 'Get a weighted maturity score with a theme-by-theme breakdown showing exactly where you stand against the standard.'],
    ['flag', 'Mapped action plan', 'Every gap links straight to the toolkit document, policy, or procedure that closes it — so you know the next move.'],
  ];
  return (
    <div>
      <section style={{ position: 'relative', background: E2V.g50, borderBottom: `1px solid ${E2V.g200}`, overflow: 'hidden', padding: '56px 0 64px' }}>
        <window.HeroWatermark variant="nodes" color={E2V.purpleDark} opacity={0.14} style={{ top: -30, right: -20, width: 460, height: 420 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: E2MW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: E2V.g500, marginBottom: 22, fontFamily: E2FT }}>
            <button onClick={() => onNav('toolkit:iso42001')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#7A7A8A', fontSize: 13, fontWeight: 600, padding: 0, fontFamily: E2FT }}>ISO 42001 Toolkit</button>
            <span style={{ color: E2V.g300 }}>/</span>
            <span style={{ color: E2V.purple }}>Online Evaluation</span>
          </div>
          <div className="vg-detail-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 400px', gap: 64, alignItems: 'center' }}>
            <div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: E2V.purpleSubtle, color: E2V.purple, fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '6px 13px', marginBottom: 20 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: E2V.orange }}></span> 13 questions · ~10 minutes · free
              </div>
              <h1 className="vg-hero-title" style={{ fontSize: 54, fontWeight: 800, color: E2V.black, letterSpacing: '-0.035em', lineHeight: 1.04, margin: '0 0 18px', fontFamily: E2FT }}>
                Know where you stand on ISO 42001.
              </h1>
              <p style={{ fontSize: 19, color: E2V.g600, lineHeight: 1.6, margin: '0 0 28px', maxWidth: 560 }}>
                Measure your current state against ISO/IEC 42001:2023 in about ten minutes. Get an instant maturity score and a prioritized action plan mapped straight to the toolkit documents that close each gap.
              </p>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                <window.Btn kind="primary" onClick={onStart}>Start the evaluation <window.Icon name="arrow" size={17} color="#fff" /></window.Btn>
                <window.Btn kind="ghost" onClick={() => onNav('contact')}>Talk to a practitioner</window.Btn>
              </div>
              <p style={{ fontSize: 12.5, color: E2V.g400, marginTop: 14 }}>Free and confidential. We'll ask for a few details so we can send your results.</p>
            </div>
            <ScorePreview42 />
          </div>
        </div>
      </section>

      <window.Section bg="#fff" pad="80px 0">
        <window.SectionHeader overline="How it works" align="center"
          title="From a blank slate to a clear plan"
          sub="Three steps take you from “where do we even stand?” to a prioritized, toolkit-mapped action list." maxSub={620} />
        <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {steps.map(([ic, t, d], i) => (
            <div key={i} style={{ border: `1px solid ${E2V.g200}`, padding: '28px 26px', background: '#fff' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                <div style={{ width: 48, height: 48, background: E2V.purpleSubtle, color: E2V.purple, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <window.Icon name={ic} size={24} />
                </div>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: 700, color: E2V.g300 }}>{String(i + 1).padStart(2, '0')}</span>
              </div>
              <h3 style={{ fontSize: 18.5, fontWeight: 700, color: E2V.black, margin: '0 0 8px', fontFamily: E2FT, letterSpacing: '-0.01em' }}>{t}</h3>
              <p style={{ fontSize: 14, color: E2V.g600, lineHeight: 1.6, margin: 0 }}>{d}</p>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
          <window.Btn kind="primary" onClick={onStart}>Start the evaluation <window.Icon name="arrow" size={17} color="#fff" /></window.Btn>
        </div>
      </window.Section>
    </div>
  );
};

/* ── SCOPE FORM (company details + scope, before the quiz) ─ */
const SCOPE_FIELDS42 = {
  industry: ['Software / SaaS', 'Financial services', 'Healthcare', 'Manufacturing', 'Professional services', 'Government / public sector', 'Retail / e-commerce', 'Other'],
  employees: ['1–50', '51–200', '201–1,000', '1,000+'],
  region: ['United States', 'United Kingdom', 'European Union', 'India', 'Singapore', 'Other'],
  locations: ['1 site', '2–5 sites', '6–20 sites', '20+ sites'],
  target: ['Within 3 months', 'Within 6 months', '6–12 months', '12+ months', 'Just exploring'],
};
const e2Input = { fontFamily: E2FT, fontSize: 14, color: E2V.black, background: '#fff', border: `1.5px solid ${E2V.g200}`, borderRadius: 8, padding: '11px 14px', outline: 'none', width: '100%' };
const e2Label = { fontSize: 12.5, fontWeight: 600, color: E2V.black, display: 'block', marginBottom: 7 };
const e2Select = { ...e2Input, appearance: 'none', backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239A9AAA' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E\")", backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', paddingRight: 32, cursor: 'pointer' };

const ScopeForm42 = ({ onSubmit, onBack }) => {
  const u = (() => { try { return window.TK_ISO42001.getUser() || {}; } catch (e) { return {}; } })();
  const [f, setF] = React.useState({
    company: u.company || '', name: u.name || '', email: u.email || '', phone: u.phone || '', role: u.role || '',
    industry: u.industry || SCOPE_FIELDS42.industry[0], employees: u.employees || SCOPE_FIELDS42.employees[0],
    region: u.region || SCOPE_FIELDS42.region[0], locations: u.locations || SCOPE_FIELDS42.locations[0],
    systems: u.systems || '', certs: u.certs || '', target: u.target || SCOPE_FIELDS42.target[1],
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const text = (k, lbl, props = {}) => <div><label style={e2Label}>{lbl}</label><input style={e2Input} value={f[k]} onChange={(e) => set(k, e.target.value)} {...props} /></div>;
  const sel = (k, lbl) => <div><label style={e2Label}>{lbl}</label><select style={e2Select} value={f[k]} onChange={(e) => set(k, e.target.value)}>{SCOPE_FIELDS42[k].map((o) => <option key={o}>{o}</option>)}</select></div>;

  return (
    <div>
      <section style={{ position: 'relative', background: E2V.g50, borderBottom: `1px solid ${E2V.g200}`, overflow: 'hidden', padding: '44px 0 40px' }}>
        <window.HeroWatermark variant="nodes" color={E2V.purpleDark} opacity={0.12} style={{ top: -30, right: -20, width: 420, height: 380 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: E2MW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: E2V.purple, marginBottom: 14 }}>Step 1 of 2 · Scope your assessment</div>
          <h1 className="vg-hero-title" style={{ fontSize: 40, fontWeight: 800, color: E2V.black, letterSpacing: '-0.03em', lineHeight: 1.06, margin: '0 0 12px', fontFamily: E2FT }}>Tell us about your organization</h1>
          <p style={{ fontSize: 17, color: E2V.g600, lineHeight: 1.6, margin: 0, maxWidth: 620 }}>A few details set the scope and let us tailor your results and quote. Then you’ll move on to the technical evaluation.</p>
        </div>
      </section>

      <window.Section bg="#fff" pad="40px 0 84px">
        <form onSubmit={(e) => { e.preventDefault(); onSubmit(f); }} style={{ maxWidth: 860, margin: '0 auto' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: E2V.g400, marginBottom: 14 }}>Your organization</div>
          <div style={{ background: '#fff', border: `1px solid ${E2V.g200}`, padding: '24px', display: 'flex', flexDirection: 'column', gap: 16, marginBottom: 28 }}>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {text('company', 'Company', { required: true, placeholder: 'Acme Technologies' })}
              {text('name', 'Your name', { required: true, placeholder: 'Jane Smith' })}
            </div>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {text('email', 'Work email', { required: true, type: 'email', placeholder: 'jane@company.com' })}
              {text('phone', 'Phone number', { required: true, type: 'tel', placeholder: '+1 555 000 1234' })}
            </div>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
              {text('role', 'Role / title', { placeholder: 'Head of AI Governance' })}
              {sel('industry', 'Industry')}
              {sel('employees', 'Company size')}
            </div>
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: E2V.g400, marginBottom: 14 }}>Assessment scope</div>
          <div style={{ background: '#fff', border: `1px solid ${E2V.g200}`, padding: '24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
              {sel('region', 'Primary region')}
              {sel('locations', 'Sites / locations')}
              {sel('target', 'Target certification')}
            </div>
            <div><label style={e2Label}>AI systems in scope</label><textarea style={{ ...e2Input, minHeight: 76, resize: 'vertical' }} value={f.systems} onChange={(e) => set('systems', e.target.value)} placeholder="e.g. customer-facing chatbot, internal document classifier, third-party LLM integrations…" /></div>
            {text('certs', 'Existing certifications (optional)', { placeholder: 'e.g. ISO 27001, none yet' })}
          </div>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 24 }}>
            <window.Btn kind="ghost" onClick={onBack}>Back</window.Btn>
            <window.Btn kind="primary">Start the technical evaluation <window.Icon name="arrow" size={16} color="#fff" /></window.Btn>
          </div>
          <p style={{ textAlign: 'right', fontSize: 12.5, color: E2V.g400, marginTop: 10 }}>13 quick questions · about 10 minutes</p>
        </form>
      </window.Section>
    </div>
  );
};

/* ── PAGE ────────────────────────────────────────────────── */
const EvaluationISO42001Page = ({ onNav }) => {
  const [stage, setStage] = React.useState('intro'); // intro | scope | quiz | results
  const [gate, setGate] = React.useState(false);
  const [results, setResults] = React.useState(null);
  const [user, setUser] = React.useState(null);

  React.useEffect(() => { try { setUser(window.TK_ISO42001.getUser()); } catch (e) {} }, []);

  const contactOk = () => { try { return !!sessionStorage.getItem('verigo_contact_ok_iso42001'); } catch (e) { return false; } };
  const requestStart = () => {
    if (contactOk()) { setUser(window.TK_ISO42001.getUser()); setStage('scope'); window.scrollTo({ top: 0 }); }
    else { setGate(true); }
  };
  const onGateSubmit = (form) => {
    window.TK_ISO42001.storeLead({ ...form, source: 'evaluation' });
    try { sessionStorage.setItem('verigo_contact_ok_iso42001', '1'); } catch (e) {}
    setUser(window.TK_ISO42001.getUser());
    setGate(false);
    setStage('scope');
    window.scrollTo({ top: 0 });
  };
  const onScopeSubmit = (form) => {
    window.TK_ISO42001.storeLead({ ...form, source: 'evaluation-scope' });
    setUser(window.TK_ISO42001.getUser());
    setStage('quiz');
    window.scrollTo({ top: 0 });
  };
  const onComplete = (res) => { setResults(res); setStage('results'); window.scrollTo({ top: 0 }); };
  const retake = () => { setResults(null); setStage('quiz'); window.scrollTo({ top: 0 }); };

  return (
    <div>
      {stage === 'intro' && <EvalIntro42 onStart={requestStart} onNav={onNav} />}
      {stage === 'scope' && <ScopeForm42 onSubmit={onScopeSubmit} onBack={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} />}
      {stage === 'quiz' && <window.EvalQuiz42 onComplete={onComplete} onExit={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} />}
      {stage === 'results' && results && <window.EvalResults42 results={results} user={user} onNav={onNav} onRetake={retake} />}

      {gate && (
        <window.LeadCaptureModal
          icon="gauge"
          eyebrow="ISO 42001 readiness evaluation"
          heading="Start your evaluation"
          intro="Tell us who you are so we can send your results and tailor your quote. Next, we’ll capture a little about your organization and scope."
          cta="Continue"
          note="Free and confidential. We'll only use your details to share your results and follow up."
          onClose={() => setGate(false)}
          onSubmit={onGateSubmit} />
      )}
    </div>
  );
};

Object.assign(window, { EvaluationISO42001Page });
