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

// ── CONSTANTS ──────────────────────────────────────────────────────────────
const BUY_LINK = "https://app.dexhunter.io/swap?tokenIdSell=&tokenIdBuy=97075bf380e65f3c63fb733267adbb7d42eec574428a754d2abca55b436861726c6573207468652043686164";
const CONTRACT = "97075bf380e65f3c63fb733267adbb7d42eec574428a754d2abca55b";
const X_LINK   = "https://x.com/charles_thechad";
const DISCORD_LINK = "https://discord.gg/8MyDZRQuWa";

const MEME_CATS = [
  { id:"fud",     label:"FUD SLAYER",         color:"#0033AD", memes:[
    { c:"They said Cardano was dead.\nCharles added another plate." },
    { c:"FUD entered the chat.\nChad entered the gym." },
    { c:"Bearish analyst.\nBullish jaw." },
    { c:"Every bad take\nis just more reps." },
    { c:"Down 80%.\nUp 100 pushups." },
    { c:"The obituary was fake.\nThe grind was not." },
  ]},
  { id:"brick",   label:"BRICK BY BRICK",     color:"#00B4FF", memes:[
    { c:"Not a roadmap.\nA training montage." },
    { c:"Every post. Every raid.\nEvery brick." },
    { c:"No shortcuts.\nJust reps." },
    { c:"Slow and steady\nbuilds the dojo." },
    { c:"Day 1 felt impossible.\nDay 365 felt easy." },
    { c:"The wall is built\nwith consistent memes." },
  ]},
  { id:"jeets",   label:"JEETS OUT",          color:"#5B8FFF", memes:[
    { c:"Jeets sold.\nChad evolved." },
    { c:"Paper hands left.\nDiamond reps remain." },
    { c:"You can't train\nif you already quit." },
    { c:"Sold at the bottom.\nDeleted from the dojo." },
    { c:"The exit door has\nno handle from outside." },
    { c:"Weak hands out.\nStrong memes in." },
  ]},
  { id:"green",   label:"GREEN CANDLE ARC",   color:"#00B4FF", memes:[
    { c:"No promises.\nJust vibes." },
    { c:"Green candle energy.\nRed candle same energy." },
    { c:"Up or down,\nthe reps don't change." },
    { c:"Price pumps: nice.\nMemes pump: mandatory." },
    { c:"The candle is green.\nTraining continues anyway." },
    { c:"It was never about the price.\nIt was about the reps." },
  ]},
  { id:"cardano", label:"CARDANO CHAD MODE",  color:"#0033AD", memes:[
    { c:"Every chain has dogs.\nCardano has a Chad." },
    { c:"Built on Cardano.\nNo rush. No regrets." },
    { c:"Peer-reviewed\nmemes only." },
    { c:"ADA in wallet.\nChad in heart." },
    { c:"Ouroboros-powered\ngrind." },
    { c:"The blockchain that\npeer-reviews its gains." },
  ]},
];

const EPISODES = [
  { num:"01", title:"BRICK BY BRICK",       desc:"Charles walks through the snow carrying Cardano bricks. The timeline watches. He doesn't." },
  { num:"02", title:"THE FUD GYM",          desc:"Every hate comment turns into a dumbbell. He has not stopped lifting since 2018." },
  { num:"03", title:"JEETS AT THE GATE",    desc:"Paper hands try to enter the dojo. Charles points to the exit. Silently." },
  { num:"04", title:"THE CHAD AWAKENING",   desc:"Green candle appears. No promises. Just vibes." },
  { num:"05", title:"RAID OF THE TIMELINE", desc:"The community drops memes like an anime battle sequence. Jeets flee. Maxis stay." },
];

const GIF_CATS = [
  { id:"fud",     label:"FUD SLAYER",        gifs:[
    { label:"ENTER THE GYM",   desc:"Deploy when haters arrive." },
    { label:"ADD A PLATE",     desc:"For every bad take." },
    { label:"CHAD STARE",      desc:"The silent response." },
    { label:"FUD BLOCKED",     desc:"Deflect with ease." },
    { label:"ZERO FUCKS",      desc:"Unbothered. Undefeated." },
    { label:"WALK AWAY",       desc:"Let them talk." },
  ]},
  { id:"brick",   label:"BRICK BY BRICK",    gifs:[
    { label:"DAILY REP",       desc:"Show up every day." },
    { label:"CARRY THE LOAD",  desc:"For grind posts." },
    { label:"SLOW WALK",       desc:"Steady pace, steady gains." },
    { label:"STACK",           desc:"Building, always building." },
    { label:"FOCUSED",         desc:"No distractions." },
    { label:"NODS",            desc:"Acknowledgment of the grind." },
  ]},
  { id:"jeets",   label:"JEETS OUT",         gifs:[
    { label:"THE POINT",       desc:"Exit is that way." },
    { label:"BYE BYE",         desc:"A dignified farewell." },
    { label:"SHRUG",           desc:"Paper hands are inevitable." },
    { label:"DOOR",            desc:"Hold it open. Then close it." },
    { label:"WAVE",            desc:"See you never." },
    { label:"EVOLVE",          desc:"After they leave, you grow." },
  ]},
  { id:"green",   label:"GREEN CANDLE ARC",  gifs:[
    { label:"POWER UP",        desc:"For green candle moments." },
    { label:"CALM NOD",        desc:"Expected. Moving on." },
    { label:"LIFT",            desc:"Up we go." },
    { label:"SMILE",           desc:"Restrained celebration." },
    { label:"FLEX",            desc:"But make it subtle." },
    { label:"CONTINUE",        desc:"Training never stops." },
  ]},
  { id:"cardano", label:"CARDANO CHAD MODE", gifs:[
    { label:"CARDANO REP",     desc:"For the true believers." },
    { label:"ADA POWER",       desc:"The chain endures." },
    { label:"PEER REVIEWED",   desc:"Verified. Tested. Chad." },
    { label:"OUROBOROS",       desc:"Infinite grind." },
    { label:"MAXIS ONLY",      desc:"No tourists." },
    { label:"BUILT DIFFERENT", desc:"On the best chain." },
  ]},
];

