/* global React, BorderBeam */
const { useEffect, useRef, useState, useCallback } = React;

/* ============================================================================
   Infrastructure — horizontal-scroll rail of pillar cards.

   The section sits at normal 100vh height. The rail scrolls horizontally
   inside its own container with overflow-x:auto + scroll-snap-x. Page scroll
   passes through cleanly. Navigation: prev/next buttons, drag-to-scroll, and
   trackpad horizontal swipe.
   ============================================================================ */

const PILLARS = [
  {
    key: "scripts",
    no: "01",
    kicker: "EXCLUSIVE",
    name: "Custom Lua",
    accent: "var(--color-scripts)",
    before: "Ideas in a Discord thread.",
    after:  "A Saturday night where nothing breaks.",
  },
  {
    key: "builds",
    no: "02",
    kicker: "TURNKEY",
    name: "Full Server Builds",
    accent: "var(--color-server-builds)",
    before: "A blank txAdmin panel.",
    after:  "Opening night with a full house.",
  },
  {
    key: "mgmt",
    no: "03",
    kicker: "24 / 7",
    name: "Server Management",
    accent: "var(--color-management)",
    before: "Tickets queued for tomorrow.",
    after:  "Your server runs. You sleep.",
  },
  {
    key: "db",
    no: "04",
    kicker: "INFRASTRUCTURE",
    name: "Database & Hosting",
    accent: "var(--color-database)",
    before: "MySQL on a stranger's box.",
    after:  "Audited. Recoverable. Quiet.",
  },
  {
    key: "assets",
    no: "05",
    kicker: "DESIGN",
    name: "3D Assets & Maps",
    accent: "var(--color-assets)",
    before: "GitHub forks of the same MLO.",
    after:  "Interiors players talk about.",
  },
  {
    key: "tebex",
    no: "06",
    kicker: "SUPPORT",
    name: "Tebex & Storefront",
    accent: "var(--color-tebex)",
    before: "A storefront copying someone else's.",
    after:  "Packages that cover your costs.",
  },
];

