// Mock data for Kidden Studio prototype
const supabase = window.supabase.createClient(CONFIG.SUPABASE_URL, CONFIG.SUPABASE_KEY);

const CATEGORIES = [
  { id: 'screen_time',    label: 'Screen time' },
  { id: 'safety',         label: 'Safety' },
  { id: 'first_phone',    label: 'First phone' },
  { id: 'social_media',   label: 'Social media' },
  { id: 'age_guides',     label: 'Age guides' },
  { id: 'parenting_tips', label: 'Parenting tips' },
  { id: 'health_dev',     label: 'Health & dev' },
  { id: 'behavior',       label: 'Behavior changes' },
];

const STATUSES = [
  { id: 'new',         label: 'New' },
  { id: 'draft',       label: 'Draft' },
  { id: 'reviewed',    label: 'Reviewed' },
  { id: 'images_done', label: 'Images done' },
  { id: 'ready',       label: 'Ready' },
  { id: 'in_prod',     label: 'In prod' },
];

const STATUS_ORDER = ['ready', 'images_done', 'reviewed', 'draft', 'new', 'in_prod'];

const CAT_BG_PALETTE = {
  screen_time:    'bg-soft-coral',
  safety:         'bg-soft-pink',
  first_phone:    'bg-soft-sage',
  social_media:   'bg-soft-lav',
  age_guides:     'bg-soft-yellow',
  parenting_tips: 'bg-soft-blue',
  health_dev:     'bg-soft-peach',
  behavior:       'bg-soft-teal',
};
const CAT_BLOB_PALETTE = {
  screen_time:    'blob-coral',
  safety:         'blob-pink',
  first_phone:    'blob-sage',
  social_media:   'blob-lav',
  age_guides:     'blob-yellow',
  parenting_tips: 'blob-blue',
  health_dev:     'blob-peach',
  behavior:       'blob-teal',
};

const KIDDEN_FEATURES = [
  "Kidden's screen time schedules",
  "Kidden's app blocking",
  "Kidden's website filtering",
  "Kidden's activity reports",
  "Kidden's app install alerts",
];

async function fetchArticles() {
  const { data, error } = await supabase
    .from('articles')
    .select('*, steps(*)')
    .order('creative_count', { ascending: false });
  if (error) throw error;
  return (data || []).map(a => ({
    ...a,
    steps: (a.steps || [])
      .sort((x, y) => x.step_number - y.step_number)
      .map(s => ({
        title: s.title || '',
        body: s.body || '',
        image_prompt: s.image_prompt || '',
        image: !!s.image_url,
      })),
  }));
}

