/* global React */
const { useState: useStateD, useEffect: useEffectD, useRef: useRefD, useMemo: useMemoD } = React;

// ═══════════════════════════════════════════════════════════════
// SHARED — channel icon, screen frame, kanban card
// ═══════════════════════════════════════════════════════════════
function Ch({ kind, size = 14 }) {
  const map = {
    wa: { bg: "var(--whatsapp)", l: "W" },
    ig: { bg: "var(--instagram)", l: "I" },
    fb: { bg: "var(--facebook)", l: "f" },
    tg: { bg: "var(--telegram)", l: "T" },
    vk: { bg: "var(--vk)", l: "V" },
    web: { bg: "var(--muted)", l: "@" },
  };
  const c = map[kind] || map.web;
  return (
    <span style={{
      width: size + 4, height: size + 4, borderRadius: 5,
      background: c.bg, color: "white",
      display: "inline-grid", placeItems: "center",
      fontWeight: 700, fontSize: Math.round(size * 0.7),
      flexShrink: 0,
    }}>{c.l}</span>
  );
}

function ScreenFrame({ children, label }) {
  return (
    <div className="demo-screen">
      <div className="demo-screen-bar">
        <div className="dots"><span></span><span></span><span></span></div>
        <div className="addr">{label}</div>
        <div style={{ width: 36 }}></div>
      </div>
      <div className="demo-screen-body">{children}</div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 1. KANBAN DEMO — drag flying card across columns
// ═══════════════════════════════════════════════════════════════
function KanbanDemo({ speed = 1 }) {
  const cols = [
    { key: "new", label: "Yeni", color: "var(--sky)" },
    { key: "contact", label: "İletişim", color: "var(--violet)" },
    { key: "offer", label: "Teklif", color: "var(--amber)" },
    { key: "won", label: "Kazanıldı", color: "var(--accent)" },
  ];

  // Static cards per column
  const baseCards = {
    new: [
      { id: "n1", name: "Levent Pırlanta", v: "₺56K", ch: "ig" },
      { id: "n2", name: "Café Roma", v: "₺18K", ch: "wa" },
    ],
    contact: [
      { id: "c1", name: "Atlas Group", v: "₺340K", ch: "wa" },
    ],
    offer: [
      { id: "o1", name: "Studio Marc", v: "€8K", ch: "tg" },
      { id: "o2", name: "Yenilik Tıp", v: "₺128K", ch: "wa" },
    ],
    won: [
      { id: "w1", name: "Polonya B2B", v: "€12K", ch: "tg" },
    ],
  };

  // Flying card cycles through columns
  const [col, setCol] = useStateD(0);
  const [phase, setPhase] = useStateD("settle"); // settle → fly
  useEffectD(() => {
    const t1 = setTimeout(() => setPhase("fly"), 1400 / speed);
    const t2 = setTimeout(() => {
      setPhase("settle");
      setCol((c) => (c + 1) % cols.length);
    }, 2200 / speed);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [col, speed, cols.length]);

  const flyer = { id: "fly", name: "Selin Y.", v: "₺128K", ch: "wa" };

  return (
    <div className="demo-frame">
      <ScreenFrame label="kanban / satış-hattı">
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 10, height: "100%" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>Pipeline</div>
            <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--muted)" }}>toplam ₺562K</div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, flex: 1, alignItems: "start", minHeight: 0 }}>
            {cols.map((c, i) => {
              const isActive = i === col;
              return (
                <div key={c.key} style={{
                  background: "var(--bg-alt)",
                  borderRadius: 10,
                  padding: 8,
                  display: "flex", flexDirection: "column", gap: 6,
                  minHeight: 220,
                  border: isActive && phase === "settle" ? `1.5px solid ${c.color}` : "1px solid var(--border)",
                  transition: "border-color 0.3s",
                }}>
                  <div style={{
                    display: "flex", alignItems: "center", gap: 6,
                    fontSize: 10, fontFamily: "var(--font-mono)",
                    textTransform: "uppercase", letterSpacing: "0.05em",
                    color: "var(--ink-2)", padding: "2px 4px",
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: "50%", background: c.color }}></span>
                    {c.label}
                    <span style={{ marginLeft: "auto", color: "var(--muted)" }}>
                      {(baseCards[c.key]?.length || 0) + (isActive && phase === "settle" ? 1 : 0)}
                    </span>
                  </div>
                  {isActive && phase === "settle" && <KanbanCard card={flyer} pulse />}
                  {(baseCards[c.key] || []).map((card) => (
                    <KanbanCard key={card.id} card={card} />
                  ))}
                </div>
              );
            })}
          </div>
        </div>
      </ScreenFrame>
      <FlyingCard card={flyer} cols={cols} col={col} phase={phase} speed={speed} />
    </div>
  );
}

function KanbanCard({ card, pulse }) {
  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--border)",
      borderRadius: 7,
      padding: "8px 9px",
      display: "flex", flexDirection: "column", gap: 4,
      boxShadow: pulse ? "0 0 0 2px oklch(from var(--accent) l c h / 0.3), var(--shadow-sm)" : "var(--shadow-sm)",
      animation: pulse ? "kc-pulse 1.4s ease-out" : undefined,
    }}>
      <div style={{ fontSize: 11, fontWeight: 500, color: "var(--ink)" }}>{card.name}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
        <Ch kind={card.ch} size={10} />
        <span style={{ marginLeft: "auto", fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--accent-ink)", fontWeight: 600 }}>
          {card.v}
        </span>
      </div>
    </div>
  );
}

