// Evaluation.jsx — Verigo Global: ISO 27001 online readiness evaluation (live, gated)
const { V: EV, MAXW: EMW, FONT: EFT } = window;

const PREVIEW_THEMES = [
  ['briefcase', 'A.5 Organizational', 72],
  ['users', 'A.6 People', 58],
  ['building', 'A.7 Physical', 84],
  ['cpu', 'A.8 Technological', 46],
];

/* ── PREVIEW DASHBOARD (illustrative, intro only) ────────── */
const ScorePreview = () => (
  <div style={{ background: '#fff', border: `1px solid ${EV.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 ${EV.g200}`, background: EV.g50 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <window.BrandMark size={22} />
        <span style={{ fontSize: 13, fontWeight: 700, color: EV.g700, fontFamily: EFT }}>Readiness report</span>
      </div>
      <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: EV.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(${EV.purple} 0% 64%, ${EV.g100} 64% 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: EV.black, fontFamily: EFT, letterSpacing: '-0.02em', lineHeight: 1 }}>64</span>
            <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: EV.g400 }}>/ 100</span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: EV.g400, marginBottom: 4 }}>Overall maturity</div>
          <div style={{ fontSize: 19, fontWeight: 800, color: EV.black, fontFamily: EFT, letterSpacing: '-0.01em' }}>Developing</div>
          <div style={{ fontSize: 12.5, color: EV.g500, marginTop: 2 }}>23 of 93 controls need work before audit.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {PREVIEW_THEMES.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: EV.g700 }}>
                <window.Icon name={ic} size={15} color={EV.purple} />{name}
              </span>
              <span style={{ fontSize: 12, fontWeight: 700, color: pct < 60 ? EV.orange : EV.purple, fontFamily: "'JetBrains Mono', monospace" }}>{pct}%</span>
            </div>
            <div style={{ height: 7, background: EV.g100, borderRadius: 9999, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: pct < 60 ? EV.orange : EV.purple, borderRadius: 9999 }}></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

