/* ============================================================
   EBTR — Author Portal: dashboard + submission detail
   ============================================================ */

function PDashboard({ onOpen, onNew, me }) {
  const D = window.EBTR_AUTHOR;
  const meReal = me || D.me;
  const [filter, setFilter] = React.useState("all");
  const LIVE = !!window.EBTR_AUTH;
  const [live, setLive] = React.useState(null);
  React.useEffect(() => {
    if (!LIVE || !meReal.email || !window.EBTR_FETCH_MY_SUBMISSIONS) return;
    window.EBTR_FETCH_MY_SUBMISSIONS(meReal.email).then(function (arts) {
      setLive((arts || []).map(function (a) {
        var em = a.editorMeta || {};
        var statusMap = { new: "submitted", peer: "peer", revisions: "revisions", ready: "accepted", published: "published" };
        return {
          id: a.id, title: a.title, dek: a.dek || "", category: a.category, format: a.category,
          status: statusMap[a.status] || a.status || "submitted", accent: a.cover || "blue",
          updated: a.date || "", comments: em.comments || [], reviews: [], scorecard: em.score || {},
          formDraft: a.formDraft || null,
        };
      }));
    }).catch(function () { setLive([]); });
  }, [LIVE, meReal.email]);
  React.useEffect(() => { if (live) window.EBTR_LIVE_SUBS = live; }, [live]);

  // Live mode: only the author's real submissions (empty until they submit). Demo: sample data.
  const source = LIVE ? (live || []) : D.submissions;
  const counts = {
    all: source.length,
    progress: source.filter((s) => !["published", "declined"].includes(s.status)).length,
    published: source.filter((s) => s.status === "published").length,
  };
  const shown = source.filter((s) =>
    filter === "all" ? true : filter === "published" ? s.status === "published" : !["published", "declined"].includes(s.status)
  );
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—";

  return (
    <main style={{ maxWidth: 1600, margin: "0 auto", padding: "44px var(--space-7) 80px" }}>
      <PEyebrow color="orange">Author dashboard</PEyebrow>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 18, marginTop: 12 }}>
        <h1 style={{ fontFamily: "var(--ebtr-display)", fontSize: "clamp(30px, 3.4vw, 44px)", letterSpacing: "0.015em", textTransform: "uppercase", color: "var(--white)", margin: 0 }}>Welcome back, {(meReal.name || "").split(" ")[0] || "there"}</h1>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {(meReal.badges || []).map((bd) => <PBadge key={bd.label} variant={bd.variant} shape="square" size="md">{bd.label}</PBadge>)}
        </div>
      </div>

      {/* stat row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, margin: "32px 0 40px" }} className="pf-stats">
        {[["Submissions", counts.all, "blue"], ["In review", counts.progress, "purple"], ["Published", counts.published, "orange"]].map(([l, v, c]) => (
          <div key={l} style={{ background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderLeft: `3px solid ${PACCENT[c]}`, padding: "22px 24px" }}>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 40, lineHeight: 1, color: "var(--white)" }}>{String(v).padStart(2, "0")}</div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 10 }}>{l}</div>
          </div>
        ))}
      </div>

      {/* all submissions — counts already shown in the KPI boxes above */}
      <div style={{ borderBottom: "1px solid var(--border-hairline)", marginBottom: 6 }}></div>

      {/* list */}
      <div>
        {shown.map((s) => (
          <button key={s.id} onClick={() => onOpen(s.id)} className="pf-row pf-listrow" style={{ display: "grid", gridTemplateColumns: "52px 1fr auto", gap: 26, alignItems: "center", width: "100%", textAlign: "left", background: "none", border: "none", borderBottom: "1px solid var(--border-hairline)", padding: "22px 8px 22px 0", cursor: "pointer" }}>
            <PThumb accent={s.accent} size={52} />
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8, flexWrap: "wrap" }}>
                <PStatus status={s.status} size="sm" />
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{s.category}</span>
                {s.status === "revisions" && s.comments && <span style={{ fontFamily: "var(--font-ui)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ebt-orange)" }}>● {s.comments.length} comments</span>}
              </div>
              <div className="pf-row-t" style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 18, lineHeight: 1.25, color: "var(--text-primary)", transition: "color var(--dur-base)" }}>{s.title}</div>
            </div>
            <div className="pf-updated" style={{ textAlign: "right", whiteSpace: "nowrap" }}>
              <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.05em", color: "var(--text-muted)" }}>Updated</div>
              <div style={{ fontFamily: "var(--font-ui)", fontSize: 12, color: "var(--text-secondary)", marginTop: 4 }}>{fmtDate(s.updated)}</div>
            </div>
          </button>
        ))}
      </div>
    </main>
  );
}

