const { useState, useEffect } = React;

/* ─────────────────────────────────────────────
   MENTALIDAD LIBRE — App Interactiva
   Companion app de la serie Free Mindset / Mentalidad Libre
   ───────────────────────────────────────────── */

const T = {
  es: {
    appTitle: "Mentalidad Libre",
    appSubtitle: "Finanzas para tu familia",
    tagline: "Aprende a invertir, educa a tus hijos y asegura su futuro",
    langSwitch: "English",
    byline: "Basado en la serie Mentalidad Libre · Miguel A. Sáez",
    selectProfile: "¿Quién eres hoy?",
    profiles: {
      kid: "🧒 Hijo/a (3–8)",
      teen: "🎒 Joven (9–13)",
      older: "🚀 Adolescente (14–18)",
      parent: "👨‍👩‍👧 Padre/Madre",
    },
    tabs: { huchas: "🏺 Las 3 Huchas", method: "📊 Método 60/20/20", retos: "🎯 Mini-Retos", learn: "📖 Del Libro" },
    huchas: {
      title: "El Bote de las Tres Cajas",
      subtitle: "Cada euro tiene una misión. Reparte tu dinero entre las tres huchas.",
      gastar: "Gastar",
      ahorrar: "Ahorrar",
      compartir: "Compartir",
      total: "Dinero disponible",
      addMoney: "Añadir dinero",
      amount: "Cantidad (€)",
      distribute: "Repartir",
      tip: "Recuerda: no se trata de decir \"no tenemos dinero\", sino \"ahora estamos priorizando otra cosa\".",
      goalLabel: "Mi objetivo de ahorro",
      goalPlaceholder: "Ej: Bicicleta nueva",
      goalAmount: "¿Cuánto cuesta? (€)",
      goalWeekly: "Ahorro semanal (€)",
      setGoal: "Fijar objetivo",
      weeksLeft: "semanas para lograrlo",
      saved: "Ahorrado",
      of: "de",
      goalAchieved: "¡Objetivo conseguido! 🎉",
      clearGoal: "Nuevo objetivo",
      bookRef: "Cap. 8 — \"El bote de las tres cajas\": gastar, ahorrar y compartir. Así aprenden a planificar sin darse cuenta.",
    },
    method: {
      title: "Método 60/20/20",
      subtitle: "El sistema de gestión familiar Mentalidad Libre",
      vivir: "Vivir",
      vivirDesc: "Vivienda, suministros, transporte, alimentación, colegios, seguros",
      crecer: "Crecer",
      crecerDesc: "Ahorro e inversión: fondos indexados, ETFs, inmuebles, cuentas infantiles",
      libertad: "Libertad",
      libertadDesc: "Experiencias, formación, ocio, viajes, proyectos personales",
      income: "Ingresos netos mensuales (€)",
      calculate: "Calcular distribución",
      result: "Tu distribución mensual",
      bookRef: "Cap. 6 — \"Cada euro tiene una función definida y visible. El sistema da estructura, pero también flexibilidad.\"",
      autoTip: "Automatiza las transferencias el día que cobres. El dinero que no ves, no lo gastas.",
      teenTitle: "Tu Presupuesto 50/30/20",
      teenSubtitle: "Aprende a gestionar tu propio dinero como un futuro inversor",
      necesidades: "Necesidades",
      necesidadesDesc: "Transporte, material escolar, comidas",
      deseos: "Deseos",
      deseosDesc: "Ocio, ropa, tecnología, salidas",
      ahorro: "Ahorro / Inversión",
      ahorroDesc: "Tu futuro empieza aquí",
      teenIncome: "Tu dinero disponible (€)",
      teenBookRef: "Cap. 8 — \"No es cuánto ganas, es cuánto haces crecer lo que ya tienes.\"",
    },
    retos: {
      title: "Mini-Retos para Padres",
      subtitle: "Pequeños desafíos semanales inspirados en el libro",
      accept: "¡Acepto el reto!",
      completed: "✓ Completado",
      streak: "Racha",
      retosCompleted: "retos completados",
      kidTitle: "Retos para Pequeños Ahorradores",
      kidSubtitle: "Aprende jugando con el dinero",
      teenTitle: "Retos para Jóvenes Inversores",
      teenSubtitle: "Da tus primeros pasos hacia la libertad",
    },
    learn: {
      title: "Del Libro",
      subtitle: "Ideas clave de la serie Mentalidad Libre",
    },
    compoundTitle: "El Poder del Interés Compuesto",
    compoundSubtitle: "Invierte con constancia y deja que el tiempo trabaje por ti",
    compoundMonthly: "Inversión mensual (€)",
    compoundYears: "Años de inversión",
    compoundRate: "Rentabilidad anual (%)",
    compoundInvested: "Invertido",
    compoundGains: "Beneficios",
    compoundTotal: "Total",
    compoundBookRef: "Cap. 4 — \"El interés compuesto no solo multiplica el capital; multiplica el tiempo, la paciencia y la visión a largo plazo.\"",
    back: "← Volver",
  },
  en: {
    appTitle: "Free Mindset",
    appSubtitle: "Family Finance",
    tagline: "Learn to invest, educate your children and secure their future",
    langSwitch: "Español",
    byline: "Based on the Free Mindset series · Miguel A. Sáez",
    selectProfile: "Who are you today?",
    profiles: {
      kid: "🧒 Child (3–8)",
      teen: "🎒 Young (9–13)",
      older: "🚀 Teen (14–18)",
      parent: "👨‍👩‍👧 Parent",
    },
    tabs: { huchas: "🏺 3 Jars", method: "📊 60/20/20 Method", retos: "🎯 Mini-Challenges", learn: "📖 From the Book" },
    huchas: {
      title: "The Three Jars",
      subtitle: "Every euro has a mission. Distribute your money between the three jars.",
      gastar: "Spend",
      ahorrar: "Save",
      compartir: "Share",
      total: "Available money",
      addMoney: "Add money",
      amount: "Amount (€)",
      distribute: "Distribute",
      tip: "Remember: it's not about saying \"we don't have money\", but \"we're prioritizing something else right now\".",
      goalLabel: "My savings goal",
      goalPlaceholder: "E.g.: New bicycle",
      goalAmount: "How much does it cost? (€)",
      goalWeekly: "Weekly savings (€)",
      setGoal: "Set goal",
      weeksLeft: "weeks to reach it",
      saved: "Saved",
      of: "of",
      goalAchieved: "Goal achieved! 🎉",
      clearGoal: "New goal",
      bookRef: "Ch. 8 — \"The three jars: spend, save and share. They learn to plan without realizing it.\"",
    },
    method: {
      title: "60/20/20 Method",
      subtitle: "The Free Father's family management system",
      vivir: "Live",
      vivirDesc: "Housing, utilities, transport, food, school, insurance",
      crecer: "Grow",
      crecerDesc: "Savings & investment: index funds, ETFs, real estate, kids' accounts",
      libertad: "Freedom",
      libertadDesc: "Experiences, training, leisure, travel, personal projects",
      income: "Net monthly income (€)",
      calculate: "Calculate distribution",
      result: "Your monthly distribution",
      bookRef: "Ch. 6 — \"Every euro has a defined and visible function. The system provides structure, but also flexibility.\"",
      autoTip: "Automate transfers on payday. The money you don't see, you don't spend.",
      teenTitle: "Your 50/30/20 Budget",
      teenSubtitle: "Learn to manage your own money like a future investor",
      necesidades: "Needs",
      necesidadesDesc: "Transport, school supplies, meals",
      deseos: "Wants",
      deseosDesc: "Leisure, clothes, tech, outings",
      ahorro: "Savings / Investment",
      ahorroDesc: "Your future starts here",
      teenIncome: "Your available money (€)",
      teenBookRef: "Ch. 8 — \"It's not how much you earn, it's how much you grow what you already have.\"",
    },
    retos: {
      title: "Mini-Challenges for Parents",
      subtitle: "Weekly challenges inspired by the book",
      accept: "I accept!",
      completed: "✓ Completed",
      streak: "Streak",
      retosCompleted: "challenges completed",
      kidTitle: "Challenges for Little Savers",
      kidSubtitle: "Learn about money through play",
      teenTitle: "Challenges for Young Investors",
      teenSubtitle: "Take your first steps toward freedom",
    },
    learn: {
      title: "From the Book",
      subtitle: "Key ideas from Free Father, Investor Father",
    },
    compoundTitle: "The Power of Compound Interest",
    compoundSubtitle: "Invest consistently and let time work for you",
    compoundMonthly: "Monthly investment (€)",
    compoundYears: "Investment years",
    compoundRate: "Annual return (%)",
    compoundInvested: "Invested",
    compoundGains: "Gains",
    compoundTotal: "Total",
    compoundBookRef: "Ch. 4 — \"Compound interest doesn't just multiply capital; it multiplies time, patience and long-term vision.\"",
    back: "← Back",
  },
};

