/* ============================================================
   SHIP TOKEN — angular silhouette, faction colour, rotatable,
   draggable (pointer events, tap vs drag threshold), arc lines
   ============================================================ */
const { useRef: useRefTok } = React;

const HULL_PATHS = {
  small:  "M50 7 L68 60 L60 86 L40 86 L32 60 Z",
  medium: "M50 5 L73 54 L72 90 L28 90 L27 54 Z",
  large:  "M50 4 L64 24 L78 68 L69 94 L31 94 L22 68 L36 24 Z",
  huge:   "M50 3 L61 20 L70 93 L30 93 L39 20 Z",
};
const NOSE_PATHS = {
  small:  "M50 7 L60 34 L40 34 Z",
  medium: "M50 5 L63 34 L37 34 Z",
  large:  "M50 4 L62 30 L38 30 Z",
  huge:   "M50 3 L59 28 L41 28 Z",
};

function ShipHull({ baseSize }) {
  const d = HULL_PATHS[baseSize] || HULL_PATHS.medium;
  const nose = NOSE_PATHS[baseSize] || NOSE_PATHS.medium;
  return (
    <svg className="token-hull-shape" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
      <path className="fill" d={d} />
      <path className="nose" d={nose} />
      <path className="stroke" d={d} />
    </svg>
  );
}

function ChitHull() {
  // rounded plate with a nose arrow — a flat "counter" look
  const plate = "M16 26 H84 Q92 26 92 34 V90 Q92 96 86 96 H14 Q8 96 8 90 V34 Q8 26 16 26 Z";
  return (
    <svg className="token-hull-shape" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
      <path className="fill" d={plate} />
      <path className="nose" d="M50 6 L66 28 L34 28 Z" />
      <path className="stroke" d={plate} />
      <path className="stroke" d="M50 6 L66 28 L34 28 Z" />
    </svg>
  );
}

function RangeArcs({ px, baseSize }) {
  // ringen volgen exact de range-logica van de engine (RANGE_DIST)
  const rL = RANGE_DIST.long, rM = RANGE_DIST.medium, rC = RANGE_DIST.close;
  const D = rL * 2 + 28, c = D / 2;
  const pol = (ang, r) => [c + Math.cos((ang - 90) * Math.PI / 180) * r, c + Math.sin((ang - 90) * Math.PI / 180) * r];
  // arclijnen lopen door de hoeken van de basis, niet over de 45°-diagonalen —
  // dezelfde hoek die hull-zones.js voor de legaliteit gebruikt
  const alpha = arcHalfAngle({ baseSize }, BASE_SIZES);
  const diag = [alpha, 180 - alpha, 180 + alpha, 360 - alpha];
  return (
    <svg className="range-arcs" width={D} height={D} viewBox={`0 0 ${D} ${D}`}
         style={{ left: "50%", top: "50%", marginLeft: -c, marginTop: -c }}>
      {/* reach bands — lighter the further out */}
      <circle className="rng-band rng-long" cx={c} cy={c} r={rL} />
      <circle className="rng-band rng-med"  cx={c} cy={c} r={rM} />
      <circle className="rng-band rng-close" cx={c} cy={c} r={rC} />
      {/* ring boundaries */}
      <circle className="rng-ring" cx={c} cy={c} r={rL} />
      <circle className="rng-ring" cx={c} cy={c} r={rM} />
      <circle className="rng-ring" cx={c} cy={c} r={rC} />
      {/* arc divider lines (front/rear/left/right) */}
      {diag.map((a) => { const [x, y] = pol(a, rL); return <line key={a} className="rng-arcline" x1={c} y1={c} x2={x} y2={y} />; })}
      {/* range labels up the front axis */}
      <text className="rng-lbl" x={c} y={c - rC + 15} textAnchor="middle">CLOSE</text>
      <text className="rng-lbl" x={c} y={c - rM + 15} textAnchor="middle">MEDIUM</text>
      <text className="rng-lbl" x={c} y={c - rL + 15} textAnchor="middle">LONG</text>
      {/* arc letters */}
      <text className="rng-arc-tag" x={c} y={c - rC * 0.46} textAnchor="middle">F</text>
      <text className="rng-arc-tag" x={c} y={c + rC * 0.56} textAnchor="middle">R</text>
      <text className="rng-arc-tag" x={c - rC * 0.52} y={c + 4} textAnchor="middle">L</text>
      <text className="rng-arc-tag" x={c + rC * 0.52} y={c + 4} textAnchor="middle">R</text>
    </svg>
  );
}

