/* global React */
const { useState: useStateP, useRef: useRefP } = React;

const PROJECTS = [
  {
    id: "virt",
    title: "Virtualization",
    sub: "Hyper-V & VMware infrastructure",
    desc: "Designed and managed virtualization environments across 1,500+ servers — Hyper-V clusters and VMware vSphere — including capacity planning, live migration, HA, and consolidation strategies for retail and corporate workloads.",
    stack: ["Hyper-V", "VMware vSphere", "Failover Clustering", "PowerCLI", "Veeam"],
    tag: "INFRA",
    glyph: "VM",
  },
  {
    id: "migration",
    title: "Cloud Migration",
    sub: "On-prem to Azure migration programs",
    desc: "Led on-premises to Azure migrations — assessment, landing zones, IaaS/PaaS workload re-platforming, identity sync via AAD Connect, and post-migration optimization for cost and performance.",
    stack: ["Azure Migrate", "ASR", "AAD Connect", "ARM/Bicep", "Azure Arc"],
    tag: "CLOUD",
    glyph: "MIG",
  },
  {
    id: "erp",
    title: "ERP Development",
    sub: "Custom ERP modules & integrations",
    desc: "Developed and maintained ERP modules — accounting, inventory, point-of-sale and supply-chain integrations — for retail networks operating across hundreds of stores.",
    stack: ["SQL Server", "C#", ".NET", "SSIS", "Power BI"],
    tag: "DEV",
    glyph: "ERP",
  },
  {
    id: "crm",
    title: "CRM Platform",
    sub: "Customer relationship management system",
    desc: "Built a CRM platform handling customer accounts, sales pipelines, ticketing and reporting — integrated with email/SMS gateways and ERP back-ends.",
    stack: ["Dynamics 365", "Power Platform", "REST APIs", "Azure Functions"],
    tag: "DEV",
    glyph: "CRM",
  },
  {
    id: "motorola",
    title: "Motorola Solutions Software",
    sub: "Two-way radio dispatch & integration",
    desc: "Configured and customized Motorola Solutions software stack — dispatch consoles, radio management, location services and back-office reporting for mission-critical communications.",
    stack: ["RadioCentral", "TRBONet", "SmartPTT", "SQL", "Windows Server"],
    tag: "TELECOM",
    glyph: "MOT",
  },
  {
    id: "ipsite",
    title: "IP Site Connect — MOTOTRBO",
    sub: "Wide-area digital radio networks",
    desc: "Designed and deployed MOTOTRBO IP Site Connect networks linking repeater sites over IP — radio infrastructure, network configuration, QoS tuning and operator training.",
    stack: ["MOTOTRBO", "IP Site Connect", "VPN", "QoS", "Networking"],
    tag: "TELECOM",
    glyph: "IPSC",
  },
  {
    id: "telecom",
    title: "Telecom Operations",
    sub: "Voice, data & radio convergence",
    desc: "Operated converged telecom platforms — VoIP, SIP trunking, radio over IP, and carrier-grade routing — supporting voice and data services for distributed sites.",
    stack: ["VoIP/SIP", "Cisco", "MikroTik", "MPLS", "RoIP"],
    tag: "TELECOM",
    glyph: "TEL",
  },
  {
    id: "datacenter",
    title: "Retail Data Center",
    sub: "Centralized ops for 310 stores",
    desc: "Centralized data center operations system for retail markets — telemetry, alerts, inventory sync and incident management across 1,500 servers and 6,000 users.",
    stack: ["Azure", "KQL", "PowerShell", "Log Analytics", "Power BI"],
    tag: "INFRA",
    glyph: "DC",
  },
  {
    id: "logistics",
    title: "Logistics Tracker",
    sub: "Real-time courier route tracking",
    desc: "End-to-end logistics platform that tracks delivery couriers in real time across active routes, with map visualization, ETAs, and dispatcher dashboards.",
    stack: ["React", "Node.js", "WebSockets", "PostgreSQL", "Maps API"],
    tag: "DEV",
    glyph: "ROUTE",
  },
  {
    id: "rental",
    title: "Rental Management",
    sub: "Property & equipment leasing system",
    desc: "Multi-tenant rental management software for tracking inventory, contracts, payments and customer history with admin dashboard and tenant portal.",
    stack: ["Next.js", "Prisma", "PostgreSQL", "Stripe"],
    tag: "DEV",
    glyph: "LEASE",
  },
  {
    id: "social",
    title: "Social Media Automation",
    sub: "AI-assisted content pipeline",
    desc: "Automation pipeline that schedules, generates and cross-posts content across social platforms — with template engine, queue and analytics.",
    stack: ["Power Automate", "Python", "OpenAI API", "Buffer"],
    tag: "AUTOMATION",
    glyph: "AUTO",
  },
  {
    id: "school",
    title: "Language School",
    sub: "Course platform & student CRM",
    desc: "Online platform for a language school with course catalog, scheduling, attendance tracking, payments and instructor dashboards.",
    stack: ["React", "Node.js", "MongoDB", "Twilio"],
    tag: "DEV",
    glyph: "LANG",
  },
  {
    id: "reader",
    title: "Books & Audiobooks Reader",
    sub: "Reader + audio player app",
    desc: "Reading and listening app with library sync, bookmarks, progress tracking across devices and offline mode for audiobooks.",
    stack: ["React Native", "Firebase", "AWS S3"],
    tag: "DEV",
    glyph: "READ",
  },
  {
    id: "games",
    title: "Web Games",
    sub: "Browser-based mini-games collection",
    desc: "Collection of HTML5 / Canvas web games with leaderboards, achievements and shared score backend.",
    stack: ["HTML5 Canvas", "WebGL", "Node.js"],
    tag: "DEV",
    glyph: "GAME",
  },
];

