// Workspace · Mail tab — Gmail-style email
function MailTab() {
  const { useState, useEffect, useRef } = React;
  const [mail, setMail] = useState(D.mail);
  const [folder, setFolder] = useState("inbox");
  const [q, setQ] = useState("");
  const [openId, setOpenId] = useState(null);
  const [compose, setCompose] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => { D.mail = mail; }, [mail]);

  // fill viewport like the chat card
  useEffect(() => {
    const fit = () => {
      const el = wrapRef.current;
      if (!el) return;
      const top = el.getBoundingClientRect().top;
      el.style.height = Math.max(420, window.innerHeight - top - 20) + "px";
    };
    fit();
    const t = setTimeout(fit, 80);
    window.addEventListener("resize", fit);
    window.addEventListener("verp-kpis", fit);
    return () => { clearTimeout(t); window.removeEventListener("resize", fit); window.removeEventListener("verp-kpis", fit); };
  }, []);

  const FOLDERS = [
    { id: "inbox", label: T("mail.inbox"), icon: "box" },
    { id: "starred", label: T("mail.starred"), icon: "spark" },
    { id: "sent", label: T("mail.sent"), icon: "send" },
    { id: "drafts", label: T("mail.drafts"), icon: "file" },
    { id: "trash", label: T("mail.trash"), icon: "x" }
  ];
  const inFolder = (m, f) => f === "starred" ? (m.starred && m.folder !== "trash") : m.folder === f;
  const count = (f) => f === "inbox" ? mail.filter((m) => m.folder === "inbox" && m.unread).length : mail.filter((m) => inFolder(m, f)).length;

  const list = mail.filter((m) => inFolder(m, folder))
    .filter((m) => q === "" || (m.from + " " + (m.to || "") + " " + m.subject + " " + m.body).toLowerCase().includes(q.toLowerCase()));
  const open = openId ? mail.find((m) => m.id === openId) : null;

  const update = (id, patch) => setMail((ms) => ms.map((m) => (m.id === id ? { ...m, ...patch } : m)));
  const openMail = (m) => { setOpenId(m.id); if (m.unread) update(m.id, { unread: false }); };
  const trash = (m) => {
    update(m.id, { folder: m.folder === "trash" ? "trash" : "trash" });
    if (m.folder === "trash") setMail((ms) => ms.filter((x) => x.id !== m.id));
    setOpenId(null);
    notify(m.folder === "trash" ? T("mail.deletedForever") : T("mail.movedToTrash"));
  };

  const send = (msg) => {
    setMail((ms) => [{ id: "M-22", folder: "sent", from: "me", to: msg.to, subject: msg.subject, body: msg.body, time: "11:55", date: "Jun 13", unread: false, starred: false }, ...ms]);
    setCompose(false);
    notify(T("mail.emailSentTo", { to: msg.to }));
  };

  return (
    <section className="card mailwrap" ref={wrapRef}>
      {/* folders */}
      <div className="mail-rail">
        <Btn variant="primary" icon="plus" onClick={() => setCompose(true)}>{T("mail.compose")}</Btn>
        <div className="mail-folders">
          {FOLDERS.map((f) => (
            <button key={f.id} className={"mail-folder" + (folder === f.id ? " on" : "")}
              onClick={() => { setFolder(f.id); setOpenId(null); }}>
              <Icon name={f.icon} size={15} />
              <span>{f.label}</span>
              {count(f.id) > 0 ? <i className="mail-count mono">{count(f.id)}</i> : null}
            </button>
          ))}
        </div>
      </div>

      {/* list or message */}
      {!open ? (
        <div className="mail-main">
          <div className="mail-tools">
            <div className="searchbox" style={{ flex: 1 }}>
              <Icon name="search" size={15} />
              <input placeholder={T("mail.searchMail")} value={q} onChange={(e) => setQ(e.target.value)} />
            </div>
          </div>
          <div className="mail-list">
            {list.map((m) => (
              <button key={m.id} className={"mail-row" + (m.unread ? " unread" : "")} onClick={() => openMail(m)}>
                <button className={"mail-star" + (m.starred ? " on" : "")}
                  onClick={(e) => { e.stopPropagation(); update(m.id, { starred: !m.starred }); }}
                  aria-label={T("mail.star")}>★</button>
                <span className="mail-from">{m.from === "me" ? T("mail.toPrefix", { to: m.to }) : m.from}</span>
                <span className="mail-subj">
                  <b>{m.subject}</b>
                  <small> — {m.body.replace(/\n/g, " ").slice(0, 60)}…</small>
                </span>
                <span className="mail-time mono">{m.time}</span>
              </button>
            ))}
            {list.length === 0 ? <p className="dim" style={{ textAlign: "center", padding: 40, fontSize: 13 }}>{T("mail.nothingIn", { folder: (FOLDERS.find((f) => f.id === folder) || {}).label || folder })}</p> : null}
          </div>
        </div>
      ) : (
        <div className="mail-main">
          <div className="mail-tools">
            <Btn small onClick={() => setOpenId(null)}>{T("common.back")}</Btn>
            <div style={{ flex: 1 }}></div>
            <Btn small onClick={() => update(open.id, { starred: !open.starred })}>{open.starred ? "★ " + T("mail.starred") : "☆ " + T("mail.star")}</Btn>
            <Btn small onClick={() => trash(open)}>{T("common.delete")}</Btn>
          </div>
          <div className="mail-read">
            <h3 className="display">{open.subject}</h3>
            <div className="mail-meta">
              <Avatar name={open.from === "me" ? "Lena Ortiz" : open.from} size={36} />
              <div className="who2">
                <b>{open.from === "me" ? T("mail.me") : open.from}</b>
                <small className="mono">{open.from === "me" ? T("mail.toName", { to: open.to }) : open.email}</small>
              </div>
              <span className="dim mono" style={{ marginInlineStart: "auto", fontSize: 11.5 }}>{open.date} · {open.time || ""}</span>
            </div>
            <div className="mail-body">{open.body}</div>
            <div className="btnrow" style={{ marginTop: 18 }}>
              <Btn variant="primary" icon="send" onClick={() => setCompose(true)}>{T("mail.reply")}</Btn>
            </div>
          </div>
        </div>
      )}

      <ComposeModal open={compose} replyTo={open} onClose={() => setCompose(false)} onSend={send} />
    </section>
  );
}

