// Deterministic demo data for the legacy-DB layer — mirrors the real shapes.
const hash = (s) => [...String(s)].reduce((a, c) => ((a * 31 + c.charCodeAt(0)) >>> 0), 7);
const rng = (seed) => { let a = seed >>> 0; return () => { a = (a * 1664525 + 1013904223) >>> 0; return a / 4294967296; }; };

const TITLES = [
  'All-new model range pricing announced', 'Record quarter for UK deliveries',
  'Electric line-up expands with new variant', 'Partnership with national retailer confirmed',
  'Design award for flagship model', 'New apprenticeship programme launches',
  'Updated infotainment rolls out fleet-wide', 'Motorsport season preview',
  'Sustainability report published', 'Dealer network expansion continues',
  'Limited edition celebrates anniversary', 'Winter testing programme underway',
];
const COMPANY_NAMES = ['Aston Field Motors', 'Britmarine Yachts', 'Caldwell Cycles', 'Dunmore Vans', 'Everline EV', 'Fenwick Trucks'];
const MEDIA_NAMES = ['front-三quarter-hero.jpg', 'interior-dash.jpg', 'launch-film.mp4', 'press-kit.pdf', 'side-profile.jpg', 'chassis-detail.jpg', 'range-overview.pdf', 'sound-clip.mp4'];
const MODEL_NAMES = ['Aria', 'Bolt GT', 'Cascade', 'Drift S', 'Echo EV', 'Flare'];

function dateIn(r, start, days) {
  const d = new Date(start + 'T00:00:00Z');
  d.setUTCDate(d.getUTCDate() + Math.floor(r() * days));
  return d.toISOString().slice(0, 10);
}

export function demoLegacyOverview(site, kind, startDate, endDate, companyId = null) {
  const seed = hash(site.id + startDate + (companyId || ''));
  const r = rng(seed);
  const days = Math.max(1, Math.round((new Date(endDate) - new Date(startDate)) / 86400000));
  const companies = kind === 'newspress'
    ? COMPANY_NAMES.map((name, i) => ({ id: i + 1, name }))
    : null;

  const nRel = 8 + Math.floor(r() * 6);
  const releases = Array.from({ length: nRel }, (_, i) => {
    const cid = companies ? 1 + Math.floor(r() * companies.length) : null;
    const viewed = 300 + Math.floor(r() * 6000);
    return {
      id: 1000 + Math.floor(r() * 9000),
      title: TITLES[(seed + i) % TITLES.length],
      published: dateIn(r, startDate, days),
      viewed,
      downloaded: kind === 'newspress' ? Math.floor(viewed * (0.05 + r() * 0.2)) : null,
      basket: kind === 'newspress' ? Math.floor(viewed * 0.02 * r()) : null,
      companyId: cid,
      companyName: cid ? companies[cid - 1].name : null,
    };
  }).filter((x) => !companyId || x.companyId === Number(companyId))
    .sort((a, b) => b.viewed - a.viewed);

  const emails = Array.from({ length: 3 + Math.floor(r() * 3) }, (_, i) => {
    const recipients = 1500 + Math.floor(r() * 8000);
    const delivered = Math.floor(recipients * 0.97);
    const opened = Math.floor(delivered * (0.25 + r() * 0.2));
    return {
      campaignId: String(2200 + Math.floor(r() * 900)),
      title: TITLES[(seed + i + 3) % TITLES.length],
      sentDate: dateIn(r, startDate, days),
      recipients, delivered, opened,
      clicked: Math.floor(opened * (0.12 + r() * 0.15)),
      unsubscribed: Math.floor(delivered * 0.002 * r() * 4),
      bounced: recipients - delivered,
      releaseId: releases[i % Math.max(1, releases.length)]?.id || null,
      source: 'db',
    };
  }).sort((a, b) => b.sentDate.localeCompare(a.sentDate));

  const media = MEDIA_NAMES.map((name, i) => ({
    id: 500 + i,
    name: name.replace('三', ''),
    type: name.endsWith('.mp4') ? 'video' : name.endsWith('.pdf') ? 'document' : 'image',
    viewed: 200 + Math.floor(r() * 4000),
    downloaded: 50 + Math.floor(r() * 1500),
  })).sort((a, b) => b.downloaded - a.downloaded);

  const byDay = {};
  releases.forEach((rl) => { byDay[rl.published] = (byDay[rl.published] || 0) + 1; });
  const distByDay = {};
  emails.forEach((e) => { distByDay[e.sentDate] = (distByDay[e.sentDate] || 0) + 1; });
  const allDates = [...new Set([...Object.keys(byDay), ...Object.keys(distByDay)])].sort();
  const cadence = {
    days: allDates.map((date) => ({ date, published: byDay[date] || 0, distributed: distByDay[date] || 0 })),
    total: releases.length,
    prevTotal: Math.max(1, releases.length + ((seed % 7) - 3)),
    distTotal: emails.length,
    distPrev: Math.max(1, emails.length + ((seed % 5) - 2)),
  };
  const out = { kind, companies, releases, emails, media, cadence, documents: media.filter((m) => m.type === 'document') };
  out.categories = ['News', 'Product', 'Corporate', 'Events', 'Motorsport'].map((name, i) => ({
    id: i + 1, name, releases: 2 + ((seed >>> i) % 9),
  })).sort((a, b) => b.releases - a.releases);
  if (kind === 'newsroom') {
    out.models = MODEL_NAMES.map((name, i) => ({ id: i + 1, name, viewed: 500 + Math.floor(r() * 9000) }))
      .sort((a, b) => b.viewed - a.viewed);
    out.topJournalists = ['Sam Ford', 'Priya Nair', 'Tom Whitfield', 'Elena Ruiz', 'Marcus Webb'].map((name, i) => ({
      userId: i + 1, name, email: name.toLowerCase().replace(' ', '.') + '@pressdesk.io', events: 320 - i * 45 + ((seed >>> i) % 40),
    }));
    out.audienceTypes = [
      { type: 'journalist', n: 400 + (seed % 900) },
      { type: 'pr agency', n: 60 + (seed % 120) },
      { type: 'consumer', n: 1500 + (seed % 4000) },
    ];
  } else {
    out.banners = Array.from({ length: 3 }, (_, i) => ({
      id: i + 1, title: `Homepage banner — ${COMPANY_NAMES[(seed + i) % COMPANY_NAMES.length]}`,
      clicked: 40 + Math.floor(r() * 900),
    }));
    out.topJournalists = ['Sam Ford', 'Priya Nair', 'Tom Whitfield', 'Elena Ruiz', 'Marcus Webb'].map((name, i) => ({
      userId: i + 1, name, email: name.toLowerCase().replace(' ', '.') + '@pressdesk.io', events: 400 - i * 60 + ((seed >>> i) % 50),
    }));
    out.topPublications = ['The Daily Motor', 'Fleet World', 'Auto Express Weekly', 'Regional Gazette'].map((name, i) => ({
      id: i + 1, name, events: 900 - i * 180 + ((seed >>> (i + 2)) % 90),
    }));
    out.audience = {
      journalists: 800 + Math.floor(r() * 3000),
      consumers: 4000 + Math.floor(r() * 20000),
      mediaClients: 40 + Math.floor(r() * 200),
    };
  }
  return out;
}

