// Resume rendering — both compact (live preview) and paper (export-style)

const normalize = (s) => (s || "").trim().replace(/\s+/g, " ").toLowerCase();

// Build everything the renderers need to display the resume w/ decisions applied.
// - base: the selected master (falls back to RESUMES[0])
// - suggestionByLine: Map<normalized before-text, suggestion> for in-place matching
//   (only for kinds that anchor to an existing line: rewrite | trim | keep)
// - addsBySection: Map<section title, suggestion[]> for kind="add" cards
function applyDecisions(decisions, resumeId) {
  // Look up bundled first; uploaded masters are cached on window by the
  // Library/Tailor screens after listAllMasters() resolves.
  const cache = window.__forgeMastersCache || [];
  const fromCache = cache.find((m) => m.id === resumeId);
  const base =
    (fromCache && fromCache.content) ||
    (window.RESUMES || []).find((r) => r.id === resumeId) ||
    (window.RESUMES || [])[0];

  const suggestionByLine = new Map();
  const addsBySection = new Map();
  for (const s of window.SUGGESTIONS || []) {
    if (s.kind === "add") {
      const key = s.section || "Skills";
      if (!addsBySection.has(key)) addsBySection.set(key, []);
      addsBySection.get(key).push(s);
    } else if (s.before) {
      suggestionByLine.set(normalize(s.before), s);
    }
  }

  return {
    base,
    suggestionByLine,
    addsBySection,
    name: base.name,
    role: base.role,
    contact: base.contact || `${base.name.toLowerCase().replace(/\s+/g, "")}@example.com`,
    summary: base.summary,
    sections: base.sections,
  };
}

// addsBySection key matching is loose: "Experience · Linear Systems" should
// land in the Experience section. We match on whichever section title the
// add suggestion's `section` field starts with.
function addsForSection(addsBySection, sectionTitle) {
  const out = [];
  for (const [key, list] of addsBySection.entries()) {
    if (
      key === sectionTitle ||
      key.toLowerCase().startsWith(sectionTitle.toLowerCase())
    ) {
      out.push(...list);
    }
  }
  return out;
}

// ---------- Compact preview (review screen right rail) ----------

function ResumePreview({ decisions, compact, resumeId }) {
  const r = applyDecisions(decisions, resumeId);
  const paperPalette = {
    "--ink": "#1B1814",
    "--muted": "#6B5E48",
    "--border": "#E2D7C2",
    "--paper": "#FFFFFF",
  };
  return (
    <div
      style={{
        ...paperPalette,
        fontFamily: "Inter, sans-serif",
        color: "#1B1814",
        fontSize: compact ? 10 : 12,
        lineHeight: 1.5,
        background: "#FFFFFF",
        padding: compact ? "24px 22px" : "40px 48px",
        borderRadius: 4,
        border: "1px solid #E2D7C2",
        boxShadow: "0 1px 0 rgba(27,24,20,0.04)",
      }}
    >
      {/* Header */}
      <div style={{ marginBottom: compact ? 14 : 24 }}>
        <div
          style={{
            fontFamily: "Newsreader, serif",
            fontSize: compact ? 22 : 30,
            fontWeight: 500,
            letterSpacing: "-0.02em",
            color: "#1B1814",
            lineHeight: 1.1,
          }}
        >
          {r.name}
        </div>
        <div
          style={{
            fontFamily: "Inter, sans-serif",
            fontSize: compact ? 10 : 12,
            color: "#6B5E48",
            marginTop: 4,
            marginBottom: compact ? 6 : 10,
          }}
        >
          {r.role}
        </div>
      </div>

      <Rule style={{ marginBottom: compact ? 12 : 18 }} />

      {/* Summary */}
      <ResumeSection title="Summary" compact={compact}>
        <DiffLine line={r.summary} decisions={decisions} index={r.suggestionByLine} />
      </ResumeSection>

      {r.sections.map((sec) => {
        const adds = addsForSection(r.addsBySection, sec.title);
        return (
          <ResumeSection key={sec.title} title={sec.title} compact={compact}>
            {sec.items.map((it, idx) => (
              <div key={idx} style={{ marginBottom: compact ? 10 : 16 }}>
                {it.heading && (
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "baseline",
                      marginBottom: 4,
                      gap: 8,
                    }}
                  >
                    <div>
                      <span
                        style={{
                          fontFamily: "Inter, sans-serif",
                          fontWeight: 600,
                          fontSize: compact ? 11 : 13,
                          color: "#1B1814",
                        }}
                      >
                        {it.heading}
                      </span>
                      <span style={{ color: "#6B5E48", margin: "0 6px" }}>·</span>
                      <span style={{ fontFamily: "Inter, sans-serif", fontSize: compact ? 11 : 13, color: "#1B1814" }}>
                        {it.org}
                      </span>
                    </div>
                    <span
                      style={{
                        fontFamily: "'JetBrains Mono', monospace",
                        fontSize: compact ? 8 : 10,
                        color: "#6B5E48",
                        letterSpacing: "0.04em",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {it.dates}
                    </span>
                  </div>
                )}
                {it.bullets && (
                  <ul style={{ margin: 0, paddingLeft: 16, color: "#1B1814" }}>
                    {it.bullets.map((b, i) => (
                      <li key={i} style={{ marginBottom: compact ? 3 : 5, lineHeight: 1.55 }}>
                        <DiffLine line={b} decisions={decisions} index={r.suggestionByLine} />
                      </li>
                    ))}
                  </ul>
                )}
                {it.inline && (
                  <div style={{ color: "#1B1814" }}>
                    <DiffLine line={it.inline} decisions={decisions} index={r.suggestionByLine} />
                  </div>
                )}
              </div>
            ))}
            {adds.map((s) => (
              <AddedLine key={s.id} suggestion={s} decisions={decisions} compact={compact} />
            ))}
          </ResumeSection>
        );
      })}
    </div>
  );
}

