// Security section — sticky-scroll encryption flow with cipher text animations.

function Security() {
  const sectionRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      if (!sectionRef.current) return;
      const r = sectionRef.current.getBoundingClientRect();
      const total = r.height - window.innerHeight;
      const p = Math.max(0, Math.min(1, -r.top / total));
      setProgress(p);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const steps = [
    { t:'You type a secret',      d:'Plaintext lives only in memory during editing. When the vault locks, the master key is cleared from RAM — credentials remain as encrypted blobs only.', code:'input → ephemeral buffer' },
    { t:'Your password → a key',  d:'PBKDF2-HMAC-SHA256 (150,000 iterations) derives a 256-bit AES key from your master password. The derived key is never stored — computed fresh on each unlock.', code:'PBKDF2-HMAC-SHA256 · 150k' },
    { t:'AES-256-GCM encrypts',   d:'AES-256-GCM via Apple CryptoKit. Each record gets a unique nonce from the OS CSPRNG. The authentication tag prevents silent tampering.', code:'AES-256-GCM · nonce₉₆' },
    { t:'Written to one file',    d:'Data stored in a sandboxed SQLite database at ~/Library/Application Support/com.cypherkeep.CypherKeep/cypherkeep_clean.db — only encrypted blobs, never plaintext.', code:'cypherkeep_clean.db · ciphertext' },
  ];
  const activeIdx = Math.min(steps.length - 1, Math.floor(progress * steps.length));

  return (
    <section id="security" ref={sectionRef} className="security-section" style={{
      background: INK, color: BONE, position:'relative',
      minHeight: '420vh',
    }}>
      {/* sticky stage */}
      <div className="security-sticky" style={{
        position:'sticky', top:0, height:'100vh',
        display:'flex', alignItems:'center',
        padding:'0 40px',
        overflow:'hidden',
      }}>
        {/* ambient pulse */}
        <div style={{
          position:'absolute', left:'68%', top:'50%', transform:'translate(-50%,-50%)',
          width:900, height:900, borderRadius:'50%',
          background:`radial-gradient(closest-side, ${ACCENT}28, transparent 70%)`,
          filter:'blur(50px)',
        }}/>
        {/* subtle grid */}
        <div style={{
          position:'absolute', inset:0,
          backgroundImage:'linear-gradient(rgba(245,243,237,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(245,243,237,.04) 1px, transparent 1px)',
          backgroundSize:'80px 80px',
          maskImage:'radial-gradient(ellipse at 60% 50%, black 20%, transparent 70%)',
          WebkitMaskImage:'radial-gradient(ellipse at 60% 50%, black 20%, transparent 70%)',
        }}/>

        <div className="security-grid" style={{
          maxWidth:1280, width:'100%', margin:'0 auto', position:'relative',
          display:'grid', gridTemplateColumns:'minmax(360px, 440px) 1fr', gap:72, alignItems:'center',
        }}>
          {/* left: intro + step list (narrower) */}
          <div>
            <div style={{ fontSize:13, color:ACCENT, fontFamily:"'Geist Mono', monospace", letterSpacing:'.15em', marginBottom:18 }}>
              02 — HOW IT KEEPS QUIET
            </div>
            <h2 style={{ fontSize:'clamp(32px, 4.8vw, 64px)', fontWeight:500, letterSpacing:'-.035em', margin:'0 0 22px', lineHeight:.98 }}>
              Zero-knowledge,<br/>
              <span style={{ fontFamily:"'Instrument Serif', serif", fontStyle:'italic' }}>by design.</span>
            </h2>
            <p style={{ fontSize:17, color:'rgba(245,243,237,.7)', lineHeight:1.55, maxWidth:440, marginBottom:36 }}>
              No account, no email, no server to compromise. Your master password
              never leaves your Mac.
            </p>

            <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
              {steps.map((s,i)=>(
                <button key={i} onClick={()=>{
                  // let click jump scroll position
                  if (!sectionRef.current) return;
                  const r = sectionRef.current.getBoundingClientRect();
                  const top = window.scrollY + r.top + (sectionRef.current.offsetHeight - window.innerHeight) * ((i + 0.5) / steps.length);
                  window.scrollTo({ top, behavior:'smooth' });
                }} style={{
                  all:'unset', cursor:'pointer',
                  display:'flex', gap:18, alignItems:'center', padding:'16px 0',
                  borderTop: i>0 ? '1px solid rgba(245,243,237,.08)' : '1px solid rgba(245,243,237,.12)',
                  borderBottom: i===steps.length-1 ? '1px solid rgba(245,243,237,.08)' : 'none',
                  opacity: i <= activeIdx ? 1 : .35,
                  transition:'opacity .4s',
                }}>
                  <span style={{
                    width:38, height:38, flexShrink:0,
                    borderRadius:'50%',
                    background: i <= activeIdx ? ACCENT : 'rgba(245,243,237,.06)',
                    color: i <= activeIdx ? '#fff' : 'rgba(245,243,237,.5)',
                    fontFamily:"'Geist Mono', monospace", fontSize:13, fontWeight:600,
                    display:'inline-flex', alignItems:'center', justifyContent:'center',
                    transition:'background .4s',
                  }}>{String(i+1).padStart(2,'0')}</span>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:15, fontWeight:500, letterSpacing:'-.01em' }}>{s.t}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* right: stage that breathes */}
          <div style={{
            position:'relative',
            height: 'min(540px, 64vh)',
            borderRadius:67,
            background:'linear-gradient(180deg, rgba(245,243,237,.07), rgba(245,243,237,.02))',
            border:'1px solid rgba(245,243,237,.12)',
            overflow:'hidden',
          }}>
            <CipherStage step={steps[activeIdx]} idx={activeIdx}/>
            {/* step chip bottom-left */}
            <div style={{
              position:'absolute', bottom:20, left:24,
              fontSize:10.5, fontFamily:"'Geist Mono', monospace",
              letterSpacing:'.18em', color:'rgba(245,243,237,.45)',
            }}>
              STEP {String(activeIdx+1).padStart(2,'0')} / {String(steps.length).padStart(2,'0')}
            </div>
          </div>
        </div>

        {/* progress bar */}
        <div style={{
          position:'absolute', left:40, right:40, bottom:40,
          height:2, background:'rgba(245,243,237,.1)', borderRadius:2, overflow:'hidden',
        }}>
          <div style={{
            width:`${progress*100}%`, height:'100%', background: ACCENT,
            transition:'width .08s linear',
          }}/>
        </div>
      </div>
    </section>
  );
}

