/* global React */
const { useState: useStatePL, useEffect: useEffectPL, useRef: useRefPL } = React;

// =============================================================================
// The Popup Library section
//
// Lives between Features and How-it-works. Full-bleed dark section using the
// supplied perspective render of ZBrush + the popup library window as the bg.
// Four callout cards float around the popup window connected to it via thin
// orange leader lines drawn in an inline SVG that shares the stage's aspect
// ratio (so everything stays aligned as the section scales).
//
// Each callout has:
//   - position : where the card sits relative to the stage (top/left/right %)
//   - target   : the point on the bg image the leader line touches (x%, y%)
//   - anchor   : which side of the card the leader line starts from
// =============================================================================

const CALLOUTS = [
{
  id: 'pin',
  side: 'right',
  title: 'Pin it!',
  body: "Pin the library so it stays on top of ZBrush while you load and test your brushes.",
  // Position the card top-right
  style: { top: '14%', right: '6%', width: 240 },
  // Anchor: line leaves from the card's LEFT edge
  anchor: { side: 'left', xPct: 0, yPct: 50 },
  // Target on the bg: the Pin button in the popup
  target: { x: 67.5, y: 24 }
},
{
  id: 'search',
  side: 'left',
  title: 'Search',
  body: "Start typing and the library filters to show the brushes you're looking for.",
  style: { top: '52%', left: '6%', width: 230 },
  anchor: { side: 'right', xPct: 100, yPct: 50 },
  // Search bar at top-left of the popup
  target: { x: 35.5, y: 46.5 }
},
{
  id: 'categories',
  side: 'left',
  title: 'Categories',
  body: "Organised by your folders. Click the star to add a brush to favourites.",
  style: { top: '80%', left: '6%', width: 230 },
  anchor: { side: 'right', xPct: 100, yPct: 50 },
  // Category sidebar in the popup
  target: { x: 33, y: 78 }
},
{
  id: 'popup',
  side: 'right',
  title: 'Pop up library',
  body: "RadialZ also includes a popup library window you can invoke at any time to search every brush you own. One click and it loads into ZBrush.",
  style: { top: '64%', right: '6%', width: 270 },
  anchor: { side: 'left', xPct: 0, yPct: 50 },
  // General popup window target (bottom-right of the popup window)
  target: { x: 70, y: 86 }
}];


// Compute where the leader line starts (in stage % coords) given the card's
// position style + anchor. We use the card's offset position from edges plus
// the anchor side to figure out an exact (x, y) in stage coords.
//
// `cardRect` is computed at render time by measuring the card; we use it for
// pixel-perfect anchoring. Until refs settle, fall back to the rough estimate
// based on the position style.
const computeAnchor = (cardRef, stageRef, anchor) => {
  const card = cardRef.current;
  const stage = stageRef.current;
  if (!card || !stage) return null;
  const cr = card.getBoundingClientRect();
  const sr = stage.getBoundingClientRect();
  if (!sr.width || !sr.height) return null;
  const xPx = cr.left - sr.left + cr.width * anchor.xPct / 100;
  const yPx = cr.top - sr.top + cr.height * anchor.yPct / 100;
  return { x: xPx / sr.width * 100, y: yPx / sr.height * 100 };
};

const PopupCallout = React.forwardRef(({ data }, ref) =>
<div className={`popup-callout popup-callout--${data.side}`} style={{ ...data.style, backgroundColor: "rgb(44, 44, 44)" }} ref={ref}>
    <div className="popup-callout-title" style={{ color: "rgb(248, 107, 51)" }}>{data.title}</div>
    <div className="popup-callout-body">{data.body}</div>
  </div>
);

const Popup = () => {
  const stageRef = useRefPL(null);
  const cardRefs = useRefPL(CALLOUTS.map(() => React.createRef()));
  const [anchors, setAnchors] = useStatePL([]);

  // Recompute leader line anchor coords whenever the section resizes.
  useEffectPL(() => {
    const measure = () => {
      const next = CALLOUTS.map((c, i) => {
        const a = computeAnchor(cardRefs.current[i], stageRef, c.anchor);
        return a ? { from: a, to: c.target } : null;
      });
      setAnchors(next);
    };
    measure();
    const ro = new ResizeObserver(measure);
    if (stageRef.current) ro.observe(stageRef.current);
    window.addEventListener('resize', measure);
    const t = setTimeout(measure, 220);
    return () => {
      ro.disconnect();
      window.removeEventListener('resize', measure);
      clearTimeout(t);
    };
  }, []);

  const bgUrl = window.__resources && window.__resources['popup-bg'] || '';

  return (
    <section className="popup-wrap" id="popup" data-screen-label="05 Popup library" ref={stageRef}>
      {/* Warm dome bleeding down from Features (warm) into this dark section.
            Same SVG used between Features and How before this section existed. */}
      <svg className="how-top-curve" viewBox="0 0 1440 240" preserveAspectRatio="none" aria-hidden="true">
        <path d="M0,0 Q720,300 1440,0 L1440,0 Z" fill="#ede7da" />
      </svg>

      <img className="popup-bg" src={bgUrl} alt="" draggable="false" />

      {/* Heading overlay — top-left, sits below the warm dome */}
      <div className="popup-head">
        <div className="lead">The popup library</div>
        <h2 className="popup-h2">
          Popup Library, <span className="it">organised and searchable.</span>
        </h2>
      </div>

      {/* Leader lines */}
      <svg
        className="popup-leaders"
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        aria-hidden="true">
        
        {anchors.map((a, i) => {
          if (!a) return null;
          const { from, to } = a;
          const midX = (from.x + to.x) / 2;
          const d = `M${from.x} ${from.y} L${midX} ${from.y} L${midX} ${to.y} L${to.x} ${to.y}`;
          return (
            <g key={i}>
              <path d={d}
              fill="none"
              stroke="#f0651f"
              strokeWidth="0.16"
              strokeLinecap="round"
              strokeLinejoin="round"
              vectorEffect="non-scaling-stroke" />
              
              <circle cx={to.x} cy={to.y} r="0.55" fill="#f0651f" />
              <circle cx={to.x} cy={to.y} r="0.25" fill="#fff" />
            </g>);

        })}
      </svg>

      {/* Callouts */}
      {CALLOUTS.map((c, i) =>
      <PopupCallout key={c.id} data={c} ref={cardRefs.current[i]} />
      )}
    </section>);

};

window.Popup = Popup;