// ── UTILS ──────────────────────────────────────────────────────────────────
function useToast() {
  const [toasts, setToasts] = useState([]);
  const show = useCallback((msg) => {
    const id = Date.now() + Math.random();
    setToasts(t => [...t, { id, msg }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2400);
  }, []);
  return [toasts, show];
}

function useReveal(ref) {
  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    el.classList.add("reveal");
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { el.classList.add("visible"); obs.disconnect(); }
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
}

function copy(text, show, msg) {
  navigator.clipboard.writeText(text).then(() => show(msg || "COPIED"));
}

function shareX(text) {
  window.open(`https://x.com/intent/tweet?text=${encodeURIComponent(text + " $CHAD #CharlesTheChad #Cardano")}`, "_blank");
}

// ── TINY SHARED ────────────────────────────────────────────────────────────
const C = { bg:"#06070e", surf:"#0c0e1a", blue:"#0033AD", accent:"#00B4FF", text:"#f0f2ff" };

function Bebas({ size, style={}, children }) {
  return <span style={{ fontFamily:"'Bebas Neue',sans-serif", fontSize:size, letterSpacing:"0.04em", ...style }}>{children}</span>;
}

function Label({ children, style={} }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:18, ...style }}>
      <span style={{ display:"block", width:28, height:1, background:C.accent }}></span>
      <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:11, fontWeight:700, letterSpacing:"0.35em", color:C.accent, textTransform:"uppercase" }}>{children}</span>
      <span style={{ display:"block", width:28, height:1, background:C.accent }}></span>
    </div>
  );
}

function CornerBox({ children, style={} }) {
  const s = { position:"relative", border:"1px solid rgba(0,180,255,0.18)", ...style };
  const corner = (t,l,b,r) => ({
    position:"absolute", width:14, height:14,
    top:t!=null?-1:undefined, bottom:b!=null?-1:undefined,
    left:l!=null?-1:undefined, right:r!=null?-1:undefined,
    borderTop:t!=null?"2px solid "+C.accent:undefined,
    borderLeft:l!=null?"2px solid "+C.accent:undefined,
    borderBottom:b!=null?"2px solid "+C.accent:undefined,
    borderRight:r!=null?"2px solid "+C.accent:undefined,
  });
  return (
    <div style={s}>
      <div style={corner(0,0)} /><div style={corner(0,undefined,undefined,0)} />
      <div style={corner(undefined,0,0)} /><div style={corner(undefined,undefined,0,0)} />
      {children}
    </div>
  );
}

function ActionBtn({ label, onClick, primary=false }) {
  const [h, sH] = useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={()=>sH(true)} onMouseLeave={()=>sH(false)}
      style={{
        background: h ? "rgba(0,180,255,0.12)" : primary ? "rgba(0,51,173,0.25)" : "transparent",
        border:"none", color: h ? C.accent : "rgba(0,180,255,0.55)",
        fontFamily:"'Exo 2',sans-serif", fontSize:10, fontWeight:700,
        letterSpacing:"0.18em", textTransform:"uppercase",
        padding:"10px 14px", cursor:"pointer", transition:"all 0.15s",
        borderRight:"1px solid rgba(0,180,255,0.08)",
      }}>{label}</button>
  );
}

function BuyBtn({ large }) {
  const [h, sH] = useState(false);
  return (
    <a href={BUY_LINK} target="_blank" rel="noopener noreferrer"
      onMouseEnter={()=>sH(true)} onMouseLeave={()=>sH(false)}
      style={{
        display:"inline-flex",
        alignItems:"center",
        justifyContent:"center",
        background: h ? C.accent : C.blue,
        color: h ? C.bg : C.text,
        fontFamily:"'Bebas Neue',sans-serif",
        fontSize: large ? 26 : 17,
        lineHeight:1,
        letterSpacing:"0.12em",
        padding: large ? "17px 48px" : "11px 26px",
        border:`2px solid ${C.accent}`,
        transition:"all 0.2s",
        cursor:"pointer",
        animation:"pulse-glow 3s ease-in-out infinite",
      }}>BUY $CHAD</a>
  );
}

