/** ✦ Krytz Advanced Interactive Demos
 * 
 * Custom graphics and visualizations to replace screenshots
 */

const { useState, useEffect, useRef } = React;

// ═══════════════════════════════════════════════════════════
// INTERACTIVE SHOWCASE - Replace screenshots with live demos
// ═══════════════════════════════════════════════════════════

function InteractiveShowcase() {
  const [activeDemo, setActiveDemo] = useState('queue');

  return (
    <div className="interactive-showcase">
      <div className="showcase-tabs">
        <button 
          className={`showcase-tab ${activeDemo === 'queue' ? 'active' : ''}`}
          onClick={() => setActiveDemo('queue')}
        >
          Action Queue
        </button>
        <button 
          className={`showcase-tab ${activeDemo === 'capture' ? 'active' : ''}`}
          onClick={() => setActiveDemo('capture')}
        >
          Capture Console
        </button>
        <button 
          className={`showcase-tab ${activeDemo === 'memory' ? 'active' : ''}`}
          onClick={() => setActiveDemo('memory')}
        >
          Memory
        </button>
      </div>

      <div className="showcase-content">
        {activeDemo === 'queue' && <ActionQueueMini />}
        {activeDemo === 'capture' && <CaptureConsoleMini />}
        {activeDemo === 'memory' && <MemoryMini />}
      </div>
    </div>
  );
}

function ActionQueueMini() {
  const [items, setItems] = useState([
    { id: 1, tier: 'primary', title: 'Fix login bug', priority: 0.92, reason: 'Blocks demo tomorrow', done: false },
    { id: 2, tier: 'secondary', title: 'Review PR #42', priority: 0.68, reason: 'Quick win, 10 min', done: false },
    { id: 3, tier: 'secondary', title: 'Update docs', priority: 0.65, reason: 'Mentioned 3x this week', done: false },
    { id: 4, tier: 'async', title: 'Invoice from vendor', priority: 0.35, reason: 'Waiting on approval', done: false },
  ]);

  const handleComplete = (id) => {
    setItems(prev => prev.map(item => 
      item.id === id ? { ...item, done: !item.done } : item
    ));
  };

  const handleReorder = (id, direction) => {
    const idx = items.findIndex(i => i.id === id);
    if ((direction === 'up' && idx === 0) || (direction === 'down' && idx === items.length - 1)) return;
    
    const newItems = [...items];
    const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
    [newItems[idx], newItems[targetIdx]] = [newItems[targetIdx], newItems[idx]];
    setItems(newItems);
  };

  return (
    <div className="mini-queue">
      <div className="mini-header">
        <span className="mini-label">Click items to complete · drag to reorder</span>
        <span className="mini-badge">{items.filter(i => !i.done).length} active</span>
      </div>
      
      {items.map((item, idx) => (
        <div key={item.id} className={`mini-item tier-${item.tier} ${item.done ? 'done' : ''}`}>
          <div className="mini-item-header">
            <input 
              type="checkbox" 
              checked={item.done}
              onChange={() => handleComplete(item.id)}
              className="mini-checkbox"
            />
            <span className={`tier-indicator ${item.tier}`}>
              {item.tier === 'primary' && '●'}
              {item.tier === 'secondary' && '○'}
              {item.tier === 'async' && '◌'}
            </span>
            <span className="mini-item-title">{item.title}</span>
            <span className="mini-priority">{item.priority}</span>
            <div className="mini-item-controls">
              {idx > 0 && (
                <button onClick={() => handleReorder(item.id, 'up')} className="reorder-btn">↑</button>
              )}
              {idx < items.length - 1 && (
                <button onClick={() => handleReorder(item.id, 'down')} className="reorder-btn">↓</button>
              )}
            </div>
          </div>
          <div className="mini-item-reason">↳ {item.reason}</div>
        </div>
      ))}
    </div>
  );
}

