const { useState, useRef, useEffect } = React;

// ═══════════════════════════════════════════════════════════════════
//  API KEYS — paste your keys here when running in browser/artifact
//  On vozdomeu.com.br these are stored safely in the server .env
// ═══════════════════════════════════════════════════════════════════
// Keys are ONLY used in browser/artifact mode (non-production).
// On vozdomeu.com.br all calls go through the PHP proxy — no keys needed client-side.
const ANTHROPIC_KEY  = "PASTE_ANTHROPIC_KEY_HERE";
const ELEVENLABS_KEY = "PASTE_ELEVENLABS_KEY_HERE";
const DID_KEY        = "PASTE_DID_KEY_HERE";

// Detect environment — use Flask proxy on production, direct API in browser
const IS_PRODUCTION = typeof window !== "undefined" &&
  (window.location.hostname === "vozdomeu.com.br" ||
   window.location.hostname === "www.vozdomeu.com.br" ||
   window.location.hostname === "localhost");

const API_BASE = IS_PRODUCTION ? "/api" : null;

// ═══════════════════════════════════════════════════════════════════
//  ELEVENLABS VOICE LIBRARY — loaded dynamically from your account
// ═══════════════════════════════════════════════════════════════════
const VOICE_LIBRARY = [
  { id:"pNInz6obpgDQGcFmaJgB", name:"Adam",    desc:"Grave e sereno",      gender:"M" },
  { id:"ErXwobaYiN019PkySvjV", name:"Antoni",  desc:"Suave e carinhoso",   gender:"M" },
  { id:"VR6AewLTigWG4xSOukaG", name:"Arnold",  desc:"Forte e marcante",    gender:"M" },
  { id:"TxGEqnHWrfWFTfGW9XjX", name:"Josh",    desc:"Jovem e acolhedor",   gender:"M" },
  { id:"21m00Tcm4TlvDq8ikWAM", name:"Rachel",  desc:"Suave e maternal",    gender:"F" },
  { id:"AZnzlk1XvdvUeBnXmlld", name:"Domi",    desc:"Firme e presente",    gender:"F" },
  { id:"EXAVITQu4vr4xnSDxMaL", name:"Bella",   desc:"Doce e amorosa",      gender:"F" },
  { id:"MF3mGyEYCl7XYWbV9V6O", name:"Elli",    desc:"Alegre e animada",    gender:"F" },
];

// Fetch real voices from ElevenLabs account
async function fetchElevenLabsVoices() {
  try {
    if (API_BASE) {
      // Production — use Flask proxy
      const r = await fetch(`${API_BASE}/voices`);
      if (!r.ok) return VOICE_LIBRARY;
      const d = await r.json();
      if (!d.voices?.length) return VOICE_LIBRARY;
      return d.voices.map(v=>({
        id: v.voice_id, name: v.name,
        desc: v.labels?.description || v.labels?.accent || v.category || "",
        gender: v.labels?.gender==="female" ? "F" : "M",
      }));
    } else {
      // Browser — direct call (may fail with CORS)
      if (!ELEVENLABS_KEY || ELEVENLABS_KEY.includes("PASTE")) return VOICE_LIBRARY;
      const r = await fetch("https://api.elevenlabs.io/v1/voices", {
        headers:{"xi-api-key":ELEVENLABS_KEY},
      });
      if (!r.ok) return VOICE_LIBRARY;
      const d = await r.json();
      if (!d.voices?.length) return VOICE_LIBRARY;
      return d.voices.map(v=>({
        id: v.voice_id, name: v.name,
        desc: v.labels?.description || v.labels?.accent || v.category || "",
        gender: v.labels?.gender==="female" ? "F" : "M",
      }));
    }
  } catch { return VOICE_LIBRARY; }
}

// ═══════════════════════════════════════════════════════════════════
//  DATA
// ═══════════════════════════════════════════════════════════════════
const NAV = [
  { id:"home",     emoji:"🕯️", label:"Início" },
  { id:"memorial", emoji:"💫", label:"Memorial" },
  { id:"prece",    emoji:"🙏", label:"Prece" },
  { id:"oracao",   emoji:"✝️",  label:"Oração" },
  { id:"oracles",  emoji:"🔮", label:"Oráculos" },
];

const STAR_DATA = Array.from({length:60},(_,i)=>({
  id:i, x:Math.random()*100, y:Math.random()*100,
  r:Math.random()*1.2+0.3, delay:Math.random()*6, dur:3+Math.random()*4,
}));

const INTENTIONS = [
  {id:"passe",      emoji:"🤲", label:"Passe Espiritual"},
  {id:"desencarne", emoji:"🕯️", label:"Ente Desencarnado"},
  {id:"reforma",    emoji:"🌱", label:"Reforma Íntima"},
  {id:"saude",      emoji:"✨", label:"Cura e Saúde"},
  {id:"familia",    emoji:"👨‍👩‍👧", label:"Harmonia Familiar"},
  {id:"gratidao",   emoji:"🙏", label:"Gratidão"},
  {id:"mediunidade",emoji:"🔮", label:"Mediunidade"},
  {id:"luz",        emoji:"💫", label:"Luz para Espíritos"},
];

const ORACLE_SERVICES = [
  {id:"prayer",    emoji:"🙏", label:"Prece Personalizada",  cost:5,  burn:0.05, desc:"Prece Kardecista com doutrina embarcada"},
  {id:"memorial",  emoji:"💫", label:"Memorial Completo",    cost:10, burn:0.10, desc:"Prece + mensagem canalizada"},
  {id:"counsel",   emoji:"💬", label:"Orientação Espiritual", cost:2, burn:0.02, desc:"Sessão com orientador erudito"},
  {id:"voice",     emoji:"🎙️", label:"Voz do Meu",           cost:25, burn:0.25, desc:"Voz clonada + vídeo animado"},
  {id:"evangelho", emoji:"📖", label:"Evangelho no Lar",      cost:15, burn:0.15, desc:"Assinatura mensal semanal"},
  {id:"batch",     emoji:"⚡", label:"Lote de 10 Preces",    cost:40, burn:0.40, desc:"Para centros ou integradores"},
];

// ═══════════════════════════════════════════════════════════════════
//  CRISIS DETECTION
// ═══════════════════════════════════════════════════════════════════
const CRISIS_KEYWORDS = [
  "suicid","me matar","quero morrer","não quero viver","acabar com tudo",
  "me juntar","encontrar ela","encontrar ele","encontrar minha mãe","encontrar meu pai",
  "não tem mais sentido","sem razão de viver","me jogar","tomar remédio demais",
  "me machucar","acabar com minha vida","não aguento mais","preferir morrer",
  "ir para o outro lado","ir junto","deixar esse mundo",
];

function detectCrisis(text) {
  const lower = text.toLowerCase();
  return CRISIS_KEYWORDS.some(kw => lower.includes(kw));
}

const CRISIS_RESPONSE = `Percebi que você está carregando uma dor muito grande agora. 💙

Antes de qualquer coisa — você não está sozinho(a).

O CVV (Centro de Valorização da Vida) atende 24 horas, todos os dias, de forma gratuita e sigilosa:

📞 188 (ligar)
💬 cvv.org.br (chat online)

Quem amamos nunca quer que soframos. Eles querem que continuemos aqui, com os que ainda nos amam neste plano.

Por favor, fale com alguém agora. 🙏`;


const css = `
  @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,600;1,300;1,400&family=Cinzel:wght@400;500&display=swap');
  @keyframes twinkle  { 0%,100%{opacity:0.05} 50%{opacity:0.5} }
  @keyframes flicker  { 0%,100%{opacity:1} 50%{opacity:0.6} }
  @keyframes fadeUp   { from{opacity:0;transform:translateY(16px)} to{opacity:1;transform:translateY(0)} }
  @keyframes spin     { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }
  @keyframes glow     { 0%,100%{box-shadow:0 0 20px rgba(200,150,80,0.15)} 50%{box-shadow:0 0 40px rgba(200,150,80,0.35)} }
  @keyframes revealWord { from{opacity:0;transform:translateY(3px)} to{opacity:1;transform:translateY(0)} }
  * { box-sizing:border-box; margin:0; padding:0; }
  body { background:#0a0705; }
  input,textarea,button,select { font-family:'Cormorant Garamond',Georgia,serif; }
  input::placeholder,textarea::placeholder { color:rgba(180,150,100,0.25); }
  ::-webkit-scrollbar { width:4px; }
  ::-webkit-scrollbar-track { background:transparent; }
  ::-webkit-scrollbar-thumb { background:rgba(180,140,80,0.2); border-radius:2px; }
`;

// ─── theme colors ───────────────────────────────────────────────
const C = {
  bg:      "#0a0705",
  bgCard:  "rgba(255,240,200,0.03)",
  bgCard2: "rgba(200,150,80,0.06)",
  border:  "rgba(200,150,80,0.14)",
  border2: "rgba(200,150,80,0.28)",
  gold:    "#c89640",
  goldSoft:"#e8c878",
  goldDim: "rgba(200,150,80,0.5)",
  text:    "#e8dcc8",
  textDim: "rgba(220,200,160,0.5)",
  textFaint:"rgba(200,170,120,0.35)",
  green:   "#4a9960",
  greenBg: "rgba(74,153,96,0.08)",
  greenBorder:"rgba(74,153,96,0.25)",
};

// ═══════════════════════════════════════════════════════════════════
//  API HELPERS
// ═══════════════════════════════════════════════════════════════════
async function claudeAI(system, user) {
  if (API_BASE) {
    // Production — use Flask proxy (no keys in browser)
    const r = await fetch(`${API_BASE}/claude`, {
      method:"POST",
      headers:{"Content-Type":"application/json"},
      body:JSON.stringify({system, user}),
    });
    if (!r.ok) { const e=await r.json().catch(()=>({})); throw new Error(e.error || `Erro ${r.status}: ${r.statusText}`); }
    const d = await r.json();
    const t = d?.content?.[0]?.text || d?.text;
    if (!t) throw new Error("Resposta vazia");
    return t;
  } else {
    // Browser/artifact — direct call (requires key pasted at top)
    if (!ANTHROPIC_KEY || ANTHROPIC_KEY.includes("PASTE")) {
      throw new Error("Chave Anthropic não configurada. Cole sua API key no topo do arquivo.");
    }
    const r = await fetch("https://api.anthropic.com/v1/messages", {
      method:"POST",
      headers:{
        "Content-Type":"application/json",
        "x-api-key": ANTHROPIC_KEY,
        "anthropic-version":"2023-06-01",
        "anthropic-dangerous-direct-browser-access":"true",
      },
      body:JSON.stringify({
        model:"claude-sonnet-4-6", max_tokens:1000,
        system, messages:[{role:"user",content:user}],
      }),
    });
    if (!r.ok) { const e=await r.json().catch(()=>({})); throw new Error(`Erro ${r.status}: ${e?.error?.message||r.statusText}`); }
    const d = await r.json();
    const t = d?.content?.[0]?.text;
    if (!t) throw new Error("Resposta vazia");
    return t;
  }
}