function Infrastructure() {
  const railRef = useRef(null);
  const [progress, setProgress] = useState(0);
  const [active, setActive] = useState(0);

  const onRailScroll = useCallback(() => {
    const el = railRef.current;
    if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    const p = max > 0 ? el.scrollLeft / max : 0;
    setProgress(p);
    // Compute active card by which one is closest to center
    const center = el.scrollLeft + el.clientWidth / 2;
    const cards = el.querySelectorAll("[data-pillar-card]");
    let bestIdx = 0, bestDist = Infinity;
    cards.forEach((c, i) => {
      const cCenter = c.offsetLeft + c.offsetWidth / 2;
      const d = Math.abs(cCenter - center);
      if (d < bestDist) { bestDist = d; bestIdx = i; }
    });
    setActive(bestIdx);
  }, []);

  // Drag-to-scroll
  useEffect(() => {
    const el = railRef.current;
    if (!el) return;
    let isDown = false, startX = 0, startScroll = 0;
    const onDown = (e) => {
      isDown = true;
      startX = e.clientX;
      startScroll = el.scrollLeft;
      el.style.cursor = "grabbing";
    };
    const onMove = (e) => {
      if (!isDown) return;
      el.scrollLeft = startScroll - (e.clientX - startX);
    };
    const onUp = () => { isDown = false; el.style.cursor = ""; };
    el.addEventListener("mousedown", onDown);
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
    return () => {
      el.removeEventListener("mousedown", onDown);
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseup", onUp);
    };
  }, []);

  const scrollByCard = (dir) => {
    const el = railRef.current;
    if (!el) return;
    const first = el.querySelector("[data-pillar-card]");
    const step = first ? first.offsetWidth + 24 : 440;
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };

  const scrollToPillar = (index) => {
    const el = railRef.current;
    if (!el) return;
    const cards = el.querySelectorAll("[data-pillar-card]");
    const target = cards[index];
    if (!target) return;
    const targetCenter = target.offsetLeft + target.offsetWidth / 2;
    const railCenter = el.clientWidth / 2;
    el.scrollTo({ left: targetCenter - railCenter, behavior: "smooth" });
  };

  return (
    <section
      id="infrastructure"
      data-screen-label="02 Vision + Infrastructure"
      style={{
        position: "relative",
        minHeight: "100vh",
        padding: "10rem 0 8rem",
        background: "var(--color-base)",
        display: "flex", flexDirection: "column",
        overflow: "hidden",
      }}
    >
      {/* Header — Vision's aspirational dream statement opens the section */}
      <div style={{
        padding: "0 clamp(2rem, 6vw, 6rem) 4rem",
      }}>
        <div>
          <div className="reveal-up" style={{
            fontFamily: "var(--font-body)", fontSize: 10,
            letterSpacing: "0.4em", textTransform: "uppercase",
            color: "var(--color-accent)", marginBottom: "1.2rem",
            display: "flex", alignItems: "center", gap: 12,
          }}>
            <span style={{ width: 36, height: 1, background: "var(--color-accent)" }}></span>
            [02] // THE SHIFT
          </div>
          <h2 className="reveal-up" style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(1.9rem, 4.4vw, 4.4rem)",
            letterSpacing: "-0.04em", lineHeight: 1.08,
            textTransform: "uppercase", color: "var(--color-ink)",
            margin: 0, maxWidth: "28ch",
          }}>
            The version of your server where everything runs, players stay, and you finally stop being the one holding it together.
          </h2>
        </div>

        {/* CTA on left, counter + arrows on right — same row, bottom-aligned */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "flex-end",
          marginTop: "2.4rem",
          gap: "2rem", flexWrap: "wrap",
        }}>
          <a
            href="#retainers"
            className="reveal-up"
            data-cursor="BUILD"
            style={{
              display: "inline-block",
              fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: "clamp(1.4rem, 3vw, 2.8rem)",
              letterSpacing: "-0.04em", lineHeight: 1,
              textTransform: "uppercase",
              color: "var(--color-accent-warm)",
              textDecoration: "none",
              borderBottom: "1px solid var(--color-accent-warm)",
              paddingBottom: "0.2em",
            }}
          >
            Let's build it. →
          </a>

          <div className="reveal-up" style={{
            display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 14,
            marginLeft: "auto",
          }}>
            <div style={{
              fontFamily: "var(--font-body)", fontSize: 11,
              letterSpacing: "0.3em", textTransform: "uppercase",
              color: "var(--color-ink-muted)",
            }}>
              <span style={{ color: "var(--color-accent-warm)" }}>{String(active + 1).padStart(2, "0")}</span>
              <span style={{ opacity: 0.4 }}> / </span>
              <span>{String(PILLARS.length).padStart(2, "0")}</span>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <RailButton onClick={() => scrollByCard(-1)} dir="prev" label="Prev" />
              <RailButton onClick={() => scrollByCard(1)} dir="next" label="Next" />
            </div>
          </div>
        </div>

      </div>

      {/* Progress meter */}
      <div style={{
        margin: "0 clamp(2rem, 6vw, 6rem) 2rem",
        height: 1, background: "rgba(255,255,255,0.08)", position: "relative",
      }}>
        <div style={{
          position: "absolute", top: -1, left: 0,
          height: 3, width: `${progress * 100}%`,
          background: "linear-gradient(90deg, var(--color-accent), var(--color-accent-warm))",
          transition: "width 0.18s var(--ease-out)",
          boxShadow: "0 0 12px rgba(200,48,47,0.42)",
        }}></div>
        {PILLARS.map((p, i) => (
          <span key={p.key} style={{
            position: "absolute", top: -3,
            left: `${(i / (PILLARS.length - 1)) * 100}%`,
            width: 1, height: 7,
            background: i === active ? "var(--color-accent-warm)" : "rgba(255,255,255,0.2)",
            transform: "translateX(-50%)",
            transition: "background 0.25s ease",
          }}></span>
        ))}
      </div>

      {/* Rail */}
      <div
        ref={railRef}
        onScroll={onRailScroll}
        className="pillar-rail"
        style={{
          display: "flex",
          gap: 24,
          padding: "20px clamp(2rem, 6vw, 6rem)",
          overflowX: "auto",
          overflowY: "hidden",
          scrollSnapType: "x mandatory",
          scrollbarWidth: "none",
          cursor: "grab",
          WebkitOverflowScrolling: "touch",
        }}
      >
        {PILLARS.map((p, i) => <PillarCard key={p.key} pillar={p} index={i} active={i === active} />)}
        <EndCap />
      </div>

      <style>{`
        .pillar-rail::-webkit-scrollbar { display: none; }
      `}</style>
    </section>
  );
}

/* ----- Rail nav button --------------------------------------------------- */
function RailButton({ onClick, dir, label }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      data-cursor={label.toUpperCase()}
      aria-label={label}
      style={{
        width: 48, height: 48,
        background: hover ? "var(--color-accent-warm)" : "transparent",
        border: `1px solid ${hover ? "var(--color-accent-warm)" : "rgba(255,255,255,0.18)"}`,
        color: hover ? "var(--color-base)" : "var(--color-ink)",
        fontFamily: "var(--font-body)", fontSize: 16,
        cursor: "none",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "background 0.25s ease, border-color 0.25s ease, color 0.25s ease",
      }}
    >
      {dir === "prev" ? "←" : "→"}
    </button>
  );
}

