const RDS = () => window.RefactoredDesignSystem_f0a141 || {};
const LAWS=[
 {n:"01",t:"Jakob's Law",k:0,p:"Users expect your UI to work like the others they know. Use the conventional pattern for any solved problem; spend novelty on content, not mechanics.",c:"NavBar · labels-above · red = destructive"},
 {n:"02",t:"Hick's Law",k:1,p:"Decision time grows with choices. One primary action per view; nav ≤7; more than five options get grouped or disclosed.",c:"--max-primary-actions:1"},
 {n:"03",t:"Fitts's Law",k:0,p:"Targets ≥44px, 48 for touch. The primary action is largest and nearest; destructive sits ≥24px from confirm.",c:"--hit-min · --gap-danger"},
 {n:"04",t:"Miller's Law",k:0,p:"Working memory holds chunks, not lists. ≤5 items per group, ≤3 groups per section. Chunk long strings.",c:"--max-group-items:5"},
 {n:"05",t:"Law of Proximity",k:1,p:"Closeness means relatedness, so space encodes relationship — never rhythm. If every gap is identical, the layout has no structure.",c:"--space-related → group → block"},
 {n:"06",t:"Common Region",k:0,p:"A shared boundary groups harder than proximity. Try spacing first; add a card only when spacing can't carry it. Never nest regions >2 deep.",c:"--radius-card · --border"},
 {n:"07",t:"Von Restorff",k:1,p:"The thing that differs is remembered. One orange per view, on the single primary action. A second orange halves the value of the first.",c:"--brand, reserved"},
 {n:"08",t:"Serial Position",k:0,p:"First and last are remembered best. Most important first, second-most last, mundane in the middle. Repeat the CTA at the end of long pages.",c:"nav order · closing CTA"},
 {n:"09",t:"Doherty Threshold",k:1,p:"Attention holds when the system answers within ~400ms. Every action acknowledged — press, spinner, skeleton or toast. No dead clicks, ever.",c:"--dur-ack-max:400ms · Skeleton"},
 {n:"10",t:"Peak–End Rule",k:1,p:"An experience is judged by its peak and its ending. Every flow ends in an explicit success state; every empty and error offers the next step.",c:"EmptyState · ErrorBoundary"}
];
const PRINCIPLES=[
 {t:"Learning leads",p:"Learner content and the wave illustration carry the page; chrome recedes into white surfaces and navy bookends."},
 {t:"One orange action",p:"#F5A623 is spent on the single primary action and active indicators — never on repeated links or decoration."},
 {t:"Inclusive by default",p:"The brand's mission is inclusivity and the UI proves it: AA in both themes, 44px targets, keyboard operable, reduced-motion honored."},
 {t:"Warm geometry, earned elevation",p:"Rounded, friendly shapes; elevation confirms interaction — hover lifts, selection floats — never decoration."},
 {t:"Same system, every hand",p:"UI references semantic tokens only, so a designer, a developer and an AI produce the same brand."}
];
const INVENTORY=["Logo","Button","Badge","TextField","SignUpForm","DemoForm","Validators","Toast","Toaster","SafetyNet","ErrorBoundary","ConfirmDialog","Skeleton","EmptyState","ProgressTrack","CourseCard","VerticalCard","HorizontalCard","NavBar","Footer","MobileNav","MobileMenu","SelectorSlider","CarouselArrow","HeroHeader","MobileHero","Icon"];
const RAMP=[["--peri-300","--peri-500","--peri-600","--peri-700","--peri-900"],["--sky-300","--sky-400","--sky-500","--sky-700","--sky-900"],["--orange-300","--orange-500","--orange-600","--orange-700","--orange-900"]];
// Live examples — real pages in this repo, rendered in scaled iframes rather than screenshotted.
const EXAMPLES=[
 {src:"showcase.html",label:"Marketing site",meta:"3 pages · hash routing · WebGL hero",w:1440,h:900,span:2,rows:2},
 {src:"mobile.html",label:"Mobile screens",meta:"390px · nav, sheet, hero",w:390,h:844,span:1,rows:2},
 {src:"guidelines/a11y-contrast.card.html",label:"Accessibility gate",meta:"50 pairs · computed live",w:980,h:960,span:1,rows:1},
 {src:"components/states/states.card.html",label:"State components",meta:"skeleton · empty · progress",w:900,h:470,span:1,rows:1},
 {src:"guidelines/ux-laws.card.html",label:"The 10 laws",meta:"decision layer · reference",w:1360,h:1220,span:2,rows:1},
 {src:"components/feedback/errors.card.html",label:"Error handling",meta:"boundary · dialog · safety net",w:920,h:600,span:2,rows:1}
];

