// Habitat — canlı bir çevre.
// Sol: LIVE_CHAT (gerçek zamanlı baloncuklar, her ~2-4s yeni mesaj, presence sayacı).
// Orta: PRESENCE (kim ne yapıyor — operatörler ve ŞAHIN AI varlıkları).
// Sağ: TALEP_MASASI.

const SEEDS = [
  { user: "@bfsahin",     role: "FOUNDER",  div: "MTR/EML/SYS", txt: "ASELS hacim onayı geldi. Stop'u 76.20 tut, hedef 82.40." },
  { user: "@arzu_kont",   role: "OPERATOR", div: "MTR",         txt: "Konya OSB'de 3 protokol haberi · lojistiğe yansır." },
  { user: "$AHIN.AI",     role: "AI",       div: "CORE",        txt: "USD/TRY 33.91 üstü 4 saattir tutuyor. Range daralıyor, kırılım yakın." },
  { user: "@quant_iz",    role: "OPERATOR", div: "SYS",         txt: "ETH/BTC ratio 0.0521. RSI dipte ama hacim onaylamıyor henüz." },
  { user: "$AHIN.AI",     role: "AI",       div: "CORE",        txt: "GDELT'te DIV.EML ile alakalı 3 sinyal · imar revizyon haberi · doğrulanmadı." },
  { user: "@fxsignals",   role: "OPERATOR", div: "SYS",         txt: "Faiz kararı öncesi pozisyon hafiflettim. Risk on-off net değil." },
  { user: "@tarık_p",     role: "OPERATOR", div: "EML",         txt: "Ankara Çankaya parsel · imar 1/1000 yarın askıya çıkıyor." },
  { user: "$NOVA.AI",     role: "AI",       div: "MTR",         txt: "Filo telemetri · 14 araç servis aralığında, 3 acil bakım." },
  { user: "@operator_07", role: "OPERATOR", div: "SYS",         txt: "BIST açılış güçsüz, defans hattı dar range." },
  { user: "$AHIN.AI",     role: "AI",       div: "CORE",        txt: "BTC 70.8K civarı mum kapanışı bekliyorum. Üzeri açılırsa 73.4K hedefle." },
  { user: "@arzu_kont",   role: "OPERATOR", div: "MTR",         txt: "Yeni RFP geldi · ERP entegrasyon · €180k+ · TALEP_MASASI'nda." },
  { user: "$ARGOS.AI",    role: "AI",       div: "SYS",         txt: "Pentest scan · 0 critical, 2 high · supply-chain risk · raporu hazırlıyorum." },
  { user: "@bfsahin",     role: "FOUNDER",  div: "MTR/EML/SYS", txt: "Bu hafta Bursa filo + İzmir parsel kapanış. Disiplin." },
  { user: "$AHIN.AI",     role: "AI",       div: "CORE",        txt: "Frankfurter feed · EUR/TRY 36.84 · 30dk içinde 0.18% düşüş, momentum yok." },
  { user: "@kayra_d",     role: "OPERATOR", div: "EML",         txt: "Antalya off-plan · 3 birim ön rezerve geçti." },
  { user: "$NOVA.AI",     role: "AI",       div: "MTR",         txt: "Yakıt fiyatları %1.2 yukarı · filo bütçe revizyonu önerilir." },
];

const TALEP = [
  { ref: "T-2026-014", title: "Kurumsal · ERP entegrasyon · SAP S/4HANA",  status: "OPEN",     budget: "€180k+" },
  { ref: "T-2026-011", title: "Devlet · OSINT toplama altyapısı",           status: "REVIEW",   budget: "₺ kapalı" },
  { ref: "T-2026-009", title: "Holding · realtime FX/BIST trade dashboard", status: "AWARDED",  budget: "€95k" },
  { ref: "T-2026-007", title: "Banka · gri kutu pentest · web + mobile",    status: "OPEN",     budget: "€60k" },
];

// Inline 12px glyphs — no emoji. Crosshair / wave / spark / shield.
const Glyph = ({ kind, color }) => {
  const c = color || "currentColor";
  const sx = { width: 12, height: 12, flexShrink: 0 };
  if (kind === "FOUNDER") return (
    <svg style={sx} viewBox="0 0 12 12"><circle cx="6" cy="6" r="5" fill="none" stroke={c} strokeWidth="1"/><circle cx="6" cy="6" r="1.6" fill={c}/></svg>
  );
  if (kind === "AI") return (
    <svg style={sx} viewBox="0 0 12 12"><polygon points="6,1 11,6 6,11 1,6" fill="none" stroke={c} strokeWidth="1"/><circle cx="6" cy="6" r="1.4" fill={c}/></svg>
  );
  return (
    <svg style={sx} viewBox="0 0 12 12"><rect x="1.5" y="1.5" width="9" height="9" fill="none" stroke={c} strokeWidth="1"/></svg>
  );
};