function FlyingCard({ card, cols, col, phase, speed }) {
  // We render the flying card absolutely positioned over the kanban
  // when phase === "fly". It travels from col to (col+1) % cols.length
  // using CSS transition.
  if (phase !== "fly") return null;
  const fromPct = (col + 0.5) * (100 / cols.length);
  const toPct = ((col + 1) % cols.length + 0.5) * (100 / cols.length);
  return (
    <div style={{
      position: "absolute", left: 0, right: 0, top: 80,
      pointerEvents: "none",
      zIndex: 5,
    }}>
      <div style={{
        position: "absolute",
        left: `${fromPct}%`,
        top: 0,
        transform: "translateX(-50%)",
        animation: `kc-fly-${col} ${800 / speed}ms cubic-bezier(0.4, 0.0, 0.2, 1) forwards`,
        width: "20%",
      }}>
        <style>{`
          @keyframes kc-fly-${col} {
            0% { left: ${fromPct}%; transform: translateX(-50%) rotate(-3deg) scale(1.05); }
            100% { left: ${toPct}%; transform: translateX(-50%) rotate(2deg) scale(1.1); }
          }
        `}</style>
        <div style={{
          background: "var(--surface)",
          border: "1.5px solid var(--accent)",
          borderRadius: 7,
          padding: "8px 9px",
          boxShadow: "0 12px 32px -8px oklch(0 0 0 / 0.3)",
          fontSize: 11,
        }}>
          <div style={{ fontWeight: 500, color: "var(--ink)" }}>{card.name}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 5, marginTop: 4 }}>
            <Ch kind={card.ch} size={10} />
            <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", color: "var(--accent-ink)", fontWeight: 600 }}>
              {card.v}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 2. AVCI DEMO — search + animated results
