const { useState, useEffect, useRef, useCallback } = React;

/* ============================================================
   ARTIFACT — what each rung produces (right-side panel)
   ============================================================ */
function Artifact({ rung }){
  const a = rung.artifact;
  if(a.type === "case"){
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body" dangerouslySetInnerHTML={{__html:a.body}} />
      </div>
    );
  }
  if(a.type === "sim"){
    const rounds = [{m:"Quarter capacity",p:72},{m:"Promo conflict",p:88},{m:"Stockout cascade",p:54},{m:"Demand spike",p:81}];
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body">
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14}}>
            <div style={{fontSize:13,fontWeight:600,color:"#0F172A"}}>Round 3 · turn 2/4 · 00:48 remaining</div>
            <div style={{fontSize:12,color:"#64748B"}}>Constraint: +CS volume, −1 truck</div>
          </div>
          {rounds.map((r,i)=>(
            <div key={i} style={{display:"flex",alignItems:"center",gap:12,padding:"8px 0",borderBottom:i<3?"1px solid #EEF2F7":"none"}}>
              <div style={{flex:"0 0 160px",fontSize:12,fontWeight:600,color:"#0F172A"}}>{r.m}</div>
              <div style={{flex:1,height:8,background:"#F1F4F8",borderRadius:4,overflow:"hidden"}}>
                <div style={{width:`${r.p}%`,height:"100%",background:"linear-gradient(90deg,#0EA34A,#1A549F)",borderRadius:4}}></div>
              </div>
              <div style={{fontSize:12,fontWeight:600,color:"#0F172A",flex:"0 0 32px",textAlign:"right"}}>{r.p}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if(a.type === "roleplay"){
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body" style={{fontSize:13,lineHeight:1.65,color:"#334155"}}>
          <div style={{fontSize:11,fontWeight:600,letterSpacing:".14em",textTransform:"uppercase",color:"#246BB2"}}>Persona · BoD member · Hard Mode</div>
          <div style={{margin:"10px 0 6px",color:"#0F172A",fontWeight:600,fontSize:15}}>"You have 60 seconds. Why are we behind?"</div>
          <div style={{padding:"10px 14px",background:"#F5F7FA",borderRadius:10,borderLeft:"3px solid #246BB2",fontStyle:"italic",fontFamily:"Lora, serif"}}>Interrupts at 0:18. Pivots to capex at 0:34. Refuses your first scope cut at 0:52.</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8,marginTop:16}}>
            {["Structure","Clarity","Client-fit","Next step"].map((k,i)=>(
              <div key={i} style={{padding:"10px 12px",background:"#fff",border:"1px solid #E5E9F0",borderRadius:10}}>
                <div style={{fontSize:10,fontWeight:600,letterSpacing:".1em",textTransform:"uppercase",color:"#64748B"}}>{k}</div>
                <div style={{fontFamily:"Open Sans Condensed",fontSize:24,fontWeight:600,marginTop:4,background:"linear-gradient(135deg,#0EA34A,#1A549F)",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent",letterSpacing:"-.02em"}}>{["A","A","B+","A−"][i]}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  if(a.type === "shadow"){
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body" style={{fontSize:13,color:"#334155"}}>
          <div style={{display:"flex",gap:14,alignItems:"center",marginBottom:14}}>
            <div style={{flex:1,height:64,borderRadius:10,background:"linear-gradient(135deg,rgba(13,144,58,.18),rgba(36,107,178,.18))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:600,letterSpacing:".14em",textTransform:"uppercase",color:"#246BB2"}}>Incident timeline.svg</div>
            <div style={{flex:1,height:64,borderRadius:10,background:"linear-gradient(135deg,rgba(13,144,58,.10),rgba(36,107,178,.24))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:600,letterSpacing:".14em",textTransform:"uppercase",color:"#164A97"}}>Handoff log.csv</div>
          </div>
          <div style={{display:"flex",flexDirection:"column",gap:6}}>
            <div><b style={{color:"#0F172A",fontWeight:600}}>What went wrong:</b> Inventory write-down trigger missed at hand-off T-72h.</div>
            <div><b style={{color:"#0F172A",fontWeight:600}}>What to say:</b> "We need a single owner per SKU class. Here's the rule."</div>
            <div><b style={{color:"#0F172A",fontWeight:600}}>Next step:</b> Propose rule to ops lead by Wed. Re-baseline write-down threshold.</div>
          </div>
        </div>
      </div>
    );
  }
  if(a.type === "debrief"){
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body" style={{fontSize:13,color:"#334155"}}>
          {[
            ["Brief was clear before delivery","pass"],
            ["Decision was made on time","pass"],
            ["Stakeholders signed off","pass"],
            ["Quality bar met on outputs","pass"],
            ["Lessons captured for next cycle","watch"]
          ].map((r,i)=>(
            <div key={i} style={{display:"flex",alignItems:"center",gap:10,padding:"8px 0",borderBottom:i<4?"1px solid #EEF2F7":"none"}}>
              <div style={{width:18,height:18,borderRadius:6,background:r[1]==="pass"?"#F0FDF4":"#FFFBEB",border:"1px solid "+(r[1]==="pass"?"#B7EBC8":"#FDE68A"),display:"flex",alignItems:"center",justifyContent:"center",color:r[1]==="pass"?"#15803D":"#B45309",fontSize:11,fontWeight:600}}>{r[1]==="pass"?"✓":"!"}</div>
              <div style={{flex:1}}>{r[0]}</div>
              <div style={{fontSize:10,fontWeight:600,letterSpacing:".1em",textTransform:"uppercase",color:r[1]==="pass"?"#15803D":"#B45309"}}>{r[1]}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if(a.type === "review"){
    return (
      <div className="artifact">
        <div className="art-head"><div className="art-dots"><span></span><span></span><span></span></div><div className="art-fname">{a.title}</div></div>
        <div className="art-body" style={{fontSize:13,color:"#334155"}}>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10}}>
            {[{l:"Cases reviewed",v:"12 / 12"},{l:"Passed quality bar",v:"11"},{l:"Pass rate",v:"92%"}].map((c,i)=>(
              <div key={i} style={{padding:"12px 14px",background:"#fff",border:"1px solid #E5E9F0",borderRadius:10}}>
                <div style={{fontSize:10,fontWeight:600,letterSpacing:".12em",textTransform:"uppercase",color:"#64748B"}}>{c.l}</div>
                <div style={{fontFamily:"Open Sans Condensed",fontSize:30,fontWeight:600,marginTop:4,color:"#0F172A",letterSpacing:"-.02em",lineHeight:1}}>{c.v}</div>
              </div>
            ))}
          </div>
          <div style={{marginTop:14,padding:"12px 14px",background:"#F0FDF4",border:"1px solid #B7EBC8",borderRadius:10,fontSize:13,color:"#0F172A"}}>
            <b style={{fontWeight:600}}>Placement signal:</b> Ready for permanent role — Customer Success lead, Region East.
          </div>
        </div>
      </div>
    );
  }
  return null;
}

/* ============================================================
   MOUNTAIN — six camps on a hand-drawn summit path
   ============================================================ */
// Camp positions: x,y on a 1200x720 viewBox, ascending left→right.
const CAMPS = [
  { x:120,  y:610, lblX:120, lblY:660, polaroidX:30,  polaroidY:480, rotate:-6,  noteX:130, noteY:680, note:"Base camp · build judgment" },
  { x:300,  y:520, lblX:300, lblY:570, polaroidX:230, polaroidY:380, rotate:4,   noteX:310, noteY:590, note:"Decide under pressure" },
  { x:480,  y:430, lblX:480, lblY:480, polaroidX:400, polaroidY:300, rotate:-3,  noteX:490, noteY:500, note:"Practice the conversation" },
  { x:660,  y:350, lblX:660, lblY:400, polaroidX:590, polaroidY:240, rotate:5,   noteX:670, noteY:420, note:"Read the real artifacts" },
  { x:850,  y:255, lblX:850, lblY:305, polaroidX:790, polaroidY:150, rotate:-4,  noteX:860, noteY:325, note:"Drive real work, supervised" },
  { x:1060, y:140, lblX:1050,lblY:195, polaroidX:980, polaroidY:50,  rotate:6,   noteX:1000,noteY:215, note:"Own it · summit reached" },
];

const POLAROID_GRAD = [
  "linear-gradient(135deg,#94A3B8,#64748B)",      // grey · case
  "linear-gradient(135deg,#1A549F,#246BB2)",      // blue · sim
  "linear-gradient(135deg,#6B46C1,#4338CA)",      // indigo · roleplay
  "linear-gradient(135deg,#475569,#1F2937)",      // slate · shadow
  "linear-gradient(135deg,#0EA34A,#057430)",      // green · supervised
  "linear-gradient(135deg,#0D903A,#1A549F)",      // brand gradient · independent
];

function Polaroid({ camp, idx, active, onClick }){
  return (
    <div
      className={`polaroid rung-reveal in ${active?"active":""}`}
      style={{
        left:`${(camp.polaroidX/1200)*100}%`,
        top:`${(camp.polaroidY/720)*100}%`,
        transform:`rotate(${camp.rotate}deg)`,
        transitionDelay:"0s",
        pointerEvents: "auto",
        cursor:"pointer"
      }}
      onClick={onClick}>
      <div style={{height:90, background:"#eee", position:"relative", overflow:"hidden", borderRadius: "1px"}}>
        <img 
          src={`/images/programs/rung-${idx+1}.png?v=2`} 
          style={{ 
            width:"100%", 
            height:"100%", 
            objectFit:"cover", 
            filter: "grayscale(0.1) contrast(1.05) sepia(0.05) brightness(0.95)" 
          }} 
        />
      </div>
      <div className="p-cap">{window.RUNGS[idx].name}</div>
    </div>
  );
}
function Mountain({ active, setActive }){
  const wrapRef = useRef(null);

  return (
    <div className="mountain-wrap" ref={wrapRef}>
      <svg className="mountain-svg" viewBox="0 0 1200 720" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#FDF9F0"/><stop offset="1" stopColor="#EBF1FA"/>
          </linearGradient>
          <linearGradient id="mtn-far" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="rgba(36,107,178,.25)"/><stop offset="1" stopColor="rgba(36,107,178,.05)"/>
          </linearGradient>
          <linearGradient id="mtn-mid" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="rgba(22,74,151,.45)"/><stop offset="1" stopColor="rgba(22,74,151,.15)"/>
          </linearGradient>
          <linearGradient id="mtn-near" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="rgba(13,144,58,.55)"/><stop offset="1" stopColor="rgba(13,144,58,.25)"/>
          </linearGradient>
        </defs>

        {/* Sun + clouds (abstract) */}
        <circle cx="980" cy="90" r="42" fill="#FFF2C7" opacity=".8"/>
        <circle cx="980" cy="90" r="64" fill="#FFE99A" opacity=".25"/>

        {/* Far range */}
        <path d="M0 380 L120 280 L240 340 L380 230 L520 310 L660 200 L820 290 L960 220 L1080 280 L1200 240 L1200 720 L0 720 Z" fill="url(#mtn-far)"/>

        {/* Mid range */}
        <path d="M0 460 L100 380 L220 420 L340 320 L480 380 L620 290 L760 360 L900 280 L1040 340 L1200 300 L1200 720 L0 720 Z" fill="url(#mtn-mid)"/>

        {/* Main summit ridge (the path the camps sit on) */}
        <path d="M0 700 L60 660 L120 610 L200 560 L300 520 L380 480 L480 430 L580 390 L660 350 L760 300 L850 255 L960 200 L1060 140 L1140 100 L1200 80 L1200 720 L0 720 Z" fill="url(#mtn-near)"/>

        {/* Hand-drawn trail (dashed) */}
        <path d="M120 610 C 200 580, 240 560, 300 520 S 420 470, 480 430 S 600 390, 660 350 S 800 290, 850 255 S 1000 180, 1060 140"
              stroke="#0F172A" strokeWidth="2" strokeDasharray="2 7" fill="none" strokeLinecap="round" opacity=".4"/>

        {/* Distance labels */}
        <text x="60" y="700" className="handwriting" style={{ fontWeight: 600, fontSize: 22 }} fill="#0F172A" opacity=".55">START</text>
        <text x="1090" y="80" className="handwriting" style={{ fontWeight: 600, fontSize: 24 }} fill="#0F172A" opacity=".7">SUMMIT</text>

        {/* Birds */}
        <g opacity=".5" stroke="#0F172A" strokeWidth="1.6" fill="none" strokeLinecap="round">
          <path d="M340 130 q 6 -6 12 0 q 6 -6 12 0"/>
          <path d="M420 160 q 5 -5 10 0 q 5 -5 10 0"/>
          <path d="M510 110 q 6 -6 12 0 q 6 -6 12 0"/>
        </g>

        {/* CAMP BUTTONS (the SVG-anchored interactive points) */}
        {CAMPS.map((c,i)=>{
          const isActive = i===active;
          return (
            <g key={i} className="camp-btn" onClick={()=>setActive(i)} tabIndex="0" role="button" aria-label={`Rung ${i+1}`}
               style={{opacity: 1, transition:`opacity 0.5s ease`}}>
              {/* flag pole */}
              <line x1={c.x} y1={c.y} x2={c.x} y2={c.y-46} stroke="#0F172A" strokeWidth="2" opacity={isActive?1:.5}/>
              {/* flag */}
              <path d={`M${c.x} ${c.y-46} L${c.x+26} ${c.y-40} L${c.x+18} ${c.y-32} L${c.x+26} ${c.y-24} L${c.x} ${c.y-30} Z`}
                    fill={isActive?"#FFBA00":"#fff"} stroke="#0F172A" strokeWidth="1.5"/>
              {/* ring + dot */}
              <circle className="camp-ring" cx={c.x} cy={c.y} r="16" fill="#fff" stroke={isActive?"#0D903A":"#0F172A"} strokeWidth={isActive?3:2} opacity={isActive?1:.85}/>
              <circle cx={c.x} cy={c.y} r="7" fill={isActive?"url(#sky)":"#0F172A"}/>
              <text x={c.x} y={c.y+4} textAnchor="middle" fontSize="11" fontFamily="Open Sans Condensed" fontWeight="600" fill={isActive?"#0D903A":"#fff"}>{i+1}</text>
              {/* label */}
              <text x={c.lblX} y={c.lblY} className="handwriting" textAnchor="middle" style={{ fontWeight: 600, fontSize: isActive ? 26 : 22 }} fill="#0F172A" opacity={isActive?1:.65}>
                {window.RUNGS[i].name}
              </text>
            </g>
          );
        })}
      </svg>

      {/* Polaroid layer (HTML overlay) — animates as rungs are selected */}
      {CAMPS.map((c,i)=>(
        <Polaroid key={i} camp={c} idx={i} active={i===active} onClick={()=>setActive(i)} />
      ))}

      {/* Hand-drawn arrow note pointing at active camp */}
      <div className="scribble-note" style={{left:"3%",top:"6%",maxWidth:200,fontSize:16,color:"#0F172A",opacity:.7}}>
        <span className="handwriting" style={{fontWeight:600,fontSize:22}}>click any camp →</span>
        <svg viewBox="0 0 80 50" style={{display:"block",width:80,height:50,marginTop:4}} fill="none" stroke="#0F172A" strokeWidth="1.6" strokeLinecap="round">
          <path d="M5 8 C 30 18, 50 30, 72 38" strokeDasharray="2 4"/>
          <path d="M65 30 L72 38 L62 42"/>
        </svg>
      </div>

      <div className="torn-edge"></div>
    </div>
  );
}

/* ============================================================
   ROOT
   ============================================================ */
function Ladder(){
  const [active, setActive] = useState(0);
  const [isOpen, setIsOpen] = useState(false);
  const [isClosing, setIsClosing] = useState(false);
  const r = window.RUNGS[active];

  const handleSelect = (i) => {
    setActive(i);
    setIsOpen(true);
    setIsClosing(false);
  };

  const handleClose = () => {
    setIsClosing(true);
    setTimeout(() => {
      setIsOpen(false);
      setIsClosing(false);
    }, 350);
  };

  // Prevent background scroll when modal is open
  useEffect(() => {
    if(isOpen) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [isOpen]);

  return (
    <div style={{ position: "relative" }}>
      <Mountain active={active} setActive={handleSelect} />

      {isOpen && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 9999,
          background: "rgba(15,23,42,0.4)", backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
          display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
          opacity: isClosing ? 0 : 1,
          transition: "opacity 0.35s ease",
          pointerEvents: isClosing ? "none" : "auto"
        }} onClick={handleClose}>
          
          <div 
            onClick={e => e.stopPropagation()}
            style={{
              width: "100%", maxWidth: 540,
              display: "flex", flexDirection: "column",
              position: "relative",
              transform: isClosing ? "scale(0.95) translateY(10px)" : (isOpen ? "scale(1) translateY(0)" : "scale(0.9) translateY(20px)"),
              opacity: isClosing ? 0 : 1,
              transition: "all 0.4s cubic-bezier(0.2, 0.8, 0.2, 1)"
            }}
          >
            <button 
              onClick={handleClose}
              style={{
                position: "absolute", right: -12, top: -12, zIndex: 10,
                width: 36, height: 36, borderRadius: "50%", background: "#fff", border: "1px solid #E2E8F0",
                display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
                boxShadow: "0 4px 12px rgba(0,0,0,0.1)", color: "#0F172A", fontWeight: "bold"
              }}
            >✕</button>

            <div className="rung-detail-card" style={{ padding: "24px", display: "flex", flexDirection: "column" }}>
              <div style={{
                height: 240, width: "100%", borderRadius: 16, marginBottom: 20, 
                backgroundImage: `url(/images/programs/rung-${r.n}.png?v=2)`, 
                backgroundSize: "cover", backgroundPosition: "center",
                boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.05)",
                filter: "grayscale(0.1) contrast(1.05) sepia(0.05) brightness(0.95)"
              }}></div>
              <div className="rd-row">
                <div className="rd-rung-tag" style={{ width: 48, height: 48, fontSize: 26, borderRadius: 12 }}>{r.n}</div>
                <div>
                  <div className="rd-step" style={{ fontSize: 11, marginBottom: 2 }}>Rung {String(r.n).padStart(2,"0")} · {r.label}</div>
                  <div className="rd-title" style={{ fontSize: 26, marginTop: 0 }}>{r.fullName || r.name}</div>
                </div>
              </div>
              <p className="rd-tagline" style={{ fontSize: 15, margin: "16px 0 12px", lineHeight: 1.5 }}>{r.tagline}</p>
              <div style={{ fontSize: 14, color: "#334155", lineHeight: 1.6, marginBottom: 24 }}>{r.what}</div>
              <div className="rd-criteria" style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: 8 }}>
                {r.criteria.map((c,i)=>(
                  <div key={i} className="crit" style={{ padding: "12px 16px", borderRadius: 12, background: "#F8FAFC", display: "flex", alignItems: "center", gap: 12, border: "1px solid #E2E8F0" }}>
                    <div style={{ color: "#0EA34A", fontWeight: "bold" }}>→</div>
                    <div>
                      <div className="crit-lbl" style={{ fontSize: 11, fontWeight: 700, color: "#0F172A", textTransform: "none", letterSpacing: 0, marginBottom: 2 }}>{c.lbl}: <span style={{ color: "#0EA34A" }}>{c.val}</span></div>
                      <div style={{ fontSize: 13, color: "#64748B" }}>{c.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

const el = document.getElementById("ladder-root");
if(el){ ReactDOM.createRoot(el).render(<Ladder/>); }
