// Variant C: Issue list drawer
// A "Review queue" chip lives at the top of the resume; a swipe-up drawer from the bottom
// shows the full list of issues. Tapping one focuses it inline (highlight + inline accept/dismiss row).

function VariantDrawer({ ctx }) {
  const { issueStates, setIssueStates, activeId, setActiveId, score, openIssues, handleFixAll, version, setVersion, undo, canUndo } = ctx;
  const [drawerOpen, setDrawerOpen] = React.useState(true);
  const scrollRef = React.useRef(null);

  const issue = activeId ? window.ISSUES[activeId] : null;

  // Scroll the active issue into view
  React.useEffect(() => {
    if (!activeId) return;
    const el = document.querySelector(`[data-issue="${activeId}"]`);
    if (el && scrollRef.current) {
      const s = scrollRef.current.getBoundingClientRect();
      const r = el.getBoundingClientRect();
      scrollRef.current.scrollBy({ top: r.top - s.top - 180, behavior: "smooth" });
    }
  }, [activeId]);

  const accept = (id) => {
    const iss = window.ISSUES[id];
    setIssueStates(prev => ({ ...prev, [id]: { state: "accepted", replaced: iss.suggestion } }));
    // auto-advance to next open issue
    const next = openIssues.find(x => x !== id);
    setActiveId(next || null);
  };
  const dismiss = (id) => {
    setIssueStates(prev => ({ ...prev, [id]: { state: "dismissed" } }));
    const next = openIssues.find(x => x !== id);
    setActiveId(next || null);
  };

  const originalFor = (id) => {
    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 === id)?.text || "";
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "var(--color-neutral-99)", position: "relative" }}>
      <TopBar score={score} issueCount={openIssues.length} version={version} onVersion={setVersion} onFixAll={handleFixAll} onUndo={undo} canUndo={canUndo} />

      <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", background: "var(--color-neutral-100)", position: "relative" }}>
        <ResumeBody onIssue={(id) => { setActiveId(id); setDrawerOpen(false); }} issueStates={issueStates} activeId={activeId} variantStyle="underline" />

        {/* Inline action bar that appears under the currently-focused issue */}
        {activeId && issue && <InlineActionFor id={activeId} scrollRef={scrollRef} onAccept={() => accept(activeId)} onDismiss={() => dismiss(activeId)} onClose={() => setActiveId(null)} original={originalFor(activeId)} />}

        <div style={{ height: drawerOpen ? 260 : 90 }} />
      </div>

      {/* Floating drawer toggle (when collapsed) */}
      {!drawerOpen && openIssues.length > 0 && (
        <button
          onClick={() => setDrawerOpen(true)}
          style={{
            position: "absolute", left: "50%", transform: "translateX(-50%)",
            bottom: "calc(18px + var(--safe-bottom, 0px) + var(--mobile-nav-height, 54px))", zIndex: 45,
            background: "var(--color-neutral-0)", color: "var(--color-neutral-100)",
            border: 0, padding: "11px 18px", borderRadius: 999, cursor: "pointer",
            fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 500,
            boxShadow: "var(--shadow-lg)",
            display: "inline-flex", alignItems: "center", gap: 8,
          }}
        >
          <span style={{
            background: "var(--color-primary-base)", color: "var(--color-neutral-0)",
            borderRadius: 999, width: 20, height: 20, display: "inline-grid", placeItems: "center",
            fontSize: 11, fontWeight: 500,
          }}>{openIssues.length}</span>
          Review queue
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="m6 15 6-6 6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
      )}

      {/* Drawer */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: "var(--mobile-nav-height, 54px)", zIndex: 40,
        background: "var(--color-neutral-100)",
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: "0 -8px 24px rgba(0,0,0,.08)",
        transform: drawerOpen ? "translateY(0)" : "translateY(100%)",
        transition: "transform .32s cubic-bezier(.22,.61,.36,1)",
        maxHeight: "62%",
        display: "flex", flexDirection: "column",
        paddingBottom: "var(--safe-bottom, 0px)",
      }}>
        <button onClick={() => setDrawerOpen(false)} style={{
          border: 0, background: "transparent", padding: "8px 0", cursor: "pointer",
          display: "grid", placeItems: "center",
        }}>
          <div style={{ width: 40, height: 4, borderRadius: 999, background: "var(--color-neutral-80)" }} />
        </button>
        <div style={{ padding: "2px 18px 10px", display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <div>
            <h3 style={{ fontFamily: "var(--font-heading)", fontWeight: 500, fontSize: 18, margin: 0, letterSpacing: "-.01em" }}>Review queue</h3>
            <div style={{ fontSize: 11, color: "var(--fg-3)", marginTop: 2 }}>{openIssues.length} left · tap to focus</div>
          </div>
          <button onClick={handleFixAll} disabled={openIssues.length === 0} style={window.fixAllButtonStyle(openIssues.length === 0)}>
            <span style={{ display: "inline-flex", opacity: openIssues.length === 0 ? .45 : 1 }}>
              <Icon name="sparkle.svg" size={12}/>
            </span>
            Fix all
          </button>
        </div>

        <div style={{ overflowY: "auto", padding: "0 10px calc(18px + var(--safe-bottom, 0px))" }}>
          {openIssues.length === 0 ? (
            <div style={{ padding: "28px 20px", textAlign: "center" }}>
              <div style={{ fontFamily: "var(--font-heading)", fontWeight: 500, fontSize: 18, letterSpacing: "-.01em" }}>All clear.</div>
              <div style={{ fontSize: 13, color: "var(--fg-3)", marginTop: 4 }}>Your resume's at its strongest.</div>
            </div>
          ) : openIssues.map(id => {
            const iss = window.ISSUES[id];
            const meta = window.ISSUE_META[iss.type];
            const tint = window.TINTS[meta.tint];
            const active = activeId === id;
            return (
              <button key={id}
                onClick={() => setActiveId(id)}
                style={{
                  display: "flex", gap: 10, width: "100%",
                  textAlign: "left", padding: 12, borderRadius: 12,
                  border: `2px solid ${active ? "var(--color-neutral-0)" : "transparent"}`,
                  background: active ? "var(--color-neutral-99)" : "transparent",
                  cursor: "pointer", marginBottom: 2,
                  fontFamily: "var(--font-body)",
                }}
              >
                <div style={{ width: 4, alignSelf: "stretch", borderRadius: 4, background: tint.underline, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3 }}>
                    <TypeChip type={iss.type} />
                    <SeverityDot severity={iss.severity} />
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: "var(--fg-1)", lineHeight: 1.3 }}>{iss.title}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-3)", marginTop: 3, overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 1, WebkitBoxOrient: "vertical" }}>
                    "{originalFor(id)}"
                  </div>
                </div>
                <Icon name="arrow-right.svg" size={14} style={{ opacity: .5, alignSelf: "center", flexShrink: 0 }} />
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}
window.VariantDrawer = VariantDrawer;

// ---------- Inline action bar (appears next to focused issue) ----------
function InlineActionFor({ id, scrollRef, onAccept, onDismiss, onClose, original }) {
  const iss = window.ISSUES[id];
  const meta = window.ISSUE_META[iss.type];
  const tint = window.TINTS[meta.tint];
  const [pos, setPos] = React.useState(null);

  React.useLayoutEffect(() => {
    const el = document.querySelector(`[data-issue="${id}"]`);
    if (!el || !scrollRef.current) return;
    const scroll = scrollRef.current;
    const update = () => {
      const r = el.getBoundingClientRect();
      const s = scroll.getBoundingClientRect();
      setPos({ top: r.bottom - s.top + scroll.scrollTop + 6, left: 16, right: 16 });
    };
    update();
    scroll.addEventListener("scroll", update);
    return () => scroll.removeEventListener("scroll", update);
  }, [id]);

  if (!pos) return null;
  return (
    <div style={{
      position: "absolute", top: pos.top, left: pos.left, right: pos.right,
      background: "var(--color-neutral-0)", color: "var(--color-neutral-100)",
      borderRadius: 14, padding: 12, boxShadow: "var(--shadow-lg)",
      fontFamily: "var(--font-body)", zIndex: 20,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
        <span style={{
          fontSize: 10.5, fontWeight: 500, padding: "2px 8px",
          background: tint.underline + "33", color: tint.underline,
          borderRadius: 999,
        }}>{meta.label}</span>
        <div style={{ fontSize: 12.5, fontWeight: 500 }}>{iss.title}</div>
        <div style={{ flex: 1 }}/>
        <button onClick={onClose} 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={{ fontSize: 12.5, color: "var(--color-neutral-80)", lineHeight: 1.5, marginBottom: 8, textWrap: "pretty" }}>{iss.why}</div>
      <div style={{ fontSize: 12.5, color: "var(--color-neutral-100)", lineHeight: 1.45, marginBottom: 10,
        background:"rgba(255,255,255,.07)", border:"1px solid rgba(255,255,255,.12)", borderRadius:8, padding:"8px 10px" }}>
        <span style={{color:"var(--color-secondary-base)",display:"inline-flex",verticalAlign:"middle",marginRight:4}}><Icon name="sparkle.svg" size={10}/></span>
        {iss.suggestion}
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <button onClick={onAccept} 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</button>
        <button onClick={onDismiss} style={{
          background: "transparent", color: "var(--color-neutral-80)",
          border: "1px solid rgba(255,255,255,.2)", padding: "9px 14px", borderRadius: 999, cursor: "pointer",
          fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 500,
        }}>Skip</button>
      </div>
    </div>
  );
}
window.InlineActionFor = InlineActionFor;