// ═══════════════════════════════════════════════════════════════
function AvciDemo({ speed = 1 }) {
  const RESULTS = [
    { name: "Demir Mücevher", addr: "Bağdat Cad. 124", rating: 4.8, phone: "+90 532 ••• 4421" },
    { name: "Levent Pırlanta", addr: "Levent Çarşı 18", rating: 4.6, phone: "+90 533 ••• 8812" },
    { name: "Şişli Altın & Gümüş", addr: "Halaskargazi 200", rating: 4.9, phone: "+90 535 ••• 2210" },
    { name: "Beyoğlu Saat Mücevher", addr: "İstiklal Cad. 88", rating: 4.5, phone: "+90 532 ••• 0901" },
    { name: "Kadıköy Pırlanta", addr: "Söğütlüçeşme 12", rating: 4.7, phone: "+90 538 ••• 3344" },
  ];
  const [shown, setShown] = useStateD(0);
  const [reset, setReset] = useStateD(0);

  useEffectD(() => {
    if (shown < RESULTS.length) {
      const t = setTimeout(() => setShown((s) => s + 1), 320 / speed);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => {
        setShown(0);
        setReset((r) => r + 1);
      }, 2400 / speed);
      return () => clearTimeout(t);
    }
  }, [shown, speed, RESULTS.length]);

  return (
    <div className="demo-frame">
      <ScreenFrame label="avcı / arama">
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 10, height: "100%" }}>
          {/* search bar */}
          <div style={{ display: "flex", gap: 6 }}>
            <div style={{
              flex: 1, padding: "8px 10px",
              background: "var(--bg-alt)", border: "1px solid var(--border)",
              borderRadius: 7, fontSize: 11, color: "var(--ink)",
              fontFamily: "var(--font-mono)",
              display: "flex", alignItems: "center", gap: 6,
            }}>
              <span style={{ color: "var(--muted)" }}>⌕</span>
              <span>mücevher</span>
              <span style={{ color: "var(--muted)" }}>·</span>
              <span>İstanbul</span>
              <span style={{ marginLeft: "auto", color: "var(--accent-ink)" }}>{shown}/60</span>
            </div>
            <button style={{
              padding: "8px 12px", background: "var(--ink)",
              color: "var(--bg)", border: "none", borderRadius: 7,
              fontSize: 11, fontWeight: 600, cursor: "pointer",
              animation: shown === 0 ? "av-pulse 1.5s ease-out infinite" : undefined,
            }}>
              Ara
            </button>
          </div>

          {/* credits bar */}
          <div style={{
            display: "flex", alignItems: "center", gap: 8,
            fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--muted)",
            padding: "6px 10px", background: "var(--bg-alt)",
            borderRadius: 7, border: "1px dashed var(--border)",
          }}>
            <span>Kredi:</span>
            <div style={{ flex: 1, height: 4, background: "var(--border)", borderRadius: 2, overflow: "hidden" }}>
              <div style={{
                height: "100%", background: "var(--accent)",
                width: `${100 - (shown / 60) * 100}%`,
                transition: "width 0.3s",
              }}></div>
            </div>
            <span style={{ color: "var(--accent-ink)" }}>{200 - shown}/200</span>
          </div>

          {/* results */}
          <div style={{ display: "flex", flexDirection: "column", gap: 5, flex: 1, overflow: "hidden" }} key={reset}>
            {RESULTS.slice(0, shown).map((r, i) => (
              <div key={r.name} style={{
                padding: "8px 10px",
                background: "var(--surface)",
                border: "1px solid var(--border)",
                borderRadius: 6,
                display: "flex", alignItems: "center", gap: 8,
                animation: `av-in 0.4s cubic-bezier(0.2, 0.8, 0.2, 1) ${i * 0.05}s both`,
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: 5,
                  background: `oklch(0.85 0.1 ${(i * 60) % 360})`,
                  display: "grid", placeItems: "center",
                  fontWeight: 700, fontSize: 10, color: "white",
                }}>{r.name[0]}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 500, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.name}</div>
                  <div style={{ fontSize: 9, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>{r.addr}</div>
                </div>
                <div style={{ fontSize: 10, color: "var(--amber-ink)", fontFamily: "var(--font-mono)", fontWeight: 600 }}>★{r.rating}</div>
                <button style={{
                  padding: "3px 8px", background: "var(--accent)", color: "white",
                  border: "none", borderRadius: 4, fontSize: 9,
                  fontWeight: 600, cursor: "pointer",
                }}>+ Lead</button>
              </div>
            ))}
            {shown < RESULTS.length && (
              <div style={{ display: "flex", justifyContent: "center", padding: 8 }}>
                <div className="spinner" style={{
                  width: 14, height: 14, borderRadius: "50%",
                  border: "2px solid var(--border)", borderTopColor: "var(--accent)",
                  animation: "av-spin 0.8s linear infinite",
                }}></div>
              </div>
            )}
          </div>
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 3. CHAT DEMO — multi-channel inbox + typing message
// ═══════════════════════════════════════════════════════════════
function ChatDemo({ speed = 1 }) {
  const threads = [
    { name: "Ayşe Demir", ch: "wa", last: "Tamam, akşam 6 müsaitim", unread: 2, active: true },
    { name: "Marc Studio", ch: "ig", last: "Photos look amazing 📸", unread: 0 },
    { name: "Pavel K.", ch: "tg", last: "Spasibo, do svidaniya", unread: 1 },
    { name: "Berlin GmbH", ch: "fb", last: "Sehr gerne, wir freuen uns", unread: 0 },
  ];

  // typing animation
  const fullMsg = "Merhaba, fiyat listesini gönderebilir misiniz?";
  const [typed, setTyped] = useStateD(0);
  const [reply, setReply] = useStateD(false);
  useEffectD(() => {
    if (typed < fullMsg.length) {
      const t = setTimeout(() => setTyped((c) => c + 1), 50 / speed);
      return () => clearTimeout(t);
    } else if (!reply) {
      const t = setTimeout(() => setReply(true), 800 / speed);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => { setTyped(0); setReply(false); }, 2000 / speed);
      return () => clearTimeout(t);
    }
  }, [typed, reply, speed]);

  return (
    <div className="demo-frame">
      <ScreenFrame label="sohbet / inbox">
        <div style={{ display: "grid", gridTemplateColumns: "130px 1fr", height: "100%" }}>
          {/* thread list */}
          <div style={{ borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column" }}>
            <div style={{ padding: "10px 12px", borderBottom: "1px solid var(--border)", fontSize: 11, fontWeight: 600, color: "var(--ink)" }}>
              Inbox <span style={{ color: "var(--muted)", fontWeight: 400 }}>· 142</span>
            </div>
            {threads.map((t, i) => (
              <div key={t.name} style={{
                padding: "9px 10px",
                borderBottom: "1px solid var(--border)",
                display: "flex", flexDirection: "column", gap: 3,
                background: t.active ? "var(--bg-alt)" : "transparent",
                borderLeft: t.active ? "2px solid var(--accent)" : "2px solid transparent",
                cursor: "pointer",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
                  <Ch kind={t.ch} size={9} />
                  <span style={{ fontSize: 10, fontWeight: 500, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.name}</span>
                  {t.unread > 0 && (
                    <span style={{
                      marginLeft: "auto", minWidth: 14, height: 14,
                      borderRadius: 7, background: "var(--accent)",
                      color: "white", fontSize: 8, fontWeight: 700,
                      display: "grid", placeItems: "center", padding: "0 4px",
                    }}>{t.unread}</span>
                  )}
                </div>
                <div style={{ fontSize: 9, color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.last}</div>
              </div>
            ))}
          </div>

          {/* chat panel */}
          <div style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0 }}>
            <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 8 }}>
              <Ch kind="wa" size={12} />
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink)" }}>Ayşe Demir</div>
                <div style={{ fontSize: 9, color: "var(--accent-ink)", fontFamily: "var(--font-mono)" }}>● online</div>
              </div>
              <span style={{
                marginLeft: "auto", fontSize: 9, fontFamily: "var(--font-mono)",
                padding: "2px 6px", background: "var(--violet-bg)",
                color: "var(--violet)", borderRadius: 4, fontWeight: 600,
              }}>İLETİŞİM</span>
            </div>

            <div style={{ flex: 1, padding: 12, display: "flex", flexDirection: "column", gap: 8, overflow: "hidden", justifyContent: "flex-end" }}>
              <div style={{ alignSelf: "flex-start", maxWidth: "75%", padding: "7px 10px", background: "var(--bg-alt)", borderRadius: "10px 10px 10px 2px", fontSize: 11, color: "var(--ink)" }}>
                Selamlar Yuka 👋
              </div>
              <div style={{ alignSelf: "flex-start", maxWidth: "75%", padding: "7px 10px", background: "var(--bg-alt)", borderRadius: "10px 10px 10px 2px", fontSize: 11, color: "var(--ink)", minHeight: 28 }}>
                {fullMsg.slice(0, typed)}
                {typed < fullMsg.length && <span className="caret">|</span>}
              </div>
              {reply && (
                <div style={{
                  alignSelf: "flex-end", maxWidth: "75%",
                  padding: "7px 10px",
                  background: "var(--accent)", color: "white",
                  borderRadius: "10px 10px 2px 10px",
                  fontSize: 11,
                  animation: "msg-in 0.4s cubic-bezier(0.2, 0.8, 0.2, 1) both",
                }}>
                  Tabii, hemen gönderiyorum 🌹
                </div>
              )}
            </div>

            <div style={{ padding: 8, borderTop: "1px solid var(--border)", display: "flex", gap: 6, alignItems: "center" }}>
              <div style={{ flex: 1, padding: "6px 10px", background: "var(--bg-alt)", border: "1px solid var(--border)", borderRadius: 14, fontSize: 10, color: "var(--muted)" }}>
                Hızlı yanıt yaz...
              </div>
              <button style={{
                width: 26, height: 26, borderRadius: "50%",
                background: "var(--accent)", color: "white", border: "none",
                cursor: "pointer", fontSize: 12,
              }}>↑</button>
            </div>
          </div>
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 4. BROADCAST DEMO — segmenting + sending progress
// ═══════════════════════════════════════════════════════════════
function BroadcastDemo({ speed = 1 }) {
  const total = 482;
  const [sent, setSent] = useStateD(0);

  useEffectD(() => {
    if (sent < total) {
      const t = setTimeout(() => {
        setSent((s) => Math.min(s + 7 + Math.floor(Math.random() * 8), total));
      }, 80 / speed);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => setSent(0), 2000 / speed);
      return () => clearTimeout(t);
    }
  }, [sent, speed]);

  const channels = [
    { ch: "wa", count: 268, color: "var(--whatsapp)" },
    { ch: "ig", count: 142, color: "var(--instagram)" },
    { ch: "tg", count: 72, color: "var(--telegram)" },
  ];

  const pct = (sent / total) * 100;

  return (
    <div className="demo-frame">
      <ScreenFrame label="broadcast / kampanya">
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12, height: "100%" }}>
          {/* segment chips */}
          <div>
            <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", textTransform: "uppercase", color: "var(--muted)", marginBottom: 5, letterSpacing: "0.05em" }}>Segment</div>
            <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              {[
                { l: "VIP müşteri", c: "var(--amber-bg)", t: "var(--amber-ink)" },
                { l: "Son 30 gün", c: "var(--accent-bg)", t: "var(--accent-ink)" },
                { l: "İstanbul", c: "var(--violet-bg)", t: "var(--violet)" },
              ].map((tag) => (
                <span key={tag.l} style={{
                  padding: "3px 7px", background: tag.c, color: tag.t,
                  fontSize: 9, fontWeight: 600, borderRadius: 4,
                  fontFamily: "var(--font-mono)",
                }}>{tag.l}</span>
              ))}
              <span style={{ fontSize: 10, color: "var(--muted)", marginLeft: "auto", fontFamily: "var(--font-mono)" }}>= {total} kişi</span>
            </div>
          </div>

          {/* message preview */}
          <div style={{
            padding: 10, background: "var(--bg-alt)",
            borderRadius: 7, border: "1px solid var(--border)",
            fontSize: 11, color: "var(--ink)", lineHeight: 1.5,
          }}>
            Merhaba <span style={{ color: "var(--accent-ink)", background: "var(--accent-bg)", padding: "0 4px", borderRadius: 3, fontFamily: "var(--font-mono)", fontSize: 10 }}>{`{ad}`}</span>, yeni koleksiyonumuz <span style={{ color: "var(--accent-ink)", background: "var(--accent-bg)", padding: "0 4px", borderRadius: 3, fontFamily: "var(--font-mono)", fontSize: 10 }}>{`{sektor}`}</span> için %15 indirimle 🌟
          </div>

          {/* progress */}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--muted)", marginBottom: 5 }}>
              <span>Gönderim {sent < total ? "akıyor" : "tamamlandı"}</span>
              <span style={{ color: sent < total ? "var(--accent-ink)" : "var(--accent)" }}>{sent}/{total}</span>
            </div>
            <div style={{ height: 8, background: "var(--bg-alt)", borderRadius: 4, overflow: "hidden", border: "1px solid var(--border)" }}>
              <div style={{
                height: "100%", width: `${pct}%`,
                background: "linear-gradient(90deg, var(--accent), oklch(from var(--accent) calc(l + 0.1) c h))",
                transition: "width 0.1s linear",
              }}></div>
            </div>
          </div>

          {/* per-channel breakdown */}
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {channels.map((ch) => {
              const chSent = Math.floor((sent / total) * ch.count);
              const chPct = (chSent / ch.count) * 100;
              return (
                <div key={ch.ch} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Ch kind={ch.ch} size={12} />
                  <div style={{ flex: 1 }}>
                    <div style={{ height: 4, background: "var(--bg-alt)", borderRadius: 2, overflow: "hidden" }}>
                      <div style={{
                        height: "100%", background: ch.color,
                        width: `${chPct}%`, transition: "width 0.1s linear",
                      }}></div>
                    </div>
                  </div>
                  <span style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--ink-2)", minWidth: 50, textAlign: "right" }}>
                    {chSent}/{ch.count}
                  </span>
                </div>
              );
            })}
          </div>

          {sent >= total && (
            <div style={{
              padding: "8px 10px", background: "var(--accent-bg)",
              borderRadius: 6, fontSize: 10, color: "var(--accent-ink)",
              display: "flex", alignItems: "center", gap: 8,
              fontWeight: 600, animation: "msg-in 0.4s ease-out",
            }}>
              <span style={{ width: 14, height: 14, borderRadius: "50%", background: "var(--accent)", color: "white", display: "grid", placeItems: "center", fontSize: 9 }}>✓</span>
              Hepsi teslim edildi · 4dk 12sn'de
            </div>
          )}
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 5. VOICE DEMO — waveform + transcript + translate
// ═══════════════════════════════════════════════════════════════
function VoiceDemo({ speed = 1 }) {
  const tr = "Yarın saat ondaki toplantı için kataloğu hazırlayabilir misiniz?";
  const en = "Can you prepare the catalog for tomorrow's 10am meeting?";
  const [phase, setPhase] = useStateD(0); // 0 idle, 1 playing, 2 transcribing, 3 done, 4 translated

  useEffectD(() => {
    const durs = [800, 1400, 1200, 1800, 1800];
    const t = setTimeout(() => setPhase((p) => (p + 1) % 5), durs[phase] / speed);
    return () => clearTimeout(t);
  }, [phase, speed]);

  // generate stable bars
  const bars = useMemoD(() => Array.from({ length: 38 }, (_, i) => 20 + Math.sin(i * 0.7) * 30 + Math.cos(i * 0.3) * 20), []);

  return (
    <div className="demo-frame">
      <ScreenFrame label="sohbet / sesli mesaj">
        <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14, height: "100%" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Ch kind="wa" size={14} />
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink)" }}>Mert Yıldız</div>
              <div style={{ fontSize: 9, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>14:23 · 0:08</div>
            </div>
          </div>

          {/* voice bubble */}
          <div style={{
            padding: "12px 14px", background: "var(--bg-alt)",
            borderRadius: 14, display: "flex", alignItems: "center", gap: 10,
            border: "1px solid var(--border)",
          }}>
            <button style={{
              width: 32, height: 32, borderRadius: "50%",
              background: phase >= 1 ? "var(--accent)" : "var(--ink)",
              color: "white", border: "none",
              display: "grid", placeItems: "center", fontSize: 13,
              cursor: "pointer", flexShrink: 0,
              transition: "background 0.3s",
            }}>{phase === 0 ? "▶" : "⏸"}</button>
            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 1.5, height: 32 }}>
              {bars.map((h, i) => (
                <div key={i} style={{
                  flex: 1,
                  height: `${h}%`,
                  background: phase >= 1 && i / bars.length < (phase === 1 ? 0.5 : 1)
                    ? "var(--accent)" : "var(--border)",
                  borderRadius: 1,
                  transition: "background 0.05s",
                }}></div>
              ))}
            </div>
            <span style={{ fontSize: 9, fontFamily: "var(--font-mono)", color: "var(--muted)" }}>0:08</span>
          </div>

          {/* transcript */}
          <div style={{
            padding: 12, background: phase >= 2 ? "var(--accent-bg)" : "var(--bg-alt)",
            border: `1px ${phase >= 2 ? "solid var(--accent)" : "dashed var(--border)"}`,
            borderRadius: 8, transition: "all 0.3s",
            minHeight: 60,
            display: "flex", flexDirection: "column", gap: 6,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ fontSize: 9, fontFamily: "var(--font-mono)", textTransform: "uppercase", color: phase >= 2 ? "var(--accent-ink)" : "var(--muted)", fontWeight: 600, letterSpacing: "0.05em" }}>
                Whisper transkript · TR
              </span>
              {phase === 2 && (
                <div style={{ display: "flex", gap: 2 }}>
                  <span className="td" style={{ animationDelay: "0s" }}></span>
                  <span className="td" style={{ animationDelay: "0.15s" }}></span>
                  <span className="td" style={{ animationDelay: "0.3s" }}></span>
                </div>
              )}
            </div>
            <div style={{ fontSize: 12, color: "var(--ink)", lineHeight: 1.5, opacity: phase >= 3 ? 1 : 0.4, transition: "opacity 0.3s" }}>
              {phase >= 3 ? tr : phase === 2 ? "..." : ""}
            </div>
          </div>

          {/* translation */}
          {phase >= 4 && (
            <div style={{
              padding: 12, background: "var(--violet-bg)",
              border: "1px solid var(--violet)",
              borderRadius: 8,
              animation: "msg-in 0.4s ease-out",
            }}>
              <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", textTransform: "uppercase", color: "var(--violet)", fontWeight: 600, letterSpacing: "0.05em", marginBottom: 4 }}>
                EN çeviri · GPT
              </div>
              <div style={{ fontSize: 12, color: "var(--ink)", fontStyle: "italic", lineHeight: 1.5 }}>
                {en}
              </div>
            </div>
          )}
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 6. TEAM DEMO — role permissions + activity log
// ═══════════════════════════════════════════════════════════════
function TeamDemo({ speed = 1 }) {
  const members = [
    { name: "Ali Yılmaz", role: "Yönetici", color: "var(--accent)", masked: false },
    { name: "Burcu Aydın", role: "Müdür", color: "var(--violet)", masked: false },
    { name: "Cenk Demir", role: "Temsilci", color: "var(--amber)", masked: true },
    { name: "Damla Öz", role: "Temsilci", color: "var(--sky)", masked: true },
  ];

  const activities = [
    { who: "Burcu", action: "Atlas Group → Teklif", time: "2dk", color: "var(--violet)" },
    { who: "Cenk", action: "Yenilik Tıp aradı", time: "8dk", color: "var(--amber)" },
    { who: "Ali", action: "Yeni şablon oluşturdu", time: "21dk", color: "var(--accent)" },
    { who: "Damla", action: "Café Roma → Yeni", time: "34dk", color: "var(--sky)" },
  ];

  const [step, setStep] = useStateD(0);
  useEffectD(() => {
    const t = setTimeout(() => setStep((s) => (s + 1) % activities.length), 1500 / speed);
    return () => clearTimeout(t);
  }, [step, speed, activities.length]);

  return (
    <div className="demo-frame">
      <ScreenFrame label="ekip / izinler">
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 12, height: "100%" }}>
          <div>
            <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6, letterSpacing: "0.05em" }}>
              Ekip · 4 üye
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
              {members.map((m) => (
                <div key={m.name} style={{
                  padding: "8px 10px", background: "var(--surface)",
                  border: "1px solid var(--border)", borderRadius: 6,
                  display: "flex", alignItems: "center", gap: 8,
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: "50%",
                    background: m.color, color: "white",
                    display: "grid", placeItems: "center",
                    fontWeight: 700, fontSize: 9,
                  }}>{m.name.split(" ").map((n) => n[0]).join("")}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11, fontWeight: 500, color: "var(--ink)" }}>{m.name}</div>
                    <div style={{ fontSize: 9, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>
                      {m.masked ? "+90 5•• ••• ••12" : "+90 532 110 4912"}
                    </div>
                  </div>
                  <span style={{
                    padding: "2px 6px", borderRadius: 4,
                    fontSize: 9, fontFamily: "var(--font-mono)", fontWeight: 600,
                    background: m.color, color: "white",
                  }}>{m.role}</span>
                </div>
              ))}
            </div>
          </div>

          {/* activity log */}
          <div style={{ flex: 1, minHeight: 0 }}>
            <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6, letterSpacing: "0.05em", display: "flex", alignItems: "center", gap: 6 }}>
              Canlı log
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", animation: "blink 1s infinite" }}></span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {activities.map((a, i) => {
                const isNew = i === step;
                return (
                  <div key={i} style={{
                    padding: "5px 8px", background: isNew ? "var(--accent-bg)" : "transparent",
                    borderRadius: 5, display: "flex", alignItems: "center", gap: 6,
                    fontSize: 10, transition: "background 0.3s",
                    border: isNew ? "1px solid var(--accent)" : "1px solid transparent",
                  }}>
                    <span style={{ width: 5, height: 5, borderRadius: "50%", background: a.color }}></span>
                    <span style={{ fontWeight: 600, color: "var(--ink)" }}>{a.who}</span>
                    <span style={{ color: "var(--ink-2)" }}>{a.action}</span>
                    <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", color: "var(--muted)", fontSize: 9 }}>{a.time}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 7. SOCIAL DEMO — composer + scheduled posts
// ═══════════════════════════════════════════════════════════════
function SocialDemo({ speed = 1 }) {
  const [active, setActive] = useStateD(0);
  const channels = [
    { key: "ig", label: "Instagram", color: "var(--instagram)" },
    { key: "fb", label: "Facebook", color: "var(--facebook)" },
    { key: "tg", label: "Telegram", color: "var(--telegram)" },
  ];

  useEffectD(() => {
    const t = setTimeout(() => setActive((a) => (a + 1) % channels.length), 1800 / speed);
    return () => clearTimeout(t);
  }, [active, speed, channels.length]);

  return (
    <div className="demo-frame">
      <ScreenFrame label="sosyal / planla">
        <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 10, height: "100%" }}>
          {/* channel toggles */}
          <div style={{ display: "flex", gap: 5 }}>
            {channels.map((c, i) => {
              const isOn = i <= active || active === channels.length - 1;
              return (
                <div key={c.key} style={{
                  flex: 1,
                  padding: "8px 10px",
                  background: isOn ? c.color : "var(--bg-alt)",
                  border: `1px solid ${isOn ? c.color : "var(--border)"}`,
                  borderRadius: 7,
                  display: "flex", alignItems: "center", gap: 6,
                  fontSize: 10, fontWeight: 600,
                  color: isOn ? "white" : "var(--muted)",
                  transition: "all 0.3s",
                }}>
                  <Ch kind={c.key} size={10} />
                  {c.label}
                  <span style={{ marginLeft: "auto", fontSize: 11 }}>{isOn ? "✓" : "○"}</span>
                </div>
              );
            })}
          </div>

          {/* composer */}
          <div style={{
            padding: 12, background: "var(--bg-alt)",
            borderRadius: 8, border: "1px solid var(--border)",
            display: "flex", flexDirection: "column", gap: 8, flex: 1,
          }}>
            <div style={{ fontSize: 11, color: "var(--ink)", lineHeight: 1.5 }}>
              ✨ <strong>Yeni koleksiyon</strong> sergi salonumuzda! Gel, dene, beğenmezsen geri al.
            </div>
            <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--accent-ink)" }}>
              #pırlanta #istanbul #yenikolleksiyon
            </div>
            {/* image placeholder */}
            <div style={{
              flex: 1, minHeight: 60,
              background: "linear-gradient(135deg, oklch(0.85 0.08 240), oklch(0.85 0.08 60))",
              borderRadius: 6, position: "relative", overflow: "hidden",
            }}>
              <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", color: "white", fontSize: 11, fontWeight: 600, opacity: 0.85 }}>
                gallery_2026.jpg
              </div>
            </div>
          </div>

          {/* schedule */}
          <div style={{
            display: "flex", alignItems: "center", gap: 8,
            padding: "8px 10px", background: "var(--surface)",
            border: "1px solid var(--border)", borderRadius: 7,
            fontSize: 10, fontFamily: "var(--font-mono)",
          }}>
            <span style={{ color: "var(--muted)" }}>⏱ Planlandı:</span>
            <span style={{ color: "var(--ink)", fontWeight: 600 }}>Yarın 10:00</span>
            <button style={{
              marginLeft: "auto", padding: "4px 10px",
              background: "var(--accent)", color: "white",
              border: "none", borderRadius: 4, fontSize: 10,
              fontWeight: 600, cursor: "pointer",
            }}>Sıraya al</button>
          </div>
        </div>
      </ScreenFrame>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// 8. INTEGRATIONS DEMO — connection diagram pulse
