// ============================================================
// MOORE AI v13 — ACTION REFERENCE TAB
// ============================================================

const ActionReferenceView = () => {
  const { useState } = React;
  const [testResults, setTestResults] = useState({});
  const [testingId, setTestingId] = useState(null);

  const runTest = async (actionId) => {
    setTestingId(actionId);
    setTestResults(prev => ({ ...prev, [actionId]: null }));
    try {
      const r = await fetch('/api/actions/test', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: actionId })
      });
      const data = await r.json();
      setTestResults(prev => ({ ...prev, [actionId]: data }));
    } catch(e) {
      setTestResults(prev => ({ ...prev, [actionId]: { ok: false, message: e.message } }));
    }
    setTestingId(null);
  };

  const defaultActions = [
    { id: 'MAKE_CALL',       icon: 'phone-call',    label: 'Call a Lead',         color: '#3b82f6', desc: 'Dispatch an AI outbound call via Bland AI to any contact in seconds.' },
    { id: 'SCHEDULE',        icon: 'calendar-check', label: 'Book Appointment',   color: '#8b5cf6', desc: 'Create a confirmed GHL calendar appointment for any contact.' },
    { id: 'SEND_EMAIL',      icon: 'mail',           label: 'Send Email',          color: '#06b6d4', desc: 'Send a GHL email to a contact — proposals, follow-ups, updates.' },
    { id: 'SEND_SMS',        icon: 'message-circle', label: 'Send SMS',            color: '#10b981', desc: 'Send an SMS via GHL. 98% open rate — fastest re-engagement channel.' },
    { id: 'UPDATE_OPP',      icon: 'trophy',         label: 'Close a Deal',        color: '#f59e0b', desc: 'Mark an opportunity won, lost, or open. Keeps pipeline accurate.' },
    { id: 'MOVE_STAGE',      icon: 'git-merge',      label: 'Move Pipeline Stage', color: '#6366f1', desc: 'Push any opportunity to a specific stage in the pipeline.' },
    { id: 'CREATE_CONTACT',  icon: 'user-plus',      label: 'Add Contact',         color: '#3b82f6', desc: 'Create a new GHL contact. Every lead captured, none fall through.' },
    { id: 'UPDATE_CONTACT',  icon: 'pencil',         label: 'Update CRM Record',   color: '#64748b', desc: 'Update any field on a GHL contact — phone, email, tags, notes.' },
    { id: 'ADD_NOTE',        icon: 'file-text',      label: 'Add Note',            color: '#ec4899', desc: 'Attach a note to any contact. Conversation context always on file.' },
    { id: 'ADD_TASK',        icon: 'check-square',   label: 'Create Task',         color: '#10b981', desc: 'Add a task to the Tasks board. No next step ever gets forgotten.' },
    { id: 'CHAIN',           icon: 'zap',            label: 'Chain Actions',       color: '#f59e0b', desc: 'One command → Jake executes a full multi-step workflow automatically.' },
  ];

  const useCases = [
    {
      id: 'voice-intake',
      label: 'AI Voice Intake',
      icon: 'mic',
      color: '#3b82f6',
      tagline: 'New lead calls in — Jake handles it.',
      description: 'A prospect fills your form or calls your number. Jake dials them within seconds, introduces himself, qualifies the lead, captures their info, and books the appointment — before a competitor can blink.',
      actions: ['MAKE_CALL', 'CREATE_CONTACT', 'ADD_NOTE', 'SCHEDULE'],
      stat: '9× faster response',
    },
    {
      id: 'appt-confirm',
      label: 'Appointment Confirmation',
      icon: 'calendar-check',
      color: '#8b5cf6',
      tagline: 'No more no-shows.',
      description: 'Day before and morning of the appointment, Jake texts the client their details, confirms attendance, and reschedules instantly if needed. Show rates go up, wasted trips go to zero.',
      actions: ['SEND_SMS', 'SCHEDULE'],
      stat: '−6% no-show rate',
    },
    {
      id: 'proposal-followup',
      label: 'Proposal Follow-Up',
      icon: 'file-text',
      color: '#06b6d4',
      tagline: 'Silence never kills a deal again.',
      description: 'Quote sent, no response. Jake emails a polished follow-up the same day the proposal lands. Three days later — another touch. He never forgets, never feels awkward making the ask.',
      actions: ['SEND_EMAIL', 'ADD_NOTE', 'ADD_TASK'],
      stat: '−9% deal ghosting',
    },
    {
      id: 'client-comms',
      label: 'Active Job Communication',
      icon: 'message-circle',
      color: '#10b981',
      tagline: 'Every client feels like your most important client.',
      description: 'Jake handles routine client communications during active jobs — update texts, confirmation emails, quick answers — so no message goes unanswered.',
      actions: ['SEND_SMS', 'SEND_EMAIL', 'UPDATE_CONTACT'],
      stat: '−4% churn from silence',
    },
    {
      id: 'invoice-followup',
      label: 'Invoice Follow-Up',
      icon: 'dollar-sign',
      color: '#f59e0b',
      tagline: 'Cash collected without the awkwardness.',
      description: 'Job done, invoice unpaid. Jake sends a friendly reminder the day it goes unpaid, then escalates automatically. No awkwardness, no lost friendship — just cash collected.',
      actions: ['SEND_EMAIL', 'SEND_SMS', 'UPDATE_OPP'],
      stat: '−9% revenue delayed',
    },
    {
      id: 're-engage',
      label: 'Past Client Re-Engagement',
      icon: 'refresh-cw',
      color: '#ec4899',
      tagline: 'Closed jobs become repeat business.',
      description: 'Jake keeps a list of closed customers and re-engages them at the right moment — seasonal check-ins, project anniversaries, referral asks. One command turns a closed deal into a repeat customer.',
      actions: ['MAKE_CALL', 'SEND_SMS', 'CREATE_CONTACT'],
      stat: '−5% revenue to silence',
    },
  ];

  const [actions, setActions] = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('moore_action_toggles') || '{}');
      return defaultActions.map(a => ({ ...a, enabled: saved[a.id] !== undefined ? saved[a.id] : true }));
    } catch(e) { return defaultActions.map(a => ({ ...a, enabled: true })); }
  });

  const toggle = (id) => {
    const updated = actions.map(a => a.id === id ? { ...a, enabled: !a.enabled } : a);
    setActions(updated);
    const map = {};
    updated.forEach(a => { map[a.id] = a.enabled; });
    localStorage.setItem('moore_action_toggles', JSON.stringify(map));
  };

  const enableAll = () => {
    const updated = actions.map(a => ({ ...a, enabled: true }));
    setActions(updated);
    localStorage.setItem('moore_action_toggles', JSON.stringify(Object.fromEntries(updated.map(a => [a.id, true]))));
  };

  const actionMap = Object.fromEntries(actions.map(a => [a.id, a]));
  const activeCount = actions.filter(a => a.enabled).length;

  return (
    <div className="p-6 space-y-10 max-w-5xl">

      {/* ── HEADER ── */}
      <div className="flex items-start justify-between">
        <div>
          <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-1">AI Capabilities</div>
          <h2 className="font-black text-white text-2xl italic tracking-tight">Action Reference</h2>
          <p className="text-xs text-slate-500 mt-1">Toggle which actions Jake AI can execute. Disabled actions are skipped with a notice.</p>
        </div>
        <div className="flex items-center gap-3 shrink-0">
          <div className="text-right">
            <div className="text-2xl font-black text-white mono">{activeCount}</div>
            <div className="text-xs text-slate-500">of {actions.length} active</div>
          </div>
          <button onClick={enableAll}
            className="px-3 py-2 bg-blue-600/10 border border-blue-500/20 rounded-xl text-xs font-bold text-blue-400 hover:bg-blue-600/20 transition-all">
            Enable All
          </button>
        </div>
      </div>

      {/* ── ACTION CAPABILITY CARDS ── */}
      <div>
        <div className="text-xs mono text-slate-600 uppercase tracking-widest mb-4">Individual Actions</div>
        <div className="grid grid-cols-3 gap-3">
          {actions.map((action) => (
            <div key={action.id}
              className={`rounded-2xl border p-5 flex flex-col gap-3 transition-all ${
                action.enabled
                  ? 'bg-slate-900/50 border-slate-800/60 hover:border-slate-700/60'
                  : 'bg-slate-950/30 border-slate-900/40 opacity-40'
              }`}>

              {/* Top row */}
              <div className="flex items-start justify-between gap-2">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0"
                  style={{ background: action.enabled ? action.color + '18' : 'rgba(30,41,59,0.4)', border: `1px solid ${action.color}28` }}>
                  <Icon name={action.icon} size={15} style={{ color: action.enabled ? action.color : '#475569' }} />
                </div>
                {/* Toggle */}
                <button onClick={() => toggle(action.id)}
                  className={`relative w-10 h-5 rounded-full border-0 transition-all shrink-0 mt-0.5`}
                  style={{ background: action.enabled ? action.color : '#1e293b' }}>
                  <div className={`absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all ${action.enabled ? 'left-[22px]' : 'left-0.5'}`} />
                </button>
              </div>

              {/* Label + trigger */}
              <div>
                <div className="font-bold text-white text-sm leading-tight">{action.label}</div>
                <div className="text-[10px] mono mt-1 px-1.5 py-0.5 rounded-md inline-block font-bold"
                  style={{ color: action.color, background: action.color + '12', border: `1px solid ${action.color}25` }}>
                  {action.id === 'CHAIN' ? 'ONE COMMAND' : action.id}
                </div>
              </div>

              {/* Desc */}
              <div className="text-xs text-slate-500 leading-relaxed">{action.desc}</div>

              {/* Test */}
              <div className="flex items-center gap-2 mt-1">
                <button
                  onClick={() => runTest(action.id)}
                  disabled={testingId === action.id}
                  className="px-2.5 py-1 rounded-lg text-[10px] mono font-bold transition-all border"
                  style={{ color: action.color, borderColor: action.color + '30', background: action.color + '10' }}>
                  {testingId === action.id ? '...' : 'Test'}
                </button>
                {testResults[action.id] && (
                  <span className={`text-[10px] mono font-bold truncate ${testResults[action.id].ok ? 'text-emerald-400' : 'text-red-400'}`}>
                    {testResults[action.id].ok ? '✓' : '✗'} {testResults[action.id].message}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── ACTIVE USE CASES ── */}
      <div>
        <div className="text-xs mono text-slate-600 uppercase tracking-widest mb-4">Active Use Cases</div>
        <div className="grid grid-cols-2 gap-4">
          {useCases.map((uc) => (
            <div key={uc.id}
              className="rounded-2xl border border-slate-800/60 overflow-hidden"
              style={{ background: 'rgba(10,15,26,0.6)' }}>

              {/* Card header */}
              <div className="p-5 border-b border-slate-800/40"
                style={{ background: uc.color + '08' }}>
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-8 h-8 rounded-xl flex items-center justify-center"
                    style={{ background: uc.color + '18', border: `1px solid ${uc.color}30` }}>
                    <Icon name={uc.icon} size={14} style={{ color: uc.color }} />
                  </div>
                  <div>
                    <div className="text-[10px] mono font-bold uppercase tracking-wider" style={{ color: uc.color }}>Jake Handles This</div>
                    <div className="font-black text-white text-sm leading-tight">{uc.label}</div>
                  </div>
                </div>
                <div className="text-xs text-slate-400 italic mb-3">"{uc.tagline}"</div>
                <div className="text-xs text-slate-500 leading-relaxed">{uc.description}</div>
              </div>

              {/* Card footer */}
              <div className="px-5 py-3 flex items-center justify-between">
                <div className="flex items-center gap-1.5 flex-wrap">
                  {uc.actions.map(aId => {
                    const a = actionMap[aId];
                    if (!a) return null;
                    return (
                      <span key={aId} className="text-[10px] mono px-2 py-0.5 rounded-md font-bold flex items-center gap-1"
                        style={{ color: a.enabled ? a.color : '#475569', background: a.enabled ? a.color + '12' : '#1e293b', border: `1px solid ${a.enabled ? a.color + '25' : '#334155'}` }}>
                        <div className="w-1 h-1 rounded-full" style={{ background: a.enabled ? a.color : '#475569' }} />
                        {aId}
                      </span>
                    );
                  })}
                </div>
                <div className="text-[10px] mono font-bold shrink-0 ml-3" style={{ color: uc.color }}>{uc.stat}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
