/* ============================================================
   ROSTER — all ships grouped by faction, squadrons, entry points
   ============================================================ */
function HullBar({ hull, max }) {
  const pct = max ? Math.max(0, Math.min(1, hull / max)) : 0;
  const cls = hull <= 0 ? "crit" : pct <= 0.34 ? "crit" : pct <= 0.6 ? "low" : "";
  return <div className="hullbar"><i className={cls} style={{ width: `${pct * 100}%` }} /></div>;
}

function Roster({ ships, squadrons, selectedId, guided, phase, activeFaction, onSelect, onAddShip, onImport, onLoadStats }) {
  const present = FACTION_ORDER.filter((f) => ships.some((s) => s.faction === f) || squadrons.some((q) => q.faction === f));
  const inGame = guided && !!phase;
  const rowSelectable = (s) =>
    !inGame || (phase === "ship" && s.faction === activeFaction && !s.activated && !s.destroyed) || (s.activationStarted && !s.activated);

  return (
    <div>
      <div className="sec-head">
        <span className="sec-accent" />
        <span className="lbl" style={{ color: "var(--text)" }}>Roster</span>
        <span className="sec-head-spacer" />
        <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{ships.length} schepen</span>
      </div>

      {inGame ? null : (
      <div className="sec-body" style={{ display: "flex", gap: 8, paddingBottom: 12 }}>
        <button className="btn" style={{ flex: 1 }} onClick={onAddShip}>
          <svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 3 V13 M3 8 H13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          Schip
        </button>
        <button className="btn" style={{ flex: 1 }} onClick={onImport}>
          <svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 2 V10 M5 7 L8 10 L11 7" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M3 12 V13.5 H13 V12" fill="none" stroke="currentColor" strokeWidth="1.5"/></svg>
          Importeer
        </button>
        {onLoadStats ? (
          <button className="btn icon-btn" title="Stats-dataset laden" onClick={onLoadStats} style={{ flex: "none", width: 38 }}>
            <svg width="15" height="15" viewBox="0 0 16 16"><path d="M2 4 C2 2.8 4.7 2 8 2 C11.3 2 14 2.8 14 4 C14 5.2 11.3 6 8 6 C4.7 6 2 5.2 2 4 Z M2 4 V12 C2 13.2 4.7 14 8 14 C11.3 14 14 13.2 14 12 V4" fill="none" stroke="currentColor" strokeWidth="1.3"/></svg>
          </button>
        ) : null}
      </div>
      )}

      {present.length === 0 ? (
        <div className="empty-state">
          <div className="es-icon">
            <svg width="20" height="20" viewBox="0 0 16 16"><path d="M8 2 V10 M5 7 L8 10 L11 7" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <div className="es-title">Nog geen vloot</div>
          <div className="es-sub">Voeg handmatig een schip toe of plak een Text Export uit je fleet builder.</div>
        </div>
      ) : present.map((f) => {
        const fc = FACTIONS[f].color;
        const fShips = ships.filter((s) => s.faction === f);
        const fSquads = squadrons.filter((q) => q.faction === f);
        const pts = fShips.reduce((n, s) => n + s.points + s.upgrades.reduce((u, x) => u + x.points, 0), 0)
                  + fSquads.reduce((n, q) => n + (q.points || 0) * (q.count || 1), 0);
        return (
          <div className="roster-group" key={f} style={{ "--fc": fc }}>
            <div className="roster-group-head">
              <span className="fc-dot" style={{ background: fc, color: fc }} />
              <span className="lbl">{FACTIONS[f].name}</span>
              <span className="rg-pts">{pts} pts</span>
            </div>
            {fShips.map((s) => (
              <div className={"roster-row" + (inGame && !rowSelectable(s) ? " locked" : "")} key={s.id} data-selected={s.id === selectedId} onClick={() => onSelect(s.id)}>
                <span className="rr-glyph" style={{ color: fc }}><ShipGlyph baseSize={s.baseSize} color={fc} size={20} /></span>
                <div className="rr-main">
                  <div className="rr-name">{s.name}</div>
                  <div className="rr-sub">{BASE_SIZES[s.baseSize].name} · {s.points} pts</div>
                  <HullBar hull={s.hull} max={s.maxHull} />
                </div>
                {s.statsMissing ? <span className="warn-tag">stats?</span> : null}
                <span className={"rr-hull " + (s.hull <= 0 ? "" : "")}>{s.hull}<span className="mx">/{s.maxHull}</span></span>
              </div>
            ))}
            {fSquads.map((q) => (
              <div className="squad-row" key={q.id}>
                <svg width="13" height="13" viewBox="0 0 14 14" style={{ color: fc }}><circle cx="3.5" cy="7" r="2" fill="currentColor"/><circle cx="10.5" cy="4" r="2" fill="currentColor"/><circle cx="10.5" cy="10" r="2" fill="currentColor"/></svg>
                <span>{q.name}</span>
                {q.count > 1 ? <span className="sq-ct">×{q.count}</span> : null}
                <span className="sq-pts">{q.points} pts</span>
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Roster });