function CipherStage({ step, idx }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => { setTick(t => t + 1); }, [idx]);
  const scenes = [StepType, StepKDF, StepAES, StepDisk];
  const Scene = scenes[idx];
  return (
    <div key={tick} style={{
      position:'absolute', inset:0,
      animation:'fadeUpS .55s cubic-bezier(.2,.7,.3,1)',
    }}>
      <style>{`@keyframes fadeUpS{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
        @keyframes floatY{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}
        @keyframes pulseR{0%,100%{box-shadow:0 0 0 0 ${ACCENT}66}50%{box-shadow:0 0 0 14px ${ACCENT}00}}
        @keyframes spin{to{transform:rotate(360deg)}}
        @keyframes caret{50%{opacity:0}}
      `}</style>
      <Scene step={step}/>
    </div>
  );
}

// STEP 1 — typing into RAM
function StepType({ step }) {
  const [typed, setTyped] = React.useState('');
  const full = 'sk-proj-abc123XYZ789';
  React.useEffect(() => {
    let i = 0;
    const id = setInterval(() => {
      i++; setTyped(full.slice(0, i));
      if (i >= full.length) clearInterval(id);
    }, 65);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={sceneWrap}>
      <SceneHead step={step}/>
      <div style={{
        flex:1, display:'flex', alignItems:'center', justifyContent:'center',
        position:'relative',
      }}>
        {/* ephemeral ring */}
        <div style={{
          position:'absolute', width:460, height:460, borderRadius:'50%',
          border:`1px dashed ${ACCENT}55`, animation:'spin 22s linear infinite',
        }}/>
        {/* input card */}
        <div style={{
          position:'relative',
          padding:'44px 48px', borderRadius:39,
          background:'rgba(0,0,0,.45)', border:'1px solid rgba(245,243,237,.18)',
          width:'min(480px, calc(100vw - 48px))', boxSizing:'border-box', boxShadow:`0 30px 80px -20px ${ACCENT}77`,
        }}>
          <div style={{ fontSize:12, fontFamily:"'Geist Mono', monospace", color:'rgba(245,243,237,.55)', letterSpacing:'.18em', marginBottom:22 }}>API KEY · NEW</div>
          <div style={{
            fontFamily:"'Geist Mono', monospace", fontSize:22,
            color: BONE, lineHeight:1.3,
          }}>
            {typed}<span style={{ animation:'caret 1s steps(1) infinite', color:ACCENT }}>▎</span>
          </div>
          <div style={{ marginTop:28, display:'flex', gap:10, flexWrap:'wrap' }}>
            {['RAM only', 'cleared on blur'].map(t => (
              <span key={t} style={{
                fontSize:11.5, fontFamily:"'Geist Mono', monospace",
                padding:'5px 12px', borderRadius:999,
                background:'rgba(245,243,237,.06)', color:'rgba(245,243,237,.65)',
                border:'1px solid rgba(245,243,237,.1)',
              }}>{t}</span>
            ))}
          </div>
        </div>
      </div>
      <SceneFoot right="plaintext · lives in RAM · 0 bytes on disk"/>
    </div>
  );
}

// STEP 2 — PBKDF2 KDF
function StepKDF() {
  // simulate iteration bars
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN(x => (x+1) % 3), 400);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={sceneWrap}>
      <SceneHead step={{ t:'Argon2id', d:'Password + salt → 150,000 PBKDF2 iterations over HMAC-SHA256.' }}/>
      <div style={{ flex:1, display:'grid', gridTemplateColumns:'1fr auto 1fr', alignItems:'center', justifyItems:'center', gap:56, padding:'0 44px' }}>
        {/* password side */}
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:12, fontFamily:"'Geist Mono', monospace", color:'rgba(245,243,237,.55)', letterSpacing:'.18em', marginBottom:14 }}>MASTER PASSWORD</div>
          <div style={{ fontFamily:"'Geist Mono', monospace", fontSize:36, letterSpacing:'.12em', color:BONE, lineHeight:1 }}>****</div>
          <div style={{ fontSize:13, color:'rgba(245,243,237,.5)', marginTop:14 }}>+ 128-bit salt</div>
        </div>

        {/* KDF machine */}
        <div style={{
          width:240, height:240, borderRadius:56,
          background:`radial-gradient(circle at 50% 40%, ${ACCENT}3d, ${ACCENT}0d 60%, transparent)`,
          border:`1px solid ${ACCENT}66`,
          display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
          gap:16, position:'relative',
        }}>
          <div style={{ fontSize:13, fontFamily:"'Geist Mono', monospace", letterSpacing:'.22em', color:ACCENT, opacity:.95 }}>PBKDF2-SHA256</div>
          {/* memory bars */}
          <div style={{ display:'flex', gap:5, alignItems:'flex-end', height:60 }}>
            {[...Array(8)].map((_,i)=>(
              <div key={i} style={{
                width:11, borderRadius:4,
                background: ACCENT,
                height: 14 + ((i + n*3) % 8) * 5,
                opacity: .55 + (((i + n*3) % 8) / 8) * 0.45,
                transition:'height .35s, opacity .35s',
              }}/>
            ))}
          </div>
          <div style={{ fontSize:11.5, fontFamily:"'Geist Mono', monospace", color:'rgba(245,243,237,.6)', letterSpacing:'.12em' }}>
            150,000 iters
          </div>
          {/* pulse ring */}
          <div style={{
            position:'absolute', inset:-1, borderRadius:57, pointerEvents:'none',
            animation:'pulseR 2s ease-in-out infinite',
          }}/>
        </div>

        {/* key side */}
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:12, fontFamily:"'Geist Mono', monospace", color:'rgba(245,243,237,.55)', letterSpacing:'.18em', marginBottom:14 }}>DERIVED KEY</div>
          <div style={{ fontFamily:"'Geist Mono', monospace", fontSize:36, letterSpacing:'.08em', color:ACCENT, lineHeight:1 }}>6E9A</div>
          <div style={{ fontSize:13, color:'rgba(245,243,237,.5)', marginTop:14 }}>· 256 bits</div>
        </div>
      </div>
      <SceneFoot right="derived fresh on each unlock"/>
    </div>
  );
}

