const body = document.body;
const loader = document.querySelector(".loader");
const menuToggle = document.querySelector(".menu-toggle");
const siteNav = document.querySelector(".site-nav");
const observedItems = document.querySelectorAll(".observe");
const projectStack = document.querySelector("[data-project-stack]");
const amsStack = document.querySelector("[data-ams-stack]");
const supportStack = document.querySelector("[data-support-stack]");
const digitrakStack = document.querySelector("[data-digitrak-stack]");
const cardStack = document.querySelector("[data-card-stack]");
const hocCardStack = document.querySelector("[data-hoc-card-stack]");

const ceonProjectModules = [
  {
    kicker: "01 / Storefront",
    title: "A calm landing page for serious energy decisions",
    meta: "Homepage / Product positioning",
    body:
      "The Ceon Energy homepage frames solar, inverter, battery, and street lighting solutions around trust: clear claims, visible product ranges, quote actions, and service reassurance.",
    bullets: [
      "Hero section with immediate product-service clarity",
      "Quote and catalogue entry points",
      "Proof points for system design, quality components, and maintenance",
    ],
  },
  {
    kicker: "02 / Catalogue",
    title: "A product system that can be filtered without friction",
    meta: "Products / Discovery",
    body:
      "The catalogue organizes batteries, inverters, solar panels, and street lights into scannable cards with category tags, featured states, stock messaging, prices, and cart actions.",
    bullets: [
      "Sidebar filters for categories and price range",
      "Product cards designed for fast comparison",
      "Clear commerce states for stock, price, and add-to-cart",
    ],
  },
  {
    kicker: "03 / Planning",
    title: "A project planner that turns needs into quote-ready intent",
    meta: "Planner / Conversion",
    body:
      "The project planner concept helps customers move from vague energy needs to a structured brief, giving Ceon Energy enough context to recommend the right setup.",
    bullets: [
      "Use-case driven planning for homes, SMEs, and businesses",
      "Guided flow for backup power and storage requirements",
      "Designed to support sales follow-up without overwhelming users",
    ],
  },
  {
    kicker: "04 / System",
    title: "A visual language built for utility, clarity, and scale",
    meta: "Design system / Frontend",
    body:
      "The interface uses a restrained green system, spacious cards, soft borders, and consistent product metadata so the experience feels dependable across landing, catalogue, and quote flows.",
    bullets: [
      "Reusable navigation, buttons, product cards, and filter controls",
      "Responsive layouts for desktop and mobile shopping",
      "A structure ready for future product and service expansion",
    ],
  },
];

const amsProjectModules = [
  {
    kicker: "01 / Command Center",
    title: "Real-time visibility for every company asset",
    meta: "Dashboard / Operations",
    body:
      "The dashboard gives HOCCAPITAL a fast operational snapshot: total assets, assigned items, available inventory, repairs, damaged or lost items, and total portfolio value.",
    bullets: [
      "Asset health and availability at a glance",
      "Status cards for leadership and operations teams",
      "A command-center visual language for internal confidence",
    ],
  },
  {
    kicker: "02 / Secure Access",
    title: "A login experience that feels private and intentional",
    meta: "Authentication / Internal tools",
    body:
      "The member login introduces the system as an internal console, with a focused sign-in flow and premium HOCCAPITAL brand atmosphere before users enter the workspace.",
    bullets: [
      "Dedicated member login surface",
      "Clear internal-use positioning",
      "High-contrast interface designed for trust and control",
    ],
  },
  {
    kicker: "03 / Asset Registry",
    title: "Searchable records for tracking and accountability",
    meta: "Tables / Asset management",
    body:
      "The all-assets view turns the company inventory into a searchable registry with asset tags, categories, state/substate labels, assignment fields, locations, cost, and bulk actions.",
    bullets: [
      "Search by name, tag, serial, and category",
      "State and substate filtering for fast triage",
      "Import, export CSV, print labels, and add-asset actions",
    ],
  },
  {
    kicker: "04 / Reporting Flow",
    title: "Built to replace scattered spreadsheets with one source of truth",
    meta: "Reporting / Process design",
    body:
      "A.M.S centralizes everyday asset workflows so teams can maintain cleaner records, reduce manual follow-ups, and create better audit trails across departments and offices.",
    bullets: [
      "Portfolio value and purchase cost visibility",
      "Maintenance and damaged/lost tracking",
      "Designed for repeated daily operational use",
    ],
  },
];

