/* APPROVALS QUEUE — keyboard-first triage stack. window.SCREENS.Approvals */
(function () {
  const { useState, useEffect, useRef } = React;
  const I = window.ICONS;
  const { Avatar, LoanMeta, ChannelChip, Pill, Btn } = window.UI;
  const { leadById } = window.DATA;

  // Alternate phrasings for "Redraft" so regeneration feels real.
  const ALT = {
    d1: "Love that, Maria. To pull your exact numbers I'll need two recent pay stubs and a bank statement. Easiest is a secure upload link — want me to text it over?",
    d2: "Hi Anita — Ray with Meridian Home Lending, thanks for the inquiry on the Cupertino listing. I can help you nail down a comfortable budget. Free for a quick call today?",
    d3: "Hi Greg,\n\nGlad your agent's ready to move. I'd rather not put estimates in writing — let's do a quick call so I can tailor everything to your scenario.\n\nTomorrow 11:00 or 2:30? I'll send a hold.\n\nBest,\nRay",
    d4: "Hi Emeka — Ray with Meridian Home Lending. Congrats on starting the Inglewood search. Want me to get a pre-approval ready so you can make strong offers?",
    d5: "Absolutely, Daniel — a HELOC lets you draw only what the remodel needs. I can show you what you'd have access to. Got a few minutes this afternoon?",
    d6: "Congrats, Luis — that's the best kind of text. You're in great shape. I'll send the closing disclosure to review and we'll verify wiring on a recorded call. Nearly there.",
    d7: "Hi Sherry,\n\nPerfect — that's the document underwriting was waiting on. Sending it up today and I'll let you know the second we're clear to close.\n\nBest,\nRay",
    d8: "Hi Carmen — Ray with Meridian Home Lending, thanks for reaching out on Long Beach financing. I can get you pre-approved so your numbers are locked in. Best time to talk?",
  };

  function Quote({ children }) {
    return (
      <div style={{ borderLeft: "2px solid var(--gold-line)", paddingLeft: 14, margin: "2px 0 4px" }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>▌ Client wrote</div>
        <div style={{ fontSize: 14, color: "var(--ink-soft)", fontStyle: "italic", lineHeight: 1.5 }}>"{children}"</div>
      </div>
    );
  }

  function DraftBody({ d, draftText }) {
    return (
      <div>
        {d.channel === "email" && (
          <div style={{ marginBottom: 10, paddingBottom: 10, borderBottom: "1px solid var(--line)" }}>
            <span className="eyebrow">Subject</span>
            <div style={{ fontSize: 15, fontWeight: 500, marginTop: 4 }}>{d.subject}</div>
          </div>
        )}
        <div className="eyebrow" style={{ marginBottom: 7, color: "var(--green-lift)" }}>◆ AI draft · in your voice</div>
        <div style={{ fontSize: 15.5, lineHeight: 1.6, whiteSpace: "pre-wrap" }}>{draftText}</div>
      </div>
    );
  }

  function Card({ d, draftText, focused, style, className }) {
    const lead = leadById[d.leadId];
    return (
      <div className={`panel ${className || ""}`} style={{ padding: 0, ...style }}>
        {/* head */}
        <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
          <Avatar init={lead.init} size={40} gold />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ fontSize: 16, fontWeight: 600 }}>{lead.name}</span>
              <ChannelChip channel={d.channel} />
              {d.priority === "high" && <Pill kind="reject">Hot</Pill>}
            </div>
            <LoanMeta lead={lead} />
          </div>
          <div style={{ textAlign: "right" }}>
            <Pill kind={d.days >= 7 ? "reject" : d.days === 0 ? "sent" : "plain"}>
              {d.days === 0 ? "Today" : `${d.days}d since contact`}
            </Pill>
            <div className="eyebrow" style={{ marginTop: 8 }}>{d.reason}</div>
          </div>
        </div>
        {/* body */}
        <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 16 }}>
          {d.inbound && <Quote>{d.inbound}</Quote>}
          <DraftBody d={d} draftText={draftText} />
        </div>
      </div>
    );
  }

  function Approvals({ queue, active, onApprove, onReject, onRedraft, sessionApproved }) {
    const [leaving, setLeaving] = useState(null);      // {d, dir, text}
    const [editing, setEditing] = useState(false);
    const [editText, setEditText] = useState("");
    const [drafts, setDrafts] = useState({});           // id -> overridden text
    const [regen, setRegen] = useState(false);
    const taRef = useRef(null);

    const top = queue[0];
    const draftText = top ? (drafts[top.id] ?? top.draft) : "";

    function fly(dir, after) {
      if (!top) return;
      setLeaving({ d: top, dir, text: draftText });
      setTimeout(() => { setLeaving(null); after && after(); }, 360);
    }
    function doApprove() { if (!top || editing) return; const t = draftText; const id = top.id; fly("right", () => onApprove(id, t)); }
    function doReject()  { if (!top || editing) return; const id = top.id; fly("left", () => onReject(id)); }
    function doRedraft() {
      if (!top || editing || regen) return;
      setRegen(true);
      setTimeout(() => {
        setDrafts(p => ({ ...p, [top.id]: ALT[top.id] || (top.draft + " (revised)") }));
        setRegen(false);
        onRedraft(top.id);
      }, 850);
    }
    function startEdit() { if (!top) return; setEditText(draftText); setEditing(true); setTimeout(() => taRef.current && taRef.current.focus(), 30); }
    function saveEdit(approve) {
      setDrafts(p => ({ ...p, [top.id]: editText }));
      setEditing(false);
      if (approve) { const id = top.id, t = editText; fly("right", () => onApprove(id, t)); }
    }

    // keyboard
    useEffect(() => {
      if (!active) return;
      function onKey(e) {
        if (editing) { if (e.key === "Escape") setEditing(false); return; }
        if (!top) return;
        const k = e.key.toLowerCase();
        if (k === "a") { e.preventDefault(); doApprove(); }
        else if (k === "r") { e.preventDefault(); doReject(); }
        else if (k === "e") { e.preventDefault(); startEdit(); }
        else if (k === "d") { e.preventDefault(); doRedraft(); }
      }
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [active, top, editing, draftText, regen]);

    const total = queue.length;

    return (
      <div className="page" style={{ maxWidth: 920, margin: "0 auto" }}>
        {/* progress / legend strip */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20, flexWrap: "wrap", gap: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <span className="display" style={{ fontSize: 40, color: "var(--green-lift)" }}>{String(total).padStart(2, "0")}</span>
            <div>
              <div className="eyebrow">Awaiting your decision</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-faint)", marginTop: 3 }}>
                {sessionApproved} approved this session
              </div>
            </div>
          </div>
          <div className="meta-row" style={{ gap: 10 }}>
            {[["A", "Approve", "sent"], ["D", "Redraft", "gold"], ["E", "Edit", "plain"], ["R", "Reject", "reject"]].map(([k, l, c]) => (
              <div key={k} className="m" style={{ gap: 7 }}>
                <span className="kbd">{k}</span>
                <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-soft)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{l}</span>
              </div>
            ))}
          </div>
        </div>

        {total === 0 ? (
          <div className="panel empty">
            <div className="empty-mark"><I.checks width={26} height={26} /></div>
            <div className="display" style={{ fontSize: 38 }}>Queue clear</div>
            <div style={{ color: "var(--ink-soft)", maxWidth: 340 }}>
              Nothing waiting on you. The assistant is watching the CRM and will queue the next draft the moment a lead moves.
            </div>
            <div className="meta-row mono" style={{ fontSize: 11, color: "var(--ink-faint)", marginTop: 4, justifyContent: "center" }}>
              <span className="m"><span className="live-dot"></span> Listening</span>
              <i className="dotsep"></i>
              <span>{sessionApproved} approved today</span>
            </div>
          </div>
        ) : (
          <div style={{ position: "relative" }}>
            {/* peek stack behind */}
            {queue.slice(1, 3).map((d, i) => (
              <Card key={d.id} d={d} draftText={drafts[d.id] ?? d.draft} className="peek"
                style={{ position: "absolute", top: -(i + 1) * 10, left: (i + 1) * 10, right: (i + 1) * 10,
                  opacity: 0.5 - i * 0.22, zIndex: 1, pointerEvents: "none", filter: "saturate(0.7)" }} />
            ))}

            {/* leaving card */}
            {leaving && (
              <div style={{ position: "absolute", inset: 0, zIndex: 5,
                animation: `${leaving.dir === "right" ? "flyRight" : "flyLeft"} .36s var(--ease) forwards` }}>
                <Card d={leaving.d} draftText={leaving.text} />
                <div style={{ position: "absolute", top: 16, [leaving.dir === "right" ? "right" : "left"]: 18,
                  color: leaving.dir === "right" ? "var(--green-lift)" : "var(--st-reject)" }}>
                  {leaving.dir === "right" ? <I.check width={30} height={30} /> : <I.x width={30} height={30} />}
                </div>
              </div>
            )}

            {/* focused card */}
            <div style={{ position: "relative", zIndex: 3, opacity: leaving ? 0 : 1 }}>
              <div style={{ position: "relative" }}>
                <Card d={top} draftText={draftText} focused />
                {regen && (
                  <div style={{ position: "absolute", inset: 0, background: "color-mix(in srgb, var(--bg-0) 55%, transparent)",
                    display: "grid", placeItems: "center", zIndex: 6, backdropFilter: "blur(2px)" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--green-lift)" }}>
                      <I.refresh width={18} height={18} className="spin" />
                      <span className="mono" style={{ fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase" }}>Redrafting…</span>
                    </div>
                  </div>
                )}
              </div>

              {/* edit drawer */}
              {editing && (
                <div className="panel" style={{ marginTop: 12, borderColor: "var(--gold-line)" }}>
                  <div className="panel-head">
                    <span className="eyebrow" style={{ color: "var(--gold)" }}>✎ Edit before sending</span>
                    <span className="mono" style={{ fontSize: 10, color: "var(--ink-faint)" }}>{editText.length} chars</span>
                  </div>
                  <div className="panel-pad">
                    <textarea ref={taRef} className="field" rows={top.channel === "email" ? 8 : 4}
                      value={editText} onChange={e => setEditText(e.target.value)} />
                    <div style={{ display: "flex", gap: 10, marginTop: 12, justifyContent: "flex-end" }}>
                      <Btn sm onClick={() => setEditing(false)}>Cancel</Btn>
                      <Btn sm onClick={() => saveEdit(false)}>Save draft</Btn>
                      <Btn sm kind="primary" icon={I.check} onClick={() => saveEdit(true)}>Save &amp; approve</Btn>
                    </div>
                  </div>
                </div>
              )}

              {/* action bar */}
              {!editing && (
                <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 10, marginTop: 12 }}>
                  <Btn kind="primary" icon={I.check} k="A" onClick={doApprove}>Approve &amp; send</Btn>
                  <Btn kind="ghost-gold" icon={I.refresh} k="D" onClick={doRedraft}>Redraft</Btn>
                  <Btn icon={I.edit} k="E" onClick={startEdit}>Edit</Btn>
                  <Btn kind="danger" icon={I.x} k="R" onClick={doReject}>Reject</Btn>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.Approvals = Approvals;
})();
