// LAR API pages: shared pieces. Every call goes through /api/lar/*, which the Worker checks against
// the caller's role on this game before it reaches the LAR API (src/routes/lar.js).

const larApi = (path, options) => api(`/api/lar/${path}`, options);

/** The API speaks unix seconds; the dashboard's formatters take ISO strings. */
const larIso = (seconds) => (seconds ? new Date(seconds * 1000).toISOString() : null);

function useLarLoad(load, deps = []) {
  const [state, setState] = React.useState({ data: null, error: null, loading: true });
  const run = React.useCallback(async () => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      setState({ data: await load(), error: null, loading: false });
    } catch (e) {
      setState({ data: null, error: e.message, loading: false });
    }
  }, deps);
  React.useEffect(() => { run(); }, [run]);
  return { ...state, reload: run };
}

const LarKpi = ({ label, value, sub, icon, tone }) => (
  <div className="kpi">
    <div className="kpi-label">{icon && <Icon name={icon} size={13}/>}{label}</div>
    <div className="kpi-value" style={tone ? { color: `var(--${tone})` } : undefined}>{value == null ? "—" : value}</div>
    {sub && <div className="kpi-delta"><span className="muted">{sub}</span></div>}
  </div>
);

/** After a change that the API pushes to the player: say whether it reached a running game. */
function LarDelivered({ result }) {
  if (!result || result.delivered === undefined) return null;
  return result.delivered > 0
    ? <div className="lar-note lar-note-ok"><span className="lar-live-dot"/>Sent to the player's game just now.</div>
    : <div className="lar-note">Player is offline. They get it on their next login.</div>;
}

function LarError({ error }) {
  return error ? <div className="tiny mt-8" style={{ color: "var(--danger)" }}>{error}</div> : null;
}

function LarJson({ value, max = 320 }) {
  let text = value;
  try { text = JSON.stringify(typeof value === "string" ? JSON.parse(value) : value, null, 2); } catch { /* not JSON */ }
  return <pre className="lar-pre" style={{ maxHeight: max }}>{text}</pre>;
}

function LarSourceTag({ player }) {
  if (player.source === "playfab" && player.claimedAt == null) return <span className="tag tag-warn">Copied · not logged in yet</span>;
  if (player.source === "playfab") return <span className="tag tag-info">Migrated</span>;
  return <span className="tag tag-success">New</span>;
}

function LarOnline({ online }) {
  return online
    ? <span className="tag tag-success"><span className="lar-live-dot"/>Online</span>
    : <span className="tag">Offline</span>;
}

function LarItemMark({ id, name, size = 28 }) {
  return (
    <div style={{ width: size, height: size, borderRadius: 7, background: gradientFor(id), display: "grid", placeItems: "center", color: "white", fontSize: size * 0.36, fontWeight: 700, flexShrink: 0 }}>
      {markFor(name || id)}
    </div>
  );
}

Object.assign(window, { larApi, larIso, useLarLoad, LarKpi, LarDelivered, LarError, LarJson, LarSourceTag, LarOnline, LarItemMark });
