// ============================================================================
// ЗАЯВКИ v2 · Картка запиту товару — права детальна панель
// ============================================================================
function LsCardSection({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 7 }}>{label}</div>
      {children}
    </div>
  );
}

function LsMessengerBtn({ icon, color, label }) {
  return (
    <button title={label} style={{
      width: 34, height: 32, borderRadius: 8, cursor: "pointer",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      border: "1px solid var(--border-default)", background: "var(--bg-raised)", color,
    }}><LsIcon name={icon} size={14}/></button>
  );
}

function LsTimeline({ lead }) {
  const t2 = lead.ts;
  const items = [
    { icon: "inbox", color: "#A78BFA", text: "Заявка створена через " + (LS_SOURCES[lead.source]?.label || "сайт"), time: t2 },
    lead.bot && lead.bot !== "—" ? { icon: "bot", color: LS_BOT[lead.bot]?.color || "var(--fg-muted)", text: "Бот відповів: «" + (LS_BOT[lead.bot]?.label || "—") + "»", time: t2 } : null,
    lead.manager && lead.manager !== "—" ? { icon: "user-check", color: "var(--fg-secondary)", text: "Менеджер: " + lead.manager, time: t2 } : null,
    lead.orderId ? { icon: "check-circle", color: "#10B981", text: "Створено замовлення №" + lead.orderId, time: t2 } : null,
  ].filter(Boolean);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
      {items.map((it, i) => (
        <div key={i} style={{ display: "flex", gap: 10, position: "relative", paddingBottom: i < items.length - 1 ? 14 : 0 }}>
          {i < items.length - 1 && <span style={{ position: "absolute", left: 9, top: 20, bottom: 0, width: 1, background: "var(--border-subtle)" }}></span>}
          <span style={{
            width: 19, height: 19, borderRadius: "50%", flexShrink: 0, marginTop: 1,
            background: "var(--bg-raised)", border: "1px solid var(--border-default)",
            display: "inline-flex", alignItems: "center", justifyContent: "center", color: it.color,
          }}><LsIcon name={it.icon} size={10}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, color: "var(--fg-secondary)", lineHeight: 1.45 }}>{it.text}</div>
            <div style={{ fontSize: 10.5, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{it.time}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function LsProductCardRail({ lead, onClose }) {
  const tone = lsAgeTone(lead.ageMin, lead.status === "converted" || lead.status === "lost");
  const done = lead.status === "converted" || lead.status === "lost";
  return (
    <div style={{
      width: 308, flexShrink: 0, borderLeft: "1px solid var(--border-subtle)", background: "var(--bg-panel)",
      display: "flex", flexDirection: "column", minHeight: 0,
    }}>
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 9, flexShrink: 0 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>#{lead.id}</span>
        <LsChip map={LS_PRODUCT_STATUSES} value={lead.status}/>
        <div style={{ flex: 1 }}></div>
        <button onClick={onClose} style={{ width: 26, height: 26, border: 0, background: "transparent", color: "var(--fg-muted)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <LsIcon name="x" size={15}/>
        </button>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: 16 }}>
        {/* SLA */}
        <div style={{
          padding: "9px 12px", borderRadius: 8, marginBottom: 16,
          background: "color-mix(in oklab, " + tone + " 12%, transparent)",
          border: "1px solid color-mix(in oklab, " + tone + " 28%, transparent)",
          display: "flex", alignItems: "center", gap: 9,
        }}>
          <LsIcon name="clock" size={14} style={{ color: tone }}/>
          <span style={{ fontSize: 12, fontWeight: 500, color: tone }}>{lsFmtAge(lead.ageMin)} тому</span>
          <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>· {lead.ts}</span>
        </div>

        {/* Товар */}
        <LsCardSection label="Товар">
          <div style={{ padding: "12px 13px", background: "var(--bg-raised)", border: "1px solid var(--border-subtle)", borderRadius: 10 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-primary)", lineHeight: 1.35 }}>{lead.product}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 9 }}>
              <LsBotPill reply={lead.bot}/>
              <span style={{ flex: 1 }}></span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{lsFmtUah(lead.price)}</span>
            </div>
            <div style={{ fontSize: 10.5, color: "var(--fg-muted)", textAlign: "right", marginTop: 2 }}>ціна на сайті</div>
          </div>
          {lead.note && (
            <div style={{ fontSize: 12, color: "var(--fg-secondary)", lineHeight: 1.5, marginTop: 8 }}>
              <span style={{ color: "var(--fg-muted)" }}>Коментар: </span>{lead.note}
            </div>
          )}
        </LsCardSection>

        {/* Клієнт */}
        <LsCardSection label="Клієнт">
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", background: "var(--bg-raised)", borderRadius: 8, border: "1px solid var(--border-subtle)", marginBottom: 8 }}>
            <LsAvatar name={lead.client} size={30}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)" }}>{lead.client}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{lsFmtPhone(lead.phone)}</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <LsMessengerBtn icon="send" color="#229ED9" label="Telegram"/>
            <LsMessengerBtn icon="phone" color="#7360F2" label="Viber"/>
            <button style={{
              flex: 1, height: 32, border: "1px solid var(--border-default)", borderRadius: 8,
              background: "var(--bg-raised)", color: "var(--fg-primary)", cursor: "pointer", fontFamily: "inherit",
              fontSize: 12, fontWeight: 500, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
            }}>
              <LsIcon name="phone-call" size={13}/> Зателефонувати
            </button>
          </div>
        </LsCardSection>

        {/* Джерело + менеджер */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 7 }}>Джерело</div>
            <LsSource source={lead.source} withLabel/>
          </div>
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 500, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 7 }}>Менеджер</div>
            {lead.manager === "—" ? (
              <button style={{ height: 24, padding: "0 10px", border: "1px dashed var(--border-strong)", background: "transparent", color: "var(--fg-secondary)", borderRadius: 6, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit" }}>
                + Призначити
              </button>
            ) : (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <LsAvatar name={lead.manager} size={20}/>
                <span style={{ fontSize: 12, color: "var(--fg-secondary)" }}>{lead.manager}</span>
              </span>
            )}
          </div>
        </div>

        {/* Історія */}
        <LsCardSection label="Історія">
          <LsTimeline lead={lead}/>
        </LsCardSection>
      </div>

      {!done && (
        <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", gap: 7, flexShrink: 0 }}>
          <LsButton variant="primary" icon="arrow-right" style={{ height: 34, justifyContent: "center" }}>Створити замовлення</LsButton>
          <LsButton variant="secondary" icon="x" style={{ height: 34, justifyContent: "center" }}>Позначити втраченою</LsButton>
        </div>
      )}
      {lead.orderId && (
        <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-subtle)", flexShrink: 0 }}>
          <div style={{
            display: "flex", alignItems: "center", gap: 9, padding: "9px 12px",
            background: "rgba(16,185,129,.08)", border: "1px solid rgba(16,185,129,.2)", borderRadius: 8,
          }}>
            <LsIcon name="check-circle" size={15} style={{ color: "#10B981" }}/>
            <span style={{ fontSize: 12, fontWeight: 500, color: "#6EE7B7", flex: 1 }}>Замовлення №{lead.orderId}</span>
            <LsIcon name="arrow-right" size={13} style={{ color: "var(--fg-muted)" }}/>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LsProductCardRail });
