// ============================================================
// SIMPLE MODE DASHBOARD
// Outcome-focused, plain-English, low cognitive load.
// ============================================================

const SimpleSparkline = ({ data, color = '#5dffb0', height = 36 }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 80 - 10}`).join(' ');
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{width: '100%', height, opacity: 0.9}}>
      <defs>
        <linearGradient id={`smp-spk-${color.slice(1)}`} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={color} stopOpacity="0.3"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={`0,100 ${pts} 100,100`} fill={`url(#smp-spk-${color.slice(1)})`}/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
};

function SimpleDashboard({ onNav, settings }) {
  const userName = settings?.userName || 'Reza';
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 18) return 'Good afternoon';
    return 'Good evening';
  })();

  const [aiQuery, setAiQuery] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [aiResult, setAiResult] = React.useState(null);

  const askDemiurge = async (q) => {
    const query = q || aiQuery;
    if (!query.trim()) return;
    setBusy(true);
    setAiResult(null);
    try {
      const text = await window.claude.complete({
        messages: [{
          role: 'user',
          content: `You are Demiurge, a friendly AI assistant for a small business owner. Answer briefly (3-5 sentences, conversational, no jargon, no bullet points unless essential): "${query}"`
        }]
      });
      setAiResult(text);
    } catch {
      setAiResult(`Here's where I'd help you get started: pick one of the quick options below and I'll set things up step-by-step. You won't have to figure anything out alone — I'll handle the technical bits.`);
    }
    setBusy(false);
  };

  const revenueData = React.useMemo(() => Array.from({length: 14}, (_, i) => 200 + Math.sin(i * 0.7) * 100 + Math.random() * 80), []);

  return (
    <div className="smp">
      {/* Greeting hero */}
      <div className="smp-hero">
        <div>
          <div className="smp-greeting">{greeting}, {userName}.</div>
          <div className="smp-sub">Here's how your business is doing today.</div>
        </div>
        <div className="smp-hero-time">
          <span className="smp-hero-time-pip"></span>
          Everything is running smoothly
        </div>
      </div>

      {/* AI onboarding assistant */}
      <div className="smp-assistant">
        <div className="smp-assistant-l">
          <div className="smp-assistant-glyph">
            <svg viewBox="0 0 40 40" width="40" height="40">
              <defs>
                <radialGradient id="smp-orb" cx="35%" cy="35%">
                  <stop offset="0%" stopColor="#fff"/>
                  <stop offset="50%" stopColor="#c8a8ff"/>
                  <stop offset="100%" stopColor="#1e1455"/>
                </radialGradient>
              </defs>
              <circle cx="20" cy="20" r="14" fill="url(#smp-orb)"/>
              <ellipse cx="20" cy="20" rx="17" ry="5" fill="none" stroke="#4be8ff" strokeWidth="0.8" transform="rotate(-22 20 20)"/>
            </svg>
          </div>
          <div>
            <div className="smp-assistant-title">What would you like help with?</div>
            <div className="smp-assistant-sub">Ask in plain English. I'll handle the rest.</div>
          </div>
        </div>
        <div className="smp-assistant-quick">
          {[
            ['Get more leads',         'Find new customers for your business'],
            ['Book more appointments', 'Fill up your calendar'],
            ['Post content',           'Show up on social media'],
            ['Follow up customers',    'Stay in touch automatically'],
            ['Grow revenue',           'Make more money this month']
          ].map(([label, sub]) => (
            <button key={label} className="smp-quick-btn" onClick={() => askDemiurge(label + '. ' + sub)}>
              <span className="smp-quick-label">{label}</span>
              <span className="smp-quick-sub">{sub}</span>
            </button>
          ))}
        </div>
        <div className="smp-assistant-input">
          <input
            value={aiQuery}
            onChange={e => setAiQuery(e.target.value)}
            placeholder={'Or type your own question — "Why aren\'t my ads working?"'}
            onKeyDown={e => { if (e.key === 'Enter') askDemiurge(); }}
          />
          <button className="smp-btn-primary" onClick={() => askDemiurge()} disabled={busy}>
            {busy ? 'Thinking…' : 'Ask Demiurge'}
          </button>
        </div>
        {aiResult && (
          <div className="smp-assistant-answer">
            <div className="smp-assistant-answer-lbl">Demiurge says</div>
            {aiResult}
          </div>
        )}
      </div>

      {/* The 7 outcome cards */}
      <div className="smp-grid">
        {/* Revenue Today — hero card */}
        <div className="smp-card smp-card-hero" onClick={() => onNav('analytics')}>
          <div className="smp-card-lbl">Revenue today</div>
          <div className="smp-card-hero-val">£18,412</div>
          <div className="smp-card-hero-sub">
            <span className="smp-up">↑ 24% more</span> than yesterday. You're having a great day.
          </div>
          <div style={{height: 60, marginTop: 18}}>
            <SimpleSparkline data={revenueData} color="#5dffb0" height={60}/>
          </div>
          <div className="smp-card-foot">
            <span>This week so far · <strong>£124,800</strong></span>
            <span className="smp-card-action">See the details →</span>
          </div>
        </div>

        {/* Leads */}
        <div className="smp-card" onClick={() => onNav('contacts')}>
          <div className="smp-card-lbl">New leads</div>
          <div className="smp-card-val">17</div>
          <div className="smp-card-desc">
            You received <strong>17 new leads</strong> this week.<br/>
            They're being reached out to automatically.
          </div>
          <div className="smp-card-tags">
            <span className="smp-tag">8 from TikTok</span>
            <span className="smp-tag">4 from Google</span>
            <span className="smp-tag">5 from referrals</span>
          </div>
          <div className="smp-card-action">See your leads →</div>
        </div>

        {/* Appointments */}
        <div className="smp-card" onClick={() => onNav('calendar')}>
          <div className="smp-card-lbl">Upcoming appointments</div>
          <div className="smp-card-val">8</div>
          <div className="smp-card-desc">
            You have <strong>8 appointments</strong> coming up in the next 7 days.
          </div>
          <div className="smp-appt-list">
            {[
              { who: 'Sarah Mitchell',  when: 'Today · 2:30 PM',     kind: 'Discovery call' },
              { who: 'James Chen',      when: 'Tomorrow · 10:00 AM', kind: 'Demo' },
              { who: 'Lily Roberts',    when: 'Tomorrow · 3:00 PM',  kind: 'Follow-up' }
            ].map((a, i) => (
              <div key={i} className="smp-appt">
                <div className="smp-appt-time">{a.when}</div>
                <div className="smp-appt-info">
                  <div>{a.who}</div>
                  <div className="smp-appt-kind">{a.kind}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="smp-card-action">See your calendar →</div>
        </div>

        {/* Messages */}
        <div className="smp-card smp-card-warn" onClick={() => onNav('inbox')}>
          <div className="smp-card-lbl">Needs your attention</div>
          <div className="smp-card-val">3</div>
          <div className="smp-card-desc">
            <strong>3 customers are waiting for replies.</strong><br/>
            Demiurge drafted responses — just say yes and they'll send.
          </div>
          <div className="smp-msg-list">
            {[
              { who: 'Mark T.', preview: '"Is this still available? Looking to..."'},
              { who: 'Aisha B.', preview: '"Can we reschedule to Thursday?"'},
              { who: 'Tom K.',  preview: '"What\'s the price for the larger pack..."'}
            ].map((m, i) => (
              <div key={i} className="smp-msg">
                <span className="smp-msg-who">{m.who}</span>
                <span className="smp-msg-preview">{m.preview}</span>
              </div>
            ))}
          </div>
          <div className="smp-card-action">Reply now →</div>
        </div>

        {/* Marketing performance */}
        <div className="smp-card" onClick={() => onNav('channels')}>
          <div className="smp-card-lbl">Marketing performance</div>
          <div className="smp-card-val-text"><strong>TikTok</strong> is bringing you the most customers right now.</div>
          <div className="smp-card-desc">
            For every £1 you spend on TikTok ads, you're making <strong className="smp-up">£8.40 back</strong>.
            That's the best of any channel.
          </div>
          <div className="smp-bars">
            {[
              { name: 'TikTok',    bar: 100, gain: '£8.40', col: '#5dffb0' },
              { name: 'Google',    bar: 76,  gain: '£6.40', col: '#4be8ff' },
              { name: 'Instagram', bar: 64,  gain: '£5.20', col: '#ff7ad9' },
              { name: 'Facebook',  bar: 42,  gain: '£3.80', col: '#8b6bff' }
            ].map((c, i) => (
              <div key={i} className="smp-bar-row">
                <span className="smp-bar-label">{c.name}</span>
                <div className="smp-bar-track">
                  <div className="smp-bar-fill" style={{width: `${c.bar}%`, background: c.col, boxShadow: `0 0 8px ${c.col}40`}}/>
                </div>
                <span className="smp-bar-val">{c.gain}</span>
              </div>
            ))}
          </div>
          <div className="smp-card-action">See marketing details →</div>
        </div>

        {/* Growth suggestions */}
        <div className="smp-card smp-card-grow">
          <div className="smp-card-lbl">
            <span className="smp-card-spark">✦</span>
            Growth suggestions
          </div>
          <div className="smp-card-desc">
            Demiurge has <strong>3 ideas</strong> to grow your business this month.
          </div>
          <div className="smp-sugg-list">
            {[
              { title: 'Reply to leads faster',     impact: 'You could close 18% more customers',   action: 'Turn on auto-replies', do: () => window.runAction('deployWorkflow') },
              { title: 'Spend more on TikTok',      impact: 'It\'s making you £8.40 for every £1',  action: 'Shift £200/week from Facebook', do: () => window.runAction('launchCampaign') },
              { title: 'Send review requests',      impact: 'Get 4-6 new 5-star reviews per month', action: 'Switch this on', do: () => window.runAction('deployWorkflow') }
            ].map((s, i) => (
              <div key={i} className="smp-sugg">
                <div className="smp-sugg-content">
                  <div className="smp-sugg-title">{s.title}</div>
                  <div className="smp-sugg-impact">{s.impact}</div>
                </div>
                <button className="smp-sugg-btn" data-handled="1" onClick={(e) => { e.stopPropagation(); s.do(); }}>{s.action}</button>
              </div>
            ))}
          </div>
        </div>

        {/* Tasks to approve */}
        <div className="smp-card">
          <div className="smp-card-lbl">Things to confirm</div>
          <div className="smp-card-val">4</div>
          <div className="smp-card-desc">
            Demiurge has <strong>4 things</strong> ready and waiting for your sign-off.
          </div>
          <div className="smp-task-list">
            {[
              { what: 'Send weekly newsletter to 2,400 customers', kind: 'Email',    edit: () => window.runAction('compose'), approve: () => window.toast('Newsletter sending', 'ok', 'Going to 2,400 customers · tracking opens') },
              { what: 'Post 3 TikTok videos for next week',         kind: 'Content',  edit: () => window.runAction('createContent'), approve: () => window.toast('Scheduled', 'ok', '3 TikTok posts queued at optimal times') },
              { what: 'Launch reactivation offer to 84 leads',     kind: 'Campaign', edit: () => window.runAction('launchCampaign'), approve: () => window.toast('Campaign launched', 'ok', '84 leads · win-back offer · live now') },
              { what: 'Reply to a complaint on Google reviews',    kind: 'Reputation', edit: () => window.runAction('compose'), approve: () => window.toast('Reply sent', 'ok', 'Posted to Google review · audit logged') }
            ].map((t, i) => (
              <div key={i} className="smp-task">
                <div className="smp-task-content">
                  <div className="smp-task-kind">{t.kind}</div>
                  <div className="smp-task-what">{t.what}</div>
                </div>
                <div className="smp-task-actions">
                  <button className="smp-task-no" data-handled="1" onClick={(e) => { e.stopPropagation(); t.edit(); }}>Edit</button>
                  <button className="smp-task-yes" data-handled="1" onClick={(e) => { e.stopPropagation(); t.approve(); }}>Approve</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quick actions footer */}
      <div className="smp-actions">
        <div className="smp-actions-title">Quick actions</div>
        <div className="smp-actions-grid">
          {[
            ['Launch campaign',     'Promote something to your customers',         'Megaphone', 'campaigns'],
            ['Post to social',      'Share content on every platform at once',     'Globe',     'channels'],
            ['Message leads',       'Reach out to people interested in you',       'Inbox',     'inbox'],
            ['Create offer',        'Make a discount or promotion',                'Sparkles',  'campaigns'],
            ['See appointments',    'View what\'s on the calendar',                'Calendar',  'calendar'],
            ['Ask AI assistant',    'Get personalised business advice',            'Bolt',      null]
          ].map(([title, sub, icon, dest], i) => {
            const I = Icon[icon] || Icon.Bolt;
            return (
              <button key={title} className="smp-action" onClick={() => dest ? onNav(dest) : askDemiurge('How can I grow my business this month?')}>
                <div className="smp-action-icon"><I/></div>
                <div>
                  <div className="smp-action-title">{title}</div>
                  <div className="smp-action-sub">{sub}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.SimpleDashboard = SimpleDashboard;
window.SimpleSparkline = SimpleSparkline;
