/* eslint-disable */
const { useState, useEffect, useRef, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "glassBlur": 28,
  "glassTint": 34,
  "saturation": 180,
  "accentTint": "green",
  "showOrbs": true,
  "billing": "week"
}/*EDITMODE-END*/;

const ACCENT_PRESETS = {
  green:  { deep: "#07391b", mid: "#1aa552", bright: "#5cdf85", pale: "#d6f7d8" },
  teal:   { deep: "#0a2f3a", mid: "#0e9aa7", bright: "#5fd6e2", pale: "#cef3f7" },
  emerald:{ deep: "#053628", mid: "#0d8c64", bright: "#4cd9a8", pale: "#cdf3e4" },
  forest: { deep: "#1a2e0e", mid: "#4a7a1f", bright: "#9bd64b", pale: "#e9f5cf" },
};

const PRICES = {
  week: { amount: 0.99,  period: "per week", old: null,      unit: "$/week" },
  year: { amount: 41.99, period: "per year", old: "$48.99",  unit: "$/year", badge: "-20%" },
};

function ArrowLeft() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 12H5M12 19l-7-7 7-7"/>
    </svg>
  );
}
function Lock() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2"/>
      <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
    </svg>
  );
}
function Plus() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>;
}
function Spark() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>;
}
function Bolt() {
  return <svg viewBox="0 0 24 24" fill="currentColor"><path d="M13 2 4 14h6l-1 8 9-12h-6l1-8z"/></svg>;
}
function User() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>;
}
function Stack() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"><path d="M12 3 3 8l9 5 9-5-9-5z"/><path d="M3 13l9 5 9-5"/><path d="M3 18l9 5 9-5"/></svg>;
}
function Badge() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"><path d="M12 2 14.5 7.5 20.5 8.5 16 13l1 6-5-3-5 3 1-6L2.5 8.5 8.5 7.5z"/></svg>;
}
function Headphones() {
  return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"/><path d="M21 19a2 2 0 0 1-2 2h-1v-6h3v4zM3 19a2 2 0 0 0 2 2h1v-6H3v4z"/></svg>;
}

// ── Free-week golden screen helpers ──────────────────────────────────────────
function playQuack() {
  try {
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    const osc = ctx.createOscillator();
    const g = ctx.createGain();
    osc.connect(g); g.connect(ctx.destination);
    osc.type = "sine";
    osc.frequency.setValueAtTime(340, ctx.currentTime);
    osc.frequency.exponentialRampToValueAtTime(160, ctx.currentTime + 0.14);
    g.gain.setValueAtTime(0.22, ctx.currentTime);
    g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.30);
    osc.start(ctx.currentTime);
    osc.stop(ctx.currentTime + 0.30);
  } catch {}
}

function FrogParade({ count = 6 }) {
  return (
    <div style={{display:"flex",justifyContent:"center",gap:14,padding:"18px 0 4px",userSelect:"none"}}>
      {Array.from({length: count}).map((_, i) => (
        <span
          key={i}
          onClick={playQuack}
          style={{
            fontSize: 28,
            display: "inline-block",
            animation: `frogJump 0.75s cubic-bezier(.36,.07,.19,.97) ${i * 0.13}s infinite`,
            cursor: "pointer",
          }}
        >🐸</span>
      ))}
    </div>
  );
}

const FEATURES = [
  { icon: <Bolt/>,       title: "Early access",        desc: "New features before the public release." },
  { icon: <Spark/>,      title: "Fast sync",            desc: "Priority sync queue for your data." },
  { icon: <User/>,       title: "Extended profile",     desc: "Extra settings and customization options." },
  { icon: <Stack/>,      title: "Higher limits",        desc: "Expanded quotas for media content." },
  { icon: <Badge/>,      title: "Premium badge",        desc: "Subscription mark in key sections." },
  { icon: <Headphones/>, title: "Faster support",       desc: "Priority in support and team responses." },
];