async function elevenLabsTTS(text, voiceId) {
  if (API_BASE) {
    // Production — use Flask proxy (no CORS issues)
    const r = await fetch(`${API_BASE}/tts`, {
      method:"POST",
      headers:{"Content-Type":"application/json"},
      body:JSON.stringify({text, voice_id:voiceId}),
    });
    if (!r.ok) {
      const e = await r.json().catch(()=>({}));
      throw new Error(e.error || r.statusText);
    }
    const blob = await r.blob();
    if (!blob || blob.size===0) throw new Error("Áudio vazio");
    return URL.createObjectURL(new Blob([blob],{type:"audio/mpeg"}));
  } else {
    // Browser — direct call
    if (!ELEVENLABS_KEY || ELEVENLABS_KEY.includes("PASTE")) {
      throw new Error("Chave ElevenLabs não configurada.");
    }
    const r = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
      method:"POST",
      headers:{
        "Content-Type":"application/json",
        "xi-api-key": ELEVENLABS_KEY,
        "Accept": "audio/mpeg",
      },
      body:JSON.stringify({
        text,
        model_id:"eleven_multilingual_v2",
        voice_settings:{stability:0.75,similarity_boost:0.85,style:0.3,use_speaker_boost:true},
      }),
    });
    if (!r.ok) {
      const errText = await r.text().catch(()=>"");
      throw new Error(`ElevenLabs ${r.status}: ${errText||r.statusText}`);
    }
    const blob = await r.blob();
    if (!blob || blob.size===0) throw new Error("ElevenLabs retornou áudio vazio");
    return URL.createObjectURL(new Blob([blob],{type:"audio/mpeg"}));
  }
}

async function didTalkingPhoto(imageUrl, audioUrl) {
  if (!DID_KEY || DID_KEY.includes("PASTE")) {
    throw new Error("Chave D-ID não configurada.");
  }
  // Create talk
  const create = await fetch("https://api.d-id.com/talks", {
    method:"POST",
    headers:{"Content-Type":"application/json","Authorization":DID_KEY},
    body:JSON.stringify({
      source_url: imageUrl,
      script: { type:"audio", audio_url: audioUrl },
      config: { fluent:true, pad_audio:0.0 },
    }),
  });
  if (!create.ok) throw new Error("D-ID create: " + create.statusText);
  const { id } = await create.json();

  // Poll for result
  for (let i=0; i<20; i++) {
    await new Promise(r=>setTimeout(r,3000));
    const poll = await fetch(`https://api.d-id.com/talks/${id}`, {
      headers:{"Authorization":DID_KEY},
    });
    const data = await poll.json();
    if (data.status === "done") return data.result_url;
    if (data.status === "error") throw new Error("D-ID erro: " + data.error?.message);
  }
  throw new Error("D-ID timeout — tente novamente");
}

// ═══════════════════════════════════════════════════════════════════
//  SHARE CARD
// ═══════════════════════════════════════════════════════════════════
async function generateShareImage(text, name, relation) {
  const canvas = document.createElement("canvas");
  canvas.width = 800; canvas.height = 1000;
  const ctx = canvas.getContext("2d");

  // warm dark background
  const bg = ctx.createRadialGradient(400,300,100,400,500,700);
  bg.addColorStop(0,"#1a1208"); bg.addColorStop(1,"#050302");
  ctx.fillStyle=bg; ctx.fillRect(0,0,800,1000);

  // candle glow top
  const glow = ctx.createRadialGradient(400,80,10,400,80,200);
  glow.addColorStop(0,"rgba(220,160,60,0.15)"); glow.addColorStop(1,"transparent");
  ctx.fillStyle=glow; ctx.fillRect(0,0,800,400);

  // stars
  for(let i=0;i<60;i++){
    ctx.beginPath(); ctx.arc(Math.random()*800,Math.random()*1000,Math.random()*1+0.3,0,Math.PI*2);
    ctx.fillStyle=`rgba(220,180,100,${Math.random()*0.25+0.05})`; ctx.fill();
  }

  // candle emoji top
  ctx.font="36px serif"; ctx.textAlign="center"; ctx.fillText("🕯️",400,65);

  // brand
  ctx.fillStyle=C.gold; ctx.font="500 16px 'Cinzel',Georgia,serif";
  ctx.letterSpacing="4px"; ctx.fillText("VOZ DO MEU",400,100);

  // name
  if(name){ ctx.fillStyle=C.goldSoft; ctx.font="italic 22px 'Cormorant Garamond',Georgia,serif"; ctx.fillText(name,400,132); }
  if(relation){ ctx.fillStyle=C.textFaint; ctx.font="14px 'Cormorant Garamond',Georgia,serif"; ctx.fillText(relation,400,154); }

  // divider
  ctx.strokeStyle="rgba(200,150,80,0.2)"; ctx.lineWidth=1;
  ctx.beginPath(); ctx.moveTo(120,172); ctx.lineTo(680,172); ctx.stroke();

  // ornament
  ctx.fillStyle="rgba(200,150,80,0.3)"; ctx.font="13px serif";
  ctx.fillText("✦  ✦  ✦",400,196);

  // text wrap
  ctx.fillStyle="#ddd0b8"; ctx.font="17px 'Cormorant Garamond',Georgia,serif";
  const words=text.split(" "); let line=""; let y=228; const maxW=560; const lh=28;
  for(let i=0;i<words.length;i++){
    const test=line+words[i]+" ";
    if(ctx.measureText(test).width>maxW&&i>0){ ctx.fillText(line.trim(),400,y); line=words[i]+" "; y+=lh; }
    else line=test;
  }
  ctx.fillText(line.trim(),400,y); y+=lh+16;

  // bottom ornament
  ctx.fillStyle="rgba(200,150,80,0.25)"; ctx.font="13px serif"; ctx.fillText("✦  ✦  ✦",400,y+10);

  // divider
  ctx.strokeStyle="rgba(200,150,80,0.15)"; ctx.beginPath(); ctx.moveTo(120,y+32); ctx.lineTo(680,y+32); ctx.stroke();

  // tagline
  ctx.fillStyle="rgba(200,160,80,0.4)"; ctx.font="italic 13px 'Cormorant Garamond',Georgia,serif";
  ctx.fillText("A voz de quem você ama, para sempre.",400,y+56);

  // domain
  ctx.fillStyle="rgba(160,120,60,0.3)"; ctx.font="11px 'Cinzel',Georgia,serif";
  ctx.fillText("vozdomeu.com.br",400,970);

  return canvas.toDataURL("image/png");
}

async function shareWhatsApp(text, name, relation) {
  try {
    const img = await generateShareImage(text,name,relation);
    if(navigator.share&&navigator.canShare){
      const blob=await(await fetch(img)).blob();
      const file=new File([blob],"vozdomeu.png",{type:"image/png"});
      if(navigator.canShare({files:[file]})){
        await navigator.share({files:[file],title:"Voz do Meu",text:text.substring(0,100)+"...\n\nvozdomeu.com.br"});
        return;
      }
    }
  } catch(e){}
  const t=encodeURIComponent(`🕯️ VOZ DO MEU 🕯️\n${name?name+"\n":""}\n${text}\n\n✦ A voz de quem você ama, para sempre ✦\nvozdomeu.com.br`);
  window.open(`https://wa.me/?text=${t}`,"_blank");
}

// ═══════════════════════════════════════════════════════════════════
//  REUSABLE COMPONENTS
// ═══════════════════════════════════════════════════════════════════
function Btn({onClick,children,disabled,variant="default",style={}}) {
  const variants = {
    default: {background:C.bgCard,border:`1px solid ${C.border}`,color:C.textDim},
    primary: {background:`linear-gradient(135deg,#3a2808,#5a3c10)`,border:`1px solid ${C.border2}`,color:C.goldSoft},
    ghost:   {background:"transparent",border:`1px solid ${C.border}`,color:C.textFaint},
    whatsapp:{background:C.greenBg,border:`1px solid ${C.greenBorder}`,color:C.green},
  };
  return (
    <button onClick={onClick} disabled={disabled} style={{
      flex:1,padding:"11px 8px",borderRadius:10,cursor:disabled?"not-allowed":"pointer",
      fontSize:13,letterSpacing:0.5,transition:"all 0.2s",opacity:disabled?0.4:1,
      ...variants[variant],...style,
    }}>{children}</button>
  );
}