// contrast, measured from the live tokens — the same technique the Accessibility Gate card uses
const _lin=c=>{c/=255;return c<=0.04045?c/12.92:Math.pow((c+0.055)/1.055,2.4);};
const _lum=p=>0.2126*_lin(p[0])+0.7152*_lin(p[1])+0.0722*_lin(p[2]);
function _parse(s){s=String(s||"").trim();
  let m=s.match(/^#([0-9a-f]{3,8})$/i);
  if(m){let h=m[1];if(h.length===3)h=h.split("").map(c=>c+c).join("");
    return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16),h.length>=8?parseInt(h.slice(6,8),16)/255:1];}
  m=s.match(/rgba?\(([^)]+)\)/i);
  if(m){const p=m[1].split(/[,\s\/]+/).filter(Boolean).map(parseFloat);return [p[0],p[1],p[2],p.length>3?p[3]:1];}
  return null;}
const _over=(f,b)=>[f[0]*f[3]+b[0]*(1-f[3]),f[1]*f[3]+b[1]*(1-f[3]),f[2]*f[3]+b[2]*(1-f[3]),1];
function ratio(fg,bg){
  const cs=getComputedStyle(document.documentElement);
  let b=_parse(cs.getPropertyValue(bg)),f=_parse(cs.getPropertyValue(fg));
  if(!b||!f)return null;
  if(b[3]<1)b=_over(b,[255,255,255,1]);
  if(f[3]<1)f=_over(f,b);
  const a=_lum(f),c=_lum(b);
  return ((Math.max(a,c)+0.05)/(Math.min(a,c)+0.05)).toFixed(2);
}
const toast=d=>window.dispatchEvent(new CustomEvent("rf:toast",{detail:d}));

