// VIEWER VIEW — for curious, non-technical minds
const { useState, useEffect, useRef } = React;

const TICKER_MESSAGES = [
  { label: "SESSION OPEN", text: "Orchestrator receiving message · context assembly begins" },
  { label: "MEMORY QUERY", text: "Traversing graph · 3 contexts in scope · 18 chunks retrieved" },
  { label: "SPECIALIST ROUTE", text: "Dispatching to domain specialist · business_deal context active · memory scoped" },
  { label: "CONTEXT READY", text: "Specialist response assembled · writing to memory queue" },
  { label: "RESPONSE SENT", text: "Exchange delivered · write worker consolidation fired async" },
  { label: "GRAPH WRITE", text: "4 new chunks stored · topic affinities updated · session closed" },
];

const TENETS = [
  { label: "Nothing is deleted", body: "Every exchange is permanent. Corrections append to the record — they never overwrite it. The history of what was said, and how understanding changed, is always preserved." },
  { label: "Privacy is structural", body: "Context boundaries are encoded into the graph's topology. A query that can't reach a node by traversal cannot retrieve it — not by rule, by structure." },
  { label: "The system earns trust", body: "Proactive agency requires explicit consent, demonstrated reliability, and full auditability. The system waits to be trusted rather than assuming it." },
  { label: "Every decision is traceable", body: "Every insight, classification, and correction carries a provenance chain. Nothing happens without a record of why." },
];

const CONCEPTS = [
  {
    color: "#e8a84c",
    icon: (
      <svg viewBox="0 0 40 40" width="36" height="36">
        <circle cx="20" cy="20" r="7" fill="none" stroke="#e8a84c" strokeWidth="1.8"/>
        <circle cx="20" cy="6" r="4" fill="rgba(232,168,76,0.2)" stroke="#e8a84c" strokeWidth="1.5"/>
        <circle cx="34" cy="28" r="4" fill="rgba(232,168,76,0.2)" stroke="#e8a84c" strokeWidth="1.5"/>
        <circle cx="6" cy="28" r="4" fill="rgba(232,168,76,0.2)" stroke="#e8a84c" strokeWidth="1.5"/>
        <line x1="20" y1="13" x2="20" y2="27" stroke="#e8a84c" strokeWidth="1" opacity="0.6"/>
        <line x1="27" y1="25" x2="23" y2="23" stroke="#e8a84c" strokeWidth="1" opacity="0.6"/>
        <line x1="13" y1="25" x2="17" y2="23" stroke="#e8a84c" strokeWidth="1" opacity="0.6"/>
      </svg>
    ),
    title: "Agents",
    body: "The orchestrator coordinates. Domain specialists execute. Each agent has a defined scope of knowledge and access — and they collaborate without crossing boundaries.",
  },
  {
    color: "#9d7ee8",
    icon: (
      <svg viewBox="0 0 40 40" width="36" height="36">
        <circle cx="20" cy="20" r="10" fill="rgba(157,126,232,0.1)" stroke="#9d7ee8" strokeWidth="1.5"/>
        <circle cx="20" cy="20" r="4" fill="rgba(157,126,232,0.4)" stroke="#9d7ee8" strokeWidth="1.2"/>
        <circle cx="10" cy="12" r="3" fill="rgba(157,126,232,0.2)" stroke="#9d7ee8" strokeWidth="1"/>
        <circle cx="30" cy="12" r="3" fill="rgba(157,126,232,0.2)" stroke="#9d7ee8" strokeWidth="1"/>
        <circle cx="10" cy="28" r="3" fill="rgba(157,126,232,0.2)" stroke="#9d7ee8" strokeWidth="1"/>
        <circle cx="30" cy="28" r="3" fill="rgba(157,126,232,0.2)" stroke="#9d7ee8" strokeWidth="1"/>
        <line x1="13" y1="14" x2="17" y2="17" stroke="#9d7ee8" strokeWidth="1" opacity="0.5"/>
        <line x1="27" y1="14" x2="23" y2="17" stroke="#9d7ee8" strokeWidth="1" opacity="0.5"/>
        <line x1="13" y1="26" x2="17" y2="23" stroke="#9d7ee8" strokeWidth="1" opacity="0.5"/>
        <line x1="27" y1="26" x2="23" y2="23" stroke="#9d7ee8" strokeWidth="1" opacity="0.5"/>
      </svg>
    ),
    title: "Memory",
    body: "Every conversation is written into a permanent graph — not a flat log. The system knows who said what, when, and in what context, and can traverse that knowledge like a map.",
  },
  {
    color: "#38d4c8",
    icon: (
      <svg viewBox="0 0 40 40" width="36" height="36">
        <circle cx="20" cy="20" r="14" fill="none" stroke="#38d4c8" strokeWidth="1" strokeDasharray="3 4" opacity="0.5"/>
        <circle cx="20" cy="20" r="9" fill="none" stroke="#38d4c8" strokeWidth="1.2" strokeDasharray="4 3" opacity="0.7"/>
        <circle cx="20" cy="20" r="4" fill="rgba(56,212,200,0.3)" stroke="#38d4c8" strokeWidth="1.5"/>
      </svg>
    ),
    title: "Context",
    body: "Your data is organized into distinct contexts. Access is determined by graph structure — not by a policy engine that can be misconfigured. Personal memories cannot reach professional queries.",
  },
  {
    color: "#3dd68c",
    icon: (
      <svg viewBox="0 0 40 40" width="36" height="36">
        <path d="M 20 8 L 22 16 L 30 16 L 24 21 L 26 30 L 20 25 L 14 30 L 16 21 L 10 16 L 18 16 Z" fill="rgba(61,214,140,0.2)" stroke="#3dd68c" strokeWidth="1.5" strokeLinejoin="round"/>
      </svg>
    ),
    title: "Insight",
    body: "A background process traverses the graph while you sleep — not responding to questions, but noticing patterns. Clusters that formed across months. Connections you didn't name. The system shows what it noticed.",
  },
];