function Placeholder({ label="anime art", ratio=75 }) {
  return (
    <div style={{ width:"100%", paddingBottom:`${ratio}%`, position:"relative", background:"rgba(0,30,80,0.15)", flexShrink:0 }}>
      <div style={{
        position:"absolute", inset:0,
        backgroundImage:"repeating-linear-gradient(45deg,transparent,transparent 10px,rgba(0,51,173,0.045) 10px,rgba(0,51,173,0.045) 20px)",
        display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:6,
      }}>
        <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:9, color:"rgba(0,180,255,0.22)", letterSpacing:"0.25em", textTransform:"uppercase" }}>{label}</span>
      </div>
    </div>
  );
}

// ── NAV ───────────────────────────────────────────────────────────────────
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 50);
    window.addEventListener("scroll", fn);
    return () => window.removeEventListener("scroll", fn);
  }, []);
  const link = (label, href) => {
    const [h, sH] = useState(false);
    return (
      <a key={label} href={href}
        target={href.startsWith("http") ? "_blank" : undefined}
        rel={href.startsWith("http") ? "noopener noreferrer" : undefined}
        onMouseEnter={()=>sH(true)} onMouseLeave={()=>sH(false)}
        style={{ display:"inline-flex", alignItems:"center", height:44, fontFamily:"'Exo 2',sans-serif", fontSize:12, fontWeight:700,
          lineHeight:1,
          letterSpacing:"0.18em", color: h ? C.accent : "rgba(240,242,255,0.45)",
          transition:"color 0.2s" }}>{label}</a>
    );
  };
  return (
    <nav style={{
      position:"fixed", top:0, left:0, right:0, zIndex:100,
      height:78, padding:"0 48px",
      display:"flex", alignItems:"center", justifyContent:"space-between",
      background: scrolled ? "rgba(6,7,14,0.96)" : "transparent",
      backdropFilter: scrolled ? "blur(12px)" : "none",
      borderBottom: scrolled ? "1px solid rgba(0,180,255,0.08)" : "none",
      transition:"all 0.3s",
    }}>
      <Bebas size={20} style={{ letterSpacing:"0.18em", color:C.text, lineHeight:1 }}>$CHAD</Bebas>
      <div style={{ display:"flex", alignItems:"center", gap:32, height:"100%" }}>
        {[["CONTENT","https://memedepot.com/d/charles-thechad"]].map(([l,h]) => link(l,h))}
        <BuyBtn />
      </div>
    </nav>
  );
}

// ── HERO ──────────────────────────────────────────────────────────────────
function Hero() {
  return (
    <section style={{ position:"relative", minHeight:"100vh", display:"flex", alignItems:"center", overflow:"hidden", background:C.bg }}>
      {/* Character art */}
      <div style={{ position:"absolute", right:0, top:0, bottom:0, width:"62%", zIndex:0 }}>
        <img src="uploads/assets-1779894315781.png" alt="Charles the Chad"
          style={{ width:"100%", height:"100%", objectFit:"cover", objectPosition:"center top" }} />
        <div style={{ position:"absolute", inset:0, background:"linear-gradient(90deg,#06070e 0%,rgba(6,7,14,0.75) 38%,rgba(6,7,14,0.08) 100%)" }} />
        <div style={{ position:"absolute", inset:0, background:"linear-gradient(180deg,transparent 55%,#06070e 100%)" }} />
      </div>

      {/* Speed lines overlay */}
      <div className="speed-lines" style={{ position:"absolute", inset:0, zIndex:1, opacity:0.7 }} />

      {/* Left accent bar */}
      <div style={{ position:"absolute", top:0, left:0, width:3, height:"40vh", background:`linear-gradient(180deg,${C.accent},transparent)`, zIndex:2 }} />

      {/* Content */}
      <div style={{ position:"relative", zIndex:2, padding:"120px 72px 80px", maxWidth:700 }}>
        <div style={{ fontFamily:"'Exo 2',sans-serif", fontSize:11, fontWeight:700, letterSpacing:"0.4em", color:C.accent, marginBottom:20, textTransform:"uppercase" }}>
          Cardano Meme Coin. Training Arc Initiated
        </div>
        <h1 style={{ fontFamily:"'Bebas Neue',sans-serif", fontSize:"clamp(76px,10vw,128px)", lineHeight:0.88, letterSpacing:"0.035em", color:C.text, marginBottom:0 }}>
          CHARLES<br/>THE CHAD
        </h1>
        <div style={{ display:"flex", alignItems:"center", gap:12, margin:"24px 0" }}>
          <div style={{ width:56, height:3, background:C.blue }} />
          <div style={{ width:12, height:3, background:C.accent }} />
        </div>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:17, lineHeight:1.65, color:"rgba(240,242,255,0.68)", maxWidth:400, marginBottom:40 }}>
          Born from FUD. Forged on Cardano.<br/>Fueled by memes.<br/>
          <strong style={{ color:C.text }}>They laughed. He lifted.</strong>
        </p>
        <div style={{ display:"flex", gap:14, flexWrap:"wrap", alignItems:"center", marginBottom:24 }}>
          <BuyBtn large />
          <a href="https://memedepot.com/d/charles-thechad" target="_blank" rel="noopener noreferrer"
            style={{ fontFamily:"'Bebas Neue',sans-serif", fontSize:20, letterSpacing:"0.1em", padding:"15px 30px", border:"2px solid rgba(240,242,255,0.18)", color:C.text, transition:"all 0.2s" }}
            onMouseEnter={e=>{e.currentTarget.style.borderColor=C.accent;e.currentTarget.style.color=C.accent;}}
            onMouseLeave={e=>{e.currentTarget.style.borderColor="rgba(240,242,255,0.18)";e.currentTarget.style.color=C.text;}}
          >ENTER THE MEME DEPOT</a>
        </div>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:11, color:"rgba(240,242,255,0.22)", letterSpacing:"0.06em" }}>
          No promises. No suits. Just meme energy.
        </p>
      </div>

      {/* Bottom scroll line */}
      <div style={{ position:"absolute", bottom:36, left:"50%", transform:"translateX(-50%)", width:1, height:48, background:`linear-gradient(180deg,transparent,${C.accent})`, zIndex:2 }} />
    </section>
  );
}