const parentRetos = [
  {
    es: "Durante una semana, sustituye \"no tenemos dinero\" por \"ahora estamos priorizando otra cosa\".",
    en: "For one week, replace \"we don't have money\" with \"we're prioritizing something else right now\".",
    chapter: "Cap. 8, Etapa 1",
  },
  {
    es: "Crea tu primera hoja de diagnóstico financiero: registra cada euro que entre y salga durante un mes.",
    en: "Create your first financial diagnosis sheet: record every euro in and out for a month.",
    chapter: "Cap. 6, Paso 1",
  },
  {
    es: "Programa una transferencia automática mensual a tu cuenta de ahorro, aunque sean 25€.",
    en: "Set up a monthly automatic transfer to your savings account, even if it's just €25.",
    chapter: "Cap. 6, Paso 4",
  },
  {
    es: "Comparte con tus hijos un resumen real de las finanzas del hogar adaptado a su edad.",
    en: "Share a real summary of household finances with your kids, adapted to their age.",
    chapter: "Cap. 8, Etapa 3",
  },
  {
    es: "Haz una lista de las 5 frases sobre dinero que más escuchaste de niño. ¿Siguen siendo ciertas?",
    en: "List the 5 money phrases you heard most as a child. Are they still true?",
    chapter: "Cap. 3, Pilar 1",
  },
  {
    es: "Identifica tus 'fugas invisibles': gastos pequeños que sumados son un agujero grande.",
    en: "Identify your 'invisible leaks': small expenses that add up to a big hole.",
    chapter: "Cap. 6, Paso 1",
  },
  {
    es: "No pagues directamente los caprichos de tus hijos esta semana. Propón: \"Si lo quieres, puedes usar tu dinero de la paga\".",
    en: "Don't directly pay for your children's whims this week. Suggest: \"If you want it, you can use your allowance.\"",
    chapter: "Cap. 8, Etapa 2",
  },
  {
    es: "Bloquea en tu calendario el primer sábado de enero como 'Día de revisión financiera familiar'.",
    en: "Block the first Saturday of January in your calendar as 'Family Financial Review Day'.",
    chapter: "Cap. 8, Revisión",
  },
];

const kidRetos = [
  { es: "Dibuja tu 'trabajo soñado' y cuéntale a papá o mamá por qué lo elegiste.", en: "Draw your 'dream job' and tell mom or dad why you chose it.", chapter: "Cap. 8, Etapa 1" },
  { es: "Juega a 'la tienda' en casa con monedas de verdad. ¡Tú pones los precios!", en: "Play 'store' at home with real coins. You set the prices!", chapter: "Cap. 5" },
  { es: "Busca monedas por la casa y ponlas en tu hucha de Ahorrar. ¡Cada moneda cuenta!", en: "Find coins around the house and put them in your Save jar. Every coin counts!", chapter: "Cap. 8, Etapa 1" },
  { es: "Elige algo que quieras comprar y calcula cuántas semanas necesitas para ahorrarlo.", en: "Choose something you want to buy and calculate how many weeks you need to save for it.", chapter: "Cap. 8, Etapa 2" },
];

const teenRetos = [
  { es: "Crea tu presupuesto 50/30/20 con tu paga de este mes. Revísalo al final del mes.", en: "Create your 50/30/20 budget with this month's allowance. Review it at month's end.", chapter: "Cap. 8, Etapa 3" },
  { es: "Elige un anuncio de redes sociales y desmoñtalo: ¿qué emoción intenta provocarte?", en: "Pick a social media ad and break it down: what emotion is it trying to trigger?", chapter: "Cap. 8, Educación digital" },
  { es: "Usa un simulador de inversión y compara: ¿qué pasa si inviertes 10€/mes desde hoy vs. dentro de 5 años?", en: "Use an investment simulator and compare: what happens if you invest €10/month from today vs. 5 years from now?", chapter: "Cap. 8, Inversión simulada" },
  { es: "Piensa en una habilidad que puedas ofrecer para ganar tu primer ingreso propio.", en: "Think of a skill you could offer to earn your first own income.", chapter: "Cap. 8, Ingresos propios" },
];

