// Inbox — Auto-Classified · soft neumorphism · shadow-safe scroll
const Inbox = ({ width = 1440, height = 900 }) => {
  const [selectedCats, setSelectedCats] = React.useState(() => new Set());
  const [selected, setSelected] = React.useState(0);

  const tabs = [
    { k: "Auto-Reply OK",  n: 23, color: "#34D399" },
    { k: "AI Drafts",      n: 18, color: "var(--midnight)" },
    { k: "Human Sends",    n: 6,  color: "#F4811F" },
    { k: "Human Required", n: 2,  color: "#E63946" },
  ];

  const allEmails = [
    { from: "Marco Castelli",   sub: "Re: Q2 portfolio update",       prev: "Thanks Sarah — appreciate the heads-up. I'll review and circle back on Friday.",         tag: "URGENT",       cat: "Human Required", tone: "high", time: "14:42", initials: "MC", avatarColor: "linear-gradient(135deg,#E63946,#F4811F)" },
    { from: "Compliance Desk",  sub: "Quarterly review · approval",   prev: "We've reviewed last week's outbound. Three items need your sign-off before Friday EOD.", tag: "ACTION",       cat: "AI Drafts",      tone: "mid",  time: "13:08", initials: "CD", avatarColor: "linear-gradient(135deg,#0A1628,#3A4556)" },
    { from: "Northwind Capital",sub: "RFP — please confirm receipt",  prev: "Confirming we received your RFP response. Internal review will conclude by 2 May.",       tag: "AUTO-REPLY",   cat: "Auto-Reply OK",  tone: "low",  time: "12:55", initials: "NC", avatarColor: "linear-gradient(135deg,#3A4556,#0A1628)" },
    { from: "Lena Park",        sub: "Coffee next week?",             prev: "Open Tues or Wed afternoon — happy to come to your office.",                            tag: "PERSONAL",     cat: "Human Sends",    tone: "low",  time: "11:30", initials: "LP", avatarColor: "linear-gradient(135deg,#F4811F,#F4C430)" },
    { from: "FCA Updates",      sub: "Consultation Paper CP25/04",    prev: "The FCA has published a new consultation paper relevant to your firm's permissions.",   tag: "MISSING INFO", cat: "AI Drafts",      tone: "mid",  time: "10:14", initials: "FC", avatarColor: "linear-gradient(135deg,#B91C2C,#E63946)" },
    { from: "James Holloway",   sub: "Complaint — fee disclosure",    prev: "I want to formally raise a concern about the fees that were applied to my account in…", tag: "COMPLAINT",    cat: "Human Required", tone: "high", time: "09:02", initials: "JH", avatarColor: "linear-gradient(135deg,#E63946,#B91C2C)" },
    { from: "Ops · Settlement", sub: "Trade confirmations · 30 Apr",  prev: "Daily settlement confirmations attached. No exceptions noted.",                          tag: "AUTO-REPLY",   cat: "Auto-Reply OK",  tone: "low",  time: "08:45", initials: "OP", avatarColor: "linear-gradient(135deg,#3A4556,#0A1628)" },
  ];

  const emails = selectedCats.size === 0
    ? allEmails
    : allEmails.filter(e => selectedCats.has(e.cat));

  const toggleCat = (k) => {
    setSelectedCats(prev => {
      const next = new Set(prev);
      if (next.has(k)) next.delete(k);
      else next.add(k);
      return next;
    });
    setSelected(0);
  };
  const clearCats = () => { setSelectedCats(new Set()); setSelected(0); };

  // Clamp selected to visible range
  const safeSelected = Math.min(selected, Math.max(0, emails.length - 1));

  const tagBg = t => t === "high" ? "rgba(230,57,70,0.10)" : t === "mid" ? "rgba(244,129,31,0.10)" : "rgba(52,211,153,0.10)";
  const tagFg = t => t === "high" ? "#B91C2C" : t === "mid" ? "#9A4F12" : "#0E7C5A";

  return (
    <div style={{ width, height, background: "var(--white-pure)", display: "flex", flexDirection: "column", position: "relative", overflow: "hidden" }}>
      <TopBar active="Inbox"/>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(0, 1fr) 460px", gap: 24, padding: 32, minHeight: 0, overflow: "hidden" }}>
        <div style={{ display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
          {/* Tabs (neu) */}
          <div style={{ display: "flex", gap: 12, marginBottom: 20, flexWrap: "wrap", alignItems: "center" }}>
            {tabs.map(t => {
              const on = selectedCats.has(t.k);
              return (
                <div key={t.k} className={`neu-tab ${on ? "on" : ""}`} onClick={() => toggleCat(t.k)}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: t.color }}/>
                  <span>{t.k}</span>
                  <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>{t.n}</span>
                </div>
              );
            })}
            <div className="neu-chip" style={{ color: "var(--midnight-soft)" }}>+ Custom category</div>
            {selectedCats.size > 0 && (
              <div className="neu-chip" onClick={clearCats} style={{
                color: "var(--red-deep)", display: "inline-flex", alignItems: "center", gap: 6,
              }}>
                <span style={{ fontSize: 14, lineHeight: 1 }}>×</span>
                <span>Clear · {selectedCats.size}</span>
              </div>
            )}
          </div>

          {/* Emails — extra side padding so the pillow shadows breathe */}
          <div className="scroll"
            style={{
              display: "flex", flexDirection: "column", gap: 14,
              overflow: "auto",
              padding: "8px 24px 24px 24px",
              margin: "-8px -24px -24px -24px",
              minHeight: 0, flex: 1,
            }}>
            {emails.length === 0 && (
              <div className="pillow" style={{
                padding: 32, textAlign: "center",
                display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
              }}>
                <div className="micro">Empty view</div>
                <div className="body" style={{ color: "var(--midnight-soft)", maxWidth: 320 }}>
                  No emails match the selected categories.
                </div>
                <div className="neu-chip" onClick={clearCats} style={{ marginTop: 6 }}>Clear filter →</div>
              </div>
            )}
            {emails.map((e, i) => {
              const on = i === safeSelected;
              return (
                <div key={`${e.from}-${i}`} className="pillow" onClick={() => setSelected(i)} style={{
                  padding: 18, display: "flex", alignItems: "center", gap: 16, cursor: "pointer",
                  borderRadius: 16, transition: "transform 200ms var(--ease-soft), box-shadow 200ms var(--ease-soft)",
                  transform: on ? "translateY(-2px)" : "none",
                  boxShadow: on ? "var(--pillow-shadow-hover)" : "var(--pillow-shadow)",
                  outline: on ? "1px solid rgba(10,22,40,0.06)" : "none",
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 999, flexShrink: 0,
                    background: e.avatarColor, color: "#fff",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontWeight: 600, fontSize: 12, letterSpacing: "0.02em",
                  }}>{e.initials}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 8, minWidth: 0 }}>
                      <span style={{ fontSize: 14, fontWeight: 600, color: "var(--midnight)" }}>{e.from}</span>
                      <span style={{ fontSize: 14, color: "var(--midnight-soft)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>· {e.sub}</span>
                    </div>
                    <div style={{ fontSize: 13, color: "var(--midnight-soft)", marginTop: 4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.prev}</div>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8, flexShrink: 0 }}>
                    <span style={{
                      fontSize: 10, fontWeight: 700, letterSpacing: "0.08em",
                      padding: "4px 8px", borderRadius: 999,
                      background: tagBg(e.tone), color: tagFg(e.tone),
                    }}>{e.tag}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>{e.time}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Right panel */}
        <RightPanel
          email={emails[safeSelected]}
          empty={emails.length === 0}
          clearCats={clearCats}
        />
      </div>

      {/* Daily summary widget */}
      <div className="pillow" style={{
        position: "absolute", right: 32, bottom: 32, padding: 18, borderRadius: 16,
        display: "flex", alignItems: "center", gap: 14, maxWidth: 480,
      }}>
        <AngelRobot size={56} facing="right"/>
        <div style={{ flex: 1 }}>
          <div className="micro">Today · so far</div>
          <div style={{ fontSize: 13, color: "var(--midnight)", marginTop: 4, lineHeight: 1.45 }}>
            RedGone handled <b>47 emails</b>: 23 auto-replied, 18 drafted, 6 in your queue. <b>1 reclassified</b>.
          </div>
        </div>
        <button className="neu-btn neu-btn-sm">Review</button>
      </div>
    </div>
  );
};

// ──────────────────────────────────────────────────────────────────────
// Right panel — preview, sub-tabs, action buttons.
// Behavior:
//  · Auto-Reply OK   → no actions (status only)
//  · AI Drafts       → Email | AI reply tabs · Approve email + Manual reply
//  · Human Sends     → Email | AI reply tabs · Approve email + Manual reply
//  · Human Required  → Reply button (red) — opens /compose
// ──────────────────────────────────────────────────────────────────────
const RightPanel = ({ email, empty, clearCats }) => {
  const [subTab, setSubTab] = React.useState("email"); // email | ai-reply

  // Reset sub-tab when the selected email changes
  React.useEffect(() => { setSubTab("email"); }, [email && (email.from + email.sub)]);

  if (empty || !email) {
    return (
      <div className="pillow float-in" style={{
        padding: 28, display: "flex", flexDirection: "column", minHeight: 0,
      }}>
        <div className="micro">Selected</div>
        <div className="h3" style={{ marginTop: 8 }}>Nothing to preview</div>
        <div className="small" style={{ color: "var(--midnight-soft)", marginTop: 4 }}>
          Pick an email from the list, or clear your filters.
        </div>
        {clearCats && (
          <div className="neu-chip" onClick={clearCats} style={{ marginTop: 16, alignSelf: "flex-start" }}>
            Clear filter →
          </div>
        )}
      </div>
    );
  }

  const cat = email.cat;
  const showAITab = cat === "AI Drafts" || cat === "Human Sends";
  const isAIReplyView = showAITab && subTab === "ai-reply";

  const aiReply = `Hi ${email.from.split(" ")[0]},

Thanks for reaching out about "${email.sub}".${
    cat === "Human Sends"
      ? "\n\nI'll review and respond personally within the next business day."
      : "\n\nThis has been routed for review and we'll follow up shortly with the requested information."
  }

Best,
Sarah`;

  return (
    <div className="pillow float-in" style={{
      padding: 28, display: "flex", flexDirection: "column", minHeight: 0,
    }}>
      {/* Header row */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="micro">Selected · {cat}</div>
          <div className="h3" style={{ marginTop: 8 }}>{email.sub}</div>
          <div className="small" style={{ color: "var(--midnight-soft)", marginTop: 4 }}>
            From {email.from} · {email.time}
          </div>
        </div>

        {cat === "Human Required" && (
          <a href="/compose" data-link className="neu-btn-redglow neu-btn-redglow-sm" style={{ flexShrink: 0 }}>
            <span>Reply</span>
            <span style={{ opacity: 0.85 }}>→</span>
          </a>
        )}
        {isAIReplyView && (
          <button className="neu-btn-redglow neu-btn-redglow-sm" style={{ flexShrink: 0 }}>
            <span>Approve email</span>
            <span style={{ opacity: 0.85 }}>✓</span>
          </button>
        )}
      </div>

      {/* Sub-tabs (only for AI Drafts / Human Sends) */}
      {showAITab && (
        <div style={{ marginTop: 14 }}>
          <div className="rg-tabs">
            <button
              className={`rg-tab ${subTab === "email" ? "on" : ""}`}
              onClick={() => setSubTab("email")}
              style={{ padding: "7px 14px", fontSize: 12 }}
            >Email</button>
            <button
              className={`rg-tab ${subTab === "ai-reply" ? "on" : ""}`}
              onClick={() => setSubTab("ai-reply")}
              style={{ padding: "7px 14px", fontSize: 12 }}
            >AI reply</button>
          </div>
        </div>
      )}

      {/* Body */}
      <div className="neu-inset-tray scroll" style={{
        marginTop: 14, padding: 18, flex: 1, overflow: "auto", minHeight: 0,
        fontSize: 14, lineHeight: 1.6, color: "var(--midnight)",
        whiteSpace: isAIReplyView ? "pre-wrap" : "normal",
      }}>
        {isAIReplyView
          ? aiReply
          : (
            <>
              {email.prev} The compliance team has surfaced this thread under "{cat}" because
              it requires sign-off before action can be taken. RedGone has prepared a draft response
              for your review.
            </>
          )
        }
      </div>

      {/* Footer actions for AI reply view */}
      {isAIReplyView && (
        <div style={{ display: "flex", gap: 10, marginTop: 14, justifyContent: "flex-end" }}>
          <a href="/compose" data-link className="neu-btn neu-btn-sm" style={{
            textDecoration: "none", color: "var(--midnight)",
            display: "inline-flex", alignItems: "center", gap: 6,
          }}>
            <span>Manual reply</span>
            <span style={{ opacity: 0.6 }}>→</span>
          </a>
        </div>
      )}

      {/* Auto-Reply status */}
      {cat === "Auto-Reply OK" && (
        <div style={{
          marginTop: 14, padding: "10px 14px", borderRadius: 12,
          background: "rgba(52, 211, 153, 0.10)",
          border: "1px solid rgba(52, 211, 153, 0.20)",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "#34D399" }}/>
          <span style={{ fontSize: 13, color: "var(--midnight)" }}>
            Auto-reply sent at {email.time}. Routed to your Ops folder.
          </span>
        </div>
      )}

      {/* Classification */}
      <div style={{
        marginTop: 14, padding: 16, borderRadius: 14,
        background: "var(--white-pure)", boxShadow: "var(--neu-out-sm)",
      }}>
        <div className="micro" style={{ color: "var(--midnight-soft)" }}>RedGone classification</div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--midnight)" }}/>
          <span style={{ fontSize: 14, fontWeight: 600 }}>{cat}</span>
          <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)", marginLeft: "auto" }}>
            CONF · 0.82
          </span>
        </div>
        <div className="small" style={{ color: "var(--midnight-soft)", marginTop: 8 }}>
          Classified as {cat} based on your spec rules.
        </div>
        <div style={{ marginTop: 12, display: "flex", gap: 10 }}>
          <button className="neu-btn neu-btn-primary neu-btn-sm">Reclassify</button>
          <input className="neu-input" placeholder="Tell RedGone why" style={{ flex: 1 }}/>
        </div>
      </div>
    </div>
  );
};

window.Inbox = Inbox;
