/* Stratum Leads — Operations Console. Auctions: a live monitor for
   marketplace auctions only (no ticket/customer data mixed in). Ops can
   start a simulation, watch bids and the countdown tick in real time, and
   extend or close an auction. Intentionally EPHEMERAL local state — the
   whole simulation resets if you navigate away and back, same as the demo
   phone-call simulation in the Product App. */

/* Design-system components — each Babel script has its own scope, so every
   ops-*.jsx file must destructure what it needs from the namespace. */
const { NavItem, IconButton, WalletPill, Tabs, LeadCard, Button, Field, Card, Metric, StatusChip, TierBadge, ContactQuality, ProgressBar, StrataAmount, Checkbox, Switch, Avatar, AvatarStack, SegmentedControl, GateCard, EmptyState, Toast } = window.StratumLeadsDesignSystem_6367ed;

const { I, fmtStrata, fmtDur } = window.OpsShared;
const ALL_CUSTOMERS = window.STRATUM_OPS.CUSTOMERS;

const AUC_TABS = ["live", "scheduled", "closed", "all"];
const AUC_TAB_LABEL = { live: "Live", scheduled: "Scheduled", closed: "Closed", all: "All" };
const AUC_TONE = { scheduled: "neutral", live: "violet", closed: "success" };

function LiveDot() {
  return <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--danger)", boxShadow: "0 0 0 rgba(220,38,38,0.5)", animation: "sop-livepulse 1.4s ease-out infinite" }} />;
}

function AuctionRow({ a, now, active, onClick }) {
  const left = a.status === "live" ? a.endsAt - now : null;
  return (
    <button onClick={onClick} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", alignItems: "center", gap: 12, width: "100%", textAlign: "left", padding: "12px 14px", border: "none", borderBottom: "1px solid var(--border-subtle)", borderLeft: active ? "3px solid var(--accent)" : "3px solid transparent", background: active ? "var(--accent-soft)" : "var(--surface)", cursor: "pointer" }}>
      <TierBadge tier={a.tier} />
      <span style={{ minWidth: 0 }}>
        <strong style={{ display: "block", fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.address}</strong>
        <span style={{ display: "block", fontSize: 11.5, color: "var(--text-muted)", margin: "2px 0 6px" }}>{a.cityZip}</span>
        <span style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
          <StatusChip tone="neutral">{a.trigger}</StatusChip>
          {a.status === "live" && <span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: left < 300000 ? "var(--danger)" : "var(--text-muted)" }}>{fmtDur(left / 60000)} left</span>}
        </span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 6 }}>
        <StatusChip tone={AUC_TONE[a.status]} dot={a.status === "live"}>{AUC_TAB_LABEL[a.status]}</StatusChip>
        <StrataAmount amount={a.currentBid} size="sm" />
      </span>
    </button>);

}

function AuctionDetail({ auction, now, onStart, onExtend, onClose }) {
  if (!auction) return <Card style={{ height: "100%" }}><EmptyState icon="gavel" title="Select an auction" message="Choose an auction from the list to watch it live or start a simulation." /></Card>;
  const a = auction;
  const left = a.status === "live" ? Math.max(0, a.endsAt - now) : null;

  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", padding: 20, display: "grid", gap: 16, height: "100%", overflowY: "auto", alignContent: "start" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
            <TierBadge tier={a.tier} />
            <strong style={{ fontSize: 18, fontWeight: 800 }}>{a.address}</strong>
            {a.status === "live" && <LiveDot />}
          </div>
          <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{a.cityZip} · {a.county} · {a.trigger}</span>
        </div>
        <StatusChip tone={AUC_TONE[a.status]}>{AUC_TAB_LABEL[a.status]}</StatusChip>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
        <Metric icon={I("coins")} value={fmtStrata(a.currentBid)} label="Current bid" accent="violet" />
        <Metric icon={I("users-round")} value={a.bidders} label="Bidders" accent="cyan" />
        <Metric icon={I("eye")} value={a.watchers} label="Watching" accent="amber" />
        <Metric icon={I("timer")} value={a.status === "live" ? fmtDur(left / 60000) : a.status === "scheduled" ? `${a.durationMinutes}m set` : "Closed"} label={a.status === "live" ? "Time left" : a.status === "scheduled" ? "Duration" : a.closedAt} accent="green" />
      </div>

      {a.status === "closed" &&
      <Card title="Auction result" style={{ boxShadow: "none", background: "var(--success-soft)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
            <span>Winner</span><strong>{a.winner}</strong>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginTop: 6 }}>
            <span>Winning bid</span><StrataAmount amount={a.wonBid} size="sm" />
          </div>
        </Card>
      }

      <Card title="Live bid feed" note={a.status === "scheduled" ? "Not started yet" : `${a.bidHistory.length} bids`}>
        {a.bidHistory.length === 0 ?
        <EmptyState icon="gavel" title="No bids yet" message="Start the simulation to watch bids come in." /> :

        <div style={{ display: "grid", gap: 2, maxHeight: 260, overflowY: "auto" }}>
            {a.bidHistory.map((b, i) =>
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 4px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
                <span style={{ fontSize: 13 }}>{b.bidder}</span>
                <span style={{ display: "flex", gap: 10, alignItems: "center" }}>
                  <StrataAmount amount={b.amount} size="sm" />
                  <span style={{ fontSize: 11, color: "var(--text-muted)", width: 70, textAlign: "right" }}>{b.time}</span>
                </span>
              </div>
          )}
          </div>
        }
      </Card>

      <div style={{ display: "flex", gap: 10 }}>
        {a.status === "scheduled" && <Button variant="primary" icon={I("play", { width: 15 })} onClick={() => onStart(a.id)} fullWidth>Start Simulation</Button>}
        {a.status === "live" &&
        <React.Fragment>
            <Button variant="secondary" icon={I("clock", { width: 14 })} onClick={() => onExtend(a.id)}>Extend +15 min</Button>
            <Button variant="danger" icon={I("square", { width: 14 })} onClick={() => onClose(a.id)}>Close Auction Now</Button>
          </React.Fragment>
        }
      </div>
    </div>);

}