// SVG Flow Diagram
function FlowDiagram({ animSpeed = 1, labelDensity = "full" }) {
  const NODES = [
    { id: "you",    cx: 95,  cy: 385, r: 28, color: "#38d4c8", label: "YOU",          sub: null },
    { id: "sera",   cx: 365, cy: 240, r: 40, color: "#e8a84c", label: "ORCHESTRATOR", sub: "Routes · Assembles" },
    { id: "spec",   cx: 185, cy: 95,  r: 30, color: "#e8a84c", label: "SPECIALISTS",  sub: "Domain Experts" },
    { id: "mem",    cx: 630, cy: 135, r: 35, color: "#9d7ee8", label: "MEMORY",       sub: "FalkorDB Graph" },
    { id: "cara",   cx: 585, cy: 375, r: 26, color: "#38d4c8", label: "WRITE WORKER", sub: "Consolidates" },
  ];

  const FLOWS = [
    { id: "f1", d: "M 95 385 C 160 320 260 270 365 240",  color: "#38d4c8", dur: "2.6s", opacity: 1,   packets: 3 },
    { id: "f2", d: "M 365 240 C 270 295 175 345 95 385",  color: "#e8a84c", dur: "2.9s", opacity: 1,   packets: 3 },
    { id: "f3", d: "M 365 240 C 450 200 540 160 630 135", color: "#9d7ee8", dur: "2.2s", opacity: 1,   packets: 3 },
    { id: "f4", d: "M 630 135 C 555 170 465 210 365 240", color: "#9d7ee8", dur: "2.2s", opacity: 0.7, packets: 3, begin: 1.1 },
    { id: "f5", d: "M 365 240 C 315 190 250 140 185 95",  color: "#e8a84c", dur: "2.0s", opacity: 0.9, packets: 2 },
    { id: "f6", d: "M 185 95 C 250 135 315 190 365 240",  color: "#e8a84c", dur: "2.0s", opacity: 0.6, packets: 2, begin: 1.0 },
    { id: "f7", d: "M 365 240 C 440 295 515 345 585 375", color: "#38d4c8", dur: "2.5s", opacity: 0.4, packets: 2 },
    { id: "f8", d: "M 585 375 C 610 295 625 215 630 135", color: "#38d4c8", dur: "2.8s", opacity: 0.4, packets: 2 },
  ];

  return (
    <svg viewBox="0 0 740 490" width="100%" height="100%" style={{ overflow: "visible" }}>
      <defs>
        <filter id="glow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur in="SourceGraphic" stdDeviation="7" result="blur"/>
          <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        <filter id="glow-sm" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur"/>
          <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        {/* Gradient for background grid */}
        <radialGradient id="center-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#e8a84c" stopOpacity="0.04"/>
          <stop offset="100%" stopColor="#e8a84c" stopOpacity="0"/>
        </radialGradient>
      </defs>

      {/* Background glow center */}
      <ellipse cx="370" cy="240" rx="280" ry="180" fill="url(#center-glow)"/>

      {/* Flow paths — dashed guide lines */}
      {FLOWS.map(f => (
        <path key={f.id + "-line"}
          id={f.id}
          d={f.d}
          fill="none"
          stroke={f.color}
          strokeWidth={1}
          strokeDasharray="3 8"
          opacity={f.opacity * 0.25}
        />
      ))}

      {/* Animated packets */}
      {FLOWS.map(f =>
        Array.from({ length: f.packets }, (_, i) => {
          const adjDur = `${parseFloat(f.dur) / animSpeed}s`;
          const delay = (i / f.packets) * (parseFloat(f.dur) / animSpeed) + (f.begin || 0);
          return (
            <circle key={f.id + "-p" + i} r={f.opacity > 0.5 ? 4 : 3}
              fill={f.color}
              opacity={f.opacity * (1 - i * 0.15)}
              filter="url(#glow-sm)"
            >
              <animateMotion dur={adjDur} begin={`${delay}s`} repeatCount="indefinite">
                <mpath href={`#${f.id}`}/>
              </animateMotion>
            </circle>
          );
        })
      )}

      {/* Nodes */}
      {NODES.map(n => (
        <g key={n.id}>
          {/* Outer pulse ring */}
          <circle cx={n.cx} cy={n.cy} r={n.r + 6} fill="none" stroke={n.color} strokeWidth={1} opacity={0}>
            <animate attributeName="r" values={`${n.r+4};${n.r+18}`} dur="2.4s" repeatCount="indefinite" begin={n.id === "sera" ? "0s" : n.id === "mem" ? "0.8s" : "1.4s"}/>
            <animate attributeName="opacity" values="0.5;0" dur="2.4s" repeatCount="indefinite" begin={n.id === "sera" ? "0s" : n.id === "mem" ? "0.8s" : "1.4s"}/>
          </circle>
          {/* Glow halo */}
          <circle cx={n.cx} cy={n.cy} r={n.r + 2} fill={`rgba(${n.color === "#38d4c8" ? "56,212,200" : n.color === "#e8a84c" ? "232,168,76" : n.color === "#9d7ee8" ? "157,126,232" : "61,214,140"},0.08)`} filter="url(#glow)"/>
          {/* Main circle */}
          <circle cx={n.cx} cy={n.cy} r={n.r}
            fill={`rgba(${n.color === "#38d4c8" ? "56,212,200" : n.color === "#e8a84c" ? "232,168,76" : n.color === "#9d7ee8" ? "157,126,232" : "61,214,140"},0.1)`}
            stroke={n.color} strokeWidth={1.5}
          />
          {/* Label */}
          <text x={n.cx} y={n.cy - (n.sub ? 6 : 0)} textAnchor="middle"
            fill={n.color} fontSize={n.r > 35 ? 10 : 9} fontWeight="600"
            fontFamily="Space Grotesk, sans-serif" letterSpacing="0.08em">
            {n.label}
          </text>
          {n.sub && labelDensity === "full" && (
            <text x={n.cx} y={n.cy + 9} textAnchor="middle"
              fill={n.color} fontSize={7.5} opacity={0.55}
              fontFamily="Inter, sans-serif">
              {n.sub}
            </text>
          )}
        </g>
      ))}

      {/* Flow labels */}
      <text x="192" y="320" fill="#38d4c8" fontSize="8.5" opacity="0.45" fontFamily="Inter, sans-serif">message in</text>
      <text x="155" y="355" fill="#e8a84c" fontSize="8.5" opacity="0.45" fontFamily="Inter, sans-serif">response out</text>
      <text x="488" y="170" fill="#9d7ee8" fontSize="8.5" opacity="0.45" fontFamily="Inter, sans-serif">memory query</text>
      <text x="240" y="185" fill="#e8a84c" fontSize="8.5" opacity="0.45" fontFamily="Inter, sans-serif">dispatch</text>
      <text x="460" y="330" fill="#38d4c8" fontSize="8.5" opacity="0.35" fontFamily="Inter, sans-serif">async write</text>
    </svg>
  );
}