// STEP 3 — AES-GCM encrypt
function StepAES() {
  const [phase, setPhase] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setPhase(p => (p+1) % 2), 1400);
    return () => clearInterval(id);
  }, []);
  const plaintext = 'sk-proj-abc123XYZ789';
  const cipher = '8A1F·3C·9E7D·2B64·FF03·A91C·4E7B·BA02';
  return (
    <div style={sceneWrap}>
      <SceneHead step={{ t:'AES-256-GCM', d:'Plaintext + key + nonce → ciphertext + 128-bit auth tag.' }}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', gap:28, padding:'0 44px', justifyContent:'center' }}>
        {/* plaintext row */}
        <Lane label="PLAINTEXT" value={plaintext} color={BONE}/>
        {/* encryptor bar */}
        <div style={{
          height:72, borderRadius:28,
          background:`linear-gradient(90deg, ${ACCENT}2d, ${ACCENT}55, ${ACCENT}2d)`,
          border:`1px solid ${ACCENT}66`,
          display:'flex', alignItems:'center', justifyContent:'center', gap:18,
          fontFamily:"'Geist Mono', monospace", fontSize:14, letterSpacing:'.18em',
          color:BONE, position:'relative', overflow:'hidden',
        }}>
          <span style={{
            position:'absolute', left:phase===0?'-20%':'100%', top:0, bottom:0,
            width:'40%',
            background:`linear-gradient(90deg, transparent, ${ACCENT}, transparent)`,
            transition:'left 1.3s cubic-bezier(.6,0,.4,1)',
            opacity:.7,
          }}/>
          <span style={{ position:'relative' }}>⟶ AES-256-GCM ⟶</span>
        </div>
        {/* ciphertext row */}
        <Lane label="CIPHERTEXT" value={cipher} color="#10b981" mono/>
      </div>
      <SceneFoot right="unique nonce per record"/>
    </div>
  );
}

