// OP1 Estate View: a live data-flow picture of one monitor group (docs/estate/CONTRACT.md).
// Loaded after app.jsx as a plain <script type="text/babel">; shares its top-level scope
// (c, Card, Btn, Input, Sel, Badge, SectionHead, Spinner, ErrBox, useState, ...). Every top-level
// name here is prefixed Estate/ESTATE so it cannot collide with the other files.
// The canvas itself is the vendored bundle (window.OpEstate, vendor/op1-estate.js).

const ESTATE_KINDS = ["dns", "cdn", "frontend", "api", "service", "journey", "database", "storage", "queue", "feed", "external", "llm", "host", "user"];
const ESTATE_EDGE_KINDS = ["http", "api", "sql", "llm", "dns", "feed", "auth", "proxy", "host", "queue", "file", "planned"];
const ESTATE_KIND_ZONE = {
  dns: "edge", cdn: "edge", user: "edge", frontend: "frontend", api: "services", service: "services", journey: "services",
  database: "data", storage: "data", queue: "data", feed: "data", external: "external", llm: "external", host: "infra",
};
// Link kinds an operator can add (host containment comes from a node's host, and the canvas hides host links).
const ESTATE_LINK_KINDS = ESTATE_EDGE_KINDS.filter(k => k !== "host");
// The server's reason can quote a config key; people see a plain sentence.
function estateAiOffText(reason) {
  const r = String(reason || "");
  if (/turned off|disabled|Ai:Enabled/i.test(r)) return "AI is turned off for this installation.";
  return "AI is unavailable: " + r.replace(/\s*\([^)]*:[^)]*\)/g, "");
}
const ESTATE_STATUS_COLOR = { up: "#22a559", degraded: "#d29922", down: "#e0524b", unknown: "#9aa3ad", disabled: "#9aa3ad" };

// "#estate/12?kiosk=1&poll=15&rotate=12,15,19&every=60" -> settings, or null when it is not a kiosk hash.
function parseKioskHash(hash) {
  const m = (hash || "").match(/^#estate\/(\d+)\?(.*)$/);
  if (!m) return null;
  const q = new URLSearchParams(m[2]);
  if (q.get("kiosk") !== "1") return null;
  const poll = Math.min(120, Math.max(5, parseInt(q.get("poll"), 10) || 15));
  const every = Math.min(3600, Math.max(10, parseInt(q.get("every"), 10) || 60));
  const rotate = [...new Set((q.get("rotate") || "").split(",").map(s => parseInt(s, 10)).filter(n => n > 0))].slice(0, 12);
  return { groupId: parseInt(m[1], 10), poll, every, rotate };
}

function estateSlug(s) {
  return (String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48)) || "node";
}

function estateUniqueId(prefix, taken) {
  let i = 1;
  while (taken.has(prefix + (i > 1 ? "-" + i : ""))) i++;
  return prefix + (i > 1 ? "-" + i : "");
}

function estateStatusCounts(statuses) {
  const out = { up: 0, degraded: 0, down: 0, unknown: 0, disabled: 0 };
  Object.values((statuses && statuses.nodes) || {}).forEach(n => { out[n.status in out ? n.status : "unknown"]++; });
  return out;
}

function estateClock(iso) {
  const d = iso ? new Date(iso) : null;
  return d && !isNaN(d) ? d.toLocaleTimeString() : "";
}

// Loads GET /api/estate/{id}; refreshes /status every pollSec while the tab is visible (paused when hidden);
// optionally re-reads the whole model every modelSec (kiosk). Same pause pattern as DashboardView.
// Loaded data is tagged with the group it was fetched for (dataGroup). When groupId changes the previous
// data stays in place until the new fetch resolves, so a rotating wall never flashes a false "no estate".
function useEstateLive(api, groupId, pollSec, modelSec) {
  const [loaded, setLoaded] = useState(null);   // { gid, d, s } : the last good GET, with its statuses
  const [err, setErr] = useState("");
  const [gone, setGone] = useState(null);       // group id whose GET answered 404
  const [statusErr, setStatusErr] = useState("");
  const gRef = useRef(groupId); gRef.current = groupId;
  const loadedRef = useRef(null); loadedRef.current = loaded;
  const seqRef = useRef(0);        // only the newest model request may write
  const statusSeqRef = useRef(0);
  const statusBusyRef = useRef(false);

  const load = useCallback(async () => {
    const g = groupId;
    const my = ++seqRef.current;
    try {
      const d = await api("GET", `/estate/${g}`);
      if (my !== seqRef.current) return;
      setLoaded({ gid: g, d, s: d && d.statuses ? d.statuses : null });
      setErr(""); setStatusErr(""); setGone(null);
    } catch (e) {
      if (my !== seqRef.current) return;
      if (e && e.status === 404 && loadedRef.current) setGone(g);
      else setErr((e && e.message) || "Could not load the estate");
    }
  }, [api, groupId]);

  useEffect(() => { load(); }, [load]);

  useEffect(() => {
    const g = groupId;
    const tick = async () => {
      const cur = loadedRef.current;
      if (document.visibilityState !== "visible" || statusBusyRef.current) return;
      if (!cur || cur.gid !== g || !(cur.d && cur.d.exists)) return;
      statusBusyRef.current = true;
      const my = ++statusSeqRef.current;
      try {
        const s = await api("GET", `/estate/${g}/status`);
        if (my === statusSeqRef.current && gRef.current === g) {
          setLoaded(p => (p && p.gid === g ? { ...p, s } : p));
          setStatusErr("");
        }
      } catch (e) {
        if (my === statusSeqRef.current && gRef.current === g) setStatusErr((e && e.message) || "Status refresh failed");
      } finally { statusBusyRef.current = false; }
    };
    const id = setInterval(tick, pollSec * 1000);
    const onVisible = () => { if (document.visibilityState === "visible") tick(); };
    document.addEventListener("visibilitychange", onVisible);
    return () => { clearInterval(id); document.removeEventListener("visibilitychange", onVisible); };
  }, [api, groupId, pollSec]);

  useEffect(() => {
    if (!modelSec) return;
    const id = setInterval(() => { if (document.visibilityState === "visible") load(); }, modelSec * 1000);
    return () => clearInterval(id);
  }, [load, modelSec]);

  return {
    data: loaded ? loaded.d : null,
    dataGroup: loaded ? loaded.gid : null,
    statuses: loaded ? loaded.s : null,
    err, statusErr, gone,
    loading: !loaded && !err,
    reload: load,
  };
}

