/* ============================================================
   COACH — altijd-aan begeleiding tijdens het spelen.
   Leest de live game-state en wijst de volgende stap aan met
   een bubbel + pulserende ring rond de relevante knop/zone.
   Puur state-gedreven (geen scripted stappen zoals de Tutorial).
   ============================================================ */
const { useState: useStateCoach, useEffect: useEffCoach, useRef: useRefCoach } = React;

// bepaal de huidige stap uit de context
function coachStep(ctx) {
  if (!ctx) return null;
  const { phase, committed, committedShip, selectedEligible, myUnact, sqTurn, round } = ctx;
  if (phase === "command") {
    return { text: `Ronde ${round}. Plan in het geheim wat elk schip gaat doen — klik “Plan commands”.`, anchor: ".flow-banner .btn-accent" };
  }
  if (phase === "ship") {
    if (committed) {
      return {
        text: `${committedShip} is aan zet. Doe (optioneel) een aanval en/of een manoeuvre, en klik dan “Beëindig”.`,
        anchor: ".flow-banner .fb-actions",
        steps: ["⚔ Aanval — vuur op een vijand in bereik", "↪ Manoeuvre — verplaats je schip", "Beëindig — geef de beurt door"],
      };
    }
    if (selectedEligible) {
      return { text: "Klik “Activeer — onthul dial” om dit schip te starten.", anchor: ".flow-banner .btn-accent" };
    }
    if (myUnact > 0) {
      return { text: "Kies één van je schepen om te activeren — de oplichtende op het bord, of een knop in de balk.", anchor: ".fb-chips" };
    }
    return { text: "Wachten op de tegenstander…", anchor: ".flow-banner" };
  }
  if (phase === "squadron") {
    return {
      text: sqTurn ? "Squadron-beurt: tik een squadron, sleep het binnen bereik, rol de aanval en klik “Klaar ✓”." : "Geen squadrons meer — ga door naar de status-fase.",
      anchor: ".flow-banner",
    };
  }
  if (phase === "status") {
    return { text: round >= 6 ? "Laatste ronde — sluit het potje af en bekijk de eindstand." : "Sluit de ronde af: tokens herstellen en het initiatief wisselt.", anchor: ".flow-banner .btn-accent" };
  }
  return null;
}

function Coach({ ctx, onDismiss }) {
  const [rect, setRect] = useStateCoach(null);
  const step = coachStep(ctx);
  const stepRef = useRefCoach(step);
  stepRef.current = step;

  useEffCoach(() => {
    let timer;
    const tick = () => {
      const s = stepRef.current;
      const el = s && s.anchor ? document.querySelector(s.anchor) : null;
      if (el) { const r = el.getBoundingClientRect(); setRect({ x: r.left, y: r.top, w: r.width, h: r.height }); }
      else setRect(null);
      timer = setTimeout(tick, 300);
    };
    tick();
    return () => clearTimeout(timer);
  }, []);

  if (!step) return null;
  const pad = 8;
  let bubble = { left: 16, bottom: 16 };
  let place = "float";
  if (rect) {
    const below = rect.y < window.innerHeight * 0.5;
    const cx = Math.min(Math.max(rect.x + rect.w / 2, 190), window.innerWidth - 190);
    place = below ? "below" : "above";
    bubble = below
      ? { left: cx, top: rect.y + rect.h + pad + 8, transform: "translateX(-50%)" }
      : { left: cx, top: rect.y - pad - 8, transform: "translate(-50%,-100%)" };
  }

  return (
    <>
      {rect ? <div className="coach-ring" style={{ left: rect.x - 5, top: rect.y - 5, width: rect.w + 10, height: rect.h + 10 }} /> : null}
      <div className={"coach-bubble" + (rect ? "" : " coach-float")} style={rect ? bubble : { left: 16, bottom: 16 }} data-place={place}>
        <div className="coach-head">
          <span className="coach-badge">Coach</span>
          <button className="coach-x" title="Coach uitzetten" onClick={onDismiss}>✕</button>
        </div>
        <div className="coach-text">{step.text}</div>
        {step.steps ? (
          <ul className="coach-steps">{step.steps.map((s, i) => <li key={i}>{s}</li>)}</ul>
        ) : null}
      </div>
    </>
  );
}

Object.assign(window, { Coach, coachStep });
