// Template Detail page — view an existing, published Template

const TPL_STEPS = {
  "tpl-quote": [
    { day: 0,  kind: "trigger", title: "Quote Sent",         detail: "Quote.status changed to Sent",                    icon: "branch" },
    { day: 7,  kind: "email",   title: "First Follow-Up",    detail: "Polite check-in, references quote line items",     icon: "mail" },
    { day: 21, kind: "email",   title: "Value Reminder",     detail: "Reiterates pricing window + key benefits",         icon: "mail" },
    { day: 60, kind: "task",    title: "Sales Rep Task",     detail: "Assign owner to make personal contact",            icon: "user" },
    { day: 90, kind: "email",   title: "Final Check-In",     detail: "Last touch — invites graceful no",                 icon: "mail" },
  ],
  "tpl-lead":   [
    { day: 0,  kind: "trigger", title: "Lead Created",       detail: "Lead.status = New",                                icon: "branch" },
    { day: 1,  kind: "email",   title: "Welcome",            detail: "Intro + relevant case studies",                    icon: "mail" },
    { day: 5,  kind: "email",   title: "Spec Sheet Nudge",   detail: "Sent if no engagement",                            icon: "mail" },
    { day: 14, kind: "task",    title: "Qualify Task",       detail: "Sales rep books discovery call",                   icon: "user" },
  ],
  "tpl-renew":  [
    { day: 0,  kind: "trigger", title: "Renewal Window",     detail: "renewal_date - 60d",                               icon: "branch" },
    { day: 30, kind: "email",   title: "Renewal Heads-Up",   detail: "Soft reminder w/ usage stats",                     icon: "mail" },
    { day: 50, kind: "email",   title: "Renewal Offer",      detail: "Pricing + multi-year incentive",                   icon: "mail" },
  ],
  "tpl-invoice": [
    { day: 0,  kind: "trigger", title: "Invoice Overdue",    detail: "Invoice.status = Overdue",                         icon: "branch" },
    { day: 3,  kind: "email",   title: "Friendly Reminder",  detail: "Polite, with payment link",                        icon: "mail" },
    { day: 10, kind: "email",   title: "Second Notice",      detail: "Firmer tone, copies AP contact",                   icon: "mail" },
    { day: 21, kind: "task",    title: "Collections Task",   detail: "Escalate to AR specialist",                        icon: "user" },
  ],
  "tpl-po": [
    { day: 0,  kind: "trigger", title: "PO Sent",            detail: "PO.status = Sent to Vendor",                       icon: "branch" },
    { day: 3,  kind: "email",   title: "Acknowledgment Ask", detail: "Confirm receipt + lead time",                      icon: "mail" },
    { day: 10, kind: "email",   title: "Delivery Date Check",detail: "Confirm confirmed delivery date",                  icon: "mail" },
  ],
};

const TPL_INSTANCES = {
  "tpl-quote": [
    { id: "j-1", customer: "Acme Manufacturing",   quote: "Q-982510", step: "3 of 5", state: "midflight", status: "Active",   value: "$148,900", owner: "OB", next: "Day 67 — Apr 25" },
    { id: "j-2", customer: "Northern Forge & Tool",quote: "Q-981207", step: "1 of 5", state: "fresh",     status: "Active",   value: "$84,200",  owner: "OB", next: "Day 7 — May 19" },
    { id: "j-3", customer: "Cascade Hydraulics",   quote: "Q-980441", step: "2 of 5", state: "paused",    status: "Paused",   value: "$32,100",  owner: "MI", next: "—" },
    { id: "j-4", customer: "Vector Steel Co.",     quote: "Q-980022", step: "5 of 5", state: "ended",     status: "Completed",value: "$211,400", owner: "OB", next: "—" },
  ],
};

const TPL_RULES = {
  "tpl-quote": [
    { kind: "skip", text: "Skip step if customer replied in last 14 days", count: 38, ai: true },
    { kind: "bundle", text: "Bundle multiple quotes sent the same day into one email", count: 12, ai: true },
    { kind: "shift", text: "If sales rep manually contacts customer, offset next step by 7 days", count: 21, ai: true },
    { kind: "exit", text: "Exit on Quote Accepted or Rejected", count: 184 },
    { kind: "exit", text: "Exit if customer marked as Do Not Contact", count: 2 },
  ],
};