// Mounts the vendored canvas into a div that fills its parent. Props are pushed through handle.update().
// The bundle refits itself when the div changes size, so nothing is observed here.
function EstateCanvas({ model, layout, statuses, mode, pollSec, onSaveLayout, onSelectNode, onSelectEdge, onDirtyChange }) {
  const elRef = useRef(null);
  const handleRef = useRef(null);
  const saveRef = useRef(onSaveLayout); saveRef.current = onSaveLayout;
  const selNodeRef = useRef(onSelectNode); selNodeRef.current = onSelectNode;
  const selEdgeRef = useRef(onSelectEdge); selEdgeRef.current = onSelectEdge;
  const dirtyRef = useRef(onDirtyChange); dirtyRef.current = onDirtyChange;
  const firstRef = useRef(true);
  const [fail, setFail] = useState("");

  useEffect(() => {
    if (!window.OpEstate) { setFail("The estate canvas did not load (vendor/op1-estate.js)."); return; }
    let h;
    try {
      h = window.OpEstate.mount(elRef.current, {
        model, layout, statuses, mode, pollSec,
        onSaveLayout: (l) => { if (saveRef.current) saveRef.current(l); },
        onSelectNode: (id) => { if (selNodeRef.current) selNodeRef.current(id); },
        onSelectEdge: (id) => { if (selEdgeRef.current) selEdgeRef.current(id); },
        onDirtyChange: (d) => { if (dirtyRef.current) dirtyRef.current(d); },
      });
    } catch (e) { setFail("The estate canvas could not start: " + (e && e.message ? e.message : e)); return; }
    handleRef.current = h;
    return () => { try { h.destroy(); } catch (_) {} handleRef.current = null; };
  }, []);

  useEffect(() => {
    if (firstRef.current) { firstRef.current = false; return; }
    if (handleRef.current) { try { handleRef.current.update({ model, layout, statuses, mode, pollSec }); } catch (_) {} }
  }, [model, layout, statuses, mode, pollSec]);

  if (fail) return <div style={{ padding: 24, color: c.red, fontSize: 13 }}>{fail}</div>;
  return <div ref={elRef} style={{ width: "100%", height: "100%" }} />;
}

// Confirm / notice dialog in the same look as the other views' modals. dlg = { msg, okLabel, onOk, single }
function EstateDialog({ dlg, onClose }) {
  if (!dlg) return null;
  return (
    <Modal open title={dlg.single ? "Notice" : "Confirm"} width={400} zIndex={1300} onClose={onClose}>
      <div>
        <div style={{ fontSize: 13, color: "#1A1A1A", marginBottom: 20, lineHeight: 1.5 }}>{dlg.msg}</div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
          {!dlg.single && <button onClick={onClose}
            style={{ fontSize: 12, padding: "6px 16px", border: "1px solid #006D8C", borderRadius: 6, background: "#fff", color: "#006D8C", cursor: "pointer" }}>{dlg.cancelLabel || "Cancel"}</button>}
          <button onClick={() => { onClose(); if (dlg.onOk) dlg.onOk(); }}
            style={{ fontSize: 12, padding: "6px 16px", border: "none", borderRadius: 6, background: dlg.single ? "#006D8C" : "#D95C5C", color: "#fff", cursor: "pointer", fontWeight: 600 }}>{dlg.okLabel || (dlg.single ? "OK" : "Confirm")}</button>
        </div>
      </div>
    </Modal>
  );
}