// ── LORE ──────────────────────────────────────────────────────────────────
function Lore() {
  const ref = useRef(); useReveal(ref);
  const lines = ["The timeline mocked.","Cardano endured.","Charles lifted.","And from the ashes of FUD,","a Chad was born."];
  const stats = [
    ["ORIGIN","Cardano Blockchain"],["FUEL","FUD & Bear Markets"],
    ["WEAPON","Memes"],["PROTOCOL","Brick by Brick"],["WEAKNESS","None detected"],
  ];
  return (
    <section id="lore" ref={ref} style={{ padding:"120px 72px", maxWidth:1200, margin:"0 auto" }}>
      <Label>Origin Story</Label>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:72, alignItems:"center" }}>
        {/* Manga panel */}
        <CornerBox style={{ padding:"40px 44px", background:"rgba(0,51,173,0.04)" }}>
          <div style={{ fontFamily:"'Exo 2',sans-serif", fontSize:10, fontWeight:700, letterSpacing:"0.3em", color:"rgba(0,180,255,0.35)", marginBottom:24 }}>EPISODE 00: THE ORIGIN</div>
          {lines.map((l,i) => (
            <p key={i} style={{
              fontFamily:"'Bebas Neue',sans-serif",
              fontSize: i===4 ? 42 : 26,
              lineHeight:1.15, marginBottom:6,
              color: i===4 ? C.accent : "rgba(240,242,255,0.82)",
              letterSpacing:"0.04em",
            }}>{l}</p>
          ))}
        </CornerBox>
        {/* Stats */}
        <div style={{ display:"flex", flexDirection:"column", gap:0 }}>
          {stats.map(([k,v]) => (
            <div key={k} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"18px 0", borderBottom:"1px solid rgba(0,180,255,0.09)" }}>
              <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:11, fontWeight:700, letterSpacing:"0.25em", color:"rgba(0,180,255,0.5)", textTransform:"uppercase" }}>{k}</span>
              <span style={{ fontFamily:"'Bebas Neue',sans-serif", fontSize:22, letterSpacing:"0.05em", color:C.text }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── CONTENT HUB sub-components (hooks must live at component top level) ───

function TopTab({ label, on, onClick }) {
  const [h, sH] = useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => sH(true)} onMouseLeave={() => sH(false)}
      style={{
        flex:1, fontFamily:"'Bebas Neue',sans-serif", fontSize:22, letterSpacing:"0.12em",
        padding:"16px 24px", cursor:"pointer", transition:"all 0.15s",
        background: on ? C.blue : h ? "rgba(0,51,173,0.15)" : "transparent",
        border: on ? `1px solid ${C.accent}` : "1px solid transparent",
        color: on ? C.text : "rgba(240,242,255,0.38)",
      }}>{label}</button>
  );
}

