// Opportunities List Page

const OPPS = [
  { id: "OPP-4821", name: "Plant 4 Conveyor Refit",    customer: "Acme Industrial",     contact: "Jenna Park",   stage: "Quoted",       amount: 184500, prob: 70, close: "May 28, 2026", owner: { initials: "NM", color: "#76ADFF" }, quotes: 2, journey: "Quote Follow-Up", health: "warm", lastActivity: "2 hrs ago" },
  { id: "OPP-4799", name: "Fleet Telematics Rollout",  customer: "Northwave Logistics", contact: "Marcus Lee",   stage: "Negotiation",  amount: 312800, prob: 60, close: "Jun 15, 2026", owner: { initials: "NM", color: "#76ADFF" }, quotes: 3, journey: "Quote Follow-Up", health: "hot",  lastActivity: "Yesterday" },
  { id: "OPP-4815", name: "Warehouse 2 Lift Upgrade",  customer: "Acme Industrial",     contact: "Jenna Park",   stage: "Quoted",       amount: 56200,  prob: 55, close: "Jun 02, 2026", owner: { initials: "NM", color: "#76ADFF" }, quotes: 1, journey: "Quote Follow-Up", health: "warm", lastActivity: "3 days ago" },
  { id: "OPP-4762", name: "Cold Storage Retrofit",     customer: "Orbital Foods",       contact: "Priya Shah",   stage: "Closed Won",   amount: 250400, prob: 100,close: "Apr 28, 2026", owner: { initials: "KN", color: "#7B3DCC" }, quotes: 3, journey: "—",                health: "won",  lastActivity: "Apr 28" },
  { id: "OPP-4803", name: "Yard Cameras Phase 2",      customer: "Northwave Logistics", contact: "Marcus Lee",   stage: "Discovery",    amount: 31200,  prob: 30, close: "Jul 10, 2026", owner: { initials: "DC", color: "#22863A" }, quotes: 0, journey: "Lead Nurturing",   health: "cool", lastActivity: "5 days ago" },
  { id: "OPP-4831", name: "Press Line Service",        customer: "Helix Manufacturing", contact: "Devon Cruz",   stage: "Proposal",     amount: 18900,  prob: 45, close: "Jun 04, 2026", owner: { initials: "DC", color: "#22863A" }, quotes: 1, journey: "Quote Follow-Up", health: "warm", lastActivity: "18 min ago" },
  { id: "OPP-4744", name: "Annual Lubricant Supply",   customer: "Acme Industrial",     contact: "Jenna Park",   stage: "Quoted",       amount: 9400,   prob: 65, close: "May 18, 2026", owner: { initials: "NM", color: "#76ADFF" }, quotes: 1, journey: "Quote Follow-Up", health: "warm", lastActivity: "Today" },
  { id: "OPP-4691", name: "Sanitation Supplies Q3",    customer: "Orbital Foods",       contact: "Priya Shah",   stage: "Closed Won",   amount: 14750,  prob: 100,close: "Apr 28, 2026", owner: { initials: "KN", color: "#7B3DCC" }, quotes: 1, journey: "—",                health: "won",  lastActivity: "Apr 28" },
  { id: "OPP-4858", name: "Driver Training Modules",   customer: "Northwave Logistics", contact: "Marcus Lee",   stage: "Quoted",       amount: 22400,  prob: 50, close: "Jun 22, 2026", owner: { initials: "NM", color: "#76ADFF" }, quotes: 1, journey: "Quote Follow-Up", health: "warm", lastActivity: "Yesterday" },
  { id: "OPP-4612", name: "Compressor Replacement",    customer: "Tannin Brewing",      contact: "Sam Ortega",   stage: "Closed Lost",  amount: 78000,  prob: 0,  close: "Apr 12, 2026", owner: { initials: "DC", color: "#22863A" }, quotes: 2, journey: "—",                health: "lost", lastActivity: "Apr 12" },
];

const STAGE_META = {
  "Discovery":     { tone: "info",     step: 1 },
  "Proposal":      { tone: "info",     step: 2 },
  "Quoted":        { tone: "info",     step: 3 },
  "Negotiation":   { tone: "warning",  step: 4 },
  "Closed Won":    { tone: "success",  step: 5 },
  "Closed Lost":   { tone: "neutral",  step: 5 },
};

const HEALTH_META = {
  hot:  { color: "#C02F32", label: "Hot" },
  warm: { color: "#C0691A", label: "Warm" },
  cool: { color: "#3B7FFF", label: "Cool" },
  won:  { color: "#22863A", label: "Won" },
  lost: { color: "#6A7383", label: "Lost" },
};