/* ----- PillarCard -------------------------------------------------------- */
function PillarCard({ pillar, index, active }) {
  const [hover, setHover] = useState(false);
  return (
    <div
      data-pillar-card
      data-cursor=""
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "relative",
        flex: "0 0 auto",
        width: "min(420px, 78vw)",
        height: "min(460px, 64vh)",
        background: "rgba(20,20,20,0.55)",
        border: `1px solid ${(hover || active) ? pillar.accent : "rgba(200,204,210,0.18)"}`,
        borderRadius: 0,
        padding: "32px 28px",
        display: "flex", flexDirection: "column",
        overflow: "hidden",
        scrollSnapAlign: "center",
        transition: "border-color 0.3s ease, transform 0.3s ease, background 0.3s ease",
        transform: hover ? "translateY(-6px)" : "translateY(0)",
      }}
    >
      <BorderBeam
        duration={(hover || active) ? 3 : 6}
        colorFrom={pillar.accent}
        colorTo="var(--color-accent-warm)"
        radius={0}
      />

      {/* Top row */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "3.5rem",
          letterSpacing: "-0.04em",
          color: pillar.accent,
          lineHeight: 0.9,
          textShadow: (hover || active) ? `0 0 30px ${pillar.accent}` : "none",
          transition: "text-shadow 0.3s ease",
        }}>
          {pillar.no}
        </div>
        <div style={{
          fontFamily: "var(--font-body)", fontSize: 9,
          letterSpacing: "0.4em", textTransform: "uppercase",
          color: "var(--color-ink-muted)",
          textAlign: "right",
          lineHeight: 1.8,
        }}>
          0{index + 1} / {String(PILLARS.length).padStart(2, "0")}
        </div>
      </div>

      {/* Title */}
      <div style={{ marginTop: 24 }}>
        <h3 style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "clamp(1.4rem, 2.2vw, 2rem)",
          letterSpacing: "-0.04em", lineHeight: 1.0,
          textTransform: "uppercase",
          color: "var(--color-ink)",
          margin: 0,
        }}>{pillar.name}</h3>
      </div>

      {/* Before / After */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 14, marginTop: "auto", paddingTop: 28 }}>
        <BeforeAfter label="BEFORE" text={pillar.before} muted />
        <BeforeAfter label="AFTER"  text={pillar.after} accent={pillar.accent} />
      </div>
    </div>
  );
}

function BeforeAfter({ label, text, muted, accent }) {
  return (
    <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
      <div style={{
        flex: "0 0 64px",
        fontFamily: "var(--font-body)", fontSize: 9,
        letterSpacing: "0.4em", textTransform: "uppercase",
        color: muted ? "var(--color-ink-dim)" : (accent || "var(--color-accent-warm)"),
        paddingTop: 4,
      }}>{label}</div>
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 13,
        lineHeight: 1.55,
        color: muted ? "var(--color-ink-dim)" : "var(--color-ink)",
        textDecoration: muted ? "line-through" : "none",
        textDecorationColor: muted ? "rgba(255,255,255,0.25)" : "transparent",
      }}>{text}</div>
    </div>
  );
}

function EndCap() {
  return (
    <div
      data-pillar-card
      style={{
        flex: "0 0 auto",
        width: "min(380px, 70vw)",
        height: "min(460px, 64vh)",
        padding: "32px 28px",
        display: "flex", flexDirection: "column", justifyContent: "center",
        gap: 24,
        background: "linear-gradient(135deg, rgba(200,204,210,0.10), rgba(200,48,47,0.10))",
        border: "1px solid rgba(200,204,210,0.26)",
        position: "relative",
        scrollSnapAlign: "center",
      }}
    >
      <h3 style={{
        fontFamily: "var(--font-display)", fontWeight: 700,
        fontSize: "clamp(1.6rem, 2.5vw, 2.3rem)",
        letterSpacing: "-0.04em", lineHeight: 0.95,
        textTransform: "uppercase",
        color: "var(--color-ink)", margin: 0,
      }}>
        One stack.
        <br />
        <span style={{ color: "var(--color-accent-warm)" }}>One line item.</span>
      </h3>
      <a
        href="#retainers"
        data-cursor="GO"
        style={{
          alignSelf: "flex-start",
          fontFamily: "var(--font-body)", fontSize: 11,
          letterSpacing: "0.3em", textTransform: "uppercase",
          color: "var(--color-base)", background: "var(--color-accent-warm)",
          padding: "12px 20px", textDecoration: "none",
        }}
      >See the retainers →</a>
    </div>
  );
}

Object.assign(window, { Infrastructure });
