// ============================================================
// SIMPLE MODE — Other views
// SimpleWorkflows · SimpleChannels · SimpleFunnels · SimpleAnalytics
// Plain-English wrappers around the Command mode systems.
// ============================================================

// ---------- Header banner shared across simple-mode pages ----------
function SimplePageHeader({ icon, title, sub, action }) {
  const I = icon ? Icon[icon] : null;
  return (
    <div className="smp-page-hd">
      <div className="smp-page-hd-l">
        {I && <div className="smp-page-icon"><I/></div>}
        <div>
          <div className="smp-page-title">{title}</div>
          <div className="smp-page-sub">{sub}</div>
        </div>
      </div>
      {action}
    </div>
  );
}

// ---------- Advanced-mode prompt (link to switch) ----------
function AdvancedToggle({ onSwitchMode }) {
  return (
    <div className="smp-advanced">
      <div>
        <div className="smp-advanced-title">Want to see everything?</div>
        <div className="smp-advanced-sub">
          Command Mode opens up every node, agent, integration, and log behind these systems —
          for power users and operators.
        </div>
      </div>
      <button className="smp-advanced-btn" onClick={onSwitchMode}>
        Show advanced controls →
      </button>
    </div>
  );
}

// ============================================================
// SimpleWorkflows — "Automations"
// Big on/off cards, friendly status labels, no node builder.
// ============================================================
function SimpleWorkflows({ onSwitchMode }) {
  const STATUS_MAP = {
    live:        { label: 'Working great',     color: '#5dffb0' },
    optimizing:  { label: 'Working great',     color: '#5dffb0' },
    training:    { label: 'Getting smarter',   color: '#8b6bff' },
    warning:     { label: 'Needs attention',   color: '#ffb14b' },
    failed:      { label: 'Needs attention',   color: '#ff5d6e' },
    paused:      { label: 'Paused',            color: '#8388a8' }
  };

  // Friendlier names for the most common categories
  const FRIENDLY = {
    capture:      'Lead follow-up',
    qualify:      'Lead scoring',
    booking:      'Booking helper',
    sales_fu:     'Missed-call recovery',
    ai_call:      'AI phone agent',
    crm:          'Contact sync',
    social:       'Social posting',
    content:      'Content creator',
    reputation:   'Reputation watcher',
    reviews:      'Review requests',
    reactivation: 'Win-back · old customers',
    support:      'Customer support',
    ops:          'Daily checklist',
    finance:      'Money reconciliation',
    team:         'Team alerts',
    multi:        'Multi-step deal closer'
  };

  const FRIENDLY_DESC = {
    capture:      'When someone leaves their email or phone, Demiurge follows up automatically.',
    qualify:      'Each new lead gets scored so you focus on the right ones.',
    booking:      'When someone wants to book, Demiurge handles the calendar back-and-forth.',
    sales_fu:     'When you miss a call, Demiurge texts them back within 30 seconds.',
    ai_call:      'Demiurge can ring leads on your behalf, answer questions, and book them in.',
    crm:          'Your contacts stay in sync across every tool you use.',
    social:       'Demiurge posts to every social account on the right schedule.',
    content:      'Captions, images, video — written in your voice, posted for you.',
    reputation:   'Demiurge watches for new reviews and mentions across the web.',
    reviews:      'Happy customers get asked for a review at the right moment.',
    reactivation: 'Demiurge re-engages old customers with personalised offers.',
    support:      'Tier-1 questions are answered automatically. Trickier ones come to you.',
    ops:          'Your daily ops checklist runs itself — vendors, invoices, follow-ups.',
    finance:      'Payments, refunds, and reconciliations are kept neat behind the scenes.',
    team:         'Your team gets the right alerts at the right time.',
    multi:        'For big deals: outreach, qualification, booking, follow-up — all chained.'
  };

  const [states, setStates] = React.useState(() => {
    const init = {};
    (window.WORKFLOWS || []).forEach(w => { init[w.id] = w.status === 'live' || w.status === 'optimizing' || w.status === 'training'; });
    return init;
  });

  const wfs = window.WORKFLOWS || [];

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Flow"
        title="Automations"
        sub="Things Demiurge does for you automatically, so you don't have to."
      />

      <div className="smp-wf-grid">
        {wfs.map(w => {
          const st = STATUS_MAP[w.status];
          const friendlyName = FRIENDLY[w.cat] || w.name;
          const friendlyDesc = FRIENDLY_DESC[w.cat] || 'Runs in the background to save you time.';
          const on = states[w.id];
          return (
            <div key={w.id} className={`smp-wf ${on ? 'on' : 'off'}`}>
              <div className="smp-wf-hd">
                <div className="smp-wf-info">
                  <div className="smp-wf-name">{friendlyName}</div>
                  <div className="smp-wf-status" style={{color: st.color}}>
                    <span className="smp-wf-pip" style={{background: st.color, boxShadow: `0 0 6px ${st.color}`}}/>
                    {on ? st.label : 'Paused'}
                  </div>
                </div>
                <button
                  className={`smp-toggle ${on ? 'on' : ''}`}
                  onClick={() => setStates(s => ({...s, [w.id]: !s[w.id]}))}
                >
                  <span className="smp-toggle-knob"/>
                </button>
              </div>
              <div className="smp-wf-desc">{friendlyDesc}</div>
              <div className="smp-wf-stats">
                <div>
                  <div className="smp-wf-stat-v">{w.triggers24h.toLocaleString()}</div>
                  <div className="smp-wf-stat-l">times this week</div>
                </div>
                <div>
                  <div className="smp-wf-stat-v" style={{color: w.success >= 90 ? '#5dffb0' : '#4be8ff'}}>{w.success}%</div>
                  <div className="smp-wf-stat-l">success rate</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <AdvancedToggle onSwitchMode={onSwitchMode}/>
    </div>
  );
}

// ============================================================
// SimpleChannels — "Social Media"
// Clean grid, hide proxy/warming/session details.
// ============================================================
function SimpleChannels({ onSwitchMode }) {
  const channels = window.CHANNELS || [];
  const broadcast = channels.filter(c => c.group === 'broadcast');
  const bots = channels.filter(c => c.group === 'bot');
  const total = channels.reduce((s, c) => s + c.total, 0);
  const totalPosts = channels.reduce((s, c) => s + c.scheduled, 0);
  const bestChannel = [...broadcast].sort((a, b) => parseFloat(b.eng) - parseFloat(a.eng))[0];

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Globe"
        title="Social media"
        sub="Every account you have — in one place."
        action={
          <div style={{display: 'flex', gap: 10}}>
            <button className="smp-btn">Post everywhere</button>
            <button className="smp-btn-primary">Create content</button>
          </div>
        }
      />

      {/* Top-line outcomes */}
      <div className="smp-channels-summary">
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Accounts connected</div>
          <div className="smp-cs-val">{total}</div>
          <div className="smp-cs-sub">across {channels.length} platforms</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Posts scheduled this week</div>
          <div className="smp-cs-val" style={{color: '#5dffb0'}}>{totalPosts}</div>
          <div className="smp-cs-sub">written and queued by Demiurge</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Best performing right now</div>
          <div className="smp-cs-val" style={{color: bestChannel?.tone || '#4be8ff'}}>{bestChannel?.name || '—'}</div>
          <div className="smp-cs-sub">{bestChannel ? `${bestChannel.eng} engagement` : ''}</div>
        </div>
      </div>

      {/* Platform grid */}
      <div className="smp-page-section-hd">All your platforms</div>
      <div className="smp-ch-grid">
        {[...broadcast, ...bots].map(c => (
          <div key={c.id} className="smp-ch-card">
            <div className="smp-ch-hd">
              <div style={{color: c.tone}}>{window.ConsoleChannelGlyph ? React.createElement(window.ConsoleChannelGlyph, {kind: c.id, size: 28}) : null}</div>
              <div style={{flex: 1, minWidth: 0}}>
                <div className="smp-ch-name">{c.name}</div>
                <div className="smp-ch-sub">{c.total} account{c.total > 1 ? 's' : ''}</div>
              </div>
              <div className="smp-ch-status">
                <span className="smp-wf-pip" style={{background: '#5dffb0', boxShadow: '0 0 6px #5dffb0'}}/>
              </div>
            </div>
            <div className="smp-ch-stats">
              <div>
                <div className="smp-ch-stat-v">{c.published24}</div>
                <div className="smp-ch-stat-l">posts this week</div>
              </div>
              <div>
                <div className="smp-ch-stat-v" style={{color: '#4be8ff'}}>{c.reach24h}</div>
                <div className="smp-ch-stat-l">people reached</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <AdvancedToggle onSwitchMode={onSwitchMode}/>
    </div>
  );
}

// ============================================================
// SimpleFunnels — "Customer Journey"
// One path. No builder. AI improves it.
// ============================================================
function SimpleFunnels({ onSwitchMode }) {
  const steps = [
    { name: 'People saw your page',  count: 8412, pct: 100 },
    { name: 'People contacted you',  count: 1284, pct: 15.3 },
    { name: 'People booked a call',  count: 236,  pct: 2.8 },
    { name: 'People became customers', count: 84,  pct: 1.0 }
  ];

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Funnel"
        title="Your customer journey"
        sub="How people discover you and become customers."
      />

      <div className="smp-journey">
        {steps.map((s, i) => {
          const next = steps[i + 1];
          const dropPct = next ? Math.round(((s.count - next.count) / s.count) * 100) : null;
          return (
            <React.Fragment key={s.name}>
              <div className="smp-journey-step">
                <div className="smp-journey-num">{String(i + 1).padStart(2, '0')}</div>
                <div className="smp-journey-info">
                  <div className="smp-journey-name">{s.name}</div>
                  <div className="smp-journey-count">{s.count.toLocaleString()} <span className="smp-journey-pct">· {s.pct.toFixed(1)}% of top</span></div>
                </div>
                <div className="smp-journey-bar-wrap">
                  <div className="smp-journey-bar" style={{width: `${Math.max(s.pct, 8)}%`}}/>
                </div>
              </div>
              {next && (
                <div className="smp-journey-drop">
                  ↓ <strong>{dropPct}%</strong> of people stopped here ({(s.count - next.count).toLocaleString()} people)
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>

      {/* AI improve panel */}
      <div className="smp-improve">
        <div className="smp-improve-glyph">✦</div>
        <div style={{flex: 1}}>
          <div className="smp-improve-title">Want more customers from the same traffic?</div>
          <div className="smp-improve-sub">
            Demiurge can analyse where people are dropping off and rewrite the parts that aren't working.
            Most owners see a 15-30% lift in 30 days.
          </div>
        </div>
        <button className="smp-btn-primary">Improve my journey</button>
      </div>

      <AdvancedToggle onSwitchMode={onSwitchMode}/>
    </div>
  );
}

// ============================================================
// SimpleAnalytics — "Insights"
// Plain English numbers, tooltips on every metric.
// ============================================================
function SimpleAnalytics({ onSwitchMode }) {
  const cards = [
    { id: 'revenue',    title: 'Money you made this month',           v: '£487,200', delta: '+18%', sub: 'vs last month' },
    { id: 'leads',      title: 'New leads',                           v: '4,218',    delta: '+24%', sub: 'people interested in you' },
    { id: 'booked',     title: 'Booked appointments',                 v: '1,284',    delta: '+24%', sub: 'on your calendar' },
    { id: 'cac',        title: 'Cost to get a customer',              v: '£184',     delta: '-12%', sub: 'cheaper than last month', invert: true,
      tooltip: 'How much you spend on average to win one new customer.' },
    { id: 'ltv',        title: 'How much a customer is worth',        v: '£8,412',   delta: '+8%',  sub: 'over their lifetime',
      tooltip: 'The total value of a customer across all their purchases with you.' },
    { id: 'roas',       title: 'Money made from advertising',         v: '6.2×',     delta: '+0.8×', sub: 'for every £1 spent',
      tooltip: 'For every £1 you put into ads, this is what comes back.' },
    { id: 'conv',       title: 'People turning into customers',       v: '18.4%',    delta: '+2.1', sub: 'of interested leads',
      tooltip: 'Out of everyone who reaches out, how many actually buy.' },
    { id: 'reach',      title: 'People your business reached',        v: '812,000',  delta: '+18%', sub: 'across all channels' }
  ];

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Chart"
        title="Insights"
        sub="What's working, what isn't, and what to do next."
        action={<button className="smp-btn">This month ▾</button>}
      />

      <div className="smp-an-grid">
        {cards.map(c => {
          const positive = c.invert ? c.delta.startsWith('-') : c.delta.startsWith('+');
          return (
            <div key={c.id} className="smp-an-card">
              <div className="smp-an-lbl">
                {c.title}
                {c.tooltip && <span className="smp-explain" title={c.tooltip}>?</span>}
              </div>
              <div className="smp-an-val">{c.v}</div>
              <div className="smp-an-delta">
                <span className={positive ? 'smp-up' : 'smp-dn'}>{c.delta}</span>
                <span style={{color: 'var(--text-dim)'}}>{c.sub}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="smp-improve">
        <div className="smp-improve-glyph">✦</div>
        <div style={{flex: 1}}>
          <div className="smp-improve-title">Where your customers come from</div>
          <div className="smp-improve-sub">
            TikTok is your best channel right now — for every £1 you put in, it returns £8.40.
            Google is second at £6.40. We'd suggest moving some Facebook spend to TikTok this month.
          </div>
        </div>
        <button className="smp-btn-primary">See the breakdown</button>
      </div>

      <AdvancedToggle onSwitchMode={onSwitchMode}/>
    </div>
  );
}

window.SimpleWorkflows = SimpleWorkflows;
window.SimpleChannels = SimpleChannels;
window.SimpleFunnels = SimpleFunnels;
window.SimpleAnalytics = SimpleAnalytics;
window.AdvancedToggle = AdvancedToggle;