const roleColor = r => r === "AI" ? "var(--phosphor)" : r === "FOUNDER" ? "var(--amber)" : "var(--wire-cyan)";

const Habitat = () => {
  const [thread, setThread] = React.useState(() => SEEDS.slice(0, 6).map((s, i) => ({ ...s, id: i, ts: tsNow(-((6 - i) * 47)) })));
  const [count, setCount] = React.useState(237);
  const [typing, setTyping] = React.useState(null);
  const idRef = React.useRef(thread.length);

  // Live mesaj akışı: her 2.4-4.6s yeni baloncuk.
  React.useEffect(() => {
    let cancelled = false;
    const loop = () => {
      const delay = 2400 + Math.random() * 2200;
      setTimeout(() => {
        if (cancelled) return;
        const seed = SEEDS[Math.floor(Math.random() * SEEDS.length)];
        // gösterim öncesi 700ms "yazıyor"
        setTyping({ user: seed.user, role: seed.role });
        setTimeout(() => {
          if (cancelled) return;
          setTyping(null);
          setThread(t => {
            const next = [...t, { ...seed, id: ++idRef.current, ts: tsNow(0) }];
            return next.length > 14 ? next.slice(-14) : next;
          });
        }, 700);
        loop();
      }, delay);
    };
    loop();
    return () => { cancelled = true; };
  }, []);

  // Presence sayacı: ~her 5s ±1
  React.useEffect(() => {
    const i = setInterval(() => setCount(v => Math.max(190, Math.min(280, v + (Math.random() > .5 ? 1 : -1)))), 1800);
    return () => clearInterval(i);
  }, []);

  const scrollerRef = React.useRef();
  React.useEffect(() => {
    if (scrollerRef.current) scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
  }, [thread, typing]);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1.1fr", gap: 8, height: "100%" }}>
      {/* LIVE_CHAT — anlık baloncuklar */}
      <div style={{ background: "var(--elevated)", border: "1px solid var(--edge)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "6px 10px", borderBottom: "1px solid var(--edge)", display: "flex", alignItems: "center", gap: 6 }}>
          <Eyebrow color="var(--bone)">LIVE_CHAT</Eyebrow>
          <span style={{ color: "var(--ash-deep)" }}>·</span>
          <Eyebrow>HABITAT</Eyebrow>
          <span style={{ marginLeft: "auto", display: "inline-flex", gap: 6, alignItems: "center" }}>
            <span style={{ width: 6, height: 6, background: "var(--phosphor)", borderRadius: "50%", boxShadow: "0 0 6px var(--phosphor)", animation: "blink 1.4s infinite" }}/>
            <span style={{ color: "var(--phosphor)", fontSize: 10, letterSpacing: ".14em", fontVariantNumeric: "tabular-nums", fontWeight: 700 }}>{count} CANLI</span>
          </span>
        </div>
        <div ref={scrollerRef} style={{ overflow: "auto", flex: 1, padding: "6px 0" }}>
          {thread.map(m => (
            <div key={m.id} style={{ padding: "5px 10px", animation: "fadein .3s ease-out" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
                <Glyph kind={m.role} color={roleColor(m.role)}/>
                <span style={{ color: roleColor(m.role), fontSize: 10, fontWeight: 700, letterSpacing: ".06em" }}>{m.user}</span>
                <span style={{ color: "var(--ash-deep)", fontSize: 9, letterSpacing: ".12em" }}>· {m.div}</span>
                <span style={{ marginLeft: "auto", color: "var(--ash-deep)", fontSize: 9, fontVariantNumeric: "tabular-nums" }}>{m.ts}</span>
              </div>
              <div style={{
                color: "var(--bone)", fontSize: 11, lineHeight: 1.45,
                paddingLeft: 18, borderLeft: `1px solid ${m.role === "AI" ? "rgba(53,255,170,.4)" : m.role === "FOUNDER" ? "rgba(255,176,0,.5)" : "var(--grid)"}`,
                marginLeft: 5,
              }}>{m.txt}</div>
            </div>
          ))}
          {typing && (
            <div style={{ padding: "5px 10px", color: "var(--ash)", fontSize: 10, display: "flex", alignItems: "center", gap: 6 }}>
              <Glyph kind={typing.role} color={roleColor(typing.role)}/>
              <span style={{ color: roleColor(typing.role), fontWeight: 700 }}>{typing.user}</span>
              <span>yazıyor</span>
              <span style={{ animation: "blink 1s steps(1) infinite" }}>▮</span>
              <span style={{ animation: "blink 1s steps(1) infinite .2s" }}>▮</span>
              <span style={{ animation: "blink 1s steps(1) infinite .4s" }}>▮</span>
            </div>
          )}
        </div>
        <div style={{ padding: 6, borderTop: "1px solid var(--edge)", display: "flex", gap: 6 }}>
          <input placeholder="// mesaj yaz, ENTER ile gönder" style={{
            flex: 1, background: "var(--panel)", border: "1px solid var(--edge)",
            color: "var(--bone)", fontFamily: "var(--font-mono)", fontSize: 11,
            padding: "5px 8px", outline: "none",
          }}/>
          <button className="btn btn--primary" style={{ fontSize: 9, padding: "5px 10px" }}>GÖNDER</button>
        </div>
      </div>

      {/* PRESENCE — kim ne yapıyor */}
      <div style={{ background: "var(--elevated)", border: "1px solid var(--edge)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "6px 10px", borderBottom: "1px solid var(--edge)", display: "flex", alignItems: "center", gap: 6 }}>
          <Eyebrow color="var(--bone)">PRESENCE</Eyebrow>
          <span style={{ color: "var(--ash-deep)" }}>·</span>
          <Eyebrow>NE YAPIYOR</Eyebrow>
        </div>
        <div style={{ flex: 1, overflow: "auto" }}>
          {[
            { u: "@bfsahin",   r: "FOUNDER",  d: "MTR/EML/SYS", a: "Ledger okuyor",      ago: "2dk" },
            { u: "$AHIN.AI",   r: "AI",       d: "CORE",        a: "BIST scan · 47ms",   ago: "canlı" },
            { u: "@arzu_kont", r: "OPERATOR", d: "MTR",         a: "Filo · servis listesi", ago: "8dk" },
            { u: "$NOVA.AI",   r: "AI",       d: "MTR",         a: "Telemetri · 14 araç", ago: "canlı" },
            { u: "@quant_iz",  r: "OPERATOR", d: "SYS",         a: "ETH/BTC chart",      ago: "1dk" },
            { u: "$ARGOS.AI",  r: "AI",       d: "SYS",         a: "Pentest scan · 62%", ago: "canlı" },
            { u: "@tarık_p",   r: "OPERATOR", d: "EML",         a: "İmar 1/1000 oku",    ago: "12dk" },
            { u: "@kayra_d",   r: "OPERATOR", d: "EML",         a: "Off-plan rezerve",   ago: "5dk" },
            { u: "@fxsignals", r: "OPERATOR", d: "SYS",         a: "FX position trim",   ago: "23dk" },
          ].map((p, i) => (
            <div key={i} style={{ padding: "6px 10px", borderBottom: "1px solid var(--grid)", display: "grid", gridTemplateColumns: "12px 1fr auto", gap: 8, alignItems: "center" }}>
              <Glyph kind={p.r} color={roleColor(p.r)}/>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: roleColor(p.r), letterSpacing: ".05em" }}>{p.u} <span style={{ color: "var(--ash-deep)", fontWeight: 400 }}>· {p.d}</span></div>
                <div style={{ fontSize: 10, color: "var(--bone-soft)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.a}</div>
              </div>
              <span style={{ fontSize: 9, color: p.ago === "canlı" ? "var(--phosphor)" : "var(--ash-deep)", letterSpacing: ".12em", fontVariantNumeric: "tabular-nums" }}>{p.ago}</span>
            </div>
          ))}
        </div>
      </div>

      {/* TALEP */}
      <div style={{ background: "var(--elevated)", border: "1px solid var(--edge)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "6px 10px", borderBottom: "1px solid var(--edge)", display: "flex", alignItems: "center", gap: 6 }}>
          <Eyebrow color="var(--bone)">TALEP_MASASI</Eyebrow>
          <span style={{ color: "var(--ash-deep)" }}>·</span>
          <Eyebrow>RFP</Eyebrow>
        </div>
        <div style={{ flex: 1, overflow: "auto" }}>
          {TALEP.map((t, i) => (
            <div key={i} style={{ padding: "8px 10px", borderBottom: "1px solid var(--grid)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                <span style={{ color: "var(--ash)", fontSize: 10, letterSpacing: ".08em" }}>{t.ref}</span>
                <span style={{
                  fontSize: 9, letterSpacing: ".16em", fontWeight: 700,
                  color: t.status === "OPEN" ? "var(--phosphor)" : t.status === "REVIEW" ? "var(--amber)" : "var(--ash)",
                }}>{t.status}</span>
              </div>
              <div style={{ color: "var(--bone)", fontSize: 11, lineHeight: 1.35 }}>{t.title}</div>
              <div style={{ color: "var(--amber)", fontSize: 10, marginTop: 3, fontVariantNumeric: "tabular-nums", letterSpacing: ".05em" }}>{t.budget}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: 8, borderTop: "1px solid var(--edge)" }}>
          <button className="btn btn--primary" style={{ width: "100%", fontSize: 10 }}>+ YENİ TALEP AÇ</button>
        </div>
      </div>

      <style>{`@keyframes fadein { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }`}</style>
    </div>
  );
};

function tsNow(offsetSec) {
  const d = new Date(Date.now() + offsetSec * 1000);
  const pad = n => String(n).padStart(2, "0");
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

window.Habitat = Habitat;