function SubTab({ label, on, onClick }) {
  const [h, sH] = useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => sH(true)} onMouseLeave={() => sH(false)}
      style={{
        flex:"1 1 auto", minWidth:120, cursor:"pointer", transition:"all 0.15s",
        fontFamily:"'Bebas Neue',sans-serif", fontSize:14, letterSpacing:"0.1em", padding:"10px 16px",
        background: on ? "rgba(0,51,173,0.35)" : h ? "rgba(0,51,173,0.12)" : "transparent",
        border: on ? "1px solid rgba(0,180,255,0.4)" : "1px solid rgba(0,180,255,0.1)",
        color: on ? C.text : "rgba(240,242,255,0.35)",
      }}>{label}</button>
  );
}

function MemeCard({ m, show }) {
  const [h, sH] = useState(false);
  return (
    <div onMouseEnter={() => sH(true)} onMouseLeave={() => sH(false)}
      style={{ background: h ? "#090c19" : C.bg, display:"flex", flexDirection:"column", transition:"background 0.2s" }}>
      <div style={{ width:"100%", paddingBottom:"75%", position:"relative", background:"rgba(0,30,80,0.12)", flexShrink:0 }}>
        <div style={{
          position:"absolute", inset:0,
          backgroundImage:"repeating-linear-gradient(45deg,transparent,transparent 9px,rgba(0,51,173,0.05) 9px,rgba(0,51,173,0.05) 18px)",
          display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", padding:"16px 20px", gap:6,
        }}>
          <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:8, color:"rgba(0,180,255,0.2)", letterSpacing:"0.2em", textTransform:"uppercase" }}>meme image</span>
          <p style={{ fontFamily:"'Bebas Neue',sans-serif", fontSize:20, letterSpacing:"0.03em", color:"rgba(240,242,255,0.65)", textAlign:"center", lineHeight:1.2, whiteSpace:"pre-line" }}>{m.c}</p>
        </div>
      </div>
      <div style={{ display:"flex", borderTop:"1px solid rgba(0,180,255,0.07)" }}>
        <ActionBtn label="COPY"      onClick={() => copy(m.c, show, "CAPTION COPIED")} />
        <ActionBtn label="POST ON X" onClick={() => shareX(m.c)} />
        <ActionBtn label="SAVE"      onClick={() => show("COMING SOON")} />
      </div>
    </div>
  );
}

function GifCard({ item, show }) {
  const [h, sH] = useState(false);
  return (
    <div onMouseEnter={() => sH(true)} onMouseLeave={() => sH(false)}
      style={{ background: h ? "#090c19" : C.bg, display:"flex", flexDirection:"column", transition:"background 0.2s" }}>
      <div style={{ paddingBottom:"75%", position:"relative", background:"rgba(0,20,60,0.18)", flexShrink:0 }}>
        <div style={{
          position:"absolute", inset:0,
          backgroundImage:"repeating-linear-gradient(-45deg,transparent,transparent 9px,rgba(0,51,173,0.045) 9px,rgba(0,51,173,0.045) 18px)",
          display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:6,
        }}>
          <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:9, color:"rgba(0,180,255,0.2)", letterSpacing:"0.22em", textTransform:"uppercase" }}>GIF</span>
          <Bebas size={18} style={{ color:"rgba(0,180,255,0.32)", letterSpacing:"0.08em", textAlign:"center", padding:"0 12px" }}>{item.label}</Bebas>
        </div>
        <div style={{ position:"absolute", top:10, left:10, background:C.blue, border:`1px solid ${C.accent}`, padding:"2px 8px" }}>
          <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:9, fontWeight:700, letterSpacing:"0.15em", color:C.text }}>GIF</span>
        </div>
      </div>
      <div style={{ padding:"18px 18px 0" }}>
        <Bebas size={20} style={{ display:"block", color:C.text, marginBottom:4 }}>{item.label}</Bebas>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:12, color:"rgba(240,242,255,0.35)", marginBottom:14 }}>{item.desc}</p>
      </div>
      <div style={{ display:"flex", padding:"0 18px 18px", gap:2, marginTop:"auto" }}>
        <ActionBtn label="COPY GIF" onClick={() => show("GIF LINK COPIED")} primary />
        <ActionBtn label="POST"     onClick={() => shareX(`${item.label} energy`)} />
      </div>
    </div>
  );
}

function EpisodeCard({ ep }) {
  const [h, sH] = useState(false);
  return (
    <div onMouseEnter={() => sH(true)} onMouseLeave={() => sH(false)}
      style={{ background: h ? "#0a0d1c" : C.bg, padding:"28px 22px 24px", position:"relative", transition:"background 0.2s", overflow:"hidden" }}>
      <div style={{ position:"absolute", top:6, right:14, fontFamily:"'Bebas Neue',sans-serif", fontSize:88, color:"rgba(0,180,255,0.03)", lineHeight:1, userSelect:"none" }}>{ep.num}</div>
      <Placeholder label="anime art" ratio={70} />
      <div style={{ marginTop:18 }}>
        <div style={{ fontFamily:"'Exo 2',sans-serif", fontSize:10, fontWeight:700, letterSpacing:"0.3em", color:C.accent, marginBottom:6 }}>EP.{ep.num}</div>
        <Bebas size={20} style={{ display:"block", color:C.text, marginBottom:10 }}>{ep.title}</Bebas>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:12, lineHeight:1.55, color:"rgba(240,242,255,0.42)" }}>{ep.desc}</p>
      </div>
    </div>
  );
}

