'use client';

/**
 * /demo — Public demo page for Embris Companion
 *
 * KYA — Know Your Agent.
 * One experience: trust score front and center, then talk to Embris.
 * No wallet required.
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import { getBrainEngine } from '../lib/brain-engine';

/* ─── Demo data ─────────────────────────────────────────── */
const DEMO_TRUST_SCORE = 87;
const DEMO_RATING = 'A';

const DEMO_CHAT_STARTERS = [
  'What is Vaultfire Protocol?',
  'How do accountability bonds work?',
  'What makes Embris different from ChatGPT?',
  'Tell me about ERC-8004',
];

/* ─── Trust score colour helper ─────────────────────────── */
function trustColor(score: number): string {
  if (score >= 80) return '#22C55E';
  if (score >= 60) return '#F59E0B';
  return '#EF4444';
}

/* ─── Big trust score badge ─────────────────────────────── */
function TrustBadge({ score, rating }: { score: number; rating: string }) {
  const color = trustColor(score);
  const ringSize = 140;
  const r = 56;
  const circumference = 2 * Math.PI * r;
  const dashOffset = circumference * (1 - score / 100);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
      {/* SVG ring */}
      <div style={{ position: 'relative', width: ringSize, height: ringSize }}>
        <svg width={ringSize} height={ringSize} viewBox={`0 0 ${ringSize} ${ringSize}`} style={{ transform: 'rotate(-90deg)' }}>
          {/* Background ring */}
          <circle
            cx={ringSize / 2} cy={ringSize / 2} r={r}
            fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="10"
          />
          {/* Score arc */}
          <circle
            cx={ringSize / 2} cy={ringSize / 2} r={r}
            fill="none" stroke={color} strokeWidth="10"
            strokeDasharray={circumference}
            strokeDashoffset={dashOffset}
            strokeLinecap="round"
            style={{ filter: `drop-shadow(0 0 8px ${color}60)`, transition: 'stroke-dashoffset 1s ease' }}
          />
        </svg>
        {/* Score number */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <span style={{ fontSize: 36, fontWeight: 800, color, fontFamily: "'JetBrains Mono', monospace", lineHeight: 1 }}>
            {score}
          </span>
          <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', fontWeight: 600, marginTop: 2 }}>/ 100</span>
        </div>
      </div>

      {/* Letter grade pill */}
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: '6px 18px', borderRadius: 20,
        backgroundColor: `${color}12`,
        border: `1.5px solid ${color}40`,
      }}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: color, boxShadow: `0 0 6px ${color}80` }} />
        <span style={{ fontSize: 14, fontWeight: 700, color, letterSpacing: '0.04em' }}>
          Grade {rating} — Trusted
        </span>
      </div>
    </div>
  );
}