/* ── INTRO STAGE ─────────────────────────────────────────── */
const EvalIntro = ({ onStart, onNav }) => {
  const steps = [
    ['clipboard', 'Self-assessment', 'Answer 16 scoped statements across the ISO 27001 clauses and all four 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: EV.g50, borderBottom: `1px solid ${EV.g200}`, overflow: 'hidden', padding: '56px 0 64px' }}>
        <window.HeroWatermark variant="rings" color={EV.purpleDark} opacity={0.14} style={{ top: -30, right: -20, width: 460, height: 420 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: EMW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: EV.g500, marginBottom: 22, fontFamily: EFT }}>
            <button onClick={() => onNav('toolkit:iso27001')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#7A7A8A', fontSize: 13, fontWeight: 600, padding: 0, fontFamily: EFT }}>ISO 27001 Toolkit</button>
            <span style={{ color: EV.g300 }}>/</span>
            <span style={{ color: EV.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: EV.purpleSubtle, color: EV.purple, fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '6px 13px', marginBottom: 20 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: EV.orange }}></span> 16 questions · ~10 minutes · free
              </div>
              <h1 className="vg-hero-title" style={{ fontSize: 54, fontWeight: 800, color: EV.black, letterSpacing: '-0.035em', lineHeight: 1.04, margin: '0 0 18px', fontFamily: EFT }}>
                Know where you stand on ISO 27001.
              </h1>
              <p style={{ fontSize: 19, color: EV.g600, lineHeight: 1.6, margin: '0 0 28px', maxWidth: 560 }}>
                Measure your current state against ISO/IEC 27001:2022 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: EV.g400, marginTop: 14 }}>Free and confidential. We'll ask for a few details so we can send your results.</p>
            </div>
            <ScorePreview />
          </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 ${EV.g200}`, padding: '28px 26px', background: '#fff' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                <div style={{ width: 48, height: 48, background: EV.purpleSubtle, color: EV.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: EV.g300 }}>{String(i + 1).padStart(2, '0')}</span>
              </div>
              <h3 style={{ fontSize: 18.5, fontWeight: 700, color: EV.black, margin: '0 0 8px', fontFamily: EFT, letterSpacing: '-0.01em' }}>{t}</h3>
              <p style={{ fontSize: 14, color: EV.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_FIELDS = {
  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 eInput = { fontFamily: EFT, fontSize: 14, color: EV.black, background: '#fff', border: `1.5px solid ${EV.g200}`, borderRadius: 8, padding: '11px 14px', outline: 'none', width: '100%' };
const eLabel = { fontSize: 12.5, fontWeight: 600, color: EV.black, display: 'block', marginBottom: 7 };
const eSelect = { ...eInput, 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 ScopeForm = ({ onSubmit, onBack }) => {
  const u = (() => { try { return window.TK_ISO.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_FIELDS.industry[0], employees: u.employees || SCOPE_FIELDS.employees[0],
    region: u.region || SCOPE_FIELDS.region[0], locations: u.locations || SCOPE_FIELDS.locations[0],
    systems: u.systems || '', certs: u.certs || '', target: u.target || SCOPE_FIELDS.target[1],
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const text = (k, lbl, props = {}) => <div><label style={eLabel}>{lbl}</label><input style={eInput} value={f[k]} onChange={(e) => set(k, e.target.value)} {...props} /></div>;
  const sel = (k, lbl) => <div><label style={eLabel}>{lbl}</label><select style={eSelect} value={f[k]} onChange={(e) => set(k, e.target.value)}>{SCOPE_FIELDS[k].map((o) => <option key={o}>{o}</option>)}</select></div>;

  return (
    <div>
      <section style={{ position: 'relative', background: EV.g50, borderBottom: `1px solid ${EV.g200}`, overflow: 'hidden', padding: '44px 0 40px' }}>
        <window.HeroWatermark variant="rings" color={EV.purpleDark} opacity={0.12} style={{ top: -30, right: -20, width: 420, height: 380 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: EMW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.purple, marginBottom: 14 }}>Step 1 of 2 · Scope your assessment</div>
          <h1 className="vg-hero-title" style={{ fontSize: 40, fontWeight: 800, color: EV.black, letterSpacing: '-0.03em', lineHeight: 1.06, margin: '0 0 12px', fontFamily: EFT }}>Tell us about your organization</h1>
          <p style={{ fontSize: 17, color: EV.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: EV.g400, marginBottom: 14 }}>Your organization</div>
          <div style={{ background: '#fff', border: `1px solid ${EV.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: 'CISO' })}
              {sel('industry', 'Industry')}
              {sel('employees', 'Company size')}
            </div>
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.g400, marginBottom: 14 }}>Assessment scope</div>
          <div style={{ background: '#fff', border: `1px solid ${EV.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={eLabel}>Systems & services in scope</label><textarea style={{ ...eInput, minHeight: 76, resize: 'vertical' }} value={f.systems} onChange={(e) => set('systems', e.target.value)} placeholder="e.g. production SaaS platform, corporate IT, AWS & Azure environments…" /></div>
            {text('certs', 'Existing certifications (optional)', { placeholder: 'e.g. SOC 2 Type II, 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: EV.g400, marginTop: 10 }}>16 quick questions · about 10 minutes</p>
        </form>
      </window.Section>
    </div>
  );
};

/* ── PAGE ────────────────────────────────────────────────── */
const EvaluationPage = ({ 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_ISO.getUser()); } catch (e) {} }, []);

  const contactOk = () => { try { return !!sessionStorage.getItem('verigo_contact_ok'); } catch (e) { return false; } };
  const requestStart = () => {
    // Scoping must always precede the technical questions. If contact was already
    // captured this session, skip only the popup — never the scope step.
    if (contactOk()) { setUser(window.TK_ISO.getUser()); setStage('scope'); window.scrollTo({ top: 0 }); }
    else { setGate(true); }
  };
  const onGateSubmit = (form) => {
    window.TK_ISO.storeLead({ ...form, source: 'evaluation' });
    try { sessionStorage.setItem('verigo_contact_ok', '1'); } catch (e) {}
    setUser(window.TK_ISO.getUser());
    setGate(false);
    setStage('scope');
    window.scrollTo({ top: 0 });
  };
  const onScopeSubmit = (form) => {
    window.TK_ISO.storeLead({ ...form, source: 'evaluation-scope' });
    setUser(window.TK_ISO.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' && <EvalIntro onStart={requestStart} onNav={onNav} />}
      {stage === 'scope' && <ScopeForm onSubmit={onScopeSubmit} onBack={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} />}
      {stage === 'quiz' && <window.EvalQuiz onComplete={onComplete} onExit={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} />}
      {stage === 'results' && results && <window.EvalResults results={results} user={user} onNav={onNav} onRetake={retake} />}

      {gate && (
        <window.LeadCaptureModal
          icon="gauge"
          eyebrow="ISO 27001 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, { EvaluationPage });