const learnContent = {
  kid: [
    { emoji: "🪙", es: { title: "El valor de las cosas", body: "Todo lo que tenemos costó tiempo y esfuerzo. Cuando cuidas tus juguetes y tus cosas, estás respetando ese esfuerzo. Las cosas buenas llevan tiempo." }, en: { title: "The value of things", body: "Everything we have cost time and effort. When you take care of your toys and things, you're respecting that effort. Good things take time." } },
    { emoji: "🏺", es: { title: "Las tres huchas", body: "Imagina que cada euro es un mensajero. Unos van a Gastar (cosas que necesitas hoy), otros a Ahorrar (cosas que quieres mañana) y otros a Compartir (ayudar a los demás). ¡Todos tienen una misión!" }, en: { title: "The three jars", body: "Imagine each euro is a messenger. Some go to Spend (things you need today), others to Save (things you want tomorrow) and others to Share (helping others). They all have a mission!" } },
    { emoji: "🌱", es: { title: "El dinero crece como un árbol", body: "Si plantas una semilla y la cuidas, crece. Con el dinero pasa igual: si lo guardas y lo cuidas, con el tiempo se hace más grande. ¡La paciencia es un superpoder!" }, en: { title: "Money grows like a tree", body: "If you plant a seed and care for it, it grows. Money works the same way: if you save it and care for it, over time it gets bigger. Patience is a superpower!" } },
  ],
  teen: [
    { emoji: "📊", es: { title: "La regla 50/30/20", body: "Divide tu dinero: 50% para lo que necesitas, 30% para lo que quieres, y 20% para ahorrar o invertir. Así nunca te quedarás sin opciones." }, en: { title: "The 50/30/20 rule", body: "Split your money: 50% for needs, 30% for wants, and 20% for saving or investing. That way you'll never run out of options." } },
    { emoji: "⏳", es: { title: "El tiempo es tu mejor aliado", body: "Si inviertes 10€ al mes desde los 13 años, a los 30 tendrás mucho más que quien empiece a los 25. El secreto no es la cantidad, es la constancia." }, en: { title: "Time is your best ally", body: "If you invest €10/month from age 13, by 30 you'll have much more than someone who starts at 25. The secret isn't the amount, it's consistency." } },
    { emoji: "🧠", es: { title: "Necesidades vs. Deseos", body: "Antes de comprar algo, pregúntate: ¿lo necesito o lo deseo? Ambos están bien, pero saber la diferencia te hará libre." }, en: { title: "Needs vs. Wants", body: "Before buying something, ask yourself: do I need it or want it? Both are fine, but knowing the difference will set you free." } },
    { emoji: "💡", es: { title: "El dinero no llega, se crea", body: "Puedes dar clases, ofrecer servicios, vender cosas que ya no uses. Ganar tu propio dinero te enseña algo que ningún libro puede: el valor del intercambio justo." }, en: { title: "Money doesn't arrive, it's created", body: "You can tutor, offer services, sell things you no longer use. Earning your own money teaches you something no book can: the value of fair exchange." } },
  ],
  older: [
    { emoji: "📈", es: { title: "Interés compuesto: tu superpoder", body: "Imagina que cada euro que inviertes genera más euros, y esos euros generan más. Con el tiempo, es como una bola de nieve que crece sola. Einstein lo llamó la fuerza más poderosa del universo." }, en: { title: "Compound interest: your superpower", body: "Imagine every euro you invest generates more euros, and those euros generate more. Over time, it's like a snowball that grows by itself. Einstein called it the most powerful force in the universe." } },
    { emoji: "🏗️", es: { title: "Activos vs. Pasivos", body: "Un activo te genera dinero (inversiones, negocio). Un pasivo te lo quita (deudas, coche). La clave: acumula activos, reduce pasivos." }, en: { title: "Assets vs. Liabilities", body: "An asset generates money (investments, business). A liability takes it away (debts, car). The key: accumulate assets, reduce liabilities." } },
    { emoji: "🎯", es: { title: "No trabajes por dinero", body: "Trabaja para construir opciones. Quien tiene opciones, tiene libertad. Y esa libertad se construye con conocimiento, control emocional y decisiones inteligentes." }, en: { title: "Don't work for money", body: "Work to build options. Those who have options have freedom. And that freedom is built with knowledge, emotional control, and smart decisions." } },
    { emoji: "⚠️", es: { title: "Invertir no es apostar", body: "Invertir es analizar, entender y tener paciencia. Apostar es poner dinero sin pensar. Aprende la diferencia ahora y te ahorrarás muchos disgustos." }, en: { title: "Investing isn't gambling", body: "Investing is analyzing, understanding and being patient. Gambling is putting money without thinking. Learn the difference now and you'll save yourself a lot of grief." } },
  ],
  parent: [
    { emoji: "🛡️", es: { title: "El fondo de emergencia", body: "Guarda entre 3 y 6 meses de gastos fijos. No es para invertir ni para mejorar rentabilidad. Su función es existir: estar disponible cuando algo inesperado ocurra." }, en: { title: "The emergency fund", body: "Save 3 to 6 months of fixed expenses. It's not for investing or improving returns. Its function is to exist: to be available when something unexpected happens." } },
    { emoji: "🔄", es: { title: "Automatiza todo", body: "La disciplina vence al impulso, pero la automatización vence a ambos. Programa tus transferencias, inversiones y ahorros para que funcionen sin que tengas que pensarlo." }, en: { title: "Automate everything", body: "Discipline beats impulse, but automation beats both. Schedule your transfers, investments and savings so they work without you having to think about it." } },
    { emoji: "👨‍👩‍👧‍👦", es: { title: "Enseña con el ejemplo", body: "Tus hijos no escuchan lo que dices, observan lo que haces. Si te ven organizar tus finanzas con calma, asociarán el dinero con equilibrio y libertad, no con estrés." }, en: { title: "Teach by example", body: "Your children don't listen to what you say, they watch what you do. If they see you organizing your finances calmly, they'll associate money with balance and freedom, not stress." } },
    { emoji: "📋", es: { title: "El Manual Financiero del Hogar", body: "Crea un documento con toda tu información financiera esencial. Tu mayor acto de amor financiero es dejar claridad, no confusión." }, en: { title: "The Home Financial Manual", body: "Create a document with all your essential financial information. Your greatest act of financial love is leaving clarity, not confusion." } },
    { emoji: "🧭", es: { title: "La mentalidad del Padre Libre", body: "Un padre libre no es el que deja de trabajar. Es el que elige en qué trabaja. No es el que huye del esfuerzo, sino el que entiende su sentido." }, en: { title: "The Free Father mindset", body: "A free father isn't one who stops working. It's one who chooses what to work on. Not one who runs from effort, but one who understands its meaning." } },
  ],
};

