/** ✦ Krytz Interactive Demos
 * 
 * Real working prototypes of core Krytz features based on actual codebase
 */

const { useState, useEffect, useRef } = React;

// ═══════════════════════════════════════════════════════════
// NEXT ACTION SYSTEM DEMO
// ═══════════════════════════════════════════════════════════

function NextActionSystemDemo() {
  const [expanded, setExpanded] = useState(false);
  const [items, setItems] = useState([
    {
      id: 1,
      title: "Send proposal to client",
      priority: 0.92,
      timeEst: "~25 min",
      tier: "primary",
      reason: "Deadline tomorrow, blocks 2 tasks",
      fullTrace: {
        deadline: "Tomorrow 5:00 PM",
        blockedTasks: ["Client kickoff meeting", "Contract review"],
        urgencyScore: 0.95,
        importanceScore: 0.88,
        energyFit: 0.92,
        downstreamImpact: 2,
        computation: "Weighted combination of urgency, importance, energy fit, and downstream impact"
      }
    },
    {
      id: 2,
      title: "Call Raj about deployment",
      priority: 0.68,
      timeEst: "~10 min",
      tier: "secondary",
      reason: "Mentioned 3x, quick win",
      fullTrace: {
        mentions: 3,
        timeEstimate: 10,
        urgencyScore: 0.62,
        importanceScore: 0.71,
        energyFit: 0.78,
        downstreamImpact: 0,
        computation: "Weighted combination of urgency, importance, energy fit, and downstream impact"
      }
    },
    {
      id: 3,
      title: "PR #42 review",
      priority: 0.35,
      timeEst: "waiting",
      tier: "async",
      reason: "Waiting for tests to pass",
      fullTrace: {
        blocker: "Waiting on CI workflow",
        urgencyScore: 0.30,
        importanceScore: 0.45,
        energyFit: 0.40,
        downstreamImpact: 0,
        computation: "Blocked state → deferred to async tier"
      }
    }
  ]);

  const [actionTaken, setActionTaken] = useState(null);

  function handleAction(action, itemId) {
    setActionTaken({ action, itemId, item: items.find(i => i.id === itemId) });
    setTimeout(() => {
      if (action === 'complete') {
        // Celebrate completion
        if (window.KrytzConfetti) {
          const btn = document.querySelector('.next-action-demo .btn-start');
          if (btn) window.KrytzConfetti.fromEl(btn, { count: 60, power: 0.95 });
        }
        setItems(items.filter(i => i.id !== itemId));
        // Promote secondary to primary
        setItems(prev => prev.map(i => {
          if (i.tier === 'secondary') return { ...i, tier: 'primary', priority: i.priority + 0.1 };
          if (i.tier === 'async') return { ...i, tier: 'secondary' };
          return i;
        }));
      } else if (action === 'snooze') {
        setItems(prev => prev.map(i => i.id === itemId ? { ...i, tier: 'async' } : i));
      }
      setActionTaken(null);
    }, 2000);
  }

  const primary = items.find(i => i.tier === 'primary');
  const secondary = items.filter(i => i.tier === 'secondary');
  const async = items.filter(i => i.tier === 'async');

  return (
    <div className="demo-card next-action-demo">
      <div className="demo-label">Live Demo · Next Action System</div>
      
      {/* PRIMARY */}
      {primary && (
        <div className="action-item primary-item">
          <div className="action-tier-badge">● PRIMARY</div>
          <h3 className="action-title">{primary.title}</h3>
          <div className="action-meta">
            <span className="action-time">{primary.timeEst}</span>
            <span className="action-priority">priority {primary.priority.toFixed(2)}</span>
          </div>
          <div className="action-reason">
            <span className="reason-arrow">↳</span> {primary.reason}
          </div>
          
          <div className="action-buttons">
            <button className="btn-action btn-start" onClick={() => handleAction('complete', primary.id)}>
              Start
            </button>
            <button className="btn-action btn-snooze" onClick={() => handleAction('snooze', primary.id)}>
              Snooze 30m
            </button>
            <button className="btn-action btn-skip" onClick={() => handleAction('skip', primary.id)}>
              Skip
            </button>
          </div>

          <button className="why-button" onClick={() => setExpanded(!expanded)}>
            {expanded ? '← Hide trace' : 'Why this task? →'}
          </button>

          {expanded && (
            <div className="decision-trace">
              <div className="trace-title">Decision Trace</div>
              <div className="trace-row">
                <span className="trace-label">Urgency Score:</span>
                <span className="trace-value">{primary.fullTrace.urgencyScore}</span>
                <div className="trace-bar" style={{width: `${primary.fullTrace.urgencyScore * 100}%`}}></div>
              </div>
              <div className="trace-row">
                <span className="trace-label">Importance Score:</span>
                <span className="trace-value">{primary.fullTrace.importanceScore}</span>
                <div className="trace-bar" style={{width: `${primary.fullTrace.importanceScore * 100}%`}}></div>
              </div>
              <div className="trace-row">
                <span className="trace-label">Energy Fit:</span>
                <span className="trace-value">{primary.fullTrace.energyFit}</span>
                <div className="trace-bar" style={{width: `${primary.fullTrace.energyFit * 100}%`}}></div>
              </div>
              <div className="trace-row">
                <span className="trace-label">Downstream Impact:</span>
                <span className="trace-value">{primary.fullTrace.downstreamImpact} tasks</span>
              </div>
              <div className="trace-computation">
                <code>{primary.fullTrace.computation}</code>
              </div>
              {primary.fullTrace.deadline && (
                <div className="trace-context">
                  <strong>Deadline:</strong> {primary.fullTrace.deadline}<br />
                  <strong>Blocks:</strong> {primary.fullTrace.blockedTasks.join(', ')}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* SECONDARY */}
      {secondary.length > 0 && (
        <div className="action-section">
          <div className="action-tier-label">○ SECONDARY — if blocked / low energy</div>
          {secondary.map(item => (
            <div key={item.id} className="action-item secondary-item">
              <div className="action-row">
                <span className="action-title">{item.title}</span>
                <span className="action-time">{item.timeEst}</span>
              </div>
              <div className="action-reason">
                <span className="reason-arrow">↳</span> {item.reason}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ASYNC */}
      {async.length > 0 && (
        <div className="action-section">
          <div className="action-tier-label">◌ ASYNC — waiting / background</div>
          {async.map(item => (
            <div key={item.id} className="action-item async-item">
              <div className="action-row">
                <span className="action-title">{item.title}</span>
                <span className="action-status">{item.timeEst}</span>
              </div>
              <div className="action-reason">
                <span className="reason-arrow">↳</span> {item.reason}
              </div>
            </div>
          ))}
        </div>
      )}

      {actionTaken && (
        <div className="action-toast">
          {actionTaken.action === 'complete' && `✓ Completed "${actionTaken.item.title}" — decision weights updated`}
          {actionTaken.action === 'snooze' && `⏰ Snoozed "${actionTaken.item.title}" for 30 minutes`}
          {actionTaken.action === 'skip' && `→ Skipped "${actionTaken.item.title}" — moved to secondary`}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// LIVE CAPTURE DEMO
// ═══════════════════════════════════════════════════════════

function LiveCaptureDemo() {
  const [input, setInput] = useState('');
  const [processing, setProcessing] = useState(false);
  const [extracted, setExtracted] = useState(null);
  const inputRef = useRef(null);

  const examples = [
    "Had a call with Raj. He needs the API docs by Thursday. Also need to fix the login bug — it's blocking the demo next week.",
    "Meeting with Sarah at 2pm. Need to prep the slides and review the Q3 numbers first.",
    "Deployed v2.3 to staging. Waiting on QA approval. Reminder: send invoice to Acme Corp.",
  ];

  function handleCapture() {
    if (!input.trim()) return;
    setProcessing(true);
    
    // Simulate AI extraction
    setTimeout(() => {
      const result = parseCapture(input);
      setExtracted(result);
      setProcessing(false);
      // Celebrate the successful extraction
      if (window.KrytzConfetti) {
        const btn = document.querySelector('.capture-demo .btn-capture')
                 || document.querySelector('.capture-demo .extraction-result');
        if (btn) window.KrytzConfetti.fromEl(btn, { count: 70, power: 0.9 });
        else window.KrytzConfetti.burst({ count: 70 });
      }
    }, 1200);
  }

  function parseCapture(text) {
    const items = [];
    
    // Simple pattern matching (in real Krytz this is AI-powered)
    if (text.match(/by (monday|tuesday|wednesday|thursday|friday|weekend|tomorrow|next week)/i)) {
      const match = text.match(/(.+?)\s+by\s+(monday|tuesday|wednesday|thursday|friday|weekend|tomorrow|next week)/i);
      if (match) {
        items.push({
          type: 'task',
          text: match[1].replace(/^(had|need to|also|reminder:?)\s+/i, '').trim(),
          deadline: match[2],
          urgency: 'high'
        });
      }
    }
    
    if (text.match(/need to|must|should|todo|fix|send|review|prep/i)) {
      const sentences = text.split(/[.!?]\s+/);
      sentences.forEach(s => {
        if (s.match(/need to|must|should|todo|fix|send|review|prep/i) && !items.find(i => i.text === s)) {
          items.push({
            type: 'task',
            text: s.replace(/^(also|reminder:?|and)\s+/i, '').trim(),
            urgency: 'medium'
          });
        }
      });
    }
    
    if (text.match(/blocking|blocked|waiting on|depends on/i)) {
      const match = text.match(/(.+?)\s+(blocking|blocked|is blocking|waiting on)/i);
      if (match) {
        items.push({
          type: 'blocker',
          text: match[1].trim(),
          reason: 'blocks other work'
        });
      }
    }
    
    if (text.match(/meeting|call|chat/i)) {
      const match = text.match(/(meeting|call|chat)\s+with\s+(\w+)/i);
      if (match) {
        items.push({
          type: 'event',
          text: `${match[1]} with ${match[2]}`,
          category: 'scheduled'
        });
      }
    }

    if (text.match(/deployed|shipped|finished|completed|done/i)) {
      const match = text.match(/(deployed|shipped|finished|completed)\s+(.+?)(\.|$)/i);
      if (match) {
        items.push({
          type: 'completion',
          text: match[2].trim()
        });
      }
    }

    return {
      raw: text,
      items: items.length > 0 ? items : [{
        type: 'note',
        text: text.slice(0, 50) + (text.length > 50 ? '...' : '')
      }],
      extracted: items.length
    };
  }

  function tryExample(ex) {
    setInput(ex);
    setExtracted(null);
    setTimeout(() => inputRef.current?.focus(), 100);
  }

  return (
    <div className="demo-card capture-demo">
      <div className="demo-label">Live Demo · Intelligent Capture</div>
      
      <div className="capture-input-area">
        <textarea
          ref={inputRef}
          className="capture-input"
          placeholder="Dump anything — meeting notes, thoughts, todos, blockers..."
          value={input}
          onChange={(e) => setInput(e.target.value)}
          rows={4}
        />
        <button 
          className="btn-capture"
          onClick={handleCapture}
          disabled={!input.trim() || processing}
        >
          {processing ? '⚡ Processing...' : '→ Capture'}
        </button>
      </div>

      <div className="capture-examples">
        <span className="ex-label">Try:</span>
        {examples.map((ex, i) => (
          <button key={i} className="ex-button" onClick={() => tryExample(ex)}>
            {ex.slice(0, 40)}...
          </button>
        ))}
      </div>

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

      {extracted && (
        <div className="extraction-result">
          <div className="result-header">
            ✓ Extracted {extracted.extracted} item{extracted.extracted !== 1 ? 's' : ''}
          </div>
          {extracted.items.map((item, i) => (
            <div key={i} className={`extracted-item type-${item.type}`}>
              <div className="item-badge">
                {item.type === 'task' && '○'}
                {item.type === 'blocker' && '⚠'}
                {item.type === 'event' && '◷'}
                {item.type === 'completion' && '✓'}
                {item.type === 'note' && '◇'}
                {' '}
                {item.type}
              </div>
              <div className="item-text">{item.text}</div>
              {item.deadline && <div className="item-meta">Due: {item.deadline}</div>}
              {item.urgency && <div className="item-meta">Urgency: {item.urgency}</div>}
              {item.reason && <div className="item-meta">{item.reason}</div>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// PRESSURE GAUGE
// ═══════════════════════════════════════════════════════════

function PressureGauge() {
  const [pressure, setPressure] = useState(0.72);
  const [details, setDetails] = useState({
    openTasks: 18,
    overdue: 3,
    blockers: 2,
    capacity: 6.2,
    dailyAvg: 4.5
  });
  const [showDetails, setShowDetails] = useState(false);

  function getLevel() {
    if (pressure < 0.4) return { label: 'Light', color: '#2ed573', desc: 'Below capacity. Room for more.' };
    if (pressure < 0.7) return { label: 'Steady', color: '#ffa502', desc: 'On track. Manageable load.' };
    return { label: 'Overload', color: '#ff6b6b', desc: 'At capacity. Prioritization critical.' };
  }

  const level = getLevel();

  return (
    <div className="demo-card pressure-demo">
      <div className="demo-label">State-First UI · Pressure Gauge</div>
      
      <div className="pressure-visual">
        <svg viewBox="0 0 200 120" className="pressure-arc">
          <defs>
            <linearGradient id="pressureGrad" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#2ed573" />
              <stop offset="50%" stopColor="#ffa502" />
              <stop offset="100%" stopColor="#ff6b6b" />
            </linearGradient>
          </defs>
          {/* Background arc */}
          <path
            d="M 20 100 A 80 80 0 0 1 180 100"
            fill="none"
            stroke="rgba(255,255,255,0.1)"
            strokeWidth="12"
            strokeLinecap="round"
          />
          {/* Filled arc */}
          <path
            d="M 20 100 A 80 80 0 0 1 180 100"
            fill="none"
            stroke="url(#pressureGrad)"
            strokeWidth="12"
            strokeLinecap="round"
            strokeDasharray={`${pressure * 251.2} 251.2`}
            style={{ transition: 'stroke-dasharray 0.8s ease' }}
          />
          {/* Needle */}
          <line
            x1="100"
            y1="100"
            x2={100 + 70 * Math.cos((pressure * 180 - 180) * Math.PI / 180)}
            y2={100 + 70 * Math.sin((pressure * 180 - 180) * Math.PI / 180)}
            stroke={level.color}
            strokeWidth="3"
            strokeLinecap="round"
            style={{ transition: 'all 0.8s ease' }}
          />
          <circle cx="100" cy="100" r="5" fill={level.color} />
        </svg>

        <div className="pressure-reading" style={{ color: level.color }}>
          {level.label}
        </div>
        <div className="pressure-desc">{level.desc}</div>
      </div>

      <button className="pressure-details-toggle" onClick={() => setShowDetails(!showDetails)}>
        {showDetails ? '↑ Hide details' : '↓ Show breakdown'}
      </button>

      {showDetails && (
        <div className="pressure-breakdown">
          <div className="breakdown-row">
            <span className="breakdown-label">Open tasks</span>
            <span className="breakdown-value">{details.openTasks}</span>
          </div>
          <div className="breakdown-row">
            <span className="breakdown-label">Overdue</span>
            <span className="breakdown-value critical">{details.overdue}</span>
          </div>
          <div className="breakdown-row">
            <span className="breakdown-label">Blockers</span>
            <span className="breakdown-value warning">{details.blockers}</span>
          </div>
          <div className="breakdown-row">
            <span className="breakdown-label">Daily capacity (hrs)</span>
            <span className="breakdown-value">{details.capacity}</span>
          </div>
          <div className="breakdown-row">
            <span className="breakdown-label">Avg completion rate</span>
            <span className="breakdown-value">{details.dailyAvg}/day</span>
          </div>
        </div>
      )}

      <div className="pressure-note">
        <em>Krytz computes your pressure in real-time based on open load, deadlines, capacity model, and historical patterns.</em>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// BEFORE/AFTER COMPARISON
// ═══════════════════════════════════════════════════════════

function BeforeAfterDemo() {
  const [view, setView] = useState('before');

  return (
    <div className="demo-card comparison-demo">
      <div className="demo-label">Before vs After</div>
      
      <div className="comparison-toggle">
        <button 
          className={`toggle-btn ${view === 'before' ? 'active' : ''}`}
          onClick={() => setView('before')}
        >
          Without Krytz
        </button>
        <button 
          className={`toggle-btn ${view === 'after' ? 'active' : ''}`}
          onClick={() => setView('after')}
        >
          With Krytz
        </button>
      </div>

      <div className="comparison-view">
        {view === 'before' ? (
          <div className="before-state">
            <div className="mock-apps">
              <div className="mock-app">
                <div className="mock-header">Todoist</div>
                <div className="mock-list">
                  <div className="mock-item">◻ Review proposal</div>
                  <div className="mock-item">◻ Call Raj</div>
                  <div className="mock-item">◻ Fix bug</div>
                  <div className="mock-item">◻ Send invoice</div>
                  <div className="mock-item">◻ Update docs</div>
                  <div className="mock-item">◻ Team meeting</div>
                  <div className="mock-item">◻ Code review</div>
                </div>
              </div>
              <div className="mock-app">
                <div className="mock-header">Notion</div>
                <div className="mock-list">
                  <div className="mock-item">📄 Project notes</div>
                  <div className="mock-item">📄 Meeting logs</div>
                  <div className="mock-item">📄 Ideas</div>
                </div>
              </div>
              <div className="mock-app">
                <div className="mock-header">Calendar</div>
                <div className="mock-list">
                  <div className="mock-item">◷ 2:00 PM Meeting</div>
                  <div className="mock-item">◷ 4:00 PM Call</div>
                </div>
              </div>
            </div>
            <div className="state-problems">
              <div className="problem">❌ Which task should I do first?</div>
              <div className="problem">❌ What's actually urgent?</div>
              <div className="problem">❌ What's blocking what?</div>
              <div className="problem">❌ Am I overcommitted?</div>
            </div>
          </div>
        ) : (
          <div className="after-state">
            <div className="krytz-interface">
              <div className="krytz-status">
                <div className="status-item">
                  <span className="status-label">Pressure:</span>
                  <span className="status-value">Steady</span>
                </div>
                <div className="status-item">
                  <span className="status-label">Next action:</span>
                  <span className="status-value">Ready</span>
                </div>
              </div>
              <div className="krytz-primary">
                <div className="primary-badge">● DO NOW</div>
                <div className="primary-task">Fix login bug</div>
                <div className="primary-reason">↳ Blocks demo tomorrow, 2 tasks waiting</div>
                <div className="primary-actions">
                  <button className="btn-mini">Start</button>
                  <button className="btn-mini">Snooze</button>
                  <button className="btn-mini">Why?</button>
                </div>
              </div>
              <div className="krytz-secondary">
                <div className="sec-label">○ If blocked:</div>
                <div className="sec-item">Call Raj (~10 min)</div>
                <div className="sec-item">Update docs (~15 min)</div>
              </div>
            </div>
            <div className="state-solutions">
              <div className="solution">✓ System decides priority</div>
              <div className="solution">✓ Transparent reasoning</div>
              <div className="solution">✓ Blocker detection</div>
              <div className="solution">✓ Load-aware prioritization</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

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

window.KrytzDemos = {
  NextActionSystemDemo,
  LiveCaptureDemo,
  PressureGauge,
  BeforeAfterDemo
};
