// v1-terminal.jsx — TERMINAL_OS variation
// Closest to user reference: pure hacker, neon, mono, ASCII dividers, Chinese chars,
// matrix rain, decrypt typing, boot-up terminal.

const V1 = ({ accent = "#00ff88", lang = "EN", density = "regular", glitch = 0.4, pulse = 0.6, bgPattern = "matrix", monoFont = "Geist Mono", onLaunch, onLangToggle }) => {
  const isCN = lang === "CN";
  const winW = useWindowWidth();
  const isMobile = winW < 640;
  const isTablet = winW >= 640 && winW < 1024;
  const padY = density === "compact" ? 16 : density === "comfy" ? 32 : 24;
  const padX = isMobile ? 16 : 40;
  const [visits, setVisits] = useState(null);
  useEffect(() => {
    fetch("https://skillstack-visits.klee062196.workers.dev/", { mode: "cors" })
      .then(r => r.json())
      .then(d => setVisits(d.visits))
      .catch(() => setVisits(null));
  }, []);
  const tFrame = useFrame();

  // Boot lines
  const bootLines = [
    "[ OK ] mounting /skills ...",
    "[ OK ] connecting to telegram bus ...",
    "[ OK ] loading torch.compile cache ...",
    "[ OK ] auth voiceprint validated ...",
    "[ OK ] websocket → binance, bybit, hyperliquid ...",
    `[ OK ] ${SKILLS.length} skills indexed.`,
    "_",
  ];
  const [bootIdx, setBootIdx] = useState(0);
  useEffect(() => {
    if (bootIdx >= bootLines.length) return;
    const t = setTimeout(() => setBootIdx(i => i + 1), 220 + Math.random() * 180);
    return () => clearTimeout(t);
  }, [bootIdx]);

  // Decrypt name
  const heroTarget = isCN ? HUB_NAME_CN : HUB_NAME;
  const scrambled = useScramble(heroTarget, { speed: 50 });

  const heroLine2 = useTypewriter(isCN ? HUB_TAGLINE_CN : HUB_TAGLINE, { speed: 22, startDelay: 1200 });

  // Cell pulse for cards on hover
  const [hoverId, setHoverId] = useState(null);

  const accentRGB = useMemo(() => hexToRgb(accent), [accent]);

  return (
    <div style={{
      minHeight: "100vh",
      background: "#050807",
      color: accent,
      fontFamily: `${monoFont}, "Roboto Mono", ui-monospace, monospace`,
      position: "relative",
      overflow: "hidden",
    }}>
      <FXCanvas pattern={bgPattern} color={accent} intensity={pulse * 0.7} />

      {/* vignette + scanlines overlay */}
      <div style={{
        position: "fixed", inset: 0, pointerEvents: "none", zIndex: 1,
        background: `radial-gradient(ellipse at 50% 30%, transparent 30%, rgba(0,0,0,0.65) 90%),
                     repeating-linear-gradient(0deg, rgba(0,0,0,0.08) 0px, rgba(0,0,0,0.08) 1px, transparent 1px, transparent 3px)`,
      }} />

      <div style={{position: "relative", zIndex: 2, padding: `0 ${padX}px`}}>
        {/* Top status bar */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontSize: 11, padding: `${padY * 0.6}px 0`, borderBottom: `1px solid rgba(${accentRGB},0.18)`,
          letterSpacing: "0.12em", textTransform: "uppercase",
        }}>
          <div style={{display: "flex", gap: 14, alignItems: "center"}}>
            {/* SkillStack logo mark — stacked bars */}
            <svg width="18" height="16" viewBox="0 0 18 16" style={{flexShrink: 0}}>
              <rect x="0" y="0"  width="18" height="3" fill={accent}/>
              <rect x="0" y="6"  width="12" height="3" fill={accent} opacity="0.8"/>
              <rect x="0" y="12" width="6"  height="3" fill={accent} opacity="0.55"/>
            </svg>
            <span style={{color: accent, fontWeight: 700}}>SKILLSTACK.FUN</span>
          </div>
          <div style={{display: "flex", gap: isMobile ? 10 : 18, alignItems: "center", opacity: 0.7}}>
            <span>◉ {visits !== null ? visits.toLocaleString() : "..."} visits</span>
            {!isMobile && <span>⏱ {new Date().toISOString().slice(11, 19)}Z</span>}
            <span
              onClick={() => onLangToggle?.(lang === "EN" ? "CN" : "EN")}
              style={{
                color: accent, cursor: "pointer",
                border: `1px solid rgba(${accentRGB},0.4)`,
                padding: "2px 8px", letterSpacing: "0.14em",
                userSelect: "none",
                transition: "background .15s",
              }}
              onMouseEnter={e => e.currentTarget.style.background = `rgba(${accentRGB},0.12)`}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >⌘ {lang}</span>
          </div>
        </div>

        {/* HERO */}
        <section style={{padding: `${padY * 2.4}px 0 ${padY * 1.4}px`, display: "grid", gridTemplateColumns: isMobile ? "1fr" : isTablet ? "1fr" : "1.4fr 1fr", gap: isMobile ? 24 : 40, alignItems: "start"}}>
          <div>
            <div style={{fontSize: 11, opacity: 0.5, letterSpacing: "0.18em", marginBottom: 18}}>
              // BOOT_LOG
            </div>
            <div style={{fontSize: 12, lineHeight: 1.7, opacity: 0.55, marginBottom: 32, minHeight: 8 * 22}}>
              {bootLines.slice(0, bootIdx).map((l, i) => (
                <div key={i} style={{color: l.includes("OK") ? accent : "rgba(255,255,255,0.5)"}}>{l}</div>
              ))}
            </div>

            {/* Massive name */}
            <div style={{fontFamily: `${monoFont}, monospace`, fontSize: isMobile ? (isCN ? 52 : 56) : isTablet ? (isCN ? 72 : 80) : (isCN ? 88 : 110), fontWeight: 700, lineHeight: 0.9, letterSpacing: "-0.04em", color: accent, textShadow: `0 0 30px rgba(${accentRGB},0.45)`}}>
              {scrambled}<BlinkCursor color={accent} w={isCN ? 32 : 22} h={isCN ? 80 : 90} />
            </div>
            <div style={{fontFamily: `${monoFont}, monospace`, fontSize: 18, lineHeight: 1.5, marginTop: 24, color: "rgba(255,255,255,0.75)", maxWidth: 640, minHeight: 56}}>
              {heroLine2}
            </div>

            {/* CTA row */}
            <div style={{display: "flex", gap: 14, marginTop: 36}}>
              <button onClick={() => document.getElementById("skills-grid")?.scrollIntoView?.({behavior: "smooth"})}
                style={btnPrimaryStyle(accent)}>
                ▸ {isCN ? "进入技能库" : "ENTER_VAULT"}
              </button>
              <button style={btnGhostStyle(accent)}>
                {isCN ? "查看源码" : "VIEW_SRC"} ↗
              </button>
            </div>
          </div>

          {/* Right: live system stats panel — hidden on mobile/tablet */}
          <div style={{display: (isMobile || isTablet) ? "none" : "block"}}><div style={{
            border: `1px solid rgba(${accentRGB},0.3)`, padding: 20,
            background: `rgba(${accentRGB},0.03)`,
            position: "relative",
          }}>
            <div style={{position: "absolute", top: -1, left: 16, padding: "0 8px", background: "#050807", fontSize: 10, color: accent, letterSpacing: "0.2em"}}>
              SYS_STATUS
            </div>
            <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, fontSize: 11, marginTop: 8}}>
              {[
                [isCN ? "访问量" : "visits", visits !== null ? visits.toLocaleString() : "..."],
                [isCN ? "技能" : "skills", `${SKILLS.length} / ${SKILLS.length}`],
                [isCN ? "延迟" : "latency", `${Math.round(40 + 8 * Math.sin(tFrame/1000))}ms`],
                [isCN ? "在线时长" : "uptime", (() => {
                  const launch = new Date("2026-04-29T00:00:00Z");
                  const diff = Date.now() - launch.getTime();
                  const days = Math.floor(diff / 86400000);
                  const hrs = Math.floor((diff % 86400000) / 3600000).toString().padStart(2,"0");
                  const mins = Math.floor((diff % 3600000) / 60000).toString().padStart(2,"0");
                  return `${days}d ${hrs}:${mins}`;
                })()],
                [isCN ? "连接状态" : "connection", <span style={{display: "inline-flex", alignItems: "center", gap: 6}}><PulseDot color={accent} size={6} intensity={pulse} />{isCN ? "已连接" : "ONLINE"}</span>],
              ].map(([k, v]) => (
                <div key={k} style={{display: "flex", justifyContent: "space-between", borderBottom: `1px dashed rgba(${accentRGB},0.18)`, paddingBottom: 6}}>
                  <span style={{opacity: 0.55}}>{k}</span>
                  <span style={{color: accent}}>{v}</span>
                </div>
              ))}
            </div>

            <div style={{marginTop: 22, fontSize: 10, opacity: 0.55, letterSpacing: "0.18em"}}>// MARIO_LEVEL_1</div>
            <div style={{marginTop: 10}}>
              <PixelRunner accent={accent} intensity={pulse} height={120} />
            </div>
          </div></div>
        </section>

        {/* ASCII divider */}
        <div style={{fontSize: 10, opacity: 0.35, lineHeight: 1, padding: `${padY}px 0`, whiteSpace: "nowrap", overflow: "hidden"}}>
          {"━".repeat(200)}
        </div>

        {/* About strip */}
        <section style={{padding: `${padY}px 0 ${padY * 1.6}px`, display: "grid", gridTemplateColumns: isMobile ? "1fr" : "120px 1fr", gap: isMobile ? 8 : 24}}>
          <div style={{fontSize: 11, color: accent, letterSpacing: "0.2em"}}>// ABOUT</div>
          <div style={{fontSize: 14, lineHeight: 1.7, color: "rgba(255,255,255,0.78)", maxWidth: 720}}>
            {isCN
              ? "每天 24/7 在折腾，把脑子里的想法做成真正能跑起来的 Skill。"
              : "Vibe building 24/7, deploying theories into actually runnable skills."}
          </div>
        </section>

        {/* SKILLS GRID */}
        <section id="skills-grid" style={{paddingBottom: padY * 3}}>
          <div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18}}>
            <div style={{fontSize: 12, color: accent, letterSpacing: "0.2em"}}>
              // CODE_VAULT — {SKILLS.length} skills
            </div>
            <div style={{fontSize: 11, opacity: 0.5}}>{isCN ? "点击查看 Alpha" : "Click to see Alpha"}</div>
          </div>

          <div style={{display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(2, 1fr)", gap: 14}}>
            {SKILLS.map((s, idx) => {
              const hov = hoverId === s.id;
              const pulseGlow = hov ? 24 + 14 * Math.sin(tFrame / 250) : 0;
              return (
                <div key={s.id}
                  onMouseEnter={() => setHoverId(s.id)}
                  onMouseLeave={() => setHoverId(null)}
                  onClick={() => onLaunch?.(s)}
                  style={{
                    border: `1px solid rgba(${accentRGB},${hov ? 0.85 : 0.22})`,
                    background: hov ? `rgba(${accentRGB},0.07)` : `rgba(${accentRGB},0.02)`,
                    padding: density === "compact" ? 16 : 20,
                    cursor: "pointer",
                    position: "relative",
                    transition: "border-color .18s, background .18s",
                    boxShadow: hov ? `0 0 ${pulseGlow}px rgba(${accentRGB},0.4)` : "none",
                  }}>
                  <div style={{display: "flex", justifyContent: "space-between", fontSize: 10, opacity: 0.5, letterSpacing: "0.16em", marginBottom: 14}}>
                    <span>#{s.code}</span>
                    <span>{s.deployed}</span>
                  </div>
                  <div style={{display: "flex", alignItems: "center", gap: 10, marginBottom: 6}}>
                    <PulseDot color={accent} size={6} intensity={pulse} />
                    <span style={{fontSize: 10, color: accent, letterSpacing: "0.2em"}}>{s.status}</span>
                    <span style={{fontSize: 10, opacity: 0.4, marginLeft: "auto"}}>{s.metric.label}: <span style={{color: accent}}>{s.metric.value}</span></span>
                  </div>
                  <div style={{fontSize: 22, fontWeight: 700, color: "#fff", letterSpacing: "-0.01em", marginBottom: 6}}>
                    {isCN ? s.name_cn : s.name}
                  </div>
                  <div style={{fontSize: 13, lineHeight: 1.55, color: "rgba(255,255,255,0.6)", marginBottom: 14, minHeight: 38}}>
                    {isCN ? s.blurb_cn : s.blurb}
                  </div>
                  <div style={{display: "flex", flexWrap: "wrap", gap: 6}}>
                    {s.tags.map(t => (
                      <span key={t} style={{
                        fontSize: 10, padding: "3px 8px",
                        border: `1px solid rgba(${accentRGB},0.3)`,
                        color: accent, opacity: 0.85,
                      }}>{t}</span>
                    ))}
                  </div>
                  {hov && (
                    <div style={{position: "absolute", right: 12, bottom: 10, fontSize: 11, color: accent, letterSpacing: "0.2em"}}>
                      EXEC ▸
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </section>

        {/* footer */}
        <div style={{borderTop: `1px solid rgba(${accentRGB},0.18)`, padding: `${padY}px 0`, fontSize: 11, opacity: 0.55, display: "flex", justifyContent: "space-between"}}>
          <span>// EOF — skillstack.fun — built with caffeine and websockets</span>
          <span>{isCN ? "更多技能即将上线" : "more skills coming"}</span>
        </div>
      </div>
    </div>
  );
};

function btnPrimaryStyle(accent) {
  return {
    background: accent, color: "#000", border: "none", padding: "12px 22px",
    fontFamily: "inherit", fontSize: 12, fontWeight: 700, letterSpacing: "0.18em",
    cursor: "pointer", boxShadow: `0 0 24px ${accent}66`,
  };
}
function btnGhostStyle(accent) {
  return {
    background: "transparent", color: accent, border: `1px solid ${accent}66`,
    padding: "12px 22px", fontFamily: "inherit", fontSize: 12, fontWeight: 700,
    letterSpacing: "0.18em", cursor: "pointer",
  };
}

function hexToRgb(h) {
  const s = h.replace("#", "");
  const n = parseInt(s.length === 3 ? s.split("").map(c => c+c).join("") : s, 16);
  return `${(n>>16)&255},${(n>>8)&255},${n&255}`;
}

window.V1 = V1;
window.hexToRgb = hexToRgb;