function CaptureConsoleMini() {
  const [input, setInput] = useState('');
  const [extracted, setExtracted] = useState([]);
  const [processing, setProcessing] = useState(false);

  const handleCapture = () => {
    if (!input.trim()) return;
    
    setProcessing(true);
    
    // Simulate extraction
    setTimeout(() => {
      const newItems = [];
      if (input.toLowerCase().includes('thursday') || input.toLowerCase().includes('friday')) {
        newItems.push({ type: 'task', text: 'Prep Q3 slides', meta: 'Due: Thursday' });
      }
      if (input.toLowerCase().includes('bug') || input.toLowerCase().includes('fix')) {
        newItems.push({ type: 'blocker', text: 'Fix staging bug', meta: 'Blocks deploy' });
      }
      if (input.toLowerCase().includes('meeting') || input.toLowerCase().includes('sync') || input.toLowerCase().includes('call')) {
        newItems.push({ type: 'event', text: 'Team sync (logged)', meta: 'Completed' });
      }
      if (input.toLowerCase().includes('review') || input.toLowerCase().includes('check')) {
        newItems.push({ type: 'task', text: 'Review items', meta: 'Added to queue' });
      }
      if (newItems.length === 0) {
        newItems.push({ type: 'note', text: input.slice(0, 40) + '...', meta: 'Saved to memory' });
      }
      
      setExtracted(newItems);
      setProcessing(false);
      // Celebrate
      if (window.KrytzConfetti) {
        const btn = document.querySelector('.mini-capture .mini-capture-btn')
                 || document.querySelector('.mini-capture .extract-header');
        if (btn) window.KrytzConfetti.fromEl(btn, { count: 50, power: 0.85 });
      }
    }, 1200);
  };

  const handleReset = () => {
    setInput('');
    setExtracted([]);
    setProcessing(false);
  };

  return (
    <div className="mini-capture">
      <div className="mini-header">
        <span className="mini-label">Type anything → watch extraction</span>
      </div>
      
      {extracted.length === 0 && !processing && (
        <div className="mini-input-area">
          <textarea 
            className="mini-input-field"
            placeholder="Try: 'Had sync with Sarah. Need to prep Q3 slides by Thursday. Bug in staging needs fixing before deploy.'"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
                handleCapture();
              }
            }}
          />
          <button 
            className="mini-capture-btn"
            onClick={handleCapture}
            disabled={!input.trim()}
          >
            Extract →
          </button>
        </div>
      )}

      {processing && (
        <div className="mini-processing">
          <div className="processing-spinner"></div>
          <span>Extracting tasks, deadlines, blockers...</span>
        </div>
      )}

      {extracted.length > 0 && !processing && (
        <div className="mini-extracted">
          <div className="extract-header">
            ✓ Extracted {extracted.length} item{extracted.length > 1 ? 's' : ''}
            <button className="mini-reset-btn" onClick={handleReset}>Try again</button>
          </div>
          {extracted.map((item, i) => (
            <div key={i} className="extract-item">
              <span className={`extract-badge ${item.type}`}>
                {item.type.toUpperCase()}
              </span>
              <span>{item.text}</span>
              <span className="extract-meta">{item.meta}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MemoryMini() {
  const [events, setEvents] = useState([
    { time: '14:23', type: 'capture', text: 'Team standup notes captured' },
    { time: '14:24', type: 'extract', text: '2 action items extracted' },
    { time: '14:25', type: 'rank', text: 'Priority recomputed → "Fix API bug" moved to PRIMARY' },
  ]);

  const addEvent = () => {
    const now = new Date();
    const time = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
    const newEvent = {
      time,
      type: 'user',
      text: 'You triggered a memory event'
    };
    setEvents(prev => [...prev, newEvent]);
  };

  return (
    <div className="mini-memory">
      <div className="mini-header">
        <span className="mini-label">Live event stream</span>
        <button className="mini-add-btn" onClick={addEvent}>+ Add event</button>
      </div>
      
      <div className="memory-timeline">
        {events.map((event, i) => (
          <div key={i} className={`memory-event ${event.type}`}>
            <span className="event-time">{event.time}</span>
            <span className={`event-type-badge ${event.type}`}>
              {event.type}
            </span>
            <span className="event-text">{event.text}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// ANIMATED LOOP VISUALIZATION
// ═══════════════════════════════════════════════════════════

function AnimatedLoopViz() {
  const [activeStage, setActiveStage] = useState(0);
  
  useEffect(() => {
    const interval = setInterval(() => {
      setActiveStage(prev => (prev + 1) % 6);
    }, 2000);
    return () => clearInterval(interval);
  }, []);

  const stages = [
    { num: '01', label: 'Capture', icon: '✦', color: '#1B2A4A' },
    { num: '02', label: 'Extract', icon: '⚡', color: '#3498db' },
    { num: '03', label: 'Compute', icon: '◆', color: '#ffa502' },
    { num: '04', label: 'Decide', icon: '●', color: '#2ed573' },
    { num: '05', label: 'Execute', icon: '→', color: '#ff6b6b' },
    { num: '06', label: 'Learn', icon: '◎', color: '#9b59b6' },
  ];

  return (
    <div className="loop-viz-animated">
      <svg viewBox="0 0 600 200" className="loop-svg">
        {/* Connection line */}
        <path
          d="M 50 100 L 550 100"
          stroke="rgba(27, 42, 74,0.12)"
          strokeWidth="2"
          fill="none"
        />
        
        {/* Animated pulse */}
        <circle
          cx={50 + (activeStage * 100)}
          cy="100"
          r="8"
          fill={stages[activeStage].color}
          style={{ transition: 'all 0.5s ease' }}
        />

        {/* Stage nodes */}
        {stages.map((stage, i) => (
          <g key={i} transform={`translate(${50 + i * 100}, 100)`}>
            <circle
              r="20"
              fill={i === activeStage ? stage.color : '#FFFFFF'}
              stroke={i === activeStage ? stage.color : 'rgba(27, 42, 74,0.18)'}
              strokeWidth={i === activeStage ? 2 : 1.5}
              style={{ transition: 'all 0.3s ease' }}
            />
            <text
              textAnchor="middle"
              y="6"
              fill={i === activeStage ? '#fff' : 'rgba(27, 42, 74,0.55)'}
              fontSize="16"
              fontWeight="600"
            >
              {stage.icon}
            </text>
            <text
              textAnchor="middle"
              y="45"
              fill={i === activeStage ? stage.color : 'rgba(27, 42, 74,0.75)'}
              fontSize="12"
              fontWeight="500"
            >
              {stage.label}
            </text>
          </g>
        ))}
      </svg>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// TASK GRAPH VISUALIZATION
// ═══════════════════════════════════════════════════════════

function TaskGraphViz() {
  const nodes = [
    { id: 'A', x: 100, y: 100, label: 'Deploy v2.3', status: 'blocked', priority: 0.88 },
    { id: 'B', x: 300, y: 60, label: 'Fix staging bug', status: 'active', priority: 0.92 },
    { id: 'C', x: 300, y: 140, label: 'QA sign-off', status: 'waiting', priority: 0.65 },
    { id: 'D', x: 500, y: 100, label: 'Prod rollout', status: 'pending', priority: 0.45 },
  ];

  const edges = [
    { from: 'B', to: 'A' },
    { from: 'C', to: 'A' },
    { from: 'A', to: 'D' },
  ];

  return (
    <div className="graph-viz">
      <div className="graph-header">
        <span className="graph-label">Task dependency graph</span>
        <span className="graph-badge">4 tasks · 1 blocker</span>
      </div>
      <svg viewBox="0 0 600 240" className="graph-svg">
        {/* Edges */}
        {edges.map((edge, i) => {
          const from = nodes.find(n => n.id === edge.from);
          const to = nodes.find(n => n.id === edge.to);
          return (
            <line
              key={i}
              x1={from.x + 40}
              y1={from.y + 20}
              x2={to.x}
              y2={to.y + 20}
              stroke="rgba(255,255,255,0.2)"
              strokeWidth="2"
              markerEnd="url(#arrowhead)"
            />
          );
        })}
        
        {/* Arrowhead marker */}
        <defs>
          <marker
            id="arrowhead"
            markerWidth="10"
            markerHeight="10"
            refX="8"
            refY="3"
            orient="auto"
          >
            <polygon points="0 0, 10 3, 0 6" fill="rgba(255,255,255,0.3)" />
          </marker>
        </defs>

        {/* Nodes */}
        {nodes.map(node => (
          <g key={node.id} transform={`translate(${node.x}, ${node.y})`}>
            <rect
              width="100"
              height="40"
              rx="6"
              fill={
                node.status === 'active' ? 'rgba(46,213,115,0.15)' :
                node.status === 'blocked' ? 'rgba(255,107,107,0.15)' :
                node.status === 'waiting' ? 'rgba(255,165,2,0.15)' :
                'rgba(255,255,255,0.05)'
              }
              stroke={
                node.status === 'active' ? '#2ed573' :
                node.status === 'blocked' ? '#ff6b6b' :
                node.status === 'waiting' ? '#ffa502' :
                'rgba(255,255,255,0.2)'
              }
              strokeWidth="2"
            />
            <text
              x="50"
              y="16"
              textAnchor="middle"
              fill="#e8e8ed"
              fontSize="11"
              fontWeight="500"
            >
              {node.label}
            </text>
            <text
              x="50"
              y="30"
              textAnchor="middle"
              fill="rgba(255,255,255,0.5)"
              fontSize="9"
              fontFamily="monospace"
            >
              {node.priority}
            </text>
          </g>
        ))}
      </svg>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// INTELLIGENCE LAYERS INTERACTIVE GRID
// ═══════════════════════════════════════════════════════════

function SystemsInteractive() {
  const [view, setView] = useState('overview');

  return (
    <div className="systems-interactive">
      <div className="systems-overview">
        <div className="overview-grid">
          <div className="overview-stat">
            <div className="stat-num">Multi-layer</div>
            <div className="stat-label">Intelligence stack</div>
            <div className="stat-desc">Working together as one unified system</div>
          </div>
          <div className="overview-stat">
            <div className="stat-num">Real-time</div>
            <div className="stat-label">Local extraction</div>
            <div className="stat-desc">Capture feels instant, AI refines in background</div>
          </div>
          <div className="overview-stat">
            <div className="stat-num">Multi-signal</div>
            <div className="stat-label">Ranked decisions</div>
            <div className="stat-desc">Every decision fully explainable and bounded</div>
          </div>
          <div className="overview-stat">
            <div className="stat-num">Budget-capped</div>
            <div className="stat-label">AI cost per user</div>
            <div className="stat-desc">Hard-capped spending, degrades gracefully</div>
          </div>
        </div>

        <div className="system-categories">
          <div className="cat-pill" style={{ borderColor: '#1B2A4A', color: '#1B2A4A' }}>
            ◆ Core Processing
          </div>
          <div className="cat-pill" style={{ borderColor: '#3498db', color: '#3498db' }}>
            ◆ Decision Layer
          </div>
          <div className="cat-pill" style={{ borderColor: '#2ed573', color: '#2ed573' }}>
            ◆ Intelligence
          </div>
          <div className="cat-pill" style={{ borderColor: '#ffa502', color: '#ffa502' }}>
            ◆ Behavioral Learning
          </div>
          <div className="cat-pill" style={{ borderColor: '#9b59b6', color: '#9b59b6' }}>
            ◆ Memory & Recall
          </div>
        </div>

        <p style={{ 
          textAlign: 'center', 
          fontSize: '14px', 
          color: 'var(--krytz-text-secondary)', 
          marginTop: '32px',
          maxWidth: '640px',
          marginLeft: 'auto',
          marginRight: 'auto'
        }}>
          Each layer is measured, circuit-broken, and bounded at runtime. The system is built for reliability — not novelty.
        </p>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// EXPORT
// ═══════════════════════════════════════════════════════════

window.KrytzAdvancedDemos = {
  InteractiveShowcase,
  AnimatedLoopViz,
  TaskGraphViz,
  SystemsInteractive
};
