// EntityPanel — slide-in from right, 480px wide. Fetches /entities/{id} for full detail.

// React hooks (Babel-standalone — make hooks visible per-script)
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

const epStyles = {
  scrim: { position: "fixed", inset: 0, background: "rgba(14,10,26,0.55)", zIndex: 50, animation: "vkfade 120ms ease-out" },
  panel: {
    position: "fixed", top: 0, right: 0, bottom: 0, width: 480,
    background: "var(--vk-surface-1)",
    boxShadow: "-1px 0 0 0 rgba(233,30,99,0.30)",
    zIndex: 60, display: "flex", flexDirection: "column",
    animation: "vkslide 200ms cubic-bezier(0.2,0.7,0.2,1)",
  },
  header: {
    padding: 16, borderBottom: "1px solid var(--vk-border-subtle)",
    display: "flex", alignItems: "flex-start", gap: 12,
  },
  scroll: { flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 16 },
  scoreGrid: {
    display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8,
    padding: 12, background: "var(--vk-surface-2)", borderRadius: 5,
  },
  scoreCell: { display: "flex", flexDirection: "column", gap: 2 },
  flagRow: {
    display: "grid", gridTemplateColumns: "1fr auto", gap: 8,
    padding: "6px 0", borderBottom: "1px solid var(--vk-border-subtle)",
    fontSize: 12, color: "var(--vk-text-secondary)",
  },
  relRow: {
    display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10,
    alignItems: "center", padding: "8px 0",
    borderBottom: "1px solid var(--vk-border-subtle)",
    fontSize: 13,
  },
};

function ScoreCell({ label, value, riskScale }) {
  return (
    <div style={epStyles.scoreCell}>
      <span style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--vk-text-tertiary)", fontWeight: 500 }}>{label}</span>
      <span className="vk-mono" style={{ fontSize: 16, fontWeight: 500 }}>
        <Score value={value} riskScale={riskScale} />
      </span>
    </div>
  );
}

function flagLabel(v) {
  if (v === "yes") return <Pill kind="high">yes</Pill>;
  if (v === "no") return <Pill kind="neutral">no</Pill>;
  return <Pill kind="neutral">unknown</Pill>;
}