// Article seed (12 articles spanning every status, mirroring creative spreadsheet topics)
const SEED_ARTICLES = [
  {
    id: 'article-01', slug: 'article-01',
    title: 'Screen time: how much is too much?',
    category: 'screen_time', reading_time: '3 min',
    creative_count: 408, status: 'ready',
    updated_at: '2h ago',
    thumbnail_prompt: 'A square illustration with a soft sage green gradient background. A child reading a book on a windowsill while a tablet rests face-down on the floor. Simplified figures, round heads, minimal facial detail, casual clothes. Calm, warm mood.',
    thumbnail_image: true,
    steps: [
      { title: 'The numbers', body: 'Kids aged 8 to 12 average about 5 hours of screen time a day, not counting school. Teens average 7 to 8. The number alone is not the issue — what those hours replace is.', image: true },
      { title: 'Sleep is the first to go', body: 'Each extra hour of evening screen time pushes bedtime later by roughly 15 minutes. Less sleep affects mood, attention, and growth long before parents notice the link.', image: true },
      { title: 'Replace, do not subtract', body: 'Cutting screen time without an alternative tends to fail. Pair every limit with a clear next activity: dinner, a walk, a project. The brain needs somewhere to land.', image: true },
      { title: 'Weekdays vs weekends', body: 'Hard daily limits can feel arbitrary on a Saturday morning. Set tighter limits on school nights and looser ones on weekends — the routine matters more than the total.', image: true },
      { title: 'What healthy use looks like', body: 'Healthy screen use is active and finite: a video lesson, a video call with grandparents, a finished episode. The same hour spent scrolling has a very different effect.', image: true },
      { title: 'Set it once, let it run', body: "Kidden's screen time schedules let you create custom limits for school days and weekends in a few taps. Activity reports show which apps eat up the most time, so the limits you set match what your child actually does.", image: true },
    ],
  },
  {
    id: 'article-06', slug: 'article-06',
    title: 'When to give your kid their first phone',
    category: 'first_phone', reading_time: '3 min',
    creative_count: 371, status: 'ready',
    updated_at: '3 days ago',
    thumbnail_prompt: 'Square illustration. A parent handing a phone to a child at a kitchen table. Soft warm coral gradient. Round heads, simplified faces.',
    thumbnail_image: true,
    steps: [
      { title: 'There is no magic age', body: 'The right age depends less on a number and more on routine. Does your child walk home alone, take a bus, or stay after school? Those moments are when a phone earns its place.', image: true },
      { title: 'Maturity over age', body: 'Two 10-year-olds can be very different. Watch how your child handles a tablet, follows rules around tech, and tells you when something feels off online. That is the real signal.', image: true },
      { title: 'Start with less, not more', body: "A first phone does not need to be a full smartphone. A basic device that calls and texts covers most actual needs and skips the social-media problem entirely for another year or two.", image: true },
      { title: 'Set the rules before the box opens', body: 'Agree on charging location, bedtime hand-in, app installs, and what happens if the rules slip. Writing it down avoids the negotiation that always follows day one.', image: true },
      { title: 'Expect to revisit it', body: "First-phone rules age fast. Plan a check-in at three months and again at six. Adjust based on how your child is actually using the phone, not on what you imagined they would.", image: true },
      { title: 'Make the first month easy to manage', body: "Kidden's app install alerts and website filtering give you a soft layer of guardrails for the first weeks — you can see what is being added and step in early without taking the phone away.", image: true },
    ],
  },
  {
    id: 'article-12', slug: 'article-12',
    title: 'Cyberbullying: signs your child is hiding it',
    category: 'safety', reading_time: '2 min',
    creative_count: 107, status: 'ready',
    updated_at: '5 days ago',
    thumbnail_prompt: 'Square illustration. A child sitting on a bedroom floor with knees up, looking at a phone. Soft blue gradient background. Quiet, thoughtful mood.',
    thumbnail_image: true,
    steps: [
      { title: 'Most kids do not tell', body: 'Roughly 1 in 3 children experiences online bullying, and most never bring it up. The shame and the fear of losing the phone usually outweigh the wish to be helped.', image: true },
      { title: 'Behavior changes first', body: 'Watch for sudden quiet after picking up the phone, dropped friendships, or skipping activities they used to like. The signal often shows up in mood before it shows up in words.', image: true },
      { title: 'Sleep, school, food', body: 'Bullying interferes with sleep within days. A child who suddenly wants to skip school, eats less, or wakes at 3 a.m. checking the phone is telling you something is going on.', image: true },
      { title: 'Open the door, do not pry', body: 'Asking "is someone bothering you online" rarely works. Asking "what is the most annoying thing your friends do in chats" does. Make space for the topic without naming it.', image: true },
      { title: 'Save before you delete', body: 'If your child shows you a message, screenshot it before anything is deleted. Most schools and platforms can act on the messages, but only if they exist.', image: true },
      { title: 'See the patterns early', body: "Kidden's activity reports show which apps your child is on most and when — useful when you are trying to spot a sudden spike in late-night messaging without reading every chat.", image: true },
    ],
  },
  {
    id: 'article-17', slug: 'article-17',
    title: 'Sextortion: what every parent should know',
    category: 'safety', reading_time: '2 min',
    creative_count: 371, status: 'images_done',
    updated_at: '5h ago',
    thumbnail_prompt: 'Square illustration. A teenage figure looking at a phone in a darkened room with a soft lamp. Muted blue and warm coral palette. Calm but serious mood.',
    thumbnail_image: true,
    steps: [
      { title: 'It is faster than parents think', body: 'Sextortion attempts often move from first message to demand within an hour. The scammer does not need a long relationship — they need one image and a panicked teen.', image: true },
      { title: 'Boys are the main target', body: 'Most reported cases involve boys 14 to 17. Scammers pose as girls of similar age, build rapport for a few minutes, then ask for an image and switch to threats immediately.', image: true },
      { title: 'The script is the same', body: '"I have your contacts. Send money or this goes to your school." The wording barely changes. Recognising the script makes it easier to help your child see it as a scam, not a personal failure.', image: true },
      { title: 'No payment, no panic', body: 'Paying does not make the threat stop — it confirms the target. Stop responding, save the messages, block, and report. Most platforms remove the account within a day.', image: true },
      { title: 'Talk before it happens', body: 'Tell your child clearly: if a stranger ever asks for an image, the answer is no, and if they slip up, you will not be angry. Knowing they will not lose the phone is what makes them tell you.', image: true },
      { title: 'Catch new contacts early', body: "Kidden's app install alerts and activity reports help you spot when a new chat app appears or a contact starts taking up unusual time, so a problem rarely sits hidden for weeks.", image: true },
    ],
  },
  {
    id: 'article-23', slug: 'article-23',
    title: 'The IQ question: do screens really hurt?',
    category: 'health_dev', reading_time: '2 min',
    creative_count: 86, status: 'draft',
    updated_at: '4h ago',
    thumbnail_prompt: 'Square illustration. A young child holding a tablet, soft glow on face. Lavender gradient background, simplified rounded figure.',
    thumbnail_image: false,
    steps: [
      { title: 'What the research actually says', body: 'Studies link heavy screen use under age 5 with small but real drops in language and attention scores. The effect is real, but it is not large, and it depends heavily on what the screen is replacing.', image: false },
      { title: 'Passive vs active matters', body: 'A child watching short videos passively for an hour shows different outcomes than one on a video call with a grandparent for the same hour. The format of the screen time changes the effect.', image: true },
      { title: 'The first three years', body: 'Brain development is fastest from 0 to 3. This is the window where face-to-face talking, eye contact, and physical play do the most. Screens during this window have the highest cost.', image: true },
      { title: 'School-age is different', body: 'After age 6, well-chosen screen time has little measurable effect on cognition. The risks shift from development to behavior — sleep, attention, and habits — not raw IQ.', image: false },
      { title: 'What to actually do', body: 'Under 2: avoid solo screen use. 2 to 5: short, co-watched, age-matched. 6 and up: focus on routine and content quality. The numbers matter less than the pattern.', image: false },
      { title: 'Make age-appropriate easy', body: "Kidden lets you set different daily limits and bedtimes for each child, so a 4-year-old and a 10-year-old in the same family do not end up with the same screen rules.", image: false },
    ],
  },
  {
    id: 'article-34', slug: 'article-34',
    title: 'How the algorithm feeds your teen',
    category: 'social_media', reading_time: '2 min',
    creative_count: 142, status: 'draft',
    updated_at: '1h ago',
    thumbnail_prompt: 'Square illustration. A teenager scrolling on a phone, with abstract feed cards floating beside them. Soft lavender and peach gradient.',
    thumbnail_image: false,
    steps: [
      { title: 'The feed is a model of your teen', body: 'Every pause, like, and re-watch is data. Within a few sessions the algorithm has a sharper read on what holds your teen\'s attention than most adults in their life do.', image: false },
      { title: 'Outrage and sadness travel fastest', body: 'Strong emotion is the cheapest engagement. Posts that scare, shock, or upset reliably get more screen time, so the system surfaces more of them — even when no one chose that.', image: false },
      { title: 'The rabbit hole is not random', body: 'Watch one workout video and you get fitness for a week. Watch one weight-loss video and you get an entire genre. The pattern is mechanical, not malicious — but the effect on a teen is the same.', image: false },
      { title: 'Reset what is possible', body: 'Most apps let your teen mark "not interested" on suggested posts and clear watch history. Doing this once a month is the cheapest way to break a topic loop they want out of.', image: false },
      { title: 'Talk about the why, not the what', body: 'Asking what they are watching usually shuts the conversation down. Asking why a video kept their attention is more interesting and tells you more.', image: false },
      { title: 'Set the boundary at the door', body: "Kidden's app blocking and schedules let you keep social apps off during school hours and after a certain time at night, which is when most algorithm-driven binges happen.", image: false },
    ],
  },
  {
    id: 'article-10', slug: 'article-10',
    title: 'ADHD or just too much YouTube?',
    category: 'health_dev', reading_time: '3 min',
    creative_count: 98, status: 'images_done',
    updated_at: '6h ago',
    thumbnail_prompt: 'Square illustration. A child sitting cross-legged surrounded by stacks of toys and an open book, looking at a tablet. Sage green gradient.',
    thumbnail_image: true,
    steps: [
      { title: 'They look similar from the outside', body: "Trouble starting tasks, restless behaviour, lost focus — these can come from ADHD, from heavy short-form video use, or from both. The two conditions are not the same, but they often look the same at home.", image: true },
      { title: 'What screens reinforce', body: 'Short videos train the brain to expect a reward every 15 to 30 seconds. After hours of that, a 20-minute homework problem feels physically uncomfortable, even for a neurotypical child.', image: true },
      { title: 'Try a content reset first', body: 'Two weeks with no short-form video, replaced by long-form (films, full episodes, books). If focus visibly improves, the problem was largely habit. If it does not, that is useful information for a doctor.', image: true },
      { title: 'When to seek a real assessment', body: 'If trouble focusing shows up across school, home, and friendships — and persists after a content reset — talk to a pediatrician or psychologist. Self-diagnosis from videos is rarely accurate.', image: true },
      { title: 'What helps both', body: 'Tight sleep windows, predictable routines, screen-free meals, and active breaks help children with and without ADHD. None of these require a diagnosis to start.', image: true },
      { title: 'Notice the patterns', body: "Kidden's activity reports show daily and weekly patterns of app use. Spotting the days a binge starts is the easiest way to tie behaviour at home back to what is happening on the phone.", image: true },
    ],
  },
  {
    id: 'article-07', slug: 'article-07',
    title: "Setting up a kid's phone safely",
    category: 'first_phone', reading_time: '2 min',
    creative_count: 74, status: 'reviewed',
    updated_at: 'May 4',
    thumbnail_prompt: 'Square illustration. A parent and child sitting side by side, both holding phones. Warm peach gradient background.',
    thumbnail_image: false,
    steps: [
      { title: 'Start with the OS, not the apps', body: "Apple's Screen Time and Android's Family Link are the floor. Set them up before any app is installed — they cover purchases, app installs, and rough time limits without extra software.", image: false },
      { title: 'Pick the apps together', body: 'Sit down once and decide which apps go on the phone. Anything not on the list needs a conversation, not a silent install. This single rule prevents most problems.', image: false },
      { title: 'Lock the store, not the phone', body: 'Most issues come from new app installs, not the apps you already approved. Disabling installs without a parent password is a much smaller intrusion than locking the whole device.', image: false },
      { title: 'Charge outside the bedroom', body: 'A phone in the bedroom at night is a phone in use at night. A simple "charges in the kitchen after 9" rule beats most software at protecting sleep.', image: false },
      { title: 'Review weekly, not daily', body: 'Daily checks feel like surveillance. A weekly five-minute look at activity reports together teaches your child what you watch for and gives them a chance to explain anything odd.', image: false },
      { title: 'Layer Kidden on top', body: "Kidden adds the layer the OS does not: app blocking by schedule, website filtering, and detailed activity reports. Use it as the everyday tool, with the OS settings as the floor underneath.", image: false },
    ],
  },
  {
    id: 'article-11', slug: 'article-11',
    title: "Speech delay isn't always autism",
    category: 'health_dev', reading_time: '2 min',
    creative_count: 261, status: 'reviewed',
    updated_at: 'yesterday',
    thumbnail_prompt: 'Square illustration. A toddler stacking blocks while a parent watches. Soft yellow gradient. Calm, attentive mood.',
    thumbnail_image: false,
    steps: [],
  },
  {
    id: 'article-28', slug: 'article-28',
    title: 'Solo parenting and digital limits',
    category: 'parenting_tips', reading_time: '2 min',
    creative_count: 39, status: 'draft',
    updated_at: '8h ago',
    thumbnail_prompt: 'Square illustration. A single parent sitting at a kitchen table with a child eating dinner, phone face-down on the counter. Soft blue gradient.',
    thumbnail_image: false,
    steps: [],
  },
  {
    id: 'article-22', slug: 'article-22',
    title: 'Brain development under 6: what changes',
    category: 'health_dev', reading_time: '2 min',
    creative_count: 30, status: 'new',
    updated_at: 'Apr 28',
    thumbnail_prompt: '',
    thumbnail_image: false,
    steps: [],
  },
  {
    id: 'article-15', slug: 'article-15',
    title: 'Mood swings vs screen withdrawal',
    category: 'behavior', reading_time: '2 min',
    creative_count: 24, status: 'new',
    updated_at: 'Apr 27',
    thumbnail_prompt: '',
    thumbnail_image: false,
    steps: [],
  },
  {
    id: 'article-26', slug: 'article-26',
    title: 'Aggressive kids and screen addiction',
    category: 'behavior', reading_time: '2 min',
    creative_count: 107, status: 'in_prod',
    updated_at: 'May 2',
    thumbnail_prompt: 'Square illustration. A child mid-tantrum, parent crouching at eye level. Soft teal gradient.',
    thumbnail_image: true,
    steps: [],
  },
  {
    id: 'article-31', slug: 'article-31',
    title: 'Should I let my 12-year-old on TikTok?',
    category: 'social_media', reading_time: '3 min',
    creative_count: 88, status: 'new',
    updated_at: 'Apr 26',
    thumbnail_prompt: '',
    thumbnail_image: false,
    steps: [],
  },
  {
    id: 'article-04', slug: 'article-04',
    title: 'Bedtime fights: the screen-time edition',
    category: 'screen_time', reading_time: '2 min',
    creative_count: 64, status: 'new',
    updated_at: 'Apr 25',
    thumbnail_prompt: '',
    thumbnail_image: false,
    steps: [],
  },
];

// Pre-fill missing steps with empty placeholders to make the data uniform
SEED_ARTICLES.forEach(a => {
  if (a.status === 'new' && a.steps.length === 0) {
    a.steps = [];
  } else {
    while (a.steps.length < 6) {
      a.steps.push({ title: '', body: '', image: false });
    }
    // Ensure step 6 references a Kidden feature (already curated for ready/draft articles)
  }
  // attach image_prompt strings (deterministic placeholders)
  a.steps = a.steps.map((s, i) => ({
    title: s.title || '',
    body: s.body || '',
    image: !!s.image,
    image_prompt: s.title
      ? `A landscape illustration in soft ${['sage','coral','blue','lavender','peach','teal'][i % 6]} tones. ${s.title}. Simplified human figures with round heads, minimal facial detail. Calm, warm mood. No text, no UI elements.`
      : '',
  }));
});

window.KS_DATA = {
  CATEGORIES, STATUSES, STATUS_ORDER,
  CAT_BG_PALETTE, CAT_BLOB_PALETTE,
  KIDDEN_FEATURES,
  SEED_ARTICLES,
  fetchArticles,
  supabase,
};
