/* ============================================================
   Campaigns — list of outreach campaigns → opens a sequence builder.
   ============================================================ */

const CHANNEL_META = {
  email:    { label: "Email", icon: "mail", color: "var(--accent)" },
  linkedin: { label: "LinkedIn", icon: "linkedin", color: "#8FB8E8" },
  dm:       { label: "DM", icon: "send", color: "var(--lane-agency)" },
};
const TOKENS = ["{{firstName}}", "{{brand}}", "{{event}}", "{{detail}}"];

const CAMPAIGN_STATUS = {
  active: { label: "Active", color: "var(--green)" },
  draft:  { label: "Draft",  color: "var(--text-2)" },
  paused: { label: "Paused", color: "var(--amber)" },
};

// ---------- Campaign list ----------
function CampaignList({ lane, onOpen, onNew }) {
  const seqs = window.WTC.sequences.filter((s) => lane === "all" || s.lane === lane);
  return (
    <div className="surface-scroll">
      <div className="today-head">
        <div>
          <h1 className="page-title">Campaigns</h1>
          <p className="page-sub">Outreach sequences per lane · open one to edit its steps · manual approve means every step surfaces as a draft</p>
        </div>
        <button className="btn btn--primary" onClick={onNew}><Icon name="plus" size={15} /> New campaign</button>
      </div>

      <div className="campaign-grid">
        {seqs.map((s) => {
          const st = CAMPAIGN_STATUS[s.status] || CAMPAIGN_STATUS.draft;
          const replyPct = s.enrolled ? Math.round((s.replied / s.enrolled) * 100) : 0;
          return (
            <button key={s.id} className="campaign-card lift" onClick={() => onOpen(s.id)}>
              <div className="cc-top">
                <LaneChip lane={s.lane} />
                <span className="cc-status" style={{ color: st.color }}>
                  <span className="stagedot" style={{ background: st.color }}></span>{st.label}
                </span>
              </div>
              <div className="cc-name">{s.name}</div>
              <div className="cc-goal">{s.goal}</div>

              <div className="cc-channels">
                {s.steps.map((step, i) => (
                  <span key={i} className="cc-chan" title={CHANNEL_META[step.channel].label} style={{ color: CHANNEL_META[step.channel].color }}>
                    <Icon name={CHANNEL_META[step.channel].icon} size={13} />
                  </span>
                ))}
                <span className="cc-steps num">{s.steps.length} steps</span>
              </div>

              <div className="cc-stats">
                <div className="cc-stat">
                  <span className="num cc-stat-num">{s.enrolled}</span>
                  <span className="cc-stat-lbl">Enrolled</span>
                </div>
                <div className="cc-stat">
                  <span className="num cc-stat-num" style={{ color: "var(--accent)" }}>{s.dueNow}</span>
                  <span className="cc-stat-lbl">Due now</span>
                </div>
                <div className="cc-stat">
                  <span className="num cc-stat-num" style={{ color: "var(--green)" }}>{replyPct}%</span>
                  <span className="cc-stat-lbl">Reply rate</span>
                </div>
              </div>

              <div className="cc-foot">
                <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>Updated {s.updated}</span>
                <span className="cc-open">Open builder <Icon name="chevronRight" size={13} /></span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Sequence builder (Flow + Steps views) ----------
function SequenceBuilder({ seqId, onBack }) {
  const seq0 = window.WTC.sequences.find((s) => s.id === seqId) || window.WTC.sequences[0];
  const [name, setName] = React.useState(seq0.name);
  const [view, setView] = React.useState("flow");
  const st = CAMPAIGN_STATUS[seq0.status] || CAMPAIGN_STATUS.draft;

  return (
    <div className="builder-surface">
      <div className="builder-bar">
        <button className="back-link" onClick={onBack}><Icon name="chevronLeft" size={15} /> Campaigns</button>
        <div className="builder-head">
          <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
            <LaneChip lane={seq0.lane} />
            <input className="builder-title" value={name} onChange={(e) => setName(e.target.value)} />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Segmented value={view === "flow" ? "Flow" : view === "people" ? "People" : "Steps"} onChange={(v) => setView(v === "Flow" ? "flow" : v === "People" ? "people" : "steps")} options={["Flow", "Steps", "People"]} />
            <span className="cc-status" style={{ color: st.color }}>
              <span className="stagedot" style={{ background: st.color }}></span>{st.label}
            </span>
            <span className="num" style={{ fontSize: 12.5, color: "var(--text-3)" }}>{seq0.enrolled} enrolled · {seq0.dueNow} due</span>
            <button className="btn btn--primary btn--sm"><Icon name="check" size={14} /> Save</button>
          </div>
        </div>
      </div>
      {view === "flow" ? <FlowBuilder seq={seq0} />
        : view === "people" ? <FlowPeople seq={seq0} />
        : <StepEditor seq={seq0} />}
    </div>
  );
}

function FlowPeople({ seq }) {
  const E = window.WTC.enrollments;
  const enrolled = window.WTC.contacts.filter((c) => E[c.id] && E[c.id].seqId === seq.id).map((c) => ({ c, step: E[c.id].step }));
  const steps = seq.steps;
  const chLabel = (ch) => ({ email: "Email", linkedin: "LinkedIn" }[ch] || "Step");
  const dist = steps.map((s, i) => enrolled.filter((e) => e.step === i + 1).length);
  const maxD = Math.max(1, ...dist);

  return (
    <div className="surface-scroll">
      <div className="people-top">
        <div className="people-stat"><span className="num people-num">{enrolled.length}</span><span className="people-lbl">In this flow</span></div>
        <div className="people-stat"><span className="num people-num" style={{ color: "var(--accent)" }}>{dist.reduce((a, b) => a + b, 0)}</span><span className="people-lbl">Active steps</span></div>
        <div className="people-stat"><span className="num people-num" style={{ color: "var(--green)" }}>{seq.replied}</span><span className="people-lbl">Replied</span></div>
        <div className="people-stat"><span className="num people-num">{steps.length}</span><span className="people-lbl">Steps in flow</span></div>
      </div>

      <div className="funnel">
        <div className="funnel-head">Where contacts are in the sequence</div>
        {steps.map((s, i) => (
          <div key={i} className="funnel-row">
            <span className="funnel-step num">{i + 1}</span>
            <span className="funnel-ch"><Icon name={s.channel === "linkedin" ? "linkedin" : "mail"} size={13} /> {chLabel(s.channel)}</span>
            <div className="funnel-bar"><div className="funnel-fill" style={{ width: (dist[i] / maxD) * 100 + "%" }}></div></div>
            <span className="num funnel-count">{dist[i]}</span>
          </div>
        ))}
      </div>

      <div className="queue-head" style={{ marginTop: 8 }}>
        <h2 style={{ fontSize: 14.5, fontWeight: 670, margin: 0 }}>Enrolled contacts</h2>
      </div>
      <div className="dense-wrap">
        <table className="dense">
          <thead><tr><th>Contact</th><th>Target</th><th>Type</th><th>Current step</th><th>Next action</th></tr></thead>
          <tbody>
            {enrolled.length === 0
              ? <tr><td colSpan="5"><div style={{ padding: "26px 0", textAlign: "center", color: "var(--text-3)" }}>No contacts enrolled yet — tag a contact to auto-enroll.</div></td></tr>
              : enrolled.map(({ c, step }) => {
                const next = steps[Math.min(step, steps.length - 1)];
                return (
                  <tr key={c.id} className="lift">
                    <td><div style={{ display: "flex", alignItems: "center", gap: 9 }}><Avatar name={c.name} initials={c.initials} color={c.color} size={26} /><span style={{ fontWeight: 600, whiteSpace: "nowrap" }}>{c.name}</span></div></td>
                    <td><div style={{ display: "flex", alignItems: "center", gap: 7 }}><Avatar mono={c.mono} size={22} square /><span style={{ color: "var(--text-2)" }}>{c.brand}</span></div></td>
                    <td><LaneChip lane={c.lane} small /></td>
                    <td><span className="num" style={{ color: "var(--text-2)" }}>Step {step} of {steps.length}</span></td>
                    <td><span style={{ color: "var(--text-2)", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name={next.channel === "linkedin" ? "linkedin" : "mail"} size={13} style={{ color: "var(--accent)" }} /> {chLabel(next.channel)}</span></td>
                  </tr>
                );
              })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function StepEditor({ seq }) {
  const [steps, setSteps] = React.useState(seq.steps.map((s, i) => ({ ...s, _id: i })));
  const [dragIdx, setDragIdx] = React.useState(null);
  React.useEffect(() => { setSteps(seq.steps.map((s, i) => ({ ...s, _id: i }))); }, [seq.id]);

  const move = (from, to) => {
    if (to < 0 || to >= steps.length) return;
    const next = steps.slice();
    const [m] = next.splice(from, 1);
    next.splice(to, 0, m);
    setSteps(next);
  };
  const update = (idx, patch) => setSteps((s) => s.map((stp, i) => i === idx ? { ...stp, ...patch } : stp));
  const addStep = () => setSteps((s) => [...s, { _id: Date.now(), channel: "email", delay: 4, mode: "manual", subject: "", body: "" }]);
  const removeStep = (idx) => setSteps((s) => s.filter((_, i) => i !== idx));

  return (
    <div className="surface-scroll">
      <p className="page-sub" style={{ marginBottom: 22, marginTop: 0 }}>{seq.goal}</p>
      <div className="seq-builder">
        {steps.map((stp, idx) => {
          const cm = CHANNEL_META[stp.channel];
          return (
            <React.Fragment key={stp._id}>
              {idx > 0 && (
                <div className="seq-connector">
                  <span className="conn-line"></span>
                  <span className="delay-pill">
                    <Icon name="clock" size={12} /> wait
                    <input type="number" className="num delay-input" min="0" value={stp.delay}
                      onChange={(e) => update(idx, { delay: Math.max(0, +e.target.value) })} />
                    {stp.delay === 1 ? "day" : "days"}
                  </span>
                  <span className="conn-line"></span>
                </div>
              )}
              <div className={"seq-card" + (dragIdx === idx ? " dragging" : "")}
                draggable onDragStart={() => setDragIdx(idx)}
                onDragOver={(e) => { e.preventDefault(); if (dragIdx !== null && dragIdx !== idx) { move(dragIdx, idx); setDragIdx(idx); } }}
                onDragEnd={() => setDragIdx(null)}>
                <div className="seq-card-head">
                  <span className="seq-grip" title="Drag to reorder"><Icon name="more" size={14} /></span>
                  <span className="step-badge num">{idx + 1}</span>
                  <div className="seq-channel" style={{ color: cm.color }}>
                    <Icon name={cm.icon} size={15} />
                    <select value={stp.channel} onChange={(e) => update(idx, { channel: e.target.value })}>
                      {Object.keys(CHANNEL_META).map((c) => <option key={c} value={c}>{CHANNEL_META[c].label}</option>)}
                    </select>
                  </div>
                  <span style={{ flex: 1 }}></span>
                  <button className={"mode-toggle" + (stp.mode === "manual" ? " manual" : " auto")}
                    onClick={() => update(idx, { mode: stp.mode === "manual" ? "auto" : "manual" })}
                    title="Manual surfaces a draft to approve — nothing auto-fires">
                    <span className="mode-dot"></span>{stp.mode === "manual" ? "Manual approve" : "Auto-send"}
                  </button>
                  <div className="seq-reorder">
                    <button className="btn btn--ghost btn--icon btn--sm" title="Move up" onClick={() => move(idx, idx - 1)} disabled={idx === 0}><Icon name="chevronDown" size={14} style={{ transform: "rotate(180deg)" }} /></button>
                    <button className="btn btn--ghost btn--icon btn--sm" title="Move down" onClick={() => move(idx, idx + 1)} disabled={idx === steps.length - 1}><Icon name="chevronDown" size={14} /></button>
                    <button className="btn btn--ghost btn--icon btn--sm btn--danger" title="Remove step" onClick={() => removeStep(idx)}><Icon name="x" size={14} /></button>
                  </div>
                </div>
                {stp.channel !== "linkedin" && (
                  <div className="seq-field">
                    <label className="seq-label">Subject</label>
                    <input className="input seq-subject" placeholder="Subject line…" value={stp.subject}
                      onChange={(e) => update(idx, { subject: e.target.value })} />
                  </div>
                )}
                <div className="seq-field">
                  <label className="seq-label">{stp.channel === "linkedin" ? "Connection note" : "Message"}</label>
                  <textarea className="seq-template" value={stp.body} placeholder="Write the template — drop in tokens below…"
                    onChange={(e) => update(idx, { body: e.target.value })} />
                </div>
                <div className="token-row">
                  <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>Insert token:</span>
                  {TOKENS.map((tk) => (
                    <button key={tk} className="token-chip" onClick={() => update(idx, { body: (stp.body ? stp.body + " " : "") + tk })}>{tk}</button>
                  ))}
                </div>
              </div>
            </React.Fragment>
          );
        })}
        <button className="seq-add" onClick={addStep}><Icon name="plus" size={16} /> Add step</button>
      </div>
    </div>
  );
}

function NewCampaignModal({ onClose, onCreate }) {
  const LM = window.WTC.LANE_META;
  const [name, setName] = React.useState("");
  const [lane, setLane] = React.useState("brand");
  const [goal, setGoal] = React.useState("");
  const [tpl, setTpl] = React.useState("default");
  const create = () => {
    onCreate({ name: name.trim() || (LM[lane].label + " outreach"), lane, goal: goal.trim() || "New outreach campaign", tpl });
  };
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" style={{ width: "min(520px, 100%)" }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <span style={{ fontSize: 15.5, fontWeight: 680 }}>New campaign</span>
          <button className="btn btn--ghost btn--icon" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 15 }}>
          <div className="brief-field"><label className="brief-label">Campaign name</label>
            <input className="input" autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Coachella brand outreach" /></div>
          <div className="brief-field"><label className="brief-label">Lane</label>
            <div className="facet-chips">{["brand", "agency", "event", "travel"].map((l) => (
              <button key={l} className="facet-chip" data-on={lane === l || undefined} onClick={() => setLane(l)}><span className="chip-dot" style={{ background: `var(--lane-${l})` }}></span>{LM[l].label}</button>
            ))}</div></div>
          <div className="brief-field"><label className="brief-label">Goal</label>
            <input className="input" value={goal} onChange={(e) => setGoal(e.target.value)} placeholder="What is this campaign for?" /></div>
          <div className="brief-field"><label className="brief-label">Start from</label>
            <Segmented value={tpl === "default" ? "Lane default" : "Blank"} onChange={(v) => setTpl(v === "Lane default" ? "default" : "blank")} options={["Lane default", "Blank"]} />
            <div className="insp-hint">{tpl === "default" ? "Pre-fills the proven steps for this lane — edit them in the builder." : "Starts with a single email step you build out."}</div></div>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "0 22px 20px" }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" onClick={create}><Icon name="plus" size={15} /> Create & open builder</button>
        </div>
      </div>
    </div>
  );
}

function Campaigns({ lane }) {
  const [openId, setOpenId] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [, bump] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => {
    if (openId) {
      const s = window.WTC.sequences.find((x) => x.id === openId);
      if (s && lane !== "all" && s.lane !== lane) setOpenId(null);
    }
  }, [lane]);
  const createCampaign = ({ name, lane, goal, tpl }) => {
    const id = "seq_" + Date.now();
    const def = window.WTC.sequences.find((s) => s.lane === lane);
    const steps = (tpl === "default" && def)
      ? def.steps.map((s) => ({ ...s }))
      : [{ channel: "email", delay: 0, mode: "manual", subject: "", body: "" }];
    window.WTC.sequences.push({ id, name, lane, status: "draft", enrolled: 0, replied: 0, dueNow: 0, updated: "just now", goal, steps });
    setCreating(false); bump(); setOpenId(id);
  };
  return (
    <React.Fragment>
      {openId
        ? <SequenceBuilder seqId={openId} onBack={() => setOpenId(null)} />
        : <CampaignList lane={lane} onOpen={setOpenId} onNew={() => setCreating(true)} />}
      {creating && <NewCampaignModal onClose={() => setCreating(false)} onCreate={createCampaign} />}
    </React.Fragment>
  );
}

Object.assign(window, { Campaigns });