function SystemLanding(){
  const { Button, Badge, TextField, ProgressTrack, Skeleton, EmptyState, Logo, Footer, Validators, Reveal, Counter, SelectorSlider, setMotionMode, motionEnabled } = RDS();
  const canvasRef=React.useRef(null),heroRef=React.useRef(null),rootRef=React.useRef(null);
  const [weight,setWeight]=React.useState(700);
  const [theme,setTheme]=React.useState(()=>document.documentElement.dataset.theme||"light");
  const [ratios,setRatios]=React.useState({});
  const [email,setEmail]=React.useState("");
  const [emailErr,setEmailErr]=React.useState("");
  const [loading,setLoading]=React.useState(false);
  const [motionOn,setMotionOn]=React.useState(()=>motionEnabled?motionEnabled():true);
  const [shown,setShown]=React.useState({}); // previews mount progressively — six live pages at once is too heavy
  const galRef=React.useRef(null);
  const [gw,setGw]=React.useState(0);
  React.useEffect(()=>{
    const el=galRef.current;if(!el)return;
    const read=()=>setGw(el.clientWidth);
    read();
    if(typeof ResizeObserver==="undefined"){window.addEventListener("resize",read);return ()=>window.removeEventListener("resize",read);}
    const ro=new ResizeObserver(read);ro.observe(el);return ()=>ro.disconnect();
  },[]);
  // Auto-load the previews once the gallery comes into view, staggered so the browser isn't hit with six
  // React+bundle boots at once. The poster is only ever a placeholder, never something you must click.
  React.useEffect(()=>{
    const el=galRef.current;
    if(!el||typeof IntersectionObserver==="undefined"){setShown(Object.fromEntries(EXAMPLES.map(e=>[e.src,true])));return;}
    let timers=[];
    const io=new IntersectionObserver(es=>{
      if(!es[0].isIntersecting)return;
      io.disconnect();
      EXAMPLES.forEach((ex,i)=>{timers.push(setTimeout(()=>setShown(s=>({...s,[ex.src]:true})),i*650));});
    },{rootMargin:"200px 0px"});
    io.observe(el);
    return ()=>{io.disconnect();timers.forEach(clearTimeout);};
  },[]);
  const toggleMotion=()=>{const next=motionOn?"reduced":"full";if(setMotionMode)setMotionMode(next);setMotionOn(!motionOn);};

  React.useEffect(()=>{document.documentElement.dataset.theme=theme;
    setRatios({body:ratio("--text-body","--surface"),link:ratio("--link","--surface"),ctrl:ratio("--border-control","--surface-field"),btn:ratio("--button-primary-fg","--brand")});},[theme]);

  React.useEffect(()=>{
    if(!canvasRef.current||!window.WaveField)return;
    let f=null;try{f=window.WaveField.mount(canvasRef.current,{});}catch(e){console.error("[System] hero field:",e);}
    if(!f)return;window.__rfField=f;
    return ()=>{try{f.destroy();}catch(e){}window.__rfField=null;};
  },[]);

  React.useEffect(()=>{
    const g=window.gsap,st=window.ScrollTrigger;
    if(!g||!rootRef.current||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;
    if(st)g.registerPlugin(st);
    const q=s=>Array.from(rootRef.current.querySelectorAll(s));
    const ctx=g.context(()=>{
      g.timeline({defaults:{ease:"power3.out"}})
        .from(q(".shero .pill"),{y:16,opacity:0,duration:.65},.1)
        .from(q(".sh1 .ln>span"),{yPercent:112,duration:1,stagger:.09},.16)
        .from(q(".shero__sub"),{y:18,opacity:0,duration:.75},.56)
        .from(q(".shero__cta>*"),{y:18,opacity:0,duration:.65,stagger:.08},.68)
        .from(q(".shero__stat"),{opacity:0,duration:.7},.88);
      if(!st)return;
      st.create({trigger:heroRef.current,start:"top top",end:"bottom top",scrub:true,
        onUpdate:s=>{if(window.__rfField)window.__rfField.setScroll(s.progress);}});
      q("[data-reveal]").forEach(el=>g.from(el.children,{y:22,opacity:0,duration:.7,stagger:.07,ease:"power3.out",
        scrollTrigger:{trigger:el,start:"top 84%",once:true}}));
      // Six lazy iframes land after mount and change the page height, so cached trigger positions go stale.
      const refresh=()=>st.refresh();
      window.addEventListener("load",refresh);
      setTimeout(refresh,1200);setTimeout(refresh,3000);
    },rootRef);
    return ()=>ctx.revert();
  },[]);

  const copy=async(text,label)=>{
    try{await navigator.clipboard.writeText(text);toast({tone:"success",title:"Copied",message:label});}
    catch(e){toast({tone:"info",title:"Copy blocked",message:"Your browser wouldn't allow it — select and copy manually."});}
  };
  const hex=tok=>getComputedStyle(document.documentElement).getPropertyValue(tok).trim();
  const checkEmail=v=>{setEmail(v);if(emailErr)setEmailErr("");};
  const runValidate=()=>{const e=Validators?Validators.vEmail(email):null;setEmailErr(e||"");
    if(!e)toast({tone:"success",title:"Valid",message:"That's the shape the Validators expect."});};
  const fakeLoad=()=>{setLoading(true);setTimeout(()=>setLoading(false),1600);};

  return <div ref={rootRef} style={{background:"var(--surface)"}} data-screen-label="system-landing">
    <nav className="snav" aria-label="Main">
      <div className="wrap snav__in">
        {Logo&&<Logo on="dark" height={34} assetsBase="assets" href="#top"/>}
        <div className="snav__links">
          <a href="#what">What this is</a><a href="#decisions">Decisions</a><a href="#hardening">Hardening</a>
          <a href="#practice">In practice</a><a href="#start">Start here</a>
        </div>
        {Button&&<Button label={motionOn?"Motion on":"Preview motion"} size="sm" variant="outline-inverse" icon={motionOn?"ri-pause-line":"ri-play-line"} onClick={toggleMotion}/>}
        {Button&&<Button label={theme==="dark"?"Light":"Dark"} size="sm" variant="outline-inverse" icon={theme==="dark"?"ri-sun-line":"ri-moon-line"} onClick={()=>setTheme(t=>t==="dark"?"light":"dark")}/>}
      </div>
    </nav>

    <header ref={heroRef} className="shero" id="top" data-screen-label="hero">
      <canvas ref={canvasRef} aria-hidden="true"></canvas>
      <div className="shero__glow" aria-hidden="true"></div>
      <div className="shero__scrim" aria-hidden="true"></div>
      <div className="wrap shero__in">
        <div className="shero__grid">
          <div>
            <span className="pill"><span className="dot"></span>Refactored by Colaberry · Design System v3</span>
            <h1 className="sh1">
              <span className="ln"><span>Every decision,</span></span>
              <span className="ln"><span>already <em>made</em>.</span></span>
            </h1>
            <p className="shero__sub">Tokens, components, templates and a decision layer of ten UX laws — so a designer, a developer or an AI ships the same on-brand, accessible screen. Everything on this page is the real system running, not a picture of it.</p>
            <div className="shero__cta">
              {Button&&<Button label="What's inside" size="lg" icon="ri-arrow-down-line" onClick={()=>document.getElementById("what").scrollIntoView()}/>}
              {Button&&<Button label="See it applied" size="lg" variant="outline-inverse" icon="ri-external-link-line" onClick={()=>{window.location.href="showcase.html";}}/>}
            </div>
            <p className="shero__stat">310 tokens · 38 components · 40 specimens · 10 UX laws · 50 contrast pairs, zero failures · 0 CDN dependencies</p>
            {!motionOn&&<span className="motionbar">
              <span>Motion is paused — your system asks for reduced motion.</span>
              {Button&&<Button label="Play it" size="sm" icon="ri-play-line" onClick={toggleMotion}/>}
            </span>}
          </div>
          <div className="spec" aria-label="Live pieces of the system">
            <div className="spec__c spec__c--a float">
              <p className="spec__k">token</p>
              <div style={{display:"flex",flexDirection:"column",gap:7}}>
                <span className="spec__tok"><i style={{background:"var(--brand)"}}></i>--brand · reserved for one action</span>
                <span className="spec__tok"><i style={{background:"var(--peri-500)"}}></i>--space-related · 8px</span>
              </div>
            </div>
            <div className="spec__c float float--2">
              <p className="spec__k">component · live</p>
              <div className="spec__row">
                {Button&&<Button label="Start Learning" size="sm" icon="ri-arrow-right-line" onClick={()=>document.getElementById("start").scrollIntoView()}/>}
                {Badge&&<Badge label="Beginner" tone="positive"/>}
              </div>
            </div>
            <div className="spec__c spec__c--b float float--3">
              <p className="spec__k">accessibility · measured now</p>
              <div className="spec__ratio">
                <b>{Counter?<Counter value={parseFloat(ratios.btn||0)} decimals={2} suffix=":1"/>:(ratios.btn||"—")+":1"}</b>
                <span>button label on orange — AA</span>
              </div>
            </div>
            <div className="spec__c spec__c--a float float--2">
              <p className="spec__k">state</p>
              {ProgressTrack&&<ProgressTrack label="Python for Data Scientists" value={3} total={8} unit="lesson" size="sm"/>}
            </div>
          </div>
        </div>
      </div>
      <span className="shero__hint" aria-hidden="true">{motionOn?"noise resolving into the brand wave":"motion paused — press Preview motion"}</span>
    </header>

    <div className="marq" aria-label="Component inventory">
      <div className="marq__t">{[0,1].map(k=><div className="marq__r" key={k} aria-hidden={k===1||undefined}>
        {INVENTORY.map(c=><span className="marq__i" key={c+k}>{c}</span>)}
      </div>)}</div>
    </div>

    <section className="sec" id="what">
      <div className="wrap" data-reveal>
        <p className="kick"><i>01</i>What this is</p>
        <h2 className="sh2">Everything the brand knows, in one place.</h2>
        <p className="lead">A design system is a brand's shared language — color, type, space, motion, components and the rules that govern them — written as code that people <b>and AI</b> can read. This is Refactored's. Nothing here is a screenshot.</p>
      </div>
      <div className="wrap"><div className="bento">

        <div className="tile tile--w2 tile--h2">
          <span className="tile__grp">Brand</span>
          <h3 className="tile__h">One mark, any surface.</h3>
          <p className="tile__p">"Refactored by Colaberry" is the only logo in the system — no bare Colaberry mark, ever. Three renderings of one master artwork, generated without a vector source.</p>
          <div style={{display:"flex",flexDirection:"column",gap:9}}>
            <div style={{padding:"15px 17px",background:"var(--surface-subtle)",borderRadius:13}}>{Logo&&<Logo on="light" height={34} assetsBase="assets"/>}</div>
            <div style={{padding:"15px 17px",background:"var(--surface-band-solid)",borderRadius:13}}>{Logo&&<Logo on="dark" height={34} assetsBase="assets"/>}</div>
            <div style={{padding:"15px 17px",background:"var(--brand)",borderRadius:13,color:"var(--color-navy)"}}>{Logo&&<Logo on="mono" height={34} assetsBase="assets"/>}</div>
          </div>
          <p className="tile__p" style={{fontSize:13}}>The mono rendering is an alpha mask with the "ed" knockout punched through, so it tints to <b>any</b> colour — the one capability a vector would have bought, recovered from a raster.</p>
          <a className="tile__lnk" href="components/brand/logo.card.html">Logo rules <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
        </div>

        <div className="tile tile--w2">
          <span className="tile__grp">Colors</span>
          <h3 className="tile__h">Ramps, then roles.</h3>
          <p className="tile__p">Three brand hues, ten steps each. Components never touch a ramp — they reference semantic roles, so both themes and every state come free. Click a swatch to copy its hex.</p>
          {RAMP.map((row,i)=><div className="sw" key={i}>{row.map(tok=>
            <button key={tok} style={{background:"var("+tok+")"}} title={tok} onClick={()=>copy(hex(tok),tok)}>{tok.replace("--","")}</button>)}</div>)}
          <div className="dvd"></div>
          <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
            <span className="ctr"><b>{ratios.body||"—"}:1</b><span>body text</span></span>
            <span className="ctr"><b>{ratios.link||"—"}:1</b><span>links</span></span>
            <span className="ctr"><b>{ratios.ctrl||"—"}:1</b><span>field edge</span></span>
          </div>
          <p className="tile__p" style={{fontSize:13}}>Measured from the live tokens as you read this — flip the theme and watch them change.</p>
          <a className="tile__lnk" href="guidelines/a11y-contrast.card.html">Full audit, 50 pairs <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
        </div>

        <div className="tile tile--w2">
          <span className="tile__grp">Elements</span>
          <h3 className="tile__h">The atoms, live.</h3>
          <div className="spec__row">
            {Button&&<Button label="Primary" size="md" icon="ri-arrow-right-line"/>}
            {Button&&<Button label="Outline" size="md" variant="outline"/>}
            {Button&&<Button label="Ghost" size="md" variant="ghost"/>}
          </div>
          <div className="spec__row">
            {Button&&<Button label="Small" size="sm"/>}
            {Button&&<Button label={loading?"Working":"Loading state"} size="sm" variant="secondary" loading={loading} onClick={fakeLoad}/>}
            {Button&&<Button label="Destructive" size="sm" variant="destructive"/>}
          </div>
          <div className="dvd"></div>
          <div className="spec__row">
            {Badge&&<Badge label="Beginner" tone="positive"/>}
            {Badge&&<Badge label="Intermediate" tone="warning"/>}
            {Badge&&<Badge label="Advanced" tone="peri"/>}
            {Badge&&<Badge label="Info" tone="info"/>}
          </div>
          {SelectorSlider&&<SelectorSlider options={["Reskill","Upskill","Augment"]} label="Learning mode"/>}
          <p className="tile__p" style={{fontSize:13}}>Exactly one primary action per view — orange is reserved (Von Restorff). Every target clears 44px, including the 36px small button, which carries an expanded hit area.</p>
        </div>

        <div className="tile tile--w2">
          <span className="tile__grp">Forms</span>
          <h3 className="tile__h">One definition of valid.</h3>
          {TextField&&<TextField label="Work email" type="email" placeholder="you@example.com" width="100%" value={email} error={emailErr} onChange={e=>checkEmail(e.target.value)}/>}
          <div className="spec__row">
            {Button&&<Button label="Validate" size="sm" variant="outline" onClick={runValidate}/>}
            {Button&&<Button label="Clear" size="sm" variant="ghost" onClick={()=>{setEmail("");setEmailErr("");}}/>}
          </div>
          {TextField&&<TextField label="Full name" placeholder="Ada Lovelace" width="100%" hint="Hint text sits where the error will appear — no layout shift."/>}
          {TextField&&<TextField label="Disabled" placeholder="Not editable" width="100%" disabled/>}
          <p className="tile__p" style={{fontSize:13}}>Every form shares <span className="mono">Validators</span>, so the same mistake reads the same everywhere. Errors clear per field as you fix them, focus jumps to the first invalid field, and unsaved input is never discarded without asking.</p>
        </div>

        <div className="tile tile--w2">
          <span className="tile__grp">Components</span>
          <h3 className="tile__h">Every state, built.</h3>
          <p className="tile__p">Six states ship for every screen: empty · loading · partial · full · error · success. Most bad UIs are a "full" state with the other five missing.</p>
          {ProgressTrack&&<ProgressTrack label="Python for Data Scientists" value={3} total={8} unit="lesson"/>}
          {ProgressTrack&&<ProgressTrack label="Nearly there — greens near the goal" value={7} total={8} unit="lesson"/>}
          <div className="dvd"></div>
          {loading&&Skeleton?<Skeleton lines={3}/>:EmptyState&&<EmptyState compact icon="ri-book-open-line" title="No courses yet" message="Pick a track and your first lesson lands here." actionLabel="Browse" onAction={fakeLoad} style={{padding:"18px 16px"}}/>}
          <p className="tile__p" style={{fontSize:13}}>Press <b>Browse</b> to watch the empty state hand off to a skeleton — the Doherty answer for anything slower than 400ms.</p>
        </div>

        <div className="tile">
          <span className="tile__grp">Type</span>
          <div className="aa" style={{fontWeight:weight,letterSpacing:weight>=700?"-.04em":"-.02em"}}>Aa</div>
          <div className="wbtn">{[400,600,700,800].map(w=>
            <button key={w} aria-pressed={weight===w} onClick={()=>setWeight(w)}>{w}</button>)}</div>
          <p className="tile__p">Mulish — 700 display with tracking that scales by size, 400 body at 1.65. Roboto Mono carries numbers.</p>
        </div>

        <div className="tile">
          <span className="tile__grp">Tokens · 310</span>
          <h3 className="tile__h">Every decision, named.</h3>
          <div style={{display:"flex",flexDirection:"column",gap:6}}>
            <span className="tok"><i style={{background:"var(--brand)"}}></i>--brand</span>
            <span className="tok"><i style={{background:"var(--border-control)"}}></i>--border-control · 3:1</span>
            <span className="tok"><i style={{background:"var(--peri-500)"}}></i>--space-related · 8px</span>
          </div>
          <p className="tile__p">Change a token, every surface follows. No component hard-codes a value.</p>
        </div>

        <div className="tile">
          <span className="tile__grp">Theme</span>
          <h3 className="tile__h">Dark mode, free.</h3>
          <p className="tile__p">Every token flips on one <span className="mono">data-theme</span> flag. Navy bands stay constant by design.</p>
          {Button&&<Button label={theme==="dark"?"Back to light":"Flip this page"} size="sm" variant="outline" icon="ri-contrast-2-line" onClick={()=>setTheme(t=>t==="dark"?"light":"dark")}/>}
        </div>

        <div className="tile">
          <span className="tile__grp">Motion</span>
          <h3 className="tile__h">Three modes, not two.</h3>
          <p className="tile__p">Auto follows the OS, full plays anyway, reduced forces calm — and reduced makes content <b>visible</b>, never merely un-animated.</p>
          {Button&&<Button label={motionOn?"Pause motion":"Preview motion"} size="sm" variant="outline" icon={motionOn?"ri-pause-line":"ri-play-line"} onClick={toggleMotion}/>}
        </div>

        <div className="tile tile--w4">
          <span className="tile__grp">Law 05 · Proximity</span>
          <h3 className="tile__h">Space encodes relationship.</h3>
          <p className="tile__p">The highest-leverage rule in the system, and the one most often broken. Same elements, same type — only the gaps differ.</p>
          <div className="gapdemo">
            <div className="bad"><small>uniform 14px — no structure</small>
              {["First name","Last name","Work email"].map(l=><div key={l} style={{marginBottom:14}}><div className="lb">{l}</div><div className="fl"></div></div>)}</div>
            <div className="good"><small>ladder · related 8, group 18</small>
              <div style={{display:"flex",flexDirection:"column",gap:18}}>
                {["First name","Last name","Work email"].map(l=><div key={l} style={{display:"flex",flexDirection:"column",gap:4}}><div className="lb">{l}</div><div className="fl"></div></div>)}</div></div>
          </div>
        </div>

      </div></div>
    </section>

    <section className="sec" id="decisions" style={{background:"var(--surface-subtle)",borderBlock:"1px solid var(--border)"}}>
      <div className="wrap" data-reveal>
        <p className="kick"><i>02</i>The decision layer</p>
        <h2 className="sh2">Tokens make it consistent. These make it intuitive.</h2>
        <p className="lead">Most systems ship components and stop. You can build a perfectly on-brand, AA-passing, thoroughly confusing screen with those. So ten named laws govern how many choices a screen offers, how it groups them, what order they sit in and how fast it answers — each wired to a token, a component, or a review question.</p>
      </div>
      <div className="wrap"><div className="laws">
        {LAWS.map(l=><article className={"law"+(l.k?" law--key":"")} key={l.n}>
          <span className="law__n">{l.n}</span>
          <div><h3>{l.t}</h3><p>{l.p}</p><code>{l.c}</code></div>
        </article>)}
      </div>
      <div style={{display:"flex",gap:12,flexWrap:"wrap",marginTop:26}}>
        <a className="tile__lnk" href="guidelines/ux-laws.card.html">The 10 laws, in full <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
        <a className="tile__lnk" href="guidelines/ux-review.card.html">The pre-ship review gate <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
      </div></div>
    </section>

    <section className="sec" id="hardening">
      <div className="wrap" data-reveal>
        <p className="kick"><i>03</i>Hardening</p>
        <h2 className="sh2">No silent failures. No lost input.</h2>
        <p className="lead">Error handling is part of the system, not per-page improvisation — so a developer inherits it instead of inventing it. Try both of these; they're the real components.</p>
      </div>
      <div className="wrap"><div className="bento">
        <div className="tile">
          <p className="tile__k">SafetyNet</p>
          <h3 className="tile__h">Errors surface, deduped.</h3>
          <p className="tile__p">Uncaught errors and rejected promises become a friendly toast instead of a dead page. Press it — nothing else breaks.</p>
          {Button&&<Button label="Throw a background error" size="sm" variant="destructive" icon="ri-error-warning-line"
            onClick={()=>setTimeout(()=>{throw new Error("Simulated background failure (demo)");},0)}/>}
        </div>
        <div className="tile">
          <p className="tile__k">Validators</p>
          <h3 className="tile__h">One definition of valid.</h3>
          {TextField&&<TextField label="Work email" type="email" placeholder="you@example.com" width="100%" value={email} error={emailErr} onChange={e=>checkEmail(e.target.value)}/>}
          {Button&&<Button label="Validate" size="sm" variant="outline" onClick={runValidate}/>}
          <p className="tile__p">The same shared check every form uses, so the same mistake reads the same everywhere.</p>
        </div>
        <div className="tile">
          <p className="tile__k">EmptyState</p>
          <h3 className="tile__h">Never a dead end.</h3>
          {EmptyState&&<EmptyState compact icon="ri-book-open-line" title="No courses yet" message="Pick a track and your first lesson lands here." actionLabel="Browse" onAction={()=>toast({tone:"info",title:"Demo",message:"This is the real EmptyState component."})} style={{padding:"20px 16px"}}/>}
        </div>
        <div className="tile">
          <p className="tile__k">ErrorBoundary · ConfirmDialog</p>
          <h3 className="tile__h">Recoverable, always.</h3>
          <p className="tile__p">A crashed section renders a Try Again / Reload card rather than a blank page, and unsaved form input is never discarded without asking. Escape and outside-click close the top-most layer first.</p>
          <a className="tile__lnk" href="components/feedback/errors.card.html">Error handling specimens <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
        </div>
      </div></div>
    </section>

    <section className="sec" id="practice" style={{background:"var(--surface-subtle)",borderBlock:"1px solid var(--border)"}}>
      <div className="wrap galhead" data-reveal>
        <div>
          <p className="kick"><i>04</i>In practice</p>
          <h2 className="sh2">Already built with it.</h2>
        <p className="lead">Six real pages from this repo, each running live inside this one — not a screenshot. They load in sequence as you arrive so the landing stays fast; open any of them full size.</p>
        </div>
      </div>
      <div className="wrap">
        <div className="galb" ref={galRef}>
          {EXAMPLES.map(ex=>{
            const GAP=16,COLS=gw>1000?4:gw>640?2:1,ROW=152;
            const colW=(gw-GAP*(COLS-1))/COLS;
            const span=Math.min(ex.span,COLS);
            const tileW=Math.max(120,colW*span+GAP*(span-1));
            const rows=COLS===1?1:ex.rows;
            const tileH=ROW*rows+GAP*(rows-1);
            const portrait=ex.h>ex.w;
            const scale=portrait?tileH/ex.h:tileW/ex.w;
            const left=portrait?Math.round((tileW-ex.w*scale)/2):0;
            const on=!!shown[ex.src];
            return <figure className={"gitem"+(ex.span>1?" gitem--w2":"")+(ex.rows>1?" gitem--r2":"")} key={ex.src} style={{margin:0}}>
              <div className="gframe" style={{height:tileH}}>
                {on
                  ?<React.Fragment>
                      <iframe src={ex.src} title={ex.label} loading="lazy" tabIndex={-1}
                        width={ex.w} height={ex.h}
                        style={{transform:"scale("+scale+")",left:left,width:ex.w,height:ex.h}}></iframe>
                      <span className="gframe__veil" aria-hidden="true"></span>
                    </React.Fragment>
                  :<button className="gposter" onClick={()=>setShown(s=>({...s,[ex.src]:true}))}>
                      <span className="rf-i gspin" aria-hidden="true" style={{fontSize:20}}><i className="ri-loader-4-line"></i></span>
                      <b>Loading preview…</b>
                      <small>{ex.w}×{ex.h}</small>
                    </button>}
              </div>
              <figcaption className="gcap"><b>{ex.label}</b><a href={ex.src}>Open ↗</a></figcaption>
              <p className="gmeta">{ex.meta}</p>
            </figure>;
          })}
        </div>
      </div>
    </section>

    <div className="band">
      <div className="wrap" data-reveal>
        <p className="kick" style={{color:"var(--text-on-band-faint)"}}>The system in numbers</p>
        <div className="band__g" style={{marginTop:26}}>
          <div><b>{Counter?<Counter value={310}/>:"310"}</b><span>semantic tokens across both themes</span></div>
          <div><b>{Counter?<Counter value={33}/>:"33"}</b><span>components, all keyboard-operable</span></div>
          <div><b>{Counter?<Counter value={50}/>:"50"}/50</b><span>contrast pairs passing AA</span></div>
          <div><b>0</b><span>runtime CDN dependencies</span></div>
        </div>
      </div>
    </div>

    <section className="sec" id="principles">
      <div className="wrap" data-reveal>
        <p className="kick"><i>05</i>Principles</p>
        <h2 className="sh2">Five beliefs that break ties.</h2>
        <p className="lead">When a decision is ambiguous, these settle it — quote one line and move on.</p>
      </div>
      <div className="wrap"><div className="prs">
        {PRINCIPLES.map((p,i)=><article className="pr" key={p.t}>
          <span className="pr__i">{"0"+(i+1)}</span>
          <div><h3>{p.t}</h3><p>{p.p}</p></div>
        </article>)}
      </div></div>
    </section>

    <section className="sec" id="start" style={{background:"var(--surface-subtle)",borderTop:"1px solid var(--border)"}}>
      <div className="wrap" data-reveal>
        <p className="kick"><i>06</i>Start here</p>
        <h2 className="sh2">Three ways in.</h2>
        <p className="lead">Plain English, the living specimens, or two lines of code. However you come in, every component documents itself the same way.</p>
      </div>
      <div className="wrap">
        <h3 style={{margin:"clamp(28px,4vw,44px) 0 0",fontSize:"var(--fs-h4)",fontWeight:700,color:"var(--text-strong)"}}>How a component documents itself</h3>
        <p className="lead" style={{marginTop:10}}>Three files sit side by side for every component. The <span className="mono">.d.ts</span> is the contract, the <span className="mono">.prompt.md</span> is the judgement, and the <span className="mono">.jsx</span> is the implementation — which means a developer and an AI read the same source of truth.</p>
        <div className="anat">
          <div className="anat__c">
            <p className="anat__f">components/buttons/Button.d.ts</p>
            <p className="tile__p">What props exist, what each one means, which values are legal. Typed, so an editor completes it.</p>
            <pre className="code"><code>{'interface ButtonProps {\n  label?: string;\n  variant?: "primary"\n    | "secondary" | "outline"\n    | "ghost" | "destructive";\n  size?: "sm"|"md"|"lg";\n  icon?: string;   // RemixIcon\n  loading?: boolean;\n}'}</code></pre>
          </div>
          <div className="anat__c">
            <p className="anat__f">components/buttons/Button.prompt.md</p>
            <p className="tile__p">The part a type signature can't carry: when to reach for it, and what never to do with it.</p>
            <pre className="code"><code>{'One primary per view — orange\nis reserved (Von Restorff).\n\nsm is 36px tall, so it carries\n.rf-hit-pad to stay a legal\n44px target (Fitts).\n\nAlways pass `loading` for any\naction over 400ms (Doherty).'}</code></pre>
          </div>
          <div className="anat__c">
            <p className="anat__f">Using it</p>
            <p className="tile__p">Destructure from the namespace. No import path, no bundler, no build step.</p>
            <pre className="code"><code>{'const { Button } =\n  window.RefactoredDesignSystem_f0a141;\n\n<Button\n  label="Start Learning"\n  size="lg"\n  icon="ri-arrow-right-line"\n  onClick={begin}\n/>'}</code></pre>
            <a className="tile__lnk" href="HANDOFF.md">Full handoff guide <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
          </div>
        </div>
      </div>
      <div className="wrap"><div className="go">
        <div className="go__c">
          <span className="rf-icon-tile" aria-hidden="true" style={{"--tile":"44px",background:"var(--surface-brand-soft)",color:"var(--brand-press)"}}><span className="rf-i"><i className="ri-chat-smile-2-line"></i></span></span>
          <p className="tile__k">Anyone</p>
          <h3>Describe it, download it.</h3>
          <ol><li>Attach this design system in a Claude chat.</li><li>Say what you need — format, size, your words.</li><li>Preview, tweak in plain English, download.</li></ol>
          <button className="snip" onClick={()=>copy('Using the Refactored by Colaberry design system, create a [landing page / slide / email] at [size] for [topic]. Headline: [your words] — give me two directions.',"Starter prompt")}>
            <span className="cp">Copy</span>
            <code>"Using the Refactored by Colaberry design system, create a [landing page] for [topic]. Headline: [your words] — give me two directions."</code>
          </button>
        </div>
        <div className="go__c">
          <span className="rf-icon-tile" aria-hidden="true" style={{"--tile":"44px",background:"var(--surface-peri-soft)",color:"var(--peri-600)"}}><span className="rf-i"><i className="ri-palette-line"></i></span></span>
          <p className="tile__k">Designers</p>
          <h3>The living reference.</h3>
          <p className="tile__p">37 specimen cards: brand and logo rules, colour ramps with live contrast, the type scale, spacing ladder, motion recipes, icon sets, every component in both themes — plus the ten laws and the review gate.</p>
          <div style={{display:"flex",flexDirection:"column",gap:2,marginTop:"auto"}}>
            <a className="tile__lnk" href="guidelines/ux-laws.card.html">The 10 laws</a>
            <a className="tile__lnk" href="guidelines/a11y-contrast.card.html">Accessibility gate</a>
            <a className="tile__lnk" href="showcase.html">The system applied</a>
          </div>
        </div>
        <div className="go__c">
          <span className="rf-icon-tile" aria-hidden="true" style={{"--tile":"44px",background:"var(--surface-sky-soft)",color:"var(--sky-700)"}}><span className="rf-i"><i className="ri-code-s-slash-line"></i></span></span>
          <p className="tile__k">Developers</p>
          <h3>Two lines of code.</h3>
          <button className="snip" onClick={()=>copy('<link rel="stylesheet" href="styles.css">\n<script src="_ds_bundle.js"></script>\n\nconst { Button, TextField, SafetyNet } = window.RefactoredDesignSystem_f0a141;',"Install snippet")}>
            <span className="cp">Copy</span>
            <code>{'<link rel="stylesheet" href="styles.css">\n<script src="_ds_bundle.js"></script>\n\nconst { Button, SafetyNet } =\n  window.RefactoredDesignSystem_f0a141;'}</code>
          </button>
          <p className="tile__p">No build step, no npm install, no CDN. Every component reads tokens from CSS, so theming is a single attribute.</p>
          <a className="tile__lnk" href="HANDOFF.md">Developer handoff <span className="rf-i" aria-hidden="true"><i className="ri-arrow-right-line"></i></span></a>
        </div>
      </div></div>
    </section>

    {Footer&&<Footer assetsBase="assets" columns={[{head:"System",links:["What this is","Decisions","Principles"]},{head:"Reference",links:["Accessibility gate","The 10 laws"]},{head:"Applied",links:["Marketing site"]}]}
      onNavigate={l=>{const m={"What this is":"#what","Decisions":"#decisions","Principles":"#principles","Accessibility gate":"guidelines/a11y-contrast.card.html","The 10 laws":"guidelines/ux-laws.card.html","Marketing site":"showcase.html"};
        const t=m[l];if(!t)return;if(t.startsWith("#"))document.querySelector(t).scrollIntoView();else window.location.href=t;}}/>}
  </div>;
}
window.SystemLanding = SystemLanding;
