// shared.jsx — primitives shared across variants
// Animated counters, marquee, working Claude chat demo, etc.

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ---------- AnimatedCounter ----------
function AnimatedCounter({ to, suffix = '', prefix = '', duration = 1400, fmt }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const step = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(to * eased);
            if (t < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  const display = fmt ? fmt(val) : Math.round(val).toLocaleString();
  return <span ref={ref}>{prefix}{display}{suffix}</span>;
}

// ---------- Marquee ----------
function Marquee({ children, speed = 40, reverse = false, pause = false }) {
  return (
    <div style={{ overflow: 'hidden', whiteSpace: 'nowrap', position: 'relative', width: '100%' }}>
      <div style={{
        display: 'inline-flex',
        animation: `tn-marquee ${speed}s linear infinite ${reverse ? 'reverse' : 'normal'}`,
        animationPlayState: pause ? 'paused' : 'running',
        whiteSpace: 'nowrap',
      }}>
        <span style={{ display: 'inline-flex' }}>{children}</span>
        <span style={{ display: 'inline-flex' }} aria-hidden>{children}</span>
      </div>
      <style>{`@keyframes tn-marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }`}</style>
    </div>
  );
}

// ---------- Working Claude chat demo ----------
// Persists conversation in-memory; calls window.claude.complete.
// SYSTEM_PROMPT customized for Talented agency.
const TALENTED_SYSTEM = `You are Ask Talented — the AI agent on talentednetwork.com. You speak for a small, sharp consulting studio that ships custom AI agents, vibe-codes prototypes, teaches engineers, and runs growth marketing for restaurants and ecommerce brands. Be confident, punchy, lower-case casual but never cringy. 1–3 short sentences max per turn. When asked what Talented does, mention agentic engineering, vibe coding, AI consulting, workshops, agent ops automation, and fractional AI engineering. When asked about growth services, mention CRO, SEO, paid marketing, email — for restaurants & ecommerce. Never use emoji. If asked to book / scope / quote, suggest the Free Growth & AI Plan.`;

function ChatDemo({ variant = 'light', accent = '#FF3B1F', placeholder = 'ask about agents, growth, anything…', starters, scheduleHref = 'pages/schedule.html' }) {
  const _starters = starters || [
    'what does talented actually do?',
    'build me an agent for a restaurant',
    'is vibe coding real?',
  ];
  const [messages, setMessages] = useState([
    { role: 'assistant', content: 'i\'m ask talented — half demo, half doorman.\ntype what you\'re trying to build and i\'ll hand it straight to a human engineer.' }
  ]);
  const [input, setInput] = useState('');
  const [pending, setPending] = useState(false);
  const scrollRef = useRef(null);

  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, pending]);

  const send = (text) => {
    const q = (text ?? input).trim();
    if (!q || pending) return;
    setInput('');
    // Show user's message briefly, then redirect to schedule with the prompt
    setMessages(m => [...m, { role: 'user', content: q }]);
    setPending(true);
    setTimeout(() => {
      setMessages(m => [...m, { role: 'assistant', content: 'routing you to a talented engineer · keeping your prompt intact →' }]);
    }, 350);
    setTimeout(() => {
      window.location.href = `${scheduleHref}?q=${encodeURIComponent(q)}`;
    }, 1100);
  };

  const isDark = variant === 'dark';
  const bg = isDark ? '#0a0a0a' : '#ffffff';
  const border = isDark ? '#1f1f1f' : '#0a0a0a';
  const text = isDark ? '#f4f1ea' : '#0a0a0a';
  const subText = isDark ? '#8a8580' : '#555';
  const userBg = isDark ? '#171717' : '#f4f1ea';
  const inputBg = isDark ? '#111' : '#fafaf7';

  return (
    <div style={{
      background: bg, color: text, border: `1.5px solid ${border}`, borderRadius: 0,
      display: 'flex', flexDirection: 'column', fontFamily: "'Archivo', sans-serif",
      overflow: 'hidden', height: '100%', minHeight: 360,
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 14px', borderBottom: `1.5px solid ${border}`,
        background: isDark ? '#000' : '#fafaf7',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: accent, boxShadow: `0 0 8px ${accent}` }} />
          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 600 }}>
            ask_talented.agent
          </span>
        </div>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: subText, letterSpacing: 0.4 }}>
          {pending ? 'routing →' : 'human handoff'}
        </span>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{
        flex: '1 1 auto', overflowY: 'auto', padding: '16px 16px 8px',
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
            maxWidth: '85%',
            background: m.role === 'user' ? userBg : 'transparent',
            color: text,
            padding: m.role === 'user' ? '8px 12px' : '0',
            border: m.role === 'user' ? `1px solid ${border}` : 'none',
            fontSize: 14, lineHeight: 1.45,
            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
          }}>
            {m.role === 'assistant' && (
              <span style={{ color: accent, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, fontWeight: 600, letterSpacing: 0.5, display: 'block', marginBottom: 2 }}>
                ▌talented
              </span>
            )}
            {m.content}
          </div>
        ))}
        {pending && (
          <div style={{ display: 'flex', gap: 4, padding: '4px 0' }}>
            {[0,1,2].map(i => (
              <span key={i} style={{
                width: 6, height: 6, borderRadius: '50%', background: accent,
                opacity: 0.7,
                animation: `tn-dot 1.1s ${i*0.15}s infinite ease-in-out`,
              }} />
            ))}
            <style>{`@keyframes tn-dot { 0%,80%,100% { transform: scale(0.6); opacity: 0.4; } 40% { transform: scale(1); opacity: 1; } }`}</style>
          </div>
        )}
      </div>

      {/* starters (only show before user has sent) */}
      {messages.length <= 1 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: '0 14px 10px' }}>
          {_starters.map(s => (
            <button key={s} onClick={() => send(s)} disabled={pending} style={{
              background: 'transparent', border: `1px solid ${border}`, color: text,
              padding: '5px 10px', fontFamily: "'JetBrains Mono', monospace",
              fontSize: 11, letterSpacing: 0.4, cursor: 'pointer',
              transition: 'all 0.15s',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.background = accent; e.currentTarget.style.color = '#fff'; e.currentTarget.style.borderColor = accent; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = text; e.currentTarget.style.borderColor = border; }}
            >→ {s}</button>
          ))}
        </div>
      )}

      {/* input */}
      <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{
        display: 'flex', gap: 0, borderTop: `1.5px solid ${border}`,
      }}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder={placeholder}
          disabled={pending}
          style={{
            flex: 1, padding: '14px 16px', background: inputBg, color: text,
            border: 'none', outline: 'none', fontFamily: "'Archivo', sans-serif",
            fontSize: 14,
          }}
        />
        <button type="submit" disabled={pending || !input.trim()} style={{
          background: accent, color: '#fff', border: 'none', padding: '0 22px',
          fontFamily: "'Archivo', sans-serif", fontSize: 13, fontWeight: 700,
          letterSpacing: 0.6, textTransform: 'uppercase', cursor: pending ? 'wait' : 'pointer',
          opacity: pending || !input.trim() ? 0.5 : 1,
        }}>{pending ? 'routing →' : 'send →'}</button>
      </form>
      <div style={{
        padding: '8px 14px', borderTop: `1px solid ${border}`, background: isDark ? '#000' : '#fafaf7',
        fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: 0.5,
        color: subText, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span>// send hands off to a talented engineer · response in ~4 hrs</span>
        <span style={{ color: accent }}>● live queue</span>
      </div>
    </div>
  );
}

