/* global React, Icon, AgentChip, OPENER_BRIEF, OPENER_MAILBOXES, OPENER_ACTIVITY, CHANNEL_LABEL */
// Opener extras — the "configured agent" surfaces that make it read as a real
// AI SDR: the editable brief (ICP / pain / signals / playbook), the sending
// infrastructure (mailboxes + deliverability), and the always-on activity feed.

const { useState: useStateX } = React;

// ---------- Opener brief (the "we know" config layer) ----------
function OpenerBrief({ onClose }) {
  const b = (typeof OPENER_BRIEF !== "undefined" && OPENER_BRIEF) || window.OPENER_BRIEF || {};
  const [signals, setSignals] = useStateX(b.signals || []);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);
  const toggle = (i) => setSignals((s) => s.map((x, j) => (j === i ? { ...x, on: !x.on } : x)));
  const ch = (c) => (CHANNEL_LABEL || {})[c] || c;
  const edit = (field) => window.fireToast && window.fireToast(`Editing ${field} — Addy will re-tune sourcing`);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal opener-brief" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Opener brief">
        <div className="modal-head">
          <div className="modal-status">
            <div className="modal-title-row"><h2 className="h2">Opener brief</h2></div>
            <div className="deal-meta-line">{b.source || "AI-generated for your org"} · edit anything to re-tune who the Opener sources</div>
          </div>
          <button className="btn sm ghost" onClick={onClose} aria-label="Close brief"><Icon name="close" size={14} /></button>
        </div>

        <div className="modal-body brief-body">
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">Product</em><button className="brief-edit" onClick={() => edit("product")}>Edit</button></div>
            <p className="brief-text">{b.product}</p>
          </div>
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">Pain we solve</em><button className="brief-edit" onClick={() => edit("pain")}>Edit</button></div>
            <p className="brief-text">{b.pain}</p>
          </div>
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">ICP</em><button className="brief-edit" onClick={() => edit("ICP")}>Edit</button></div>
            <div className="brief-chips">{(b.icp?.industries || []).map((x) => <span key={x} className="brief-chip">{x}</span>)}</div>
            <p className="brief-meta">{b.icp?.size} · {b.icp?.geo} · {b.icp?.stack}</p>
          </div>
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">Target personas</em><button className="brief-edit" onClick={() => edit("personas")}>Edit</button></div>
            <div className="brief-chips">{(b.personas || []).map((x) => <span key={x} className="brief-chip is-persona">{x}</span>)}</div>
          </div>
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">Buying-intent signals tracked</em></div>
            <div className="brief-signals">
              {signals.map((s, i) => (
                <button key={i} type="button" className={`brief-signal ${s.on ? "is-on" : ""}`} onClick={() => toggle(i)} aria-pressed={s.on}>
                  <span className="brief-signal-dot" />{s.label}
                </button>
              ))}
            </div>
          </div>
          <div className="brief-sec">
            <div className="brief-sec-head"><em className="lead-sec-label">Sequence / playbook</em><button className="brief-edit" onClick={() => edit("sequence")}>Edit</button></div>
            <div className="brief-seq">
              {(b.sequence || []).map((s) => (
                <div key={s.n} className="brief-step">
                  <span className="brief-step-n">{s.n}</span>
                  <span className="brief-step-label">{s.label}</span>
                  <span className="brief-step-ch">{ch(s.channel)} · {s.wait}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <footer className="brief-foot">
          <button type="button" className="btn ghost" onClick={onClose}>Close</button>
          <button type="button" className="btn accent" onClick={() => { window.fireToast && window.fireToast("Brief saved — Opener re-tuned sourcing"); onClose(); }}>Save brief</button>
        </footer>
      </div>
    </div>
  );
}

// ---------- Sending infra: the accounts the Opener sends as you from ----------
// LinkedIn seat + email inboxes, with the caps that protect the identity:
// invite quota and accept rate on LinkedIn, warmth and deliverability on email.
function OpenerMailboxes() {
  const m = (typeof OPENER_MAILBOXES !== "undefined" && OPENER_MAILBOXES) || window.OPENER_MAILBOXES;
  if (!m) return null;
  const li = (window.OPENER_CHANNEL_ACCOUNTS || {}).linkedin;
  const warm = m.inboxes.filter((x) => x.warm).length;
  return (
    <section className="op-panel">
      <header className="op-panel-head">
        <h3>Sending channels</h3>
        <span className="op-panel-score">{Math.round(m.deliverability * 100)}% deliverability</span>
      </header>
      {li && li.connected && (
        <div className="op-channel-block">
          <div className="op-mailbox op-li">
            <span className="op-mailbox-dot is-warm" />
            <span className="op-mailbox-addr">LinkedIn · {li.profile}</span>
            <span className="op-mailbox-cap">{li.dmsToday}/{li.dmCapDay} DMs today</span>
          </div>
          <div className="op-li-stat">
            <b>{li.invitesUsedWeek}/{li.inviteCapWeek}</b> invites this week <i aria-hidden="true">·</i> <b>{Math.round(li.acceptRate * 100)}%</b> accepted
          </div>
        </div>
      )}
      <div className="op-channel-block">
        <div className="op-mailbox-stat">
          <b>{warm}/{m.inboxes.length}</b> inboxes warm <i aria-hidden="true">·</i> <b>{m.sentToday}/{m.dailyCap}</b> sent today
        </div>
        <div className="op-mailboxes">
          {m.inboxes.map((ib) => (
            <div key={ib.addr} className="op-mailbox">
              <span className={`op-mailbox-dot ${ib.warm ? "is-warm" : ""}`} />
              <span className="op-mailbox-addr">{ib.addr}</span>
              <span className="op-mailbox-cap">{ib.cap}/day</span>
            </div>
          ))}
        </div>
      </div>
      <p className="op-panel-note">One channel per touch, rate-limited on both — invites and sends that protect the relationship. The Opener never blasts.</p>
    </section>
  );
}

// ---------- Always-on activity feed ----------
function OpenerActivity() {
  const items = (typeof OPENER_ACTIVITY !== "undefined" && OPENER_ACTIVITY) || window.OPENER_ACTIVITY || [];
  if (!items.length) return null;
  return (
    <section className="op-panel">
      <header className="op-panel-head">
        <h3>Opener activity</h3>
        <span className="op-live"><span className="op-live-dot" />live</span>
      </header>
      <ul className="op-activity">
        {items.map((a, i) => (
          <li key={i} className="op-activity-item">
            <span className="op-activity-when">{a.when}</span>
            <span className="op-activity-text">{a.text}</span>
          </li>
        ))}
      </ul>
    </section>
  );
}

window.OpenerBrief = OpenerBrief;
window.OpenerMailboxes = OpenerMailboxes;
window.OpenerActivity = OpenerActivity;
