/* Relay — shared UI components */
const { PLATFORMS, STATUS, FLOW_LABELS } = window.RelayData;

// ---------- helpers ----------
function fmtMoney(n) {
  return n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function minsAgo(ts, now) {
  return Math.max(0, Math.floor((now - ts) / 60000));
}
function timeAgo(ts, now) {
  const m = minsAgo(ts, now);
  if (m < 1) return "şimdi";
  if (m < 60) return m + " dk önce";
  const h = Math.floor(m / 60);
  return h + "sa " + (m % 60) + "dk önce";
}
function clockTime(ts) {
  return new Date(ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
}
function itemCount(o) { return o.items.reduce((s, it) => s + it.qty, 0); }

// ---------- atoms ----------
function PlatformBadge({ pid, withName, size = 26 }) {
  const p = PLATFORMS[pid];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, minWidth: 0 }}>
      <span style={{
        width: size, height: size, borderRadius: 6, background: p.color, color: "#fff",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--mono)", fontWeight: 600, fontSize: size * 0.42, flexShrink: 0,
        letterSpacing: ".02em",
      }}>{p.short}</span>
      {withName && <span style={{ fontWeight: 600, fontSize: 13, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</span>}
    </span>
  );
}

// Prep timer: counts elapsed since accepted; flags late vs prepMins target
function StatusPill({ status, type }) {
  const s = STATUS[status];
  const label = type ? FLOW_LABELS[type][status] || s.label : s.label;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      background: `var(--${status}-bg)`, color: `var(--${status})`,
      fontSize: 11.5, fontWeight: 600, padding: "3px 9px 3px 7px", borderRadius: 999,
      whiteSpace: "nowrap", letterSpacing: ".01em",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: `var(--${status})` }} />
      {label}
    </span>
  );
}

function TypeIcon({ type, size = 14 }) {
  return (
    <span title={type === "food" ? "Yemek siparişi" : "Perakende sipariş"} style={{ color: "var(--text-3)", display: "inline-flex" }}>
      {type === "food" ? <I.utensils size={size} /> : <I.package size={size} />}
    </span>
  );
}

function PrepTimer({ order, now, compact }) {
  if (order.status === "completed" || order.status === "cancelled") return null;
  const base = order.acceptedAt || order.placedAt;
  const elapsedMs = Math.max(0, now - base);
  const elapsedMin = Math.floor(elapsedMs / 60000);
  const elapsedSec = Math.floor(elapsedMs / 1000) % 60;
  const late = elapsedMin >= order.prepMins;
  const color = late ? "var(--cancelled)" : order.status === "new" ? "var(--new)" : "var(--text-2)";
  const mm = String(elapsedMin).padStart(2, "0");
  const ss = String(elapsedSec).padStart(2, "0");
  return (
    <span className="mono" style={{
      display: "inline-flex", alignItems: "center", gap: 5, color, fontWeight: 600,
      fontSize: compact ? 12 : 13,
    }}>
      <I.clock size={compact ? 12 : 13} />
      {mm}:{ss}
      {late && !compact && <span style={{ fontSize: 10.5, fontWeight: 600 }}>GECİKTİ</span>}
    </span>
  );
}