// ───────── Single project card (slide) ─────────
function ProjectSlide({ p, idx, total }) {
  return (
    <div style={{
      flex: "0 0 100%",
      scrollSnapAlign: "start",
      padding: "0 4px",
    }}>
      <div className="panel project-slide-grid" style={{
        padding: "32px 36px",
        position: "relative",
        overflow: "hidden",
      }}>
        {/* corner ID */}
        <div className="mono" style={{
          position: "absolute", top: 14, right: 18,
          fontSize: 10, letterSpacing: "0.18em",
          color: "var(--ink-dim)",
        }}>
          {String(idx + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
        </div>

        {/* LEFT — text */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{
              fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
              color: "var(--accent)", fontFamily: "JetBrains Mono, monospace",
              padding: "3px 8px", border: "1px solid var(--accent)", borderRadius: 3,
            }}>
              {p.tag}
            </span>
            <span className="ink-dim mono" style={{ fontSize: 10.5, letterSpacing: "0.16em" }}>
              ▸ ./{p.id}
            </span>
          </div>

          <h3 className="display" style={{
            fontSize: "clamp(28px, 3.6vw, 42px)",
            fontWeight: 700,
            letterSpacing: "-0.02em",
            lineHeight: 1.05,
            margin: 0,
          }}>
            {p.title}
          </h3>
          <div className="ink-mute" style={{ fontSize: 14, lineHeight: 1.4 }}>
            {p.sub}
          </div>

          <p className="ink-mute" style={{ fontSize: 14, lineHeight: 1.7, margin: "6px 0 0", maxWidth: 600 }}>
            {p.desc}
          </p>

          <div style={{ marginTop: "auto", paddingTop: 18, display: "flex", flexWrap: "wrap", gap: 6 }}>
            {p.stack.map((s) => (
              <span key={s} className="mono" style={{
                fontSize: 10.5, letterSpacing: "0.06em",
                padding: "5px 10px",
                border: "1px solid var(--line)",
                borderRadius: 4,
                color: "var(--ink-mute)",
                background: "rgba(255,255,255,0.02)",
              }}>
                {s}
              </span>
            ))}
          </div>
        </div>

        {/* RIGHT — visual block */}
        <div style={{
          border: "1px solid var(--line)",
          borderRadius: 8,
          padding: 22,
          display: "flex",
          flexDirection: "column",
          background: "linear-gradient(180deg, color-mix(in oklab, var(--accent) 4%, transparent), transparent)",
          position: "relative",
          overflow: "hidden",
          minHeight: 280,
        }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-dim)", letterSpacing: "0.18em" }}>
              SYS · {p.glyph}
            </span>
            <span style={{ display: "flex", gap: 4 }}>
              <span style={{ width: 6, height: 6, background: "var(--accent)", borderRadius: "50%" }}></span>
              <span style={{ width: 6, height: 6, background: "var(--ink-dim)", borderRadius: "50%" }}></span>
              <span style={{ width: 6, height: 6, background: "var(--ink-dim)", borderRadius: "50%" }}></span>
            </span>
          </div>

          {/* big glyph */}
          <div style={{
            flex: 1,
            display: "grid",
            placeItems: "center",
            position: "relative",
          }}>
            <div className="display" style={{
              fontSize: "clamp(56px, 8vw, 96px)",
              fontWeight: 800,
              color: "var(--accent)",
              letterSpacing: "-0.04em",
              opacity: 0.92,
              lineHeight: 0.9,
              textAlign: "center",
            }}>
              {p.glyph}
            </div>

            {/* scan dots grid */}
            <div style={{
              position: "absolute", inset: 0,
              backgroundImage: "radial-gradient(circle, color-mix(in oklab, var(--accent) 30%, transparent) 1px, transparent 1px)",
              backgroundSize: "16px 16px",
              opacity: 0.18,
              pointerEvents: "none",
            }}></div>
          </div>

          <div className="mono" style={{
            marginTop: 14,
            fontSize: 10, letterSpacing: "0.18em",
            color: "var(--ink-dim)",
            display: "flex", justifyContent: "space-between",
          }}>
            <span>// drop screenshot here</span>
            <span style={{ color: "var(--accent)" }}>● READY</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ───────── Slider component ─────────
function Projects() {
  const trackRef = useRefP(null);
  const [active, setActive] = useStateP(0);
  const [paused, setPaused] = useStateP(false);

  const goTo = (i, behavior = "smooth") => {
    const t = trackRef.current;
    if (!t) return;
    const idx = ((i % PROJECTS.length) + PROJECTS.length) % PROJECTS.length;
    t.scrollTo({ left: idx * t.clientWidth, behavior });
    setActive(idx);
  };

  const onScroll = () => {
    const t = trackRef.current;
    if (!t) return;
    const i = Math.round(t.scrollLeft / t.clientWidth);
    if (i !== active) setActive(i);
  };

  // auto-advance every 2s, pause on hover
  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => goTo(active + 1, "smooth"), 2000);
    return () => clearInterval(id);
  }, [active, paused]);

  return (
    <section id="projects" style={{ padding: "60px 28px", maxWidth: 1280, margin: "0 auto" }}>
      <div className="section-head" style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
        <span className="cmd mono" style={{ fontSize: 13 }}>$ ls ~/projects</span>
        <h2 className="h" style={{ margin: 0 }}>Projects</h2>
        <a
          href="/projects/"
          className="mono see-more-ember"
          style={{
            position: "relative", overflow: "hidden",
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "8px 14px", borderRadius: 999,
            background: "linear-gradient(180deg, #ffdf3a 0%, #ffb347 60%, #ff8a3d 100%)",
            color: "#2a0f00",
            fontSize: 12, fontWeight: 800, letterSpacing: "0.06em",
            textDecoration: "none", textTransform: "uppercase",
            border: "1px solid rgba(120,40,0,0.35)",
          }}
        >
          <span aria-hidden className="ember-glow" style={{
            position: "absolute", left: "-10%", right: "-10%", bottom: "-30%", height: "85%",
            background: "radial-gradient(60% 100% at 50% 100%, rgba(255,180,60,0.85) 0%, rgba(255,120,30,0.55) 35%, rgba(255,60,10,0.0) 75%)",
            filter: "blur(6px)", pointerEvents: "none",
            mixBlendMode: "screen",
          }}></span>
          <span aria-hidden className="ember-flicker" style={{
            position: "absolute", inset: 0, borderRadius: 999, pointerEvents: "none",
            background: "linear-gradient(180deg, rgba(255,240,180,0.35) 0%, rgba(255,255,255,0.0) 45%)",
          }}></span>
          <span style={{ position: "relative", zIndex: 1 }}>See more</span>
        </a>
        <span className="meta" style={{ marginLeft: "auto" }}>// 03</span>
      </div>
      <p className="ink-mute" style={{ maxWidth: 760, margin: "0 0 28px", fontSize: 14, lineHeight: 1.6 }}>
        Selected work across infrastructure, cloud, telecom and software development — drag, swipe, or use the arrows to navigate.
      </p>

      {/* Slider shell */}
      <div
        style={{ position: "relative" }}
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
      >
        {/* Arrows — always enabled (infinite); hidden on touch viewports via CSS */}
        <button
          onClick={() => goTo(active - 1)}
          aria-label="Previous project"
          className="slide-arrow prev"
        >
          ◀
        </button>
        <button
          onClick={() => goTo(active + 1)}
          aria-label="Next project"
          className="slide-arrow next"
        >
          ▶
        </button>

        {/* Track */}
        <div
          ref={trackRef}
          onScroll={onScroll}
          style={{
            display: "flex",
            overflowX: "auto",
            scrollSnapType: "x mandatory",
            scrollBehavior: "smooth",
            gap: 0,
            padding: "0 0 8px",
            scrollbarWidth: "none",
          }}
          className="hide-scrollbar"
        >
          {PROJECTS.map((p, i) => (
            <ProjectSlide key={p.id} p={p} idx={i} total={PROJECTS.length} />
          ))}
        </div>

        {/* Pagination dots */}
        <div style={{
          display: "flex",
          justifyContent: "center",
          gap: 8,
          marginTop: 22,
          flexWrap: "wrap",
        }}>
          {PROJECTS.map((p, i) => (
            <button
              key={p.id}
              onClick={() => goTo(i)}
              aria-label={"Go to " + p.title}
              style={{
                width: i === active ? 28 : 8,
                height: 8,
                borderRadius: 4,
                border: "none",
                background: i === active ? "var(--accent)" : "var(--line-strong)",
                cursor: "pointer",
                transition: "all .25s",
                padding: 0,
              }}
            ></button>
          ))}
        </div>

        {/* Counter */}
        <div className="mono" style={{
          textAlign: "center",
          marginTop: 12,
          fontSize: 11,
          letterSpacing: "0.18em",
          color: "var(--ink-dim)",
        }}>
          [ {String(active + 1).padStart(2, "0")} / {String(PROJECTS.length).padStart(2, "0")} ] · {PROJECTS[active].title.toUpperCase()}
        </div>
      </div>

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

window.PROJECTS = PROJECTS;
window.Projects = Projects;