const StageProgress = ({ stage }) => {
  const m = STAGE_META[stage] || STAGE_META["Discovery"];
  const isLost = stage === "Closed Lost";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 2 }}>
        {[1, 2, 3, 4, 5].map((i) => (
          <span key={i} style={{
            width: 14, height: 4, borderRadius: 2,
            background: i <= m.step ? (isLost ? "#A3ACBA" : i === 5 ? "var(--mw-success)" : "var(--mw-brand-500)") : "#E5E7EB",
          }} />
        ))}
      </div>
      <span style={{ fontSize: 12, color: "var(--mw-text-secondary)", fontWeight: 500, minWidth: 90 }}>{stage}</span>
    </div>
  );
};

const OpportunitiesListPage = () => {
  const [view, setView] = React.useState("list"); // list | kanban
  const [stage, setStage] = React.useState("all");
  const [search, setSearch] = React.useState("");

  let filtered = OPPS;
  if (stage !== "all") filtered = filtered.filter((o) => o.stage === stage);
  if (search) {
    const s = search.toLowerCase();
    filtered = filtered.filter((o) =>
      o.name.toLowerCase().includes(s) || o.customer.toLowerCase().includes(s) || o.id.toLowerCase().includes(s)
    );
  }

  const totals = {
    pipeline:  OPPS.filter((o) => !o.stage.startsWith("Closed")).reduce((s, o) => s + o.amount, 0),
    won30:     OPPS.filter((o) => o.stage === "Closed Won").reduce((s, o) => s + o.amount, 0),
    weighted:  OPPS.filter((o) => !o.stage.startsWith("Closed")).reduce((s, o) => s + o.amount * o.prob / 100, 0),
    quotes:    OPPS.reduce((s, o) => s + o.quotes, 0),
  };

  const stages = ["all", "Discovery", "Proposal", "Quoted", "Negotiation", "Closed Won", "Closed Lost"];

  return (
    <div data-screen-label="03 Opportunities" style={{ padding: "24px 28px" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", display: "flex", alignItems: "center", gap: 6 }}>
            <span>Sales</span>
            <Icon name="chevronRight" size={12} opacity={0.5} />
            <span>Opportunities</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6 }}>
            <h1 className="mw-h1" style={{ fontSize: 26, margin: 0 }}>Opportunities</h1>
            <Chip tone="info">{OPPS.length} total</Chip>
          </div>
          <div style={{ fontSize: 13, color: "var(--mw-text-tertiary)", marginTop: 6 }}>
            Track open deals across stages, see related quotes and active follow-up journeys at a glance.
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button kind="secondary" icon="download">Export</Button>
          <Button kind="primary" icon="plus">New Opportunity</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 18 }}>
        {[
          { l: "Open Pipeline", v: "$" + (totals.pipeline / 1000).toFixed(0) + "k", tone: "info",    icon: "branch" },
          { l: "Weighted Forecast", v: "$" + (totals.weighted / 1000).toFixed(0) + "k", tone: "info",    icon: "calculator" },
          { l: "Closed Won (30d)", v: "$" + (totals.won30 / 1000).toFixed(0) + "k", tone: "success", icon: "check" },
          { l: "Active Quotes", v: totals.quotes, tone: "warning", icon: "files" },
        ].map((s, i) => (
          <div key={i} className="mw-card" style={{ padding: 14, display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{
              width: 32, height: 32, borderRadius: 8, flexShrink: 0,
              background: s.tone === "success" ? "#DAF0E0" : s.tone === "warning" ? "#FFF9E0" : "#E8E9F6",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
              <Icon name={s.icon} size={16} opacity={0.7} />
            </span>
            <div>
              <div style={{ fontSize: 22, fontWeight: 600, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{s.v}</div>
              <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 4, textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>{s.l}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Filter bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ position: "relative", width: 280 }}>
          <Icon name="search" size={14} style={{ position: "absolute", left: 10, top: 8, opacity: 0.5 }} />
          <input className="mw-input" placeholder="Search opportunities…"
                 value={search} onChange={(e) => setSearch(e.target.value)}
                 style={{ width: "100%", paddingLeft: 32, height: 30 }} />
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {stages.map((s) => (
            <button key={s} onClick={() => setStage(s)} style={{
              padding: "5px 10px", fontSize: 12, borderRadius: 9999,
              border: stage === s ? "1px solid var(--mw-brand-500)" : "1px solid var(--mw-border)",
              background: stage === s ? "var(--mw-brand-50)" : "#fff",
              color: stage === s ? "var(--mw-brand-500)" : "var(--mw-text-secondary)",
              cursor: "pointer", fontWeight: 500,
            }}>{s === "all" ? `All (${OPPS.length})` : `${s} (${OPPS.filter((o) => o.stage === s).length})`}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", border: "1px solid var(--mw-border)", borderRadius: 8, overflow: "hidden" }}>
          {[
            { id: "list", icon: "list", label: "List" },
            { id: "kanban", icon: "layers", label: "Kanban" },
          ].map((v) => (
            <button key={v.id} onClick={() => setView(v.id)} style={{
              padding: "5px 10px", fontSize: 12, fontWeight: 500,
              background: view === v.id ? "var(--mw-brand-50)" : "#fff",
              color: view === v.id ? "var(--mw-brand-500)" : "var(--mw-text-secondary)",
              border: 0, cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 5,
            }}>
              <Icon name={v.icon} size={12} color={view === v.id ? "brand" : null} />
              {v.label}
            </button>
          ))}
        </div>
      </div>

      {view === "list" && (
        <div className="mw-card" style={{ padding: 0, overflow: "hidden" }}>
          <table className="mw-table">
            <thead>
              <tr>
                <th style={{ width: 28 }}><input type="checkbox" /></th>
                <th>Opportunity</th>
                <th>Customer / Contact</th>
                <th>Stage</th>
                <th style={{ textAlign: "right" }}>Amount</th>
                <th style={{ textAlign: "right" }}>Prob.</th>
                <th>Close Date</th>
                <th>Journey</th>
                <th>Owner</th>
                <th style={{ width: 32 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((o, i) => (
                <tr key={o.id} style={{ animation: `mw-row-in 240ms ${i * 25}ms var(--mw-ease) both`, cursor: "pointer" }}>
                  <td><input type="checkbox" onClick={(e) => e.stopPropagation()} /></td>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 6, height: 28, borderRadius: 3, background: HEALTH_META[o.health].color, flexShrink: 0 }} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--mw-text-primary)" }}>{o.name}</div>
                        <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", fontFamily: "var(--mw-font-mono)" }}>{o.id} · {o.quotes} quote{o.quotes !== 1 ? "s" : ""} · {o.lastActivity}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div style={{ fontSize: 13, color: "var(--mw-text-secondary)" }}>{o.customer}</div>
                    <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)" }}>{o.contact}</div>
                  </td>
                  <td><StageProgress stage={o.stage} /></td>
                  <td style={{ textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>
                    ${o.amount.toLocaleString("en-US")}
                  </td>
                  <td style={{ textAlign: "right" }}>
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <div style={{ width: 36, height: 4, borderRadius: 2, background: "#E5E7EB", overflow: "hidden" }}>
                        <div style={{ width: `${o.prob}%`, height: "100%", background: o.prob === 100 ? "var(--mw-success)" : o.prob === 0 ? "#A3ACBA" : "var(--mw-brand-500)" }} />
                      </div>
                      <span style={{ fontSize: 12, color: "var(--mw-text-secondary)", fontVariantNumeric: "tabular-nums", width: 30 }}>{o.prob}%</span>
                    </div>
                  </td>
                  <td><span style={{ fontSize: 12, color: "var(--mw-text-secondary)" }}>{o.close}</span></td>
                  <td>
                    {o.journey === "—"
                      ? <span style={{ fontSize: 12, color: "var(--mw-text-quaternary)" }}>—</span>
                      : <span style={{
                          display: "inline-flex", alignItems: "center", gap: 4,
                          padding: "2px 8px", borderRadius: 6, fontSize: 11, fontWeight: 500,
                          background: "rgba(83,74,255,.08)", color: "var(--mw-brand-500)",
                        }}>
                          <Icon name="branch" size={10} color="brand" />
                          {o.journey}
                        </span>}
                  </td>
                  <td><Avatar initials={o.owner.initials} color={o.owner.color} size={24} /></td>
                  <td><Icon name="more" size={14} opacity={0.5} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {view === "kanban" && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
          {["Discovery", "Proposal", "Quoted", "Negotiation", "Closed Won"].map((st) => {
            const items = OPPS.filter((o) => o.stage === st);
            const sum = items.reduce((s, o) => s + o.amount, 0);
            return (
              <div key={st} style={{ background: "var(--mw-bg)", borderRadius: 10, padding: 10, minHeight: 320 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "2px 6px 10px" }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "var(--mw-text-secondary)" }}>{st}</div>
                    <div style={{ fontSize: 10, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 600 }}>{items.length} · ${(sum / 1000).toFixed(0)}k</div>
                  </div>
                  <Icon name="plus" size={12} opacity={0.6} />
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {items.map((o, i) => (
                    <div key={o.id} className="mw-card" style={{ padding: 10, animation: `mw-row-in 240ms ${i * 30}ms var(--mw-ease) both`, cursor: "pointer" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: HEALTH_META[o.health].color }} />
                        <span style={{ fontSize: 10, color: "var(--mw-text-tertiary)", fontFamily: "var(--mw-font-mono)" }}>{o.id}</span>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.3 }}>{o.name}</div>
                      <div style={{ fontSize: 11, color: "var(--mw-text-tertiary)", marginTop: 2 }}>{o.customer}</div>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>${(o.amount / 1000).toFixed(0)}k</span>
                        <Avatar initials={o.owner.initials} color={o.owner.color} size={20} />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { OpportunitiesListPage });
