// CampaignModal.jsx — generic renderer for the outreach plan.
// Takes a `lead`, builds the plan via CP_buildCampaign(lead), and renders the
// same assemble-then-reveal flow as before — but every line of copy, the step
// count, channels and cadence now come from the plan (type + phase aware).

const { useState: useModalState, useEffect: useModalEffect } = React;

const HelmAvatar = ({ size = 40 }) => (
  <div style={{ width: size, height: size, borderRadius: size / 2, background: "var(--helm-dark-green)", color: "var(--helm-lemon)", display: "grid", placeItems: "center", flexShrink: 0 }}>
    <span className="helm-star" style={{ width: size * 0.45, height: size * 0.45 }} />
  </div>
);

const HelmBy = () => (
  <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--helm-dark-grey)", fontSize: 12, letterSpacing: "0.06em", textTransform: "uppercase", fontWeight: 700, whiteSpace: "nowrap" }}>
    <span className="helm-star" style={{ width: 12, height: 12, color: "var(--helm-chartreuse-2)" }} />
    Drafted by Helm Co-pilot
  </div>
);

const StepIcon = ({ type, size = 22 }) => {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "var(--helm-dark-green)", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
  if (type === "email") return <svg {...common}><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" /></svg>;
  if (type === "sms") return <svg {...common}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>;
  if (type === "call") return <svg {...common}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" /></svg>;
  return null;
};

// ----------------------------------------------------------------- content blocks
const EmailContent = ({ c, attachment }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", marginBottom: 8 }}>
      <span style={{ color: "var(--helm-dark-green)", fontWeight: 700 }}>To</span> {c.to} &nbsp;·&nbsp;
      <span style={{ color: "var(--helm-dark-green)", fontWeight: 700 }}>From</span> {c.from}
    </div>
    <div style={{ fontWeight: 700, fontSize: 17, marginBottom: 14, color: "var(--helm-dark-green)" }}>{c.subject}</div>
    <div style={{ display: "flex", flexDirection: "column", gap: 11, fontSize: 14, lineHeight: "22px", color: "var(--helm-dark-green)" }}>
      {c.body.map((p, i) => <p key={i} style={{ margin: 0 }}>{p}</p>)}
    </div>
  </div>
);

const SmsContent = ({ c }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", marginBottom: 10 }}>
      To <span style={{ color: "var(--helm-dark-green)", fontWeight: 700 }}>{c.to}</span> &nbsp;·&nbsp; From {CP_PRODUCER}'s iMessage
    </div>
    <div style={{ display: "flex", justifyContent: "flex-end" }}>
      <div style={{ maxWidth: 480, padding: "12px 16px", background: "var(--helm-blue)", color: "var(--helm-dark-green)", borderRadius: "18px 18px 4px 18px", fontSize: 14, lineHeight: "20px" }}>{c.text}</div>
    </div>
    <div style={{ display: "flex", justifyContent: "flex-end", fontSize: 11, color: "var(--helm-dark-grey)", marginTop: 4 }}>Delivered · 1 message</div>
  </div>
);

const CallContent = ({ c }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", marginBottom: 10 }}>
      You call <span style={{ color: "var(--helm-dark-green)", fontWeight: 700 }}>{c.who}</span> &nbsp;·&nbsp; {c.note}
    </div>
    <div style={{ padding: "12px 16px", borderRadius: 12, background: "rgba(255,184,118,0.18)", border: "1px solid var(--helm-dark-ecru)", marginBottom: 14, fontStyle: "italic", fontFamily: "var(--font-serif)", fontSize: 16 }}>{c.opener}</div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 8 }}>Talk-track</div>
    <ol style={{ margin: 0, paddingLeft: 22, display: "flex", flexDirection: "column", gap: 6 }}>
      {c.beats.map((b, i) => <li key={i} style={{ fontSize: 14, lineHeight: "20px" }}>{b}</li>)}
    </ol>
  </div>
);

const StepContent = ({ content }) => {
  if (content.kind === "email") return <EmailContent c={content} />;
  if (content.kind === "sms") return <SmsContent c={content} />;
  return <CallContent c={content} />;
};

const Stat = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)", textTransform: "uppercase", fontWeight: 600, letterSpacing: "0.05em" }}>{label}</div>
    <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 22, color: "var(--helm-dark-green)", lineHeight: 1.1 }}>{value}</div>
  </div>
);

// ----------------------------------------------------------------- modal
const CampaignModal = ({ lead, onClose }) => {
  const plan = CP_buildCampaign(lead);
  const STEPS = plan.steps;
  const [active, setActive] = useModalState(0);
  const step = STEPS[active];

  const [generating, setGenerating] = useModalState(true);
  const [revealed, setRevealed] = useModalState(0);
  const [statusIdx, setStatusIdx] = useModalState(0);

  useModalEffect(() => {
    const timers = [];
    for (let i = 1; i <= STEPS.length; i++) timers.push(setTimeout(() => setRevealed(i), 250 + i * 430));
    plan.buildStatus.forEach((_, i) => timers.push(setTimeout(() => setStatusIdx(i), i * 660)));
    timers.push(setTimeout(() => setGenerating(false), 3500));
    return () => timers.forEach(clearTimeout);
  }, [lead.id]);

  return (
    <>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(0,29,0,0.45)", zIndex: 2 }} />
      <div style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)", zIndex: 3, width: 920, maxWidth: "calc(100vw - 48px)", maxHeight: "calc(100vh - 48px)", overflow: "hidden", background: "var(--helm-white)", border: "1px solid var(--helm-dark-green)", boxShadow: "var(--shadow-card-lg)", borderRadius: 24, padding: "32px 40px 26px", display: "flex", flexDirection: "column", gap: 22, fontFamily: "var(--font-sans)", color: "var(--helm-dark-green)" }}>
        <style>{`
          @keyframes helmBreathe { 0%,100% { transform: scale(1); opacity: 0.85; } 50% { transform: scale(1.14); opacity: 1; } }
          @keyframes helmSpin { to { transform: rotate(360deg); } }
          @keyframes helmFadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
          .cp-fade { animation: helmFadeUp 450ms ease both; }
        `}</style>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <HelmAvatar size={40} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <HelmBy />
            <h2 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 30, lineHeight: "34px", margin: "4px 0 0", letterSpacing: "-0.01em" }}>{plan.title}</h2>
            <div style={{ fontSize: 12.5, color: "var(--helm-dark-grey)", marginTop: 4, fontWeight: 600 }}>{plan.kicker}</div>
          </div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", fontSize: 24, color: "var(--helm-dark-grey)", cursor: "pointer", padding: 4, lineHeight: 1, alignSelf: "flex-start" }}>×</button>
        </div>

        {/* Stepper */}
        <div style={{ display: "flex", alignItems: "flex-start", position: "relative" }}>
          {STEPS.map((s, i) => {
            const shown = !generating || i < revealed;
            return (
              <React.Fragment key={i}>
                <button onClick={() => !generating && setActive(i)} style={{ background: "transparent", border: "none", cursor: generating ? "default" : "pointer", padding: 0, display: "flex", flexDirection: "column", alignItems: "center", gap: 6, width: 96, fontFamily: "var(--font-sans)", opacity: shown ? 1 : 0, transform: shown ? "translateY(0) scale(1)" : "translateY(7px) scale(0.85)", transition: "opacity 360ms ease, transform 360ms cubic-bezier(.2,.7,.3,1)" }}>
                  <div style={{ width: 48, height: 48, borderRadius: 14, background: s.color, border: (!generating && active === i) ? "2px solid var(--helm-dark-green)" : "1px solid rgba(0,29,0,0.12)", display: "grid", placeItems: "center", boxShadow: (!generating && active === i) ? "0 0 0 4px rgba(0,29,0,0.06)" : "none", transition: "box-shadow 150ms ease, border-color 150ms ease" }}>
                    <StepIcon type={s.icon} />
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: "var(--helm-dark-green)" }}>{s.day}</div>
                  <div style={{ fontSize: 11, color: "var(--helm-dark-grey)" }}>{s.kind}</div>
                </button>
                {i < STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: "var(--helm-dark-ecru)", marginTop: 24, opacity: shown ? 1 : 0, transition: "opacity 360ms ease" }} />}
              </React.Fragment>
            );
          })}
        </div>

        {generating ? (
          <div style={{ flex: "1 1 auto", minHeight: 0, border: "1px solid var(--helm-dark-ecru)", borderRadius: 16, background: "var(--helm-white)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 18, padding: "40px 24px" }}>
            <div style={{ position: "relative", width: 64, height: 64, display: "grid", placeItems: "center" }}>
              <div style={{ position: "absolute", inset: 0, borderRadius: "50%", border: "2px solid var(--helm-dark-ecru)", borderTopColor: "var(--helm-chartreuse-2)", animation: "helmSpin 1.1s linear infinite" }} />
              <span className="helm-star" style={{ width: 30, height: 30, color: "var(--helm-chartreuse-2)", animation: "helmBreathe 1.6s ease-in-out infinite" }} />
            </div>
            <div key={statusIdx} style={{ fontFamily: "var(--font-serif)", fontSize: 19, lineHeight: "26px", color: "var(--helm-dark-green)", textAlign: "center", maxWidth: 480 }}>{plan.buildStatus[statusIdx]}</div>
            <div style={{ display: "flex", gap: 6 }}>
              {plan.buildStatus.map((_, i) => (
                <span key={i} style={{ width: 6, height: 6, borderRadius: "50%", background: i <= statusIdx ? "var(--helm-chartreuse-2)" : "var(--helm-dark-ecru)", transition: "background 300ms ease" }} />
              ))}
            </div>
          </div>
        ) : (
          <div style={{ padding: "22px 24px", border: "1px solid var(--helm-dark-ecru)", borderRadius: 16, background: "var(--helm-white)", flex: "1 1 auto", minHeight: 0, overflowY: "auto" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <span className="chip" style={{ background: "rgba(198,179,235,0.25)", color: "var(--helm-dark-green)", border: `1px solid ${step.color}` }}>{step.day} · {step.short}</span>
              <span style={{ fontSize: 12, color: "var(--helm-dark-grey)" }}>{step.note}</span>
              <button style={{ marginLeft: "auto", background: "transparent", border: "none", color: "var(--helm-dark-grey)", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>Regenerate</button>
            </div>
            <StepContent content={step.content} />
          </div>
        )}

        {/* Footer */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", borderTop: "1px solid var(--helm-dark-ecru)", paddingTop: 18, opacity: generating ? 0.45 : 1, pointerEvents: generating ? "none" : "auto", transition: "opacity 350ms ease" }}>
          <Stat label="Projected commission" value={plan.commission} />
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose} className="btn btn-ghost">Edit plan</button>
            <button onClick={onClose} className="btn btn-primary">Approve all {STEPS.length} steps</button>
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { CampaignModal });
