// Review screen — accept/reject AI suggestion cards

const { useState: useStateRev, useMemo: useMemoRev } = React;

function ReviewScreen({ context, onContinue, onBack }) {
  // status: pending | accepted | rejected
  const [decisions, setDecisions] = useStateRev(() => {
    const initial = Object.fromEntries(window.SUGGESTIONS.map((s) => [s.id, "pending"]));
    // Restore prior decisions when re-opening a saved version.
    if (context && context.decisions) {
      for (const [k, v] of Object.entries(context.decisions)) {
        if (k in initial) initial[k] = v;
      }
    }
    return initial;
  });
  const [activeId, setActiveId] = useStateRev(window.SUGGESTIONS[0].id);

  const counts = useMemoRev(() => {
    const out = { pending: 0, accepted: 0, rejected: 0 };
    Object.values(decisions).forEach((d) => (out[d] += 1));
    return out;
  }, [decisions]);

  const total = window.SUGGESTIONS.length;
  const progress = ((counts.accepted + counts.rejected) / total) * 100;

  const setDecision = (id, val) => setDecisions((d) => ({ ...d, [id]: val }));

  const acceptAll = () => {
    const next = {};
    window.SUGGESTIONS.forEach((s) => (next[s.id] = "accepted"));
    setDecisions(next);
  };

  return (
    <div style={{ display: "flex", height: "calc(100vh - 73px)" }}>
      {/* Left: suggestion stream */}
      <div style={{ flex: 1, overflowY: "auto", padding: "40px 56px 80px" }}>
        <div style={{ marginBottom: 32 }}>
          <StepIndicator step="review" />
        </div>

        <div style={{ marginBottom: 32 }}>
          <Eyebrow style={{ marginBottom: 10 }}>
            Tailoring · Vercel · Senior PM, Platform
          </Eyebrow>
          <h1
            style={{
              fontFamily: "Newsreader, serif",
              fontSize: 38,
              fontWeight: 400,
              letterSpacing: "-0.025em",
              color: "var(--ink)",
              margin: 0,
              lineHeight: 1.1,
            }}
          >
            {total} suggestions.{" "}
            <em style={{ color: "var(--accent)", fontStyle: "italic" }}>
              Approve each one.
            </em>
          </h1>
        </div>

        {/* Progress + bulk */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "14px 16px",
            background: "var(--paper)",
            border: "1px solid var(--border)",
            borderRadius: 8,
            marginBottom: 28,
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div
                style={{
                  width: 120,
                  height: 4,
                  background: "var(--border)",
                  borderRadius: 999,
                  overflow: "hidden",
                }}
              >
                <div
                  style={{
                    width: `${progress}%`,
                    height: "100%",
                    background: "var(--accent)",
                    transition: "width 200ms",
                  }}
                />
              </div>
              <Eyebrow>
                {counts.accepted + counts.rejected} / {total} reviewed
              </Eyebrow>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <Pill tone="success">{counts.accepted} accepted</Pill>
              <Pill>{counts.rejected} skipped</Pill>
            </div>
          </div>
          <Button variant="quiet" onClick={acceptAll}>
            Accept all
          </Button>
        </div>

        {/* Cards */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {window.SUGGESTIONS.map((s, i) => (
            <SuggestionCard
              key={s.id}
              suggestion={s}
              index={i}
              decision={decisions[s.id]}
              active={activeId === s.id}
              onActivate={() => setActiveId(s.id)}
              onAccept={() => setDecision(s.id, "accepted")}
              onReject={() => setDecision(s.id, "rejected")}
            />
          ))}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 40 }}>
          <Button variant="ghost" onClick={onBack}>
            Back
          </Button>
          <Button
            variant="accent"
            icon={Icon.arrow}
            onClick={() => onContinue({ decisions })}
            disabled={counts.pending === total}
          >
            Continue to export
          </Button>
        </div>
      </div>

      {/* Right: resume preview */}
      <div
        style={{
          width: 460,
          flexShrink: 0,
          borderLeft: "1px solid var(--border)",
          background: "var(--paper-2)",
          overflowY: "auto",
        }}
      >
        <div
          style={{
            position: "sticky",
            top: 0,
            background: "var(--paper-2)",
            padding: "20px 28px 16px",
            borderBottom: "1px solid var(--border)",
            zIndex: 2,
          }}
        >
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Eyebrow>Live preview</Eyebrow>
            <Pill tone="accent">{counts.accepted} changes applied</Pill>
          </div>
        </div>
        <div style={{ padding: "32px 28px" }}>
          <ResumePreview decisions={decisions} compact resumeId={context && context.resumeId} />
        </div>
      </div>
    </div>
  );
}