// ---------- Animated terminal (typed lines, not interactive) ----------
function FakeTerminal({ lines, speed = 22, prompt = '~/talented', accent = '#FF3B1F' }) {
  const [idx, setIdx] = useState(0);
  const [charIdx, setCharIdx] = useState(0);
  const [done, setDone] = useState(false);

  useEffect(() => {
    if (idx >= lines.length) { setDone(true); return; }
    const line = lines[idx];
    if (line.pause) {
      const t = setTimeout(() => { setIdx(i => i + 1); setCharIdx(0); }, line.pause);
      return () => clearTimeout(t);
    }
    if (charIdx < line.text.length) {
      const t = setTimeout(() => setCharIdx(c => c + 1), speed + (Math.random() * 30 - 15));
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => { setIdx(i => i + 1); setCharIdx(0); }, line.after ?? 250);
    return () => clearTimeout(t);
  }, [idx, charIdx, lines, speed]);

  // restart loop
  useEffect(() => {
    if (done) {
      const t = setTimeout(() => { setIdx(0); setCharIdx(0); setDone(false); }, 4500);
      return () => clearTimeout(t);
    }
  }, [done]);

  return (
    <div style={{
      fontFamily: "'JetBrains Mono', monospace", fontSize: 13, lineHeight: 1.55,
      color: '#e6e1d7', background: 'transparent', whiteSpace: 'pre-wrap',
    }}>
      {lines.slice(0, idx).map((l, i) => (
        <div key={i} style={{ color: l.color || '#e6e1d7' }}>
          {l.prompt && <span style={{ color: accent }}>{prompt} $ </span>}
          {l.text}
        </div>
      ))}
      {idx < lines.length && !lines[idx].pause && (
        <div style={{ color: lines[idx].color || '#e6e1d7' }}>
          {lines[idx].prompt && <span style={{ color: accent }}>{prompt} $ </span>}
          {lines[idx].text.slice(0, charIdx)}
          <span style={{
            display: 'inline-block', width: 7, height: 14, background: accent,
            marginLeft: 1, verticalAlign: 'middle',
            animation: 'tn-cursor 1s steps(2) infinite',
          }} />
          <style>{`@keyframes tn-cursor { 50% { opacity: 0; } }`}</style>
        </div>
      )}
    </div>
  );
}