const RECENT_TPL_DECISIONS = [
  { at: "2h ago",  kind: "skip",    text: "Skipped Day 21 step on Q-981044", reason: "Customer replied yesterday — suppressed redundant outreach." },
  { at: "5h ago",  kind: "bundled", text: "Bundled 3 quotes into one follow-up for Acme",  reason: "Same customer, same day. Consolidated to avoid 3 near-identical emails." },
  { at: "Yest.",   kind: "shift",   text: "Shifted Day 60 task on Q-980441", reason: "Sales rep made manual call. Delayed automated touchpoint by 7 days." },
  { at: "Yest.",   kind: "sent",    text: "Sent Day 7 follow-up on Q-982510", reason: "No engagement detected. Step executed on schedule." },
  { at: "2d ago",  kind: "exit",    text: "Ended journey on Q-979812",       reason: "Quote Accepted — exit condition met." },
];

const StepKindIcon = ({ kind }) => {
  const map = {
    trigger: "branch", email: "send", task: "user", check: "check",
  };
  return <Icon name={map[kind] || "check"} size={18} color={kind === "trigger" ? "white" : undefined} />;
};

const FlowRail = ({ steps }) => {
  const maxDay = Math.max(...steps.map(s => s.day), 90);
  const RULES = [
    { after: 0, label: "Skip if customer replied", icon: "cross" },
    { after: 1, label: "Bundle same-day quotes", icon: "layers" },
    { after: 2, label: "Shift on manual contact", icon: "clock" },
  ];
  return (
    <div style={{ position: "relative", padding: "8px 0 4px" }}>
      {/* Proportional spine: a thin reference rail showing real time spacing */}
      <div style={{ position: "relative", height: 38, marginBottom: 14 }}>
        <div style={{
          position: "absolute", left: 0, right: 0, top: 18, height: 2,
          background: "var(--mw-border-strong)", borderRadius: 2,
        }} />
        <div style={{
          position: "absolute", left: 0, top: 18, height: 2,
          width: `${(steps[steps.length-1].day / maxDay) * 100}%`,
          background: "var(--mw-brand-500)", borderRadius: 2,
        }} />
        {steps.map((s, i) => {
          const pct = (s.day / maxDay) * 100;
          const prevPct = i > 0 ? (steps[i-1].day / maxDay) * 100 : -999;
          const showLabel = pct - prevPct > 8;
          return (
            <div key={i} style={{ position: "absolute", left: `${pct}%`, top: 8, transform: "translateX(-50%)", textAlign: "center", whiteSpace: "nowrap" }}>
              <div style={{
                width: 22, height: 22, borderRadius: "50%",
                background: s.kind === "trigger" ? "var(--mw-brand-500)" : "#fff",
                border: s.kind === "trigger" ? "none" : "2px solid var(--mw-brand-500)",
                margin: "0 auto",
                boxShadow: "0 0 0 4px #fff",
              }} />
              {showLabel && (
                <div style={{ fontSize: 10, fontWeight: 600, color: "var(--mw-text-tertiary)", marginTop: 6,
                  textTransform: "uppercase", letterSpacing: 0.5 }}>
                  {s.kind === "trigger" ? "Start" : `Day ${s.day}`}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Evenly-spaced step cards with elapsed-time gap chips between */}
      <div style={{ display: "flex", alignItems: "stretch", gap: 0, overflowX: "auto", paddingTop: 14, paddingBottom: 8 }}>
        {steps.map((s, i) => {
          const isTrigger = s.kind === "trigger";
          const toneBg = isTrigger ? "var(--mw-brand-500)" : s.kind === "email" ? "#E8E9F6" : s.kind === "task" ? "#FFF9E0" : "#fff";
          const toneFg = isTrigger ? "#fff" : s.kind === "email" ? "#534AFF" : s.kind === "task" ? "#B2791A" : "var(--mw-text-secondary)";
          const gap = i > 0 ? s.day - steps[i-1].day : null;
          const rule = i > 0 ? RULES[(i - 1) % RULES.length] : null;
          return (
            <React.Fragment key={i}>
              {gap !== null && (
                <div style={{
                  flex: "0 0 auto", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-start",
                  padding: "20px 8px 0", minWidth: 120,
                  animation: `mw-row-in 360ms ${i * 80}ms var(--mw-ease) both`,
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, width: "100%" }}>
                    <div style={{ flex: 1, height: 1, borderTop: "1.5px dashed var(--mw-border-strong)" }} />
                    <div style={{
                      fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)",
                      background: "#fff", padding: "2px 8px", borderRadius: 9999,
                      border: "1px solid var(--mw-border)", whiteSpace: "nowrap",
                    }}>
                      +{gap}d
                    </div>
                    <div style={{ flex: 1, height: 1, borderTop: "1.5px dashed var(--mw-border-strong)" }} />
                  </div>
                  {rule && (
                    <div style={{
                      marginTop: 10,
                      display: "inline-flex", alignItems: "center", gap: 4,
                      padding: "3px 8px", borderRadius: 9999,
                      background: "rgba(83,74,255,.06)", border: "1px dashed rgba(83,74,255,.35)",
                      color: "var(--mw-brand-500)", fontSize: 10, fontWeight: 600,
                      whiteSpace: "nowrap",
                    }}>
                      <Icon name={rule.icon} size={10} color="brand" />
                      AI · {rule.label}
                    </div>
                  )}
                </div>
              )}
              <div style={{
                flex: "0 0 auto", width: 180,
                display: "flex", flexDirection: "column", alignItems: "stretch", gap: 8,
                animation: `mw-row-in 360ms ${i * 80}ms var(--mw-ease) both`,
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: "50%",
                    background: toneBg, color: toneFg,
                    border: isTrigger ? "none" : "1px solid var(--mw-border-strong)",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    boxShadow: isTrigger ? "0 4px 12px rgba(83,74,255,.25)" : "none",
                    flexShrink: 0,
                  }}>
                    <StepKindIcon kind={s.kind} />
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 10, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5 }}>
                      {isTrigger ? "Trigger" : `Day ${s.day}`}
                    </div>
                    <Chip tone={s.kind === "trigger" ? "info" : s.kind === "email" ? "info" : s.kind === "task" ? "warning" : "neutral"} style={{ marginTop: 2 }}>
                      {s.kind}
                    </Chip>
                  </div>
                </div>
                <div style={{
                  background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 12,
                  padding: "10px 12px", boxShadow: "0 1px 2px rgba(64,68,82,.04)",
                }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--mw-text-primary)", lineHeight: 1.3 }}>{s.title}</div>
                  <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 4, lineHeight: 1.4 }}>{s.detail}</div>
                </div>
              </div>
            </React.Fragment>
          );
        })}
        {/* End cap */}
        <div style={{
          flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center",
          padding: "20px 8px 0", minWidth: 100,
        }}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <div style={{
              width: 36, height: 36, borderRadius: "50%", background: "#fff",
              border: "1.5px dashed var(--mw-border-strong)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              color: "var(--mw-text-tertiary)",
            }}>
              <Icon name="check" size={14} opacity={0.6} />
            </div>
            <div style={{ fontSize: 10, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>End</div>
          </div>
        </div>
      </div>
    </div>
  );
};

const RuleRow = ({ r }) => {
  const tone = { skip: "warning", bundle: "info", shift: "info", exit: "neutral" }[r.kind] || "neutral";
  const icon = { skip: "cross", bundle: "layers", shift: "clock", exit: "check" }[r.kind] || "check";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", borderBottom: "1px solid var(--mw-border-soft)" }}>
      <span style={{ width: 28, height: 28, borderRadius: 8, background: "var(--mw-bg)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon name={icon} size={14} opacity={0.7} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: "var(--mw-text-primary)", display: "flex", alignItems: "center", gap: 6 }}>
          {r.text}
          {r.ai && <span style={{ fontSize: 10, fontWeight: 600, color: "var(--mw-brand-500)", padding: "2px 6px", borderRadius: 4, background: "var(--mw-brand-50)" }}>AI</span>}
        </div>
        <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 2 }}>Triggered {r.count} times in last 30 days</div>
      </div>
      <Chip tone={tone}>{r.kind}</Chip>
      <button style={{ width: 28, height: 28, borderRadius: 8, border: "1px solid var(--mw-border)", background: "#fff", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name="pen" size={12} opacity={0.6} />
      </button>
    </div>
  );
};

const DecisionRow = ({ d }) => {
  const kindMap = {
    skip:    { tone: "warning", icon: "cross",  label: "Skipped" },
    bundled: { tone: "info",    icon: "layers", label: "Bundled" },
    shift:   { tone: "info",    icon: "clock",  label: "Shifted" },
    sent:    { tone: "info",   icon: "mail",   label: "Sent" },
    exit:    { tone: "neutral", icon: "check",  label: "Ended" },
  };
  const m = kindMap[d.kind] || kindMap.sent;
  return (
    <div style={{ display: "flex", gap: 10, padding: "10px 0", borderBottom: "1px solid var(--mw-border-soft)" }}>
      <span style={{ width: 24, height: 24, borderRadius: 6, background: "var(--mw-bg)", flexShrink: 0,
                     display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name={m.icon} size={12} opacity={0.7} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <Chip tone={m.tone}>{m.label}</Chip>
          <span style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>{d.at}</span>
        </div>
        <div style={{ fontSize: 12, color: "var(--mw-text-primary)", marginTop: 4 }}>{d.text}</div>
        <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 2, lineHeight: 1.4 }}>{d.reason}</div>
      </div>
    </div>
  );
};

const InstanceRow = ({ j, onOpen }) => {
  const dotColor = {
    Active:    "var(--mw-success)",
    Paused:    "var(--mw-warning)",
    Completed: "var(--mw-text-quaternary)",
  }[j.status];
  return (
    <div onClick={() => onOpen && onOpen(j)} style={{
      display: "grid", gridTemplateColumns: "1fr 100px 110px 100px 110px",
      alignItems: "center", gap: 10, padding: "12px 14px",
      borderBottom: "1px solid var(--mw-border-soft)", cursor: "pointer",
      fontSize: 13,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: dotColor, flexShrink: 0 }} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 500, color: "var(--mw-text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{j.customer}</div>
          <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>{j.quote}</div>
        </div>
      </div>
      <div style={{ color: "var(--mw-text-secondary)", fontVariantNumeric: "tabular-nums" }}>{j.value}</div>
      <div style={{ color: "var(--mw-text-tertiary)" }}>{j.step}</div>
      <div><Chip tone={j.status === "Active" ? "success" : j.status === "Paused" ? "warning" : "neutral"} dot={true}>{j.status}</Chip></div>
      <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{j.next}</div>
    </div>
  );
};

const TemplateDetailPage = ({ template, onBack, onEdit, onOpenInstance }) => {
  const [tab, setTab] = React.useState("Flow");
  const steps = TPL_STEPS[template.id] || TPL_STEPS["tpl-quote"];
  const instances = TPL_INSTANCES[template.id] || [];
  const rules = TPL_RULES[template.id] || TPL_RULES["tpl-quote"];

  return (
    <div data-screen-label={`01c Template — ${template.name}`} style={{ padding: "24px 28px", maxWidth: 1320, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 18 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mw-text-tertiary)", fontSize: 12, marginBottom: 6 }}>
            <span onClick={onBack} style={{ cursor: "pointer" }}>Templates</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span style={{ color: "var(--mw-text-primary)" }}>{template.name}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--mw-brand-50)",
              display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="branch" size={20} color="brand" />
            </span>
            <h1 className="mw-h1" style={{ fontSize: 26, margin: 0 }}>{template.name}</h1>
            <Chip tone={template.status === "Active" ? "success" : "neutral"} dot={template.status === "Active"}>{template.status}</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginTop: 8, display: "flex", gap: 14, flexWrap: "wrap" }}>
            <span>Trigger: <strong style={{ color: "var(--mw-text-primary)" }}>{template.trigger}</strong></span>
            <span>Owner: <strong style={{ color: "var(--mw-text-primary)" }}>{template.owner}</strong></span>
            <span>Edited {template.lastEdited}</span>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
          <Button kind="secondary" icon="clock">Pause</Button>
          <Button kind="secondary" icon="files">Duplicate</Button>
          <Button kind="ai" icon="ai" onClick={onEdit}>Edit with AI</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="mw-card" style={{ padding: 0, marginBottom: 16, display: "grid", gridTemplateColumns: "repeat(5, 1fr)" }}>
        {[
          { l: "Active Instances", v: template.activeCount, tone: "info", icon: "branch" },
          { l: "Completed (all-time)", v: template.completedCount, icon: "check" },
          { l: "Reply Rate", v: `${template.replyRate}%`, icon: "mail" },
          { l: "Accept Rate", v: `${template.acceptRate}%`, icon: "star" },
          { l: "AI Skip Rate", v: "12%", icon: "ai", tone: "ai" },
        ].map((kpi, i) => (
          <div key={i} style={{ padding: "16px 18px", borderRight: i < 4 ? "1px solid var(--mw-border-soft)" : "none" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>
              <Icon name={kpi.icon} size={11} opacity={0.6} color={kpi.tone === "ai" ? "brand" : undefined} />
              {kpi.l}
            </div>
            <div style={{ fontSize: 24, fontWeight: 600,
              color: kpi.tone === "brand" || kpi.tone === "ai" ? "var(--mw-brand-500)" : "var(--mw-text-primary)",
              lineHeight: 1.1, fontVariantNumeric: "tabular-nums" }}>{kpi.v}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 0, borderBottom: "1px solid var(--mw-border)", marginBottom: 18 }}>
        {["Flow", "Rules & Conditions", `Live Instances (${instances.length})`, "Recent Activity"].map((t) => {
          const isActive = tab === t || (t.startsWith("Live") && tab === "Live Instances");
          const key = t.startsWith("Live") ? "Live Instances" : t;
          return (
            <div key={t} onClick={() => setTab(key)} style={{
              padding: "10px 14px", fontSize: 13, fontWeight: 500, cursor: "pointer",
              color: isActive ? "var(--mw-text-primary)" : "var(--mw-text-tertiary)",
              borderBottom: isActive ? "2px solid var(--mw-brand-500)" : "2px solid transparent",
              marginBottom: -1,
            }}>{t}</div>
          );
        })}
      </div>

      {/* Tab content */}
      {tab === "Flow" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div className="mw-card" style={{ padding: 20, overflow: "hidden" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Journey Map</div>
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>Proportional timeline · {steps.length} steps over {Math.max(...steps.map(s=>s.day))} days</div>
            </div>
            <FlowRail steps={steps} />
          </div>
          <div className="mw-card" style={{ padding: 20, alignSelf: "flex-start" }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>AI Behavior</div>
            <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", lineHeight: 1.5, marginBottom: 14 }}>
              This template's automated steps are continuously evaluated against live CRM activity. Steps may be skipped, delayed, or bundled to keep outreach feeling human.
            </div>
            {[
              { icon: "cross",  label: "Skip on recent reply",    on: true },
              { icon: "layers", label: "Bundle same-day outreach", on: true },
              { icon: "clock",  label: "Shift on manual contact",  on: true },
              { icon: "ai",     label: "Tone-match to customer style", on: false },
            ].map((b, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderTop: i ? "1px solid var(--mw-border-soft)" : "none" }}>
                <Icon name={b.icon} size={14} opacity={0.7} color={b.label.includes("Tone") ? "brand" : undefined} />
                <span style={{ flex: 1, fontSize: 13 }}>{b.label}</span>
                <span style={{
                  width: 30, height: 18, borderRadius: 9999, background: b.on ? "var(--mw-brand-500)" : "var(--mw-border-strong)",
                  position: "relative", flexShrink: 0,
                }}>
                  <span style={{
                    position: "absolute", top: 2, left: b.on ? 14 : 2, width: 14, height: 14, borderRadius: "50%",
                    background: "#fff", transition: "left 120ms var(--mw-ease)",
                  }} />
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "Rules & Conditions" && (
        <div className="mw-card" style={{ padding: 0 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", borderBottom: "1px solid var(--mw-border-soft)" }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Skip, Shift, Bundle &amp; Exit Rules</div>
            <Button kind="secondary" icon="plus">Add Rule</Button>
          </div>
          {rules.map((r, i) => <RuleRow key={i} r={r} />)}
        </div>
      )}

      {tab === "Live Instances" && (
        <div className="mw-card" style={{ padding: 0 }}>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 100px 110px 100px 110px", gap: 10,
            padding: "10px 14px", borderBottom: "1px solid var(--mw-border)",
            fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5,
          }}>
            <div>Customer / Quote</div><div>Value</div><div>Progress</div><div>Status</div><div>Next Run</div>
          </div>
          {instances.map((j) => <InstanceRow key={j.id} j={j} onOpen={onOpenInstance} />)}
          {instances.length === 0 && (
            <div style={{ padding: 32, textAlign: "center", fontSize: 13, color: "var(--mw-text-tertiary)" }}>
              No active instances for this template.
            </div>
          )}
        </div>
      )}

      {tab === "Recent Activity" && (
        <div className="mw-card" style={{ padding: "8px 18px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "12px 0", borderBottom: "1px solid var(--mw-border-soft)" }}>
            <AIOrb size={18} />
            <div style={{ fontSize: 13, fontWeight: 600 }}>AI Decisions across all instances</div>
            <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--mw-text-tertiary)" }}>Last 7 days</span>
          </div>
          {RECENT_TPL_DECISIONS.map((d, i) => <DecisionRow key={i} d={d} />)}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { TemplateDetailPage });