function ArcOverlay({ px }) {
  const pad = px * 0.34;
  const W = px + pad * 2, c = W / 2;
  return (
    <svg className="arcs" width={W} height={W} viewBox={`0 0 ${W} ${W}`}
         style={{ left: -pad, top: -pad }}>
      <line className="arc-line" x1={pad * 0.4} y1={pad * 0.4} x2={W - pad * 0.4} y2={W - pad * 0.4} />
      <line className="arc-line" x1={W - pad * 0.4} y1={pad * 0.4} x2={pad * 0.4} y2={W - pad * 0.4} />
      <text className="arc-tag" x={c} y={pad * 0.7} textAnchor="middle">F</text>
      <text className="arc-tag" x={c} y={W - pad * 0.34} textAnchor="middle">R</text>
      <text className="arc-tag" x={pad * 0.62} y={c + 3} textAnchor="middle">L</text>
      <text className="arc-tag" x={W - pad * 0.62} y={c + 3} textAnchor="middle">R</text>
    </svg>
  );
}

function ShipToken({ ship, selected, zoom, showArcs, tokenStyle, eligible, spent, locked, movable = true, onSelect, onMove, onDragState }) {
  const px = BASE_SIZES[ship.baseSize].px;
  const fc = FACTIONS[ship.faction].color;
  const drag = useRefTok(null);

  const onPointerDown = (e) => {
    e.stopPropagation();
    e.currentTarget.setPointerCapture(e.pointerId);
    drag.current = { x0: e.clientX, y0: e.clientY, sx: ship.x, sy: ship.y, moved: false };
  };
  const onPointerMove = (e) => {
    const d = drag.current; if (!d || !movable) return; // niet-movable: wel aantikken, niet verslepen
    const dx = e.clientX - d.x0, dy = e.clientY - d.y0;
    if (!d.moved && Math.hypot(dx, dy) > 3) { d.moved = true; onDragState && onDragState(true); }
    if (d.moved) onMove(ship.id, d.sx + dx / zoom, d.sy + dy / zoom);
  };
  const onPointerUp = (e) => {
    const d = drag.current; drag.current = null;
    try { e.currentTarget.releasePointerCapture(e.pointerId); } catch (_) {}
    if (d && d.moved) { onDragState && onDragState(false); }
    else { onSelect(ship.id); }
  };

  const hullPct = ship.maxHull ? ship.hull / ship.maxHull : 1;
  const hullCls = ship.hull <= 0 ? "crit" : hullPct <= 0.34 ? "crit" : hullPct <= 0.6 ? "low" : "";

  return (
    <div className="token" data-selected={selected} data-destroyed={ship.hull <= 0}
         data-eligible={eligible || undefined} data-spent={spent || undefined} data-locked={locked || undefined}
         style={{ left: ship.x, top: ship.y, width: px, height: px,
                  transform: `translate(-50%,-50%) rotate(${ship.facing}deg)`, "--fc": fc }}
         onPointerDown={locked ? undefined : onPointerDown} onPointerMove={locked ? undefined : onPointerMove}
         onPointerUp={locked ? undefined : onPointerUp} onPointerCancel={locked ? undefined : onPointerUp}>
      <div className="token-ring" />
      {eligible ? <div className="token-eligible-ring" /> : null}
      {selected && showArcs ? <RangeArcs px={px} baseSize={ship.baseSize} /> : null}
      <div className="token-body" style={{ width: px, height: px }}>
        {tokenStyle === "chit" ? <ChitHull /> : <ShipHull baseSize={ship.baseSize} />}
        {/* counter-rotate label so text stays upright */}
        <div className="token-label" style={{ transform: `translate(-50%,-50%) rotate(${-ship.facing}deg)` }}>
          <span className="token-name">{ship.name}</span>
          <span className={"token-hullnum " + hullCls}>{ship.hull}</span>
        </div>
      </div>
      {ship.statsMissing ? (
        <div className="token-badge" title="Stats ontbreken"
             style={{ transform: `rotate(${-ship.facing}deg)` }}>!</div>
      ) : null}
    </div>
  );
}

Object.assign(window, { ShipToken, HULL_PATHS, NOSE_PATHS });
