/* global React */
const { useMemo: useMemoC } = React;
const { RangeBar, StatusPill } = window.__dashAtoms;
const { parseRange, parsePrice, fmtUsd } = window.__dashUtils;

// ============================================================
// NICHE CARD — rich, high-fidelity bento tile
// ============================================================
window.NicheCard = function NicheCard({ niche, onOpen, size = "md", tweaks = {}, globalRange }) {
  const isOurs = niche.hasUs;
  const isAbsent = niche.isAbsent;
  const count = niche.models.length;
  const accent = tweaks.accent || "#22c55e";
  const showSpec = tweaks.showSpec !== false;
  const cs = size === "lg" ? { pad: 22, h: 240, num: 64, title: 16 }
           : size === "sm" ? { pad: 14, h: 160, num: 32, title: 12 }
           : { pad: 18, h: 230, num: 44, title: 14 };

  const tone = isOurs
    ? { bg: `color-mix(in srgb, ${accent} 7%, #0a0a0a)`, border: `color-mix(in srgb, ${accent} 55%, transparent)`, accent }
    : isAbsent
      ? { bg: "transparent", border: "rgba(217,170,80,0.25)", accent: "#d9aa50" }
      : { bg: "#0a0a0a", border: "rgba(255,255,255,0.12)", accent: "rgba(255,255,255,0.55)" };

  const topModels = niche.models.slice(0, 3);
  // build distribution dots: one tiny dot per model, green if ours
  const dots = niche.models;

  return (
    <button onClick={() => onOpen(niche)} className="niche-card" style={{
      background: tone.bg, border: `1px solid ${tone.border}`,
      padding: cs.pad, minHeight: cs.h,
      display: "flex", flexDirection: "column", gap: 10,
      cursor: "pointer", textAlign: "left", color: "#fff",
      fontFamily: "var(--sketch)", position: "relative",
      transition: "transform 140ms ease, border-color 140ms",
      borderRadius: 8, overflow: "hidden",
    }}>
      {/* corner status indicator */}
      {isOurs && (
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2, background: accent }}/>
      )}
      {isAbsent && (
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2,
          background: "repeating-linear-gradient(90deg, #d9aa50 0 6px, transparent 6px 12px)" }}/>
      )}

      {/* HEAD: status pill + cluster + cherry */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0, flex: 1 }}>
          <StatusPill kind={isOurs ? "ours" : isAbsent ? "absent" : "competitor"} accent={accent}/>
          <div style={{
            fontSize: cs.title, fontWeight: 700, lineHeight: 1.15,
            textTransform: tweaks.uppercaseTitles === false ? "none" : "uppercase",
            letterSpacing: 0.4, color: isAbsent ? "rgba(255,255,255,0.65)" : "#fff",
          }}>
            {niche.title}
          </div>
          <div style={{ fontSize: 10, opacity: 0.45, letterSpacing: 1, textTransform: "uppercase" }}>{niche.cluster}</div>
        </div>
        <div style={{ width: 54, height: 54, color: tone.accent, opacity: isAbsent ? 0.5 : 1, flex: "0 0 auto" }}>
          <window.NicheIcon kind={niche.icon}/>
        </div>
      </div>

      <div style={{ flex: 1 }}/>

      {/* BIG NUMBER + dot distribution */}
      <div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
          {tweaks.showCount !== false && (
            <div style={{
              fontSize: cs.num, fontWeight: 700, color: tone.accent,
              lineHeight: 0.95, fontFamily: "var(--mono-num)", letterSpacing: -2,
            }}>
              {isAbsent ? "0" : count}
            </div>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 2, paddingBottom: 4 }}>
            <div style={{ fontSize: 10, opacity: 0.5, textTransform: "uppercase", letterSpacing: 1, fontWeight: 600 }}>
              {isOurs ? `${niche.ours.length} наш${niche.ours.length>1?'их':''} · ${niche.competitors.length} конкур.` : isAbsent ? "ніша вільна" : "конкурентів"}
            </div>
            {!isAbsent && (
              <div style={{ display: "flex", gap: 3, alignItems: "center" }}>
                {dots.map((m, i) => (
                  <div key={i} style={{
                    width: 6, height: 6, borderRadius: "50%",
                    background: window.IS_OURS(m.maker) ? accent : "rgba(255,255,255,0.35)",
                  }}/>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* TOP MODELS — names list */}
        {!isAbsent && (
          <div style={{ marginTop: 10, fontSize: 11, color: "rgba(255,255,255,0.7)", lineHeight: 1.4,
            display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
          }}>
            {topModels.map((m, i) => (
              <span key={i}>
                <span style={{ color: window.IS_OURS(m.maker) ? accent : "rgba(255,255,255,0.85)", fontWeight: window.IS_OURS(m.maker) ? 600 : 400 }}>{m.model}</span>
                {i < topModels.length - 1 && <span style={{ opacity: 0.3 }}>  ·  </span>}
              </span>
            ))}
            {niche.models.length > 3 && <span style={{ opacity: 0.4 }}>  +{niche.models.length - 3}</span>}
          </div>
        )}
        {isAbsent && (
          <div style={{ marginTop: 10, fontSize: 11, color: "#d9aa50", opacity: 0.8, lineHeight: 1.4 }}>
            Можлива точка входу — ні в нас, ні у відомих виробників
          </div>
        )}

        {/* SPEC BARS: price + range */}
        {showSpec && !isAbsent && globalRange && size !== "sm" && (
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
            {niche.priceMin != null && (
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9, opacity: 0.5, marginBottom: 3, textTransform: "uppercase", letterSpacing: 1, fontFamily: "var(--mono-num)" }}>
                  <span>ЦІНА</span><span>{fmtUsd(niche.priceMin)}–{fmtUsd(niche.priceMax)}</span>
                </div>
                <RangeBar min={niche.priceMin} max={niche.priceMax} niceMin={globalRange.priceMin} niceMax={globalRange.priceMax} color={tone.accent} height={3}/>
              </div>
            )}
            {niche.rangeMin != null && (
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9, opacity: 0.5, marginBottom: 3, textTransform: "uppercase", letterSpacing: 1, fontFamily: "var(--mono-num)" }}>
                  <span>ДАЛЬН.</span><span>{niche.rangeMin}–{niche.rangeMax} км</span>
                </div>
                <RangeBar min={niche.rangeMin} max={niche.rangeMax} niceMin={globalRange.rangeMin} niceMax={globalRange.rangeMax} color={tone.accent} height={3}/>
              </div>
            )}
          </div>
        )}
      </div>
    </button>
  );
};