function Field({label,value,set,ph,multi,rows=2}) {
  const base={width:"100%",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:10,padding:"11px 13px",color:C.text,fontSize:15,outline:"none",display:"block"};
  return (
    <div style={{marginBottom:12}}>
      <label style={{fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",display:"block",marginBottom:5}}>{label}</label>
      {multi
        ? <textarea value={value} onChange={e=>set(e.target.value)} placeholder={ph} rows={rows} style={{...base,resize:"vertical"}}/>
        : <input value={value} onChange={e=>set(e.target.value)} placeholder={ph} style={base}/>
      }
    </div>
  );
}

function WordReveal({text,style={}}) {
  const [vis,setVis] = useState(0);
  const words = text.split(" ");
  useEffect(()=>{
    setVis(0); let i=0;
    const iv=setInterval(()=>{ i++; setVis(i); if(i>=words.length)clearInterval(iv); },70);
    return ()=>clearInterval(iv);
  },[text]);
  return (
    <p style={{margin:0,lineHeight:2,fontSize:15,wordBreak:"break-word",overflowWrap:"break-word",whiteSpace:"normal",...style}}>
      {words.map((w,i)=>(
        <span key={i} style={{opacity:i<vis?1:0,transition:"opacity 0.25s ease",marginRight:"4px",display:"inline"}}>{w}</span>
      ))}
    </p>
  );
}

function ShareBtn({text,name="",relation=""}) {
  const [st,setSt]=useState("idle");
  const go=async()=>{
    setSt("loading");
    try{ await shareWhatsApp(text,name,relation); setSt("done"); setTimeout(()=>setSt("idle"),3000); }
    catch(e){ setSt("idle"); }
  };
  return (
    <Btn onClick={go} disabled={st==="loading"} variant="whatsapp">
      {st==="loading"?"⏳":st==="done"?"✓ Enviado!":"💬 WhatsApp"}
    </Btn>
  );
}

function ApiWarning({service}) {
  const missing = (service==="anthropic"&&(!ANTHROPIC_KEY||ANTHROPIC_KEY.includes("PASTE")))
    || (service==="elevenlabs"&&(!ELEVENLABS_KEY||ELEVENLABS_KEY.includes("PASTE")))
    || (service==="did"&&(!DID_KEY||DID_KEY.includes("PASTE")));
  if (!missing) return null;
  const names={anthropic:"Anthropic",elevenlabs:"ElevenLabs",did:"D-ID"};
  return (
    <div style={{background:"rgba(180,120,40,0.1)",border:`1px solid rgba(200,150,60,0.25)`,borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:12,color:"rgba(220,170,80,0.7)",display:"flex",gap:8,alignItems:"center"}}>
      <span>⚠️</span>
      <span>Chave {names[service]} não configurada — cole no topo do arquivo para ativar esta função.</span>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  APP ROOT
// ═══════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════
//  DISCLAIMER SCREEN — shown once on first open
// ═══════════════════════════════════════════════════════════════════
function DisclaimerScreen({onAccept}) {
  const [page,setPage] = useState(1); // 1=welcome, 2=terms
  const [scrolled,setScrolled] = useState(false);
  const scrollRef = useRef(null);

  const handleScroll = (e) => {
    const el = e.target;
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 20) setScrolled(true);
  };

  if (page===1) return (
    <div style={{
      position:"fixed",inset:0,zIndex:999,background:"#0a0705",
      display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",
      padding:"32px 24px",animation:"fadeUp 0.6s ease",
    }}>
      <div style={{fontSize:48,marginBottom:16,animation:"flicker 3s ease-in-out infinite"}}>🕯️</div>
      <h1 style={{fontFamily:"'Cinzel',Georgia,serif",fontSize:24,fontWeight:400,letterSpacing:6,color:C.gold,textAlign:"center",marginBottom:6}}>
        VOZ DO MEU
      </h1>
      <p style={{fontSize:10,letterSpacing:4,color:C.textFaint,marginBottom:36,textAlign:"center",fontFamily:"'Cinzel',Georgia,serif"}}>
        A VOZ DE QUEM VOCÊ AMA, PARA SEMPRE
      </p>

      <div style={{background:"rgba(255,240,200,0.03)",border:`1px solid ${C.border}`,borderRadius:18,padding:"28px 24px",maxWidth:400,width:"100%",marginBottom:28}}>
        <p style={{fontSize:15,color:C.textDim,lineHeight:1.9,textAlign:"center",fontStyle:"italic",marginBottom:20}}>
          Um espaço sagrado para honrar, lembrar e sentir a presença de quem amamos.
        </p>
        <div style={{borderTop:`1px solid ${C.border}`,paddingTop:18,textAlign:"center"}}>
          <p style={{fontSize:12,color:"rgba(120,180,255,0.8)",marginBottom:6}}>
            💙 Se você está em sofrimento intenso agora:
          </p>
          <p style={{fontSize:20,color:"rgba(140,200,255,1)",fontWeight:600,letterSpacing:3,marginBottom:2}}>
            CVV · 188
          </p>
          <p style={{fontSize:11,color:C.textFaint}}>Gratuito · 24 horas · Sigiloso</p>
        </div>
      </div>

      <button onClick={()=>setPage(2)} style={{
        background:`linear-gradient(135deg,${C.bgCard2},rgba(200,150,80,0.15))`,
        border:`1px solid ${C.border2}`,borderRadius:14,padding:"14px 44px",cursor:"pointer",
        fontSize:14,color:C.goldSoft,fontFamily:"'Cinzel',Georgia,serif",letterSpacing:3,
      }}>
        CONTINUAR
      </button>
    </div>
  );

  return (
    <div style={{
      position:"fixed",inset:0,zIndex:999,background:"#0a0705",
      display:"flex",flexDirection:"column",padding:"0",animation:"fadeUp 0.4s ease",
    }}>
      {/* Header */}
      <div style={{padding:"20px 24px 12px",borderBottom:`1px solid ${C.border}`,textAlign:"center",flexShrink:0}}>
        <p style={{fontSize:10,letterSpacing:4,color:C.textFaint,fontFamily:"'Cinzel',Georgia,serif"}}>TERMOS DE USO E RESPONSABILIDADE</p>
        <p style={{fontSize:11,color:C.textFaint,marginTop:4}}>Voz do Meu · vozdomeu.com.br</p>
      </div>

      {/* Scrollable terms */}
      <div ref={scrollRef} onScroll={handleScroll} style={{
        flex:1,overflowY:"auto",padding:"20px 24px",
        fontSize:13,color:C.textDim,lineHeight:1.9,
      }}>
        <Section title="1. NATUREZA DO SERVIÇO">
          O Voz do Meu é uma plataforma de conforto espiritual, homenagem afetiva e memória digital. As mensagens, preces e orações geradas são criadas por inteligência artificial com base nas informações fornecidas pelo usuário. Não constituem canalizações mediúnicas literais, diagnósticos psicológicos, aconselhamento clínico ou qualquer forma de atendimento em saúde mental.
        </Section>

        <Section title="2. ISENÇÃO DE RESPONSABILIDADE EMOCIONAL">
          O uso deste aplicativo pressupõe que o usuário está em condições emocionais de interagir com conteúdo relacionado a luto e perda. O Voz do Meu não se responsabiliza por reações emocionais decorrentes do uso da plataforma. Em caso de crise emocional, depressão, ou pensamentos de autolesão, o usuário deve procurar imediatamente auxílio profissional.
        </Section>

        <Section title="3. NÃO SUBSTITUI TRATAMENTO PROFISSIONAL">
          Este aplicativo não substitui, em nenhuma hipótese, acompanhamento psicológico, psiquiátrico ou espiritual presencial. Se você está passando por luto intenso, transtorno depressivo, ou qualquer condição de saúde mental, procure um profissional habilitado. O CVV (Centro de Valorização da Vida) atende gratuitamente pelo número 188, 24 horas por dia.
        </Section>

        <Section title="4. CONTEÚDO GERADO POR INTELIGÊNCIA ARTIFICIAL">
          Todas as mensagens canalizadas, preces, orações e respostas do orientador espiritual são geradas por modelos de inteligência artificial. Embora inspiradas nas informações fornecidas, são criações computacionais e não devem ser interpretadas como comunicações literais de pessoas falecidas. O Voz do Meu apresenta estas criações como homenagens afetivas e instrumentos de conforto espiritual.
        </Section>

        <Section title="5. PRIVACIDADE DAS INFORMAÇÕES">
          As informações sobre o falecido fornecidas pelo usuário são utilizadas exclusivamente para geração do conteúdo memorial. Não são vendidas, compartilhadas com terceiros, ou armazenadas permanentemente em nossos servidores além do necessário para a geração da sessão. Fotos enviadas são processadas localmente e não publicadas.
        </Section>

        <Section title="6. PROPRIEDADE INTELECTUAL">
          O conteúdo gerado pela plataforma é de uso pessoal do usuário. É proibida a reprodução comercial, revenda ou distribuição em massa do conteúdo gerado sem autorização expressa. O nome Voz do Meu, a marca Monet de Bahia e o token $MONET são de propriedade exclusiva de seus respectivos titulares.
        </Section>

        <Section title="7. MENORES DE IDADE">
          O uso desta plataforma por menores de 18 anos requer supervisão e consentimento de um responsável legal. O conteúdo emocional relacionado a luto e morte pode não ser adequado para crianças sem acompanhamento adulto.
        </Section>

        <Section title="8. ACEITAÇÃO E VIGÊNCIA">
          Ao clicar em "ENTRAR COM AMOR" o usuário declara ter lido, compreendido e aceito integralmente estes Termos de Uso. Esta aceitação é registrada localmente no dispositivo. Estes termos podem ser atualizados periodicamente. O uso continuado da plataforma implica aceitação das versões vigentes.
        </Section>

        <div style={{textAlign:"center",padding:"16px 0 8px",borderTop:`1px solid ${C.border}`,marginTop:8}}>
          <p style={{fontSize:11,color:C.textFaint,fontStyle:"italic"}}>
            "Nenhum ser amado se perde para sempre. A saudade é a prova do amor que permanece."
          </p>
        </div>

        {!scrolled && (
          <p style={{textAlign:"center",fontSize:11,color:C.textFaint,marginTop:12,animation:"fadeUp 0.5s ease"}}>
            ↓ Role até o fim para continuar
          </p>
        )}
      </div>

      {/* Footer */}
      <div style={{padding:"16px 24px",borderTop:`1px solid ${C.border}`,flexShrink:0,textAlign:"center"}}>
        <button
          onClick={scrolled ? onAccept : ()=>{ scrollRef.current?.scrollTo({top:99999,behavior:"smooth"}); }}
          style={{
            background: scrolled
              ? `linear-gradient(135deg,${C.bgCard2},rgba(200,150,80,0.15))`
              : "rgba(255,255,255,0.03)",
            border:`1px solid ${scrolled ? C.border2 : C.border}`,
            borderRadius:14,padding:"14px 44px",cursor:"pointer",
            fontSize:14,color: scrolled ? C.goldSoft : C.textFaint,
            fontFamily:"'Cinzel',Georgia,serif",letterSpacing:3,
            transition:"all 0.4s",width:"100%",maxWidth:360,
          }}
        >
          {scrolled ? "ENTRAR COM AMOR" : "LEIA OS TERMOS COMPLETOS ↓"}
        </button>
        <p style={{fontSize:10,color:C.textFaint,marginTop:8}}>
          Ao continuar você aceita os termos acima · CVV 188 sempre disponível
        </p>
      </div>
    </div>
  );
}

function Section({title,children}) {
  return (
    <div style={{marginBottom:20}}>
      <p style={{fontSize:11,color:C.gold,letterSpacing:2,fontFamily:"'Cinzel',Georgia,serif",marginBottom:6,opacity:0.8}}>
        {title}
      </p>
      <p style={{color:"rgba(220,200,160,0.55)",lineHeight:1.85,fontSize:13}}>
        {children}
      </p>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  CVV BANNER — always visible at bottom
// ═══════════════════════════════════════════════════════════════════
function CvvBanner() {
  const [open,setOpen] = useState(false);
  return (
    <div style={{
      position:"fixed",bottom:72,left:0,right:0,zIndex:90,
      display:"flex",justifyContent:"center",pointerEvents:"none",
    }}>
      {open ? (
        <div style={{
          background:"rgba(10,20,40,0.97)",border:"1px solid rgba(100,160,255,0.3)",
          borderRadius:14,padding:"16px 20px",maxWidth:340,width:"90%",
          pointerEvents:"all",animation:"fadeUp 0.3s ease",
        }}>
          <p style={{fontSize:13,color:"rgba(160,210,255,0.9)",marginBottom:10,lineHeight:1.7}}>
            💙 Se você está pensando em se machucar, por favor fale com alguém agora.
          </p>
          <p style={{fontSize:16,color:"rgba(140,200,255,1)",fontWeight:600,letterSpacing:2,marginBottom:4}}>
            📞 CVV — 188
          </p>
          <p style={{fontSize:11,color:"rgba(140,180,255,0.6)",marginBottom:12}}>
            Gratuito · 24 horas · Sigiloso · cvv.org.br
          </p>
          <button onClick={()=>setOpen(false)} style={{
            background:"transparent",border:"1px solid rgba(100,160,255,0.2)",
            borderRadius:8,padding:"6px 16px",cursor:"pointer",
            fontSize:12,color:"rgba(140,180,255,0.6)",fontFamily:"inherit",
          }}>Fechar</button>
        </div>
      ) : (
        <button onClick={()=>setOpen(true)} style={{
          background:"rgba(10,20,40,0.85)",border:"1px solid rgba(100,160,255,0.2)",
          borderRadius:20,padding:"6px 16px",cursor:"pointer",
          fontSize:11,color:"rgba(140,180,255,0.6)",fontFamily:"inherit",
          pointerEvents:"all",backdropFilter:"blur(6px)",letterSpacing:1,
        }}>
          💙 CVV 188
        </button>
      )}
    </div>
  );
}

function App() {
  const [tab,setTab] = useState("home");
  const [muted,setMuted] = useState(false);
  const [accepted,setAccepted] = useState(()=>!!localStorage.getItem("vzm_accepted"));
  const ctxRef     = useRef(null);
  const masterRef  = useRef(null);
  const buffersRef = useRef({});
  const activeRef  = useRef(true);
  const mutedRef   = useRef(false);
  const startedRef = useRef(false);

  // ── Real piano samples via Web Audio API ─────────────────────────
  useEffect(()=>{
    // Notes we'll use — sparse pentatonic grief phrases
    const SAMPLE_NOTES = ["C3","G3","C4","E4","G4","A4","C5"];
    const BASE = "https://gleitz.github.io/midi-js-soundfonts/MusyngKite/acoustic_grand_piano-mp3/";

    const PHRASES = [
      ["C4","G3","C3"],
      ["E4","C4","G3"],
      ["A4","E4","C4"],
      ["G4","C4","G3"],
      ["C5","A4","E4"],
      ["G3","C4"],
      ["E4","G4"],
    ];

    const loadSample = async (ctx, note) => {
      try {
        const res = await fetch(`${BASE}${note.replace("#","s")}.mp3`);
        const buf = await res.arrayBuffer();
        return await ctx.decodeAudioData(buf);
      } catch(e) { return null; }
    };

    const playNote = (ctx, buffer, when, vol=0.18) => {
      if (!buffer || !activeRef.current) return;
      const src  = ctx.createBufferSource();
      const gain = ctx.createGain();
      src.buffer = buffer;
      src.connect(gain);
      gain.connect(masterRef.current);
      gain.gain.setValueAtTime(0, when);
      gain.gain.linearRampToValueAtTime(vol, when + 0.03);
      gain.gain.exponentialRampToValueAtTime(0.0001, when + 6);
      src.start(when);
      src.stop(when + 7);
    };

    const schedulePhrase = () => {
      if (!activeRef.current || !ctxRef.current) return;
      const ctx     = ctxRef.current;
      const bufs    = buffersRef.current;
      const phrase  = PHRASES[Math.floor(Math.random()*PHRASES.length)];
      const noteGap = 1.2 + Math.random()*1.6;
      const now     = ctx.currentTime + 0.1;

      phrase.forEach((note, i) => {
        const buf = bufs[note];
        if (buf) playNote(ctx, buf, now + i*noteGap, 0.12 + Math.random()*0.1);
      });

      const next = (phrase.length * noteGap * 1000) + 2000 + Math.random()*5000;
      setTimeout(()=>{ if(activeRef.current) schedulePhrase(); }, next);
    };

    const startMusic = async () => {
      if (startedRef.current) return;
      startedRef.current = true;

      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      ctxRef.current = ctx;

      // Master gain with reverb
      const master  = ctx.createGain();
      const reverb  = ctx.createConvolver();
      const revGain = ctx.createGain();
      masterRef.current = master;

      // Build impulse reverb
      const sr  = ctx.sampleRate;
      const len = sr * 3;
      const ir  = ctx.createBuffer(2, len, sr);
      for (let ch=0;ch<2;ch++){
        const d=ir.getChannelData(ch);
        for(let i=0;i<len;i++) d[i]=(Math.random()*2-1)*Math.pow(1-i/len,2.5);
      }
      reverb.buffer = ir;

      master.connect(revGain);
      revGain.connect(reverb);
      reverb.connect(ctx.destination);
      master.connect(ctx.destination);
      revGain.gain.value = 0.5;

      // Fade in
      master.gain.setValueAtTime(0, ctx.currentTime);
      master.gain.linearRampToValueAtTime(0.7, ctx.currentTime + 4);

      // Load samples then start
      const loaded = await Promise.all(
        SAMPLE_NOTES.map(async note => {
          const buf = await loadSample(ctx, note);
          if (buf) buffersRef.current[note] = buf;
        })
      );

      if (activeRef.current) schedulePhrase();
    };

    const onInteract = () => startMusic();
    document.addEventListener("click",    onInteract, {once:true});
    document.addEventListener("touchend", onInteract, {once:true});

    return () => {
      activeRef.current = false;
      ctxRef.current?.close();
    };
  }, []);

  // ── Mute toggle ───────────────────────────────────────────────────
  useEffect(()=>{
    mutedRef.current = muted;
    if (!masterRef.current || !ctxRef.current) return;
    masterRef.current.gain.linearRampToValueAtTime(
      muted ? 0 : 0.7,
      ctxRef.current.currentTime + 1.2
    );
  }, [muted]);

  return (
    <div style={{minHeight:"100vh",background:C.bg,color:C.text,fontFamily:"'Cormorant Garamond',Georgia,serif",position:"relative",overflowX:"hidden"}}>
      <style>{css}</style>

      {/* Disclaimer — first time only */}
      {!accepted && <DisclaimerScreen onAccept={()=>{
        localStorage.setItem("vzm_accepted","1");
        setAccepted(true);
      }}/>}

      {/* CVV always visible */}
      <CvvBanner/>

      {/* Mute button */}
      <button onClick={()=>setMuted(m=>!m)} style={{
        position:"fixed",top:14,right:14,zIndex:100,
        background:"rgba(255,255,255,0.04)",border:`1px solid ${C.border}`,
        borderRadius:20,padding:"5px 11px",cursor:"pointer",
        fontSize:13,color:C.textFaint,fontFamily:"inherit",
        backdropFilter:"blur(6px)",transition:"all 0.3s",
      }}>
        {muted ? "🔇" : "🎵"}
      </button>

      {/* Stars */}
      <svg style={{position:"fixed",inset:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:0}}>
        {STAR_DATA.map(s=>(
          <circle key={s.id} cx={`${s.x}%`} cy={`${s.y}%`} r={s.r} fill="#e8c878"
            style={{animation:`twinkle ${s.dur}s ${s.delay}s infinite`}}/>
        ))}
      </svg>

      {/* Candle glow */}
      <div style={{position:"fixed",top:0,left:"50%",transform:"translateX(-50%)",width:400,height:300,background:"radial-gradient(ellipse,rgba(200,140,40,0.08) 0%,transparent 70%)",pointerEvents:"none",zIndex:0}}/>

      {/* Header */}
      <div style={{position:"relative",zIndex:1,textAlign:"center",padding:"28px 20px 12px"}}>
        <div style={{fontSize:28,animation:"flicker 3s ease-in-out infinite"}}>🕯️</div>
        <h1 style={{margin:"8px 0 3px",fontSize:26,fontWeight:400,letterSpacing:8,color:C.gold,fontFamily:"'Cinzel',Georgia,serif",textTransform:"uppercase"}}>
          Voz do Meu
        </h1>
        <p style={{margin:0,fontSize:11,letterSpacing:3,color:C.textFaint,fontFamily:"'Cinzel',Georgia,serif"}}>
          A VOZ DE QUEM VOCÊ AMA, PARA SEMPRE
        </p>
        <div style={{margin:"12px auto 0",maxWidth:380,padding:"10px 16px",borderTop:`1px solid ${C.border}`,borderBottom:`1px solid ${C.border}`}}>
          <p style={{margin:0,fontSize:13,fontStyle:"italic",color:C.textDim,lineHeight:1.7}}>
            "Fora da caridade não há salvação."
          </p>
          <p style={{margin:"4px 0 0",fontSize:10,color:C.textFaint,letterSpacing:1}}>— Allan Kardec</p>
        </div>
      </div>

      {/* Nav */}
      <div style={{position:"relative",zIndex:1,display:"flex",gap:6,padding:"8px 16px 14px",maxWidth:520,margin:"0 auto"}}>
        {NAV.map(n=>(
          <button key={n.id} onClick={()=>setTab(n.id)} style={{
            flex:1,padding:"10px 4px",borderRadius:12,cursor:"pointer",fontFamily:"'Cinzel',Georgia,serif",
            background:tab===n.id?C.bgCard2:"rgba(255,255,255,0.02)",
            border:tab===n.id?`1px solid ${C.border2}`:`1px solid ${C.border}`,
            color:tab===n.id?C.gold:C.textFaint,fontSize:9,letterSpacing:1.5,textAlign:"center",transition:"all 0.25s",
          }}>
            <div style={{fontSize:16,marginBottom:2}}>{n.emoji}</div>
            {n.label.toUpperCase()}
          </button>
        ))}
      </div>

      {/* Content */}
      <div style={{position:"relative",zIndex:1,maxWidth:520,margin:"0 auto",padding:"0 16px 80px",overflowX:"hidden"}}>
        {tab==="home"    && <HomeTab    onNav={setTab}/>}
        {tab==="memorial"&& <MemorialTab/>}
        {tab==="prece"   && <PreceTab/>}
        {tab==="oracao"  && <OracaoTab/>}
        {tab==="oracles" && <OraclesTab/>}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  HOME
// ═══════════════════════════════════════════════════════════════════
function HomeTab({onNav}) {
  return (
    <div style={{animation:"fadeUp 0.6s ease"}}>
      <p style={{fontSize:17,color:C.textDim,lineHeight:1.9,marginBottom:24,textAlign:"center",fontStyle:"italic"}}>
        Um espaço sagrado para ouvir a voz de quem partiu, elevar preces e honrar a memória de quem você ama.
      </p>

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:16}}>
        {[
          {id:"memorial",emoji:"💫",title:"Memorial",desc:"Foto, história de vida e sessão mediúnica com voz e vídeo animado"},
          {id:"prece",   emoji:"🙏",title:"Prece Espírita",desc:"Prece personalizada com doutrina Kardecista e orientador espiritual"},
          {id:"oracao",  emoji:"✝️", title:"Oração",desc:"Oração católica personalizada com intercessão e meditação"},
        ].map(c=>(
          <button key={c.id} onClick={()=>onNav(c.id)} style={{
            background:C.bgCard2,border:`1px solid ${C.border}`,borderRadius:16,
            padding:"20px 14px",cursor:"pointer",textAlign:"center",animation:`glow 4s ease-in-out infinite`,
          }}>
            <div style={{fontSize:28,marginBottom:8}}>{c.emoji}</div>
            <div style={{fontSize:14,color:C.gold,marginBottom:6,fontFamily:"'Cinzel',Georgia,serif",letterSpacing:1}}>{c.title}</div>
            <div style={{fontSize:13,color:C.textFaint,lineHeight:1.5}}>{c.desc}</div>
          </button>
        ))}
      </div>

      <button onClick={()=>onNav("oracles")} style={{
        width:"100%",background:"rgba(60,40,180,0.06)",border:"1px solid rgba(120,80,220,0.2)",
        borderRadius:14,padding:"14px",cursor:"pointer",textAlign:"center",marginBottom:16,
      }}>
        <div style={{fontSize:20,marginBottom:4}}>🔮</div>
        <div style={{fontSize:13,color:"rgba(180,140,240,0.6)",fontFamily:"'Cinzel',Georgia,serif",letterSpacing:1}}>ORÁCULOS</div>
        <div style={{fontSize:12,color:"rgba(160,120,220,0.4)",marginTop:3}}>Oracle Gateway · $MONET · Para agentes de IA</div>
      </button>

      <div style={{padding:"14px 16px",background:C.greenBg,border:`1px solid ${C.greenBorder}`,borderRadius:12,marginBottom:14,textAlign:"center"}}>
        <p style={{margin:0,fontSize:13,color:C.green}}>💬 Compartilhe memórias diretamente no WhatsApp</p>
        <p style={{margin:"3px 0 0",fontSize:11,color:"rgba(74,153,96,0.5)"}}>Cartão visual gerado automaticamente · vozdomeu.com.br</p>
      </div>

      <div style={{padding:"12px 14px",background:"rgba(60,40,180,0.04)",border:"1px solid rgba(100,70,200,0.12)",borderRadius:12,textAlign:"center"}}>
        <p style={{margin:0,fontSize:10,color:"rgba(160,130,220,0.35)",letterSpacing:2,fontFamily:"'Cinzel',Georgia,serif"}}>💎 ECOSSISTEMA MONET DE BAHIA</p>
        <p style={{margin:"4px 0 0",fontSize:11,color:"rgba(160,130,220,0.3)"}}>Solana · SPL Token · Oracle Gateway · $MONET</p>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  MEMORIAL
// ═══════════════════════════════════════════════════════════════════
function MemorialTab() {
  const [step,setStep]         = useState("form"); // form|processing|result|session
  const [name,setName]         = useState("");
  const [relation,setRelation] = useState("");
  const [birth,setBirth]       = useState("");
  const [passing,setPassing]   = useState("");
  const [story,setStory]       = useState("");
  const [personality,setPersonality] = useState("");
  const [sayings,setSayings]   = useState("");
  const [photo,setPhoto]       = useState(null);
  const [photoFile,setPhotoFile] = useState(null);
  const [selectedVoice,setSelectedVoice] = useState(VOICE_LIBRARY[0]);
  const [result,setResult]     = useState({prayer:"",message:""});
  const [audioUrl,setAudioUrl] = useState(null);
  const [videoUrl,setVideoUrl] = useState(null);
  const [loading,setLoading]   = useState(false);
  const [loadMsg,setLoadMsg]   = useState("");
  const [error,setError]       = useState("");
  const [playing,setPlaying]   = useState(false);
  const audioRef  = useRef(null);
  const fileRef   = useRef(null);

  const handlePhoto = (e) => {
    const f=e.target.files?.[0]; if(!f) return;
    setPhotoFile(f);
    const reader=new FileReader();
    reader.onload=ev=>setPhoto(ev.target.result);
    reader.readAsDataURL(f);
  };

  const generate = async () => {
    if (!name) return;
    // Crisis check on story/context before generating
    const allInput = [story, personality, sayings].join(" ");
    if (detectCrisis(allInput)) {
      setError(CRISIS_RESPONSE);
      return;
    }
    setLoading(true); setError(""); setStep("processing");
    const ctx=`Nome: ${name}. Relação: ${relation||"ente querido"}. ${birth?`Nascimento: ${birth}.`:""} ${passing?`Desencarne: ${passing}.`:""} História: ${story||"N/A"}. Personalidade: ${personality||"N/A"}. Frases: ${sayings||"N/A"}.`;

    try {
      setLoadMsg("Gerando prece memorial...");
      const [prayerText,messageText] = await Promise.all([
        claudeAI(
          "Voce e profundo conhecedor da Doutrina Espirita de Allan Kardec. Escreve preces memoriais autenticas e poeticamente belas. Retorne APENAS o texto da prece.",
          `Gere prece memorial espirita para ${name}. Contexto: ${ctx}. 150-200 palavras em portugues. Use: perispírito, plano espiritual, reencontro, evolução espiritual.`
        ),
        claudeAI(
          "Voce e medium espirita versado em Kardec e Chico Xavier. Canalize mensagens positivas e consoladoras de entes desencarnados. Sempre em primeira pessoa, como se viesse do desencarnado. Seja poetico, amoroso e reconfortante.",
          `Canalize mensagem de amor e paz em nome de ${name} para seus entes queridos. Contexto: ${ctx}. 100-150 palavras em portugues. Primeira pessoa, paz, sabedoria espirita, mencione detalhes pessoais.`
        ),
      ]);
      setResult({prayer:prayerText,message:messageText});

      // ElevenLabs TTS
      if (ELEVENLABS_KEY && !ELEVENLABS_KEY.includes("PASTE")) {
        setLoadMsg("Gerando voz...");
        const vId = selectedVoice?.id || VOICE_LIBRARY[0].id;
        const url = await elevenLabsTTS(messageText, vId);
        setAudioUrl(url);

        // D-ID talking photo
        if (DID_KEY && !DID_KEY.includes("PASTE") && photo) {
          setLoadMsg("Animando foto...");
          try {
            // Convert local photo to uploadable URL — for demo we skip D-ID if no hosted URL
            // In production: upload photo to your server first, then pass URL to D-ID
            setLoadMsg("Sessão mediúnica pronta...");
          } catch(e) { console.warn("D-ID skip:",e.message); }
        }
      }

      setStep("result");
    } catch(e) { setError(e.message); setStep("form"); }
    finally { setLoading(false); setLoadMsg(""); }
  };

  const playAudio = () => {
    if (!audioRef.current) return;
    if (playing) { audioRef.current.pause(); setPlaying(false); }
    else { audioRef.current.play(); setPlaying(true); }
  };

  if (step==="processing") return (
    <div style={{textAlign:"center",padding:"70px 0",animation:"fadeUp 0.4s ease"}}>
      <div style={{fontSize:42,animation:"flicker 1.5s ease-in-out infinite",marginBottom:16}}>🕯️</div>
      <p style={{color:C.textDim,fontSize:15,letterSpacing:2,marginBottom:8}}>{loadMsg||"Preparando o memorial..."}</p>
      <p style={{color:C.textFaint,fontSize:13,fontStyle:"italic"}}>Conectando com amor e luz...</p>
    </div>
  );

  if (step==="result") return (
    <div style={{animation:"fadeUp 0.5s ease"}}>
      {/* Photo + name header */}
      <div style={{textAlign:"center",marginBottom:20}}>
        {photo
          ? <img src={photo} alt={name} style={{width:96,height:96,borderRadius:"50%",objectFit:"cover",border:`2px solid ${C.border2}`,marginBottom:10,boxShadow:"0 0 30px rgba(200,150,60,0.2)"}}/>
          : <div style={{width:96,height:96,borderRadius:"50%",background:C.bgCard2,border:`2px solid ${C.border}`,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 10px",fontSize:36}}>🕯️</div>
        }
        <h3 style={{fontSize:20,fontWeight:400,color:C.goldSoft,letterSpacing:3,fontFamily:"'Cinzel',Georgia,serif"}}>{name}</h3>
        {relation&&<p style={{fontSize:13,color:C.textFaint,marginTop:3}}>{relation}</p>}
        {(birth||passing)&&<p style={{fontSize:11,color:"rgba(200,160,80,0.3)",marginTop:2}}>{birth}{birth&&passing?" · ":""}{passing}</p>}
      </div>

      {/* Audio player */}
      {audioUrl && (
        <div style={{background:C.bgCard2,border:`1px solid ${C.border}`,borderRadius:14,padding:"14px 16px",marginBottom:14,display:"flex",alignItems:"center",gap:12}}>
          <audio ref={audioRef} src={audioUrl} onEnded={()=>setPlaying(false)} style={{display:"none"}}/>
          <button onClick={playAudio} style={{width:44,height:44,borderRadius:"50%",background:`linear-gradient(135deg,#3a2808,#6a4010)`,border:`1px solid ${C.border2}`,cursor:"pointer",flexShrink:0,fontSize:18,color:C.gold}}>
            {playing?"⏸":"▶"}
          </button>
          <div>
            <p style={{margin:0,fontSize:13,color:C.textDim}}>Mensagem canalizada — {selectedVoice?.name||"Voz selecionada"}</p>
            <p style={{margin:"2px 0 0",fontSize:11,color:C.textFaint}}>Toque para ouvir</p>
          </div>
        </div>
      )}

      {/* Video session placeholder */}
      {DID_KEY && !DID_KEY.includes("PASTE") && photo && (
        <div style={{background:"rgba(60,30,100,0.1)",border:"1px solid rgba(120,80,200,0.2)",borderRadius:14,padding:"14px",marginBottom:14,textAlign:"center"}}>
          <p style={{margin:0,fontSize:13,color:"rgba(180,140,240,0.6)"}}>🎭 Sessão Mediúnica com Vídeo</p>
          <p style={{margin:"4px 0 0",fontSize:11,color:"rgba(160,120,220,0.4)"}}>Ativar sessão com foto animada em tempo real</p>
          <button onClick={()=>setStep("session")} style={{marginTop:10,padding:"10px 20px",borderRadius:10,background:"linear-gradient(135deg,#3a1860,#5a2890)",border:"none",cursor:"pointer",color:"#d0c0f0",fontSize:12,letterSpacing:1}}>
            Abrir Sessão Mediúnica
          </button>
        </div>
      )}

      {/* Prayer */}
      <div style={{background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:16,padding:"20px",marginBottom:14,overflowX:"hidden",boxSizing:"border-box"}}>
        <p style={{margin:"0 0 10px",fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>🙏 Prece Memorial</p>
        <WordReveal text={result.prayer} style={{color:C.text}}/>
      </div>

      {/* Message */}
      <div style={{background:C.bgCard2,border:`1px solid ${C.border2}`,borderRadius:16,padding:"20px",marginBottom:16,overflowX:"hidden",boxSizing:"border-box"}}>
        <p style={{margin:"0 0 10px",fontSize:10,color:C.goldDim,letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>💫 Mensagem Canalizada</p>
        <p style={{margin:0,lineHeight:1.9,fontSize:15,color:C.goldSoft,fontStyle:"italic",whiteSpace:"pre-wrap"}}>{result.message}</p>
      </div>

      <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
        <ShareBtn text={result.prayer+"\n\n"+result.message} name={name} relation={relation}/>
        <Btn onClick={()=>navigator.clipboard?.writeText(result.prayer+"\n\n"+result.message)}>📋 Copiar</Btn>
        <Btn onClick={()=>{setStep("form");setResult({prayer:"",message:""});setAudioUrl(null);}}>🔄 Novo</Btn>
      </div>
    </div>
  );

  // FORM
  return (
    <div>
      <ApiWarning service="anthropic"/>
      {error&&<div style={{background:"rgba(180,60,60,0.1)",border:"1px solid rgba(200,80,80,0.25)",borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:13,color:"rgba(240,160,160,0.8)"}}>{error}</div>}

      <p style={{textAlign:"center",fontSize:12,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",marginBottom:18,fontFamily:"'Cinzel',Georgia,serif"}}>Honrar Ente Querido</p>

      {/* Photo upload */}
      <div onClick={()=>fileRef.current?.click()} style={{textAlign:"center",marginBottom:20,cursor:"pointer"}}>
        {photo
          ? <img src={photo} alt="foto" style={{width:88,height:88,borderRadius:"50%",objectFit:"cover",border:`2px solid ${C.border2}`,boxShadow:"0 0 20px rgba(200,150,60,0.15)"}}/>
          : <div style={{width:88,height:88,borderRadius:"50%",background:C.bgCard2,border:`2px dashed ${C.border}`,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",margin:"0 auto"}}>
              <div style={{fontSize:24}}>📷</div>
              <div style={{fontSize:9,color:C.textFaint,marginTop:3,letterSpacing:1,fontFamily:"'Cinzel',Georgia,serif"}}>FOTO</div>
            </div>
        }
        <input ref={fileRef} type="file" accept="image/*" onChange={handlePhoto} style={{display:"none"}}/>
        <p style={{margin:"6px 0 0",fontSize:12,color:C.textFaint}}>Toque para adicionar foto</p>
      </div>

      <Field label="Nome *"          value={name}        set={setName}        ph="Nome do ente querido"/>
      <Field label="Relação"          value={relation}    set={setRelation}    ph="Mãe, pai, filho..."/>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
        <Field label="Nascimento"     value={birth}       set={setBirth}       ph="ex: 1942"/>
        <Field label="Desencarne"     value={passing}     set={setPassing}     ph="ex: 2023"/>
      </div>
      <Field label="História de vida" value={story}       set={setStory}       ph="Quem foi? O que amava? Como viveu?" multi rows={3}/>
      <Field label="Personalidade"    value={personality} set={setPersonality} ph="Alegre, sábio, carinhoso, forte..."/>
      <Field label="Frases marcantes" value={sayings}     set={setSayings}     ph="Algo que sempre dizia..."/>

      {/* Voice selection */}
      <div style={{marginBottom:16}}>
        <label style={{fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",display:"block",marginBottom:10,fontFamily:"'Cinzel',Georgia,serif"}}>🎙️ Voz da Mensagem</label>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
          {VOICE_LIBRARY.map(v=>(
            <button key={v.id} onClick={()=>setSelectedVoice(v)} style={{
              background:selectedVoice?.id===v.id?C.bgCard2:"rgba(255,255,255,0.02)",
              border:selectedVoice?.id===v.id?`1px solid ${C.border2}`:`1px solid ${C.border}`,
              borderRadius:10,padding:"10px 8px",cursor:"pointer",textAlign:"center",
            }}>
              <div style={{fontSize:11,color:selectedVoice?.id===v.id?C.gold:C.textDim,marginBottom:2}}>{v.gender==="M"?"👨":"👩"} {v.name}</div>
              <div style={{fontSize:10,color:C.textFaint}}>{v.desc}</div>
            </button>
          ))}
        </div>
        <ApiWarning service="elevenlabs"/>
        <ApiWarning service="did"/>
      </div>

      <button onClick={generate} disabled={!name||loading} style={{
        width:"100%",padding:"16px",borderRadius:13,cursor:name?"pointer":"not-allowed",
        background:name?"linear-gradient(135deg,#3a2808,#6a3c10)":"rgba(60,40,10,0.2)",
        border:`1px solid ${name?C.border2:C.border}`,
        color:name?C.goldSoft:"rgba(180,140,60,0.3)",fontSize:14,letterSpacing:3,
        fontFamily:"'Cinzel',Georgia,serif",textTransform:"uppercase",
      }}>
        🕯️ Criar Memorial
      </button>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  PRECE ESPÍRITA
// ═══════════════════════════════════════════════════════════════════
function PreceTab() {
  const [screen,setScreen] = useState("pick");
  const [intention,setIntention] = useState(null);
  const [forWhom,setForWhom] = useState("");
  const [prayer,setPrayer] = useState("");
  const [loading,setLoading] = useState(false);
  const [error,setError] = useState("");
  const [msgs,setMsgs] = useState([]);
  const [chatIn,setChatIn] = useState("");
  const [chatLoad,setChatLoad] = useState(false);
  const [audioUrl,setAudioUrl] = useState(null);
  const [playing,setPlaying] = useState(false);
  const [voices,setVoices] = useState(VOICE_LIBRARY);
  const endRef = useRef(null);
  const audioRef = useRef(null);

  useEffect(()=>{ endRef.current?.scrollIntoView({behavior:"smooth"}); },[msgs]);
  useEffect(()=>{ fetchElevenLabsVoices().then(v=>{ if(v?.length) setVoices(v); }); },[]);

  const generate = async () => {
    if (!intention) return;
    setLoading(true); setError(""); setScreen("loading");
    const sel = INTENTIONS.find(i=>i.id===intention);
    try {
      const text = await claudeAI(
        "Voce e profundo conhecedor da Doutrina Espirita de Allan Kardec e das obras de Chico Xavier. Escreve preces autenticas, elevadas e poeticamente belas. Retorne APENAS o texto da prece, sem titulo.",
        `${forWhom?`Dedicada a ${forWhom}. `:""}Gere prece espirita autentica sobre "${sel.label}". 150-200 palavras, portugues do Brasil, terminologia espirita correta.`
      );
      setPrayer(text);
      setMsgs([{r:"a",t:"A prece foi elevada com amor. 🙏\n\nComo você se sente? Estou aqui como orientador espiritual, versado na Doutrina de Kardec. Pergunte sobre reencarnação, mediunidade, reforma íntima — ou compartilhe o que vai no coração."}]);

      // ElevenLabs TTS — use first available voice
      if (ELEVENLABS_KEY && !ELEVENLABS_KEY.includes("PASTE")) {
        try {
          const voiceList = await fetchElevenLabsVoices();
          const voiceId = voiceList?.[0]?.id || VOICE_LIBRARY[0].id;
          const url = await elevenLabsTTS(text, voiceId);
          setAudioUrl(url);
        } catch(e) {
            setError("ElevenLabs: " + e.message);
          setAudioUrl(null);
        }
      }

      setScreen("prayer");
    } catch(e) { setError(e.message); setScreen("pick"); }
    finally { setLoading(false); }
  };

  const playAudio = () => {
    // ElevenLabs audio available — use it
    if (audioUrl && audioRef.current) {
      if (playing) { audioRef.current.pause(); setPlaying(false); }
      else { audioRef.current.play(); setPlaying(true); }
      return;
    }
    // Browser TTS fallback
    if (!("speechSynthesis" in window)) return;
    if (playing) { window.speechSynthesis.cancel(); setPlaying(false); return; }
    const u = new SpeechSynthesisUtterance(prayer);
    u.lang="pt-BR"; u.rate=0.82; u.pitch=0.9;
    u.onend=()=>setPlaying(false);
    window.speechSynthesis.speak(u); setPlaying(true);
  };

  const sendChat = async () => {
    if (!chatIn.trim()||chatLoad) return;
    const msg=chatIn.trim().slice(0,500); setChatIn("");
    const next=[...msgs,{r:"u",t:msg}];
    setMsgs(next); setChatLoad(true);
    // Crisis detection — intercept before sending to AI
    if (detectCrisis(msg)) {
      setMsgs(p=>[...p,{r:"a",t:CRISIS_RESPONSE}]);
      setChatLoad(false); return;
    }
    try {
      const history = next.map(m => `${m.r==="u"?"Usuário":"Orientador"}: ${m.t}`).join("\n\n");
      const reply = await claudeAI(
        "Voce e orientador espiritual erudito na Doutrina Espirita de Allan Kardec. Responda com amor e sabedoria espirita, cite Kardec e Chico Xavier quando relevante. 80-150 palavras em portugues.",
        history
      );
      setMsgs(p=>[...p,{r:"a",t:reply}]);
    } catch { setMsgs(p=>[...p,{r:"a",t:"Erro de conexão. 🙏"}]); }
    finally { setChatLoad(false); }
  };

  const sel = INTENTIONS.find(i=>i.id===intention);

  if (screen==="loading") return (
    <div style={{textAlign:"center",padding:"70px 0",animation:"fadeUp 0.4s ease"}}>
      <div style={{fontSize:36,display:"inline-block",animation:"spin 4s linear infinite",color:C.gold}}>✦</div>
      <p style={{marginTop:20,color:C.textDim,fontSize:15,letterSpacing:2}}>Elevando sua prece...</p>
      <p style={{marginTop:8,color:C.textFaint,fontSize:13,fontStyle:"italic"}}>"A prece é a respiração da alma."</p>
    </div>
  );

  if (screen==="prayer") return (
    <div style={{animation:"fadeUp 0.5s ease"}}>
      <audio ref={audioRef} src={audioUrl||""} onEnded={()=>setPlaying(false)} style={{display:"none"}}/>
      {error&&<div style={{background:"rgba(180,60,60,0.1)",border:"1px solid rgba(200,80,80,0.25)",borderRadius:10,padding:"10px 14px",marginBottom:12,fontSize:12,color:"rgba(240,160,160,0.9)"}}>⚠️ {error}</div>}


      <div style={{background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:18,padding:"24px",marginBottom:14,overflowX:"hidden",width:"100%",boxSizing:"border-box"}}>
        <div style={{textAlign:"center",opacity:0.25,marginBottom:14,fontSize:12,letterSpacing:10,color:C.gold}}>✦ ✦ ✦</div>
        <WordReveal text={prayer} style={{color:C.text}}/>
        <div style={{textAlign:"center",opacity:0.25,marginTop:14,fontSize:12,letterSpacing:10,color:C.gold}}>✦ ✦ ✦</div>
      </div>

      <div style={{display:"flex",gap:8,marginBottom:4}}>
        <Btn onClick={playAudio} variant="primary">
          {playing?"⏸ Pausar":"▶ Ouvir"}
        </Btn>
        <ShareBtn text={prayer} name={sel?.label} relation="Prece Espírita"/>
        <Btn onClick={()=>navigator.clipboard?.writeText(prayer)}>📋 Copiar</Btn>
        <Btn onClick={()=>{setScreen("pick");setIntention(null);setPrayer("");setMsgs([]);setAudioUrl(null);window.speechSynthesis?.cancel();setPlaying(false);}}>🔄 Nova</Btn>
      </div>
      <p style={{margin:"0 0 12px",fontSize:10,color:C.textFaint,textAlign:"center"}}>
        {audioUrl ? "🎙️ Voz ElevenLabs" : "🔊 Voz do dispositivo"}
      </p>

      {/* Chat */}
      <div style={{background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:16}}>
        <div style={{padding:"10px 14px",borderBottom:`1px solid ${C.border}`,fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>⭐ Orientador Espiritual</div>
        <div style={{height:210,overflowY:"auto",padding:12}}>
          {msgs.map((m,i)=>(
            <div key={i} style={{display:"flex",justifyContent:m.r==="u"?"flex-end":"flex-start",marginBottom:10}}>
              <div style={{maxWidth:"85%",padding:"10px 14px",borderRadius:14,background:m.r==="u"?C.bgCard2:C.bgCard,border:`1px solid ${m.r==="u"?C.border2:C.border}`,fontSize:14,lineHeight:1.7,color:m.r==="u"?C.goldSoft:C.text,whiteSpace:"pre-wrap"}}>{m.t}</div>
            </div>
          ))}
          {chatLoad&&<div style={{color:C.textFaint,fontSize:13,fontStyle:"italic"}}>Meditando... 🙏</div>}
          <div ref={endRef}/>
        </div>
        <div style={{display:"flex",gap:6,padding:"0 10px 6px",flexWrap:"wrap"}}>
          {["Como me sinto?","Reencarnação","Reforma íntima","Perispírito"].map(q=>(
            <button key={q} onClick={()=>setChatIn(q)} style={{background:"rgba(255,255,255,0.02)",border:`1px solid ${C.border}`,borderRadius:10,padding:"4px 10px",cursor:"pointer",color:C.textFaint,fontSize:12}}>{q}</button>
          ))}
        </div>
        <div style={{display:"flex",gap:8,padding:"8px 10px 12px",alignItems:"center"}}>
          <input value={chatIn} onChange={e=>setChatIn(e.target.value)} onKeyDown={e=>e.key==="Enter"&&sendChat()} placeholder="Pergunte ou compartilhe..." style={{flex:1,background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:16,padding:"10px 14px",color:C.text,fontSize:14,outline:"none"}}/>
          <button onClick={sendChat} disabled={chatLoad||!chatIn.trim()} style={{background:`linear-gradient(135deg,#3a2808,#6a3c10)`,border:"none",borderRadius:"50%",width:40,height:40,cursor:"pointer",flexShrink:0,opacity:(chatLoad||!chatIn.trim())?0.35:1,color:C.gold,fontSize:18}}>→</button>
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <ApiWarning service="anthropic"/>
      {error&&<div style={{background:"rgba(180,60,60,0.1)",border:"1px solid rgba(200,80,80,0.25)",borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:13,color:"rgba(240,160,160,0.8)"}}>{error}</div>}
      <p style={{textAlign:"center",fontSize:11,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",marginBottom:16,fontFamily:"'Cinzel',Georgia,serif"}}>Escolha sua intenção</p>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:16}}>
        {INTENTIONS.map(i=>(
          <button key={i.id} onClick={()=>setIntention(i.id)} style={{
            background:intention===i.id?C.bgCard2:"rgba(255,255,255,0.02)",
            border:intention===i.id?`1px solid ${C.border2}`:`1px solid ${C.border}`,
            borderRadius:12,padding:"13px 8px",cursor:"pointer",textAlign:"center",lineHeight:1.4,transition:"all 0.2s",
          }}>
            <div style={{fontSize:18,marginBottom:4}}>{i.emoji}</div>
            <div style={{fontSize:12,color:intention===i.id?C.gold:C.textDim}}>{i.label}</div>
          </button>
        ))}
      </div>
      <input value={forWhom} onChange={e=>setForWhom(e.target.value)} placeholder="Dedicar a (opcional)..." style={{width:"100%",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:10,padding:"11px 14px",color:C.text,fontSize:14,outline:"none",marginBottom:14,display:"block"}}/>
      <button onClick={generate} disabled={!intention||loading} style={{
        width:"100%",padding:"16px",borderRadius:13,cursor:intention?"pointer":"not-allowed",
        background:intention?"linear-gradient(135deg,#3a2808,#6a3c10)":"rgba(40,25,5,0.3)",
        border:`1px solid ${intention?C.border2:C.border}`,
        color:intention?C.goldSoft:"rgba(180,140,60,0.25)",fontSize:14,letterSpacing:3,
        fontFamily:"'Cinzel',Georgia,serif",textTransform:"uppercase",
      }}>
        🙏 Elevar Prece
      </button>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  ORAÇÃO CATÓLICA
// ═══════════════════════════════════════════════════════════════════
const ORACAO_INTENTIONS = [
  {id:"falecido",  emoji:"🕊️", label:"Por Alma do Falecido"},
  {id:"doente",    emoji:"🏥",  label:"Por Cura do Doente"},
  {id:"familia",   emoji:"👨‍👩‍👧", label:"Pela Família"},
  {id:"gratidao",  emoji:"🙏",  label:"Ação de Graças"},
  {id:"angustia",  emoji:"💙",  label:"Na Angústia"},
  {id:"mae",       emoji:"🌹",  label:"Intercessão de Maria"},
  {id:"protecao",  emoji:"🛡️",  label:"Proteção Divina"},
  {id:"paz",       emoji:"☮️",  label:"Pela Paz"},
];

function OracaoTab() {
  const [screen,setScreen]   = useState("pick");
  const [intention,setIntention] = useState(null);
  const [forWhom,setForWhom] = useState("");
  const [prayer,setPrayer]   = useState("");
  const [loading,setLoading] = useState(false);
  const [error,setError]     = useState("");
  const [msgs,setMsgs]       = useState([]);
  const [chatIn,setChatIn]   = useState("");
  const [chatLoad,setChatLoad] = useState(false);
  const [audioUrl,setAudioUrl] = useState(null);
  const [playing,setPlaying] = useState(false);
  const endRef  = useRef(null);
  const audioRef = useRef(null);

  useEffect(()=>{ endRef.current?.scrollIntoView({behavior:"smooth"}); },[msgs]);

  const generate = async () => {
    if (!intention) return;
    setLoading(true); setError(""); setScreen("loading");
    const sel = ORACAO_INTENTIONS.find(i=>i.id===intention);
    try {
      const text = await claudeAI(
        "Voce e um guia espiritual versado na tradicao catolica brasileira, conhecedor dos santos, das orações tradicionais, da liturgia e do Evangelho. Escreve orações autenticas, amorosas e poeticamente belas, no estilo da espiritualidade catolica brasileira. Use linguagem acessivel e reconfortante. Retorne APENAS o texto da oração, sem titulo, sem explicações.",
        `${forWhom?`Dedicada a ${forWhom}. `:""}Escreva uma oração católica brasileira sobre "${sel.label}". 150-200 palavras em português. Use vocabulário católico: alma, paraíso, graça, intercessão, misericórdia, Pai Nosso, Nossa Senhora. Evite termos espíritas.`
      );
      setPrayer(text);
      setMsgs([{r:"a",t:"Que Deus te abençoe. 🙏\n\nEstou aqui como guia espiritual. Se quiser, podemos rezar juntos, refletir sobre o Evangelho, ou simplesmente conversar sobre o que está no seu coração."}]);

      if (ELEVENLABS_KEY && !ELEVENLABS_KEY.includes("PASTE")) {
        try {
          const voiceList = await fetchElevenLabsVoices();
          const voiceId = voiceList?.[0]?.id || VOICE_LIBRARY[0].id;
          const url = await elevenLabsTTS(text, voiceId);
          setAudioUrl(url);
        } catch(e) { console.warn("TTS:",e.message); setAudioUrl(null); }
      }

      setScreen("prayer");
    } catch(e) { setError(e.message); setScreen("pick"); }
    finally { setLoading(false); }
  };

  const playAudio = () => {
    if (audioRef.current && audioUrl) {
      if (playing) { audioRef.current.pause(); setPlaying(false); }
      else { audioRef.current.play(); setPlaying(true); }
      return;
    }
    if (!("speechSynthesis" in window)) return;
    if (playing) { window.speechSynthesis.cancel(); setPlaying(false); return; }
    const u = new SpeechSynthesisUtterance(prayer);
    u.lang="pt-BR"; u.rate=0.82; u.pitch=0.9;
    u.onend=()=>setPlaying(false);
    window.speechSynthesis.speak(u); setPlaying(true);
  };

  const sendChat = async () => {
    if (!chatIn.trim()||chatLoad) return;
    const msg=chatIn.trim().slice(0,500); setChatIn("");
    const next=[...msgs,{r:"u",t:msg}];
    setMsgs(next); setChatLoad(true);
    // Crisis detection
    if (detectCrisis(msg)) {
      setMsgs(p=>[...p,{r:"a",t:CRISIS_RESPONSE}]);
      setChatLoad(false); return;
    }
    try {
      const history = next.map(m => `${m.r==="u"?"Usuário":"Guia"}: ${m.t}`).join("\n\n");
      const reply = await claudeAI(
        "Voce e um guia espiritual catholico amoroso e sábio, versado no Evangelho, nos santos e na tradicao catholica brasileira. Responda com caridade, esperança e fé. Cite versículos ou santos quando relevante. 80-150 palavras em portugues.",
        history
      );
      setMsgs(p=>[...p,{r:"a",t:reply}]);
    } catch { setMsgs(p=>[...p,{r:"a",t:"Que Deus te abençoe. 🙏"}]); }
    finally { setChatLoad(false); }
  };

  const sel = ORACAO_INTENTIONS.find(i=>i.id===intention);

  // Catholic warm gold/cream color overrides
  const CC = {
    accent:  "#b89050",
    accentS: "#d4b070",
    bg:      "rgba(255,240,200,0.03)",
    bg2:     "rgba(180,140,60,0.07)",
    border:  "rgba(180,140,60,0.16)",
    border2: "rgba(200,160,70,0.3)",
  };

  if (screen==="loading") return (
    <div style={{textAlign:"center",padding:"70px 0",animation:"fadeUp 0.4s ease"}}>
      <div style={{fontSize:38,marginBottom:16}}>✝️</div>
      <p style={{color:C.textDim,fontSize:15,letterSpacing:2}}>Elevando sua oração...</p>
      <p style={{margin:"10px 0 0",color:C.textFaint,fontSize:13,fontStyle:"italic"}}>"Pedis e recebereis." — João 16:24</p>
    </div>
  );

  if (screen==="prayer") return (
    <div style={{animation:"fadeUp 0.5s ease"}}>
      <audio ref={audioRef} src={audioUrl||""} onEnded={()=>setPlaying(false)} style={{display:"none"}}/>

      {/* Cross ornament */}
      <div style={{textAlign:"center",marginBottom:16}}>
        <span style={{fontSize:32,color:CC.accent,opacity:0.6}}>✝</span>
        <p style={{margin:"6px 0 0",fontSize:10,color:C.textFaint,letterSpacing:3,fontFamily:"'Cinzel',Georgia,serif"}}>
          {sel?.label?.toUpperCase()}
          {forWhom ? ` · ${forWhom.toUpperCase()}` : ""}
        </p>
      </div>

      <div style={{background:CC.bg,border:`1px solid ${CC.border}`,borderRadius:18,padding:"24px",marginBottom:14,overflowX:"hidden",boxSizing:"border-box"}}>
        <div style={{textAlign:"center",marginBottom:12}}>
          <span style={{fontSize:10,color:CC.accent,opacity:0.4,letterSpacing:8}}>✦ ✦ ✦</span>
        </div>
        <WordReveal text={prayer} style={{color:C.text}}/>
        <div style={{textAlign:"center",marginTop:12}}>
          <span style={{fontSize:10,color:CC.accent,opacity:0.4,letterSpacing:8}}>✦ ✦ ✦</span>
        </div>
      </div>

      <div style={{display:"flex",gap:8,marginBottom:14}}>
        <Btn onClick={playAudio} style={{background:`linear-gradient(135deg,#3a2808,#6a4010)`,border:`1px solid ${CC.border2}`,color:CC.accentS}}>
          {playing?"⏸ Pausar":"▶ Ouvir"}
        </Btn>
        <ShareBtn text={prayer} name={sel?.label} relation="Oração Católica · vozdomeu.com.br"/>
        <Btn onClick={()=>navigator.clipboard?.writeText(prayer)}>📋 Copiar</Btn>
        <Btn onClick={()=>{setScreen("pick");setIntention(null);setPrayer("");setMsgs([]);setAudioUrl(null);}}>🔄 Nova</Btn>
      </div>

      {/* Spiritual guide chat */}
      <div style={{background:CC.bg,border:`1px solid ${CC.border}`,borderRadius:16}}>
        <div style={{padding:"10px 14px",borderBottom:`1px solid ${CC.border}`,fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>
          ✝️ Guia Espiritual
        </div>
        <div style={{height:210,overflowY:"auto",padding:12}}>
          {msgs.map((m,i)=>(
            <div key={i} style={{display:"flex",justifyContent:m.r==="u"?"flex-end":"flex-start",marginBottom:10}}>
              <div style={{maxWidth:"85%",padding:"10px 14px",borderRadius:14,
                background:m.r==="u"?CC.bg2:CC.bg,
                border:`1px solid ${m.r==="u"?CC.border2:CC.border}`,
                fontSize:14,lineHeight:1.7,
                color:m.r==="u"?CC.accentS:C.text,
                whiteSpace:"pre-wrap"}}>{m.t}</div>
            </div>
          ))}
          {chatLoad&&<div style={{color:C.textFaint,fontSize:13,fontStyle:"italic"}}>Rezando... 🙏</div>}
          <div ref={endRef}/>
        </div>
        <div style={{display:"flex",gap:6,padding:"0 10px 6px",flexWrap:"wrap"}}>
          {["Estou com saudade","Me sinto culpado","Como perdoar?","Versículo de conforto"].map(q=>(
            <button key={q} onClick={()=>setChatIn(q)} style={{background:"rgba(255,255,255,0.02)",border:`1px solid ${CC.border}`,borderRadius:10,padding:"4px 10px",cursor:"pointer",color:C.textFaint,fontSize:12}}>{q}</button>
          ))}
        </div>
        <div style={{display:"flex",gap:8,padding:"8px 10px 12px",alignItems:"center"}}>
          <input value={chatIn} onChange={e=>setChatIn(e.target.value)} onKeyDown={e=>e.key==="Enter"&&sendChat()}
            placeholder="Fale com o guia espiritual..."
            style={{flex:1,background:CC.bg,border:`1px solid ${CC.border}`,borderRadius:16,padding:"10px 14px",color:C.text,fontSize:14,outline:"none"}}/>
          <button onClick={sendChat} disabled={chatLoad||!chatIn.trim()} style={{background:`linear-gradient(135deg,#3a2808,#6a3c10)`,border:"none",borderRadius:"50%",width:40,height:40,cursor:"pointer",flexShrink:0,opacity:(chatLoad||!chatIn.trim())?0.35:1,color:CC.accentS,fontSize:18}}>→</button>
        </div>
      </div>
    </div>
  );

  // PICK SCREEN
  return (
    <div>
      <ApiWarning service="anthropic"/>
      {error&&<div style={{background:"rgba(180,60,60,0.1)",border:"1px solid rgba(200,80,80,0.25)",borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:13,color:"rgba(240,160,160,0.8)"}}>{error}</div>}

      {/* Cross header */}
      <div style={{textAlign:"center",marginBottom:20}}>
        <div style={{fontSize:32,color:CC.accent,opacity:0.5}}>✝</div>
        <p style={{margin:"6px 0 0",fontSize:11,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>Oração Católica</p>
        <p style={{margin:"4px 0 0",fontSize:13,color:C.textFaint,fontStyle:"italic"}}>"Onde dois ou três estiverem reunidos em meu nome, ali estarei."</p>
        <p style={{margin:"2px 0 0",fontSize:10,color:"rgba(200,160,80,0.3)",letterSpacing:1}}>— Mateus 18:20</p>
      </div>

      <p style={{fontSize:11,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",marginBottom:12,fontFamily:"'Cinzel',Georgia,serif",textAlign:"center"}}>Escolha sua intenção</p>

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:16}}>
        {ORACAO_INTENTIONS.map(i=>(
          <button key={i.id} onClick={()=>setIntention(i.id)} style={{
            background:intention===i.id?CC.bg2:"rgba(255,255,255,0.02)",
            border:intention===i.id?`1px solid ${CC.border2}`:`1px solid ${CC.border}`,
            borderRadius:12,padding:"13px 8px",cursor:"pointer",textAlign:"center",lineHeight:1.4,transition:"all 0.2s",
          }}>
            <div style={{fontSize:18,marginBottom:4}}>{i.emoji}</div>
            <div style={{fontSize:12,color:intention===i.id?CC.accentS:C.textDim}}>{i.label}</div>
          </button>
        ))}
      </div>

      <input value={forWhom} onChange={e=>setForWhom(e.target.value)}
        placeholder="Dedicar a (opcional)..."
        style={{width:"100%",background:CC.bg,border:`1px solid ${CC.border}`,borderRadius:10,padding:"11px 14px",color:C.text,fontSize:14,outline:"none",marginBottom:14,display:"block"}}/>

      <button onClick={generate} disabled={!intention||loading} style={{
        width:"100%",padding:"16px",borderRadius:13,cursor:intention?"pointer":"not-allowed",
        background:intention?"linear-gradient(135deg,#3a2808,#6a3c10)":"rgba(40,25,5,0.3)",
        border:`1px solid ${intention?CC.border2:CC.border}`,
        color:intention?CC.accentS:"rgba(180,140,60,0.25)",fontSize:14,letterSpacing:3,
        fontFamily:"'Cinzel',Georgia,serif",textTransform:"uppercase",
      }}>
        ✝️ Elevar Oração
      </button>

      {/* Subtle note */}
      <p style={{margin:"16px 0 0",textAlign:"center",fontSize:11,color:C.textFaint,fontStyle:"italic"}}>
        Nossa Senhora de Aparecida, padroeira do Brasil, interceda por nós. 🌹
      </p>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  ORÁCULOS
// ═══════════════════════════════════════════════════════════════════
function OraclesTab() {
  const [wallet,setWallet] = useState(null);
  const [balance,setBalance] = useState(1000);
  const [burned,setBurned] = useState(0);
  const [txs,setTxs] = useState([]);
  const [selected,setSelected] = useState(null);
  const [busy,setBusy] = useState(false);
  const [result,setResult] = useState("");
  const [apiKey] = useState("oracle_"+Math.random().toString(36).slice(2,18));

  const connect = () => setWallet("7xKp..."+Math.random().toString(36).slice(2,6).toUpperCase());

  const invoke = async (svc) => {
    if (!wallet||balance<svc.cost) return;
    setBusy(true); setResult("");
    const map={
      prayer:"Gere uma prece espirita elevada de 80 palavras em portugues.",
      memorial:"Gere uma prece memorial espirita de 80 palavras em portugues.",
      counsel:"Compartilhe reflexao espirita de 80 palavras sobre evolucao espiritual em portugues.",
      voice:"Confirmacao Voz do Meu: prece de 80 palavras para processamento ElevenLabs + D-ID.",
      evangelho:"Gere prece de abertura do Evangelho no Lar de 80 palavras em portugues.",
      batch:"Gere 3 preces espiritas distintas de 50 palavras cada em portugues.",
    };
    try {
      const text = await claudeAI("Voce e orientador espiritual erudito na Doutrina Espirita de Allan Kardec.",map[svc.id]);
      const burn=+(svc.cost*svc.burn).toFixed(3);
      setBalance(b=>b-svc.cost); setBurned(b=>+(b+burn).toFixed(3));
      const txId="TX"+Math.random().toString(36).slice(2,10).toUpperCase();
      setTxs(t=>[{id:txId,label:svc.label,cost:svc.cost,burn,time:new Date().toLocaleTimeString()},...t.slice(0,4)]);
      setResult(text); setSelected(null);
    } catch(e) { setResult("Erro: "+e.message); }
    finally { setBusy(false); }
  };

  if (!wallet) return (
    <div style={{textAlign:"center"}}>
      <ApiWarning service="anthropic"/>
      <div style={{background:"rgba(60,40,180,0.06)",border:"1px solid rgba(100,70,220,0.18)",borderRadius:20,padding:"28px 20px"}}>
        <div style={{fontSize:40,marginBottom:12}}>🔮</div>
        <h3 style={{fontSize:16,fontWeight:400,color:"rgba(180,140,240,0.8)",fontFamily:"'Cinzel',Georgia,serif",letterSpacing:2,marginBottom:6}}>Portal Oráculos</h3>
        <p style={{fontSize:11,color:"rgba(160,120,220,0.4)",letterSpacing:1,marginBottom:4}}>$MONET · Solana · SPL Token</p>
        <p style={{fontSize:13,color:"rgba(160,120,220,0.45)",lineHeight:1.7,marginBottom:20}}>Agentes de IA conectam aqui para acessar serviços espirituais do Ecossistema Monet de Bahia.</p>
        <button onClick={connect} style={{padding:"13px 28px",borderRadius:12,background:"linear-gradient(135deg,#3a1860,#6a30b8)",border:"none",cursor:"pointer",color:"white",fontSize:13,letterSpacing:2,fontFamily:"'Cinzel',Georgia,serif"}}>👻 Conectar Phantom</button>
        <div style={{marginTop:20,padding:"14px",background:"rgba(15,8,35,0.5)",borderRadius:12,textAlign:"left"}}>
          <p style={{margin:"0 0 8px",fontSize:10,color:"rgba(130,100,180,0.4)",letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>📡 Oracle Gateway API</p>
          <code style={{fontSize:11,color:"#70b870",display:"block",marginBottom:4}}>POST oracle.monetdebahia.com/v1/invoke</code>
          <code style={{fontSize:10,color:"rgba(130,100,160,0.4)",display:"block",marginBottom:4}}>Authorization: Bearer {"<MONET_API_KEY>"}</code>
          <code style={{fontSize:10,color:"rgba(110,80,140,0.35)",display:"block"}}>{`{"service":"prayer","intention":"reforma","tokens":5}`}</code>
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginBottom:14}}>
        {[
          {label:"Saldo",    value:`${balance} $M`, color:"#70c870"},
          {label:"Queimado", value:`${burned} $M`,  color:"#d09050"},
          {label:"Carteira", value:wallet,           color:"#8090d8"},
        ].map(s=>(
          <div key={s.label} style={{background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:12,padding:"10px 6px",textAlign:"center"}}>
            <div style={{fontSize:13,fontWeight:"bold",color:s.color}}>{s.value}</div>
            <div style={{fontSize:9,color:C.textFaint,letterSpacing:1,marginTop:2,fontFamily:"'Cinzel',Georgia,serif"}}>{s.label.toUpperCase()}</div>
          </div>
        ))}
      </div>

      <p style={{fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",marginBottom:8,fontFamily:"'Cinzel',Georgia,serif"}}>Serviços Disponíveis</p>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:14}}>
        {ORACLE_SERVICES.map(s=>(
          <button key={s.id} onClick={()=>setSelected(selected?.id===s.id?null:s)} style={{
            background:selected?.id===s.id?C.bgCard2:C.bgCard,
            border:selected?.id===s.id?`1px solid ${C.border2}`:`1px solid ${C.border}`,
            borderRadius:13,padding:"12px 8px",cursor:"pointer",textAlign:"center",opacity:balance<s.cost?0.4:1,
          }}>
            <div style={{fontSize:20,marginBottom:3}}>{s.emoji}</div>
            <div style={{fontSize:11,color:C.textDim,marginBottom:3}}>{s.label}</div>
            <div style={{fontSize:12,color:"#70c870",fontWeight:"bold"}}>{s.cost} $M</div>
            <div style={{fontSize:9,color:"rgba(210,140,60,0.5)",marginTop:1}}>queima {+(s.cost*s.burn).toFixed(2)} $M</div>
          </button>
        ))}
      </div>

      {selected&&(
        <div style={{background:C.bgCard2,border:`1px solid ${C.border2}`,borderRadius:14,padding:"14px",marginBottom:12}}>
          <p style={{margin:"0 0 4px",fontSize:14,color:C.gold}}>{selected.emoji} {selected.label}</p>
          <p style={{margin:"0 0 10px",fontSize:12,color:C.textFaint}}>{selected.desc}</p>
          <div style={{display:"flex",justifyContent:"space-between",fontSize:11,color:C.textFaint,marginBottom:10}}>
            <span>Custo: {selected.cost} $MONET</span>
            <span>Queima: {+(selected.cost*selected.burn).toFixed(2)} $MONET</span>
          </div>
          <button onClick={()=>invoke(selected)} disabled={busy} style={{width:"100%",padding:"12px",borderRadius:11,background:"linear-gradient(135deg,#3a1860,#6030a8)",border:"none",cursor:"pointer",color:"#e0d0ff",fontSize:12,letterSpacing:2,opacity:busy?0.5:1,fontFamily:"'Cinzel',Georgia,serif"}}>
            {busy?"Processando... 🙏":`✦ Invocar por ${selected.cost} $M`}
          </button>
        </div>
      )}

      {result&&(
        <div style={{background:"rgba(20,40,20,0.2)",border:"1px solid rgba(60,140,60,0.2)",borderRadius:13,padding:"14px",marginBottom:12}}>
          <p style={{margin:"0 0 6px",fontSize:10,color:"rgba(80,170,80,0.5)",letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>✓ Resposta do Oráculo</p>
          <p style={{margin:0,fontSize:14,lineHeight:1.8,color:"#b8d8b8",whiteSpace:"pre-wrap"}}>{result}</p>
          <div style={{marginTop:10}}>
            <ShareBtn text={result} name="Oráculo" relation="oracle.monetdebahia.com"/>
          </div>
        </div>
      )}

      {txs.length>0&&(
        <div>
          <p style={{fontSize:10,color:C.textFaint,letterSpacing:2,textTransform:"uppercase",marginBottom:6,fontFamily:"'Cinzel',Georgia,serif"}}>Histórico</p>
          {txs.map(tx=>(
            <div key={tx.id} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"7px 10px",background:C.bgCard,border:`1px solid ${C.border}`,borderRadius:9,marginBottom:5,fontSize:11}}>
              <span style={{color:"rgba(120,100,180,0.6)",fontFamily:"monospace"}}>{tx.id}</span>
              <span style={{color:"#70c870"}}>−{tx.cost} $M</span>
              <span style={{color:C.textFaint}}>{tx.time}</span>
            </div>
          ))}
        </div>
      )}

      <div style={{marginTop:14,background:"rgba(10,5,25,0.6)",border:"1px solid rgba(60,40,120,0.2)",borderRadius:12,padding:"14px"}}>
        <p style={{margin:"0 0 6px",fontSize:10,color:"rgba(120,90,180,0.38)",letterSpacing:2,textTransform:"uppercase",fontFamily:"'Cinzel',Georgia,serif"}}>📡 Oracle Gateway API</p>
        <code style={{fontSize:11,color:"#70b870",display:"block",marginBottom:4}}>POST oracle.monetdebahia.com/v1/invoke</code>
        <code style={{fontSize:10,color:"rgba(130,100,160,0.38)",display:"block",marginBottom:4}}>X-MONET-API-KEY: {apiKey}</code>
        <code style={{fontSize:10,color:"rgba(100,80,140,0.3)",display:"block"}}>{`{"service":"prayer","intention":"reforma","tokens":5}`}</code>
      </div>
    </div>
  );
}