// Right-hand refine panel (operators only). Edits a draft model held by EstateView; nothing is saved until Save.
function EstateRefinePanel({ api, groupId, model, onChange, onSave, onCancel, saving, notice, selectedEdgeId }) {
  const [description, setDescription] = useState("");
  const [proposing, setProposing] = useState(false);
  const [unavailable, setUnavailable] = useState("");
  const [aiNotes, setAiNotes] = useState("");
  const [proposedNodes, setProposedNodes] = useState([]);
  const [err, setErr] = useState("");
  const [newNode, setNewNode] = useState({ label: "", kind: "service" });
  const [newLink, setNewLink] = useState({ source: "", target: "", label: "", kind: "http" });

  const nodes = model.nodes || [];
  const edges = model.edges || [];
  const labelOf = (id) => { const n = nodes.find(x => x.id === id); return n ? n.label : id; };
  const taken = () => new Set([...nodes.map(n => n.id), ...edges.map(e => e.id)]);

  const patchNode = (id, patch) => onChange({
    ...model,
    nodes: nodes.map(n => {
      if (n.id !== id) return n;
      const next = { ...n, ...patch };
      if (patch.kind && patch.kind !== n.kind && n.zone === ESTATE_KIND_ZONE[n.kind]) next.zone = ESTATE_KIND_ZONE[patch.kind] || n.zone;
      if (n.source === "inferred") next.source = "declared";
      return next;
    }),
  });
  const patchEdge = (id, fn) => onChange({ ...model, edges: edges.map(e => e.id === id ? fn(e) : e) });
  const dropEdge = (id) => onChange({ ...model, edges: edges.filter(e => e.id !== id) });

  const addNode = () => {
    const label = newNode.label.trim();
    if (!label) { setErr("Give the new node a label."); return; }
    setErr("");
    const id = estateUniqueId("n-decl-" + estateSlug(label), taken());
    onChange({ ...model, nodes: [...nodes, { id, label, kind: newNode.kind, zone: ESTATE_KIND_ZONE[newNode.kind] || "services", monitorIds: [], source: "declared" }] });
    setNewNode({ label: "", kind: newNode.kind });
  };

  const addLink = () => {
    const { source, target } = newLink;
    if (!source || !target) { setErr("Choose a source and a target for the link."); return; }
    if (source === target) { setErr("A link needs two different nodes."); return; }
    if (edges.some(e => e.source === source && e.target === target)) { setErr("Those two nodes are already linked."); return; }
    setErr("");
    const id = estateUniqueId("e-u", taken());
    onChange({ ...model, edges: [...edges, { id, source, target, label: newLink.label.trim() || undefined, kind: newLink.kind, state: "confirmed" }] });
    setNewLink({ source: "", target: "", label: "", kind: newLink.kind });
  };

  const propose = async () => {
    setProposing(true); setErr(""); setUnavailable(""); setAiNotes("");
    try {
      const r = await api("POST", `/estate/${groupId}/propose`, { model, description });
      if (r && r.unavailable) { setUnavailable(r.unavailable); return; }
      const ids = taken();
      const fresh = [];
      (r.edges || []).forEach((e, i) => {
        if (!nodes.some(n => n.id === e.source) || !nodes.some(n => n.id === e.target)) return;
        if (edges.some(x => x.source === e.source && x.target === e.target && x.kind === e.kind)) return;
        const id = ids.has(e.id) || !e.id ? estateUniqueId("e-ai", ids) : e.id;
        ids.add(id);
        fresh.push({ ...e, id, state: "proposed" });
      });
      if (fresh.length) onChange({ ...model, edges: [...edges, ...fresh] });
      setProposedNodes(r.nodes || []);
      setAiNotes(r.notes || (fresh.length || (r.nodes || []).length ? "" : "The AI found nothing to add."));
    } catch (e) { setErr(e.message || "The AI request failed."); }
    finally { setProposing(false); }
  };

  const acceptNode = (p, idx) => {
    const id = estateUniqueId("n-ai-" + estateSlug(p.label), taken());
    const kind = ESTATE_KINDS.includes(p.kind) ? p.kind : "service";
    onChange({ ...model, nodes: [...nodes, { id, label: p.label, kind, zone: p.zone || ESTATE_KIND_ZONE[kind], monitorIds: [], detail: p.reason || undefined, source: "ai" }] });
    setProposedNodes(proposedNodes.filter((_, i) => i !== idx));
  };

  const proposedEdges = edges.filter(e => e.state === "proposed");
  const otherEdges = edges.filter(e => e.state !== "proposed");
  const small = { fontSize: 11, color: c.textDimmer };
  const row = { display: "flex", alignItems: "center", gap: 6, marginBottom: 6 };
  const selStyle = { padding: "5px 6px", fontSize: 12, minWidth: 0 };
  const inpStyle = { padding: "5px 8px", fontSize: 12 };

  const edgeRow = (e, proposed) => (
    <div key={e.id} style={{ padding: "6px 8px", marginBottom: 6, border: `${e.id === selectedEdgeId ? 2 : 1}px ${proposed ? "dashed" : "solid"} ${e.id === selectedEdgeId ? c.blue : proposed ? c.amber : c.border}`, borderRadius: 6, background: proposed ? c.yellowLight : c.surface }}>
      <div style={{ fontSize: 12, color: c.text }}>
        {labelOf(e.source)} {"→"} {labelOf(e.target)}
        <span style={{ ...small, marginLeft: 6 }}>{e.kind}{e.label ? ` · ${e.label}` : ""}{e.confidence != null ? ` · ${Math.round(e.confidence * 100)}%` : ""}</span>
      </div>
      {e.reason && <div style={{ ...small, marginTop: 2 }}>{e.reason}</div>}
      <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
        {proposed ? (
          <>
            <Btn variant="success" style={{ padding: "3px 10px", fontSize: 11 }} onClick={() => patchEdge(e.id, x => ({ ...x, state: "confirmed", confidence: undefined }))}>Accept</Btn>
            <Btn variant="secondary" style={{ padding: "3px 10px", fontSize: 11 }} onClick={() => dropEdge(e.id)}>Reject</Btn>
          </>
        ) : (
          <Btn variant="danger" style={{ padding: "3px 10px", fontSize: 11 }} onClick={() => dropEdge(e.id)}>Remove link</Btn>
        )}
      </div>
    </div>
  );

  const nodeOptions = [{ value: "", label: "Choose…" }, ...nodes.map(n => ({ value: n.id, label: `${n.label} (${n.kind})` }))];
  // B -> A when A -> B already exists is allowed; it only gets a note
  const reverseExists = !!newLink.source && !!newLink.target
    && edges.some(e => e.source === newLink.target && e.target === newLink.source)
    && !edges.some(e => e.source === newLink.source && e.target === newLink.target);
  const kindOptions = ESTATE_KINDS.map(k => ({ value: k, label: k }));

  return (
    <div style={{ width: 360, flexShrink: 0, borderLeft: `1px solid ${c.border}`, background: c.surfaceAlt, display: "flex", flexDirection: "column", minHeight: 0 }}>
      <div style={{ flex: 1, overflowY: "auto", padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: c.text, marginBottom: 2 }}>Refine estate</div>
        <div style={{ ...small, marginBottom: 12 }}>Changes stay in this draft until you press Save.</div>
        <ErrBox msg={err} />
        {notice && <div style={{ background: c.yellowLight, border: `1px solid ${c.amber}`, borderRadius: 8, padding: "8px 12px", fontSize: 12, color: c.text, marginBottom: 12 }}>{notice}</div>}

        <SectionHead>Nodes ({nodes.length})</SectionHead>
        {nodes.map(n => (
          <div key={n.id} style={row}>
            <div style={{ flex: 1, minWidth: 0 }}><Input aria-label={`Label for ${n.label}`} value={n.label} maxLength={80} onChange={e => patchNode(n.id, { label: e.target.value })} style={inpStyle} /></div>
            <div style={{ width: 96 }}><Sel aria-label={`Kind for ${n.label}`} value={n.kind} options={kindOptions} onChange={e => patchNode(n.id, { kind: e.target.value })} style={selStyle} /></div>
          </div>
        ))}
        <div style={{ ...row, marginTop: 8 }}>
          <div style={{ flex: 1, minWidth: 0 }}><Input placeholder="New node label" aria-label="New node label" value={newNode.label} maxLength={80} onChange={e => setNewNode({ ...newNode, label: e.target.value })} style={inpStyle} /></div>
          <div style={{ width: 96 }}><Sel aria-label="New node kind" value={newNode.kind} options={kindOptions} onChange={e => setNewNode({ ...newNode, kind: e.target.value })} style={selStyle} /></div>
          <Btn variant="secondary" style={{ padding: "5px 10px", fontSize: 11 }} onClick={addNode}>Add</Btn>
        </div>

        {(model.questions || []).length > 0 && (
          <div style={{ marginTop: 16 }}>
            <SectionHead>Questions</SectionHead>
            {(model.questions || []).map(q => (
              <label key={q.id} style={{ display: "flex", gap: 8, alignItems: "flex-start", fontSize: 12, color: q.answered ? c.textDimmer : c.text, marginBottom: 6, cursor: "pointer" }}>
                <input type="checkbox" checked={!!q.answered} style={{ marginTop: 2 }}
                  onChange={e => onChange({ ...model, questions: model.questions.map(x => x.id === q.id ? { ...x, answered: e.target.checked } : x) })} />
                <span>{q.text}{q.nodeId ? <span style={small}> ({labelOf(q.nodeId)})</span> : null}</span>
              </label>
            ))}
          </div>
        )}

        <div style={{ marginTop: 16 }}>
          <SectionHead>Describe this application</SectionHead>
          <textarea aria-label="Describe this application" value={description} maxLength={2000} rows={4} onChange={e => setDescription(e.target.value)}
            placeholder="e.g. The kiosk app calls the API, which reads the SQL database and asks Anthropic for summaries."
            style={{ width: "100%", background: c.surface, border: `1px solid ${c.border}`, borderRadius: 6, padding: "8px 10px", color: c.text, fontSize: 12, fontFamily: "inherit", resize: "vertical" }} />
          <Btn variant="secondary" loading={proposing} disabled={!description.trim()} onClick={propose} style={{ marginTop: 6, fontSize: 11 }}>Ask AI to propose links</Btn>
          {unavailable && <div style={{ fontSize: 12, color: c.amber, marginTop: 6 }}>{estateAiOffText(unavailable)}</div>}
          {aiNotes && <div style={{ ...small, marginTop: 6 }}>{aiNotes}</div>}
        </div>

        {proposedNodes.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <SectionHead>Proposed nodes</SectionHead>
            {proposedNodes.map((p, i) => (
              <div key={i} style={{ padding: "6px 8px", marginBottom: 6, border: `1px dashed ${c.amber}`, borderRadius: 6, background: c.yellowLight }}>
                <div style={{ fontSize: 12, color: c.text }}>{p.label} <span style={small}>{p.kind}</span></div>
                {p.reason && <div style={{ ...small, marginTop: 2 }}>{p.reason}</div>}
                <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                  <Btn variant="success" style={{ padding: "3px 10px", fontSize: 11 }} onClick={() => acceptNode(p, i)}>Accept</Btn>
                  <Btn variant="secondary" style={{ padding: "3px 10px", fontSize: 11 }} onClick={() => setProposedNodes(proposedNodes.filter((_, j) => j !== i))}>Reject</Btn>
                </div>
              </div>
            ))}
          </div>
        )}

        <div style={{ marginTop: 16 }}>
          <SectionHead>Proposed links ({proposedEdges.length})</SectionHead>
          {proposedEdges.length === 0 && <div style={small}>None waiting for a decision.</div>}
          {proposedEdges.map(e => edgeRow(e, true))}
        </div>

        <div style={{ marginTop: 16 }}>
          <SectionHead>Links ({otherEdges.length})</SectionHead>
          {otherEdges.map(e => edgeRow(e, false))}
          <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={row}>
              <div style={{ flex: 1, minWidth: 0 }}><Sel aria-label="Link source" value={newLink.source} options={nodeOptions} onChange={e => setNewLink({ ...newLink, source: e.target.value })} style={{ ...selStyle, flex: 1 }} /></div>
              <span style={small}>{"→"}</span>
              <div style={{ flex: 1, minWidth: 0 }}><Sel aria-label="Link target" value={newLink.target} options={nodeOptions} onChange={e => setNewLink({ ...newLink, target: e.target.value })} style={{ ...selStyle, flex: 1 }} /></div>
            </div>
            <div style={row}>
              <div style={{ flex: 1, minWidth: 0 }}><Input placeholder="Label (optional)" aria-label="Link label" value={newLink.label} maxLength={80} onChange={e => setNewLink({ ...newLink, label: e.target.value })} style={inpStyle} /></div>
              <div style={{ width: 84 }}><Sel aria-label="Link kind" value={newLink.kind} options={ESTATE_LINK_KINDS.map(k => ({ value: k, label: k }))} onChange={e => setNewLink({ ...newLink, kind: e.target.value })} style={selStyle} /></div>
              <Btn variant="secondary" style={{ padding: "5px 10px", fontSize: 11 }} onClick={addLink}>Add link</Btn>
            </div>
            {reverseExists && <div style={{ ...small, color: c.amber }}>The opposite link already exists. You can still add this one.</div>}
          </div>
        </div>
      </div>
      <div style={{ padding: 12, borderTop: `1px solid ${c.border}`, display: "flex", gap: 8, background: c.surface }}>
        <Btn loading={saving} onClick={onSave} style={{ flex: 1 }}>Save</Btn>
        <Btn variant="secondary" disabled={saving} onClick={onCancel}>Cancel</Btn>
      </div>
    </div>
  );
}