// ============================================================
// MODEL ROW (modal)
// ============================================================
function ModelRow({ m, ours, accent }) {
  return (
    <div style={{
      border: `1px solid ${ours ? `color-mix(in srgb, ${accent} 55%, transparent)` : "rgba(255,255,255,0.12)"}`,
      padding: 14, background: ours ? `color-mix(in srgb, ${accent} 9%, #0a0a0a)` : "#0a0a0a",
      borderRadius: 6, display: "flex", flexDirection: "column", gap: 8,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
        <div style={{ fontWeight: 700, fontSize: 14, color: ours ? accent : "#fff" }}>{m.model}</div>
        <span style={{ fontSize: 12 }}>{m.country}</span>
      </div>
      <div style={{ fontSize: 11, opacity: 0.55 }}>{m.maker}</div>
      <div style={{ fontSize: 12, opacity: 0.85, lineHeight: 1.45 }}>{m.desc}</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 4, paddingTop: 8, borderTop: "1px solid rgba(255,255,255,0.08)" }}>
        <Spec label="Дальн." value={m.range}/>
        <Spec label="Час" value={m.endurance}/>
        <Spec label="Ціна" value={m.price}/>
      </div>
    </div>
  );
}
const Spec = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 9, opacity: 0.4, textTransform: "uppercase", letterSpacing: 1, fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 11, fontFamily: "var(--mono-num)", marginTop: 2, opacity: value === "—" ? 0.3 : 1 }}>{value}</div>
  </div>
);