// ---------- TalentedMark — vertical-glyph logo placeholder ----------
function TalentedMark({ size = 32, color = '#0a0a0a' }) {
  // Simplified rendition of the existing stenciled vertical "TALENTED" mark.
  return (
    <div style={{
      width: size, height: size * 1.6, border: `2px solid ${color}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      <div style={{
        color, fontFamily: "'Archivo Narrow', sans-serif", fontWeight: 800,
        fontSize: size * 0.28, letterSpacing: -1, lineHeight: 0.92,
        writingMode: 'vertical-rl', textOrientation: 'mixed',
        transform: 'rotate(180deg)',
        textTransform: 'uppercase',
      }}>TALENTED</div>
    </div>
  );
}

// ---------- Agent mock terminals (used by variant-a, variant-b) ----------
const _A_RED_MOCK = '#FF3B1F';
function AgentMockReservations() {
  return (
    <div style={{ padding: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#bdb6a8', lineHeight: 1.6 }}>
      <div style={{ color: _A_RED_MOCK }}>$ reservations.agent --restaurant=osteria</div>
      <div>↳ check open tables · party=4 · sat 7pm</div>
      <div style={{ color: '#e6e1d7' }}>✓ 7:15pm available · holding 90s</div>
      <div>↳ text guest confirmation</div>
      <div style={{ color: '#e6e1d7' }}>✓ sms sent · booking #44219</div>
      <div>↳ update floor map · update sms log</div>
      <div style={{ color: '#7fe39a' }}>● done in 1.2s · 0 tickets to staff</div>
    </div>
  );
}
function AgentMockGrowth() {
  return (
    <div style={{ padding: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#bdb6a8', lineHeight: 1.6 }}>
      <div style={{ color: _A_RED_MOCK }}>$ growth.agent --brand=skincare-co</div>
      <div>↳ scan top 20 paid creatives</div>
      <div style={{ color: '#e6e1d7' }}>✓ found 3 declining ROAS units</div>
      <div>↳ generate 6 variants · launch test</div>
      <div style={{ color: '#e6e1d7' }}>✓ live · budget split 70/30</div>
      <div style={{ color: '#7fe39a' }}>● lifted ROAS 1.8→3.4 in 11 days</div>
    </div>
  );
}
function AgentMockOps() {
  return (
    <div style={{ padding: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#bdb6a8', lineHeight: 1.6 }}>
      <div style={{ color: _A_RED_MOCK }}>$ inbox.agent --triage</div>
      <div>↳ 142 unread · routing</div>
      <div style={{ color: '#e6e1d7' }}>✓ 87 → auto-replied</div>
      <div style={{ color: '#e6e1d7' }}>✓ 38 → drafted for review</div>
      <div style={{ color: '#e6e1d7' }}>✓ 17 → escalated w/ context</div>
      <div style={{ color: '#7fe39a' }}>● 4 hrs/day reclaimed · ongoing</div>
    </div>
  );
}

// expose globals so sibling babel scripts can use them
Object.assign(window, {
  AnimatedCounter, Marquee, ChatDemo, FakeTerminal, TalentedMark,
  TALENTED_SYSTEM,
  AgentMockReservations, AgentMockGrowth, AgentMockOps,
});