export function demoLegacyRelease(site, kind, releaseId, startDate, endDate) {
  const seed = hash(site.id + releaseId);
  const r = rng(seed);
  const viewed = 400 + Math.floor(r() * 5000);
  return {
    id: Number(releaseId),
    title: TITLES[seed % TITLES.length],
    published: startDate,
    viewed,
    downloaded: Math.floor(viewed * (0.06 + r() * 0.2)),
    basket: Math.floor(viewed * 0.03 * r()),
    categories: ['News', kind === 'newsroom' ? 'Product' : 'Corporate'].slice(0, 1 + (seed % 2)),
    companyName: kind === 'newspress' ? COMPANY_NAMES[seed % COMPANY_NAMES.length] : null,
    countries: [
      { country: 'United Kingdom', events: Math.floor(viewed * 0.6) },
      { country: 'United States', events: Math.floor(viewed * 0.15) },
      { country: 'Germany', events: Math.floor(viewed * 0.08) },
    ],
    emails: [{
      campaignId: String(2200 + (seed % 900)), title: TITLES[(seed + 2) % TITLES.length],
      sentDate: startDate, recipients: 4200 + (seed % 3000),
      opened: 1400 + (seed % 900), clicked: 260 + (seed % 200), source: 'db', dedicated: true,
    }],
    readers: ['Sam Ford', 'Priya Nair', 'Tom Whitfield', 'Elena Ruiz'].map((name, i) => ({
      userId: i + 1, name, email: name.toLowerCase().replace(' ', '.') + '@pressdesk.io', type: 3,
      views: 9 - i * 2, downloads: Math.max(0, 3 - i), lastSeen: startDate,
    })),
    assets: [
      { id: 501, name: 'front-quarter-hero.jpg', type: 'image', viewed: 900 + (seed % 500), downloaded: 300 + (seed % 200), variants: 3 },
      { id: 503, name: 'press-kit.pdf', type: 'document', viewed: 200 + (seed % 100), downloaded: 120 + (seed % 90), variants: 1 },
    ],
    dailyEvents: Array.from({ length: 7 }, (_, i) => {
      const d = new Date(startDate + 'T00:00:00Z'); d.setUTCDate(d.getUTCDate() + i);
      return { date: d.toISOString().slice(0, 10), events: Math.max(2, Math.floor(viewed * 0.3 * Math.exp(-i / 2) / 10)) };
    }),
  };
}