function ComposeModal({ open, replyTo, onClose, onSend }) {
  const { useState, useEffect } = React;
  const [to, setTo] = useState("");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [err, setErr] = useState("");

  useEffect(() => {
    if (open) {
      setTo(replyTo ? (replyTo.from === "me" ? replyTo.to : replyTo.email) : "");
      setSubject(replyTo ? (replyTo.subject.startsWith("Re:") ? replyTo.subject : "Re: " + replyTo.subject) : "");
      setBody("");
      setErr("");
    }
  }, [open]);

  const send = () => {
    if (!to.trim() || !to.includes("@")) { setErr(T("mail.errRecipient")); return; }
    if (!subject.trim()) { setErr(T("mail.errSubject")); return; }
    onSend({ to: to.trim(), subject: subject.trim(), body });
  };

  return (
    <Modal open={open} onClose={onClose} width={620} title={replyTo ? T("mail.reply") : T("mail.newEmail")} sub={T("mail.fromAddress", { email: "lena.ortiz@vision.co" })}
      footer={<div className="btnrow"><Btn variant="primary" icon="send" onClick={send}>{T("chat.send")}</Btn><Btn onClick={onClose}>{T("mail.discard")}</Btn></div>}>
      <Field label={T("mail.to")} error={err}>
        <Input placeholder="name@company.com" value={to} onChange={(e) => setTo(e.target.value)} />
      </Field>
      <Field label={T("mail.subject")}>
        <Input placeholder={T("mail.subject")} value={subject} onChange={(e) => setSubject(e.target.value)} />
      </Field>
      <Field label="">
        <textarea className="input area" rows="8" placeholder={T("mail.writeMessage")} value={body} onChange={(e) => setBody(e.target.value)}></textarea>
      </Field>
    </Modal>
  );
}
window.MailTab = MailTab;