/* ─── Main demo page ─────────────────────────────────────── */
export default function DemoPage() {
  const [chatMessages, setChatMessages] = useState<Array<{ role: 'user' | 'embris'; text: string }>>([]);
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const chatEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatMessages]);

  const handleSendMessage = useCallback(async (message?: string) => {
    const msg = message || inputValue.trim();
    if (!msg) return;
    setInputValue('');
    setChatMessages(prev => [...prev, { role: 'user', text: msg }]);
    setIsTyping(true);

    try {
      const brain = getBrainEngine();
      const results = brain.search(msg, 3);
      let response: string;
      if (results.length > 0 && results[0].relevanceScore > 0.2) {
        response = results[0].entry.content;
        if (results.length > 1 && results[1].relevanceScore > 0.3) {
          response += '\n\n' + results[1].entry.content;
        }
      } else {
        response = `Great question! In the full version I have deep knowledge on this. Connect your wallet to experience Embris with real on-chain accountability and partnership bonds.`;
      }
      await new Promise(resolve => setTimeout(resolve, 700 + Math.random() * 500));
      setChatMessages(prev => [...prev, { role: 'embris', text: response }]);
    } catch {
      await new Promise(resolve => setTimeout(resolve, 500));
      setChatMessages(prev => [...prev, {
        role: 'embris',
        text: "I'm Embris — Vaultfire's first verified AI companion. My full brain runs locally on your device. Connect your wallet to experience the real thing!",
      }]);
    }
    setIsTyping(false);
  }, [inputValue]);

  return (
    <div style={{ minHeight: '100vh', backgroundColor: '#09090B', color: '#F4F4F5' }}>
      <div style={{ maxWidth: 680, margin: '0 auto', padding: '48px 20px 64px' }}>

        {/* ── Alpha disclaimer — visible but not overwhelming ── */}
        <div style={{
          display: 'flex', alignItems: 'flex-start', gap: 10,
          padding: '10px 14px', borderRadius: 10,
          backgroundColor: 'rgba(234,179,8,0.06)',
          border: '1px solid rgba(234,179,8,0.20)',
          marginBottom: 48,
        }}>
          <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="#EAB308" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
            <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
          </svg>
          <p style={{ fontSize: 11, color: '#A1A1AA', margin: 0, lineHeight: 1.6 }}>
            <strong style={{ color: '#EAB308' }}>Alpha — not audited.</strong>{' '}
            Smart contracts are live but have not been audited. Do not use with significant funds. All on-chain transactions are{' '}
            <strong style={{ color: '#D4D4D8' }}>irreversible</strong>.
          </p>
        </div>

        {/* ── Trust score badge ── */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <TrustBadge score={DEMO_TRUST_SCORE} rating={DEMO_RATING} />
        </div>

        {/* ── Embris intro ── */}
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <h1 style={{ fontSize: 26, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.03em', marginBottom: 8 }}>
            This is Embris.
          </h1>
          <p style={{ fontSize: 15, color: '#71717A', lineHeight: 1.65, maxWidth: 480, margin: '0 auto' }}>
            Vaultfire&apos;s first verified AI companion — on-chain identity, accountability bond, and local brain.
          </p>
        </div>

        {/* ── Three proof items ── */}
        <div style={{
          display: 'flex', flexDirection: 'column', gap: 10,
          marginBottom: 48,
          padding: '20px 24px',
          borderRadius: 16,
          backgroundColor: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.06)',
        }}>
          {[
            {
              label: 'Verified Identity',
              desc: 'Registered on-chain via ERC-8004 — a cryptographic proof, not a username.',
              color: '#A78BFA',
            },
            {
              label: 'Accountability Bond',
              desc: 'Real ETH staked on-chain. Violations are recorded permanently.',
              color: '#F97316',
            },
            {
              label: 'Local Brain',
              desc: 'Everything runs on your device. No cloud. No surveillance. No KYC.',
              color: '#22C55E',
            },
          ].map((item) => (
            <div key={item.label} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              {/* Checkmark */}
              <div style={{
                width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
                backgroundColor: `${item.color}14`,
                border: `1.5px solid ${item.color}40`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                marginTop: 1,
              }}>
                <svg width={11} height={11} viewBox="0 0 24 24" fill="none" stroke={item.color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </div>
              <div>
                <p style={{ fontSize: 13, fontWeight: 700, color: '#F4F4F5', marginBottom: 2 }}>{item.label}</p>
                <p style={{ fontSize: 12, color: '#71717A', lineHeight: 1.55 }}>{item.desc}</p>
              </div>
            </div>
          ))}
        </div>

        {/* ── Chat interface ── */}
        <div style={{
          borderRadius: 18,
          border: '1px solid rgba(249,115,22,0.14)',
          backgroundColor: 'rgba(249,115,22,0.02)',
          overflow: 'hidden',
          marginBottom: 48,
        }}>
          {/* Chat header */}
          <div style={{
            padding: '16px 20px',
            borderBottom: '1px solid rgba(255,255,255,0.05)',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'linear-gradient(135deg, rgba(249,115,22,0.25), rgba(167,139,250,0.15))',
              border: '1.5px solid rgba(249,115,22,0.3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <svg width={16} height={16} viewBox="0 0 32 32" fill="none">
                <path d="M16 4c-3 3.5-6 8-6 12 0 3.31 2.69 6 6 6s6-2.69 6-6c0-4-3-8.5-6-12z" fill="#F97316" opacity="0.9"/>
                <path d="M16 10c-1.5 2-3 4.5-3 6.5 0 1.66 1.34 3 3 3s3-1.34 3-3c0-2-1.5-4.5-3-6.5z" fill="#FB923C"/>
              </svg>
            </div>
            <div>
              <p style={{ fontSize: 13, fontWeight: 700, color: '#F4F4F5', margin: 0 }}>Embris</p>
              <p style={{ fontSize: 10, color: '#52525B', margin: 0 }}>Ask anything — no wallet required</p>
            </div>
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 5 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: '#22C55E', boxShadow: '0 0 6px rgba(34,197,94,0.6)' }} />
              <span style={{ fontSize: 10, color: '#22C55E', fontWeight: 600 }}>Online</span>
            </div>
          </div>

          {/* Messages */}
          <div style={{ height: 320, overflowY: 'auto', padding: '20px' }}>
            {chatMessages.length === 0 && (
              <div style={{ textAlign: 'center', paddingTop: 32 }}>
                <p style={{ fontSize: 12, color: '#52525B', marginBottom: 16 }}>Ask Embris anything about Vaultfire</p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center' }}>
                  {DEMO_CHAT_STARTERS.map(q => (
                    <button
                      key={q}
                      onClick={() => handleSendMessage(q)}
                      style={{
                        padding: '8px 14px', borderRadius: 8,
                        backgroundColor: 'rgba(249,115,22,0.06)', border: '1px solid rgba(249,115,22,0.12)',
                        color: '#F97316', fontSize: 11, cursor: 'pointer',
                        transition: 'all 0.15s ease',
                      }}
                      onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'rgba(249,115,22,0.12)'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'rgba(249,115,22,0.06)'; }}
                    >
                      {q}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {chatMessages.map((msg, i) => (
              <div key={i} style={{
                display: 'flex', gap: 10, marginBottom: 16,
                flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  backgroundColor: msg.role === 'embris' ? 'rgba(249,115,22,0.12)' : 'rgba(99,102,241,0.12)',
                  border: `1px solid ${msg.role === 'embris' ? 'rgba(249,115,22,0.2)' : 'rgba(99,102,241,0.2)'}`,
                }}>
                  {msg.role === 'embris' ? (
                    <svg width={14} height={14} viewBox="0 0 32 32" fill="none">
                      <path d="M16 4c-3 3.5-6 8-6 12 0 3.31 2.69 6 6 6s6-2.69 6-6c0-4-3-8.5-6-12z" fill="#F97316" opacity="0.9"/>
                    </svg>
                  ) : (
                    <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="#6366F1" strokeWidth="2">
                      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                    </svg>
                  )}
                </div>
                <div style={{
                  maxWidth: '75%', padding: '10px 14px', borderRadius: 12,
                  backgroundColor: msg.role === 'embris' ? 'rgba(249,115,22,0.04)' : 'rgba(99,102,241,0.06)',
                  border: `1px solid ${msg.role === 'embris' ? 'rgba(249,115,22,0.08)' : 'rgba(99,102,241,0.1)'}`,
                }}>
                  <p style={{ fontSize: 12, color: '#E4E4E7', lineHeight: 1.6, margin: 0, whiteSpace: 'pre-wrap' }}>{msg.text}</p>
                </div>
              </div>
            ))}
            {isTyping && (
              <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  backgroundColor: 'rgba(249,115,22,0.12)', border: '1px solid rgba(249,115,22,0.2)',
                }}>
                  <svg width={14} height={14} viewBox="0 0 32 32" fill="none">
                    <path d="M16 4c-3 3.5-6 8-6 12 0 3.31 2.69 6 6 6s6-2.69 6-6c0-4-3-8.5-6-12z" fill="#F97316" opacity="0.9"/>
                  </svg>
                </div>
                <div style={{ padding: '10px 14px', borderRadius: 12, backgroundColor: 'rgba(249,115,22,0.04)', border: '1px solid rgba(249,115,22,0.08)' }}>
                  <div style={{ display: 'flex', gap: 4 }}>
                    {[0, 1, 2].map(d => (
                      <div key={d} style={{
                        width: 6, height: 6, borderRadius: '50%', backgroundColor: '#F97316',
                        animation: `pulse 1.2s ease-in-out ${d * 0.2}s infinite`,
                        opacity: 0.4,
                      }} />
                    ))}
                  </div>
                </div>
              </div>
            )}
            <div ref={chatEndRef} />
          </div>

          {/* Input */}
          <div style={{
            padding: '14px 16px', borderTop: '1px solid rgba(255,255,255,0.06)',
            display: 'flex', gap: 8,
          }}>
            <input
              type="text"
              value={inputValue}
              onChange={e => setInputValue(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSendMessage()}
              placeholder="Ask Embris anything..."
              style={{
                flex: 1, padding: '11px 16px', borderRadius: 10,
                backgroundColor: '#111113', border: '1px solid rgba(255,255,255,0.07)',
                color: '#F4F4F5', fontSize: 13, outline: 'none',
                transition: 'border-color 0.15s ease',
              }}
              onFocus={(e) => { e.currentTarget.style.borderColor = 'rgba(249,115,22,0.35)'; }}
              onBlur={(e) => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.07)'; }}
            />
            <button
              onClick={() => handleSendMessage()}
              disabled={isTyping || !inputValue.trim()}
              style={{
                padding: '11px 22px', borderRadius: 10,
                background: inputValue.trim() ? 'linear-gradient(135deg, #F97316, #EA580C)' : 'rgba(255,255,255,0.04)',
                border: inputValue.trim() ? 'none' : '1px solid rgba(255,255,255,0.06)',
                color: inputValue.trim() ? '#FFF' : '#52525B',
                fontSize: 13, fontWeight: 700, cursor: inputValue.trim() ? 'pointer' : 'default',
                transition: 'all 0.15s ease',
                boxShadow: inputValue.trim() ? '0 2px 12px rgba(249,115,22,0.25)' : 'none',
              }}
            >
              Send
            </button>
          </div>
        </div>

        {/* ── KYA one-liner ── */}
        <div style={{
          textAlign: 'center',
          padding: '20px 24px',
          borderRadius: 14,
          backgroundColor: 'rgba(249,115,22,0.04)',
          border: '1px solid rgba(249,115,22,0.10)',
          marginBottom: 48,
        }}>
          <p style={{ fontSize: 14, color: '#A1A1AA', lineHeight: 1.7, margin: 0 }}>
            <span style={{ color: '#F97316', fontWeight: 700 }}>KYA — Know Your Agent.</span>{' '}
            The trust standard for the AI age.
          </p>
        </div>

        {/* ── CTA ── */}
        <div style={{
          textAlign: 'center',
          padding: '32px 24px',
          borderRadius: 18,
          background: 'linear-gradient(135deg, rgba(249,115,22,0.06) 0%, rgba(249,115,22,0.02) 100%)',
          border: '1px solid rgba(249,115,22,0.14)',
        }}>
          <h3 style={{ fontSize: 20, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.02em', margin: '0 0 10px 0' }}>
            Ready for the real thing?
          </h3>
          <p style={{ fontSize: 13, color: '#71717A', margin: '0 0 24px 0', lineHeight: 1.65 }}>
            Connect your wallet to create a real partnership bond and experience Embris with full on-chain accountability.
          </p>
          <button
            onClick={() => {
              if (typeof window !== 'undefined') {
                const nav = (window as unknown as { __setSection?: (s: string) => void }).__setSection;
                if (nav) { nav('account'); window.location.href = '/'; }
                else { window.location.href = '/'; }
              }
            }}
            style={{
              padding: '13px 36px', borderRadius: 12,
              background: 'linear-gradient(135deg, #F97316, #EA580C)',
              border: 'none', color: '#fff', fontSize: 14, fontWeight: 700,
              cursor: 'pointer', boxShadow: '0 4px 20px rgba(249,115,22,0.3)',
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 8px 28px rgba(249,115,22,0.4)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 4px 20px rgba(249,115,22,0.3)'; }}
          >
            Connect Wallet &amp; Create Your Bond
          </button>
        </div>

        {/* ── Footer ── */}
        <div style={{ textAlign: 'center', marginTop: 48, paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.04)' }}>
          <p style={{ fontSize: 11, color: '#52525B', lineHeight: 1.8, marginBottom: 4 }}>
            <strong style={{ color: '#A1A1AA' }}>Vaultfire Protocol</strong> — Morals over metrics. Privacy over surveillance. Freedom over control.
          </p>
          <p style={{ fontSize: 10, color: '#3F3F46' }}>
            Making human thriving more profitable than extraction.
          </p>
        </div>

      </div>
    </div>
  );
}