function Btn({ kind = "default", children, onClick, small, full, style, title }) {
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
    fontFamily: "var(--font)", fontWeight: 600, fontSize: small ? 12.5 : 13.5,
    padding: small ? "6px 11px" : "9px 14px", borderRadius: "var(--radius-sm)",
    border: "1px solid transparent", width: full ? "100%" : "auto", transition: "all .12s ease",
    whiteSpace: "nowrap", ...style,
  };
  const kinds = {
    default: { background: "var(--surface)", color: "var(--text)", borderColor: "var(--border-strong)" },
    primary: { background: "var(--graphite)", color: "#fff" },
    accept: { background: "var(--ready)", color: "#fff" },
    reject: { background: "var(--surface)", color: "var(--cancelled)", borderColor: "#f0c9c9" },
    ghost: { background: "transparent", color: "var(--text-2)" },
  };
  return (
    <button title={title} onClick={(e) => { e.stopPropagation(); onClick && onClick(e); }}
      onMouseEnter={(e) => { e.currentTarget.style.filter = "brightness(.96)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.filter = "none"; }}
      style={{ ...base, ...kinds[kind] }}>
      {children}
    </button>
  );
}

// next-step CTA based on status
function actionFor(order) {
  const f = FLOW_LABELS[order.type];
  switch (order.status) {
    case "preparing": return { to: "ready", label: f.readyCta };
    case "ready": return { to: "completed", label: f.doneCta };
    default: return null;
  }
}

// ---------- Order Card (grid + kanban) ----------
function OrderCard({ order, now, onOpen, onAccept, onReject, onAdvance, dense }) {
  const isNew = order.status === "new";
  const act = actionFor(order);
  const shown = order.items.slice(0, dense ? 2 : 3);
  const extra = order.items.length - shown.length;
  return (
    <div onClick={() => onOpen(order)} className={order._flash ? "flash-new" : ""}
      style={{
        background: "var(--surface)", border: "1px solid var(--border)",
        borderLeft: `3px solid ${isNew ? "var(--new)" : "transparent"}`,
        borderRadius: "var(--radius)", padding: dense ? "11px 13px" : "13px 15px",
        boxShadow: "var(--shadow-sm)", cursor: "pointer", transition: "box-shadow .12s, transform .12s",
        display: "flex", flexDirection: "column", gap: dense ? 8 : 10,
        animation: isNew ? "pulseRing 2.2s ease-out 1" : "none",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = "var(--shadow-md)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = "var(--shadow-sm)"; e.currentTarget.style.transform = "none"; }}>
      {/* header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <span style={{ flex: 1, minWidth: 0, display: "flex" }}><PlatformBadge pid={order.platformId} withName size={24} /></span>
        <span className="mono" style={{ fontSize: 11.5, color: "var(--text-3)", fontWeight: 500, whiteSpace: "nowrap", flexShrink: 0 }}>{order.channelRef}</span>
      </div>
      {/* customer + meta */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{order.customer}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--text-3)", fontSize: 12, marginTop: 2 }}>
            <TypeIcon type={order.type} />
            <span>{order.fulfillment}</span>
            <span style={{ color: "var(--border-strong)" }}>·</span>
            <span>{order.area}</span>
          </div>
        </div>
        {isNew ? <PrepTimer order={order} now={now} compact /> : <StatusPill status={order.status} type={order.type} />}
      </div>
      {/* items */}
      <div style={{ display: "flex", flexDirection: "column", gap: 3, borderTop: "1px dashed var(--border)", paddingTop: dense ? 7 : 9 }}>
        {shown.map((it, i) => (
          <div key={i} style={{ display: "flex", gap: 8, fontSize: 12.5, color: "var(--text-2)" }}>
            <span className="mono" style={{ color: "var(--text)", fontWeight: 600, minWidth: 22 }}>{it.qty}×</span>
            <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.name}</span>
          </div>
        ))}
        {extra > 0 && <div style={{ fontSize: 12, color: "var(--text-3)", paddingLeft: 30 }}>+{extra} ürün daha</div>}
      </div>
      {/* footer */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginTop: 2 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, minWidth: 0 }}>
          <span className="mono" style={{ fontWeight: 600, fontSize: 15, whiteSpace: "nowrap" }}>{order.currency} {fmtMoney(order.total)}</span>
          <span style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap" }}>{timeAgo(order.placedAt, now)}</span>
        </div>
        {!isNew && !act && order.status === "completed" && <PrepTimer order={order} now={now} compact />}
      </div>
      {/* actions */}
      {isNew && (
        <div style={{ display: "flex", gap: 8 }}>
          <Btn kind="reject" small onClick={() => onReject(order)}><I.x size={14} />Reddet</Btn>
          <Btn kind="accept" small full onClick={() => onAccept(order)}><I.check size={14} />Kabul Et</Btn>
        </div>
      )}
      {act && (
        <Btn kind="primary" small full onClick={() => onAdvance(order)}>{act.label}<I.arrowRight size={14} /></Btn>
      )}
    </div>
  );
}

// ---------- Order Row (list view) ----------
function OrderRow({ order, now, onOpen, onAccept, onReject, onAdvance, dense }) {
  const isNew = order.status === "new";
  const act = actionFor(order);
  const pad = dense ? "8px 16px" : "12px 16px";
  return (
    <div onClick={() => onOpen(order)} className={order._flash ? "flash-new" : ""}
      style={{
        display: "grid",
        gridTemplateColumns: "150px 110px 1fr 70px 130px 140px 210px",
        alignItems: "center", gap: 14, padding: pad,
        background: "var(--surface)", borderBottom: "1px solid var(--border)",
        borderLeft: `3px solid ${isNew ? "var(--new)" : "transparent"}`,
        cursor: "pointer", transition: "background .1s",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-2)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = "var(--surface)"; }}>
      <PlatformBadge pid={order.platformId} withName size={24} />
      <span className="mono" style={{ fontSize: 12, color: "var(--text-2)" }}>{order.channelRef}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{order.customer}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--text-3)", fontSize: 11.5, marginTop: 1 }}>
          <TypeIcon type={order.type} size={12} />
          <span>{order.fulfillment} · {order.area}</span>
        </div>
      </div>
      <span className="mono" style={{ fontSize: 13, color: "var(--text-2)", textAlign: "center" }} title={itemCount(order) + " ürün"}>{itemCount(order)} ✕</span>
      <span className="mono" style={{ fontWeight: 600, fontSize: 14 }}>{order.currency} {fmtMoney(order.total)}</span>
      <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
        {isNew ? <PrepTimer order={order} now={now} /> : <StatusPill status={order.status} type={order.type} />}
        <span style={{ fontSize: 11, color: "var(--text-3)" }}>{clockTime(order.placedAt)}</span>
      </div>
      <div style={{ display: "flex", gap: 7, justifyContent: "flex-end" }}>
        {isNew && <>
          <Btn kind="reject" small onClick={() => onReject(order)}><I.x size={13} /></Btn>
          <Btn kind="accept" small onClick={() => onAccept(order)}><I.check size={13} />Kabul Et</Btn>
        </>}
        {act && <Btn kind="primary" small onClick={() => onAdvance(order)}>{act.label}<I.arrowRight size={13} /></Btn>}
        {!isNew && !act && <span style={{ fontSize: 12, color: "var(--text-3)" }}>{order.status === "completed" ? "Tamamlandı" : ""}</span>}
      </div>
    </div>
  );
}

// ---------- KPI tile ----------
function Kpi({ label, value, sub, accent, icon }) {
  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)",
      padding: "11px 15px", display: "flex", flexDirection: "column", gap: 3, minWidth: 0, flex: 1,
      boxShadow: "var(--shadow-sm)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, color: "var(--text-3)", fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>
        {icon}{label}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <span className="mono" style={{ fontSize: 23, fontWeight: 600, color: accent || "var(--text)", lineHeight: 1 }}>{value}</span>
        {sub && <span style={{ fontSize: 12, color: "var(--text-3)" }}>{sub}</span>}
      </div>
    </div>
  );
}

Object.assign(window, {
  fmtMoney, minsAgo, timeAgo, clockTime, itemCount, actionFor,
  PlatformBadge, StatusPill, TypeIcon, PrepTimer, Btn, OrderCard, OrderRow, Kpi,
});