function MemesPanel({ show }) {
  const [memeCat, setMemeCat] = useState("fud");
  const activeMeme = MEME_CATS.find(c => c.id === memeCat);
  return (
    <div>
      <div style={{ display:"flex", gap:2, marginBottom:32, flexWrap:"wrap" }}>
        {MEME_CATS.map(c => (
          <SubTab key={c.id} label={c.label} on={memeCat === c.id} onClick={() => setMemeCat(c.id)} />
        ))}
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(290px,1fr))", gap:2, background:"rgba(0,180,255,0.05)" }}>
        {activeMeme.memes.map((m, i) => <MemeCard key={i} m={m} show={show} />)}
      </div>
    </div>
  );
}

function GifsPanel({ show }) {
  const [gifCat, setGifCat] = useState("fud");
  const active = GIF_CATS.find(c => c.id === gifCat);
  return (
    <div>
      <div style={{ display:"flex", gap:2, marginBottom:32, flexWrap:"wrap" }}>
        {GIF_CATS.map(c => (
          <SubTab key={c.id} label={c.label} on={gifCat === c.id} onClick={() => setGifCat(c.id)} />
        ))}
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(280px,1fr))", gap:2, background:"rgba(0,180,255,0.05)" }}>
        {active.gifs.map((item, i) => <GifCard key={i} item={item} show={show} />)}
      </div>
    </div>
  );
}

function AnimePanel() {
  return (
    <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(260px,1fr))", gap:2, background:"rgba(0,180,255,0.05)" }}>
      {EPISODES.map(ep => <EpisodeCard key={ep.num} ep={ep} />)}
    </div>
  );
}

// ── CONTENT HUB ───────────────────────────────────────────────────────────
function ContentHub({ show }) {
  const ref = useRef(); useReveal(ref);
  const [tab, setTab] = useState("memes");
  const TOP_TABS = [{ id:"memes", label:"MEMES" }, { id:"gifs", label:"GIFs" }, { id:"anime", label:"ANIME" }];
  return (
    <section id="content" ref={ref} style={{ padding:"120px 72px", maxWidth:1400, margin:"0 auto" }}>
      <Label>Content Hub</Label>
      <Bebas size="clamp(52px,5.5vw,76px)" style={{ display:"block", color:C.text, marginBottom:48 }}>MEMES BUILT DIFFERENT</Bebas>
      <div style={{ display:"flex", gap:2, marginBottom:40, background:"rgba(0,180,255,0.04)", padding:2 }}>
        {TOP_TABS.map(t => (
          <TopTab key={t.id} label={t.label} on={tab === t.id} onClick={() => setTab(t.id)} />
        ))}
      </div>
      {tab === "memes" && <MemesPanel show={show} />}
      {tab === "gifs"  && <GifsPanel  show={show} />}
      {tab === "anime" && <AnimePanel />}
    </section>
  );
}

// ── BUY SECTION ───────────────────────────────────────────────────────────
function BuySection({ show }) {
  const ref = useRef(); useReveal(ref);
  return (
    <section id="buy" ref={ref} style={{ padding:"130px 72px", textAlign:"center", position:"relative", overflow:"hidden", borderTop:"1px solid rgba(0,180,255,0.07)" }}>
      <div style={{ position:"absolute", inset:0, backgroundImage:"radial-gradient(ellipse at 50% -10%, rgba(0,51,173,0.22) 0%, transparent 65%)", pointerEvents:"none" }} />
      <div className="speed-lines" style={{ position:"absolute", inset:0, opacity:0.35 }} />
      <div style={{ position:"relative", zIndex:1, maxWidth:640, margin:"0 auto" }}>
        <Label style={{ justifyContent:"center" }}>Enter the Arc</Label>
        <Bebas size="clamp(52px,6.5vw,88px)" style={{ display:"block", color:C.text, lineHeight:0.92, marginBottom:18 }}>
          READY TO JOIN<br/>THE CHAD ARC?
        </Bebas>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:17, color:"rgba(240,242,255,0.4)", marginBottom:48 }}>Swap. Meme. Raid. Repeat.</p>
        <div style={{ marginBottom:44 }}><BuyBtn large /></div>
        {/* Contract */}
        <CornerBox style={{ display:"inline-flex", flexWrap:"wrap", alignItems:"center", gap:10, padding:"14px 20px", background:"rgba(0,51,173,0.06)", justifyContent:"center", margin:"0 auto" }}>
          <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:10, fontWeight:700, letterSpacing:"0.22em", color:"rgba(0,180,255,0.45)", textTransform:"uppercase" }}>Policy ID</span>
          <code style={{ fontFamily:"'Space Grotesk',monospace", fontSize:12, color:"rgba(240,242,255,0.38)", letterSpacing:"0.04em", wordBreak:"break-all", maxWidth:340 }}>{CONTRACT}</code>
          <button onClick={()=>copy(CONTRACT,show,"POLICY ID COPIED")}
            style={{ background:"transparent", border:`1px solid rgba(0,180,255,0.2)`, color:"rgba(0,180,255,0.55)", fontFamily:"'Exo 2',sans-serif", fontSize:10, fontWeight:700, letterSpacing:"0.18em", padding:"6px 14px", cursor:"pointer", textTransform:"uppercase", transition:"all 0.15s" }}
            onMouseEnter={e=>{e.currentTarget.style.background="rgba(0,180,255,0.1)";e.currentTarget.style.color=C.accent;}}
            onMouseLeave={e=>{e.currentTarget.style.background="transparent";e.currentTarget.style.color="rgba(0,180,255,0.55)";}}>COPY</button>
        </CornerBox>
        <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:11, color:"rgba(240,242,255,0.18)", marginTop:28, lineHeight:1.65 }}>
          Always verify the official contract before swapping.<br/>Meme coin. High risk. Not financial advice.
        </p>
      </div>
    </section>
  );
}