// STEP 4 — disk
function StepDisk() {
  return (
    <div style={sceneWrap}>
      <SceneHead step={{ t:'One file.', d:'~/Library/Application Support/com.cypherkeep.CypherKeep/cypherkeep_clean.db' }}/>
      <div style={{
        flex:1, display:'flex', alignItems:'center', justifyContent:'center',
        position:'relative', padding:'0 32px',
      }}>
        {/* file illustration */}
        <div style={{
          position:'relative', width:230, height:280,
          animation:'floatY 4s ease-in-out infinite',
        }}>
          {/* file body */}
          <div style={{
            position:'absolute', inset:0,
            borderRadius:34,
            background:'linear-gradient(160deg, rgba(245,243,237,.12), rgba(245,243,237,.04))',
            border:'1px solid rgba(245,243,237,.2)',
            boxShadow:`0 40px 80px -30px ${ACCENT}aa`,
            overflow:'hidden',
          }}>
            {/* folded corner */}
            <div style={{
              position:'absolute', top:0, right:0,
              width:42, height:42,
              background:'rgba(245,243,237,.09)',
              clipPath:'polygon(0 0, 100% 100%, 100% 0)',
            }}/>
            {/* content lines */}
            <div style={{ padding:'30px 22px 22px', display:'flex', flexDirection:'column', gap:9 }}>
              <div style={{ fontSize:10.5, fontFamily:"'Geist Mono', monospace", color:ACCENT, letterSpacing:'.18em' }}>CYPHERKEEP_CLEAN.DB</div>
              {[...Array(8)].map((_,i) => (
                <div key={i} style={{
                  height:7, borderRadius:4,
                  width: `${40 + ((i*37) % 55)}%`,
                  background:`linear-gradient(90deg, ${ACCENT}66, rgba(245,243,237,.08))`,
                  opacity: .6 + (i%3)*0.12,
                }}/>
              ))}
              <div style={{
                marginTop:10,
                fontFamily:"'Geist Mono', monospace", fontSize:10.5,
                color:'rgba(245,243,237,.4)',
              }}>· · · ciphertext · · ·</div>
            </div>
          </div>
          {/* lock badge — larger, fully within stage */}
          <div style={{
            position:'absolute', bottom:-8, right:-8,
            width:84, height:84, borderRadius:'50%',
            background:'linear-gradient(135deg, #34d399 0%, #10b981 55%, #047857 100%)',
            display:'flex', alignItems:'center', justifyContent:'center',
            fontSize:38, color:'#fff', fontWeight:600,
            boxShadow:'0 18px 44px -6px rgba(16,185,129,.65), inset 0 1px 0 rgba(255,255,255,.25)',
          }}>🔒</div>
        </div>
      </div>
      <SceneFoot right="export as .cypherkeep backup anywhere"/>
    </div>
  );
}