const COMPARE_ROWS = [
  { feat: "Early access",  free: "—",        plus: <span><span className="check">✓</span>Yes</span>,     pp: <span><span className="check">✓</span>Yes+</span> },
  { feat: "Limits",        free: "Basic",    plus: <b>Extended</b>,                                       pp: <b>Maximum</b> },
  { feat: "Profile",       free: "Standard", plus: <b>Plus</b>,                                           pp: <b>Ultimate</b> },
  { feat: "Sync speed",    free: "Normal",   plus: <b>Priority</b>,                                       pp: <b>Instant</b> },
  { feat: "Support",       free: "Basic",    plus: <b>24 hours</b>,                                       pp: <b>1 hour</b> },
];

const FAQ = [
  { q: "Can I cancel my subscription?", a: "Yes, at any time in your account settings. Access to features remains until the end of the paid period — no hidden charges." },
  { q: "When does qwe [+] activate?", a: "Immediately after a successful payment. The badge and extended limits apply automatically within a minute." },
  { q: "Where is it safe to pay?", a: "Through our account portal qweapp.online. Payment data is not stored in the app — processing goes through a certified acquirer." },
  { q: "Can I change the billing period later?", a: "Yes. Switching to an annual plan takes effect from the next billing cycle, and the difference is calculated automatically." },
  { q: "What's included in qwe {++}?", a: "Everything from qwe [+] plus maximum quotas, instant sync, a personal manager and exclusive profile themes." },
];