/* ---- Submission detail ---- */
function PDetail({ id, onBack, onResubmit }) {
  const D = window.EBTR_AUTHOR;
  const s = (window.EBTR_LIVE_SUBS || []).find((x) => x.id === id) || D.submissions.find((x) => x.id === id);
  if (!s) return null;
  const st = D.statuses[s.status] || D.statuses.submitted || { step: 1 };
  const fmtDate = (d) => d ? new Date(d).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—";
  const verdictColor = { passed: "var(--blue-400)", accepted: "var(--blue-400)", revisions: "var(--ebt-orange)", active: "var(--ebt-purple)", declined: "var(--text-muted)" };
  const reviews = s.reviews || [];
  const scorecard = s.scorecard || {};

  return (
    <main style={{ maxWidth: 1600, margin: "0 auto", padding: "40px var(--space-7) 80px" }}>
      <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 9, background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--text-secondary)", marginBottom: 28 }}>← Dashboard</button>

      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16, flexWrap: "wrap" }}>
        <PStatus status={s.status} />
        <span style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{s.format}</span>
      </div>
      <h1 style={{ fontFamily: "var(--ebtr-display)", fontSize: "clamp(26px, 3vw, 40px)", lineHeight: 1.12, letterSpacing: "0.015em", textTransform: "uppercase", color: "var(--white)", margin: 0, textWrap: "balance" }}>{s.title}</h1>
      <p style={{ fontFamily: "var(--font-body)", fontSize: 18, lineHeight: 1.5, color: "var(--text-secondary)", margin: "18px 0 28px" }}>{s.dek}</p>

      {/* pipeline */}
      <div style={{ display: "flex", alignItems: "center", gap: 0, margin: "0 0 36px", flexWrap: "wrap" }}>
        {D.pipeline.map((p, i) => {
          const done = i < st.step; const active = i === st.step;
          const isRev = s.status === "revisions" && i === 3;
          return (
            <React.Fragment key={p}>
              <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                <span style={{ width: 22, height: 22, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "50%", fontFamily: "var(--font-ui)", fontSize: 10, background: isRev ? "var(--ebt-orange)" : done ? "var(--ebt-blue)" : active ? "var(--ebt-purple)" : "var(--neutral-800)", color: done || active || isRev ? "var(--white)" : "var(--text-muted)", border: done || active || isRev ? "none" : "1px solid var(--border-strong)" }}>{done ? "✓" : i + 1}</span>
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.06em", textTransform: "uppercase", color: active || isRev ? "var(--white)" : done ? "var(--text-secondary)" : "var(--text-muted)" }}>{p}</span>
              </div>
              {i < D.pipeline.length - 1 && <div style={{ width: 28, height: 1, background: i < st.step ? "var(--ebt-blue)" : "var(--border-hairline)", margin: "0 12px" }} />}
            </React.Fragment>
          );
        })}
      </div>

      {/* reviewer feedback (why pushed back) */}
      {s.comments && s.comments.length > 0 && (
        <div style={{ background: "rgba(255,140,3,0.07)", border: "1px solid rgba(255,140,3,0.4)", padding: "24px 26px", marginBottom: 30 }}>
          <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ebt-orange)", marginBottom: 18 }}>Why this came back — reviewer feedback</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            {s.comments.map((c, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "38px 1fr", gap: 14 }}>
                <div style={{ width: 38, height: 38, borderRadius: "50%", background: "var(--neutral-800)", border: "1px solid var(--border-strong)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-ui)", fontSize: 11, color: "var(--white)" }}>{c.from.split(" ").map((x) => x[0]).join("").replace(".", "")}</div>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6, flexWrap: "wrap" }}>
                    <span style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 14, color: "var(--white)" }}>{c.from}</span>
                    <span style={{ fontFamily: "var(--font-ui)", fontSize: 10, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--text-muted)" }}>{c.role} · {fmtDate(c.date)}</span>
                  </div>
                  <p style={{ fontFamily: "var(--font-body)", fontSize: 15, lineHeight: 1.6, color: "var(--neutral-100)", margin: 0 }}>{c.text}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* review timeline */}
      {reviews.length > 0 && (
        <div style={{ marginBottom: 32 }}>
          <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 16 }}>Review trail</div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {reviews.map((r, i) => (
              <div key={i} className="pf-trail-row" style={{ display: "grid", gridTemplateColumns: "140px 1fr auto", gap: 16, padding: "16px 0", borderBottom: "1px solid var(--border-hairline)", alignItems: "baseline" }}>
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--white)" }}>{r.stage}</span>
                <div>
                  <span style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-secondary)" }}>{r.note}</span>
                  <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, color: "var(--text-muted)", marginTop: 5 }}>{r.reviewer} · {r.role}{r.date ? " · " + fmtDate(r.date) : ""}</div>
                </div>
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: verdictColor[r.verdict] || "var(--text-muted)" }}>{r.verdict}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* scorecard */}
      <div style={{ border: "1px solid var(--border-hairline)", padding: "22px 26px", marginBottom: 30 }}>
        <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 16 }}>Quality scorecard</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="pf-score">
          {D.litmus.map((l) => {
            const ok = scorecard[l.key];
            return (
              <div key={l.key} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 10, alignItems: "start" }}>
                <span style={{ color: ok ? "var(--blue-400)" : "var(--ebt-orange)", fontFamily: "var(--font-ui)", fontSize: 14 }}>{ok ? "✓" : "✕"}</span>
                <span style={{ fontFamily: "var(--font-body)", fontSize: 14, lineHeight: 1.4, color: ok ? "var(--text-secondary)" : "var(--neutral-100)" }}>{l.label}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* actions */}
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
        {s.status === "revisions" && <PBtn variant="primary" size="lg" icon="none" onClick={() => onResubmit(s)}>Revise & resubmit</PBtn>}
        {s.status === "draft" && <PBtn variant="primary" size="lg" icon="none" onClick={() => onResubmit(s)}>Continue editing</PBtn>}
        {s.status === "published" && <PBtn variant="secondary" size="lg" icon="none" onClick={() => window.open("EBTR Review.html", "_blank")}>View live in the Review</PBtn>}
        {["submitted", "screening", "peer", "accepted"].includes(s.status) && <span style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-muted)", alignSelf: "center" }}>In the editors' hands — we'll email you when the status changes.</span>}
      </div>
    </main>
  );
}

Object.assign(window, { PDashboard, PDetail });