// helpers
const sceneWrap = {
  position:'absolute', inset:0,
  display:'flex', flexDirection:'column',
  padding:'44px 44px 32px',
  gap:24,
};
function SceneHead({ step }) {
  // Split title into head + italic tail if it contains the right shape;
  // otherwise show whole thing. Stylized: first word(s) plain, last word in serif italic.
  const parts = splitStylizedTitle(step.t);
  return (
    <div style={{ maxWidth:640 }}>
      <div style={{ fontSize:48, fontWeight:500, letterSpacing:'-.03em', lineHeight:1.02, marginBottom:14 }}>
        {parts.head}
        {parts.tail && (
          <span style={{ fontFamily:"'Instrument Serif', serif", fontStyle:'italic', fontWeight:400, fontSize:'1.18em', color:ACCENT, letterSpacing:'-.02em' }}>
            {parts.head ? ' ' : ''}{parts.tail}
          </span>
        )}
      </div>
      <div style={{ fontSize:17, color:'rgba(245,243,237,.72)', lineHeight:1.5 }}>{step.d}</div>
    </div>
  );
}
function splitStylizedTitle(t) {
  // Heuristic: last meaningful word in italic serif.
  // Map specific titles for best effect.
  const map = {
    'You type a secret': { head:'You type a', tail:'secret' },
    'Argon2id':          { head:'Password → a', tail:'key' },
    'AES-256-GCM':       { head:'AES-256-GCM', tail:'encrypts' },
    'One file.':         { head:'One', tail:'file.' },
  };
  return map[t] || { head:t, tail:'' };
}
function SceneFoot({ right }) {
  return (
    <div style={{
      display:'flex', justifyContent:'flex-end',
      fontSize:10.5, fontFamily:"'Geist Mono', monospace",
      letterSpacing:'.15em', color:'rgba(245,243,237,.45)',
    }}>
      → {right}
    </div>
  );
}
function Lane({ label, value, color, mono }) {
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:18,
      padding:'20px 26px', borderRadius:28,
      background:'rgba(0,0,0,.35)', border:'1px solid rgba(245,243,237,.1)',
    }}>
      <span style={{
        fontSize:11, fontFamily:"'Geist Mono', monospace",
        letterSpacing:'.22em', color:'rgba(245,243,237,.5)',
        width:106, flexShrink:0,
      }}>{label}</span>
      <span style={{
        fontFamily:"'Geist Mono', monospace", fontSize:17, color,
        letterSpacing: mono ? '.05em' : 0, whiteSpace:'nowrap',
        overflow:'hidden', textOverflow:'ellipsis',
      }}>{value}</span>
    </div>
  );
}

Object.assign(window, { Security });