/* ────────────────────────────────────────────────────────────────────────── */
/* Frog cashier mini-game                                                     */
/* ────────────────────────────────────────────────────────────────────────── */
function FrogCashier({ onReward }) {
  const COOLDOWN_KEY = "frog_last_played";
  const REWARDS_KEY  = "frog_rewards";
  const COOLDOWN_MS  = 60 * 60 * 1000;

  function getCooldownSecs() {
    const last = parseInt(localStorage.getItem(COOLDOWN_KEY) || "0");
    const elapsed = Date.now() - last;
    return elapsed >= COOLDOWN_MS ? 0 : Math.ceil((COOLDOWN_MS - elapsed) / 1000);
  }
  function fmtTime(secs) {
    const m = Math.floor(secs / 60), s = secs % 60;
    return m > 0 ? `${m}m ${s}s` : `${s}s`;
  }
  function getRewards() {
    try { return JSON.parse(localStorage.getItem(REWARDS_KEY) || "{}"); } catch { return {}; }
  }
  function computeGameReward(s) {
    if (s >= 50) return { discountPct: 0,  freeWeek: true  };
    if (s >= 30) return { discountPct: 10, freeWeek: false };
    if (s >= 15) return { discountPct: 5,  freeWeek: false };
    return null;
  }
  function mergeAndSave(earned) {
    const prev = getRewards();
    const merged = {
      discountPct: Math.min(50, (prev.discountPct || 0) + (earned.discountPct || 0)),
      freeWeek: !!(prev.freeWeek || earned.freeWeek),
    };
    localStorage.setItem(REWARDS_KEY, JSON.stringify(merged));
    return merged;
  }

  const ITEM_TYPES = {
    ruble:  { symbol: "$",  points: +1, color: "#5cdf85" },
    dollar: { symbol: "💰", points: +3, color: "#ffd700" },
    cross:  { symbol: "✕",  points: -3, color: "#ff5555" },
    bomb:   { symbol: "💣", lives: -1,  color: "#ff9933" },
  };
  const LIFETIMES = { ruble: 3000, dollar: 2000, cross: 4000, bomb: 4000 };

  function randomType() {
    const r = Math.random() * 120;
    if (r < 50)  return "ruble";
    if (r < 80)  return "cross";
    if (r < 105) return "bomb";
    return "dollar";
  }
  function makeBug(id) {
    return {
      id: id ?? Math.random().toString(36).slice(2),
      type: randomType(),
      x: 0.45 + Math.random() * 0.45,
      y: 0.05 + Math.random() * 0.55,
      drift: Math.random() * Math.PI * 2,
      caught: false,
      spawnTime: Date.now(),
    };
  }

  const stageRef = useRef(null);
  const frogRef  = useRef(null);
  const [phase,          setPhase]          = useState("idle");
  const [bugs,           setBugs]           = useState([]);
  const [score,          setScore]          = useState(0);
  const [lives,          setLives]          = useState(3);
  const [timeLeft,       setTimeLeft]       = useState(30);
  const [tongue,         setTongue]         = useState(null);
  const [shoot,          setShoot]          = useState(false);
  const [coolSecs,       setCoolSecs]       = useState(() => getCooldownSecs());
  const [storedRewards,  setStoredRewards]  = useState(() => getRewards());
  const [earnedThisGame, setEarnedThisGame] = useState(null);

  useEffect(() => {
    const t = setInterval(() => setCoolSecs(getCooldownSecs()), 1000);
    return () => clearInterval(t);
  }, []);

  // Award reward when game ends
  useEffect(() => {
    if (phase !== "gameover") return;
    const earned = computeGameReward(score);
    if (earned) {
      const merged = mergeAndSave(earned);
      setStoredRewards(merged);
      setEarnedThisGame(earned);
      onReward?.(merged);
    }
  }, [phase]);

  function startGame() {
    if (getCooldownSecs() > 0) return;
    localStorage.setItem(COOLDOWN_KEY, String(Date.now()));
    setStoredRewards(getRewards());
    setEarnedThisGame(null);
    setBugs(Array.from({length: 10}, () => makeBug()));
    setScore(0); setLives(3); setTimeLeft(30);
    setShoot(false); setTongue(null);
    setPhase("playing");
    setCoolSecs(getCooldownSecs());
  }

  useEffect(() => {
    if (phase !== "playing") return;
    const t = setInterval(() => {
      setTimeLeft((prev) => { if (prev <= 1) { setPhase("gameover"); return 0; } return prev - 1; });
    }, 1000);
    return () => clearInterval(t);
  }, [phase]);

  useEffect(() => { if (phase === "playing" && lives <= 0) setPhase("gameover"); }, [lives, phase]);

  useEffect(() => {
    if (phase !== "playing") return;
    const t = setInterval(() => {
      const now = Date.now();
      setBugs((bs) => bs.map((b) => {
        if (b.caught) return b;
        if (now - b.spawnTime >= LIFETIMES[b.type]) return makeBug(b.id);
        return b;
      }));
    }, 200);
    return () => clearInterval(t);
  }, [phase]);

  useEffect(() => {
    if (phase !== "playing") return;
    let raf, last = performance.now();
    const tick = (now) => {
      const dt = (now - last) / 1000; last = now;
      setBugs((bs) => bs.map((b) => {
        if (b.caught) return b;
        const d = b.drift + dt * 0.5;
        return { ...b, drift: d,
          x: Math.max(0.42, Math.min(0.92, b.x + Math.sin(d) * 0.0008)),
          y: Math.max(0.04, Math.min(0.62, b.y + Math.cos(d * 0.8) * 0.0009)) };
      }));
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [phase]);

  const onBugClick = (id) => {
    if (phase !== "playing") return;
    const stage = stageRef.current?.getBoundingClientRect();
    const frog  = frogRef.current?.getBoundingClientRect();
    if (!stage || !frog) return;
    const bug = bugs.find((b) => b.id === id);
    if (!bug || bug.caught) return;
    const bx = bug.x * stage.width, by = bug.y * stage.height;
    const fx = frog.left - stage.left + frog.width * 0.85;
    const fy = frog.top  - stage.top  + frog.height * 0.4;
    const dx = bx - fx, dy = by - fy;
    setTongue({ x: fx, y: fy, angle: Math.atan2(dy, dx) * 180 / Math.PI, len: Math.sqrt(dx*dx + dy*dy) });
    setShoot(true);
    const item = ITEM_TYPES[bug.type];
    setTimeout(() => {
      setBugs((bs) => bs.map((b) => b.id === id ? { ...b, caught: true } : b));
      if (item.lives !== undefined) setLives((l) => Math.max(0, l + item.lives));
      else setScore((s) => s + item.points);
    }, 140);
    setTimeout(() => setTongue(null), 280);
    setTimeout(() => setShoot(false), 320);
    setTimeout(() => { setBugs((bs) => bs.map((b) => b.id === id ? makeBug(id) : b)); }, 1400);
  };

  const livesStr = Array.from({length: 3}, (_, i) => i < lives ? "❤️" : "🖤").join("");
  const hasBonus = storedRewards.discountPct > 0 || storedRewards.freeWeek;

  const MILESTONES = [
    { pts: 15, label: "+5% off yearly",  color: "#5cdf85", key: "disc5"  },
    { pts: 30, label: "+10% off yearly", color: "#fcd34d", key: "disc10" },
    { pts: 50, label: "free week 🎁",   color: "#ff8fb3", key: "week"   },
  ];

  function isEarned(m) {
    if (m.key === "week")   return !!storedRewards.freeWeek;
    if (m.key === "disc5")  return (storedRewards.discountPct || 0) >= 5;
    if (m.key === "disc10") return (storedRewards.discountPct || 0) >= 10;
    return false;
  }
  function isJustEarned(m) {
    if (!earnedThisGame) return false;
    if (m.key === "week")   return !!earnedThisGame.freeWeek;
    if (m.key === "disc5")  return earnedThisGame.discountPct === 5;
    if (m.key === "disc10") return earnedThisGame.discountPct === 10;
    return false;
  }

  const rewardsPanel = (
    <div style={{width:"100%",borderTop:"0.5px solid rgba(255,255,255,0.12)",marginTop:10,paddingTop:10}}>
      <div style={{fontSize:9,fontWeight:800,letterSpacing:".1em",textTransform:"uppercase",opacity:0.45,marginBottom:8}}>🏆 REWARDS PER GAME</div>
      {MILESTONES.map(m => {
        const earned  = isEarned(m);
        const justNow = isJustEarned(m);
        const progress = phase === "playing" ? Math.min(1, score / m.pts) : (score >= m.pts ? 1 : 0);
        return (
          <div key={m.pts} style={{marginBottom:8}}>
            <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:3}}>
              <span style={{fontSize:12,lineHeight:1}}>{justNow ? "🎉" : earned ? "✅" : "○"}</span>
              <span style={{flex:1,fontSize:10,fontWeight:earned?700:400,
                color:earned ? m.color : "inherit",opacity:earned?1:0.55}}>
                {m.label}
              </span>
              <span style={{fontSize:9,opacity:0.38,fontVariantNumeric:"tabular-nums"}}>{m.pts} pts</span>
            </div>
            <div style={{height:3,borderRadius:999,background:"rgba(255,255,255,0.14)",overflow:"hidden"}}>
              <div style={{height:"100%",width:`${(phase==="playing"?progress:(score>=m.pts?1:0))*100}%`,
                borderRadius:999,background:m.color,
                transition:"width 0.25s ease",opacity:earned?1:0.7}}/>
            </div>
          </div>
        );
      })}
      {hasBonus && (
        <div style={{marginTop:6,padding:"7px 10px",borderRadius:10,
          background:"rgba(92,223,133,0.12)",border:"0.5px solid rgba(92,223,133,0.3)"}}>
          <div style={{fontSize:10,fontWeight:800,color:"#5cdf85",marginBottom:3}}>🐸 active bonus</div>
          {storedRewards.discountPct > 0 && (
            <div style={{fontSize:10,opacity:0.85}}>−{storedRewards.discountPct}% off yearly plan</div>
          )}
          {storedRewards.freeWeek && (
            <div style={{fontSize:10,opacity:0.85}}>free week unlocked!</div>
          )}
        </div>
      )}
    </div>
  );

  if (phase === "idle") return (
    <div className="glass mascot">
      <div className="mascot-head">
        <div className="mascot-title"><span>🐸</span><span>frog cashier mode</span></div>
      </div>
      <div className="mascot-stage" style={{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",gap:8,overflowY:"auto",paddingBottom:6}}>
        {rewardsPanel}
        <div style={{fontSize:36,marginTop:4}}>🐸</div>
        {coolSecs > 0
          ? <><div style={{fontSize:12,opacity:0.55}}>next game in</div><div style={{fontSize:20,fontWeight:700}}>{fmtTime(coolSecs)}</div></>
          : <button className="buy" style={{padding:"9px 32px",fontSize:14}} onClick={startGame}>Play</button>
        }
        <div style={{fontSize:10,opacity:0.45,textAlign:"center",lineHeight:1.7}}>$ +1 · 💰 +3 · ✕ −3 · 💣 −❤️<br/>30 sec · 3 lives</div>
      </div>
    </div>
  );

  if (phase === "gameover") return (
    <div className="glass mascot">
      <div className="mascot-head">
        <div className="mascot-title"><span>🐸</span><span>game over</span></div>
        <div className="mascot-score">score · {score}</div>
      </div>
      <div className="mascot-stage" style={{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",gap:8,overflowY:"auto",paddingBottom:6}}>
        {rewardsPanel}
        <div style={{fontSize:11,opacity:0.55,marginTop:4}}>your score</div>
        <div style={{fontSize:38,fontWeight:800,lineHeight:1}}>{score}</div>
        {earnedThisGame
          ? <div style={{fontSize:12,color:"#5cdf85",fontWeight:700,textAlign:"center"}}>
              🎉 {earnedThisGame.freeWeek ? "free week unlocked!" : `+${earnedThisGame.discountPct}% yearly discount!`}
            </div>
          : <div style={{fontSize:11,opacity:0.4}}>{score > 0 ? "almost there next time!" : "score 15+ to earn rewards"}</div>
        }
        <div style={{fontSize:11,opacity:0.4}}>next game in {fmtTime(coolSecs)}</div>
      </div>
    </div>
  );

  return (
    <div className="glass mascot">
      <div className="mascot-head">
        <div className="mascot-title"><span>🐸</span><span>frog cashier mode</span></div>
        <div style={{display:"flex",gap:6,alignItems:"center"}}>
          <span style={{fontSize:11,letterSpacing:1}}>{livesStr}</span>
          <div className="mascot-score">{score}</div>
          <div style={{fontSize:11,fontWeight:700,opacity:0.65,minWidth:28,textAlign:"right"}}>{timeLeft}s</div>
        </div>
      </div>
      <div className="mascot-stage" ref={stageRef}>
        {/* milestone overlay during play */}
        <div style={{position:"absolute",top:6,left:6,zIndex:10,display:"flex",flexDirection:"column",gap:3,pointerEvents:"none"}}>
          {MILESTONES.map(m => {
            const prog = Math.min(1, score / m.pts);
            const done = score >= m.pts;
            return (
              <div key={m.pts} style={{display:"flex",alignItems:"center",gap:4,
                padding:"2px 6px 2px 4px",borderRadius:999,
                background: done ? "rgba(0,0,0,0.28)" : "rgba(0,0,0,0.18)",
                border: done ? `0.5px solid ${m.color}55` : "0.5px solid rgba(255,255,255,0.12)"}}>
                <div style={{width:22,height:3,borderRadius:999,background:"rgba(255,255,255,0.15)",overflow:"hidden"}}>
                  <div style={{height:"100%",width:`${prog*100}%`,borderRadius:999,background:m.color,transition:"width 0.2s"}}/>
                </div>
                <span style={{fontSize:8,fontWeight:800,color: done ? m.color : "rgba(255,255,255,0.5)"}}>
                  {done ? "✓" : m.pts} {m.label.split(" ")[0]}
                </span>
              </div>
            );
          })}
        </div>
        <div ref={frogRef} className={"frog" + (shoot ? " shoot" : "")}>🐸</div>
        {tongue && <div className="tongue" style={{left:tongue.x,top:tongue.y,width:tongue.len,transform:`rotate(${tongue.angle}deg)`,animation:"tongueIn 280ms ease-out"}}/>}
        {bugs.map((b) => {
          const item = ITEM_TYPES[b.type];
          return (
            <div key={b.id}
              className={"bug" + (b.caught ? " caught" : "")}
              style={{left:`calc(${b.x*100}% - 14px)`,top:`calc(${b.y*100}% - 14px)`,color:item.color}}
              onClick={() => onBugClick(b.id)}>
              {item.symbol}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────────── */
/* Main app                                                                   */
/* ────────────────────────────────────────────────────────────────────────── */
function randToken() {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let s = '';
  for (let i = 0; i < 10; i++) s += chars[Math.floor(Math.random() * chars.length)];
  return s;
}
function randDigits12() {
  let s = '';
  for (let i = 0; i < 12; i++) s += Math.floor(Math.random() * 10);
  return s;
}

async function startPayment(billing) {
  let rewards = {};
  try { rewards = JSON.parse(localStorage.getItem("frog_rewards") || "{}"); } catch {}
  const disc     = rewards.discountPct || 0;
  const freeWeek = rewards.freeWeek   || false;

  const base   = `https://qweapp.online/subscription/${randToken()}`;
  const suffix = `/buy/eng_${randDigits12()}`;

  if (billing === "year") {
    let url = base + "plusyear" + suffix;
    if (disc > 0) url += "?discount=" + disc;
    window.location.href = url;
  } else if (freeWeek) {
    window.location.href = base + "plus" + suffix + "?freeweek=1";
  } else {
    window.location.href = base + "plus" + suffix;
  }
  return { redirect: true };
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [billing, setBilling] = useState(t.billing === "month" ? "week" : (t.billing || "week"));
  const [openFaq, setOpenFaq] = useState(0);
  const [buying, setBuying] = useState(false);
  const [buyStatus, setBuyStatus] = useState("");
  const [rewards, setRewards] = useState(() => {
    try { return JSON.parse(localStorage.getItem("frog_rewards") || "{}"); } catch { return {}; }
  });

  const price = PRICES[billing] || PRICES.week;
  // Dynamic badge: base -20% + frog bonus
  const frogDisc    = rewards.discountPct || 0;
  const yearBadge   = frogDisc > 0 ? `-${20 + frogDisc}%` : "-20%";
  // Hero price with frog bonus applied
  const heroDisc    = billing === "year" ? frogDisc : 0;
  const heroFreeWk  = billing === "week" && !!(rewards.freeWeek);
  const isFreeWeek  = heroFreeWk;
  const heroDiscAmt = heroDisc > 0 ? +(price.amount * (1 - heroDisc / 100)).toFixed(2) : price.amount;

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--glass-blur", `${t.glassBlur}px`);
    root.style.setProperty("--glass-tint", `rgba(255,255,255,${t.glassTint / 100})`);
    root.style.setProperty("--glass-sat", `${t.saturation}%`);
    const a = ACCENT_PRESETS[t.accentTint] || ACCENT_PRESETS.green;
    root.style.setProperty("--bg-deep", a.deep);
    root.style.setProperty("--bg-mid", a.mid);
    root.style.setProperty("--bg-bright", a.bright);
    root.style.setProperty("--bg-pale", a.pale);
    const stage = document.querySelector(".stage");
    if (stage) {
      stage.style.background = `radial-gradient(140% 90% at 50% -10%, ${a.bright} 0%, ${a.mid} 40%, ${a.deep} 75%, #061a0e 100%)`;
    }
    document.querySelector(".orbs").style.display = t.showOrbs ? "" : "none";
  }, [t.glassBlur, t.glassTint, t.saturation, t.accentTint, t.showOrbs]);

  // Golden stage when free week is active
  useEffect(() => {
    const stage = document.querySelector(".stage");
    if (!stage) return;
    if (isFreeWeek) {
      stage.style.background = "radial-gradient(140% 90% at 50% -10%, #ffe566 0%, #e8a000 40%, #7a4800 75%, #2a1a00 100%)";
    }
  }, [isFreeWeek]);

  // Auto-quack every few seconds when free week is shown
  useEffect(() => {
    if (!isFreeWeek) return;
    const id = setInterval(playQuack, 2800);
    return () => clearInterval(id);
  }, [isFreeWeek]);

  return (
    <>
      <div className="wrap">
        {/* topbar */}
        <div className="topbar">
          <button className="back glass-soft" aria-label="Back" onClick={() => {
            window.location.href = "https://qweapp.org/home/";
          }}>
            <ArrowLeft/>
          </button>

          <div className="top-controls">
            <div className="plan-switch glass-soft">
              <button className="active">qwe [+]</button>
              <a href="/sub/++/">qwe {"{++}"}</a>
            </div>

            <div className="billing-pill glass-soft">
              {[
                { id: "week", label: "Week" },
                { id: "year", label: "Year", save: yearBadge },
              ].map((b) => (
                <button
                  key={b.id}
                  className={billing === b.id ? "active" : ""}
                  onClick={() => { setBilling(b.id); setTweak("billing", b.id); }}
                >
                  {b.label}
                  {b.save && <span className="save-tag">{b.save}</span>}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* golden free-week banner */}
        {isFreeWeek && (
          <div style={{
            textAlign:"center",
            padding:"14px 20px 8px",
            background:"linear-gradient(135deg,rgba(255,215,0,.18),rgba(255,160,0,.12))",
            borderRadius:18,
            border:"1px solid rgba(255,200,50,.35)",
            marginBottom:8,
          }}>
            <div style={{fontSize:32,marginBottom:4}}>🏆</div>
            <div style={{fontSize:17,fontWeight:800,color:"#ffe566",letterSpacing:"-0.3px"}}>Free Week Unlocked!</div>
            <div style={{fontSize:12,color:"rgba(255,220,100,.65)",marginTop:3}}>You won a free week of qwe&nbsp;[+] in Frog Cashier</div>
          </div>
        )}

        {/* hero */}
        <div className="hero">
          <div className="glass hero-main">
            <div className="eyebrow">
              <span className="dot"></span>
              <span>recommended plan</span>
            </div>
            <h1 className="title">
              qwe <span className="bracket">[+]</span>
            </h1>
            <p className="sub">
              One plan that covers 90% of your daily needs: more speed, priority access to releases and the full qwe ecosystem.
            </p>
            <div className="price-block">
              <div className="price-num">
                <span className="currency" style={{fontSize:38,transform:'translateY(-12px)',display:'inline-block'}}>$</span>
                <span>{heroFreeWk ? "0" : heroDiscAmt}</span>
              </div>
              <div className="price-meta">
                {heroFreeWk
                  ? <div className="price-old">${price.amount}</div>
                  : heroDisc > 0
                  ? <div className="price-old">${price.amount}</div>
                  : price.old && <div className="price-old">{price.old}</div>
                }
                <div className="price-period">
                  {heroFreeWk
                    ? <span style={{color:"var(--bg-mid)",fontWeight:800}}>first week free 🐸</span>
                    : <>{price.period}{heroDisc > 0 && <span style={{marginLeft:8,fontSize:15,color:"#0e7a3a",fontWeight:800}}>🐸 −{heroDisc}%</span>}</>
                  }
                </div>
              </div>
            </div>
          </div>

          <FrogCashier onReward={setRewards}/>
        </div>

        {/* features */}
        <div className="sect-h">What's included in [+]</div>
        <div className="features">
          {FEATURES.map((f, i) => (
            <div key={i} className="glass feat">
              <div className="feat-icon">{f.icon}</div>
              <h4>{f.title}</h4>
              <p>{f.desc}</p>
            </div>
          ))}
        </div>

        {/* compare table */}
        <div className="sect-h">Plan comparison</div>
        <div className="glass compare">
          <div className="compare-grid">
            <div className="compare-hl" style={{ left: "calc((1.2 + 1) / 4.3 * 100%)", width: "calc(1.1 / 4.3 * 100%)" }}></div>
            <div className="head feature-head">Feature</div>
            <div className="head cell-center">Free</div>
            <div className="head cell-center"><span style={{fontWeight:800}}>qwe [+]</span></div>
            <div className="head cell-center">qwe {"{++}"}</div>
            {COMPARE_ROWS.map((r, i) => {
              const last = i === COMPARE_ROWS.length - 1;
              return (
                <React.Fragment key={i}>
                  <div className={"row-label" + (last ? " last" : "")}>{r.feat}</div>
                  <div className={"cell-center" + (last ? " last" : "")}>
                    {r.free === "—" ? <span className="dash">—</span> : r.free}
                  </div>
                  <div className={"cell-center" + (last ? " last" : "")}>{r.plus}</div>
                  <div className={"cell-center" + (last ? " last" : "")}>{r.pp}</div>
                </React.Fragment>
              );
            })}
          </div>
        </div>

        {/* FAQ */}
        <div className="sect-h">FAQ</div>
        <div className="faq">
          {FAQ.map((f, i) => (
            <div key={i} className={"glass faq-item" + (openFaq === i ? " open" : "")} onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
              <div className="faq-q">
                <span>{f.q}</span>
                <span className="faq-q-icon"><Plus/></span>
              </div>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>

        {/* frog parade when free week is active */}
        {isFreeWeek && <FrogParade />}
      </div>

      {/* sticky CTA */}
      <div className="cta-dock">
        <div className="glass cta">
          <div className="cta-info">
            {(() => {
              const disc   = billing === "year" ? frogDisc : 0;
              const freeWk = billing === "week" && (rewards.freeWeek || false);
              const discAmt = disc > 0 ? +(price.amount * (1 - disc/100)).toFixed(2) : price.amount;
              return (
                <div className="price">
                  {freeWk
                    ? <><s style={{opacity:.35,fontWeight:400}}>${price.amount}</s>{" "}
                        <span style={{color:"var(--bg-bright)",fontWeight:900}}>free</span>
                        {" "}· {price.period}{" "}
                        <span style={{fontSize:10,color:"var(--bg-bright)"}}>🐸</span></>
                    : disc > 0
                    ? <><s style={{opacity:.35,fontWeight:400}}>${price.amount}</s>{" "}
                        <span style={{fontWeight:900}}>${discAmt}</span>
                        {" "}· {price.period}{" "}
                        <span style={{fontSize:10,color:"var(--bg-bright)"}}>🐸 −{disc}%</span></>
                    : <><span style={{fontWeight:900}}>${price.amount}</span> · {price.period}</>
                  }
                </div>
              );
            })()}
            {frogDisc > 0 && billing !== "year" && (
              <div style={{fontSize:10,marginTop:2,display:"flex",alignItems:"center",gap:4,color:"var(--ink-soft)"}}>
                <span>🐸</span>
                <span>−{frogDisc}% discount waiting on <b>Year</b></span>
              </div>
            )}
            {rewards.freeWeek && billing !== "week" && (
              <div style={{fontSize:10,marginTop:2,display:"flex",alignItems:"center",gap:4,color:"var(--ink-soft)"}}>
                <span>🐸</span>
                <span>free week waiting on <b>Week</b></span>
              </div>
            )}
            <div className="secure"><Lock/> Secure payment via qweapp.online</div>
            {buyStatus && <div style={{fontSize:11,marginTop:2,color:'rgba(7,57,27,0.65)'}}>{buyStatus}</div>}
          </div>
          <button className="buy" disabled={buying} onClick={async () => {
            setBuying(true);
            setBuyStatus(billing === "year" ? "Redirecting to checkout…" : "Preparing payment…");
            try {
              await startPayment(billing);
            } catch (e) {
              setBuyStatus("Network error. Please try again.");
              setBuying(false);
            }
          }}>
            {buying ? "Loading…" : "Get qwe [+]"}
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
        </div>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Glass" />
        <TweakSlider label="Blur" value={t.glassBlur} min={6} max={60} step={1} unit="px"
          onChange={(v) => setTweak("glassBlur", v)} />
        <TweakSlider label="Tint" value={t.glassTint} min={0} max={80} step={1} unit="%"
          onChange={(v) => setTweak("glassTint", v)} />
        <TweakSlider label="Saturation" value={t.saturation} min={100} max={260} step={5} unit="%"
          onChange={(v) => setTweak("saturation", v)} />
        <TweakSection label="Scene" />
        <TweakRadio label="Accent" value={t.accentTint}
          options={["green","emerald","teal","forest"]}
          onChange={(v) => setTweak("accentTint", v)} />
        <TweakToggle label="Animated orbs" value={t.showOrbs}
          onChange={(v) => setTweak("showOrbs", v)} />
        <TweakSection label="Plan" />
        <TweakRadio label="Billing" value={billing}
          options={["week","year"]}
          onChange={(v) => { setBilling(v); setTweak("billing", v); }} />
      </TweaksPanel>
    </>
  );
}

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