// Services.jsx — showroom gradient + giant watermark + car w/ glass callout pills
// Pills expand into image+text cards on click. Card anchors at the pill's position
// and grows toward whichever corner of the stage has the most room. Only one open
// at a time; click outside closes.

function GlassPill({ label, dimmed, x, y, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={"rd-pill" + (dimmed ? " is-dimmed" : "")}
      style={{ left: x, top: y }}
    >
      <span>{label}</span>
      <span className="rd-pill__plus">+</span>
    </button>
  );
}

const ServiceCard = React.forwardRef(function ServiceCard({ x, y, title, body, img }, ref) {
  // Decide which corner of the card anchors at (x, y) based on the pill's
  // position within the stage — if the pill sits in the right half, the
  // card grows leftward; if in the bottom half, it grows upward.
  const xPct = parseFloat(x);
  const yPct = parseFloat(y);
  const fromRight  = xPct >= 50;
  const fromBottom = yPct >= 50;

  const pos = {};
  if (fromRight) pos.right = `calc(100% - ${x})`;
  else           pos.left  = x;
  if (fromBottom) pos.bottom = `calc(100% - ${y})`;
  else            pos.top    = y;

  // Animation origin matches the anchor corner so it scales out from the pill.
  const origin = `${fromRight ? "right" : "left"} ${fromBottom ? "bottom" : "top"}`;

  return (
    <div
      ref={ref}
      className="rd-scard"
      style={{ ...pos, transformOrigin: origin }}
    >
      <div className="rd-scard__img" style={{ backgroundImage: `url(${img})` }} />
      <div className="rd-scard__body">
        <h3 className="rd-scard__title">{title}</h3>
        <p className="rd-scard__copy">{body}</p>
        <a href="#" className="rd-scard__cta" aria-label={`Learn more about ${title}`}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
            <path d="M3 13L13 3M13 3H5M13 3V11" stroke="white" strokeWidth="2" strokeLinecap="square" />
          </svg>
        </a>
      </div>
    </div>
  );
});

function Services() {
  const callouts = [
    { id: "collision", label: "Full Collision Repair",        x: "8%",  y: "44%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Certified technicians restore all makes and models to factory spec.",
      img: "assets/service-placeholder.webp" },
    { id: "glass",     label: "Glass Repair & Replacement",   x: "20%", y: "26%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. From chips to full windshield replacement using OEM glass.",
      img: "assets/service-placeholder.webp" },
    { id: "scratch",   label: "Scratch Repair & Car Painting", x: "26%", y: "62%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Spectral paint matching with multi-stage finish and clear coat.",
      img: "assets/service-placeholder.webp" },
    { id: "ac",        label: "Air Condition Repair",         x: "38%", y: "33%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Full HVAC diagnostics, recharge, and component replacement.",
      img: "assets/service-placeholder.webp" },
    { id: "align",     label: "Wheel Alignment",              x: "62%", y: "70%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Precision 4-wheel laser alignment for handling and tire life.",
      img: "assets/service-placeholder.webp" },
    { id: "detail",    label: "Auto Detailing",               x: "70%", y: "52%",
      body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interior and exterior detail packages with paint correction.",
      img: "assets/service-placeholder.webp" },
  ];

  const [active, setActive] = React.useState(null);
  const cardRef = React.useRef(null);

  // Outside-click closes. Any mousedown that isn't on the open card collapses
  // it. Clicks on another pill still open that pill's card because the pill's
  // onClick fires after the mousedown-driven close.
  React.useEffect(() => {
    if (!active) return;
    const onDown = (e) => {
      if (cardRef.current && cardRef.current.contains(e.target)) return;
      setActive(null);
    };
    const onKey = (e) => { if (e.key === "Escape") setActive(null); };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [active]);

  const activeCallout = callouts.find((c) => c.id === active);

  return (
    <section className="rd-services" data-screen-label="01 Home / Services">
      <div className="rd-services__mark">SERVICES</div>
      <h2 className="rd-services__title">Our Services</h2>
      <div className="rd-services__bar" />
      <div className={"rd-services__stage" + (active ? " has-open" : "")}>
        <img className="rd-services__car" src="assets/services-car.png" alt="" />
        {callouts.map((c) => (
          active === c.id ? null : (
            <GlassPill
              key={c.id}
              {...c}
              dimmed={active && active !== c.id}
              onClick={() => setActive(c.id)}
            />
          )
        ))}
        {activeCallout && (
          <ServiceCard
            ref={cardRef}
            key={activeCallout.id}
            x={activeCallout.x}
            y={activeCallout.y}
            title={activeCallout.label}
            body={activeCallout.body}
            img={activeCallout.img}
          />
        )}
      </div>
      <div className="rd-services__copy">
        <p>
          At RAYDAR, we offer comprehensive auto body repair services, from minor dents and dings
          to repairing your accident damage. Whether you've had an accident, tangled with Mother
          Nature or want to freshen up your car's look, you can relax, we'll take it from here!
        </p>
        <button className="btn-primary btn-primary--lg">SEE All Services</button>
      </div>
    </section>
  );
}

window.Services = Services;