function EstateView({ api, groupId, canManage, onBack }) {
  const live = useEstateLive(api, groupId, 30, 0);
  const { statusErr, reload } = live;
  const data = live.dataGroup === groupId ? live.data : null;
  const statuses = live.dataGroup === groupId ? live.statuses : null;
  // a group deleted meanwhile is an error here (the kiosk keeps the last picture instead)
  const err = live.err || (live.gone === groupId && !data ? "Group not found." : "");
  const loading = !data && !err;
  const [draft, setDraft] = useState(null);        // unsaved EstateModel being refined
  const [draftNotice, setDraftNotice] = useState("");
  const [editLayout, setEditLayout] = useState(false);
  const [layoutDirty, setLayoutDirty] = useState(false);
  const [busy, setBusy] = useState("");
  const [actErr, setActErr] = useState("");
  const [actDetails, setActDetails] = useState([]);
  const [info, setInfo] = useState("");
  const [dlg, setDlg] = useState(null);
  const [selNode, setSelNode] = useState(null);
  const [selEdge, setSelEdge] = useState(null);
  const baseVersionRef = useRef(null);

  const exists = !!(data && data.exists);
  const groupName = (data && data.groupName) || `Group ${groupId}`;
  const counts = estateStatusCounts(statuses);
  const draftChanged = !!draft && JSON.stringify(draft) !== JSON.stringify(data && data.model ? data.model : null);

  const pickNode = (id) => { setSelNode(id); if (id) setSelEdge(null); };
  const pickEdge = (id) => { setSelEdge(id); if (id) setSelNode(null); };
  const clearErr = () => { setActErr(""); setActDetails([]); };

  const startDraft = (model) => { baseVersionRef.current = data && data.version != null ? data.version : null; setDraft(model); setDraftNotice(""); setEditLayout(false); setLayoutDirty(false); clearErr(); setInfo(""); };

  const generate = async (existing) => {
    setBusy("generate"); clearErr();
    try {
      const r = await api("POST", `/estate/${groupId}/generate`, { existing: existing || null });
      startDraft(r.model);
      if (existing) setDraftNotice("Regenerated from the group's monitors. Nothing is saved until you press Save.");
    } catch (e) { setActErr(e.message || "Could not generate the estate."); }
    finally { setBusy(""); }
  };

  const conflict = () => setDlg({
    msg: "Someone else saved this estate while you were editing. Load their version to continue? Your unsaved changes will be lost.",
    okLabel: "Load latest",
    onOk: () => { setDraft(null); reload(); },
  });

  const save = async () => {
    setBusy("save"); clearErr();
    try {
      const body = { model: draft };
      if (baseVersionRef.current != null) body.ifVersion = baseVersionRef.current;
      const r = await api("PUT", `/estate/${groupId}`, body);
      const warnings = (r && r.warnings) || [];
      setDraft(null);
      setInfo(warnings.length ? "Saved with warnings: " + warnings.join(" ") : "Estate saved.");
      await reload();
    } catch (e) {
      if (e && e.status === 409) conflict();
      else { setActErr((e && e.message) || "Could not save the estate."); setActDetails(e && Array.isArray(e.details) ? e.details : []); }
    } finally { setBusy(""); }
  };

  const saveLayout = async (layout) => {
    setBusy("layout"); clearErr();
    try {
      await api("PUT", `/estate/${groupId}/layout`, { layout });
      setEditLayout(false); setLayoutDirty(false);
      setInfo("Layout saved.");
      await reload();
    } catch (e) { setActErr(e.message || "Could not save the layout."); }
    finally { setBusy(""); }
  };

  const remove = () => setDlg({
    msg: `Delete the estate view for "${groupName}"? The saved model and layout are removed. Monitors are not affected.`,
    okLabel: "Delete estate",
    onOk: async () => {
      setBusy("delete"); clearErr();
      try { await api("DELETE", `/estate/${groupId}`); setEditLayout(false); setLayoutDirty(false); setInfo(""); await reload(); }
      catch (e) { setActErr(e.message || "Could not delete the estate."); }
      finally { setBusy(""); }
    },
  });

  // one prompt wording for every way out of unsaved work
  const discardPrompt = (okLabel, onOk) => setDlg({ msg: "Discard your changes to this estate?", okLabel, onOk });
  const cancelDraft = () => {
    const go = () => { setDraft(null); clearErr(); };
    if (draftChanged) discardPrompt("Discard", go); else go();
  };
  const cancelLayout = () => {
    const go = () => { setEditLayout(false); setLayoutDirty(false); };
    if (layoutDirty) setDlg({ msg: "Leave layout editing? Any moves you have not saved with Save layout on the canvas are lost.", okLabel: "Leave", onOk: go });
    else go();
  };
  const back = () => {
    if ((editLayout && layoutDirty) || draftChanged) discardPrompt("Leave", onBack); else onBack();
  };

  const openKiosk = () => window.open(`${window.location.origin}${window.location.pathname}#estate/${groupId}?kiosk=1`, "_blank", "noopener");

  const toolBtn = { padding: "5px 12px", fontSize: 12 };
  let body;
  if (loading) body = <Spinner />;
  else if (err && !data) body = (
    <div style={{ padding: 24 }}><ErrBox msg={err} /><Btn variant="secondary" onClick={reload}>Retry</Btn></div>
  );
  else if (!exists && !draft) body = (
    <div style={{ padding: 32, display: "flex", justifyContent: "center" }}>
      <Card style={{ maxWidth: 520, textAlign: "center" }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 8 }}>No estate yet</div>
        {canManage ? (
          <>
            <p style={{ fontSize: 13, color: c.textMuted, lineHeight: 1.5, marginBottom: 16 }}>
              An estate is a live data-flow picture of this group: its front ends, APIs, databases, hosts and external services, drawn from the group's monitors. OP1 generates a draft you can refine before saving.
            </p>
            <ErrBox msg={actErr} />
            <Btn loading={busy === "generate"} onClick={() => generate(null)}>Generate estate</Btn>
          </>
        ) : (
          <p style={{ fontSize: 13, color: c.textMuted, lineHeight: 1.5 }}>No estate yet. An operator can generate one from this group's monitors.</p>
        )}
      </Card>
    </div>
  );
  else {
    const model = draft || data.model;
    const hasNodes = model && (model.nodes || []).length > 0;
    body = (
      <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
        <div style={{ flex: 1, position: "relative", minWidth: 0, background: "#f6f9fb" }}>
          {hasNodes
            ? <EstateCanvas model={model} layout={data && data.layout} statuses={draft ? null : statuses} mode={editLayout && !draft ? "edit" : "view"} pollSec={30} onSaveLayout={saveLayout} onSelectNode={pickNode} onSelectEdge={pickEdge} onDirtyChange={setLayoutDirty} />
            : <div style={{ padding: 32, fontSize: 13, color: c.textMuted }}>This group has no monitors to draw yet. Add monitors, or add nodes by hand in the panel.</div>}
        </div>
        {draft && canManage && (
          <EstateRefinePanel api={api} groupId={groupId} model={draft} onChange={setDraft} onSave={save}
            onCancel={cancelDraft} saving={busy === "save"} notice={draftNotice} selectedEdgeId={selEdge} />
        )}
      </div>
    );
  }

  // detail strip: always present once there is a picture, so the canvas never shifts when something is selected
  let strip = null;
  if (exists || draft) {
    const model = draft || (data && data.model) || { nodes: [], edges: [] };
    const nodeById = (id) => (model.nodes || []).find(n => n.id === id);
    const edge = selEdge ? (model.edges || []).find(e => e.id === selEdge) : null;
    const node = !edge && selNode ? nodeById(selNode) : null;
    const st = node && statuses && statuses.nodes && Object.prototype.hasOwnProperty.call(statuses.nodes, node.id) ? statuses.nodes[node.id] : null;
    const dot = " \u00b7 ";
    let content;
    if (edge) {
      const from = nodeById(edge.source), to = nodeById(edge.target);
      const why = [edge.reason, edge.confidence != null ? `confidence ${Math.round(edge.confidence * 100)} %` : ""].filter(Boolean).join(", ");
      content = (
        <>
          <span><b style={{ color: c.text }}>{from ? from.label : edge.source}</b> {"\u2192"} <b style={{ color: c.text }}>{to ? to.label : edge.target}</b>
            {dot}{edge.kind || "http"}{edge.label ? dot + edge.label : ""}{dot}{edge.state || "confirmed"}{why ? ` (${why})` : ""}</span>
          {draft && canManage && <Btn variant="danger" style={{ padding: "2px 10px", fontSize: 11 }}
            onClick={() => { setDraft({ ...draft, edges: (draft.edges || []).filter(e => e.id !== edge.id) }); setSelEdge(null); }}>Remove link</Btn>}
        </>
      );
    } else if (node) {
      const parts = [];
      if (st) {
        parts.push(<span key="st" style={{ color: ESTATE_STATUS_COLOR[st.status] || ESTATE_STATUS_COLOR.unknown, fontWeight: 600 }}>{st.status}</span>);
        if (st.ms != null) parts.push(<span key="ms">{st.ms} ms</span>);
        if (st.openAlerts) parts.push(<span key="oa">{st.openAlerts} open alert{st.openAlerts === 1 ? "" : "s"}</span>);
        if ((st.monitors || []).length) parts.push(<span key="mo">monitors: {st.monitors.map(m => `${m.name} (${m.status})`).join(", ")}</span>);
        if ((st.flows || []).length) parts.push(<span key="fl">flows: {st.flows.map(f => `${f.name} (${f.status})`).join(", ")}</span>);
      }
      content = (
        <span><b style={{ color: c.text }}>{node.label}</b>{dot}{node.kind}
          {parts.map((p, i) => <span key={i}>{dot}{p}</span>)}</span>
      );
    } else {
      content = <span style={{ color: c.textDimmer }}>Click a card or a link to see its detail.</span>;
    }
    strip = (
      <div style={{ padding: "4px 16px", background: c.surfaceAlt, borderBottom: `1px solid ${c.border}`, fontSize: 12, color: c.textMuted, flexShrink: 0, minHeight: 34, boxSizing: "border-box", display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        {content}
      </div>
    );
  }

  const detailText = actDetails.length > 1 || (actDetails.length === 1 && actDetails[0] !== actErr) ? actDetails.join(" \u00b7 ") : "";

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "calc(100vh - 20px)", overflow: "hidden", background: "#ffffff" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderBottom: `1px solid ${c.border}`, flexShrink: 0, flexWrap: "wrap" }}>
        <Btn variant="secondary" onClick={back} style={toolBtn}>{"\u2190"} Back</Btn>
        <div style={{ fontSize: 15, fontWeight: 700, color: c.text }}>{"\u2b21"} Estate{" \u00b7 "}{groupName}</div>
        {exists && !draft && (
          <div style={{ display: "flex", gap: 6, alignItems: "center", fontSize: 11 }}>
            {["up", "degraded", "down", "unknown"].filter(k => counts[k] > 0).map(k => (
              <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 4, color: c.textMuted }}>
                <span style={{ width: 8, height: 8, borderRadius: 4, background: ESTATE_STATUS_COLOR[k] }} />{counts[k]} {k}
              </span>
            ))}
            {statuses && statuses.asOf && <span role="status" style={{ color: c.textDimmer }}>{"\u00b7"} as of {estateClock(statuses.asOf)}</span>}
          </div>
        )}
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, flexWrap: "wrap" }}>
          {exists && !draft && (
            <>
              {canManage && !editLayout && <Btn variant="secondary" style={toolBtn} onClick={() => setEditLayout(true)}>Edit layout</Btn>}
              {canManage && editLayout && <Btn variant="secondary" style={toolBtn} loading={busy === "layout"} onClick={cancelLayout}>Cancel layout edit</Btn>}
              {canManage && <Btn variant="secondary" style={toolBtn} onClick={() => startDraft(data.model)}>Refine</Btn>}
              {canManage && <Btn variant="secondary" style={toolBtn} loading={busy === "generate"} onClick={() => generate(data.model)}>Regenerate</Btn>}
              <Btn variant="secondary" style={toolBtn} onClick={openKiosk}>Kiosk</Btn>
              {canManage && <Btn variant="danger" style={toolBtn} loading={busy === "delete"} onClick={remove}>Delete estate</Btn>}
            </>
          )}
        </div>
      </div>
      {(actErr || statusErr || info || editLayout) && (
        <div style={{ padding: "6px 16px", background: "#F0F7FB", borderBottom: `1px solid ${c.border}`, fontSize: 12, flexShrink: 0 }}>
          {actErr && <span style={{ color: c.red, marginRight: 12 }}>{actErr}</span>}
          {detailText && <div style={{ color: c.red, marginTop: 2 }}>{detailText}</div>}
          {statusErr && <span role="status" style={{ color: c.amberText, marginRight: 12 }}>Status refresh failed, showing the last known status. ({statusErr})</span>}
          {info && !actErr && <span style={{ color: c.green, marginRight: 12 }}>{info}</span>}
          {editLayout && <span style={{ color: c.textMuted }}>Drag cards and zones, then use Save layout on the canvas to keep the layout.</span>}
        </div>
      )}
      {strip}
      {body}
      <EstateDialog dlg={dlg} onClose={() => setDlg(null)} />
    </div>
  );
}