// ── Compound interest calculator ──
function calcCompound(monthly, years, rate) {
  const r = rate / 100 / 12;
  const n = years * 12;
  const total = monthly * ((Math.pow(1 + r, n) - 1) / r);
  const invested = monthly * n;
  return { total: Math.round(total), invested: Math.round(invested), gains: Math.round(total - invested) };
}

// ── Progress ring ──
function Ring({ pct, size = 90, stroke = 8, color = "#d4a017", bg = "#2a2520" }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const o = c - (Math.min(pct, 100) / 100) * c;
  return (
    <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={bg} strokeWidth={stroke} />
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
        strokeDasharray={c} strokeDashoffset={o} strokeLinecap="round"
        style={{ transition: "stroke-dashoffset 0.8s ease" }} />
      <text x={size/2} y={size/2} textAnchor="middle" dominantBaseline="central"
        fill="#f5e6c8" fontSize={size * 0.22} fontWeight="bold"
        style={{ transform: "rotate(90deg)", transformOrigin: "center" }}>
        {Math.round(pct)}%
      </text>
    </svg>
  );
}

// ── Bar chart for compound interest ──
function CompoundBars({ data, t }) {
  const max = data.total || 1;
  return (
    <div style={{ display: "flex", gap: "1rem", justifyContent: "center", alignItems: "flex-end", height: 160, margin: "1.5rem 0" }}>
      <div style={{ textAlign: "center", flex: 1 }}>
        <div style={{ background: "linear-gradient(to top, #8b7355, #a0896c)", borderRadius: "6px 6px 0 0", height: `${(data.invested / max) * 120}px`, transition: "height 0.6s ease", minHeight: 20, display: "flex", alignItems: "flex-end", justifyContent: "center", paddingBottom: 4 }}>
          <span style={{ color: "#fff", fontSize: "0.75rem", fontWeight: 600 }}>{data.invested.toLocaleString()}€</span>
        </div>
        <div style={{ fontSize: "0.75rem", color: "#a09080", marginTop: 6 }}>{t.compoundInvested}</div>
      </div>
      <div style={{ textAlign: "center", flex: 1 }}>
        <div style={{ background: "linear-gradient(to top, #b8860b, #daa520)", borderRadius: "6px 6px 0 0", height: `${(data.gains / max) * 120}px`, transition: "height 0.6s ease", minHeight: 20, display: "flex", alignItems: "flex-end", justifyContent: "center", paddingBottom: 4 }}>
          <span style={{ color: "#1a1510", fontSize: "0.75rem", fontWeight: 600 }}>{data.gains.toLocaleString()}€</span>
        </div>
        <div style={{ fontSize: "0.75rem", color: "#a09080", marginTop: 6 }}>{t.compoundGains}</div>
      </div>
      <div style={{ textAlign: "center", flex: 1 }}>
        <div style={{ background: "linear-gradient(to top, #228B22, #32CD32)", borderRadius: "6px 6px 0 0", height: `${120}px`, transition: "height 0.6s ease", display: "flex", alignItems: "flex-end", justifyContent: "center", paddingBottom: 4 }}>
          <span style={{ color: "#fff", fontSize: "0.85rem", fontWeight: 700 }}>{data.total.toLocaleString()}€</span>
        </div>
        <div style={{ fontSize: "0.75rem", color: "#a09080", marginTop: 6 }}>{t.compoundTotal}</div>
      </div>
    </div>
  );
}

