// THE GUN CASE — Pelican-style hard case + THRAXEL App + Music Box
const SCENE_PRESETS = [
  { id:'everyday',  name:'Everyday Warm', colors:['#FFB347'], pattern:'solid' },
  { id:'gameday',   name:'Game Day',      colors:['#C8102E','#FFFFFF'], pattern:'alt' },
  { id:'wedding',   name:'Wedding',       colors:['#FFE9C8'], pattern:'solid' },
  { id:'christmas', name:'Christmas',     colors:['#C8102E','#0E8C3A'], pattern:'alt' },
  { id:'july4',     name:'July 4th',      colors:['#C8102E','#FFFFFF','#1A4DCF'], pattern:'march' },
  { id:'halloween', name:'Halloween',     colors:['#FF7A00','#7A2DCF'], pattern:'pulse' },
];

// Pelican-style hard case rendered with CSS — long, flat, hinged
function PelicanCase({ caseOpen, setCaseOpen, mode, color, brightness, warmth, dim, preset, audioLevels, beatPulse }){
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf;
    const tick = () => { setT(performance.now()); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const stripColor = (i) => {
    if (mode === 'solid') return { c: color, glow: brightness/100 };
    if (mode === 'warm') {
      const k = warmth / 100;
      const r = Math.round(255*(1-k*0.4));
      const g = Math.round(180 + k*70);
      const b = Math.round(95 + k*155);
      return { c: `rgb(${r},${g},${b})`, glow: dim/100 };
    }
    if (mode === 'preset') {
      const p = SCENE_PRESETS.find(x=>x.id===preset) || SCENE_PRESETS[0];
      const phase = Math.floor(t/450);
      let c;
      if (p.pattern==='solid') c = p.colors[0];
      else if (p.pattern==='alt') c = p.colors[(i+phase)%p.colors.length];
      else if (p.pattern==='march') c = p.colors[(i + Math.floor(t/300))%p.colors.length];
      else c = p.colors[i%p.colors.length];
      const a = p.pattern==='pulse' ? 0.5 + 0.5*Math.sin(t/300 + i) : 0.9;
      return { c, glow: a };
    }
    if (mode === 'music') {
      const lvl = audioLevels[i] ?? beatPulse;
      const hue = 350 + lvl*30;
      return { c: `hsl(${hue}, 90%, ${30 + lvl*40}%)`, glow: 0.2 + lvl*0.9 };
    }
    return { c:'#FFB347', glow:0.7 };
  };

  // Latches — Pelican press-and-pull style
  const Latch = ({ left, right }) => (
    <div style={{
      position:'absolute',
      left, right,
      top: 'auto', bottom: '-9%',
      width: '7%', height: '36%',
      background:'linear-gradient(180deg,#4a4a52 0%,#2a2a2e 30%,#0a0a0a 100%)',
      border:'1.5px solid #000',
      borderRadius: '3px',
      boxShadow:'inset 0 1px 0 rgba(255,255,255,0.18), inset 0 -2px 4px rgba(0,0,0,0.7), 0 3px 8px rgba(0,0,0,0.7)',
      zIndex: 4,
      display:'flex', alignItems:'center', justifyContent:'center',
    }}>
    </div>
  );

  const Wheel = ({ left, right }) => (
    <div style={{position:'absolute',bottom:-12,left,right,width:'9%',height:'18%',
      background:'radial-gradient(ellipse at 40% 30%, #2a2a2e, #050505)',
      borderRadius:'2px 2px 8px 8px',
      border:'1px solid #000',
      display:'none',
      boxShadow:'0 4px 8px rgba(0,0,0,0.6)',
      zIndex:1}}/>
  );

  return (
    <div style={{
      position:'relative', flex:'1 1 60%', minWidth:0,
      aspectRatio:'5/4',
      background:'radial-gradient(ellipse at 50% 65%, #1a1a1e 0%, #050505 70%)',
      border:'1px solid #2a2a2e', overflow:'hidden',
    }}>
      {/* atmospheric idle */}
      {!caseOpen && (
        <div style={{position:'absolute',inset:0,opacity:0.3,pointerEvents:'none'}}>
          <div style={{position:'absolute',top:'25%',left:'-5%',width:'60%',height:'30%'}}>
            <LightningArc seed={1} opacity={0.4}/>
          </div>
          <div style={{position:'absolute',bottom:'18%',right:'-5%',width:'55%',height:'25%'}}>
            <LightningArc seed={3} opacity={0.3}/>
          </div>
        </div>
      )}
      {mode==='music' && caseOpen && (
        <div style={{position:'absolute',inset:0,opacity:0.6,pointerEvents:'none',mixBlendMode:'screen'}}>
          <div style={{position:'absolute',top:'15%',left:'-5%',width:'60%',height:'30%'}}><LightningArc seed={t/200|0} opacity={beatPulse}/></div>
          <div style={{position:'absolute',top:'45%',right:'-5%',width:'70%',height:'30%'}}><LightningArc seed={(t/180|0)+5} opacity={beatPulse*0.8}/></div>
        </div>
      )}

      {/* CASE BODY — Pelican Air 1745 proportions */}
      <div style={{
        position:'absolute', left:'50%', top:'56%',
        transform:'translate(-50%,-50%)',
        width:'88%', aspectRatio:'5.2/2.4',
        perspective: 1800,
      }}>
        {/* Drop shadow under case */}
        <div style={{
          position:'absolute', left:'-4%', right:'-4%', bottom:'-12%', height:'18%',
          background:'radial-gradient(ellipse at center, rgba(0,0,0,0.85), transparent 70%)',
          filter:'blur(12px)', zIndex:0,
        }}/>

        {/* Bottom shell */}
        <div style={{
          position:'absolute', inset:0,
          background:`
            linear-gradient(180deg, #2a2a2e 0%, #1a1a1e 8%, #0a0a0a 14%, #0a0a0a 86%, #1a1a1e 92%, #050505 100%)
          `,
          border:'2px solid #000',
          borderTop:'2px solid #3a3a40',
          borderRadius:'10px',
          boxShadow:`
            0 60px 100px rgba(0,0,0,0.85),
            inset 0 0 40px rgba(0,0,0,0.6),
            inset 0 4px 0 rgba(255,255,255,0.06),
            inset 0 -4px 0 rgba(0,0,0,0.5)
          `,
        }}>
          {/* Top edge highlight rim */}
          <div style={{position:'absolute',top:0,left:8,right:8,height:2,background:'linear-gradient(90deg,transparent,rgba(255,255,255,0.18),transparent)'}}/>

          {/* Vertical reinforcement ribs - more pelican-like */}
          {[0.12, 0.22, 0.32, 0.42, 0.58, 0.68, 0.78, 0.88].map((p,i) => (
            <div key={i} style={{
              position:'absolute', left:`${p*100}%`, top:'8%', bottom:'8%',
              width:3,
              background:'linear-gradient(90deg,rgba(0,0,0,0.85) 0%, rgba(255,255,255,0.06) 50%, rgba(0,0,0,0.85) 100%)',
              borderLeft:'1px solid rgba(0,0,0,0.6)',
              borderRight:'1px solid rgba(255,255,255,0.04)',
            }}/>
          ))}
          {/* Bottom rib edge highlights between ribs */}
          {[0.17, 0.27, 0.37, 0.5, 0.63, 0.73, 0.83].map((p,i) => (
            <div key={`h-${i}`} style={{
              position:'absolute', left:`${p*100}%`, top:'8%', bottom:'8%',
              width:1, background:'rgba(255,255,255,0.025)',
            }}/>
          ))}

          {/* Corner bumpers — pelican has rounded reinforced corners */}
          <div style={{position:'absolute',left:-6,top:-4,bottom:-4,width:18,background:'linear-gradient(90deg,#1a1a1e,#0a0a0a)',borderRadius:'8px',border:'1px solid #000'}}/>
          <div style={{position:'absolute',right:-6,top:-4,bottom:-4,width:18,background:'linear-gradient(90deg,#0a0a0a,#1a1a1e)',borderRadius:'8px',border:'1px solid #000'}}/>

          {/* Wheels at base corners */}
          <Wheel left="6%" right="auto"/>
          <Wheel left="auto" right="6%"/>

          {/* INTERIOR */}
          <div style={{
            position:'absolute', left:'4%', right:'4%', top:'8%', bottom:'8%',
            background:'#040404',
            boxShadow:'inset 0 0 50px rgba(0,0,0,1), inset 0 4px 8px rgba(0,0,0,0.95)',
            opacity: caseOpen ? 1 : 0.15,
            transition:'opacity .8s ease',
            border:'1px solid #000',
          }}>
            {/* egg-crate foam */}
            <div style={{
              position:'absolute',inset:0,
              backgroundImage:'radial-gradient(circle at 50% 50%, #1a1a1e 0%, transparent 45%)',
              backgroundSize:'18px 14px',
              opacity: 0.5,
              mixBlendMode:'screen',
            }}/>
            {/* 4 strips */}
            <div style={{position:'absolute',inset:'8% 5%',display:'flex',flexDirection:'column',gap:'3%',justifyContent:'space-between'}}>
              {[0,1,2,3].map(i => {
                const { c, glow } = stripColor(i);
                const visible = caseOpen;
                return (
                  <div key={i} style={{
                    flex:1, position:'relative',
                    background: visible ? c : '#0e0e10',
                    borderRadius: 1,
                    transition:'background .25s',
                    boxShadow: visible ? `0 0 ${22+glow*40}px ${glow*1.4}px ${c}, 0 0 ${70+glow*60}px ${c}` : 'none',
                    opacity: visible ? glow : 0.3,
                  }}>
                    <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'space-around'}}>
                      {Array.from({length:32}).map((_,j)=>(
                        <div key={j} style={{
                          width:2, height:'55%',
                          background:'#fff',
                          opacity: visible ? (0.4 + glow*0.4) : 0.1,
                          boxShadow: visible ? '0 0 6px #fff' : 'none',
                        }}/>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Top shell (lid) */}
        <div style={{
          position:'absolute', inset:0,
          transformOrigin:'top center',
          transform: caseOpen ? 'rotateX(-118deg) translateZ(0)' : 'rotateX(0deg)',
          transition:'transform 1.4s cubic-bezier(0.6,0.05,0.2,1)',
          background:`
            linear-gradient(180deg, #2a2a2e 0%, #1a1a1e 6%, #0e0e10 14%, #0a0a0a 50%, #0a0a0a 86%, #050505 100%)
          `,
          border:'2px solid #000',
          borderTop:'2px solid #3a3a40',
          borderRadius:'10px',
          boxShadow:`
            0 -2px 12px rgba(0,0,0,0.7),
            inset 0 4px 0 rgba(255,255,255,0.08),
            inset 0 -4px 0 rgba(0,0,0,0.5)
          `,
          backfaceVisibility:'hidden',
        }}>
          {/* Top edge highlight */}
          <div style={{position:'absolute',top:0,left:8,right:8,height:2,background:'linear-gradient(90deg,transparent,rgba(255,255,255,0.22),transparent)'}}/>

          {/* Recessed center panel — perfectly centered THRAXEL with gold illumination */}
          <div style={{
            position:'absolute', left:'24%', right:'24%', top:'30%', bottom:'30%',
            background:'linear-gradient(180deg,#050505,#0a0a0a)',
            boxShadow:`
              inset 0 3px 6px rgba(0,0,0,0.95),
              inset 0 -2px 4px rgba(255,255,255,0.04),
              inset 3px 0 4px rgba(0,0,0,0.6),
              inset -3px 0 4px rgba(0,0,0,0.6)
            `,
            borderRadius: 3,
            display:'flex', alignItems:'center', justifyContent:'center',
            zIndex: 3,
          }}>
            <div style={{
              fontFamily:'Orbitron,sans-serif',
              fontWeight:900, fontSize:'clamp(20px,2.6vw,38px)',
              letterSpacing:'0.42em',
              paddingLeft:'0.42em',
              color:'#e8e8eb',
              WebkitTextStroke:'1px rgba(200,16,46,0.6)',
              textShadow:'0 0 18px rgba(200,16,46,0.22)',
            }}>THRAXEL</div>
          </div>

          {/* Vertical ribs on lid - skip the center panel zone (24%-76%) */}
          {[0.06, 0.12, 0.18, 0.82, 0.88, 0.94].map((p,i) => (
            <div key={i} style={{
              position:'absolute', left:`${p*100}%`, top:'8%', bottom:'8%',
              width:3,
              background:'linear-gradient(90deg,rgba(0,0,0,0.85) 0%, rgba(255,255,255,0.06) 50%, rgba(0,0,0,0.85) 100%)',
              borderLeft:'1px solid rgba(0,0,0,0.6)',
              borderRight:'1px solid rgba(255,255,255,0.04)',
            }}/>
          ))}

          {/* Corner bumpers */}
          <div style={{position:'absolute',left:-6,top:-4,bottom:-4,width:18,background:'linear-gradient(90deg,#1a1a1e,#0a0a0a)',borderRadius:'8px',border:'1px solid #000'}}/>
          <div style={{position:'absolute',right:-6,top:-4,bottom:-4,width:18,background:'linear-gradient(90deg,#0a0a0a,#1a1a1e)',borderRadius:'8px',border:'1px solid #000'}}/>

          {/* Recessed handle on top edge */}
          <div style={{
            position:'absolute', top:'-2.5%', left:'44%', right:'44%', height:'10%',
            background:'linear-gradient(180deg,#050505,#0a0a0a)',
            border:'1px solid #000', borderRadius:'10px 10px 4px 4px',
            boxShadow:'inset 0 2px 5px rgba(0,0,0,0.95), 0 1px 0 rgba(255,255,255,0.05)',
          }}/>

          {/* latches — 4 stainless press-and-pull */}
          <Latch left="4%" right="auto"/>
          <Latch left="28%" right="auto"/>
          <Latch left="auto" right="28%"/>
          <Latch left="auto" right="4%"/>
        </div>

        {/* hinge line */}
        <div style={{
          position:'absolute', bottom:0, left:0, right:0, height:8,
          background:'linear-gradient(180deg,#000,#1a1a1e 50%,#000)',
          borderTop:'1px solid #2a2a2e',
          borderBottom:'1px solid #000',
          zIndex:5,
        }}/>
      </div>

      {/* tap to open */}
      {!caseOpen && (
        <button onClick={()=>setCaseOpen(true)} style={{
          position:'absolute', inset:0, zIndex:5,
          display:'flex', alignItems:'flex-end', justifyContent:'center',
          padding:'0 0 5%',
        }}>
          <div className="btn-red">Tap to Open the Case</div>
        </button>
      )}
      {caseOpen && (
        <button onClick={()=>setCaseOpen(false)} style={{
          position:'absolute', top:16, right:16, zIndex:5,
          padding:'8px 14px', fontSize:11,
          fontFamily:'Orbitron,sans-serif', fontWeight:700, letterSpacing:'0.18em',
          color:'var(--thraxel-light-grey)', border:'1px solid #2a2a2e',
        }}>CLOSE CASE</button>
      )}
    </div>
  );
}

// THRAXEL App in a phone frame
function ThraxelApp({ mode, setMode, color, setColor, brightness, setBrightness, warmth, setWarmth, dim, setDim, preset, setPreset, micState, requestMic, beatTap }) {
  const tabs = [
    { id:'solid',  label:'Color' },
    { id:'warm',   label:'Warm' },
    { id:'preset', label:'Scenes' },
    { id:'music',  label:'Music' },
  ];
  return (
    <div style={{
      flex:'0 0 360px', maxWidth:360,
      display:'flex', flexDirection:'column', alignItems:'center',
    }}>
      {/* Phone bezel */}
      <div style={{
        width:'100%', aspectRatio:'9/19',
        background:'linear-gradient(180deg,#0a0a0a,#050505)',
        border:'2px solid #1a1a1e',
        borderRadius:32,
        padding:8,
        boxShadow:'0 30px 80px rgba(0,0,0,0.7), inset 0 1px 0 rgba(255,255,255,0.08)',
        position:'relative',
      }}>
        {/* Notch */}
        <div style={{
          position:'absolute', top:6, left:'50%', transform:'translateX(-50%)',
          width:'30%', height:18, background:'#050505', borderRadius:'0 0 12px 12px', zIndex:5,
        }}/>
        {/* Screen */}
        <div style={{
          width:'100%', height:'100%',
          background:'linear-gradient(180deg,#0e0e10 0%,#050505 100%)',
          borderRadius:24,
          overflow:'hidden',
          display:'flex', flexDirection:'column',
        }}>
          {/* Status bar */}
          <div style={{
            display:'flex', justifyContent:'space-between', alignItems:'center',
            padding:'14px 24px 8px', fontSize:11, color:'#fff',
            fontFamily:'Orbitron,sans-serif', fontWeight:700, letterSpacing:'0.1em',
          }}>
            <span>9:41</span>
            <span style={{display:'flex',gap:4,alignItems:'center'}}>
              <span style={{width:14,height:8,border:'1px solid #fff',borderRadius:1,position:'relative'}}>
                <span style={{position:'absolute',inset:1,background:'#fff',width:'80%'}}/>
              </span>
            </span>
          </div>

          {/* App header */}
          <div style={{
            padding:'18px 20px 14px',
            borderBottom:'1px solid #2a2a2e',
            display:'flex', alignItems:'center', justifyContent:'space-between',
          }}>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <img src="public/img/thraxel-logo.png" style={{height:28}}/>
              <div>
                <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:11,letterSpacing:'0.22em',color:'#fff'}}>THRAXEL</div>
                <div style={{fontSize:8,color:'var(--thraxel-light-grey)',letterSpacing:'0.18em',fontFamily:'Orbitron,sans-serif',fontWeight:700,marginTop:2}}>CONTROLLER</div>
              </div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:6}}>
              <span style={{width:6,height:6,borderRadius:'50%',background:'#3aff7a',boxShadow:'0 0 6px #3aff7a'}}/>
              <span style={{fontSize:8,fontFamily:'Orbitron,sans-serif',fontWeight:700,letterSpacing:'0.16em',color:'var(--thraxel-light-grey)'}}>ONLINE</span>
            </div>
          </div>

          {/* Tabs */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',borderBottom:'1px solid #2a2a2e'}}>
            {tabs.map(t => (
              <button key={t.id} onClick={()=>{ if(t.id==='music' && micState==='idle') requestMic(); setMode(t.id); }} style={{
                padding:'12px 4px', fontSize:9, fontFamily:'Orbitron,sans-serif', fontWeight:700, letterSpacing:'0.14em',
                textTransform:'uppercase',
                color: mode===t.id ? '#fff' : 'var(--thraxel-mid-grey)',
                borderBottom: mode===t.id ? '2px solid var(--thraxel-red)' : '2px solid transparent',
                background: mode===t.id ? 'rgba(200,16,46,0.06)' : 'transparent',
              }}>{t.label}</button>
            ))}
          </div>

          <div style={{padding:18, flex:1, overflow:'auto'}}>
            {mode==='solid' && (
              <div style={{display:'flex',flexDirection:'column',gap:16}}>
                <div className="fld">
                  <label>Color</label>
                  <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:6}}>
                    {['#FFB347','#FFFFFF','#C8102E','#FF7A00','#1A4DCF','#0E8C3A','#7A2DCF','#FFE9C8'].map(c=>(
                      <button key={c} onClick={()=>setColor(c)} style={{
                        height:32, background:c,
                        border: color===c ? '2px solid #fff' : '1px solid #2a2a2e',
                        boxShadow: color===c ? `0 0 10px ${c}` : 'none',
                      }}/>
                    ))}
                  </div>
                  <input type="color" value={color} onChange={e=>setColor(e.target.value)} style={{width:'100%',height:32,padding:0,border:'1px solid #2a2a2e',background:'#0a0a0a'}}/>
                </div>
                <Slider label="Brightness" value={brightness} onChange={setBrightness} unit="%"/>
              </div>
            )}
            {mode==='warm' && (
              <div style={{display:'flex',flexDirection:'column',gap:16}}>
                <Slider label="Warmth" value={warmth} onChange={setWarmth} hintLeft="2200K" hintRight="6500K"/>
                <Slider label="Dimmer" value={dim} onChange={setDim} unit="%"/>
                <div style={{
                  padding:12,border:'1px solid #2a2a2e',
                  background:`linear-gradient(135deg, hsl(${30+warmth*0.6}, ${80-warmth*0.7}%, ${50+warmth*0.2}%), hsl(${30+warmth*0.6}, 50%, ${30+warmth*0.2}%))`,
                  fontSize:9,letterSpacing:'0.16em',fontFamily:'Orbitron,sans-serif',fontWeight:700, color:'#0a0a0a',
                }}>RGBWW PREVIEW</div>
              </div>
            )}
            {mode==='preset' && (
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                {SCENE_PRESETS.map(p=>(
                  <button key={p.id} onClick={()=>setPreset(p.id)} style={{
                    padding:10, textAlign:'left',
                    background: preset===p.id ? 'rgba(200,16,46,0.1)' : '#0a0a0a',
                    border: preset===p.id ? '1px solid var(--thraxel-red)' : '1px solid #2a2a2e',
                  }}>
                    <div style={{display:'flex',gap:3,marginBottom:6}}>
                      {p.colors.map((c,i)=>(<div key={i} style={{width:10,height:10,background:c,boxShadow:`0 0 6px ${c}`}}/>))}
                    </div>
                    <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.12em',textTransform:'uppercase',color:'#fff'}}>{p.name}</div>
                  </button>
                ))}
              </div>
            )}
            {mode==='music' && (
              <div style={{display:'flex',flexDirection:'column',gap:14}}>
                <div style={{
                  padding:12,border:'1px solid #2a2a2e',background:'#0a0a0a',
                  display:'flex',alignItems:'center',gap:10,
                }}>
                  <Icons.mic/>
                  <div style={{flex:1}}>
                    <div style={{fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:9,letterSpacing:'0.16em',textTransform:'uppercase',color:'#fff'}}>{
                      micState==='live' ? 'Mic Live' :
                      micState==='denied' ? 'Mic Denied' :
                      micState==='requesting' ? 'Requesting…' : 'Tap to Enable'
                    }</div>
                    <div style={{fontSize:9,color:'var(--thraxel-light-grey)',marginTop:2}}>{
                      micState==='live' ? 'Strips reactive to ambient audio' :
                      micState==='denied' ? 'Use TAP TO BEAT' :
                      'Allow mic in browser'
                    }</div>
                  </div>
                  {micState!=='live' && <button onClick={requestMic} className="btn-red" style={{padding:'6px 10px',fontSize:9}}>Enable</button>}
                </div>
                <button onMouseDown={beatTap} onTouchStart={beatTap} style={{
                  padding:'18px',background:'#0a0a0a',border:'1px solid #2a2a2e',
                  fontFamily:'Orbitron,sans-serif',fontWeight:900,fontSize:14,letterSpacing:'0.2em',
                  color:'var(--thraxel-red)',
                }}>TAP TO BEAT</button>
              </div>
            )}
          </div>

          <div style={{padding:'10px 16px',borderTop:'1px solid #2a2a2e',background:'#0a0a0a',
            fontSize:8,fontFamily:'Orbitron,sans-serif',fontWeight:700,letterSpacing:'0.18em',color:'var(--thraxel-mid-grey)',
            display:'flex',justifyContent:'space-between',
          }}>
            <span>4 STRIPS · 128 LEDs</span>
            <span>v3.2.1</span>
          </div>
        </div>
      </div>
      <div style={{
        marginTop:16, fontFamily:'Orbitron,sans-serif',fontWeight:700,fontSize:10,letterSpacing:'0.2em',
        color:'var(--thraxel-light-grey)',textTransform:'uppercase',
      }}>iOS · Android · Web</div>
    </div>
  );
}