function ResumeSection({ title, compact, children }) {
  return (
    <div style={{ marginBottom: compact ? 12 : 22 }}>
      <Eyebrow style={{ marginBottom: compact ? 6 : 10, fontSize: compact ? 8 : 10 }}>{title}</Eyebrow>
      {children}
    </div>
  );
}

// ---------- Diff renderers ----------

// A line of resume content that may have an associated suggestion.
// - pending / no match: render plain
// - accepted + rewrite|trim|keep: render `after` with accent highlight
// - rejected + trim: muted strikethrough (you said "no, keep the line")
// - rejected + rewrite|keep: render `before` plain
function DiffLine({ line, decisions, index }) {
  const suggestion = index.get(normalize(line));
  if (!suggestion) return <>{line}</>;
  const d = decisions[suggestion.id];

  if (d === "accepted") {
    return (
      <span
        style={{
          background: "rgba(205,236,79,0.32)",
          borderRadius: 2,
          padding: "0 2px",
          transition: "background 200ms",
        }}
      >
        {suggestion.after}
      </span>
    );
  }
  if (d === "rejected" && suggestion.kind === "trim") {
    return (
      <span style={{ color: "#9A8E76", textDecoration: "line-through", textDecorationColor: "rgba(154,142,118,0.6)" }}>
        {line}
      </span>
    );
  }
  // Pending / rejected-rewrite / rejected-keep — just show the original line.
  return <>{line}</>;
}

// A NEW line proposed by an "add" suggestion. Only renders when accepted.
function AddedLine({ suggestion, decisions, compact }) {
  if (decisions[suggestion.id] !== "accepted") return null;
  return (
    <div
      style={{
        marginTop: compact ? 4 : 8,
        paddingLeft: 16,
        position: "relative",
      }}
    >
      <span
        style={{
          background: "rgba(205,236,79,0.32)",
          borderRadius: 2,
          padding: "0 2px",
          color: "#1B1814",
        }}
      >
        + {suggestion.after}
      </span>
    </div>
  );
}

// ---------- Full-page paper version (export) ----------