function AuctionsPage() {
  // Local + ephemeral by design: this page's own state, not lifted to the
  // app shell, so navigating away and back always restarts from the seed.
  const [items, setItems] = React.useState(() => window.STRATUM_OPS.AUCTIONS.map((a) => {
    if (a.status === "live") return { ...a, endsAt: Date.now() + (a.endsAtInMinutes || 20) * 60000 };
    return { ...a };
  }));
  const [tab, setTab] = React.useState("live");
  const [selectedId, setSelectedId] = React.useState(null);
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(refresh, [tab, selectedId]);

  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);

  React.useEffect(() => {
    const t = setInterval(() => {
      setItems((prev) => {
        if (!prev.some((a) => a.status === "live")) return prev;
        return prev.map((a) => {
          if (a.status !== "live") return a;
          if (Date.now() >= a.endsAt) {
            const winner = a.bidHistory[0]?.bidder || "Unclaimed";
            return { ...a, status: "closed", winner, wonBid: a.currentBid, closedAt: "Just now" };
          }
          if (Math.random() < 0.3) {
            const bump = a.currentBid + a.bidIncrement + Math.floor(Math.random() * 6);
            const bidder = ALL_CUSTOMERS[Math.floor(Math.random() * ALL_CUSTOMERS.length)].name;
            return { ...a, currentBid: bump, bidders: a.bidders + (Math.random() < 0.6 ? 1 : 0), watchers: a.watchers + (Math.random() < 0.3 ? 1 : 0), bidHistory: [{ bidder, amount: bump, time: "Just now" }, ...a.bidHistory] };
          }
          return a;
        });
      });
    }, 1000);
    return () => clearInterval(t);
  }, []);

  const start = (id) => setItems((prev) => prev.map((a) => a.id === id ? { ...a, status: "live", endsAt: Date.now() + a.durationMinutes * 60000, bidders: Math.max(1, a.bidders), bidHistory: a.bidHistory.length ? a.bidHistory : [{ bidder: "Opening", amount: a.startingBid, time: "Just now" }] } : a));
  const extend = (id) => setItems((prev) => prev.map((a) => a.id === id ? { ...a, endsAt: a.endsAt + 15 * 60000 } : a));
  const closeNow = (id) => setItems((prev) => prev.map((a) => a.id === id ? { ...a, status: "closed", winner: a.bidHistory[0]?.bidder || "Unclaimed", wonBid: a.currentBid, closedAt: "Just now" } : a));

  const rows = tab === "all" ? items : items.filter((a) => a.status === tab);
  const selected = items.find((a) => a.id === selectedId) || rows[0] || null;

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)", height: "calc(100vh - 4px)", display: "flex", flexDirection: "column" }}>
      <style>{"@keyframes sop-livepulse { 0% { box-shadow: 0 0 0 0 rgba(220,38,38,0.55); } 70% { box-shadow: 0 0 0 7px rgba(220,38,38,0); } 100% { box-shadow: 0 0 0 0 rgba(220,38,38,0); } }"}</style>
      <PageHeader eyebrow="Live Marketplace" title="Auctions" description="Watch marketplace auctions live — start a simulation, then watch bids and the clock tick. Resets if you navigate away." />

      <div style={{ marginBottom: 14 }}>
        <Tabs value={tab} onChange={(v) => {setTab(v);setSelectedId(null);}} tabs={AUC_TABS.map((t) => ({ value: t, label: AUC_TAB_LABEL[t], count: t === "all" ? items.length : items.filter((a) => a.status === t).length }))} />
      </div>

      <div style={{ flex: 1, minHeight: 0, display: "grid", gridTemplateColumns: "400px 1fr", gap: 18 }}>
        <div style={{ overflowY: "auto", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)" }}>
          {rows.length === 0 ?
          <EmptyState icon="gavel" title="Nothing here" message="No auctions in this state." /> :

          rows.map((a) => <AuctionRow key={a.id} a={a} now={now} active={selected?.id === a.id} onClick={() => setSelectedId(a.id)} />)
          }
        </div>
        <AuctionDetail auction={selected} now={now} onStart={start} onExtend={extend} onClose={closeNow} />
      </div>
    </div>);

}

Object.assign(window, { OpsAuctions: { AuctionsPage } });