const supportProjectModules = [
  {
    kicker: "01 / Analytics",
    title: "A service desk view that turns support volume into signal",
    meta: "Dashboard / IT admin",
    body:
      "The analytics dashboard gives IT admins an immediate read on ticket volume, resolved requests, first response time, SLA compliance, and ARIA deflection.",
    bullets: [
      "Time-range filters for Today, 7 Days, 30 Days, and 90 Days",
      "Performance cards for ticket health and response behavior",
      "Charts for category distribution and ticket activity over time",
    ],
  },
  {
    kicker: "02 / Member Portal",
    title: "A secure entry point for internal operations",
    meta: "Authentication / Access",
    body:
      "The login experience frames the support desk as a private internal operations portal, with a premium HOCCAPITAL look and clear member-only access cues.",
    bullets: [
      "Credential-based access flow",
      "Company SSO unavailable state",
      "Designed to feel secure without adding friction",
    ],
  },
  {
    kicker: "03 / Request Flow",
    title: "A structure for moving from issue to resolution",
    meta: "Tickets / Workflow design",
    body:
      "The system supports the everyday service workflow: new requests, user tickets, all-ticket management, agent assignment, knowledge base guidance, and admin oversight.",
    bullets: [
      "Clear navigation for users and IT admins",
      "Knowledge base and ARIA chat support entry points",
      "Admin tools for agent and user management",
    ],
  },
  {
    kicker: "04 / Operations System",
    title: "Designed for calmer support teams and better reporting",
    meta: "System design / Reporting",
    body:
      "The product reduces operational noise by giving teams a single place to understand service demand, report on performance, and keep internal requests moving.",
    bullets: [
      "SLA and response-time visibility",
      "Reporting-ready service desk metrics",
      "Premium dark interface aligned with HOCCAPITAL systems",
    ],
  },
];

const digitrakProjectModules = [
  {
    kicker: "01 / Access",
    title: "A private entry point for high-trust users",
    meta: "Authentication / Member access",
    body:
      "DigiTrack opens with an invitation-only posture and secure operator login, reinforcing that the product is built for confidential mobility intelligence rather than public browsing.",
    bullets: [
      "Member login and operator passphrase flows",
      "Trusted device and request-access cues",
      "Premium visual system for confidentiality and control",
    ],
  },
  {
    kicker: "02 / Intelligence Model",
    title: "Jurisdiction as a measurable operating signal",
    meta: "Product strategy / Data model",
    body:
      "The platform frames jurisdictions, members, accounts, applications, and mobility events as linked signals that administrators can search, compare, and export.",
    bullets: [
      "Doctrine and pillar pages define the product premise",
      "Global member and account intelligence views",
      "Exportable intelligence for operational reporting",
    ],
  },
  {
    kicker: "03 / Admin Console",
    title: "One dashboard for members, accounts, and applications",
    meta: "Dashboard / Operations",
    body:
      "The admin console gives operators a real-time overview of active members, pending applications, total accounts, deployed capital, and recent activity across the network.",
    bullets: [
      "Search across sovereign IDs and jurisdiction records",
      "Quick actions for member invites, accounts, and events",
      "Live network and ledger-sync indicators",
    ],
  },
  {
    kicker: "04 / Travel Matrix",
    title: "Movement patterns translated into actionable intelligence",
    meta: "Mobility / Signal mapping",
    body:
      "The Travel Matrix turns member movement into a map-based intelligence surface, helping administrators see active routes, regional anomalies, and members in transit.",
    bullets: [
      "Live flow map for jurisdiction movement density",
      "Anomaly callouts with region-level signal changes",
      "Active member transit list for fast drill-in",
    ],
  },
];

const businessCardModules = [
  {
    kicker: "01 / Positioning",
    title: "A first impression built around premium trust",
    meta: "Brand tone / Client handoff",
    body:
      "The card was designed to make the dealership feel curated and established, using a restrained luxury palette and strong hierarchy instead of loud promotional styling.",
    bullets: [
      "Black and gold treatment for premium automotive cues",
      "Minimal structure that keeps the dealership identity central",
      "Designed for in-person handoff and digital portfolio preview",
    ],
  },
  {
    kicker: "02 / Layout",
    title: "Front and back treated as one brand system",
    meta: "Print design / Information hierarchy",
    body:
      "The front carries the visual identity while the back organizes contact details with enough spacing to feel intentional, not crowded.",
    bullets: [
      "Distinct front and reverse compositions",
      "Clear contact hierarchy for quick scanning",
      "Balanced decorative detail with practical readability",
    ],
  },
  {
    kicker: "03 / Delivery",
    title: "Vector artwork prepared for sharp output",
    meta: "SVG / Production asset",
    body:
      "Using SVG keeps the design crisp at multiple preview sizes and supports a cleaner handoff for print preparation or future brand adaptations.",
    bullets: [
      "Crisp vector output for display and print workflows",
      "Reusable front and back artwork files",
      "Portfolio page displays the actual SVG card assets",
    ],
  },
];

const hocCardModules = [
  {
    kicker: "01 / Brand Signal",
    title: "A small-format artifact with executive presence",
    meta: "Brand identity / Print design",
    body:
      "The HOC Capital Club card was designed to feel private and premium, using restrained composition, dark contrast, and gold detailing to match the club's executive tone.",
    bullets: [
      "Black-and-gold visual language aligned with HOC Capital Club",
      "Minimal structure for a confident first impression",
      "Designed for high-trust, in-person introductions",
    ],
  },
  {
    kicker: "02 / Front and Back",
    title: "Two sides working as one identity system",
    meta: "Layout / Hierarchy",
    body:
      "The front establishes the brand presence while the back supports recognition and follow-up, keeping the card useful without losing the luxury feel.",
    bullets: [
      "Front side focused on brand impact",
      "Reverse side designed for practical contact use",
      "Balanced spacing for readability at business-card scale",
    ],
  },
  {
    kicker: "03 / Production",
    title: "Crisp vector artwork ready for handoff",
    meta: "SVG / Print-ready asset",
    body:
      "The SVG source preserves sharp detail and gives the design flexibility for preview, print preparation, and future brand-system extensions.",
    bullets: [
      "Vector artwork for clean scaling",
      "Separate front and back deliverables",
      "Portfolio preview uses the actual card SVGs",
    ],
  },
];

document.addEventListener("DOMContentLoaded", () => {
  const cursorGlow = document.createElement("div");
  cursorGlow.className = "cursor-glow";
  document.body.appendChild(cursorGlow);

  document.addEventListener("mousemove", (event) => {
    const xPercent = `${(event.clientX / window.innerWidth) * 100}%`;
    const yPercent = `${(event.clientY / window.innerHeight) * 100}%`;

    cursorGlow.style.left = `${event.clientX}px`;
    cursorGlow.style.top = `${event.clientY}px`;
    cursorGlow.classList.add("is-active");

    document.body.style.setProperty("--bg-x", xPercent);
    document.body.style.setProperty("--bg-y", yPercent);
  });

  if (projectStack) {
    renderProjectPanels(projectStack, ceonProjectModules);
  }

  if (amsStack) {
    renderProjectPanels(amsStack, amsProjectModules);
  }

  if (supportStack) {
    renderProjectPanels(supportStack, supportProjectModules);
  }

  if (digitrakStack) {
    renderProjectPanels(digitrakStack, digitrakProjectModules);
  }

  if (cardStack) {
    renderProjectPanels(cardStack, businessCardModules);
  }

  if (hocCardStack) {
    renderProjectPanels(hocCardStack, hocCardModules);
  }
});

