// scripture-engine.jsx
// Shared logic for the "What's on your heart?" widget.
// Calls window.claude.complete and returns { response, verses }
// where each verse has translations for NKJV, NIV, TPT.
//
// Exports to window: callScripture, sampleScripture, useScripture.

const SAMPLE_RESPONSE = {
  response: "That's a heavy thing to carry — and you're not carrying it alone. Here's what Heaven's been saying.",
  verses: [
    {
      reference: "Psalm 34:18",
      translations: {
        NKJV: "The Lord is near to those who have a broken heart, and saves such as have a contrite spirit.",
        NIV: "The Lord is close to the brokenhearted and saves those who are crushed in spirit.",
        TPT: "The Lord is close to those who are discouraged; he saves those who are crushed in spirit."
      }
    },
    {
      reference: "Zephaniah 3:17",
      translations: {
        NKJV: "The Lord your God in your midst, the Mighty One, will save; He will rejoice over you with gladness, He will quiet you with His love, He will rejoice over you with singing.",
        NIV: "The Lord your God is with you, the Mighty Warrior who saves. He will take great delight in you; in his love he will no longer rebuke you, but will rejoice over you with singing.",
        TPT: "For the Mighty One is right here among you, and he is your champion. He will rejoice over you with happy songs of joy, for his love for you takes away your fear."
      }
    },
    {
      reference: "Isaiah 41:10",
      translations: {
        NKJV: "Fear not, for I am with you; be not dismayed, for I am your God. I will strengthen you, yes, I will help you, I will uphold you with My righteous right hand.",
        NIV: "So do not fear, for I am with you; do not be dismayed, for I am your God. I will strengthen you and help you; I will uphold you with my righteous right hand.",
        TPT: "Do not yield to fear, for I am always near. Never turn your gaze from me, for I am your faithful God. I will infuse you with my strength and help you in every situation."
      }
    }
  ]
};

async function callScripture(input, opts = {}) {
  const useReal = opts.useReal !== false;

  if (!useReal) {
    // Simulate network delay so the UI animation still feels real.
    await new Promise(r => setTimeout(r, 900));
    return SAMPLE_RESPONSE;
  }

  const prompt = `Someone just shared this with you: "${input.replace(/"/g, '\\"')}"

You're responding as a warm, plainspoken friend grounded in the Christian faith — the kind of person who would sit on the kitchen floor with someone and not flinch at hard feelings. No religious jargon. No platitudes. Real.

Return ONLY valid JSON (no markdown, no code fences, no commentary) in this EXACT shape:

{
  "response": "1-2 sentences acknowledging what they shared — warm, grounded, never preachy. Talk like a friend.",
  "verses": [
    {
      "reference": "Book Chapter:Verse",
      "translations": {
        "NKJV": "verse text in NKJV",
        "NIV": "verse text in NIV",
        "TPT": "verse text in TPT (The Passion Translation)"
      }
    },
    {
      "reference": "Book Chapter:Verse",
      "translations": {"NKJV": "...", "NIV": "...", "TPT": "..."}
    },
    {
      "reference": "Book Chapter:Verse",
      "translations": {"NKJV": "...", "NIV": "...", "TPT": "..."}
    }
  ]
}

Pick 3 verses that genuinely speak to what they shared — God's nearness, identity, healing, courage, intimacy with the Trinity. Quote accurately.`;

  const raw = await window.claude.complete(prompt);
  // Strip any accidental code fencing or whitespace.
  const cleaned = raw
    .replace(/^[\s\S]*?(\{[\s\S]*\})[\s\S]*$/, '$1')
    .trim();
  let parsed;
  try {
    parsed = JSON.parse(cleaned);
  } catch (e) {
    console.error('Failed to parse scripture response:', raw);
    throw new Error("We couldn't quite hear that. Try again?");
  }
  if (!parsed.verses || !Array.isArray(parsed.verses)) {
    throw new Error("Got an unexpected response. Try again?");
  }
  return parsed;
}

// React hook: useScripture(useReal) → { state, ask, reset }
// state: { phase: 'idle'|'thinking'|'ready'|'error', data, error }
function useScripture(useReal = true) {
  const [state, setState] = React.useState({ phase: 'idle', data: null, error: null });

  const ask = React.useCallback(async (input) => {
    if (!input || !input.trim()) return;
    setState({ phase: 'thinking', data: null, error: null });
    try {
      const data = await callScripture(input, { useReal });
      setState({ phase: 'ready', data, error: null });
    } catch (e) {
      setState({ phase: 'error', data: null, error: e.message || 'Something went quiet.' });
    }
  }, [useReal]);

  const reset = React.useCallback(() => {
    setState({ phase: 'idle', data: null, error: null });
  }, []);

  return { state, ask, reset };
}

Object.assign(window, {
  callScripture,
  sampleScripture: SAMPLE_RESPONSE,
  useScripture
});
