// MissionChef — Marketing module data + API extensions
// Newsletter (subscribers, segments, campaigns), Social (posts, channels, calendar),
// Inbox (messages), Analytics — everything wired into mcStore + mcApi.

(function () {
  if (!window.mcStore || !window.mcApi) {
    console.warn('mc-marketing-data: mcApi not loaded yet');
    return;
  }

  const daysAgo = (n) => { const d = new Date(); d.setDate(d.getDate() - n); return d.toISOString(); };
  const daysAhead = (n) => { const d = new Date(); d.setDate(d.getDate() + n); return d.toISOString(); };
  const hoursAgo = (n) => new Date(Date.now() - n * 3600 * 1000).toISOString();

  // ─── SUBSCRIBERS ───────────────────────────────────────────────────────────
  const FIRST_NAMES = ['Anna','Markus','Lisa','Stefan','Julia','Thomas','Sabine','Michael','Petra','Klaus','Sophie','Daniel','Eva','Christian','Karin','Patrick','Nina','Andreas','Maria','Florian','Hannah','Lukas','Carolin','Jonas','Lena','Tobias','Vanessa','Felix','Verena','Sebastian','Anja','Dominik','Birgit','Manuel','Sandra','Philipp','Tanja','Robert','Melanie','Ralf','Claudia','Oliver','Susanne','Martin','Nadine','Bernd','Katrin','Frank','Yvonne','Jörg'];
  const LAST_NAMES = ['Bauer','Schmidt','Müller','Wagner','Schneider','Fischer','Weber','Schulz','Hoffmann','Becker','Koch','Richter','Klein','Wolf','Schröder','Neumann','Schwarz','Zimmermann','Braun','Krüger','Hofmann','Hartmann','Lange','Werner','Schmitt','Krause','Meier','Lehmann','König','Köhler','Walter','Mayer','Huber','Kaiser','Fuchs','Peters','Lang','Scholz','Möller','Weiss','Jung','Hahn','Vogel','Friedrich','Keller','Günther','Frank','Berger','Winkler','Roth'];
  const SEGMENTS = ['VIP','Regulars','Newsletter only','Family','Birthday club','Lapsed','Wine lovers','Event guests'];
  const SOURCES = ['Reservierung','Website','Walk-in','Event','Instagram','Empfehlung','QR-Code'];

  function makeSubscribers() {
    const out = [];
    let r = 1;
    const seed = () => { r = (r * 9301 + 49297) % 233280; return r / 233280; };
    for (let i = 0; i < 1247; i++) {
      const fn = FIRST_NAMES[Math.floor(seed() * FIRST_NAMES.length)];
      const ln = LAST_NAMES[Math.floor(seed() * LAST_NAMES.length)];
      const segs = [];
      const segCount = seed() < 0.3 ? 2 : 1;
      for (let s = 0; s < segCount; s++) {
        const seg = SEGMENTS[Math.floor(seed() * SEGMENTS.length)];
        if (!segs.includes(seg)) segs.push(seg);
      }
      const status = seed() < 0.06 ? 'unsubscribed' : (seed() < 0.04 ? 'pending' : 'active');
      const opens = status === 'active' ? Math.floor(seed() * 24) : 0;
      const clicks = Math.floor(opens * (0.15 + seed() * 0.25));
      out.push({
        id: 'sub' + (1000 + i),
        name: `${fn} ${ln}`,
        firstName: fn,
        email: `${fn.toLowerCase()}.${ln.toLowerCase()}@${['gmail.com','web.de','gmx.de','outlook.com','t-online.de','icloud.com'][Math.floor(seed()*6)]}`,
        phone: seed() < 0.4 ? `+49 ${150 + Math.floor(seed()*99)} ${1000000 + Math.floor(seed()*8999999)}` : null,
        segments: segs,
        status,
        source: SOURCES[Math.floor(seed() * SOURCES.length)],
        joined: daysAgo(Math.floor(seed() * 720)),
        lastOpen: status === 'active' && seed() < 0.7 ? daysAgo(Math.floor(seed() * 30)) : null,
        opens,
        clicks,
        birthday: seed() < 0.55 ? `${1960 + Math.floor(seed()*45)}-${String(1+Math.floor(seed()*12)).padStart(2,'0')}-${String(1+Math.floor(seed()*28)).padStart(2,'0')}` : null,
        consent: { confirmed: status !== 'pending', confirmedAt: status !== 'pending' ? daysAgo(Math.floor(seed()*700)) : null, ip: '91.64.' + Math.floor(seed()*255) + '.' + Math.floor(seed()*255), source: 'Reservierungsformular' },
      });
    }
    return out;
  }

  // ─── SEGMENTS (with rules) ─────────────────────────────────────────────────
  const segments = [
    { id: 'sg-all',      name: 'Alle aktiven',     rule: 'status = active',                      count: 0, system: true },
    { id: 'sg-vip',      name: 'VIP',              rule: 'mehr als 12 Besuche / Jahr',           count: 0 },
    { id: 'sg-regulars', name: 'Stammgäste',       rule: 'mehr als 4 Besuche / Jahr',            count: 0 },
    { id: 'sg-bday',     name: 'Geburtstag heute', rule: 'birthday = TODAY',                     count: 7, dynamic: true },
    { id: 'sg-bday30',   name: 'Geburtstag 30 Tage', rule: 'birthday in 30d',                    count: 84, dynamic: true },
    { id: 'sg-lapsed',   name: 'Inaktiv 90+ Tage',  rule: 'last_visit > 90d',                    count: 0 },
    { id: 'sg-wine',     name: 'Weinliebhaber',     rule: 'tag = Wine lovers',                   count: 0 },
    { id: 'sg-events',   name: 'Event-Gäste',       rule: 'source = Event',                      count: 0 },
  ];

  // ─── CAMPAIGNS ─────────────────────────────────────────────────────────────
  const campaigns = [
    {
      id: 'cmp01',
      name: 'Frühlingsmenü 2026',
      subject: 'Spargel, Erdbeeren & ein neuer Wein für Sie 🌿',
      preview: 'Unser Frühlingsmenü startet am 12. April — sichern Sie Ihren Tisch.',
      segment: 'sg-all',
      status: 'sent',
      sentAt: daysAgo(14),
      scheduled: null,
      sent: 1184,
      delivered: 1167,
      opened: 489,
      clicked: 142,
      unsub: 6,
      bounced: 17,
      revenue: 2840,
      template: 'newsletter-image',
      author: 'Paul Wagner',
    },
    {
      id: 'cmp02',
      name: 'Weinabend Mai',
      subject: 'Exklusiv für Sie: Weinabend mit dem Winzer',
      preview: 'Begrenzte Plätze — 5-Gang-Menü mit Weinbegleitung.',
      segment: 'sg-wine',
      status: 'sent',
      sentAt: daysAgo(7),
      sent: 312,
      delivered: 308,
      opened: 187,
      clicked: 71,
      unsub: 1,
      bounced: 4,
      revenue: 4120,
      template: 'event-invite',
      author: 'Paul Wagner',
    },
    {
      id: 'cmp03',
      name: 'Muttertag-Angebot',
      subject: 'Reservieren Sie zum Muttertag — kostenlose Blume inklusive',
      preview: 'Sonntag, 11. Mai — alle Mütter erhalten eine Rose und ein Glas Prosecco.',
      segment: 'sg-all',
      status: 'scheduled',
      sentAt: null,
      scheduled: daysAhead(3),
      sent: 0, delivered: 0, opened: 0, clicked: 0, unsub: 0, bounced: 0, revenue: 0,
      template: 'newsletter-promo',
      author: 'Paul Wagner',
    },
    {
      id: 'cmp04',
      name: 'Sommerterrasse Eröffnung',
      subject: 'Die Terrasse öffnet wieder',
      preview: 'Aperitivo unter Olivenbäumen — ab 1. Juni.',
      segment: 'sg-regulars',
      status: 'draft',
      sentAt: null,
      scheduled: null,
      sent: 0, delivered: 0, opened: 0, clicked: 0, unsub: 0, bounced: 0, revenue: 0,
      template: 'newsletter-image',
      author: 'Paul Wagner',
    },
    {
      id: 'cmp05',
      name: 'Reaktivierung — wir vermissen Sie',
      subject: 'Wir vermissen Sie — 10 € Gutschein für Ihren nächsten Besuch',
      preview: 'Es ist über 90 Tage her. Kommen Sie wieder vorbei.',
      segment: 'sg-lapsed',
      status: 'sent',
      sentAt: daysAgo(28),
      sent: 142,
      delivered: 138,
      opened: 51,
      clicked: 18,
      unsub: 2,
      bounced: 4,
      revenue: 680,
      template: 'reactivation',
      author: 'Paul Wagner',
    },
  ];

  // ─── AUTOMATIONS ───────────────────────────────────────────────────────────
  const automations = [
    { id: 'auto01', name: 'Geburtstags-Mail',          trigger: 'Geburtstag = heute',                  template: 'birthday',   active: true,  sent30d: 84, openRate: 62, lastRun: hoursAgo(8) },
    { id: 'auto02', name: 'Reservierungs-Erinnerung',  trigger: '24 Stunden vor Reservierung',          template: 'res-reminder', active: true,  sent30d: 312, openRate: 78, lastRun: hoursAgo(3) },
    { id: 'auto03', name: 'Dankeschön nach Besuch',    trigger: 'Tag nach Reservierung',                template: 'thanks',     active: true,  sent30d: 287, openRate: 54, lastRun: hoursAgo(11) },
    { id: 'auto04', name: 'Reaktivierung',              trigger: '90 Tage ohne Besuch',                  template: 'reactivation', active: true,  sent30d: 18, openRate: 36, lastRun: daysAgo(2) },
    { id: 'auto05', name: 'Bestätigungs-Mail (Opt-in)', trigger: 'Newsletter-Anmeldung (Double Opt-in)', template: 'confirm',    active: true,  sent30d: 47, openRate: 89, lastRun: hoursAgo(2) },
  ];

  // ─── SOCIAL CHANNELS ───────────────────────────────────────────────────────
  const channels = [
    { id: 'ch-ig',  platform: 'instagram', handle: '@osteria.botanica', followers: 4827, growth30d: 142, connected: true,  avatar: '#E1306C' },
    { id: 'ch-fb',  platform: 'facebook',  handle: 'Osteria Botanica',  followers: 2145, growth30d:  38, connected: true,  avatar: '#1877F2' },
    { id: 'ch-gmb', platform: 'google',    handle: 'Osteria Botanica · Kempten', followers: 0, reviews: 287, rating: 4.7, growth30d: 12, connected: true, avatar: '#34A853' },
  ];

  // ─── SOCIAL POSTS ──────────────────────────────────────────────────────────
  // Mix of past (published), today (scheduled), future (scheduled), drafts
  const posts = [
    { id: 'p01', channels: ['ch-ig','ch-fb'], status: 'published', publishedAt: daysAgo(12), text: 'Frische Burrata, Ochsenherztomate, Basilikum-Öl. Ein Antipasto, das den Frühling begrüßt. 🌿', media: { type: 'image', tone: 'warm' }, likes: 287, comments: 24, shares: 12, reach: 3140 },
    { id: 'p02', channels: ['ch-ig'],          status: 'published', publishedAt: daysAgo(9),  text: 'Pasta-Tag in der Osteria. Tagliatelle, frisch ausgerollt. Heute Abend mit schwarzem Trüffel.', media: { type: 'image', tone: 'cream' }, likes: 412, comments: 38, shares: 18, reach: 4520 },
    { id: 'p03', channels: ['ch-ig','ch-fb','ch-gmb'], status: 'published', publishedAt: daysAgo(5), text: 'Unser Frühlingsmenü ist da — ab 12. April. Reservieren Sie jetzt online.', media: { type: 'image', tone: 'green' }, likes: 521, comments: 47, shares: 33, reach: 6240 },
    { id: 'p04', channels: ['ch-ig'],          status: 'published', publishedAt: daysAgo(3),  text: 'Dietro le quinte — der Pass um 19:42. Service auf Hochtouren.', media: { type: 'image', tone: 'dark' }, likes: 348, comments: 19, shares: 7, reach: 3820 },
    { id: 'p05', channels: ['ch-ig','ch-fb'], status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(0).slice(0,10) + 'T18:00:00.000Z', text: 'Aperitivo-Stunde startet jetzt. Aperol Spritz · Negroni · und ein neuer Frühlings-Spritz mit Holunder.', media: { type: 'image', tone: 'orange' } },
    { id: 'p06', channels: ['ch-ig'],          status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(1).slice(0,10) + 'T11:00:00.000Z', text: 'Ein neuer Wein in der Karte: Etna Rosso DOC 2021. Vulkanisch, mineralisch, elegant.', media: { type: 'image', tone: 'red' } },
    { id: 'p07', channels: ['ch-ig','ch-fb'], status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(2).slice(0,10) + 'T19:30:00.000Z', text: 'Weinabend mit dem Winzer — diesen Donnerstag. Letzte Plätze.', media: { type: 'image', tone: 'warm' } },
    { id: 'p08', channels: ['ch-ig','ch-fb','ch-gmb'], status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(3).slice(0,10) + 'T10:00:00.000Z', text: 'Muttertag-Sonntag. Reservieren Sie jetzt — alle Mütter erhalten eine Rose.', media: { type: 'image', tone: 'pink' } },
    { id: 'p09', channels: ['ch-ig'],          status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(5).slice(0,10) + 'T17:00:00.000Z', text: 'Pasta-Sonntag. Lasagne della casa, 6 Lagen, Ragù bolognese, 3 Stunden im Ofen.', media: { type: 'image', tone: 'cream' } },
    { id: 'p10', channels: ['ch-ig','ch-fb'], status: 'scheduled', publishedAt: null, scheduledAt: daysAhead(7).slice(0,10) + 'T12:00:00.000Z', text: 'Die Terrasse öffnet wieder. Aperitivo unter Olivenbäumen.', media: { type: 'image', tone: 'green' } },
    { id: 'p11', channels: ['ch-ig'],          status: 'draft', text: 'Neue Sommer-Pasta in Arbeit — Cacio e Pepe mit Zitrone? Was meint ihr?', media: null },
    { id: 'p12', channels: ['ch-fb'],          status: 'draft', text: 'Stellenanzeige: Wir suchen einen Sous-Chef. Vollzeit, ab Juni.', media: null },
  ];

  // ─── SOCIAL INBOX (DMs & Comments) ─────────────────────────────────────────
  const inbox = [
    { id: 'm01', channelId: 'ch-ig', kind: 'dm',      from: 'sophie_mxx',         avatar: '#E1306C', preview: 'Habt ihr am Samstag noch was um 20 Uhr für 4 Personen?', received: hoursAgo(0.5), unread: true,  thread: [
      { from: 'them', text: 'Habt ihr am Samstag noch was um 20 Uhr für 4 Personen?', at: hoursAgo(0.5) },
    ]},
    { id: 'm02', channelId: 'ch-ig', kind: 'comment', from: 'pasta_lover_99',      avatar: '#1877F2', preview: 'Diese Tagliatelle sehen umwerfend aus 😍', postId: 'p02', received: hoursAgo(2), unread: true, thread: [
      { from: 'them', text: 'Diese Tagliatelle sehen umwerfend aus 😍', at: hoursAgo(2) },
    ]},
    { id: 'm03', channelId: 'ch-fb', kind: 'dm',      from: 'Markus Wagner',       avatar: '#1877F2', preview: 'Bietet ihr auch Catering für eine Geburtstagsfeier?', received: hoursAgo(4), unread: true, thread: [
      { from: 'them', text: 'Bietet ihr auch Catering für eine Geburtstagsfeier? 30 Personen, 17. Juni.', at: hoursAgo(4) },
    ]},
    { id: 'm04', channelId: 'ch-gmb', kind: 'review',  from: 'Anna B.',             avatar: '#34A853', preview: '⭐⭐⭐⭐⭐ Bestes italienisches Restaurant in Kempten!', received: hoursAgo(8), unread: true, rating: 5, thread: [
      { from: 'them', text: 'Bestes italienisches Restaurant in Kempten! Service, Essen, Wein — alles perfekt. Wir kommen wieder.', at: hoursAgo(8) },
    ]},
    { id: 'm05', channelId: 'ch-ig', kind: 'comment', from: 'kempten_eats',        avatar: '#E1306C', preview: 'Repost? 🙏', postId: 'p03', received: hoursAgo(14), unread: false, thread: [
      { from: 'them', text: 'Repost? 🙏', at: hoursAgo(14) },
      { from: 'us',   text: 'Sehr gerne — bitte verlinken.', at: hoursAgo(13) },
    ]},
    { id: 'm06', channelId: 'ch-ig', kind: 'dm',      from: 'foodie_alpine',       avatar: '#E1306C', preview: 'Habt ihr glutenfreie Pasta?', received: hoursAgo(22), unread: false, thread: [
      { from: 'them', text: 'Habt ihr glutenfreie Pasta?', at: hoursAgo(22) },
      { from: 'us',   text: 'Ja — wir haben jeden Tag mindestens eine glutenfreie Option. Einfach Bescheid geben bei der Reservierung.', at: hoursAgo(21) },
    ]},
    { id: 'm07', channelId: 'ch-gmb', kind: 'review',  from: 'Klaus M.',            avatar: '#34A853', preview: '⭐⭐⭐⭐ Sehr gute Küche, Service etwas langsam', received: hoursAgo(38), unread: false, rating: 4, thread: [
      { from: 'them', text: 'Sehr gute Küche, Service war an dem Abend etwas langsam, aber das Essen hat gepasst.', at: hoursAgo(38) },
      { from: 'us',   text: 'Vielen Dank für das Feedback — es war ein voller Samstag. Wir freuen uns auf Ihren nächsten Besuch.', at: hoursAgo(36) },
    ]},
    { id: 'm08', channelId: 'ch-fb', kind: 'comment', from: 'Sabine R.',            avatar: '#1877F2', preview: 'Wann startet der Frühling-Brunch?', postId: 'p03', received: hoursAgo(52), unread: false, thread: [
      { from: 'them', text: 'Wann startet der Frühling-Brunch?', at: hoursAgo(52) },
    ]},
  ];

  // ─── AI TOPIC SUGGESTIONS ──────────────────────────────────────────────────
  const aiSuggestions = [
    { id: 'ai01', topic: 'Spargel-Saison',          reason: 'Saisonal, lokal — hohe Engagement-Quote bei Food-Posts', bestTime: 'Mi · 18:00', channels: ['ch-ig','ch-fb'] },
    { id: 'ai02', topic: 'Behind-the-scenes Pass',  reason: 'Pasta-Posts performen +34% besser als Durchschnitt',     bestTime: 'Fr · 19:30', channels: ['ch-ig'] },
    { id: 'ai03', topic: 'Weinwissen — Etna Rosso', reason: 'Neuer Wein in Karte, Wein-Posts haben +28% Saves',       bestTime: 'Do · 17:00', channels: ['ch-ig'] },
    { id: 'ai04', topic: 'Muttertag-Reminder',      reason: 'Sonntag in 5 Tagen, noch 14 Plätze frei',                bestTime: 'Sa · 10:00', channels: ['ch-ig','ch-fb','ch-gmb'] },
  ];

  // ─── ANALYTICS HISTORY (30 days) ───────────────────────────────────────────
  function makeAnalytics() {
    const out = [];
    let r = 7;
    const seed = () => { r = (r * 9301 + 49297) % 233280; return r / 233280; };
    for (let d = 29; d >= 0; d--) {
      const day = new Date(); day.setDate(day.getDate() - d); day.setHours(0,0,0,0);
      out.push({
        date: day.toISOString().slice(0,10),
        followersTotal: 6800 + (29-d) * 6 + Math.floor(seed() * 8),
        reach: 800 + Math.floor(seed() * 1400),
        engagement: 40 + Math.floor(seed() * 80),
        newSubs: Math.floor(seed() * 12),
        unsubs: Math.floor(seed() * 3),
      });
    }
    return out;
  }

  // ─── ATTACH TO STORE ───────────────────────────────────────────────────────
  const subscribers = makeSubscribers();
  // Compute counts for non-dynamic segments
  segments[0].count = subscribers.filter(s => s.status === 'active').length;
  segments[1].count = subscribers.filter(s => s.segments.includes('VIP') && s.status === 'active').length;
  segments[2].count = subscribers.filter(s => s.segments.includes('Regulars') && s.status === 'active').length;
  segments[5].count = subscribers.filter(s => s.segments.includes('Lapsed')).length;
  segments[6].count = subscribers.filter(s => s.segments.includes('Wine lovers')).length;
  segments[7].count = subscribers.filter(s => s.segments.includes('Event guests')).length;

  Object.assign(window.mcStore, {
    subscribers,
    segments,
    campaigns,
    automations,
    channels,
    posts,
    inbox,
    aiSuggestions,
    marketingAnalytics: makeAnalytics(),
  });

  // ─── EXTEND mcApi ──────────────────────────────────────────────────────────
  const _origGet = window.mcApi.get;
  const _origPost = window.mcApi.post;
  const _origPatch = window.mcApi.patch;
  const _origDelete = window.mcApi.delete;

  const mkRoutes = {
    'GET /subscribers':  () => mcStore.subscribers,
    'GET /segments':     () => mcStore.segments,
    'GET /campaigns':    () => mcStore.campaigns,
    'GET /automations':  () => mcStore.automations,
    'GET /channels':     () => mcStore.channels,
    'GET /posts':        () => mcStore.posts,
    'GET /inbox':        () => mcStore.inbox,
    'GET /ai-suggestions': () => mcStore.aiSuggestions,
    'GET /marketing-analytics': () => mcStore.marketingAnalytics,
    'GET /marketing-summary': () => {
      const subs = mcStore.subscribers;
      const camps = mcStore.campaigns.filter(c => c.status === 'sent');
      const totalSent = camps.reduce((a, c) => a + c.sent, 0);
      const totalOpens = camps.reduce((a, c) => a + c.opened, 0);
      const totalClicks = camps.reduce((a, c) => a + c.clicked, 0);
      const followers = mcStore.channels.reduce((a, c) => a + (c.followers || 0), 0);
      const growth = mcStore.channels.reduce((a, c) => a + (c.growth30d || 0), 0);
      return {
        subscribersActive: subs.filter(s => s.status === 'active').length,
        subscribersTotal:  subs.length,
        subscribersNew30d: subs.filter(s => new Date(s.joined) > new Date(Date.now() - 30*86400000)).length,
        openRate:  totalSent ? (totalOpens / totalSent) * 100 : 0,
        clickRate: totalSent ? (totalClicks / totalSent) * 100 : 0,
        scheduledPosts: mcStore.posts.filter(p => p.status === 'scheduled').length,
        scheduledCampaigns: mcStore.campaigns.filter(c => c.status === 'scheduled').length,
        unreadInbox: mcStore.inbox.filter(m => m.unread).length,
        followersTotal: followers,
        followersGrowth30d: growth,
        avgRating: 4.7,
        reviewsCount: 287,
      };
    },
  };

  window.mcApi.get = async function (path) {
    if (mkRoutes['GET ' + path]) {
      await new Promise(r => setTimeout(r, 80 + Math.random()*120));
      return JSON.parse(JSON.stringify(mkRoutes['GET ' + path]()));
    }
    return _origGet.call(this, path);
  };

  window.mcApi.post = async function (path, body) {
    if (path === '/subscribers') {
      const s = {
        id: 'sub' + Date.now(),
        name: body.name || (body.firstName + ' ' + (body.lastName||'')).trim(),
        firstName: body.firstName || (body.name||'').split(' ')[0],
        email: body.email,
        phone: body.phone || null,
        segments: body.segments || ['Newsletter only'],
        status: body.confirmed ? 'active' : 'pending',
        source: body.source || 'Reservierung',
        joined: new Date().toISOString(),
        lastOpen: null, opens: 0, clicks: 0,
        birthday: body.birthday || null,
        consent: { confirmed: !!body.confirmed, confirmedAt: body.confirmed ? new Date().toISOString() : null, ip: '91.64.22.14', source: body.source || 'Reservierungsformular' },
      };
      mcStore.subscribers.unshift(s);
      // Send confirmation email (simulated)
      mcStore.security.auditLog.unshift({ id: 'al'+Date.now(), at: new Date().toISOString(), actor: 'System', action: `Bestätigungs-Mail versendet an ${s.email}`, ip: '—', tone: 'info' });
      // emit
      window.mcApi.mutate(() => {});
      return s;
    }
    if (path === '/campaigns') {
      const c = { id: 'cmp'+Date.now(), status: 'draft', sent:0, delivered:0, opened:0, clicked:0, unsub:0, bounced:0, revenue:0, sentAt:null, scheduled:null, ...body };
      mcStore.campaigns.unshift(c);
      window.mcApi.mutate(() => {}); return c;
    }
    if (path === '/posts') {
      const p = { id: 'p'+Date.now(), status: body.status || 'draft', ...body };
      mcStore.posts.unshift(p);
      window.mcApi.mutate(() => {}); return p;
    }
    if (path.match(/^\/inbox\/[^/]+\/reply$/)) {
      const id = path.split('/')[2];
      const m = mcStore.inbox.find(x => x.id === id);
      if (m) { m.thread.push({ from: 'us', text: body.text, at: new Date().toISOString() }); m.unread = false; }
      window.mcApi.mutate(() => {}); return m;
    }
    return _origPost.call(this, path, body);
  };

  window.mcApi.patch = async function (path, body) {
    if (path.startsWith('/subscribers/')) {
      const id = path.split('/')[2];
      const s = mcStore.subscribers.find(x => x.id === id);
      if (s) Object.assign(s, body);
      window.mcApi.mutate(() => {}); return s;
    }
    if (path.startsWith('/campaigns/')) {
      const id = path.split('/')[2];
      const c = mcStore.campaigns.find(x => x.id === id);
      if (c) Object.assign(c, body);
      window.mcApi.mutate(() => {}); return c;
    }
    if (path.startsWith('/posts/')) {
      const id = path.split('/')[2];
      const p = mcStore.posts.find(x => x.id === id);
      if (p) Object.assign(p, body);
      window.mcApi.mutate(() => {}); return p;
    }
    if (path.startsWith('/automations/')) {
      const id = path.split('/')[2];
      const a = mcStore.automations.find(x => x.id === id);
      if (a) Object.assign(a, body);
      window.mcApi.mutate(() => {}); return a;
    }
    if (path.startsWith('/inbox/')) {
      const id = path.split('/')[2];
      const m = mcStore.inbox.find(x => x.id === id);
      if (m) Object.assign(m, body);
      window.mcApi.mutate(() => {}); return m;
    }
    return _origPatch.call(this, path, body);
  };

  window.mcApi.delete = async function (path) {
    if (path.startsWith('/subscribers/')) {
      const id = path.split('/')[2];
      mcStore.subscribers = mcStore.subscribers.filter(x => x.id !== id);
      window.mcApi.mutate(() => {}); return { ok: true };
    }
    if (path.startsWith('/posts/')) {
      const id = path.split('/')[2];
      mcStore.posts = mcStore.posts.filter(x => x.id !== id);
      window.mcApi.mutate(() => {}); return { ok: true };
    }
    if (path.startsWith('/campaigns/')) {
      const id = path.split('/')[2];
      mcStore.campaigns = mcStore.campaigns.filter(x => x.id !== id);
      window.mcApi.mutate(() => {}); return { ok: true };
    }
    return _origDelete.call(this, path);
  };
})();