// ═══════════════════════════════════════════════════════════════
function IntegrationsDemo({ speed = 1 }) {
  const [pulse, setPulse] = useStateD(0);
  useEffectD(() => {
    const t = setTimeout(() => setPulse((p) => (p + 1) % 6), 700 / speed);
    return () => clearTimeout(t);
  }, [pulse, speed]);

  const sources = [
    { kind: "wa", label: "WhatsApp", angle: -150 },
    { kind: "ig", label: "Instagram", angle: -90 },
    { kind: "fb", label: "Facebook", angle: -30 },
    { kind: "tg", label: "Telegram", angle: 30 },
    { kind: "vk", label: "VK", angle: 90 },
    { kind: "web", label: "Web Form", angle: 150 },
  ];

  return (
    <div className="demo-frame">
      <ScreenFrame label="entegrasyonlar / hub">
        <div style={{ padding: 14, height: "100%", position: "relative", overflow: "hidden" }}>
          <div style={{
            position: "absolute", inset: 14,
            display: "grid", placeItems: "center",
          }}>
            <div style={{
              position: "relative", width: "100%", height: "100%",
            }}>
              {/* center hub */}
              <div style={{
                position: "absolute",
                top: "50%", left: "50%",
                transform: "translate(-50%, -50%)",
                width: 70, height: 70, borderRadius: "50%",
                background: "var(--ink)",
                color: "var(--bg)",
                display: "grid", placeItems: "center",
                boxShadow: "0 0 0 6px var(--surface), 0 0 0 7px var(--border), 0 8px 24px -6px oklch(0 0 0 / 0.3)",
                zIndex: 3,
              }}>
                <div style={{ fontSize: 18, fontWeight: 700, fontFamily: "var(--font-display)" }}>Y</div>
                <div style={{ position: "absolute", bottom: -2, fontSize: 8, fontFamily: "var(--font-mono)", letterSpacing: "0.1em" }}>YUKA</div>
              </div>

              {/* orbit ring */}
              <div style={{
                position: "absolute", top: "50%", left: "50%",
                width: 220, height: 220,
                transform: "translate(-50%, -50%)",
                borderRadius: "50%",
                border: "1px dashed var(--border)",
              }}></div>

              {/* sources */}
              {sources.map((s, i) => {
                const rad = (s.angle * Math.PI) / 180;
                const x = Math.cos(rad) * 110;
                const y = Math.sin(rad) * 110;
                const isActive = i === pulse;
                return (
                  <div key={s.kind} style={{
                    position: "absolute",
                    top: "50%", left: "50%",
                    transform: `translate(calc(${x}px - 50%), calc(${y}px - 50%))`,
                    zIndex: 2,
                  }}>
                    <div style={{
                      padding: "5px 10px",
                      background: "var(--surface)",
                      border: `1.5px solid ${isActive ? "var(--accent)" : "var(--border)"}`,
                      borderRadius: 999,
                      display: "flex", alignItems: "center", gap: 5,
                      fontSize: 10, fontWeight: 600, color: "var(--ink)",
                      boxShadow: isActive ? "0 0 0 4px oklch(from var(--accent) l c h / 0.2)" : "var(--shadow-sm)",
                      transition: "all 0.3s",
                      whiteSpace: "nowrap",
                    }}>
                      <Ch kind={s.kind} size={10} />
                      {s.label}
                    </div>
                  </div>
                );
              })}

              {/* animated lines */}
              <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}>
                {sources.map((s, i) => {
                  const rad = (s.angle * Math.PI) / 180;
                  const x = 50 + (Math.cos(rad) * 110) / (220 / 100);
                  const y = 50 + (Math.sin(rad) * 110) / (220 / 100);
                  const isActive = i === pulse;
                  return (
                    <line
                      key={s.kind}
                      x1="50%" y1="50%"
                      x2={`${x}%`} y2={`${y}%`}
                      stroke={isActive ? "var(--accent)" : "var(--border)"}
                      strokeWidth={isActive ? 2 : 1}
                      strokeDasharray={isActive ? "none" : "3 3"}
                      style={{ transition: "all 0.3s" }}
                    />
                  );
                })}
              </svg>
            </div>
          </div>

          {/* status footer */}
          <div style={{
            position: "absolute", bottom: 14, left: 14, right: 14,
            padding: "6px 10px",
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: 6,
            display: "flex", alignItems: "center", gap: 8,
            fontSize: 10, fontFamily: "var(--font-mono)",
          }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", animation: "blink 1.2s infinite" }}></span>
            <span style={{ color: "var(--ink)" }}>{sources[pulse].label}</span>
            <span style={{ color: "var(--muted)" }}>→ Yuka</span>
            <span style={{ marginLeft: "auto", color: "var(--accent-ink)" }}>● 6/6 senkron</span>
          </div>
        </div>
      </ScreenFrame>
    </div>
  );
}

Object.assign(window, {
  Ch, ScreenFrame,
  KanbanDemo, AvciDemo, ChatDemo, BroadcastDemo,
  VoiceDemo, TeamDemo, SocialDemo, IntegrationsDemo,
});