function ResumePaper({ decisions, template, resumeId }) {
  const r = applyDecisions(decisions, resumeId);
  const isClassic = template === "classic";
  const isMinimal = template === "minimal";
  const isModern = template === "modern" || (!isClassic && !isMinimal);

  return (
    <div
      style={{
        fontFamily: isClassic ? "Newsreader, serif" : "Inter, sans-serif",
        color: "#1B1814",
        fontSize: 11,
        lineHeight: 1.55,
      }}
    >
      {/* Header */}
      <div style={{ marginBottom: 24, textAlign: isClassic ? "center" : "left" }}>
        <div
          style={{
            fontFamily: isMinimal ? "Inter, sans-serif" : "Newsreader, serif",
            fontSize: isMinimal ? 22 : 32,
            fontWeight: isMinimal ? 600 : 500,
            letterSpacing: isMinimal ? "-0.01em" : "-0.025em",
            color: "#1B1814",
            lineHeight: 1.05,
            textTransform: isMinimal ? "uppercase" : "none",
          }}
        >
          {r.name}
        </div>
        <div
          style={{
            fontFamily: "Inter, sans-serif",
            fontSize: 13,
            color: "#6B5E48",
            marginTop: 6,
            marginBottom: 10,
            fontStyle: isClassic ? "italic" : "normal",
          }}
        >
          {r.role}
        </div>
      </div>

      <div
        style={{
          height: isClassic ? 0 : 1,
          background: "#E2D7C5",
          marginBottom: 22,
          borderTop: isClassic ? "1px solid #1B1814" : "none",
        }}
      />

      {/* Summary */}
      <PaperSection title="Summary" template={template}>
        <DiffLine line={r.summary} decisions={decisions} index={r.suggestionByLine} />
      </PaperSection>

      {r.sections.map((sec) => {
        const adds = addsForSection(r.addsBySection, sec.title);
        return (
          <PaperSection key={sec.title} title={sec.title} template={template}>
            {sec.items.map((it, idx) => (
              <div key={idx} style={{ marginBottom: 14 }}>
                {it.heading && (
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "baseline",
                      marginBottom: 5,
                    }}
                  >
                    <div style={{ fontFamily: "Inter, sans-serif" }}>
                      <span style={{ fontWeight: 600, color: "#1B1814" }}>{it.heading}</span>
                      <span style={{ color: "#6B5E48", margin: "0 6px" }}>·</span>
                      <span style={{ color: "#1B1814" }}>{it.org}</span>
                    </div>
                    <span
                      style={{
                        fontFamily: isModern ? "'JetBrains Mono', monospace" : "Inter, sans-serif",
                        fontSize: 10,
                        color: "#6B5E48",
                        letterSpacing: isModern ? "0.04em" : "0",
                      }}
                    >
                      {it.dates}
                    </span>
                  </div>
                )}
                {it.bullets && (
                  <ul style={{ margin: 0, paddingLeft: 18, color: "#1B1814", fontFamily: "Inter, sans-serif" }}>
                    {it.bullets.map((b, i) => (
                      <li key={i} style={{ marginBottom: 4, lineHeight: 1.55 }}>
                        <DiffLine line={b} decisions={decisions} index={r.suggestionByLine} />
                      </li>
                    ))}
                  </ul>
                )}
                {it.inline && (
                  <div style={{ color: "#1B1814", fontFamily: "Inter, sans-serif" }}>
                    <DiffLine line={it.inline} decisions={decisions} index={r.suggestionByLine} />
                  </div>
                )}
              </div>
            ))}
            {adds.map((s) => (
              <AddedLine key={s.id} suggestion={s} decisions={decisions} />
            ))}
          </PaperSection>
        );
      })}
    </div>
  );
}

function PaperSection({ title, template, children }) {
  const isClassic = template === "classic";
  const isMinimal = template === "minimal";
  return (
    <div style={{ marginBottom: 20 }}>
      <div
        style={{
          fontFamily: isClassic ? "Newsreader, serif" : "'JetBrains Mono', monospace",
          fontSize: isClassic ? 14 : 10,
          textTransform: isClassic ? "none" : "uppercase",
          letterSpacing: isClassic ? "0" : "0.16em",
          fontStyle: isClassic ? "italic" : "normal",
          fontWeight: isClassic ? 500 : 500,
          color: isMinimal ? "#1B1814" : "#6B5E48",
          marginBottom: 10,
          borderBottom: isMinimal ? "1px solid #1B1814" : "none",
          paddingBottom: isMinimal ? 4 : 0,
        }}
      >
        {title}
      </div>
      {children}
    </div>
  );
}

// ---------- Pure data: produce the final resume after decisions ----------
//
// Used by exporters (PDF / DOCX). No JSX, no React. Walks the master,
// substitutes accepted lines, drops trimmed lines that were ALSO accepted
// (trim+accept means "yes, cut this"), and appends accepted "add" lines.
function finalizeResume(decisions, resumeId) {
  const r = applyDecisions(decisions, resumeId);

  const transformLine = (line) => {
    const s = r.suggestionByLine.get(normalize(line));
    if (!s) return { keep: true, text: line };
    const d = decisions[s.id];
    if (s.kind === "trim" && d === "accepted") return { keep: false };
    if (d === "accepted") return { keep: true, text: s.after };
    return { keep: true, text: line };
  };

  const summary = transformLine(r.summary).text || r.summary;

  const sections = r.sections.map((sec) => {
    const items = sec.items.map((it) => {
      const out = { ...it };
      if (it.bullets) {
        out.bullets = it.bullets.map(transformLine).filter((x) => x.keep).map((x) => x.text);
      }
      if (it.inline) {
        const t = transformLine(it.inline);
        out.inline = t.keep ? t.text : null;
      }
      return out;
    });
    const adds = addsForSection(r.addsBySection, sec.title)
      .filter((s) => decisions[s.id] === "accepted")
      .map((s) => s.after);
    return { title: sec.title, items, addedLines: adds };
  });

  return {
    name: r.name,
    role: r.role,
    contact: r.contact,
    summary,
    sections,
  };
}

Object.assign(window, { ResumePreview, ResumePaper, finalizeResume });