function App() {
  const [lang, setLang] = useState("es");
  const [profile, setProfile] = useState(null);
  const [tab, setTab] = useState("huchas");

  // Huchas state
  const [huchaGastar, setHuchaGastar] = useState(0);
  const [huchaAhorrar, setHuchaAhorrar] = useState(0);
  const [huchaCompartir, setHuchaCompartir] = useState(0);
  const [addAmount, setAddAmount] = useState("");
  const [splitG, setSplitG] = useState(40);
  const [splitA, setSplitA] = useState(40);
  const [splitC, setSplitC] = useState(20);

  // Goal
  const [goalName, setGoalName] = useState("");
  const [goalAmount, setGoalAmount] = useState("");
  const [goalWeekly, setGoalWeekly] = useState("");
  const [activeGoal, setActiveGoal] = useState(null);

  // Method
  const [income, setIncome] = useState("");
  const [showMethodResult, setShowMethodResult] = useState(false);

  // Compound
  const [cMonthly, setCMonthly] = useState(200);
  const [cYears, setCYears] = useState(20);
  const [cRate, setCRate] = useState(7);

  // Retos
  const [completedRetos, setCompletedRetos] = useState([]);

  // Expanded learn card
  const [expandedLearn, setExpandedLearn] = useState(null);

  const t = T[lang];

  const addToHuchas = () => {
    const amt = parseFloat(addAmount);
    if (!amt || amt <= 0) return;
    setHuchaGastar(prev => prev + (amt * splitG / 100));
    setHuchaAhorrar(prev => prev + (amt * splitA / 100));
    setHuchaCompartir(prev => prev + (amt * splitC / 100));
    setAddAmount("");
  };

  const setGoalAction = () => {
    if (!goalName || !goalAmount || !goalWeekly) return;
    setActiveGoal({ name: goalName, amount: parseFloat(goalAmount), weekly: parseFloat(goalWeekly) });
    setGoalName(""); setGoalAmount(""); setGoalWeekly("");
  };

  const toggleReto = (idx) => {
    setCompletedRetos(prev => prev.includes(idx) ? prev.filter(i => i !== idx) : [...prev, idx]);
  };

  const compoundData = calcCompound(cMonthly, cYears, cRate);

  const currentRetos = profile === "kid" ? kidRetos : profile === "teen" || profile === "older" ? teenRetos : parentRetos;

  // ── Styles ──
  const css = `
    @import url('https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,600;0,700;1,400&family=DM+Sans:wght@400;500;600;700&display=swap');
    @keyframes fadeUp { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } }
    @keyframes pulse { 0%,100% { transform:scale(1); } 50% { transform:scale(1.03); } }
    * { box-sizing:border-box; margin:0; padding:0; }
    input[type=range] { accent-color: #b8860b; }
    input[type=range]::-webkit-slider-runnable-track { background: #3a3025; border-radius: 4px; height: 6px; }
  `;

  const page = {
    fontFamily: "'DM Sans', sans-serif",
    minHeight: "100vh",
    background: "#1a1510",
    color: "#f5e6c8",
    position: "relative",
  };

  const card = {
    background: "rgba(42, 37, 32, 0.85)",
    backdropFilter: "blur(8px)",
    borderRadius: "12px",
    border: "1px solid rgba(184, 134, 11, 0.15)",
    padding: "1.25rem",
    marginBottom: "0.85rem",
    animation: "fadeUp 0.5s ease forwards",
  };

  const btn = {
    fontFamily: "'DM Sans', sans-serif",
    background: "linear-gradient(135deg, #b8860b, #8b6914)",
    color: "#1a1510",
    border: "none",
    borderRadius: "8px",
    padding: "0.65rem 1.25rem",
    fontSize: "0.95rem",
    fontWeight: 600,
    cursor: "pointer",
    transition: "all 0.2s",
  };

  const input = {
    fontFamily: "'DM Sans', sans-serif",
    background: "rgba(26, 21, 16, 0.7)",
    border: "1px solid rgba(184, 134, 11, 0.25)",
    borderRadius: "8px",
    padding: "0.6rem 0.85rem",
    color: "#f5e6c8",
    fontSize: "0.95rem",
    width: "100%",
    outline: "none",
  };

  const tabBtn = (active) => ({
    fontFamily: "'DM Sans', sans-serif",
    background: active ? "linear-gradient(135deg, #b8860b, #8b6914)" : "rgba(42, 37, 32, 0.6)",
    color: active ? "#1a1510" : "#a09080",
    border: active ? "none" : "1px solid rgba(184, 134, 11, 0.12)",
    borderRadius: "8px",
    padding: "0.5rem 0.65rem",
    fontSize: "clamp(0.65rem, 2.2vw, 0.82rem)",
    fontWeight: 600,
    cursor: "pointer",
    flex: 1,
    transition: "all 0.3s",
  });

  const quoteBox = {
    ...card,
    borderLeft: "3px solid #b8860b",
    fontFamily: "'Lora', serif",
    fontStyle: "italic",
    fontSize: "0.9rem",
    color: "#d4b896",
    lineHeight: 1.6,
  };

  const profileBtn = (hover) => ({
    fontFamily: "'DM Sans', sans-serif",
    background: "rgba(42, 37, 32, 0.8)",
    border: "2px solid rgba(184, 134, 11, 0.25)",
    borderRadius: "12px",
    padding: "1.1rem 0.75rem",
    color: "#f5e6c8",
    fontSize: "1rem",
    fontWeight: 600,
    cursor: "pointer",
    transition: "all 0.3s",
    textAlign: "center",
    flex: 1,
    minWidth: "110px",
  });

  // ── PROFILE SELECTION ──
  if (!profile) {
    return (
      <div style={page}>
        <style>{css}</style>
        <div style={{ maxWidth: 560, margin: "0 auto", padding: "1rem" }}>
          <div style={{ textAlign: "center", padding: "2.5rem 1rem 1.5rem" }}>
            <div style={{ fontFamily: "'Lora', serif", fontSize: "clamp(2rem, 6vw, 2.8rem)", fontWeight: 700, color: "#daa520", lineHeight: 1.1 }}>
              {t.appTitle}
            </div>
            <div style={{ fontFamily: "'Lora', serif", fontSize: "clamp(1.2rem, 3.5vw, 1.6rem)", fontWeight: 400, color: "#b8960b", marginTop: "0.25rem" }}>
              {t.appSubtitle}
            </div>
            <p style={{ color: "#a09080", marginTop: "0.75rem", fontSize: "0.95rem", lineHeight: 1.5 }}>{t.tagline}</p>
            <p style={{ color: "#7a6a5a", marginTop: "0.4rem", fontSize: "0.8rem", fontStyle: "italic" }}>{t.byline}</p>
            <button onClick={() => setLang(lang === "es" ? "en" : "es")}
              style={{ ...btn, marginTop: "1rem", fontSize: "0.8rem", padding: "0.4rem 0.9rem", background: "rgba(184,134,11,0.15)", color: "#d4b896", border: "1px solid rgba(184,134,11,0.2)" }}>
              🌐 {t.langSwitch}
            </button>
          </div>

          <div style={{ ...card, marginTop: "1rem" }}>
            <h2 style={{ fontFamily: "'Lora', serif", textAlign: "center", marginBottom: "1.25rem", fontSize: "1.15rem" }}>
              {t.selectProfile}
            </h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.6rem" }}>
              {["kid", "teen", "older", "parent"].map((p) => (
                <button key={p} style={profileBtn()} onClick={() => { setProfile(p); setTab(p === "parent" ? "method" : "huchas"); setCompletedRetos([]); }}
                  onMouseEnter={e => { e.target.style.borderColor = "#daa520"; e.target.style.transform = "translateY(-2px)"; }}
                  onMouseLeave={e => { e.target.style.borderColor = "rgba(184,134,11,0.25)"; e.target.style.transform = ""; }}>
                  {t.profiles[p]}
                </button>
              ))}
            </div>
          </div>

          <div style={quoteBox}>
            "El dinero no compra libertad; la construye quien aprende a dirigirlo con inteligencia."
            <div style={{ fontStyle: "normal", fontSize: "0.8rem", color: "#8a7a6a", marginTop: "0.5rem" }}>— Miguel A. Sáez</div>
          </div>
        </div>
      </div>
    );
  }

  // Available tabs per profile
  const availableTabs = profile === "parent"
    ? ["method", "retos", "learn"]
    : profile === "kid"
    ? ["huchas", "retos", "learn"]
    : ["huchas", "method", "retos", "learn"];

  return (
    <div style={page}>
      <style>{css}</style>
      <div style={{ maxWidth: 560, margin: "0 auto", padding: "0.6rem" }}>

        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "0.6rem 0" }}>
          <button onClick={() => { setProfile(null); setShowMethodResult(false); }}
            style={{ background: "none", border: "none", color: "#a09080", cursor: "pointer", fontSize: "0.85rem" }}>
            {t.back}
          </button>
          <div style={{ fontFamily: "'Lora', serif", fontSize: "1rem", color: "#daa520", fontWeight: 600 }}>
            {t.appTitle}
          </div>
          <button onClick={() => setLang(lang === "es" ? "en" : "es")}
            style={{ background: "rgba(184,134,11,0.1)", border: "none", color: "#a09080", cursor: "pointer", fontSize: "0.75rem", padding: "0.3rem 0.6rem", borderRadius: "6px" }}>
            🌐 {t.langSwitch}
          </button>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", gap: "0.35rem", marginBottom: "0.85rem" }}>
          {availableTabs.map(tb => (
            <button key={tb} style={tabBtn(tab === tb)} onClick={() => { setTab(tb); setShowMethodResult(false); }}>
              {t.tabs[tb]}
            </button>
          ))}
        </div>

        {/* ════════ HUCHAS TAB ════════ */}
        {tab === "huchas" && (
          <div>
            <div style={card}>
              <h2 style={{ fontFamily: "'Lora', serif", fontSize: "1.2rem", marginBottom: "0.3rem" }}>{t.huchas.title}</h2>
              <p style={{ color: "#a09080", fontSize: "0.85rem", marginBottom: "1rem" }}>{t.huchas.subtitle}</p>

              {/* Three jars display */}
              <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
                {[
                  { label: t.huchas.gastar, value: huchaGastar, color: "#cd853f", emoji: "🛍️" },
                  { label: t.huchas.ahorrar, value: huchaAhorrar, color: "#daa520", emoji: "🏺" },
                  { label: t.huchas.compartir, value: huchaCompartir, color: "#8fbc8f", emoji: "❤️" },
                ].map((jar, i) => (
                  <div key={i} style={{ flex: 1, textAlign: "center", background: "rgba(26,21,16,0.5)", borderRadius: "10px", padding: "0.75rem 0.4rem", border: `1px solid ${jar.color}33` }}>
                    <div style={{ fontSize: "1.5rem" }}>{jar.emoji}</div>
                    <div style={{ fontFamily: "'Lora', serif", fontSize: "1.1rem", color: jar.color, fontWeight: 700, margin: "0.3rem 0" }}>
                      {jar.value.toFixed(1)}€
                    </div>
                    <div style={{ fontSize: "0.75rem", color: "#a09080" }}>{jar.label}</div>
                  </div>
                ))}
              </div>

              {/* Add money */}
              <div style={{ display: "flex", gap: "0.5rem", marginBottom: "0.75rem" }}>
                <input style={{ ...input, flex: 1 }} type="number" min="0" placeholder={t.huchas.amount} value={addAmount} onChange={e => setAddAmount(e.target.value)} />
                <button style={btn} onClick={addToHuchas}>{t.huchas.distribute}</button>
              </div>

              {/* Split sliders */}
              <div style={{ fontSize: "0.8rem", color: "#a09080", marginBottom: "0.5rem" }}>
                {t.huchas.gastar}: {splitG}% · {t.huchas.ahorrar}: {splitA}% · {t.huchas.compartir}: {splitC}%
              </div>
              {[
                { label: t.huchas.gastar, val: splitG, set: (v) => { setSplitG(v); setSplitA(Math.max(0, 100 - v - splitC)); } },
                { label: t.huchas.ahorrar, val: splitA, set: (v) => { setSplitA(v); setSplitC(Math.max(0, 100 - splitG - v)); } },
              ].map((s, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.3rem" }}>
                  <span style={{ fontSize: "0.75rem", width: 65, color: "#a09080" }}>{s.label}</span>
                  <input type="range" min="0" max="100" value={s.val} onChange={e => s.set(parseInt(e.target.value))} style={{ flex: 1 }} />
                  <span style={{ fontSize: "0.8rem", width: 35, textAlign: "right" }}>{s.val}%</span>
                </div>
              ))}
            </div>

            {/* Savings goal */}
            <div style={card}>
              <h3 style={{ fontFamily: "'Lora', serif", fontSize: "1rem", marginBottom: "0.75rem" }}>{t.huchas.goalLabel}</h3>
              {!activeGoal ? (
                <div style={{ display: "grid", gap: "0.5rem" }}>
                  <input style={input} placeholder={t.huchas.goalPlaceholder} value={goalName} onChange={e => setGoalName(e.target.value)} />
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.5rem" }}>
                    <input style={input} type="number" placeholder={t.huchas.goalAmount} value={goalAmount} onChange={e => setGoalAmount(e.target.value)} />
                    <input style={input} type="number" placeholder={t.huchas.goalWeekly} value={goalWeekly} onChange={e => setGoalWeekly(e.target.value)} />
                  </div>
                  <button style={btn} onClick={setGoalAction}>{t.huchas.setGoal}</button>
                </div>
              ) : (
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
                    <Ring pct={(huchaAhorrar / activeGoal.amount) * 100} size={80} stroke={7} />
                    <div>
                      <div style={{ fontFamily: "'Lora', serif", fontSize: "1.05rem", color: "#daa520" }}>🎯 {activeGoal.name}</div>
                      <div style={{ color: "#a09080", fontSize: "0.85rem", marginTop: "0.25rem" }}>
                        {t.huchas.saved}: <strong style={{ color: "#daa520" }}>{huchaAhorrar.toFixed(1)}€</strong> {t.huchas.of} {activeGoal.amount}€
                      </div>
                      {huchaAhorrar >= activeGoal.amount ? (
                        <div style={{ color: "#8fbc8f", fontWeight: 700, marginTop: "0.3rem", animation: "pulse 1.5s infinite" }}>{t.huchas.goalAchieved}</div>
                      ) : (
                        <div style={{ color: "#a09080", fontSize: "0.8rem", marginTop: "0.2rem" }}>
                          {Math.ceil((activeGoal.amount - huchaAhorrar) / activeGoal.weekly)} {t.huchas.weeksLeft}
                        </div>
                      )}
                    </div>
                  </div>
                  <button onClick={() => setActiveGoal(null)} style={{ ...btn, background: "transparent", color: "#a09080", border: "1px solid rgba(184,134,11,0.2)", fontSize: "0.8rem", marginTop: "0.75rem", padding: "0.4rem 0.8rem" }}>
                    {t.huchas.clearGoal}
                  </button>
                </div>
              )}
            </div>

            <div style={quoteBox}>
              📖 {t.huchas.bookRef}
            </div>
            <div style={{ ...card, borderLeft: "3px solid #8fbc8f", fontSize: "0.85rem", color: "#b8a890" }}>
              💡 {t.huchas.tip}
            </div>
          </div>
        )}

        {/* ════════ METHOD TAB ════════ */}
        {tab === "method" && (
          <div>
            {(profile === "teen" || profile === "older") ? (
              /* Teen 50/30/20 */
              <div>
                <div style={card}>
                  <h2 style={{ fontFamily: "'Lora', serif", fontSize: "1.15rem", marginBottom: "0.25rem" }}>{t.method.teenTitle}</h2>
                  <p style={{ color: "#a09080", fontSize: "0.85rem", marginBottom: "1rem" }}>{t.method.teenSubtitle}</p>
                  <input style={{ ...input, marginBottom: "0.75rem" }} type="number" placeholder={t.method.teenIncome} value={income} onChange={e => setIncome(e.target.value)} />
                  <button style={{ ...btn, width: "100%" }} onClick={() => setShowMethodResult(true)}>{t.method.calculate}</button>
                </div>
                {showMethodResult && income && (
                  <div style={{ ...card, animation: "fadeUp 0.4s ease" }}>
                    <h3 style={{ fontFamily: "'Lora', serif", fontSize: "1rem", marginBottom: "0.75rem" }}>{t.method.result}</h3>
                    {[
                      { label: t.method.necesidades, pct: 50, color: "#cd853f", desc: t.method.necesidadesDesc },
                      { label: t.method.deseos, pct: 30, color: "#b8860b", desc: t.method.deseosDesc },
                      { label: t.method.ahorro, pct: 20, color: "#228B22", desc: t.method.ahorroDesc },
                    ].map((block, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "0.6rem", padding: "0.6rem", background: "rgba(26,21,16,0.4)", borderRadius: "8px", borderLeft: `3px solid ${block.color}` }}>
                        <div style={{ fontFamily: "'Lora', serif", fontSize: "1.3rem", color: block.color, fontWeight: 700, minWidth: 70 }}>
                          {(parseFloat(income) * block.pct / 100).toFixed(0)}€
                        </div>
                        <div>
                          <div style={{ fontSize: "0.9rem", fontWeight: 600 }}>{block.label} ({block.pct}%)</div>
                          <div style={{ fontSize: "0.75rem", color: "#a09080" }}>{block.desc}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
                <div style={quoteBox}>📖 {t.method.teenBookRef}</div>
              </div>
            ) : (
              /* Parent 60/20/20 */
              <div>
                <div style={card}>
                  <h2 style={{ fontFamily: "'Lora', serif", fontSize: "1.15rem", marginBottom: "0.25rem" }}>{t.method.title}</h2>
                  <p style={{ color: "#a09080", fontSize: "0.85rem", marginBottom: "1rem" }}>{t.method.subtitle}</p>
                  <input style={{ ...input, marginBottom: "0.75rem" }} type="number" placeholder={t.method.income} value={income} onChange={e => setIncome(e.target.value)} />
                  <button style={{ ...btn, width: "100%" }} onClick={() => setShowMethodResult(true)}>{t.method.calculate}</button>
                </div>
                {showMethodResult && income && (
                  <div style={{ ...card, animation: "fadeUp 0.4s ease" }}>
                    <h3 style={{ fontFamily: "'Lora', serif", fontSize: "1rem", marginBottom: "0.75rem" }}>{t.method.result}</h3>
                    {[
                      { label: t.method.vivir, pct: 60, color: "#cd853f", desc: t.method.vivirDesc, emoji: "🏠" },
                      { label: t.method.crecer, pct: 20, color: "#228B22", desc: t.method.crecerDesc, emoji: "📈" },
                      { label: t.method.libertad, pct: 20, color: "#daa520", desc: t.method.libertadDesc, emoji: "✨" },
                    ].map((block, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "0.6rem", padding: "0.7rem", background: "rgba(26,21,16,0.4)", borderRadius: "8px", borderLeft: `3px solid ${block.color}` }}>
                        <div style={{ textAlign: "center" }}>
                          <div style={{ fontSize: "1.3rem" }}>{block.emoji}</div>
                          <div style={{ fontFamily: "'Lora', serif", fontSize: "1.4rem", color: block.color, fontWeight: 700 }}>
                            {(parseFloat(income) * block.pct / 100).toFixed(0)}€
                          </div>
                        </div>
                        <div>
                          <div style={{ fontSize: "0.9rem", fontWeight: 600 }}>{block.label} ({block.pct}%)</div>
                          <div style={{ fontSize: "0.75rem", color: "#a09080" }}>{block.desc}</div>
                        </div>
                      </div>
                    ))}
                    <div style={{ fontSize: "0.8rem", color: "#8fbc8f", marginTop: "0.5rem", padding: "0.5rem", background: "rgba(34,139,34,0.08)", borderRadius: "6px" }}>
                      💡 {t.method.autoTip}
                    </div>
                  </div>
                )}
                <div style={quoteBox}>📖 {t.method.bookRef}</div>

                {/* Compound interest calculator for parents */}
                <div style={card}>
                  <h3 style={{ fontFamily: "'Lora', serif", fontSize: "1.05rem", marginBottom: "0.25rem" }}>{t.compoundTitle}</h3>
                  <p style={{ color: "#a09080", fontSize: "0.8rem", marginBottom: "1rem" }}>{t.compoundSubtitle}</p>
                  {[
                    { label: t.compoundMonthly, val: cMonthly, set: setCMonthly, min: 25, max: 1000, step: 25 },
                    { label: t.compoundYears, val: cYears, set: setCYears, min: 1, max: 40, step: 1 },
                    { label: t.compoundRate, val: cRate, set: setCRate, min: 1, max: 15, step: 0.5 },
                  ].map((s, i) => (
                    <div key={i} style={{ marginBottom: "0.6rem" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.8rem", color: "#a09080", marginBottom: "0.2rem" }}>
                        <span>{s.label}</span>
                        <span style={{ color: "#daa520", fontWeight: 600 }}>{s.val}{i === 2 ? "%" : i === 0 ? "€" : ""}</span>
                      </div>
                      <input type="range" min={s.min} max={s.max} step={s.step} value={s.val} onChange={e => s.set(parseFloat(e.target.value))} style={{ width: "100%" }} />
                    </div>
                  ))}
                  <CompoundBars data={compoundData} t={t} />
                </div>
                <div style={quoteBox}>📖 {t.compoundBookRef}</div>
              </div>
            )}
          </div>
        )}

        {/* ════════ RETOS TAB ════════ */}
        {tab === "retos" && (
          <div>
            <div style={{ marginBottom: "1rem" }}>
              <h2 style={{ fontFamily: "'Lora', serif", fontSize: "1.15rem" }}>
                {profile === "kid" ? t.retos.kidTitle : profile === "teen" || profile === "older" ? t.retos.teenTitle : t.retos.title}
              </h2>
              <p style={{ color: "#a09080", fontSize: "0.85rem" }}>
                {profile === "kid" ? t.retos.kidSubtitle : profile === "teen" || profile === "older" ? t.retos.teenSubtitle : t.retos.subtitle}
              </p>
              {completedRetos.length > 0 && (
                <div style={{ display: "inline-block", marginTop: "0.5rem", background: "rgba(34,139,34,0.1)", border: "1px solid rgba(34,139,34,0.25)", borderRadius: "999px", padding: "0.3rem 0.75rem", fontSize: "0.8rem", color: "#8fbc8f" }}>
                  🔥 {t.retos.streak}: {completedRetos.length} {t.retos.retosCompleted}
                </div>
              )}
            </div>
            {currentRetos.map((reto, idx) => {
              const done = completedRetos.includes(idx);
              return (
                <div key={idx} style={{ ...card, opacity: done ? 0.7 : 1, animationDelay: `${idx * 0.08}s`, borderLeft: done ? "3px solid #228B22" : "3px solid #b8860b" }}>
                  <p style={{ fontSize: "0.9rem", lineHeight: 1.5, marginBottom: "0.6rem", textDecoration: done ? "line-through" : "none" }}>
                    {reto[lang]}
                  </p>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontSize: "0.7rem", color: "#7a6a5a", fontStyle: "italic" }}>📖 {reto.chapter}</span>
                    <button onClick={() => toggleReto(idx)} style={{
                      ...btn,
                      fontSize: "0.8rem",
                      padding: "0.35rem 0.8rem",
                      background: done ? "rgba(34,139,34,0.15)" : btn.background,
                      color: done ? "#8fbc8f" : btn.color,
                      border: done ? "1px solid rgba(34,139,34,0.3)" : "none",
                    }}>
                      {done ? t.retos.completed : t.retos.accept}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ════════ LEARN TAB ════════ */}
        {tab === "learn" && (
          <div>
            <h2 style={{ fontFamily: "'Lora', serif", fontSize: "1.15rem", marginBottom: "0.25rem" }}>{t.learn.title}</h2>
            <p style={{ color: "#a09080", fontSize: "0.85rem", marginBottom: "0.85rem" }}>{t.learn.subtitle}</p>
            {(learnContent[profile] || learnContent.parent).map((item, idx) => {
              const open = expandedLearn === idx;
              const accentColors = ["#cd853f", "#daa520", "#8fbc8f", "#b8860b", "#a0896c"];
              return (
                <div key={idx} style={{ ...card, cursor: "pointer", borderLeft: `3px solid ${accentColors[idx % accentColors.length]}`, animationDelay: `${idx * 0.08}s` }}
                  onClick={() => setExpandedLearn(open ? null : idx)}>
                  <div style={{ display: "flex", alignItems: "center", gap: "0.6rem" }}>
                    <span style={{ fontSize: "1.6rem" }}>{item.emoji}</span>
                    <div style={{ flex: 1 }}>
                      <h3 style={{ fontFamily: "'Lora', serif", fontSize: "0.95rem" }}>{item[lang].title}</h3>
                      {open && (
                        <p style={{ color: "#c8b8a0", marginTop: "0.4rem", fontSize: "0.9rem", lineHeight: 1.6, animation: "fadeUp 0.3s ease" }}>
                          {item[lang].body}
                        </p>
                      )}
                    </div>
                    <span style={{ color: "#7a6a5a", transition: "transform 0.3s", transform: open ? "rotate(180deg)" : "" }}>▼</span>
                  </div>
                </div>
              );
            })}

            {/* Compound interest for teens/older */}
            {(profile === "teen" || profile === "older") && (
              <>
                <div style={{ ...card, marginTop: "0.5rem" }}>
                  <h3 style={{ fontFamily: "'Lora', serif", fontSize: "1rem", marginBottom: "0.25rem" }}>{t.compoundTitle}</h3>
                  <p style={{ color: "#a09080", fontSize: "0.8rem", marginBottom: "1rem" }}>{t.compoundSubtitle}</p>
                  {[
                    { label: t.compoundMonthly, val: cMonthly, set: setCMonthly, min: 5, max: 200, step: 5 },
                    { label: t.compoundYears, val: cYears, set: setCYears, min: 1, max: 30, step: 1 },
                    { label: t.compoundRate, val: cRate, set: setCRate, min: 1, max: 12, step: 0.5 },
                  ].map((s, i) => (
                    <div key={i} style={{ marginBottom: "0.5rem" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.75rem", color: "#a09080" }}>
                        <span>{s.label}</span>
                        <span style={{ color: "#daa520", fontWeight: 600 }}>{s.val}{i === 2 ? "%" : i === 0 ? "€" : ""}</span>
                      </div>
                      <input type="range" min={s.min} max={s.max} step={s.step} value={s.val} onChange={e => s.set(parseFloat(e.target.value))} style={{ width: "100%" }} />
                    </div>
                  ))}
                  <CompoundBars data={compoundData} t={t} />
                </div>
                <div style={quoteBox}>📖 {t.compoundBookRef}</div>
              </>
            )}
          </div>
        )}

        <div style={{ height: "1.5rem" }} />
      </div>
    </div>
  );
}
