// WOD generation logic
// Calls the Cloudflare Worker proxy — the OpenAI key lives there, not here.

// Local dev: wrangler dev → http://localhost:8787
// Production: deployed Cloudflare Worker URL
const WORKER_URL = 'https://snatch-coach.henryfan1104.workers.dev/';

async function callCoach(messages) {
  const res = await fetch(WORKER_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      messages: messages.map(m => ({
        role: m.role,
        content: m.content || '',
      })),
    }),
  });

  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error?.message || `Worker error ${res.status}`);
  }

  const data = await res.json();
  return data.choices[0].message.content;
}

function parseWodResponse(text) {
  // Try standard fenced code block first
  const fenced = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
  if (fenced) {
    try {
      const wod = JSON.parse(fenced[1]);
      const intro = text.slice(0, fenced.index).trim();
      const outro = text.slice(fenced.index + fenced[0].length).trim();
      return { intro, wod, outro };
    } catch {}
  }

  // Fallback: find the first { ... } JSON object in the text
  const start = text.indexOf('{');
  const end = text.lastIndexOf('}');
  if (start !== -1 && end !== -1 && end > start) {
    try {
      const wod = JSON.parse(text.slice(start, end + 1));
      const intro = text.slice(0, start).trim();
      const outro = text.slice(end + 1).trim();
      return { intro, wod, outro };
    } catch {}
  }

  return { intro: text.trim(), wod: null };
}

const SAMPLE_WODS = [
  {
    title: "THE GRINDER",
    subtitle: "Full-body conditioning",
    duration: "32 MIN",
    intensity: "HARD",
    focus: "Conditioning",
    equipment: "None",
    blocks: [
      { label: "WARMUP", time: "5 MIN", items: [
        { name: "Jumping jacks", reps: "60s" },
        { name: "World's greatest stretch", reps: "5/side" },
        { name: "Arm circles", reps: "30s each way" }
      ]},
      { label: "MAIN", time: "22 MIN", note: "AMRAP — as many rounds as possible", items: [
        { name: "Burpees", reps: "10" },
        { name: "Air squats", reps: "20" },
        { name: "Push-ups", reps: "15" },
        { name: "Mountain climbers", reps: "30" }
      ]},
      { label: "FINISHER", time: "3 MIN", items: [
        { name: "Plank", reps: "60s" },
        { name: "Hollow hold", reps: "30s" }
      ]},
      { label: "COOLDOWN", time: "2 MIN", items: [
        { name: "Pigeon pose", reps: "60s/side" },
        { name: "Forward fold", reps: "45s" }
      ]}
    ],
    closer: "Lock in. You've got this."
  }
];

window.WODLib = { callCoach, parseWodResponse, SAMPLE_WODS };