// Chrome-free wall display. Same session and sign-in as the rest of the app (App renders this instead of the shell).
// The canvas stays mounted while the wall rotates: a new group's model is pushed through update().
function EstateKiosk({ api, cfg }) {
  const list = cfg.rotate.length ? cfg.rotate : [cfg.groupId];
  const [idx, setIdx] = useState(() => Math.max(0, list.indexOf(cfg.groupId)));
  const groupId = list[idx % list.length];
  const live = useEstateLive(api, groupId, cfg.poll, 300);
  const { data, dataGroup, statuses, err, statusErr, gone, loading } = live;
  const [fullscreen, setFullscreen] = useState(!!document.fullscreenElement);
  const [fsMsg, setFsMsg] = useState("");

  useEffect(() => {
    if (list.length < 2) return;
    const id = setInterval(() => setIdx(i => (i + 1) % list.length), cfg.every * 1000);
    return () => clearInterval(id);
  }, [list.length, cfg.every]);

  useEffect(() => {
    const onFs = () => setFullscreen(!!document.fullscreenElement);
    document.addEventListener("fullscreenchange", onFs);
    return () => document.removeEventListener("fullscreenchange", onFs);
  }, []);

  const goFullscreen = async () => {
    try { await document.documentElement.requestFullscreen(); setFsMsg(""); }
    catch (_) { setFsMsg("Your browser only allows fullscreen from a click on this page. Click again, or press F11."); }
  };

  // title, counter and picture all come from the same loaded data, so they change together
  const shown = data && data.exists && data.model ? data : null;
  const pos = dataGroup != null && list.indexOf(dataGroup) >= 0 ? list.indexOf(dataGroup) : idx % list.length;
  const title = data && data.groupName ? data.groupName : "";
  const warn = { fontSize: 14, color: "#f0b040", background: "rgba(13,21,33,.85)", borderRadius: 8, padding: "4px 12px", alignSelf: "flex-start" };
  return (
    <div style={{ position: "fixed", inset: 0, background: "#0d1521", color: "#e6edf5", fontFamily: "'IBM Plex Sans',system-ui,sans-serif" }}>
      {shown && shown.model.nodes.length > 0 && (
        <EstateCanvas model={shown.model} layout={shown.layout} statuses={statuses} mode="kiosk" pollSec={cfg.poll} />
      )}
      {!(shown && shown.model.nodes.length > 0) && (
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, color: "#9aa3ad", padding: 24, textAlign: "center" }}>
          {loading ? "Loading estate\u2026"
            : !data ? `Could not load the estate: ${err}`
            : !data.exists ? "No estate has been saved for this group."
            : "This estate has no nodes to draw yet."}
        </div>
      )}
      <div style={{ position: "absolute", zIndex: 20, top: 10, left: 14, display: "flex", flexDirection: "column", gap: 6, pointerEvents: "none" }}>
        {(title || list.length > 1) && (
          <div style={{ fontSize: 20, fontWeight: 600, color: "#e6edf5", background: "rgba(13,21,33,.85)", borderRadius: 10, padding: "6px 14px", alignSelf: "flex-start" }}>
            {title}{list.length > 1 ? `${title ? "  " : ""}(${pos + 1}/${list.length})` : ""}
          </div>
        )}
        {gone === groupId && shown && <div role="status" style={warn}>This group no longer exists. Showing the last known picture.</div>}
        {(statusErr || (err && shown)) && shown && <div role="status" style={warn}>Refresh failed. Showing the last known status.</div>}
      </div>
      {!fullscreen && (
        <div style={{ position: "absolute", zIndex: 20, top: 8, right: 12, textAlign: "right", fontSize: 12 }}>
          <button onClick={goFullscreen}
            style={{ fontSize: 12, padding: "4px 12px", borderRadius: 6, border: "1px solid #3b4a5e", background: "rgba(13,21,33,0.8)", color: "#e6edf5", cursor: "pointer" }}>Fullscreen</button>
          {fsMsg && <div style={{ marginTop: 6, maxWidth: 260, color: "#e0a030" }}>{fsMsg}</div>}
        </div>
      )}
    </div>
  );
}