// ── FOOTER ────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{ padding:"44px 72px", borderTop:"1px solid rgba(0,180,255,0.07)", display:"flex", justifyContent:"space-between", alignItems:"center", flexWrap:"wrap", gap:24 }}>
      <div>
        <Bebas size={26} style={{ display:"block", letterSpacing:"0.18em", color:C.text, marginBottom:4 }}>$CHAD</Bebas>
        <span style={{ fontFamily:"'Exo 2',sans-serif", fontSize:10, color:"rgba(240,242,255,0.18)", letterSpacing:"0.12em" }}>CHARLES THE CHAD / CARDANO</span>
      </div>
      <div style={{ display:"flex", gap:28, alignItems:"center" }}>
        {[["X / TWITTER", X_LINK], ["DISCORD", DISCORD_LINK], ["BUY $CHAD", BUY_LINK]].map(([l,h]) => (
          <a key={l} href={h} target="_blank" rel="noopener noreferrer"
            style={{ fontFamily:"'Exo 2',sans-serif", fontSize:12, fontWeight:700, letterSpacing:"0.14em", color:"rgba(240,242,255,0.35)", transition:"color 0.2s" }}
            onMouseEnter={e=>e.currentTarget.style.color=C.accent}
            onMouseLeave={e=>e.currentTarget.style.color="rgba(240,242,255,0.35)"}>{l}</a>
        ))}
      </div>
      <p style={{ fontFamily:"'Exo 2',sans-serif", fontSize:10, color:"rgba(240,242,255,0.14)", maxWidth:280, lineHeight:1.6, textAlign:"right" }}>
        Meme coin. High risk. Not financial advice.<br/>Verify all links before swapping. $CHAD on Cardano.
      </p>
    </footer>
  );
}

