// Journeys list / index page

const StatusChip = ({ status }) => {
  const map = {
    Active:    { tone: "success", dot: true },
    Paused:    { tone: "warning", dot: true },
    Completed: { tone: "neutral", dot: true },
    Draft:     { tone: "info",    dot: true },
  };
  const m = map[status] || map.Draft;
  return <Chip tone={m.tone} dot={m.dot}>{status}</Chip>;
};

const TemplateBadge = ({ name }) => {
  const colorMap = {
    "Quote Follow-Up": { bg: "#E8E9F6", fg: "#534AFF" },
    "Demo Recovery":   { bg: "#FFE9DC", fg: "#C0691A" },
    "Renewal Nudge":   { bg: "#DAF0E0", fg: "#22863A" },
    "Lead Activation": { bg: "#F0E8FF", fg: "#7B3DCC" },
  };
  const c = colorMap[name] || { bg: "#F1F2F4", fg: "#6A7383" };
  return (
    <span style={{
      fontSize: 12, fontWeight: 500, padding: "3px 8px", borderRadius: 6,
      background: c.bg, color: c.fg, whiteSpace: "nowrap",
    }}>{name}</span>
  );
};

const SparkRail = ({ state }) => {
  // 5 dots representing journey progress with appropriate semantics
  // state determines fills
  const fills = {
    fresh:    ["done", "now",  "next", "next", "next"],
    midflight:["done", "done", "skip", "shift","next"],
    paused:   ["done", "done", "pause","pause","pause"],
    ended:    ["done", "done", "exit", "exit", "exit"],
  }[state] || ["next","next","next","next","next"];
  const colorOf = (f) => ({
    done:  "var(--mw-brand-500)",
    now:   "var(--mw-brand-500)",
    next:  "#D5DBE1",
    skip:  "#A3ACBA",
    shift: "var(--mw-warning)",
    pause: "var(--mw-warning)",
    exit:  "var(--mw-success)",
  })[f];
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
      {fills.map((f, i) => (
        <React.Fragment key={i}>
          <span style={{
            width: f === "now" ? 9 : 7, height: f === "now" ? 9 : 7, borderRadius: "50%",
            background: f === "next" ? "#fff" : colorOf(f),
            border: f === "next" ? "1.5px solid #D5DBE1" : f === "skip" ? "1.5px solid #A3ACBA" : "0",
            boxShadow: f === "now" ? "0 0 0 3px rgba(83,74,255,.18)" : "none",
            position: "relative",
          }} />
          {i < fills.length - 1 && (
            <span style={{
              width: 14, height: 1.5,
              background: f === "skip" || fills[i+1] === "skip" ? "repeating-linear-gradient(90deg,#A3ACBA 0 3px,transparent 3px 6px)" : "#E3E5E8",
            }} />
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

const JourneysListPage = ({ onOpen, onNew, list }) => {
  const [filter, setFilter] = React.useState("All");
  const filters = ["All", "Active", "Paused", "Completed"];
  const filtered = list.filter((j) => filter === "All" ? true : j.status === filter);

  return (
    <div data-screen-label="01 Active Journeys" style={{ padding: "24px 28px", maxWidth: 1320, margin: "0 auto" }}>
      {/* Title row */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 6 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mw-text-tertiary)", fontSize: 12, marginBottom: 4 }}>
            <span>Sales</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>Journeys</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>Active</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 className="mw-h1" style={{ fontSize: 26 }}>Active Journeys</h1>
            <Chip tone="info">{list.filter((j) => j.status === "Active").length} running</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginTop: 6 }}>
            Live instances of automations tied to specific quotes, opportunities, and customers.
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button icon="filter">Filter</Button>
          <Button icon="sort">Sort</Button>
          <Button icon="layers" onClick={onNew}>Browse Templates</Button>
        </div>
      </div>

      {/* Summary cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, margin: "20px 0 18px" }}>
        {[
          { label: "Active Journeys", value: 16, sub: "+3 this week", tone: "brand" },
          { label: "Customers in Flow", value: 47, sub: "across 6 templates" },
          { label: "AI Decisions Today", value: 28, sub: "21 sent · 5 skipped · 2 shifted", tone: "ai" },
          { label: "Avg. Reply Time", value: "3.2d", sub: "−18% vs last month", tone: "good" },
        ].map((s, i) => (
          <div key={i} className="mw-card" style={{ padding: 16, position: "relative", overflow: "hidden" }}>
            {s.tone === "ai" && (
              <div style={{ position: "absolute", inset: 0, background:
                "radial-gradient(120% 80% at 100% 0%, rgba(123,200,255,.12), transparent 60%)", pointerEvents: "none" }} />
            )}
            <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", fontWeight: 500, display: "flex", alignItems: "center", gap: 6 }}>
              {s.tone === "ai" && <AIOrb size={14} />}
              {s.label}
            </div>
            <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", margin: "6px 0 2px", color: s.tone === "brand" ? "var(--mw-brand-500)" : "var(--mw-text-primary)" }}>
              {s.value}
            </div>
            <div style={{ fontSize: 12, color: s.tone === "good" ? "var(--mw-success)" : "var(--mw-text-tertiary)" }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Filter pills */}
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 12 }}>
        {filters.map((f) => (
          <button key={f}
            onClick={() => setFilter(f)}
            className={`mw-nav-tab ${filter === f ? "active" : ""}`}
            style={{ fontSize: 13 }}>
            {f}
            {f !== "All" && (
              <span style={{ fontSize: 11, color: filter === f ? "var(--mw-brand-500)" : "var(--mw-text-tertiary)", marginLeft: 2 }}>
                {list.filter((j) => j.status === f).length}
              </span>
            )}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <div style={{ position: "relative", width: 240 }}>
          <Icon name="search" size={14} style={{ position: "absolute", left: 10, top: 9, opacity: 0.5 }} />
          <input className="mw-input" placeholder="Search journeys…"
                 style={{ width: "100%", height: 30, paddingLeft: 30, fontSize: 13 }} />
        </div>
      </div>

      {/* Table */}
      <div className="mw-card" style={{ overflow: "hidden" }}>
        <table className="mw-table" style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr>
              <th style={{ width: 36 }}><input type="checkbox" /></th>
              <th>Journey</th>
              <th>Customer</th>
              <th>Template</th>
              <th>Status</th>
              <th>Progress</th>
              <th>Next Action</th>
              <th>Owner</th>
              <th>Value</th>
              <th style={{ width: 36 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((j, i) => (
              <tr key={j.id} onClick={() => onOpen(j)} style={{ animation: `mw-row-in 280ms ${i * 30}ms var(--mw-ease) both` }}>
                <td><input type="checkbox" onClick={(e) => e.stopPropagation()} /></td>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <StepIcon kind="trigger" status="done" size={26} />
                    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                      <span style={{ fontWeight: 500, fontSize: 14 }}>{j.name}</span>
                      <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>Trigger: Quote Sent · 5 steps</span>
                    </div>
                  </div>
                </td>
                <td><span style={{ fontWeight: 500 }}>{j.customer}</span></td>
                <td><TemplateBadge name={j.template} /></td>
                <td><StatusChip status={j.status} /></td>
                <td>
                  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                    <SparkRail state={j.state} />
                    <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>Step {j.step}</span>
                  </div>
                </td>
                <td>
                  <span style={{ fontSize: 13 }}>{j.nextRun}</span>
                </td>
                <td><Avatar initials={j.owner} color={j.owner === "MI" ? "#FF9143" : "#76ADFF"} size={26} /></td>
                <td><span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>{j.value}</span></td>
                <td>
                  <button style={{ width: 26, height: 26, borderRadius: 6, border: 0, background: "transparent", cursor: "pointer" }}
                          onClick={(e) => e.stopPropagation()}>
                    <Icon name="more" size={16} opacity={0.6} />
                  </button>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={10} style={{ padding: 48, textAlign: "center", color: "var(--mw-text-tertiary)" }}>
                No journeys match this filter.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const TplViewToggle = ({ view, onChange }) => {
  const Btn = ({ kind, children }) => (
    <button onClick={() => onChange(kind)} style={{
      width: 32, height: 28, padding: 0, border: "none", cursor: "pointer",
      background: view === kind ? "#fff" : "transparent",
      color: view === kind ? "var(--mw-text-primary)" : "var(--mw-text-tertiary)",
      boxShadow: view === kind ? "0 1px 2px rgba(64,68,82,.12)" : "none",
      borderRadius: 6, display: "inline-flex", alignItems: "center", justifyContent: "center",
      transition: "all 120ms var(--mw-ease)",
    }} title={kind === "list" ? "List View" : "Card View"}>
      {children}
    </button>
  );
  return (
    <div style={{ display: "inline-flex", padding: 3, background: "var(--mw-bg)", borderRadius: 8, border: "1px solid var(--mw-border-soft)" }}>
      <Btn kind="list">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
          <line x1="5" y1="4" x2="14" y2="4" /><line x1="5" y1="8" x2="14" y2="8" /><line x1="5" y1="12" x2="14" y2="12" />
          <circle cx="2.5" cy="4" r="0.8" fill="currentColor" stroke="none" />
          <circle cx="2.5" cy="8" r="0.8" fill="currentColor" stroke="none" />
          <circle cx="2.5" cy="12" r="0.8" fill="currentColor" stroke="none" />
        </svg>
      </Btn>
      <Btn kind="card">
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
          <rect x="2" y="2" width="5" height="5" rx="1" /><rect x="9" y="2" width="5" height="5" rx="1" />
          <rect x="2" y="9" width="5" height="5" rx="1" /><rect x="9" y="9" width="5" height="5" rx="1" />
        </svg>
      </Btn>
    </div>
  );
};

const TemplatesListPage = ({ onNew, onOpen }) => {
  const [view, setView] = React.useState("list");
  return (
    <div data-screen-label="01b Templates" style={{ padding: "24px 28px", maxWidth: 1320, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 6 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mw-text-tertiary)", fontSize: 12, marginBottom: 4 }}>
            <span>Sales</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>Journeys</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>Templates</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 className="mw-h1" style={{ fontSize: 26 }}>Templates</h1>
            <Chip tone="neutral">{TEMPLATES.length}</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginTop: 6 }}>
            Reusable automation definitions. Each template can have many live instances running on quotes, leads, or customers.
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <TplViewToggle view={view} onChange={setView} />
          <Button kind="ai" icon="ai" onClick={onNew}>New Template with AI</Button>
        </div>
      </div>

      {view === "list" && (
        <div className="mw-card" style={{ padding: 0, marginTop: 18 }}>
          <div style={{
            display: "grid", gridTemplateColumns: "minmax(220px, 1.4fr) 1.6fr 90px 110px 100px 100px 90px",
            gap: 12, padding: "10px 16px", borderBottom: "1px solid var(--mw-border)",
            fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5,
          }}>
            <div>Template</div><div>Trigger</div><div>Status</div><div>Active</div><div>Steps</div><div>Reply Rate</div><div>Owner</div>
          </div>
          {TEMPLATES.map((tpl, i) => (
            <div key={tpl.id} onClick={() => onOpen && onOpen(tpl)}
                 className="mw-row" style={{
              display: "grid", gridTemplateColumns: "minmax(220px, 1.4fr) 1.6fr 90px 110px 100px 100px 90px",
              gap: 12, padding: "12px 16px", borderBottom: i < TEMPLATES.length - 1 ? "1px solid var(--mw-border-soft)" : "none",
              cursor: "pointer", alignItems: "center", fontSize: 13,
              animation: `mw-row-in 220ms ${i * 30}ms var(--mw-ease) both`,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                <span style={{ width: 28, height: 28, borderRadius: 8, background: "var(--mw-brand-50)", flexShrink: 0,
                  display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="branch" size={14} color="brand" />
                </span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 500, color: "var(--mw-text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{tpl.name}</div>
                  <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{tpl.description}</div>
                </div>
              </div>
              <div style={{ color: "var(--mw-text-secondary)", fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{tpl.trigger}</div>
              <div><Chip tone={tpl.status === "Active" ? "success" : "neutral"} dot={tpl.status === "Active"}>{tpl.status}</Chip></div>
              <div style={{ color: "var(--mw-brand-500)", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{tpl.activeCount}</div>
              <div style={{ color: "var(--mw-text-secondary)", fontVariantNumeric: "tabular-nums" }}>{tpl.steps}</div>
              <div style={{ color: "var(--mw-text-secondary)", fontVariantNumeric: "tabular-nums" }}>{tpl.replyRate}%</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <Avatar initials={tpl.ownerInitials} color={tpl.ownerColor} size={20} />
              </div>
            </div>
          ))}
        </div>
      )}

      {view === "card" && (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14, marginTop: 18 }}>
        {TEMPLATES.map((tpl, i) => (
          <div key={tpl.id} className="mw-card"
               onClick={() => onOpen && onOpen(tpl)}
               style={{ padding: 20, cursor: "pointer", animation: `mw-row-in 280ms ${i * 40}ms var(--mw-ease) both`,
                        display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ width: 36, height: 36, borderRadius: 10, background: "var(--mw-brand-50)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="branch" size={18} color="brand" />
                </span>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600 }}>{tpl.name}</div>
                  <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 2 }}>
                    Trigger: {tpl.trigger}
                  </div>
                </div>
              </div>
              <Chip tone={tpl.status === "Active" ? "success" : "neutral"} dot={tpl.status === "Active"}>{tpl.status}</Chip>
            </div>
            <div style={{ fontSize: 13, color: "var(--mw-text-secondary)", lineHeight: 1.5 }}>{tpl.description}</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10,
              padding: "12px 0", borderTop: "1px solid var(--mw-border-soft)", borderBottom: "1px solid var(--mw-border-soft)" }}>
              {[
                { l: "Steps", v: tpl.steps },
                { l: "Conditions", v: tpl.conditions },
                { l: "Active", v: tpl.activeCount, tone: "brand" },
                { l: "Reply rate", v: `${tpl.replyRate}%` },
              ].map((s, k) => (
                <div key={k}>
                  <div style={{ fontSize: 18, fontWeight: 600, color: s.tone === "brand" ? "var(--mw-brand-500)" : "var(--mw-text-primary)", lineHeight: 1.1, fontVariantNumeric: "tabular-nums" }}>{s.v}</div>
                  <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 2 }}>{s.l}</div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {tpl.topRules.slice(0, 2).map((r, k) => (
                <div key={k} style={{ fontSize: 12, color: "var(--mw-text-secondary)", display: "flex", gap: 6, alignItems: "center" }}>
                  <Icon name="check" size={12} opacity={0.5} /> {r}
                </div>
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 2 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <Avatar initials={tpl.ownerInitials} color={tpl.ownerColor} size={20} />
                <span style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>{tpl.owner} · edited {tpl.lastEdited}</span>
              </div>
              <span style={{ fontSize: 12, color: "var(--mw-brand-500)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4 }}>
                Open <Icon name="chevronRight" size={12} color="brand" />
              </span>
            </div>
          </div>
        ))}
      </div>
      )}
    </div>
  );
};

Object.assign(window, { JourneysListPage, TemplatesListPage });