// Variant A: Bottom Sheet
// Tap a highlight → sheet slides up with issue details + AI suggestion + Accept/Edit/Dismiss.
// "Review queue" button opens a second sheet with the full issue list.

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

function VariantSheet({ ctx }) {
  const { issueStates, setIssueStates, activeId, setActiveId, score, openIssues, handleFixAll, version, setVersion, undo, canUndo } = ctx;
  const [editing, setEditing] = useStateA(false);
  const [editText, setEditText] = useStateA("");
  const [reviewOpen, setReviewOpen] = useStateA(false);

  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 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 || "";
  };

  const originalText = activeId ? originalFor(activeId) : "";

  useEffectA(() => { setEditing(false); setEditText(originalText); }, [activeId, originalText]);

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

  const openFromQueue = (id) => {
    setActiveId(id);
    setReviewOpen(false);
  };

  const sheetOpen = !!activeId;
  const backdropOpen = sheetOpen || reviewOpen;

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", 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)" }}>
        <ResumeBody onIssue={(id) => { setActiveId(id); setReviewOpen(false); }} issueStates={issueStates} activeId={activeId} variantStyle="underline" />
      </div>

      {/* Review queue floating button — visible when no sheet is open */}
      {!sheetOpen && !reviewOpen && openIssues.length > 0 && (
        <button
          onClick={() => setReviewOpen(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>
      )}

      {/* Backdrop */}
      <div
        onClick={() => { setActiveId(null); setReviewOpen(false); }}
        style={{
          position: "absolute", inset: 0,
          background: backdropOpen ? "rgba(16,15,14,.28)" : "transparent",
          pointerEvents: backdropOpen ? "auto" : "none",
          transition: "background .2s ease",
          zIndex: 40,
        }}
      />

      {/* Review Queue Sheet */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: "var(--mobile-nav-height, 54px)", zIndex: 50,
        background: "var(--color-neutral-100)",
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: "0 -8px 24px rgba(0,0,0,.08)",
        transform: reviewOpen ? "translateY(0)" : "translateY(110%)",
        transition: "transform .32s cubic-bezier(.22,.61,.36,1)",
        maxHeight: "62%",
        display: "flex", flexDirection: "column",
        paddingBottom: "var(--safe-bottom, 0px)",
      }}>
        <button onClick={() => setReviewOpen(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 review</div>
          </div>
          <button onClick={() => { handleFixAll(); setReviewOpen(false); }} 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 issMeta = window.ISSUE_META[iss.type];
            const issTint = window.TINTS[issMeta.tint];
            return (
              <button key={id}
                onClick={() => openFromQueue(id)}
                style={{
                  display: "flex", gap: 10, width: "100%",
                  textAlign: "left", padding: 12, borderRadius: 12,
                  border: "2px solid transparent",
                  background: "transparent",
                  cursor: "pointer", marginBottom: 2,
                  fontFamily: "var(--font-body)",
                }}
              >
                <div style={{ width: 4, alignSelf: "stretch", borderRadius: 4, background: issTint.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>

      {/* Issue Detail Sheet */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: "var(--mobile-nav-height, 54px)", zIndex: 50,
        background: "var(--color-neutral-100)",
        borderTopLeftRadius: 20, borderTopRightRadius: 20,
        boxShadow: "var(--shadow-xl)",
        transform: sheetOpen ? "translateY(0)" : "translateY(110%)",
        transition: "transform .32s cubic-bezier(.22,.61,.36,1)",
        padding: "10px 18px calc(22px + var(--safe-bottom, 0px))",
        maxHeight: "72%",
        overflowY: "auto",
      }}>
        <div style={{ display: "grid", placeItems: "center", padding: "4px 0 10px" }}>
          <div style={{ width: 40, height: 4, borderRadius: 999, background: "var(--color-neutral-80)" }} />
        </div>
        {issue && (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
              <TypeChip type={issue.type} />
              <SeverityDot severity={issue.severity} />
              <span style={{ fontSize: 11, color: "var(--fg-3)", fontFamily: "var(--font-body)" }}>
                {issue.severity === "high" ? "High impact" : issue.severity === "med" ? "Medium" : "Low"}
              </span>
            </div>
            <h3 style={{ fontFamily: "var(--font-heading)", fontWeight: 500, fontSize: 20, margin: "0 0 6px", letterSpacing: "-.01em", color: "var(--fg-1)" }}>
              {issue.title}
            </h3>
            <p style={{ fontSize: 13.5, color: "var(--fg-2)", lineHeight: 1.55, margin: "0 0 14px", textWrap: "pretty" }}>
              {issue.why}
            </p>

            {/* Before */}
            <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--fg-3)", marginBottom: 6 }}>
              Your text
            </div>
            <div style={{
              background: "var(--color-neutral-95)", border: "1px solid var(--border-1)",
              borderRadius: 10, padding: "10px 12px", fontSize: 13.5,
              color: "var(--fg-2)", lineHeight: 1.5, marginBottom: 12, textDecoration: "line-through",
              textDecorationColor: tint.underline, textDecorationThickness: 1,
            }}>
              {originalText}
            </div>

            {/* After */}
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
              <span style={{ color: "var(--color-ai-50)", display: "inline-flex" }}>
                <Icon name="sparkle.svg" size={12} />
              </span>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--color-ai-50)" }}>
                AI suggestion
              </div>
            </div>

            {editing ? (
              <textarea
                value={editText}
                onChange={e => setEditText(e.target.value)}
                rows={3}
                autoFocus
                style={{
                  width: "100%", boxSizing: "border-box", resize: "vertical",
                  border: "2px solid var(--color-neutral-0)", borderRadius: 10,
                  padding: "10px 12px", fontSize: 13.5, lineHeight: 1.5,
                  fontFamily: "var(--font-body)", color: "var(--fg-1)",
                  background: "var(--color-neutral-100)", outline: "none",
                  marginBottom: 12,
                }}
              />
            ) : (
              <div style={{
                background: "var(--color-ai-99)", border: "1px solid var(--color-ai-90)",
                borderRadius: 10, padding: "10px 12px", fontSize: 13.5,
                color: "var(--fg-1)", lineHeight: 1.5, marginBottom: 12,
              }}>
                {issue.suggestion}
              </div>
            )}

            {/* Actions */}
            <div style={{ display: "flex", gap: 8 }}>
              <button
                onClick={() => accept(editing ? editText : issue.suggestion)}
                style={{
                  flex: 1, background: "var(--color-neutral-0)", color: "var(--color-neutral-100)",
                  border: 0, padding: "13px 14px", borderRadius: 999,
                  fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 500, cursor: "pointer",
                  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
                }}
              >
                {editing ? "Save edit" : "Accept"}
                {!editing && <span style={{color:"var(--color-secondary-base)",display:"inline-flex"}}><Icon name="sparkle.svg" size={12}/></span>}
              </button>
              <button
                onClick={() => setEditing(e => !e)}
                style={{
                  background: "var(--color-neutral-100)", color: "var(--fg-1)",
                  border: "1.5px solid var(--border-1)", padding: "13px 14px", borderRadius: 999,
                  fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 500, cursor: "pointer",
                }}
              >{editing ? "Cancel" : "Edit"}</button>
              <button
                onClick={dismiss}
                style={{
                  background: "transparent", color: "var(--fg-2)",
                  border: 0, padding: "13px 10px", borderRadius: 999,
                  fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 500, cursor: "pointer",
                }}
              >Dismiss</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
window.VariantSheet = VariantSheet;