function Slider({ label, value, onChange, unit='', hintLeft, hintRight }){
  return (
    <div className="fld">
      <label style={{display:'flex',justifyContent:'space-between'}}>
        <span>{label}</span><span>{value}{unit}</span>
      </label>
      <input type="range" min={0} max={100} value={value} onChange={e=>onChange(+e.target.value)} style={{accentColor:'var(--thraxel-red)'}}/>
      {(hintLeft||hintRight) && (
        <div style={{display:'flex',justifyContent:'space-between',fontSize:9,color:'var(--thraxel-mid-grey)',fontFamily:'Orbitron,sans-serif',fontWeight:700,letterSpacing:'0.14em'}}>
          <span>{hintLeft}</span><span>{hintRight}</span>
        </div>
      )}
    </div>
  );
}

function GunCaseSection() {
  const [caseOpen, setCaseOpen] = useState(false);
  const [mode, setMode] = useState('preset');
  const [color, setColor] = useState('#C8102E');
  const [brightness, setBrightness] = useState(85);
  const [warmth, setWarmth] = useState(20);
  const [dim, setDim] = useState(80);
  const [preset, setPreset] = useState('everyday');
  const [micState, setMicState] = useState('idle');
  const [audioLevels, setAudioLevels] = useState([0,0,0,0]);
  const [beatPulse, setBeatPulse] = useState(0);
  const audioRef = useRef(null);

  const requestMic = async () => {
    setMicState('requesting');
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio:true });
      const ctx = new (window.AudioContext||window.webkitAudioContext)();
      const src = ctx.createMediaStreamSource(stream);
      const analyser = ctx.createAnalyser();
      analyser.fftSize = 64;
      src.connect(analyser);
      audioRef.current = { ctx, analyser, data: new Uint8Array(analyser.frequencyBinCount) };
      setMicState('live');
      const tick = () => {
        if (!audioRef.current) return;
        analyser.getByteFrequencyData(audioRef.current.data);
        const bins = audioRef.current.data;
        const n = bins.length;
        const lvls = [0,1,2,3].map(i => {
          let s=0,c=0;
          for (let j=Math.floor(i*n/4); j<Math.floor((i+1)*n/4); j++){ s+=bins[j]; c++; }
          return Math.min(1, (s/c)/180);
        });
        setAudioLevels(lvls);
        requestAnimationFrame(tick);
      };
      tick();
    } catch (e) { setMicState('denied'); }
  };

  const beatTap = () => {
    setBeatPulse(1);
    setAudioLevels([Math.random(),Math.random(),Math.random(),Math.random()]);
    setTimeout(()=>setBeatPulse(0.2),120);
    setTimeout(()=>setBeatPulse(0),350);
  };

  return (
    <section id="gun-case-demo" style={{position:'relative',padding:'140px 64px 160px',overflow:'hidden'}}>
      <div className="smoke"/>
      <div style={{position:'absolute',inset:0,background:'radial-gradient(ellipse 60% 40% at 30% 20%, rgba(200,16,46,0.06), transparent 60%)',pointerEvents:'none'}}/>
      <div style={{maxWidth:1440,margin:'0 auto',position:'relative',zIndex:2}}>
        <div className="eyebrow-red" style={{marginBottom:18}}>THE DEMO WE BRING TO YOUR DRIVEWAY</div>
        <ChromeTitle size={'clamp(48px,8vw,112px)'}>Open the case.</ChromeTitle>
        <div style={{marginTop:14}}><RedTitle size={'clamp(28px,4.5vw,64px)'}>Light up your world.</RedTitle></div>
        <p style={{maxWidth:680,marginTop:24,fontSize:18,color:'var(--thraxel-light-grey)'}}>This is the same hard case we walk into your driveway with. Four RGBWW strips, controlled live from the Thraxel app. Tap to open. Grant mic access for Music Box.</p>

        <div style={{display:'flex',gap:48,marginTop:60,flexWrap:'wrap',alignItems:'flex-start',justifyContent:'center'}}>
          <PelicanCase {...{caseOpen,setCaseOpen,mode,color,brightness,warmth,dim,preset,audioLevels,beatPulse}}/>
          <ThraxelApp {...{mode,setMode,color,setColor,brightness,setBrightness,warmth,setWarmth,dim,setDim,preset,setPreset,micState,requestMic,beatTap}}/>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { GunCaseSection });
