/* ============================================================================
   DIVONCI WORLD — SCREEN: WORLD MAP COMMAND CENTRE (home)
   Full-bleed live operational world. A real-geography canvas map (d3 land →
   dot field, camera pan/zoom) drives the tab; the vanilla engine is mounted on
   enter and torn down on leave. The map is data, never decoration.
   ========================================================================== */

/* small shared building blocks reused across screens */
function Panel({ children, style, className = "", glow, ...rest }) {
  return <div className={"panel " + className} style={{ ...(glow ? { boxShadow: "var(--glow-violet), var(--shadow-2)" } : null), ...style }} {...rest}>{children}</div>;
}
function PHead({ icon, eyebrow, title, right }) {
  return (
    <div className="phead">
      <div>
        <div className="eyebrow">{icon && <Icon name={icon} className="glyph" style={{ width: 13, height: 13 }} />}{eyebrow}</div>
        {title && <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 15, marginTop: 4 }}>{title}</div>}
      </div>
      {right && <div className="right">{right}</div>}
    </div>
  );
}
function MTile({ k, v, d, dColor, icon, spark, sparkColor, state }) {
  return (
    <div className="mtile">
      <div className="k">{icon && <Icon name={icon} style={{ width: 12, height: 12 }} />}{k}</div>
      <div className="v" style={{ color: state ? DW.STATE_META[state].c : "var(--ink)" }}>{v}</div>
      {d && <div className="d" style={{ color: dColor || "var(--ink-3)" }}>{d}</div>}
      {spark && <div style={{ marginTop: 8 }}><Sparkline data={spark} color={sparkColor || "var(--violet-bright)"} h={32} w={160} /></div>}
    </div>
  );
}

/* legend swatch for the empire network node types */
function LegendDot({ shape, color, label }) {
  return (
    <span className="lg">
      <i className={shape} style={{ background: color, color }} />{label}
    </span>
  );
}

/* the 6 head offices: [id, country-initials, accent, label] — locate-only, no drawer */
const WM_OFFICE_CC = [
  ["ccp", "GB", "#A974FF", "CCP · London"],
  ["code", "JP", "#FF8A3C", "Code · Tokyo"],
  ["projects", "US", "#3FA9FF", "Projects · New York"],
  ["treasury", "AE", "#F4C24B", "Treasury · Dubai"],
  ["products", "SG", "#36E08D", "Products · Singapore"],
  ["alerts", "BR", "#FF5454", "Alerts · São Paulo"],
  ["warroom", "RU", "#4D9FFF", "War Room · Moscow"],
  ["opportunities", "AU", "#22D3EE", "Opportunities · Sydney"],
];

function WorldMap({ nav, sys }) {
  const rootRef = React.useRef(null);
  const [controlsOpen, setControlsOpen] = React.useState(true);

  React.useEffect(() => {
    if (sys === "offline") return undefined;
    const root = rootRef.current;
    if (!root || !window.DWMAP) return undefined;
    const teardown = window.DWMAP.mount(root, { nav });
    return () => { if (teardown) teardown(); };
  }, [sys]);

  if (sys === "offline") return <OfflinePanel />;

  return (
    <div className="worldmap-screen" ref={rootRef}>
      <div id="wm-stage"><canvas className="dwmap"></canvas></div>

      {/* live + nav actions */}
      <div className="wm-actions">
        <span className="wm-live"><span className="d"></span> Live</span>
        <button className="btn primary" onClick={() => nav("warroom")}>War Room</button>
      </div>

      {/* collapsible controls: zoom + level + office locate row, toggles into one button */}
      <div className={"zoom " + (controlsOpen ? "open" : "collapsed")}>
        <div className="zoom-body">
          <div className="level">LVL <b className="js-level">0</b> · <span className="js-pct">100%</span></div>
          <div className="zbtns">
            <button className="zbtn js-zin" type="button" title="Zoom in">+</button>
            <button className="zbtn js-zout" type="button" title="Zoom out">−</button>
            <button className="zbtn js-home" type="button" title="Reset view">⌂</button>
            <div className="wm-cc-group">
              {WM_OFFICE_CC.map(([id, cc, oc, label]) => (
                <button key={id} className="wm-cc" data-office={id} style={{ "--oc": oc }} title={`Locate ${label} (${cc}) — no drawer`}><i></i>{cc}</button>
              ))}
            </div>
          </div>
        </div>
        <button className="zoom-toggle" type="button" aria-label="Toggle map controls" title="Map controls" onClick={() => setControlsOpen(o => !o)}>
          <svg className="zt-ico" viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
            <path d="M4 8h9M17 8h3M4 16h3M11 16h9" />
            <circle cx="15" cy="8" r="2.3" /><circle cx="9" cy="16" r="2.3" />
          </svg>
          <svg className="zt-close" viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            <path d="M7 7l10 10M17 7L7 17" />
          </svg>
        </button>
      </div>

      <div className="tip"></div>
      <div className="scrim"></div>
      <aside className="drawer"></aside>
      <div className="loading">Charting world…</div>
    </div>
  );
}

function OfflinePanel() {
  return (
    <div className="screen">
      <div className="screen-head"><div className="title"><span className="sub">Command Centre</span>World Map</div></div>
      <Panel style={{ borderColor: "color-mix(in srgb, var(--state-crisis) 30%, transparent)" }}>
        <div className="emptystate" style={{ padding: "var(--s-13)" }}>
          <div className="ring" style={{ borderColor: "color-mix(in srgb, var(--state-crisis) 50%, transparent)", color: "var(--state-crisis)" }}><Icon name="power" style={{ width: 24, height: 24 }} /></div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 20, color: "var(--ink)" }}>Connection lost — operating from last snapshot</div>
          <div style={{ maxWidth: "46ch", fontSize: 13 }}>Empire telemetry is frozen at <span className="mono" style={{ color: "var(--ink-2)" }}>14:22:08 UTC</span>. The map will not reflect live state until the uplink is restored. No commands will dispatch while offline.</div>
          <div style={{ display: "flex", gap: 10 }}>
            <StateChip state="crisis" label="Offline" tag="degraded uplink" />
            <span className="todochip">retry policy · TODO</span>
          </div>
        </div>
      </Panel>
    </div>
  );
}

Object.assign(window, { WorldMap, Panel, PHead, MTile, OfflinePanel });
