// page-projects.jsx — live demo gallery; click → open in new tab
const { SiteCtx: SiteCtx_P, useReveal: useReveal_P, I18N: I18N_P } = window.MM_HOOKS;

function ProjectsPage() {
  const { lang } = React.useContext(SiteCtx_P);
  const t = I18N_P[lang];
  const demos = window.SITE_DATA.DEMOS;
  const [hRef, hShown] = useReveal_P({ threshold: 0.1 });

  return (
    <section id="projects" className="page page--scrollable">
      <div className="page-inner">
        <div ref={hRef} className={`reveal ${hShown ? "is-shown" : ""}`}>
          <div className="section-eyebrow">{t.projects_eyebrow}</div>
          <h2 className="section-title">{t.projects_title}</h2>
          <p className="section-sub">{t.projects_sub}</p>
        </div>
        <div className="demo-grid">
          {demos.map((d, i) => <DemoCard key={d.id} d={d} i={i} />)}
        </div>
        <div className="page-footer">[ {demos.filter(d => !d.placeholder).length} live · {demos.filter(d => d.placeholder).length} wip ]</div>
      </div>
    </section>
  );
}

function DemoCard({ d, i }) {
  const { lang } = React.useContext(SiteCtx_P);
  const [ref, shown] = useReveal_P({ threshold: 0.1 });
  const [hovered, setHovered] = React.useState(false);
  const [loaded, setLoaded] = React.useState(false);
  const isLive = !d.placeholder && d.url && (d.url.startsWith("http") || d.url.endsWith(".html"));
  const initials = (d.title_en || "X").split(/\s+/).slice(0, 2).map(w => w[0]).join("").toUpperCase();

  const Tag = isLive ? "a" : "div";
  const linkProps = isLive
    ? { href: d.url, target: "_blank", rel: "noopener noreferrer" }
    : {};

  return (
    <Tag
      ref={ref}
      {...linkProps}
      className={`demo-card reveal-pop ${shown ? "is-shown" : ""} ${hovered ? "is-hovered" : ""}`}
      style={{ transitionDelay: `${(i % 6) * 70}ms`, "--accent": d.accent }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <div className="demo-preview">
        <div className="demo-chrome">
          <span className="dot dot--r"></span>
          <span className="dot dot--y"></span>
          <span className="dot dot--g"></span>
          <span className="demo-chrome-url">{isLive ? d.url.replace(/^https?:\/\//, "").replace(/\/$/, "").slice(0, 40) : "—— wip ——"}</span>
          <span className={`demo-status ${isLive ? "is-live" : "is-soon"}`}>
            <span className="demo-status-dot"></span>
            {isLive ? "live" : "soon"}
          </span>
        </div>
        <div className="demo-frame-wrap">
          {isLive ? (
            <>
              {!loaded && <div className="demo-loading"><span className="loading-spark"></span></div>}
              <iframe
                src={d.url}
                className="demo-frame"
                loading="lazy"
                sandbox="allow-scripts allow-same-origin"
                onLoad={() => setLoaded(true)}
                title={d.title_en}
              />
              <div className="demo-overlay">
                <div className="demo-overlay-cta">
                  <span className="demo-overlay-icon">↗</span>
                  <span>{lang === "zh" ? "在新标签打开" : "Open in new tab"}</span>
                </div>
              </div>
            </>
          ) : (
            <DemoBlueprint d={d} initials={initials} lang={lang} />
          )}
        </div>
      </div>
      <div className="demo-meta">
        <div className="demo-meta-top">
          <div className="demo-num">#{String(i + 1).padStart(2, "0")}</div>
          <div className="demo-title">{lang === "zh" ? d.title_zh : d.title_en}</div>
        </div>
        <div className="demo-desc">{lang === "zh" ? d.desc_zh : d.desc_en}</div>
        <div className="demo-foot">
          {isLive ? (
            <span className="demo-go">
              {lang === "zh" ? "试玩" : "Try it"} <span className="demo-go-arrow">↗</span>
            </span>
          ) : (
            <span className="demo-wip">{lang === "zh" ? "建设中…" : "Work in progress…"}</span>
          )}
        </div>
      </div>
    </Tag>
  );
}

function DemoBlueprint({ d, initials, lang }) {
  const variants = ["bars", "nodes", "grid", "wave"];
  let h = 0;
  for (const c of d.id) h = (h * 31 + c.charCodeAt(0)) | 0;
  const variant = variants[Math.abs(h) % variants.length];
  return (
    <div className="demo-blueprint" style={{ "--accent": d.accent }}>
      <svg viewBox="0 0 200 120" className="demo-blueprint-svg" preserveAspectRatio="xMidYMid meet">
        <defs>
          <pattern id={`grid-${d.id}`} width="10" height="10" patternUnits="userSpaceOnUse">
            <path d="M 10 0 L 0 0 0 10" fill="none" stroke="currentColor" strokeWidth="0.5" opacity="0.18" />
          </pattern>
        </defs>
        <rect width="200" height="120" fill={`url(#grid-${d.id})`} />
        {variant === "bars" && [12, 28, 44, 60, 76, 92, 108, 124, 140, 156, 172].map((x, i) => (
          <rect key={i} x={x} y={120 - (20 + (i * 7) % 65)} width="10" height={20 + (i * 7) % 65} fill={d.accent} opacity={0.55 - i * 0.03} />
        ))}
        {variant === "nodes" && (
          <>
            {[[40, 30], [100, 25], [160, 40], [60, 70], [130, 80], [90, 95]].map(([x, y], i) => (
              <circle key={i} cx={x} cy={y} r={6 + (i % 3) * 2} fill={d.accent} opacity={0.7} />
            ))}
            <line x1="40" y1="30" x2="100" y2="25" stroke={d.accent} strokeWidth="1" opacity="0.5" />
            <line x1="100" y1="25" x2="160" y2="40" stroke={d.accent} strokeWidth="1" opacity="0.5" />
            <line x1="40" y1="30" x2="60" y2="70" stroke={d.accent} strokeWidth="1" opacity="0.5" />
            <line x1="100" y1="25" x2="130" y2="80" stroke={d.accent} strokeWidth="1" opacity="0.5" />
            <line x1="60" y1="70" x2="90" y2="95" stroke={d.accent} strokeWidth="1" opacity="0.5" />
            <line x1="130" y1="80" x2="90" y2="95" stroke={d.accent} strokeWidth="1" opacity="0.5" />
          </>
        )}
        {variant === "grid" && (
          <>
            {[0, 1, 2, 3].map(r => [0, 1, 2, 3, 4, 5].map(c => (
              <rect key={`${r}-${c}`} x={20 + c * 28} y={15 + r * 25} width="22" height="18" rx="3" fill={d.accent} opacity={((r + c) % 3 === 0) ? 0.65 : 0.18} />
            )))}
          </>
        )}
        {variant === "wave" && (
          <>
            <path d="M 0 70 Q 25 40, 50 70 T 100 70 T 150 70 T 200 70" fill="none" stroke={d.accent} strokeWidth="2" opacity="0.7" />
            <path d="M 0 85 Q 25 55, 50 85 T 100 85 T 150 85 T 200 85" fill="none" stroke={d.accent} strokeWidth="1.5" opacity="0.4" />
            <path d="M 0 55 Q 25 25, 50 55 T 100 55 T 150 55 T 200 55" fill="none" stroke={d.accent} strokeWidth="1.5" opacity="0.4" />
          </>
        )}
      </svg>
      <div className="demo-blueprint-stamp">
        <div className="demo-blueprint-mark" style={{ background: d.accent }}>{initials}</div>
        <div className="demo-blueprint-meta">
          <div className="bp-label">{lang === "zh" ? "蓝图阶段" : "BLUEPRINT"}</div>
          <div className="bp-id">{d.id}</div>
        </div>
      </div>
    </div>
  );
}

window.ProjectsPage = ProjectsPage;