function ViewerView({ animSpeed = 1, labelDensity = "full" }) {
  const [tickerIdx, setTickerIdx] = useState(0);
  const [tickerVisible, setTickerVisible] = useState(true);

  useEffect(() => {
    const interval = setInterval(() => {
      setTickerVisible(false);
      setTimeout(() => {
        setTickerIdx(i => (i + 1) % TICKER_MESSAGES.length);
        setTickerVisible(true);
      }, 350);
    }, 2800);
    return () => clearInterval(interval);
  }, []);

  const tick = TICKER_MESSAGES[tickerIdx];

  return (
    <div style={{ height: "100%", overflowY: "auto", padding: "40px 48px 60px" }}>

      {/* Headline */}
      <div style={{ maxWidth: 860, margin: "0 auto 32px" }}>
        <p style={{ fontFamily: "Space Grotesk, sans-serif", fontSize: 11, letterSpacing: "0.16em", color: "var(--muted)", marginBottom: 14, textTransform: "uppercase" }}>The System</p>
        <h1 style={{ fontFamily: "Space Grotesk, sans-serif", fontWeight: 300, fontSize: "clamp(28px, 3.5vw, 46px)", color: "var(--text)", lineHeight: 1.2, marginBottom: 12 }}>
          Memory is efficient because<br/>
          <span style={{ color: "#e8a84c", fontWeight: 500 }}>context is explicit.</span>
        </h1>
        <p style={{ fontSize: 15, color: "var(--muted)", lineHeight: 1.7, maxWidth: 600 }}>
          An AI agent system that remembers — structured, private, and permanently auditable. Every conversation becomes knowledge. Every piece of knowledge knows its place.
        </p>
      </div>

      {/* SVG Diagram */}
      <div style={{ maxWidth: 860, margin: "0 auto", position: "relative" }}>
        <div style={{ height: "min(440px, 48vh)", position: "relative" }}>
          <FlowDiagram animSpeed={animSpeed} labelDensity={labelDensity}/>
        </div>

        {/* Ticker */}
        <div style={{
          display: "flex", alignItems: "center", gap: 14,
          padding: "10px 16px", margin: "0 auto",
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 6, maxWidth: 560,
          opacity: tickerVisible ? 1 : 0, transition: "opacity 0.3s ease",
        }}>
          <span style={{
            fontSize: 9, fontFamily: "JetBrains Mono, monospace", letterSpacing: "0.1em",
            color: "#3dd68c", background: "rgba(61,214,140,0.1)", padding: "2px 7px",
            borderRadius: 3, whiteSpace: "nowrap",
          }}>{tick.label}</span>
          <span style={{ fontSize: 12, color: "var(--muted)", fontFamily: "Inter, sans-serif" }}>{tick.text}</span>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#3dd68c", flexShrink: 0,
            animation: "blink 1.2s ease-in-out infinite" }}/>
        </div>
      </div>

      {/* Concept Cards */}
      <div style={{ maxWidth: 860, margin: "36px auto 0", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        {CONCEPTS.map(c => (
          <div key={c.title} style={{
            background: "var(--surface)", border: "1px solid var(--border)",
            borderRadius: 8, padding: "20px 16px",
            transition: "border-color 0.2s",
          }}
            onMouseEnter={e => e.currentTarget.style.borderColor = c.color + "60"}
            onMouseLeave={e => e.currentTarget.style.borderColor = "var(--border)"}
          >
            <div style={{ marginBottom: 12 }}>{c.icon}</div>
            <div style={{ fontFamily: "Space Grotesk, sans-serif", fontWeight: 600, fontSize: 13, color: c.color, marginBottom: 8 }}>{c.title}</div>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.65 }}>{c.body}</div>
          </div>
        ))}
      </div>

      {/* Tenets */}
      <div style={{ maxWidth: 860, margin: "40px auto 0" }}>
        <p style={{ fontFamily: "Space Grotesk, sans-serif", fontSize: 10, letterSpacing: "0.14em", color: "var(--dim)", marginBottom: 20, textTransform: "uppercase" }}>Architectural Tenets</p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          {TENETS.map((t, i) => (
            <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
              <div style={{ width: 3, height: 3, borderRadius: "50%", background: "#e8a84c", marginTop: 7, flexShrink: 0 }}/>
              <div>
                <div style={{ fontFamily: "Space Grotesk, sans-serif", fontWeight: 600, fontSize: 13, color: "var(--text)", marginBottom: 5 }}>{t.label}</div>
                <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.7 }}>{t.body}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

window.ViewerView = ViewerView;