function EntityPanel({ entityId, onClose, openEvidence, openEntity }) {
  const { data, loading } = useApi(entityId ? "/entities/" + entityId : null, {}, [entityId]);
  if (!entityId) return null;

  const entity = data?.entity || null;
  const evidence = data?.evidence || [];
  const rels = data?.relationships || [];

  return (
    <>
      <div style={epStyles.scrim} onClick={onClose}></div>
      <div style={epStyles.panel}>
        <div style={epStyles.header}>
          {entity ? <Avatar name={entity.canonical_name} size={48} /> : <div style={{ width: 48, height: 48, borderRadius: 999, background: "var(--vk-surface-2)" }}></div>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 500, color: "var(--vk-text-primary)" }}>
                {entity?.canonical_name || (loading ? "Loading…" : "Not found")}
              </h2>
              {entity?.needs_review && <Pill kind="med">needs review</Pill>}
            </div>
            {entity && (
              <>
                <div style={{ fontSize: 12, color: "var(--vk-text-secondary)", marginTop: 4 }}>
                  {entity.entity_type}{entity.subtype ? ` · ${entity.subtype}` : ""}
                  {entity.sector_or_focus ? ` · ${entity.sector_or_focus}` : ""}
                </div>
                <div style={{ fontSize: 11, color: "var(--vk-text-tertiary)", marginTop: 2 }}>
                  {entity.city}{entity.state ? `, ${entity.state}` : ""} · entity_id <span className="vk-mono">{entity.entity_id}</span>
                </div>
              </>
            )}
          </div>
          <button className="vk-btn vk-btn--ghost" onClick={onClose} aria-label="Close panel" style={{ width: 28, padding: 0, justifyContent: "center" }}>
            <Icon name="X" size={16} />
          </button>
        </div>

        <div style={epStyles.scroll}>
          {loading && <SkeletonBlock rows={6} />}

          {entity && entity.role_in_ecosystem && (
            <div>
              <MicroCap>Role</MicroCap>
              <p style={{ fontSize: 13, lineHeight: 1.55, color: "var(--vk-text-primary)", marginTop: 4 }}>
                {entity.role_in_ecosystem}
              </p>
            </div>
          )}

          {entity && entity.description && (
            <div>
              <MicroCap>Description</MicroCap>
              <p style={{ fontSize: 13, lineHeight: 1.55, color: "var(--vk-text-primary)", marginTop: 4 }}>
                {entity.description}
              </p>
            </div>
          )}

          {entity && (
            <>
              <div>
                <MicroCap>Scores</MicroCap>
                <div style={{ ...epStyles.scoreGrid, marginTop: 6 }}>
                  <ScoreCell label="Infl." value={entity.influence_score} />
                  <ScoreCell label="Relev." value={entity.relevance_score} />
                  <ScoreCell label="Risk" value={entity.risk_score} riskScale />
                  <ScoreCell label="Conf." value={entity.confidence_score} />
                </div>
              </div>

              <div>
                <MicroCap>Candidate flags</MicroCap>
                <div style={{ marginTop: 6 }}>
                  {[
                    ["Partner", "partner_candidate"],
                    ["Supporter", "supporter_candidate"],
                    ["Competitor", "competitor_candidate"],
                    ["Blocker", "blocker_candidate"],
                    ["Investment target", "investment_candidate"],
                    ["Support target", "support_candidate"],
                    ["Recruiting target", "recruiting_candidate"],
                  ].map(([lbl, k]) => (
                    <div key={k} style={epStyles.flagRow}>
                      <span>{lbl}</span>{flagLabel(entity[k])}
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <MicroCap>Relationships <span style={{ color: "var(--vk-text-tertiary)", marginLeft: 8, fontFamily: "var(--vk-font-mono)" }}>{rels.length}</span></MicroCap>
                <div style={{ marginTop: 6 }}>
                  {rels.length === 0 && <EmptyState icon="Share2" title="No relationships yet for this entity." />}
                  {rels.slice(0, 20).map((r) => {
                    const otherId = r.source_entity_id === entity.entity_id ? r.target_entity_id : r.source_entity_id;
                    const otherName = r.source_entity_id === entity.entity_id ? r.target_entity_name : r.source_entity_name;
                    const direction = r.source_entity_id === entity.entity_id ? "→" : "←";
                    return (
                      <div key={r.relationship_id} style={epStyles.relRow}>
                        <span className="vk-mono" style={{ fontSize: 11, color: "var(--vk-text-tertiary)" }}>
                          {direction} {r.relationship_type.replaceAll("_", " ").toLowerCase()}
                        </span>
                        <a href="#"
                          className="vk-link"
                          onClick={(e) => {
                            e.preventDefault();
                            window.VK_API.fetchPath("/entities/" + otherId).then((res) => {
                              if (res?.entity) openEntity(res.entity);
                            });
                          }}
                        >{otherName}</a>
                        <ConfPill confidence={r.confidence} />
                      </div>
                    );
                  })}
                </div>
              </div>

              <div>
                <MicroCap>Evidence <span style={{ color: "var(--vk-text-tertiary)", marginLeft: 8, fontFamily: "var(--vk-font-mono)" }}>{evidence.length}</span></MicroCap>
                <div style={{ marginTop: 6 }}>
                  {evidence.length === 0 && (
                    <div style={{ fontSize: 12, color: "var(--vk-text-tertiary)" }}>No evidence rows linked to this entity yet.</div>
                  )}
                  {evidence.slice(0, 8).map((ev) => (
                    <div key={ev.evidence_id}
                      onClick={() => openEvidence(ev)}
                      style={{ padding: "8px 0", borderBottom: "1px solid var(--vk-border-subtle)", cursor: "pointer", display: "flex", flexDirection: "column", gap: 2 }}
                    >
                      <span style={{ fontSize: 12, color: "var(--vk-text-primary)" }}>{ev.source_title}</span>
                      <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                        <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)" }}>{ev.publisher_or_owner} · {ev.date_published}</span>
                        <ConfPill confidence={ev.confidence} />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { EntityPanel });