function SuggestionCard({ suggestion, index, decision, active, onActivate, onAccept, onReject }) {
  const s = suggestion;
  const severityTone = { high: "accent", medium: "default", low: "default" }[s.severity];
  const kindLabel = { rewrite: "Rewrite", add: "Add", trim: "Trim", keep: "Keep" }[s.kind];

  const accepted = decision === "accepted";
  const rejected = decision === "rejected";
  const reviewed = accepted || rejected;

  return (
    <div
      onClick={onActivate}
      style={{
        background: "var(--paper)",
        border: `1px solid ${active ? "var(--ink)" : "var(--border)"}`,
        borderRadius: 10,
        padding: 24,
        cursor: "pointer",
        transition: "all 150ms",
        opacity: rejected ? 0.55 : 1,
        position: "relative",
        overflow: "hidden",
      }}
    >
      {/* Severity stripe */}
      <div
        style={{
          position: "absolute",
          left: 0,
          top: 0,
          bottom: 0,
          width: 3,
          background:
            s.severity === "high"
              ? "var(--accent)"
              : s.severity === "medium"
              ? "color-mix(in oklab, var(--accent) 50%, transparent)"
              : "var(--border)",
        }}
      />

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Eyebrow style={{ fontSize: 9 }}>№ {String(index + 1).padStart(2, "0")}</Eyebrow>
          <div
            style={{
              width: 3,
              height: 3,
              borderRadius: 999,
              background: "var(--border)",
            }}
          />
          <Eyebrow style={{ fontSize: 9, color: "var(--ink)" }}>{s.section}</Eyebrow>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Pill tone={severityTone}>{kindLabel}</Pill>
          <Pill>{s.severity}</Pill>
        </div>
      </div>

      {/* Reason */}
      <p
        style={{
          fontFamily: "Newsreader, serif",
          fontSize: 15,
          lineHeight: 1.55,
          color: "var(--ink)",
          margin: "0 0 18px",
          fontStyle: "italic",
        }}
      >
        &ldquo;{s.reason}&rdquo;
      </p>

      {/* Diff */}
      {s.kind !== "keep" && (
        <div
          style={{
            border: "1px solid var(--border)",
            borderRadius: 6,
            overflow: "hidden",
            marginBottom: 16,
          }}
        >
          <div
            style={{
              padding: "12px 16px",
              background: "color-mix(in oklab, #c44a3c 7%, transparent)",
              borderBottom: "1px solid var(--border)",
            }}
          >
            <Eyebrow style={{ marginBottom: 6, color: "color-mix(in oklab, #c44a3c 80%, black)" }}>
              Before
            </Eyebrow>
            <div
              style={{
                fontFamily: "Inter, sans-serif",
                fontSize: 13,
                lineHeight: 1.55,
                color: "var(--ink)",
                textDecoration: "line-through",
                textDecorationColor: "color-mix(in oklab, #c44a3c 60%, transparent)",
              }}
            >
              {s.before}
            </div>
          </div>
          <div
            style={{
              padding: "12px 16px",
              background: "color-mix(in oklab, var(--accent) 7%, transparent)",
            }}
          >
            <Eyebrow style={{ marginBottom: 6, color: "var(--accent)" }}>After</Eyebrow>
            <div
              style={{
                fontFamily: "Inter, sans-serif",
                fontSize: 13,
                lineHeight: 1.55,
                color: "var(--ink)",
              }}
            >
              {highlightKeywords(s.after, s.keywords)}
            </div>
          </div>
        </div>
      )}

      {/* Keywords */}
      {Array.isArray(s.keywords) && s.keywords.length > 0 && (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 18 }}>
          {s.keywords.map((k) => (
            <span
              key={k}
              style={{
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 10,
                padding: "3px 8px",
                background: "color-mix(in oklab, var(--accent) 10%, transparent)",
                color: "var(--accent)",
                borderRadius: 3,
                letterSpacing: "0.02em",
              }}
            >
              +{k}
            </span>
          ))}
        </div>
      )}

      {/* Actions */}
      <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
        {!reviewed && (
          <>
            <Button
              variant="primary"
              icon={Icon.check}
              onClick={(e) => {
                e.stopPropagation();
                onAccept();
              }}
            >
              Accept
            </Button>
            <Button
              variant="ghost"
              icon={Icon.x}
              onClick={(e) => {
                e.stopPropagation();
                onReject();
              }}
            >
              Skip
            </Button>
            <button
              style={{
                fontFamily: "Inter, sans-serif",
                fontSize: 12,
                color: "var(--muted)",
                background: "none",
                border: "none",
                cursor: "pointer",
                marginLeft: 4,
              }}
            >
              Edit&hellip;
            </button>
          </>
        )}
        {accepted && (
          <>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "6px 12px",
                background: "color-mix(in oklab, #4a7a4a 12%, transparent)",
                color: "#3d6b3d",
                borderRadius: 5,
                fontFamily: "Inter, sans-serif",
                fontSize: 12,
                fontWeight: 500,
              }}
            >
              {Icon.check} Accepted
            </div>
            <Button
              variant="quiet"
              onClick={(e) => {
                e.stopPropagation();
                onReject();
              }}
            >
              Undo
            </Button>
          </>
        )}
        {rejected && (
          <>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "6px 12px",
                background: "var(--paper-2)",
                color: "var(--muted)",
                borderRadius: 5,
                fontFamily: "Inter, sans-serif",
                fontSize: 12,
              }}
            >
              Skipped
            </div>
            <Button
              variant="quiet"
              onClick={(e) => {
                e.stopPropagation();
                onAccept();
              }}
            >
              Reconsider
            </Button>
          </>
        )}
      </div>
    </div>
  );
}

function highlightKeywords(text, keywords) {
  if (!keywords || !keywords.length) return text;
  // Split by keywords (case insensitive)
  const re = new RegExp(`(${keywords.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "gi");
  const parts = text.split(re);
  return parts.map((p, i) => {
    const match = keywords.some((k) => k.toLowerCase() === p.toLowerCase());
    return match ? (
      <strong key={i} style={{ color: "var(--accent)", fontWeight: 600 }}>
        {p}
      </strong>
    ) : (
      <React.Fragment key={i}>{p}</React.Fragment>
    );
  });
}

Object.assign(window, { ReviewScreen });