function renderProjectPanels(stack, modules) {
  stack.innerHTML = modules
    .map(
      (project, index) => `
        <article class="project-panel${index === 0 ? " is-open" : ""}">
          <button
            class="project-panel__button"
            type="button"
            aria-expanded="${index === 0 ? "true" : "false"}"
          >
            <span>
              <span class="project-panel__kicker">${project.kicker}</span>
              <span class="project-panel__title">${project.title}</span>
            </span>
            <span class="project-panel__icon" aria-hidden="true">+</span>
          </button>
          <div class="project-panel__content">
            <div class="project-panel__meta">
              <span>Scope</span>
              ${project.meta}
            </div>
            <div>
              <p>${project.body}</p>
              <ul class="project-panel__bullets">
                ${project.bullets.map((bullet) => `<li>${bullet}</li>`).join("")}
              </ul>
            </div>
          </div>
        </article>
      `
    )
    .join("");

  stack.querySelectorAll(".project-panel__button").forEach((button) => {
    button.addEventListener("click", () => {
      const panel = button.closest(".project-panel");
      const isOpen = panel.classList.contains("is-open");

      stack.querySelectorAll(".project-panel").forEach((item) => {
        item.classList.remove("is-open");
        item
          .querySelector(".project-panel__button")
          .setAttribute("aria-expanded", "false");
      });

      if (!isOpen) {
        panel.classList.add("is-open");
        button.setAttribute("aria-expanded", "true");
      }
    });
  });
}

window.addEventListener("load", () => {
  window.setTimeout(() => {
    loader?.classList.add("is-hidden");
    body.classList.remove("is-loading");
    body.classList.add("is-ready");

    const heroTitle = document.querySelector(".hero h1");

    if (heroTitle && !heroTitle.dataset.letterReveal) {
      const characters = [...heroTitle.textContent.trim()];
      heroTitle.textContent = "";
      heroTitle.dataset.letterReveal = "true";

      characters.forEach((character, index) => {
        const span = document.createElement("span");
        span.innerHTML = character === " " ? "&nbsp;" : character;
        span.style.display = "inline-block";
        span.style.opacity = "0";
        span.style.transform = "translateY(0.4em)";
        span.style.transition = "opacity 500ms ease, transform 500ms ease";
        span.style.transitionDelay = `${600 + index * 38}ms`;
        heroTitle.appendChild(span);

        requestAnimationFrame(() => {
          span.style.opacity = "1";
          span.style.transform = "translateY(0)";
        });
      });
    }
  }, 1500);
});

menuToggle.addEventListener("click", () => {
  const isOpen = menuToggle.getAttribute("aria-expanded") === "true";
  menuToggle.setAttribute("aria-expanded", String(!isOpen));
  menuToggle.setAttribute("aria-label", isOpen ? "Open menu" : "Close menu");
  menuToggle.classList.toggle("is-open", !isOpen);
  siteNav.classList.toggle("is-open", !isOpen);
});

siteNav.addEventListener("click", (event) => {
  if (event.target.closest("a")) {
    menuToggle.setAttribute("aria-expanded", "false");
    menuToggle.setAttribute("aria-label", "Open menu");
    menuToggle.classList.remove("is-open");
    siteNav.classList.remove("is-open");
  }
});

const itemObserver = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add("is-visible");
        itemObserver.unobserve(entry.target);
      }
    });
  },
  {
    threshold: 0.22,
  }
);

observedItems.forEach((item) => itemObserver.observe(item));
