// ============================================================
// SIMPLE MODE — Remaining views
// SimpleInbox · SimpleCalendar · SimpleContacts · SimpleCampaigns · SimpleSettings
// ============================================================

// ============================================================
// SimpleInbox — "Messages"
// ============================================================
function SimpleInbox({ onSwitchMode }) {
  const [active, setActive] = React.useState(0);
  const [draft, setDraft] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const threads = [
    { who: 'Mark Thompson',    channel: 'Instagram DM',  preview: 'Is this still available?',                  needsReply: true,  unread: 2, time: '14m ago' },
    { who: 'Aisha Bello',      channel: 'WhatsApp',      preview: 'Can we reschedule to Thursday?',            needsReply: true,  unread: 1, time: '38m ago' },
    { who: 'Tom Kettle',       channel: 'SMS',           preview: 'What\'s the price for the larger pack?',    needsReply: true,  unread: 1, time: '1h ago' },
    { who: 'Sarah Mitchell',   channel: 'Email',         preview: 'Confirmed for Tuesday at 2:30 PM. Thanks!', needsReply: false, unread: 0, time: '2h ago' },
    { who: 'James Chen',       channel: 'Facebook',      preview: 'Great chat — sent over the brief.',         needsReply: false, unread: 0, time: '3h ago' },
    { who: 'Lily Roberts',     channel: 'Instagram DM',  preview: 'See you Thursday!',                         needsReply: false, unread: 0, time: '5h ago' },
    { who: 'Priya Iyer',       channel: 'Email',         preview: 'I love the proposal — sending payment.',    needsReply: false, unread: 0, time: '1d ago' }
  ];

  const t = threads[active];

  const draftReply = async () => {
    setBusy(true);
    try {
      const reply = await window.claude.complete({
        messages: [{
          role: 'user',
          content: `You are replying as a friendly small-business owner. The customer asked: "${t.preview}". Write a short, warm 2-3 sentence reply. No preamble.`
        }]
      });
      setDraft(reply);
    } catch {
      setDraft(`Hi ${t.who.split(' ')[0]} — yes it is! Want me to hold one for you? I can also send over a quick rundown if helpful.`);
    }
    setBusy(false);
  };

  React.useEffect(() => { setDraft(''); }, [active]);

  return (
    <div className="smp">
      <SimplePageHeader icon="Inbox" title="Messages" sub="Everyone trying to reach you, in one place."/>

      <div className="smp-inbox">
        <div className="smp-inbox-list">
          {threads.map((th, i) => (
            <button
              key={i}
              className={`smp-inbox-thread ${active === i ? 'on' : ''} ${th.needsReply ? 'attention' : ''}`}
              onClick={() => setActive(i)}
            >
              <div className="smp-inbox-thread-l">
                <div className="smp-inbox-avatar">{th.who.split(' ').map(p => p[0]).slice(0, 2).join('')}</div>
                {th.unread > 0 && <span className="smp-inbox-unread">{th.unread}</span>}
              </div>
              <div className="smp-inbox-thread-r">
                <div className="smp-inbox-thread-top">
                  <span className="smp-inbox-who">{th.who}</span>
                  <span className="smp-inbox-time">{th.time}</span>
                </div>
                <div className="smp-inbox-channel">{th.channel}</div>
                <div className="smp-inbox-preview">{th.preview}</div>
              </div>
            </button>
          ))}
        </div>

        <div className="smp-inbox-panel">
          <div className="smp-inbox-panel-hd">
            <div>
              <div className="smp-inbox-panel-who">{t.who}</div>
              <div className="smp-inbox-panel-channel">{t.channel} · {t.time}</div>
            </div>
            {t.needsReply && <span className="smp-inbox-tag">Needs reply</span>}
          </div>

          <div className="smp-inbox-conv">
            <div className="smp-inbox-msg them">{t.preview}</div>
            <div className="smp-inbox-msg-time">{t.time}</div>
          </div>

          <div className="smp-inbox-draft">
            <div className="smp-inbox-draft-hd">
              <span className="smp-card-spark">✦</span>
              <span>Demiurge can draft your reply</span>
              <span style={{flex: 1}}/>
              <button className="smp-btn-primary" onClick={draftReply} disabled={busy}>
                {busy ? 'Writing…' : draft ? 'Rewrite' : 'Draft a reply'}
              </button>
            </div>
            <textarea
              value={draft}
              onChange={e => setDraft(e.target.value)}
              placeholder="Or type your own reply…"
              rows={4}
            />
            <div className="smp-inbox-draft-actions">
              <button className="smp-btn">Save for later</button>
              <button className="smp-btn-primary" disabled={!draft.trim()}>Send reply</button>
            </div>
          </div>
        </div>
      </div>

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

// ============================================================
// SimpleCalendar — "Appointments"
// ============================================================
function SimpleCalendar({ onSwitchMode }) {
  const days = [
    { date: 'Today',        d: 'Tue 22 May', slots: [
      { time: '10:00 AM', who: 'Sarah Mitchell',  kind: 'Discovery call', status: 'confirmed' },
      { time: '2:30 PM',  who: 'Mark Thompson',   kind: 'Demo',           status: 'confirmed' }
    ]},
    { date: 'Tomorrow',     d: 'Wed 23 May', slots: [
      { time: '10:00 AM', who: 'James Chen',      kind: 'Demo',           status: 'confirmed' },
      { time: '3:00 PM',  who: 'Lily Roberts',    kind: 'Follow-up',      status: 'confirmed' },
      { time: '4:30 PM',  who: 'Aisha Bello',     kind: 'Discovery call', status: 'awaiting' }
    ]},
    { date: 'Thursday',     d: 'Thu 24 May', slots: [
      { time: '11:00 AM', who: 'Tom Kettle',      kind: 'Quote review',   status: 'confirmed' }
    ]},
    { date: 'Friday',       d: 'Fri 25 May', slots: [
      { time: '9:30 AM',  who: 'Priya Iyer',      kind: 'Close call',     status: 'confirmed' },
      { time: '2:00 PM',  who: 'Marcus W.',       kind: 'Demo',           status: 'confirmed' }
    ]}
  ];

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Calendar"
        title="Appointments"
        sub="What's on your calendar this week."
        action={<button className="smp-btn-primary">Block off time</button>}
      />

      <div className="smp-cal-summary">
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">This week</div>
          <div className="smp-cs-val">{days.reduce((s, d) => s + d.slots.length, 0)}</div>
          <div className="smp-cs-sub">appointments booked</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Booked by Demiurge</div>
          <div className="smp-cs-val" style={{color: '#5dffb0'}}>{days.reduce((s, d) => s + d.slots.length, 0) - 1}</div>
          <div className="smp-cs-sub">while you were busy</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Next available slot</div>
          <div className="smp-cs-val" style={{color: '#4be8ff', fontSize: 28}}>Today<br/>4:30 PM</div>
          <div className="smp-cs-sub">free to take a meeting</div>
        </div>
      </div>

      <div className="smp-page-section-hd">Schedule</div>
      <div className="smp-cal-days">
        {days.map((day, i) => (
          <div key={i} className="smp-cal-day">
            <div className="smp-cal-day-hd">
              <div className="smp-cal-day-name">{day.date}</div>
              <div className="smp-cal-day-date">{day.d} · {day.slots.length} appt{day.slots.length !== 1 ? 's' : ''}</div>
            </div>
            <div className="smp-cal-slots">
              {day.slots.map((s, si) => (
                <div key={si} className={`smp-cal-slot ${s.status}`}>
                  <div className="smp-cal-slot-time">{s.time}</div>
                  <div className="smp-cal-slot-info">
                    <div className="smp-cal-slot-who">{s.who}</div>
                    <div className="smp-cal-slot-kind">{s.kind}</div>
                  </div>
                  <div className="smp-cal-slot-status">
                    {s.status === 'confirmed'
                      ? <span style={{color: '#5dffb0'}}>● Confirmed</span>
                      : <span style={{color: '#ffb14b'}}>● Waiting</span>}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

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

// ============================================================
// SimpleContacts — "Customers"
// ============================================================
function SimpleContacts({ onSwitchMode }) {
  const [filter, setFilter] = React.useState('all');
  const customers = [
    { name: 'Sarah Mitchell',  status: 'customer', value: 8400,  source: 'Google',    lastTouch: '2d ago', mood: 'happy' },
    { name: 'James Chen',      status: 'lead',     value: 0,     source: 'TikTok',    lastTouch: '6h ago', mood: 'warm' },
    { name: 'Lily Roberts',    status: 'customer', value: 12800, source: 'Referral',  lastTouch: '14m ago', mood: 'happy' },
    { name: 'Mark Thompson',   status: 'hot',      value: 0,     source: 'Instagram', lastTouch: 'now',    mood: 'warm' },
    { name: 'Priya Iyer',      status: 'customer', value: 24000, source: 'LinkedIn',  lastTouch: '1d ago', mood: 'happy' },
    { name: 'Aisha Bello',     status: 'lead',     value: 0,     source: 'WhatsApp',  lastTouch: '38m ago', mood: 'cold' },
    { name: 'Tom Kettle',      status: 'hot',      value: 0,     source: 'SMS',       lastTouch: '1h ago',  mood: 'warm' },
    { name: 'Marcus Whitfield',status: 'customer', value: 18400, source: 'Google',    lastTouch: '3d ago',  mood: 'happy' },
    { name: 'Anya Patel',      status: 'customer', value: 38400, source: 'Referral',  lastTouch: '6d ago',  mood: 'happy' },
    { name: 'Hiroshi Tanaka',  status: 'lead',     value: 0,     source: 'Email',     lastTouch: '4h ago',  mood: 'cold' }
  ];

  const STATUS = {
    customer: { label: 'Customer',  color: '#5dffb0' },
    hot:      { label: 'Hot lead',  color: '#ffb14b' },
    lead:     { label: 'Lead',      color: '#4be8ff' }
  };

  const filtered = filter === 'all' ? customers : customers.filter(c => c.status === filter);
  const totalValue = customers.filter(c => c.status === 'customer').reduce((s, c) => s + c.value, 0);

  return (
    <div className="smp">
      <SimplePageHeader
        icon="People"
        title="Customers"
        sub="Everyone who's interested in your business."
        action={<button className="smp-btn-primary">Add customer</button>}
      />

      <div className="smp-cal-summary">
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Total people</div>
          <div className="smp-cs-val">{customers.length}</div>
          <div className="smp-cs-sub">customers + leads</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Customer value</div>
          <div className="smp-cs-val" style={{color: '#5dffb0'}}>£{(totalValue/1000).toFixed(0)}k</div>
          <div className="smp-cs-sub">total spent with you</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Hot leads right now</div>
          <div className="smp-cs-val" style={{color: '#ffb14b'}}>{customers.filter(c => c.status === 'hot').length}</div>
          <div className="smp-cs-sub">worth reaching out today</div>
        </div>
      </div>

      <div className="smp-customer-filters">
        {[['all','All'],['customer','Customers'],['hot','Hot leads'],['lead','Leads']].map(([k, l]) => (
          <button key={k} className={`smp-filter ${filter === k ? 'on' : ''}`} onClick={() => setFilter(k)}>
            {l} <span style={{opacity: 0.6}}>{k === 'all' ? customers.length : customers.filter(c => c.status === k).length}</span>
          </button>
        ))}
      </div>

      <div className="smp-customer-list">
        {filtered.map((c, i) => (
          <div key={i} className="smp-customer">
            <div className="smp-customer-avatar">{c.name.split(' ').map(p => p[0]).slice(0, 2).join('')}</div>
            <div className="smp-customer-info">
              <div className="smp-customer-name">{c.name}</div>
              <div className="smp-customer-meta">
                Found you on <strong>{c.source}</strong> · Last spoke <strong>{c.lastTouch}</strong>
              </div>
            </div>
            <div className="smp-customer-status" style={{color: STATUS[c.status].color, borderColor: `${STATUS[c.status].color}40`, background: `${STATUS[c.status].color}10`}}>
              {STATUS[c.status].label}
            </div>
            <div className="smp-customer-value">
              {c.value > 0 ? <span>£{c.value.toLocaleString()}</span> : <span style={{color: 'var(--text-faint)'}}>—</span>}
            </div>
            <div className="smp-customer-actions">
              <button className="smp-btn" data-handled="1" onClick={() => window.runAction('compose', { to: c.name })}>Message</button>
              <button className="smp-btn-primary" data-handled="1" onClick={() => window.toast(`Opening ${c.name}…`, 'info', `${STATUS[c.status].label} · ${c.source} · last spoke ${c.lastTouch}`)}>View</button>
            </div>
          </div>
        ))}
      </div>

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

// ============================================================
// SimpleCampaigns — "Campaigns"
// ============================================================
function SimpleCampaigns({ onSwitchMode }) {
  const campaigns = [
    { name: 'May newsletter',         channel: 'Email',     status: 'sent',     sent: 2400, opened: 1284, replied: 142, money: 8400 },
    { name: 'New patient offer',      channel: 'SMS',       status: 'live',     sent: 412,  opened: 392,  replied: 84,  money: 18400 },
    { name: 'TikTok video series',    channel: 'TikTok',    status: 'live',     sent: 6,    opened: 184000, replied: 412, money: 24800 },
    { name: 'Reactivation · 3 month', channel: 'Email+SMS', status: 'scheduled',sent: 0,    opened: 0,    replied: 0,   money: 0 },
    { name: 'Spring offer · LinkedIn',channel: 'LinkedIn',  status: 'draft',    sent: 0,    opened: 0,    replied: 0,   money: 0 }
  ];

  const STATUS = {
    live:      { label: 'Live now',     color: '#5dffb0' },
    sent:      { label: 'Finished',     color: '#4be8ff' },
    scheduled: { label: 'Scheduled',    color: '#8b6bff' },
    draft:     { label: 'Draft',        color: '#8388a8' }
  };

  return (
    <div className="smp">
      <SimplePageHeader
        icon="Megaphone"
        title="Campaigns"
        sub="Promotions and offers you're running."
        action={<button className="smp-btn-primary">Launch campaign</button>}
      />

      <div className="smp-cal-summary">
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Live right now</div>
          <div className="smp-cs-val" style={{color: '#5dffb0'}}>{campaigns.filter(c => c.status === 'live').length}</div>
          <div className="smp-cs-sub">campaigns running</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Money earned this month</div>
          <div className="smp-cs-val" style={{color: '#5dffb0'}}>£{(campaigns.reduce((s, c) => s + c.money, 0)/1000).toFixed(0)}k</div>
          <div className="smp-cs-sub">from active campaigns</div>
        </div>
        <div className="smp-cs-card">
          <div className="smp-cs-lbl">Best campaign</div>
          <div className="smp-cs-val" style={{color: '#4be8ff', fontSize: 26, lineHeight: 1.2}}>TikTok<br/>video series</div>
          <div className="smp-cs-sub">£24,800 earned</div>
        </div>
      </div>

      <div className="smp-page-section-hd">Your campaigns</div>
      <div className="smp-camp-list">
        {campaigns.map((c, i) => (
          <div key={i} className="smp-camp">
            <div className="smp-camp-l">
              <div className="smp-camp-name">{c.name}</div>
              <div className="smp-camp-channel">via {c.channel}</div>
            </div>
            <div className="smp-camp-status" style={{color: STATUS[c.status].color, borderColor: `${STATUS[c.status].color}40`, background: `${STATUS[c.status].color}10`}}>
              {STATUS[c.status].label}
            </div>
            <div className="smp-camp-stats">
              {c.status !== 'draft' && c.status !== 'scheduled' ? (
                <>
                  <div><div className="smp-camp-stat-v">{c.sent.toLocaleString()}</div><div className="smp-camp-stat-l">{c.channel === 'TikTok' ? 'posts' : 'sent'}</div></div>
                  <div><div className="smp-camp-stat-v" style={{color: '#4be8ff'}}>{c.opened.toLocaleString()}</div><div className="smp-camp-stat-l">{c.channel === 'TikTok' ? 'views' : 'opened'}</div></div>
                  <div><div className="smp-camp-stat-v" style={{color: '#5dffb0'}}>£{c.money.toLocaleString()}</div><div className="smp-camp-stat-l">earned</div></div>
                </>
              ) : (
                <div style={{color: 'var(--text-faint)', fontSize: 12.5, fontStyle: 'italic'}}>
                  {c.status === 'scheduled' ? 'Will go out next Monday' : 'Not yet started'}
                </div>
              )}
            </div>
            <button className="smp-btn">{c.status === 'draft' ? 'Continue editing' : c.status === 'scheduled' ? 'Edit' : 'View report'}</button>
          </div>
        ))}
      </div>

      <div className="smp-improve">
        <div className="smp-improve-glyph">✦</div>
        <div style={{flex: 1}}>
          <div className="smp-improve-title">Want Demiurge to write your next one?</div>
          <div className="smp-improve-sub">
            Just describe the offer or audience. Demiurge writes the email, picks the right channels,
            and schedules it. You approve before it sends.
          </div>
        </div>
        <button className="smp-btn-primary">Write me a campaign</button>
      </div>

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

// ============================================================
// SimpleSettings — "Settings"
// ============================================================
function SimpleSettings({ onSwitchMode }) {
  const [autopilot, setAutopilot] = React.useState(true);
  const [approveAll, setApproveAll] = React.useState(false);
  const [notifs, setNotifs] = React.useState(true);
  const [voice, setVoice] = React.useState('warm');

  return (
    <div className="smp">
      <SimplePageHeader icon="Settings" title="Settings" sub="Control how Demiurge runs your business."/>

      <div className="smp-settings">
        <div className="smp-set-card">
          <div className="smp-set-card-hd">Your business</div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Business name</div>
              <div className="smp-set-row-sub">How customers see you</div>
            </div>
            <input className="smp-set-input" defaultValue="Belmont Dental Group"/>
          </div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Industry</div>
              <div className="smp-set-row-sub">Helps Demiurge tune itself for you</div>
            </div>
            <input className="smp-set-input" defaultValue="Dental · multi-location"/>
          </div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Time zone</div>
              <div className="smp-set-row-sub">When messages and posts go out</div>
            </div>
            <input className="smp-set-input" defaultValue="Europe / London"/>
          </div>
        </div>

        <div className="smp-set-card">
          <div className="smp-set-card-hd">How Demiurge works for you</div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Let Demiurge run on autopilot</div>
              <div className="smp-set-row-sub">It will reply to messages, post content, and book calls automatically.</div>
            </div>
            <button className={`smp-toggle ${autopilot ? 'on' : ''}`} onClick={() => setAutopilot(a => !a)}>
              <span className="smp-toggle-knob"/>
            </button>
          </div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Ask me before sending anything</div>
              <div className="smp-set-row-sub">Useful if you want full control of every message and post.</div>
            </div>
            <button className={`smp-toggle ${approveAll ? 'on' : ''}`} onClick={() => setApproveAll(a => !a)}>
              <span className="smp-toggle-knob"/>
            </button>
          </div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Brand voice</div>
              <div className="smp-set-row-sub">How content sounds when Demiurge writes for you</div>
            </div>
            <div style={{display: 'flex', gap: 6}}>
              {[['warm','Warm'],['professional','Professional'],['playful','Playful'],['bold','Bold']].map(([k, l]) => (
                <button key={k} className={`smp-filter ${voice === k ? 'on' : ''}`} onClick={() => setVoice(k)}>{l}</button>
              ))}
            </div>
          </div>
        </div>

        <div className="smp-set-card">
          <div className="smp-set-card-hd">Notifications</div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Tell me when something needs my attention</div>
              <div className="smp-set-row-sub">Daily digest at 7 AM. Urgent items right away.</div>
            </div>
            <button className={`smp-toggle ${notifs ? 'on' : ''}`} onClick={() => setNotifs(a => !a)}>
              <span className="smp-toggle-knob"/>
            </button>
          </div>
        </div>

        <div className="smp-set-card">
          <div className="smp-set-card-hd">Plan & billing</div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Current plan</div>
              <div className="smp-set-row-sub">Growth · £2,400 / month · Cohort 014</div>
            </div>
            <button className="smp-btn">Manage</button>
          </div>
          <div className="smp-set-row">
            <div className="smp-set-row-l">
              <div className="smp-set-row-title">Payment method</div>
              <div className="smp-set-row-sub">Visa ending 4421 · expires 09/27</div>
            </div>
            <button className="smp-btn">Update</button>
          </div>
        </div>
      </div>

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

window.SimpleInbox = SimpleInbox;
window.SimpleCalendar = SimpleCalendar;
window.SimpleContacts = SimpleContacts;
window.SimpleCampaigns = SimpleCampaigns;
window.SimpleSettings = SimpleSettings;