// ============================================================
// MODAL
// ============================================================
window.NicheModal = function NicheModal({ niche, onClose, accent }) {
  if (!niche) return null;
  const isOurs = niche.hasUs;
  const sorted = useMemoC(() => {
    return [...niche.models].sort((a, b) => {
      const ao = window.IS_OURS(a.maker) ? 0 : 1;
      const bo = window.IS_OURS(b.maker) ? 0 : 1;
      if (ao !== bo) return ao - bo;
      const ar = parseRange(a.range)?.[1] || 0;
      const br = parseRange(b.range)?.[1] || 0;
      return br - ar;
    });
  }, [niche]);

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.85)", zIndex: 1000,
      display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
      backdropFilter: "blur(4px)",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: "#080808", border: `1px solid ${isOurs ? accent : "rgba(255,255,255,0.18)"}`,
        maxWidth: 1100, width: "100%", maxHeight: "88vh", overflowY: "auto", color: "#fff",
        fontFamily: "var(--sketch)", borderRadius: 12, boxShadow: "0 20px 60px rgba(0,0,0,0.6)",
      }}>
        {/* HERO */}
        <div style={{
          padding: "28px 32px 20px", borderBottom: "1px solid rgba(255,255,255,0.08)",
          background: isOurs ? `linear-gradient(180deg, color-mix(in srgb, ${accent} 12%, transparent) 0%, transparent 100%)` : "transparent",
          display: "flex", gap: 24, alignItems: "flex-start",
        }}>
          <div style={{ width: 88, height: 88, color: isOurs ? accent : niche.isAbsent ? "#d9aa50" : "rgba(255,255,255,0.7)", flex: "0 0 auto" }}>
            <window.NicheIcon kind={niche.icon}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, opacity: 0.5, textTransform: "uppercase", letterSpacing: 2, marginBottom: 6 }}>{niche.cluster}</div>
            <h2 style={{ margin: 0, fontSize: 32, fontWeight: 800, color: "#fff", letterSpacing: -0.5, textTransform: "uppercase" }}>{niche.title}</h2>
            <div style={{ display: "flex", gap: 10, marginTop: 12, flexWrap: "wrap" }}>
              <StatusPill kind={isOurs ? "ours" : niche.isAbsent ? "absent" : "competitor"} accent={accent}/>
              {!niche.isAbsent && (
                <>
                  <Chip>{niche.models.length} моделей</Chip>
                  {niche.priceMin != null && <Chip>{fmtUsd(niche.priceMin)}–{fmtUsd(niche.priceMax)}</Chip>}
                  {niche.rangeMin != null && <Chip>{niche.rangeMin}–{niche.rangeMax} км</Chip>}
                </>
              )}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: "transparent", border: "1px solid rgba(255,255,255,0.2)", color: "#fff",
            padding: "6px 12px", cursor: "pointer", fontFamily: "var(--sketch)", borderRadius: 4, fontSize: 12,
          }}>✕ Закрити</button>
        </div>

        <div style={{ padding: 32 }}>
          {niche.isAbsent ? (
            <div style={{
              padding: "40px 24px", textAlign: "center", border: "1px dashed rgba(217,170,80,0.4)",
              background: "rgba(217,170,80,0.04)", borderRadius: 8,
            }}>
              <div style={{ fontSize: 48, color: "#d9aa50", marginBottom: 12 }}>⌀</div>
              <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 6 }}>Біла пляма</div>
              <div style={{ fontSize: 13, opacity: 0.65, maxWidth: 480, margin: "0 auto", lineHeight: 1.5 }}>
                У цій ніші не зафіксовано продуктів ні у Gen Cherry, ні в українських виробників (за даними дашборду).
                Можлива точка входу.
              </div>
            </div>
          ) : (
            <>
              {isOurs && (
                <Section title="🍒 Наші продукти" count={niche.ours.length} color={accent}>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
                    {niche.ours.map(m => <ModelRow key={m.model} m={m} ours accent={accent}/>)}
                  </div>
                </Section>
              )}
              {niche.competitors.length > 0 && (
                <Section title="Конкуренти" count={niche.competitors.length} color="rgba(255,255,255,0.6)">
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
                    {sorted.filter(m => !window.IS_OURS(m.maker)).map(m => <ModelRow key={m.model} m={m} accent={accent}/>)}
                  </div>
                </Section>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};
const Chip = ({ children }) => (
  <span style={{
    fontSize: 11, padding: "3px 9px", border: "1px solid rgba(255,255,255,0.15)",
    borderRadius: 4, fontFamily: "var(--mono-num)", color: "rgba(255,255,255,0.75)",
  }}>{children}</span>
);
const Section = ({ title, count, color, children }) => (
  <div style={{ marginBottom: 28 }}>
    <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 14, paddingBottom: 8, borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
      <h3 style={{ margin: 0, fontSize: 13, color, textTransform: "uppercase", letterSpacing: 1.5, fontWeight: 700 }}>{title}</h3>
      <span style={{ fontSize: 11, opacity: 0.45, fontFamily: "var(--mono-num)" }}>({count})</span>
    </div>
    {children}
  </div>
);
