// Variant B: Inline Popover
// Tap a highlight → compact popover appears anchored to the text.
// Highlights render as soft chip-boxes (not just underlines) so the touch target is big.

function VariantPopover({ ctx }) {
  const { issueStates, setIssueStates, activeId, setActiveId, score, openIssues, handleFixAll, version, setVersion, undo, canUndo } = ctx;
  const [anchor, setAnchor] = React.useState(null);
  const stageRef = React.useRef(null);

  const issue = activeId ? window.ISSUES[activeId] : null;
  const meta = issue ? window.ISSUE_META[issue.type] : null;
  const tint = meta ? window.TINTS[meta.tint] : null;

  const originalText = (() => {
    if (!activeId) return "";
    const all = [
      ...window.RESUME.summary.fragments,
      ...window.RESUME.experience.flatMap(e => e.bullets.flatMap(b => b.fragments)),
      ...window.RESUME.skills.fragments,
    ];
    return all.find(f => f.issue === activeId)?.text || "";
  })();

  const accept = () => {
    setIssueStates(prev => ({ ...prev, [activeId]: { state: "accepted", replaced: issue.suggestion } }));
    setActiveId(null);
  };
  const dismiss = () => {
    setIssueStates(prev => ({ ...prev, [activeId]: { state: "dismissed" } }));
    setActiveId(null);
  };

  const onIssue = (id, el) => {
    const stage = stageRef.current;
    if (!stage) return;
    const r = el.getBoundingClientRect();
    const s = stage.getBoundingClientRect();
    setAnchor({
      left: Math.max(10, Math.min(r.left - s.left + r.width / 2, s.width - 10)),
      top: r.top - s.top,
      bottom: r.bottom - s.top,
    });
    setActiveId(id);
  };

  // Position popover: prefer above the anchor; if too close to top (<180px), flip below
  const placeAbove = anchor ? anchor.top > 220 : true;
  const popTop = placeAbove ? (anchor?.top || 0) - 12 : (anchor?.bottom || 0) + 12;
  const popTransform = placeAbove ? "translate(-50%, -100%)" : "translate(-50%, 0)";

  return (
    <div ref={stageRef} style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", background: "var(--color-neutral-99)" }}>
      <TopBar score={score} issueCount={openIssues.length} version={version} onVersion={setVersion} onFixAll={handleFixAll} onUndo={undo} canUndo={canUndo} />
      <div style={{ flex: 1, overflowY: "auto", background: "var(--color-neutral-100)" }} onClick={() => setActiveId(null)}>
        <ResumeBody onIssue={onIssue} issueStates={issueStates} activeId={activeId} variantStyle="chip" />
      </div>

      {activeId && anchor && issue && (
        <>
          {/* tiny tail */}
          <div style={{
            position: "absolute", left: anchor.left, top: placeAbove ? anchor.top - 6 : anchor.bottom + 4,
            width: 10, height: 10, background: "var(--color-neutral-0)",
            transform: `translate(-50%, ${placeAbove ? "-50%" : "-50%"}) rotate(45deg)`,
            zIndex: 49,
          }} />
          <div style={{
            position: "absolute", left: anchor.left, top: popTop,
            transform: popTransform, zIndex: 50,
            width: "min(320px, calc(100% - 24px))",
            background: "var(--color-neutral-0)", color: "var(--color-neutral-100)",
            borderRadius: 14, padding: 14, boxShadow: "var(--shadow-lg)",
            fontFamily: "var(--font-body)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <span style={{
                fontSize: 10.5, fontWeight: 500, padding: "2px 8px",
                background: tint.underline + "33", color: tint.underline,
                borderRadius: 999, border: `1px solid ${tint.underline}55`,
              }}>{meta.label}</span>
              <SeverityDot severity={issue.severity} />
              <div style={{ flex: 1 }} />
              <button onClick={() => setActiveId(null)} style={{ background: "transparent", border: 0, color: "var(--color-neutral-80)", cursor: "pointer", padding: 2, display: "inline-flex" }}>
                <Icon name="close.svg" size={14} style={{ filter: "invert(1)" }} />
              </button>
            </div>
            <div style={{ fontFamily: "var(--font-heading)", fontWeight: 500, fontSize: 16, letterSpacing: "-.01em", marginBottom: 4 }}>{issue.title}</div>
            <div style={{ fontSize: 12.5, color: "var(--color-neutral-80)", lineHeight: 1.5, marginBottom: 10, textWrap: "pretty" }}>{issue.why}</div>

            <div style={{
              background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.12)",
              borderRadius: 10, padding: "8px 10px", fontSize: 12.5, lineHeight: 1.45,
              marginBottom: 10, color: "var(--color-neutral-90)",
            }}>
              <div style={{ fontSize: 9.5, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--color-neutral-70)", marginBottom: 2 }}>From</div>
              <div style={{ textDecoration: "line-through", textDecorationColor: tint.underline, textDecorationThickness: 1 }}>{originalText}</div>
              <div style={{ fontSize: 9.5, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--color-secondary-base)", marginTop: 8, marginBottom: 2, display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{color:"var(--color-secondary-base)",display:"inline-flex"}}><Icon name="sparkle.svg" size={10}/></span> To
              </div>
              <div style={{ color: "var(--color-neutral-100)" }}>{issue.suggestion}</div>
            </div>

            <div style={{ display: "flex", gap: 6 }}>
              <button onClick={accept} style={{
                flex: 1, background: "var(--color-secondary-base)", color: "var(--color-neutral-0)",
                border: 0, padding: "9px 12px", borderRadius: 999, cursor: "pointer",
                fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 500,
              }}>Accept fix</button>
              <button onClick={dismiss} style={{
                background: "transparent", color: "var(--color-neutral-80)",
                border: "1px solid rgba(255,255,255,.2)", padding: "9px 12px", borderRadius: 999, cursor: "pointer",
                fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 500,
              }}>Ignore</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
window.VariantPopover = VariantPopover;
