/* ── CRM VISUAL — light theme, used on login page left side ────────── */

function CRMVisual() {
  // The "card" we move through a mini pipeline: New → Qualified → Won
  const [cardCol, setCardCol] = useState(0); // 0,1,2
  useEffect(() => {
    const t = setInterval(() => setCardCol(c => (c + 1) % 4), 1900); // 4 phases incl reset
    return () => clearInterval(t);
  }, []);

  // Live activity feed
  const ACTIVITY = [
    { who: "Priya S.",  text: "captured a new lead from",  src: "Meta Ads",     color: "#1877F2", icon: "spark" },
    { who: "Auto-flow", text: "sent WhatsApp follow-up to", src: "Rahul M.",    color: "#25D366", icon: "chat" },
    { who: "Arjun K.",  text: "moved deal to",              src: "Closed Won",  color: "#10b981", icon: "check" },
    { who: "Pipeline",  text: "scored hot lead from",       src: "Google Ads",  color: "#EA4335", icon: "fire" },
    { who: "Sara R.",   text: "booked demo via",            src: "Booking link", color: "#8b5cf6", icon: "cal" },
  ];
  const [feed, setFeed] = useState([0, 1, 2]); // visible indices, newest first
  useEffect(() => {
    const t = setInterval(() => {
      setFeed(f => [(f[0] + 1) % ACTIVITY.length, f[0], f[1]]);
    }, 2400);
    return () => clearInterval(t);
  }, []);

  // Animated counters
  const [leadsToday, setLeadsToday] = useState(128);
  const [conv, setConv] = useState(34);
  useEffect(() => {
    const t = setInterval(() => {
      setLeadsToday(v => v + Math.floor(Math.random() * 3));
      setConv(v => Math.max(28, Math.min(42, v + (Math.random() - 0.5) * 1.2)));
    }, 2800);
    return () => clearInterval(t);
  }, []);

  // Sparkline
  const sparkPath = "M 0 30 L 24 22 L 48 26 L 72 12 L 96 18 L 120 6 L 144 14 L 168 4";
  const sparkArea = "M 0 30 L 24 22 L 48 26 L 72 12 L 96 18 L 120 6 L 144 14 L 168 4 L 168 40 L 0 40 Z";

  // ring math
  const ringR = 38;
  const ringC = 2 * Math.PI * ringR;
  const dash = ringC * (1 - Math.round(conv) / 100);

  return (
    <div style={{ position: "relative", width: "100%", maxWidth: 560, marginInline: "auto" }}>

      {/* ─── Mini Pipeline ──────────────────────────────────────── */}
      <div style={{
        position: "relative", borderRadius: 24, background: "#fff",
        border: "1px solid var(--line-2)", padding: 18,
        boxShadow: "0 30px 70px -22px rgba(15,23,42,.2), 0 8px 24px -10px rgba(15,23,42,.08)",
      }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: "linear-gradient(135deg,#0d2a5e,#3b82f6)", display: "grid", placeItems: "center" }}>
              <svg width="16" height="16" viewBox="0 0 56 56">
                <path d="M14 30 C8 30 5 25 5 20 C5 15 8 10 14 10 C18 10 21 12 23 15 L25 15 C27 12 30 10 34 10 C40 10 43 15 43 20 C43 25 40 30 34 30 C30 30 27 28 25 25 L23 25 C21 28 18 30 14 30 Z M14 16 C11 16 9 18 9 20 C9 22 11 24 14 24 C17 24 19 22 19 20 C19 18 17 16 14 16 Z M34 16 C31 16 29 18 29 20 C29 22 31 24 34 24 C37 24 39 22 39 20 C39 18 37 16 34 16 Z"
                  fill="#7CB7FF" transform="translate(2 8)" />
              </svg>
            </div>
            <div>
              <p style={{ margin: 0, fontSize: 13, fontWeight: 800, color: "var(--ink)" }} className="display">Pipeline · Today</p>
              <p style={{ margin: 0, fontSize: 10, fontWeight: 600, color: "var(--muted-2)" }}>3 teammates viewing</p>
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "4px 10px", borderRadius: 999, background: "#f8fafc", border: "1px solid var(--line)" }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--emerald)" }} className="kr-pulse-dot" />
            <span style={{ fontSize: 10, fontWeight: 800, color: "var(--ink)", letterSpacing: ".08em", textTransform: "uppercase" }}>Live</span>
          </div>
        </div>

        {/* columns */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
          {[
            { label: "New", color: "#3b82f6", count: 12 },
            { label: "Qualified", color: "#8b5cf6", count: 8 },
            { label: "Won", color: "#10b981", count: 38 },
          ].map((col, ci) => (
            <div key={col.label} style={{ borderRadius: 14, background: "#f8fafc", padding: 10, minHeight: 180, position: "relative" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 10, fontWeight: 800, color: "var(--ink)", letterSpacing: ".08em", textTransform: "uppercase" }}>
                  <span style={{ width: 7, height: 7, borderRadius: "50%", background: col.color }} />{col.label}
                </span>
                <span style={{ fontSize: 10, fontWeight: 700, color: "var(--muted)", background: "#fff", border: "1px solid var(--line)", borderRadius: 999, padding: "1px 6px" }}>{col.count}</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {/* Fixed cards per column */}
                {ci === 0 && <MiniCard title="Web enquiry" sub="Meta · just now" tag="Meta" tagColor="#1877f2" />}
                {ci === 1 && <MiniCard title="Demo booked" sub="Google · hot" tag="Google" tagColor="#ea4335" />}
                {ci === 2 && <MiniCard title="₹4.2L closed" sub="Acme Realty" tag="Won" tagColor="#10b981" />}

                {/* The MOVING card: appears in the column matching cardCol */}
                {cardCol === ci && (
                  <div key={`mover-${cardCol}`} style={{ animation: "kr-card-arrive .5s var(--ease)" }}>
                    <MiniCard
                      title={ci === 0 ? "Ravi Kumar" : ci === 1 ? "Ravi · qualified" : "Ravi · closed"}
                      sub={ci === 0 ? "Meta · new" : ci === 1 ? "Hot · score 92" : "₹1.8L · won"}
                      tag={ci === 0 ? "Meta" : ci === 1 ? "Hot" : "Won"}
                      tagColor={ci === 0 ? "#1877f2" : ci === 1 ? "#C9A227" : "#10b981"}
                      ring
                    />
                  </div>
                )}
              </div>

              {/* arrow indicator to next column */}
              {ci < 2 && (
                <div style={{
                  position: "absolute", right: -7, top: "50%", transform: "translateY(-50%)", zIndex: 2,
                  width: 14, height: 14, borderRadius: "50%", background: "#fff",
                  border: `1.5px solid ${cardCol === ci ? col.color : "var(--line-2)"}`,
                  display: "grid", placeItems: "center",
                  transition: "border-color .3s var(--ease)",
                }}>
                  <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke={cardCol === ci ? col.color : "#94a3b8"} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="9 18 15 12 9 6" />
                  </svg>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* sparkline footer */}
        <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 12, padding: 12, borderRadius: 12, background: "#f8fafc", border: "1px solid var(--line)" }}>
          <div>
            <p style={{ margin: 0, fontSize: 11, fontWeight: 700, color: "var(--muted-2)", textTransform: "uppercase", letterSpacing: ".08em" }}>Leads · 7d</p>
            <p className="display" style={{ margin: "2px 0 0", fontSize: 22, fontWeight: 800, color: "var(--ink)", letterSpacing: "-.02em", lineHeight: 1 }}>{leadsToday}</p>
          </div>
          <svg viewBox="0 0 168 40" preserveAspectRatio="none" style={{ flex: 1, height: 40 }}>
            <defs>
              <linearGradient id="crm-spark" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" stopColor="#3b82f6" stopOpacity=".25" />
                <stop offset="1" stopColor="#3b82f6" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path d={sparkArea} fill="url(#crm-spark)" />
            <path d={sparkPath} fill="none" stroke="#3b82f6" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <circle r="3" fill="#fff" stroke="#3b82f6" strokeWidth="2">
              <animateMotion dur="4s" repeatCount="indefinite" path={sparkPath} />
            </circle>
          </svg>
        </div>
      </div>

      {/* ─── Floating: live activity toasts ───────────────────────── */}
      <div className="kr-float-soft" style={{
        position: "absolute", top: 50, right: -28, zIndex: 3,
        width: 260, padding: 12, borderRadius: 18, background: "#fff",
        border: "1px solid var(--line)",
        boxShadow: "0 20px 50px -16px rgba(15,23,42,.22)",
        animationDelay: "-1s",
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
          <p style={{ margin: 0, fontSize: 10, fontWeight: 800, color: "var(--ink)", letterSpacing: ".08em", textTransform: "uppercase" }}>Activity feed</p>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 9, fontWeight: 700, color: "var(--muted)" }}>
            <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#ef4444" }} className="kr-pulse-dot" />
            LIVE
          </span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {feed.map((idx, j) => {
            const a = ACTIVITY[idx];
            return (
              <div key={`${idx}-${j}`} style={{
                display: "flex", alignItems: "center", gap: 10,
                animation: j === 0 ? "kr-rise .35s var(--ease)" : "none",
                opacity: 1 - j * 0.3,
                transition: "opacity .4s var(--ease)",
              }}>
                <div style={{ width: 26, height: 26, borderRadius: 8, background: `${a.color}1c`, color: a.color, display: "grid", placeItems: "center", flexShrink: 0 }}>
                  <ActivityIcon kind={a.icon} />
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <p style={{ margin: 0, fontSize: 10, fontWeight: 700, color: "var(--muted)", lineHeight: 1.35, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    <span style={{ color: "var(--ink)", fontWeight: 800 }}>{a.who}</span> {a.text}
                  </p>
                  <p style={{ margin: 0, fontSize: 10, fontWeight: 700, color: a.color }}>{a.src}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* ─── Floating: conversion ring ────────────────────────────── */}
      <div className="kr-float-soft" style={{
        position: "absolute", bottom: -28, left: -28, zIndex: 3,
        padding: "14px 16px", borderRadius: 18,
        background: "linear-gradient(135deg,#fff,#FFFBEF)",
        border: "1px solid rgba(201,162,39,.32)",
        boxShadow: "0 18px 40px -12px rgba(201,162,39,.32)",
        display: "flex", alignItems: "center", gap: 14,
        animationDelay: "-2.4s",
      }}>
        <svg width="84" height="84" viewBox="0 0 100 100">
          <circle cx="50" cy="50" r={ringR} fill="none" stroke="#FEF3C7" strokeWidth="9" />
          <circle cx="50" cy="50" r={ringR} fill="none" stroke="url(#g-gold)" strokeWidth="9" strokeLinecap="round"
            strokeDasharray={ringC} strokeDashoffset={dash}
            transform="rotate(-90 50 50)"
            style={{ transition: "stroke-dashoffset .8s var(--ease)" }} />
          <defs>
            <linearGradient id="g-gold" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0" stopColor="#E0B842" />
              <stop offset="1" stopColor="#C9A227" />
            </linearGradient>
          </defs>
          <text x="50" y="55" textAnchor="middle" fill="#8a6a14" fontSize="18" fontWeight="800" fontFamily="Plus Jakarta Sans, sans-serif">{Math.round(conv)}%</text>
        </svg>
        <div>
          <p style={{ margin: 0, fontSize: 11, fontWeight: 800, color: "#8a6a14", letterSpacing: ".06em", textTransform: "uppercase" }}>Conversion</p>
          <p style={{ margin: "2px 0 0", fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>↑ this week</p>
          <p style={{ margin: "2px 0 0", fontSize: 10, fontWeight: 600, color: "var(--muted)" }}>vs 27% last week</p>
        </div>
      </div>

      {/* ─── Floating: top funnel card ────────────────────────────── */}
      <div className="kr-float-soft" style={{
        position: "absolute", top: -22, left: -24, zIndex: 3,
        padding: "10px 14px", borderRadius: 16, background: "#fff",
        border: "1px solid var(--line)",
        boxShadow: "0 16px 36px -12px rgba(15,23,42,.18)",
        display: "flex", alignItems: "center", gap: 10,
        animationDelay: "-3.5s",
      }}>
        <div style={{ width: 32, height: 32, borderRadius: 10, background: "linear-gradient(135deg,#3b82f6,#1d4ed8)", display: "grid", placeItems: "center" }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>
        </div>
        <div>
          <p style={{ margin: 0, fontSize: 11, fontWeight: 800, color: "var(--ink)" }}>+ {leadsToday} new leads</p>
          <p style={{ margin: 0, fontSize: 10, fontWeight: 600, color: "var(--muted-2)" }}>today, auto-captured</p>
        </div>
      </div>

      <style>{`
        @keyframes kr-card-arrive {
          0%   { opacity: 0; transform: translateX(-14px) scale(.94); }
          60%  { opacity: 1; transform: translateX(0) scale(1.04); }
          100% { opacity: 1; transform: translateX(0) scale(1); }
        }
      `}</style>
    </div>
  );
}

function MiniCard({ title, sub, tag, tagColor, ring }) {
  return (
    <div style={{
      borderRadius: 8, background: "#fff",
      border: `1px solid ${ring ? `${tagColor}66` : "var(--line)"}`,
      padding: 8,
      boxShadow: ring ? `0 6px 18px -8px ${tagColor}44, 0 0 0 2px ${tagColor}22` : "0 1px 0 rgba(15,23,42,.02)",
    }}>
      <div style={{ fontSize: 11, fontWeight: 800, color: "var(--ink)" }}>{title}</div>
      <div style={{ fontSize: 9, fontWeight: 600, color: "var(--muted-2)", marginTop: 1 }}>{sub}</div>
      <div style={{ marginTop: 6 }}>
        <span style={{ fontSize: 8, fontWeight: 800, padding: "2px 6px", borderRadius: 999, color: tagColor, background: `${tagColor}18` }}>{tag}</span>
      </div>
    </div>
  );
}

function ActivityIcon({ kind }) {
  const p = { width: 13, height: 13, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round" };
  if (kind === "spark") return <svg {...p}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>;
  if (kind === "check") return <svg {...p}><polyline points="20 6 9 17 4 12" /></svg>;
  if (kind === "fire")  return <svg {...p}><path d="M8.5 14.5C6 12 6 10 6 8c0 0 2-4 6-6 0 4 4 6 4 10 0 4-3 7-7 7s-7-3-7-7c0-2 1-4 3-5" /></svg>;
  if (kind === "cal")   return <svg {...p}><rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></svg>;
  if (kind === "chat")  return <svg {...p}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>;
  return null;
}

Object.assign(window, { CRMVisual });