// ── TWEAKS PANEL ──────────────────────────────────────────────────────────
function TweaksPanel({ tweaks, set, close }) {
  const ACCENTS = ["#00B4FF","#39FF14","#FFD700","#FF3A6E","#A855F7"];
  const BG_OPTS = [["NAVY","#06070e"],["PITCH BLACK","#010101"],["WARM DARK","#0e0a06"]];
  return (
    <div style={{ position:"fixed", bottom:24, right:24, width:272, background:"#0a0d1c", border:"1px solid rgba(0,180,255,0.2)", zIndex:500, fontFamily:"'Exo 2',sans-serif" }}>
      <div style={{ padding:"14px 18px", borderBottom:"1px solid rgba(0,180,255,0.1)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
        <span style={{ fontSize:12, fontWeight:700, letterSpacing:"0.2em", color:C.accent }}>TWEAKS</span>
        <button onClick={close} style={{ background:"none", border:"none", color:"rgba(240,242,255,0.3)", cursor:"pointer", fontSize:20, lineHeight:1 }}>×</button>
      </div>
      <div style={{ padding:18, display:"flex", flexDirection:"column", gap:20 }}>
        {/* Accent color */}
        <div>
          <div style={{ fontSize:10, fontWeight:700, letterSpacing:"0.22em", color:"rgba(0,180,255,0.45)", marginBottom:10, textTransform:"uppercase" }}>Accent Color</div>
          <div style={{ display:"flex", gap:8 }}>
            {ACCENTS.map(c => (
              <button key={c} onClick={()=>set("accent",c)} style={{ width:30, height:30, background:c, border: tweaks.accent===c?"2px solid #fff":"2px solid transparent", cursor:"pointer", transition:"transform 0.15s" }}
                onMouseEnter={e=>e.currentTarget.style.transform="scale(1.12)"}
                onMouseLeave={e=>e.currentTarget.style.transform="scale(1)"} />
            ))}
          </div>
        </div>
        {/* BG tone */}
        <div>
          <div style={{ fontSize:10, fontWeight:700, letterSpacing:"0.22em", color:"rgba(0,180,255,0.45)", marginBottom:10, textTransform:"uppercase" }}>Background</div>
          <div style={{ display:"flex", gap:2 }}>
            {BG_OPTS.map(([l,v]) => (
              <button key={l} onClick={()=>set("bg",v)} style={{
                flex:1, padding:"8px 4px", fontSize:9, fontWeight:700, letterSpacing:"0.1em",
                background: tweaks.bg===v?"rgba(0,180,255,0.15)":"transparent",
                border: tweaks.bg===v?`1px solid ${C.accent}`:"1px solid rgba(240,242,255,0.08)",
                color: tweaks.bg===v?C.accent:"rgba(240,242,255,0.3)", cursor:"pointer", transition:"all 0.15s",
                textTransform:"uppercase",
              }}>{l}</button>
            ))}
          </div>
        </div>
        {/* Speed lines toggle */}
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
          <span style={{ fontSize:10, fontWeight:700, letterSpacing:"0.22em", color:"rgba(0,180,255,0.45)", textTransform:"uppercase" }}>Speed Lines</span>
          <button onClick={()=>set("lines",!tweaks.lines)} style={{
            padding:"7px 16px", fontSize:10, fontWeight:700, letterSpacing:"0.1em",
            background: tweaks.lines?"rgba(0,180,255,0.15)":"transparent",
            border: tweaks.lines?`1px solid ${C.accent}`:"1px solid rgba(240,242,255,0.1)",
            color: tweaks.lines?C.accent:"rgba(240,242,255,0.3)", cursor:"pointer", transition:"all 0.15s", textTransform:"uppercase",
          }}>{tweaks.lines?"ON":"OFF"}</button>
        </div>
        {/* Buy link button */}
        <a href={BUY_LINK} target="_blank" rel="noopener noreferrer"
          style={{ display:"block", textAlign:"center", padding:"11px", background:C.blue, border:`1px solid ${C.accent}`, fontFamily:"'Bebas Neue',sans-serif", fontSize:16, letterSpacing:"0.1em", color:C.text }}>
          BUY $CHAD ↗
        </a>
      </div>
    </div>
  );
}

// ── APP ───────────────────────────────────────────────────────────────────
function App() {
  const [toasts, show] = useToast();
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [tweaks, setTweaksState] = useState(/*EDITMODE-BEGIN*/{
    "accent": "#00B4FF",
    "bg": "#06070e",
    "lines": true
  }/*EDITMODE-END*/);

  function set(key, value) {
    const next = { ...tweaks, [key]:value };
    setTweaksState(next);
    window.parent.postMessage({ type:"__edit_mode_set_keys", edits: next }, "*");
  }

  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode")   setTweaksOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type:"__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  useEffect(() => {
    const blockContextMenu = (e) => e.preventDefault();
    const blockInspectShortcuts = (e) => {
      const key = e.key.toLowerCase();
      const modifier = e.ctrlKey || e.metaKey;
      const devToolsCombo = modifier && e.shiftKey && ["i", "j", "c"].includes(key);
      const viewSourceCombo = modifier && key === "u";
      const macDevToolsCombo = e.metaKey && e.altKey && ["i", "j", "c"].includes(key);
      if (key === "f12" || devToolsCombo || viewSourceCombo || macDevToolsCombo) {
        e.preventDefault();
        e.stopPropagation();
      }
    };

    window.addEventListener("contextmenu", blockContextMenu);
    window.addEventListener("keydown", blockInspectShortcuts, true);
    return () => {
      window.removeEventListener("contextmenu", blockContextMenu);
      window.removeEventListener("keydown", blockInspectShortcuts, true);
    };
  }, []);

  // Apply accent as CSS var
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", tweaks.accent);
    document.body.style.background = tweaks.bg;
  }, [tweaks.accent, tweaks.bg]);

  return (
    <div style={{ background: tweaks.bg }}>
      {/* Inject CSS var for accent */}
      <style>{`
        .speed-lines { opacity: ${tweaks.lines ? 1 : 0} !important; transition: opacity 0.3s; }
        ::selection { background: ${tweaks.accent}33; }
      `}</style>
      <Nav />
      <Hero />
      <BuySection show={show} />
      <Footer />
      {/* Toasts */}
      <div style={{ position:"fixed", bottom:28, left:"50%", zIndex:9999, display:"flex", flexDirection:"column", gap:8, alignItems:"center", pointerEvents:"none" }}>
        {toasts.map(t => <div key={t.id} className="toast-item">{t.msg}</div>)}
      </div>
      {tweaksOpen && (
        <TweaksPanel tweaks={tweaks} set={set} close={()=>{ setTweaksOpen(false); window.parent.postMessage({ type:"__edit_mode_dismissed" }, "*"); }} />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
