/* ═══════════════════════════════════════════════════════════════════
   MENTALIDAD LIBRE — App v2  ·  AizuaLabs Academy
   Gamified · Colorful · Fun · Bilingual ES/EN
   ═══════════════════════════════════════════════════════════════════ */

const { useState, useEffect, useRef } = React;

/* ── Translations ────────────────────────────────────────────────── */
const T = {
  es: {
    appTitle: "Mentalidad Libre",
    appSubtitle: "Tu aventura financiera comienza aquí",
    langToggle: "EN",
    levelUp: "¡Subiste de nivel!",
    xpEarned: "XP ganados",
    streak: "Racha",
    days: "días",
    chooseProfile: "¿Quién eres hoy?",
    profileSubtitle: "Elige tu aventurero y empieza a jugar",
    profiles: {
      kid:    { label: "Explorador",   emoji: "🌱", age: "3–8 años",   level: "Nivel 1", color: "#29B6F6" },
      teen:   { label: "Navegante",    emoji: "🚀", age: "9–13 años",  level: "Nivel 2", color: "#29B6F6" },
      older:  { label: "Pionero",      emoji: "⚡",  age: "14–18 años", level: "Nivel 3", color: "#E8C96A" },
      parent: { label: "Estratega",    emoji: "💼", age: "Adulto",     level: "Nivel 4", color: "#E8C96A" },
    },
    nav: {
      dashboard: "Dashboard",
      huchas:    "3 Huchas",
      method:    "60/20/20",
      retos:     "Retos",
      compound:  "Interés",
    },
    dashboard: {
      title: "¡Hola, aventurero!",
      subtitle: "Aquí está tu resumen de hoy",
      savings: "Ahorrado",
      goal: "Objetivo",
      xp: "XP Total",
      streak: "Racha",
      noGoal: "Sin objetivo",
      tip: "Consejo del día",
      tips: [
        "💡 Invierte aunque sea 10€ al mes. En 20 años puede ser mucho más.",
        "🎯 Un objetivo claro es más poderoso que una gran cantidad de dinero.",
        "🌱 El hábito de ahorrar vale más que el monto que ahorras.",
        "🔑 La libertad financiera se construye decisión a decisión.",
        "🚀 Empieza hoy. Tu yo del futuro te lo agradecerá.",
      ],
    },
    huchas: {
      title: "Las 3 Huchas",
      subtitle: "Cada euro tiene una misión. ¡Repártelo!",
      gastar:   { label: "Gastar",   emoji: "🛍️",  pct: 60, color: "#0288D1" },
      ahorrar:  { label: "Ahorrar",  emoji: "🐷",  pct: 20, color: "#C9A84C" },
      invertir: { label: "Invertir", emoji: "📈",  pct: 20, color: "#E8C96A" },
      incomeLabel: "¿Cuánto dinero tienes? (€)",
      distribute: "¡Repartir!",
      result: "Tu reparto:",
      xpReward: "+15 XP por repartir tu dinero",
      tip: "💡 Gastar 60%, Ahorrar 20%, Invertir 20% — la fórmula mágica.",
    },
    method: {
      title: "Método 60/20/20",
      subtitle: "El sistema familiar Mentalidad Libre",
      categories: [
        { key: "vivir",    label: "Vivir",    emoji: "🏠", pct: 60, color: "#0288D1", desc: "Vivienda, comida, transporte, colegio" },
        { key: "crecer",   label: "Crecer",   emoji: "📈", pct: 20, color: "#C9A84C", desc: "Ahorro, inversión, fondos indexados" },
        { key: "libertad", label: "Libertad", emoji: "✨", pct: 20, color: "#E8C96A", desc: "Viajes, formación, ocio, experiencias" },
      ],
      incomeLabel: "Ingresos netos mensuales (€)",
      calculate: "Calcular",
      result: "Tu distribución:",
      monthlyLabel: "al mes",
      tip: "💡 Automatiza las transferencias el día que cobres.",
    },
    retos: {
      title: "Mini-Retos",
      subtitle: "Completa retos y gana XP",
      completed: "¡Hecho!",
      pending: "Completar",
      xpEach: "XP",
      allDone: "¡Completaste todos los retos! 🏆",
      challenges: [
        { id: "r1", emoji: "💰", text: "Abre una cuenta de ahorro separada", xp: 20 },
        { id: "r2", emoji: "📊", text: "Calcula tus gastos del mes pasado", xp: 15 },
        { id: "r3", emoji: "🎯", text: "Fija un objetivo financiero específico", xp: 15 },
        { id: "r4", emoji: "📚", text: "Lee 15 minutos sobre finanzas personales", xp: 10 },
        { id: "r5", emoji: "💬", text: "Habla con tus hijos sobre el dinero hoy", xp: 20 },
        { id: "r6", emoji: "🔄", text: "Automatiza una transferencia mensual", xp: 25 },
        { id: "r7", emoji: "🛑", text: "Cancela una suscripción que no usas", xp: 15 },
        { id: "r8", emoji: "🌱", text: "Investiga un fondo indexado", xp: 20 },
      ],
      kidChallenges: [
        { id: "k1", emoji: "🐷", text: "Mete una moneda en tu hucha hoy", xp: 10 },
        { id: "k2", emoji: "🛒", text: "Ayuda a elegir algo barato en la tienda", xp: 10 },
        { id: "k3", emoji: "🎁", text: "Ahorra para comprar un regalo a alguien", xp: 15 },
        { id: "k4", emoji: "💡", text: "Apaga las luces al salir de la habitación", xp: 5 },
        { id: "k5", emoji: "📝", text: "Escribe 3 cosas que quieres comprar", xp: 10 },
      ],
    },
    compound: {
      title: "Interés Compuesto",
      subtitle: "El 8º milagro del mundo ✨",
      capital: "Capital inicial (€)",
      monthly: "Aportación mensual (€)",
      years: "Años",
      rate: "Rentabilidad anual (%)",
      calculate: "Ver magia",
      invested: "Invertido",
      gains: "Beneficios",
      total: "Total",
      multiplier: "Multiplicador",
      tip: "💡 \"El interés compuesto es la fuerza más poderosa del universo.\" — Einstein",
      chartLabel: "Crecimiento de tu inversión",
    },
  },
  en: {
    appTitle: "Free Mindset",
    appSubtitle: "Your financial adventure starts here",
    langToggle: "ES",
    levelUp: "You leveled up!",
    xpEarned: "XP earned",
    streak: "Streak",
    days: "days",
    chooseProfile: "Who are you today?",
    profileSubtitle: "Choose your adventurer and start playing",
    profiles: {
      kid:    { label: "Explorer",   emoji: "🌱", age: "3–8 yrs",    level: "Level 1", color: "#29B6F6" },
      teen:   { label: "Navigator",  emoji: "🚀", age: "9–13 yrs",   level: "Level 2", color: "#29B6F6" },
      older:  { label: "Pioneer",    emoji: "⚡",  age: "14–18 yrs",  level: "Level 3", color: "#E8C96A" },
      parent: { label: "Strategist", emoji: "💼", age: "Adult",      level: "Level 4", color: "#E8C96A" },
    },
    nav: {
      dashboard: "Dashboard",
      huchas:    "3 Buckets",
      method:    "60/20/20",
      retos:     "Quests",
      compound:  "Compound",
    },
    dashboard: {
      title: "Hello, adventurer!",
      subtitle: "Here's your summary for today",
      savings: "Saved",
      goal: "Goal",
      xp: "Total XP",
      streak: "Streak",
      noGoal: "No goal set",
      tip: "Tip of the day",
      tips: [
        "💡 Invest even just €10/month. In 20 years it could be much more.",
        "🎯 A clear goal is more powerful than a large amount of money.",
        "🌱 The saving habit is worth more than the amount you save.",
        "🔑 Financial freedom is built decision by decision.",
        "🚀 Start today. Your future self will thank you.",
      ],
    },
    huchas: {
      title: "The 3 Buckets",
      subtitle: "Every euro has a mission. Split it!",
      gastar:   { label: "Spend",   emoji: "🛍️",  pct: 60, color: "#0288D1" },
      ahorrar:  { label: "Save",    emoji: "🐷",  pct: 20, color: "#C9A84C" },
      invertir: { label: "Invest",  emoji: "📈",  pct: 20, color: "#E8C96A" },
      incomeLabel: "How much money do you have? (€)",
      distribute: "Split it!",
      result: "Your split:",
      xpReward: "+15 XP for splitting your money",
      tip: "💡 Spend 60%, Save 20%, Invest 20% — the magic formula.",
    },
    method: {
      title: "60/20/20 Method",
      subtitle: "The Free Mindset family system",
      categories: [
        { key: "live",    label: "Live",    emoji: "🏠", pct: 60, color: "#0288D1", desc: "Housing, food, transport, school" },
        { key: "grow",    label: "Grow",    emoji: "📈", pct: 20, color: "#C9A84C", desc: "Savings, investment, index funds" },
        { key: "freedom", label: "Freedom", emoji: "✨", pct: 20, color: "#E8C96A", desc: "Travel, education, leisure, experiences" },
      ],
      incomeLabel: "Monthly net income (€)",
      calculate: "Calculate",
      result: "Your distribution:",
      monthlyLabel: "per month",
      tip: "💡 Automate transfers on payday.",
    },
    retos: {
      title: "Mini-Quests",
      subtitle: "Complete quests and earn XP",
      completed: "Done!",
      pending: "Complete",
      xpEach: "XP",
      allDone: "You completed all quests! 🏆",
      challenges: [
        { id: "r1", emoji: "💰", text: "Open a separate savings account", xp: 20 },
        { id: "r2", emoji: "📊", text: "Calculate your expenses from last month", xp: 15 },
        { id: "r3", emoji: "🎯", text: "Set a specific financial goal", xp: 15 },
        { id: "r4", emoji: "📚", text: "Read 15 minutes about personal finance", xp: 10 },
        { id: "r5", emoji: "💬", text: "Talk to your kids about money today", xp: 20 },
        { id: "r6", emoji: "🔄", text: "Automate a monthly transfer", xp: 25 },
        { id: "r7", emoji: "🛑", text: "Cancel a subscription you don't use", xp: 15 },
        { id: "r8", emoji: "🌱", text: "Research an index fund", xp: 20 },
      ],
      kidChallenges: [
        { id: "k1", emoji: "🐷", text: "Put a coin in your piggy bank today", xp: 10 },
        { id: "k2", emoji: "🛒", text: "Help choose something cheaper at the store", xp: 10 },
        { id: "k3", emoji: "🎁", text: "Save up to buy a gift for someone", xp: 15 },
        { id: "k4", emoji: "💡", text: "Turn off the lights when leaving the room", xp: 5 },
        { id: "k5", emoji: "📝", text: "Write 3 things you want to buy", xp: 10 },
      ],
    },
    compound: {
      title: "Compound Interest",
      subtitle: "The 8th wonder of the world ✨",
      capital: "Starting capital (€)",
      monthly: "Monthly contribution (€)",
      years: "Years",
      rate: "Annual return (%)",
      calculate: "See magic",
      invested: "Invested",
      gains: "Gains",
      total: "Total",
      multiplier: "Multiplier",
      tip: "💡 \"Compound interest is the most powerful force in the universe.\" — Einstein",
      chartLabel: "Growth of your investment",
    },
  },
};

/* ── Helpers ─────────────────────────────────────────────────────── */
function fmt(n) {
  return new Intl.NumberFormat("es-ES", { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n);
}

function useLocalState(key, initial) {
  const [val, setVal] = useState(() => {
    try { const s = localStorage.getItem(key); return s ? JSON.parse(s) : initial; }
    catch { return initial; }
  });
  useEffect(() => { try { localStorage.setItem(key, JSON.stringify(val)); } catch {} }, [key, val]);
  return [val, setVal];
}

/* ── Donut Chart ─────────────────────────────────────────────────── */
function DonutChart({ segments, size = 160, strokeWidth = 22, animated }) {
  const r = (size - strokeWidth) / 2;
  const circ = 2 * Math.PI * r;
  const cx = size / 2, cy = size / 2;
  const [progress, setProgress] = useState(animated ? 0 : 1);
  useEffect(() => {
    if (!animated) { setProgress(1); return; }
    setProgress(0);
    const t = setTimeout(() => {
      let start = null;
      const dur = 800;
      const step = (ts) => {
        if (!start) start = ts;
        const p = Math.min((ts - start) / dur, 1);
        setProgress(p < 1 ? p : 1);
        if (p < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
    }, 100);
    return () => clearTimeout(t);
  }, [animated, JSON.stringify(segments)]);

  let offset = 0;
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  return (
    <svg width={size} height={size} style={{ display: "block", margin: "0 auto" }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#f0ede8" strokeWidth={strokeWidth} />
      {segments.map((seg, i) => {
        const frac = (seg.value / total) * progress;
        const dash = frac * circ;
        const gap = circ - dash;
        const rot = offset * 360 - 90;
        offset += seg.value / total;
        return (
          <circle
            key={i}
            cx={cx} cy={cy} r={r}
            fill="none"
            stroke={seg.color}
            strokeWidth={strokeWidth}
            strokeDasharray={`${dash} ${gap}`}
            strokeDashoffset={0}
            strokeLinecap="round"
            transform={`rotate(${rot} ${cx} ${cy})`}
            style={{ transition: "stroke-dasharray 0.05s" }}
          />
        );
      })}
      <text x={cx} y={cy - 6} textAnchor="middle" fontSize="11" fill="#9ca3af" fontFamily="sans-serif">Total</text>
      <text x={cx} y={cy + 14} textAnchor="middle" fontSize="18" fontWeight="700" fill="#1f2937" fontFamily="sans-serif">
        {total > 1 ? `${fmt(total)}€` : "—"}
      </text>
    </svg>
  );
}

/* ── Animated Bar Chart ──────────────────────────────────────────── */
function BarChart({ data, height = 140 }) {
  const [drawn, setDrawn] = useState(false);
  useEffect(() => { const t = setTimeout(() => setDrawn(true), 200); return () => clearTimeout(t); }, [data]);
  const max = Math.max(...data.map(d => d.value), 1);
  const barW = Math.max(18, Math.floor(220 / data.length) - 6);
  const gap = 6;
  const totalW = data.length * (barW + gap);

  return (
    <div style={{ overflowX: "auto", paddingBottom: 4 }}>
      <svg width={Math.max(totalW, 260)} height={height + 36} style={{ display: "block", margin: "0 auto" }}>
        {data.map((d, i) => {
          const bh = drawn ? Math.max(4, (d.value / max) * height) : 4;
          const x = i * (barW + gap);
          const y = height - bh;
          return (
            <g key={i}>
              <rect
                x={x} y={y} width={barW} height={bh}
                rx={6} fill={d.color}
                style={{ transition: "all 0.6s cubic-bezier(0.34,1.56,0.64,1)" }}
              />
              <text x={x + barW / 2} y={height + 14} textAnchor="middle" fontSize="9" fill="#9ca3af" fontFamily="sans-serif">
                {d.label}
              </text>
              {d.value > 0 && (
                <text x={x + barW / 2} y={y - 4} textAnchor="middle" fontSize="9" fill={d.color} fontWeight="700" fontFamily="sans-serif">
                  {fmt(d.value)}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

/* ── XP Toast ────────────────────────────────────────────────────── */
function XPToast({ amount, onDone }) {
  useEffect(() => { const t = setTimeout(onDone, 2000); return () => clearTimeout(t); }, []);
  return (
    <div style={{
      position: "fixed", bottom: 90, left: "50%", transform: "translateX(-50%)",
      background: "linear-gradient(135deg, #C9A84C, #B8962C)",
      color: "#fff", fontWeight: 700, fontSize: 16,
      padding: "12px 28px", borderRadius: 50,
      boxShadow: "0 8px 32px rgba(201,168,76,0.4)",
      zIndex: 9999, whiteSpace: "nowrap",
      animation: "toastIn 0.3s cubic-bezier(0.34,1.56,0.64,1)",
    }}>
      ✨ +{amount} XP
    </div>
  );
}

/* ── Progress Ring ───────────────────────────────────────────────── */
function ProgressRing({ pct, size = 52, color, emoji }) {
  const r = (size - 6) / 2;
  const circ = 2 * Math.PI * r;
  const dash = (pct / 100) * circ;
  return (
    <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#f0ede8" strokeWidth={5} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={5}
          strokeDasharray={`${dash} ${circ - dash}`} strokeLinecap="round"
          style={{ transition: "stroke-dasharray 0.8s ease" }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18 }}>
        {emoji}
      </div>
    </div>
  );
}

/* ── Card ────────────────────────────────────────────────────────── */
function Card({ children, style, gradient }) {
  return (
    <div style={{
      background: gradient || "#1E2E3E",
      borderRadius: 20,
      padding: "20px 18px",
      boxShadow: "0 2px 16px rgba(0,0,0,0.07)",
      marginBottom: 14,
      border: "1px solid rgba(255,255,255,0.07)",
      ...style,
    }}>
      {children}
    </div>
  );
}

/* ── Slider ──────────────────────────────────────────────────────── */
function Slider({ label, value, min, max, step, onChange, color, unit }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <span style={{ fontSize: 13, color: "rgba(255,255,255,0.45)", fontWeight: 500 }}>{label}</span>
        <span style={{ fontSize: 15, fontWeight: 700, color }}>
          {fmt(value)}{unit}
        </span>
      </div>
      <input
        type="range" min={min} max={max} step={step} value={value}
        onChange={e => onChange(Number(e.target.value))}
        style={{ width: "100%", accentColor: color, cursor: "pointer" }}
      />
    </div>
  );
}

/* ── Profile Selector ────────────────────────────────────────────── */
function ProfileSelect({ lang, onSelect }) {
  const t = T[lang];
  const profiles = [
    { key: "kid",    ...t.profiles.kid },
    { key: "teen",   ...t.profiles.teen },
    { key: "older",  ...t.profiles.older },
    { key: "parent", ...t.profiles.parent },
  ];
  return (
    <div style={{ minHeight: "60vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "24px 8px" }}>
      <div style={{ fontSize: 48, marginBottom: 12 }}>🎮</div>
      <h2 style={{ fontSize: 22, fontWeight: 800, color: "#FFFFFF", marginBottom: 6, textAlign: "center" }}>{t.chooseProfile}</h2>
      <p style={{ fontSize: 14, color: "rgba(255,255,255,0.45)", marginBottom: 28, textAlign: "center" }}>{t.profileSubtitle}</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, width: "100%", maxWidth: 340 }}>
        {profiles.map(p => (
          <button key={p.key} onClick={() => onSelect(p.key)} style={{
            background: "#162030",
            border: `2px solid ${p.color}55`,
            borderRadius: 18,
            padding: "18px 12px",
            cursor: "pointer",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
            boxShadow: `0 4px 20px ${p.color}20`,
            transition: "transform 0.15s, box-shadow 0.15s",
          }}
            onMouseEnter={e => { e.currentTarget.style.transform = "scale(1.04)"; e.currentTarget.style.boxShadow = `0 8px 28px ${p.color}40`; }}
            onMouseLeave={e => { e.currentTarget.style.transform = "scale(1)"; e.currentTarget.style.boxShadow = `0 4px 20px ${p.color}20`; }}
          >
            <div style={{ fontSize: 36, lineHeight: 1 }}>{p.emoji}</div>
            <div style={{ fontWeight: 800, fontSize: 15, color: "#FFFFFF" }}>{p.label}</div>
            <div style={{ fontSize: 11, color: p.color, fontWeight: 600, background: `${p.color}15`, padding: "2px 8px", borderRadius: 20 }}>{p.level}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)" }}>{p.age}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ── Dashboard Tab ───────────────────────────────────────────────── */
function DashboardTab({ lang, profile, xp, streak, savings, t }) {
  const td = t.dashboard;
  const tip = td.tips[Math.floor(Date.now() / 86400000) % td.tips.length];
  const p = T[lang].profiles[profile];
  const levelBadges = [
    { min: 0,   label: lang === "es" ? "Semilla 🌰" : "Seed 🌰",      color: "#C9A84C" },
    { min: 50,  label: lang === "es" ? "Brote 🌱" : "Sprout 🌱",      color: "#22c55e" },
    { min: 150, label: lang === "es" ? "Árbol 🌳" : "Tree 🌳",         color: "#29B6F6" },
    { min: 300, label: lang === "es" ? "Experto ⭐" : "Expert ⭐",      color: "#C9A84C" },
    { min: 500, label: lang === "es" ? "Maestro 🏆" : "Master 🏆",     color: "#E8C96A" },
    { min: 800, label: lang === "es" ? "Leyenda 💎" : "Legend 💎",     color: "#0288D1" },
  ];
  const badge = [...levelBadges].reverse().find(b => xp >= b.min) || levelBadges[0];
  const nextBadge = levelBadges[levelBadges.findIndex(b => b === badge) + 1];
  const pctToNext = nextBadge ? Math.min(100, ((xp - badge.min) / (nextBadge.min - badge.min)) * 100) : 100;

  return (
    <div>
      {/* Hero greeting */}
      <Card gradient={`linear-gradient(135deg, ${p.color}, ${p.color}cc)`} style={{ color: "#fff", border: "none" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ fontSize: 48 }}>{p.emoji}</div>
          <div>
            <div style={{ fontSize: 12, opacity: 0.8, fontWeight: 500, marginBottom: 2 }}>{p.level} · {p.label}</div>
            <div style={{ fontSize: 20, fontWeight: 800 }}>{td.title}</div>
            <div style={{ fontSize: 13, opacity: 0.85 }}>{td.subtitle}</div>
          </div>
        </div>
        {/* XP progress bar */}
        <div style={{ marginTop: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, opacity: 0.85, marginBottom: 5 }}>
            <span style={{ fontWeight: 700 }}>{badge.label}</span>
            {nextBadge && <span>{xp} / {nextBadge.min} XP</span>}
          </div>
          <div style={{ background: "rgba(255,255,255,0.25)", borderRadius: 99, height: 8 }}>
            <div style={{ background: "#162030", borderRadius: 99, height: 8, width: `${pctToNext}%`, transition: "width 0.8s ease" }} />
          </div>
        </div>
      </Card>

      {/* Stats row */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
        <Card style={{ margin: 0, padding: "16px 14px", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ fontSize: 28 }}>🐷</div>
          <div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)", fontWeight: 500 }}>{td.savings}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: "#C9A84C" }}>{fmt(savings)}€</div>
          </div>
        </Card>
        <Card style={{ margin: 0, padding: "16px 14px", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ fontSize: 28 }}>⚡</div>
          <div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)", fontWeight: 500 }}>{td.xp}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: "#29B6F6" }}>{fmt(xp)}</div>
          </div>
        </Card>
        <Card style={{ margin: 0, padding: "16px 14px", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ fontSize: 28 }}>🔥</div>
          <div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)", fontWeight: 500 }}>{t.streak}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: "#0288D1" }}>{streak} <span style={{ fontSize: 12, fontWeight: 500, color: "rgba(255,255,255,0.45)" }}>{t.days}</span></div>
          </div>
        </Card>
        <Card style={{ margin: 0, padding: "16px 14px", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ fontSize: 28 }}>🏅</div>
          <div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)", fontWeight: 500 }}>{lang === "es" ? "Insignia" : "Badge"}</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: badge.color }}>{badge.label}</div>
          </div>
        </Card>
      </div>

      {/* Tip of the day */}
      <Card gradient="linear-gradient(135deg, rgba(201,168,76,0.15), rgba(201,168,76,0.06))">
        <div style={{ fontSize: 11, fontWeight: 700, color: "#29B6F6", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>{td.tip}</div>
        <div style={{ fontSize: 14, color: "rgba(255,255,255,0.75)", lineHeight: 1.6 }}>{tip}</div>
      </Card>
    </div>
  );
}

/* ── Huchas Tab ──────────────────────────────────────────────────── */
function HuchasTab({ lang, onXP, t }) {
  const th = t.huchas;
  const [income, setIncome] = useState("");
  const [distributed, setDistributed] = useState(null);
  const [animKey, setAnimKey] = useState(0);

  const buckets = [
    { key: "gastar",   ...th.gastar },
    { key: "ahorrar",  ...th.ahorrar },
    { key: "invertir", ...th.invertir },
  ];

  function distribute() {
    const n = parseFloat(income);
    if (!n || n <= 0) return;
    setDistributed({ gastar: n * 0.6, ahorrar: n * 0.2, invertir: n * 0.2, total: n });
    setAnimKey(k => k + 1);
    onXP(15);
  }

  const segments = distributed ? [
    { value: distributed.gastar,   color: th.gastar.color },
    { value: distributed.ahorrar,  color: th.ahorrar.color },
    { value: distributed.invertir, color: th.invertir.color },
  ] : [
    { value: 60, color: th.gastar.color },
    { value: 20, color: th.ahorrar.color },
    { value: 20, color: th.invertir.color },
  ];

  return (
    <div>
      <Card>
        <h3 style={{ fontSize: 18, fontWeight: 800, color: "#FFFFFF", marginBottom: 4 }}>{th.title}</h3>
        <p style={{ fontSize: 13, color: "rgba(255,255,255,0.45)", marginBottom: 20 }}>{th.subtitle}</p>

        <DonutChart key={animKey} segments={segments} animated={!!distributed} />

        {/* Legend */}
        <div style={{ display: "flex", justifyContent: "center", gap: 16, marginTop: 16, flexWrap: "wrap" }}>
          {buckets.map(b => (
            <div key={b.key} style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <div style={{ width: 10, height: 10, borderRadius: "50%", background: b.color }} />
              <span style={{ fontSize: 12, color: "rgba(255,255,255,0.45)" }}>{b.emoji} {b.label} <strong style={{ color: b.color }}>{b.pct}%</strong></span>
            </div>
          ))}
        </div>
      </Card>

      <Card>
        <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "rgba(255,255,255,0.85)", marginBottom: 8 }}>
          {th.incomeLabel}
        </label>
        <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
          <input
            type="number" value={income} onChange={e => setIncome(e.target.value)}
            placeholder="100"
            style={{
              flex: 1, padding: "12px 14px", borderRadius: 12,
              border: "2px solid rgba(255,255,255,0.12)", fontSize: 16, fontWeight: 600,
              outline: "none", color: "#FFFFFF", background: "#111D27",
            }}
            onFocus={e => e.target.style.borderColor = "#C9A84C"}
            onBlur={e => e.target.style.borderColor = "rgba(255,255,255,0.12)"}
          />
          <button onClick={distribute} style={{
            background: "linear-gradient(135deg, #C9A84C, #B8962C)",
            color: "#fff", border: "none", borderRadius: 12,
            padding: "0 20px", fontWeight: 700, fontSize: 15, cursor: "pointer",
            boxShadow: "0 4px 14px rgba(201,168,76,0.4)",
          }}>{th.distribute}</button>
        </div>

        {distributed && (
          <div>
            <div style={{ fontSize: 12, color: "#C9A84C", fontWeight: 700, marginBottom: 12, textAlign: "center" }}>✅ {th.xpReward}</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
              {buckets.map(b => (
                <div key={b.key} style={{
                  background: `${b.color}12`,
                  border: `2px solid ${b.color}30`,
                  borderRadius: 14, padding: "12px 8px", textAlign: "center",
                }}>
                  <div style={{ fontSize: 24 }}>{b.emoji}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)", marginTop: 4 }}>{b.label}</div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: b.color, marginTop: 2 }}>
                    {fmt(distributed[b.key])}€
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </Card>

      <Card gradient="linear-gradient(135deg, rgba(41,182,246,0.12), rgba(41,182,246,0.05))">
        <p style={{ fontSize: 13, color: "#29B6F6", lineHeight: 1.6 }}>{th.tip}</p>
      </Card>
    </div>
  );
}

/* ── Method Tab ──────────────────────────────────────────────────── */
function MethodTab({ lang, onXP, t }) {
  const tm = t.method;
  const [income, setIncome] = useState("");
  const [result, setResult] = useState(null);

  function calculate() {
    const n = parseFloat(income);
    if (!n || n <= 0) return;
    setResult(tm.categories.map(c => ({ ...c, amount: n * (c.pct / 100) })));
    onXP(10);
  }

  return (
    <div>
      <Card>
        <h3 style={{ fontSize: 18, fontWeight: 800, color: "#FFFFFF", marginBottom: 4 }}>{tm.title}</h3>
        <p style={{ fontSize: 13, color: "rgba(255,255,255,0.45)", marginBottom: 20 }}>{tm.subtitle}</p>

        {/* Visual bars */}
        <div style={{ marginBottom: 20 }}>
          {tm.categories.map(c => (
            <div key={c.key} style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 20 }}>{c.emoji}</span>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 14, color: "#FFFFFF" }}>{c.label}</div>
                    <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)" }}>{c.desc}</div>
                  </div>
                </div>
                <span style={{
                  fontWeight: 800, fontSize: 18, color: c.color,
                  background: `${c.color}15`, padding: "2px 10px", borderRadius: 20,
                }}>{c.pct}%</span>
              </div>
              <div style={{ background: "#1E2E3E", borderRadius: 99, height: 10 }}>
                <div style={{
                  background: c.color, borderRadius: 99, height: 10,
                  width: `${c.pct}%`,
                  transition: "width 0.8s cubic-bezier(0.34,1.56,0.64,1)",
                }} />
              </div>
            </div>
          ))}
        </div>

        <label style={{ display: "block", fontSize: 13, fontWeight: 600, color: "rgba(255,255,255,0.85)", marginBottom: 8 }}>
          {tm.incomeLabel}
        </label>
        <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
          <input
            type="number" value={income} onChange={e => setIncome(e.target.value)}
            placeholder="2000"
            style={{
              flex: 1, padding: "12px 14px", borderRadius: 12,
              border: "2px solid rgba(255,255,255,0.12)", fontSize: 16, fontWeight: 600,
              outline: "none", color: "#FFFFFF", background: "#111D27",
            }}
            onFocus={e => e.target.style.borderColor = "#E8C96A"}
            onBlur={e => e.target.style.borderColor = "rgba(255,255,255,0.12)"}
          />
          <button onClick={calculate} style={{
            background: "linear-gradient(135deg, #E8C96A, #D4B44A)",
            color: "#fff", border: "none", borderRadius: 12,
            padding: "0 20px", fontWeight: 700, fontSize: 15, cursor: "pointer",
            boxShadow: "0 4px 14px rgba(232,201,106,0.4)",
          }}>{tm.calculate}</button>
        </div>

        {result && (
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: "#E8C96A", marginBottom: 12, textAlign: "center" }}>
              ✅ {tm.result}
            </div>
            {result.map(c => (
              <div key={c.key} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                background: `${c.color}10`, border: `1px solid ${c.color}25`,
                borderRadius: 12, padding: "12px 14px", marginBottom: 8,
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 22 }}>{c.emoji}</span>
                  <span style={{ fontWeight: 600, color: "rgba(255,255,255,0.85)", fontSize: 14 }}>{c.label}</span>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontWeight: 800, fontSize: 18, color: c.color }}>{fmt(c.amount)}€</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)" }}>{tm.monthlyLabel}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card gradient="linear-gradient(135deg, rgba(41,182,246,0.10), rgba(41,182,246,0.04))">
        <p style={{ fontSize: 13, color: "#29B6F6", lineHeight: 1.6 }}>{tm.tip}</p>
      </Card>
    </div>
  );
}

/* ── Retos Tab ───────────────────────────────────────────────────── */
function RetosTab({ lang, profile, onXP, t }) {
  const tr = t.retos;
  const isKid = profile === "kid";
  const challenges = isKid ? tr.kidChallenges : tr.challenges;
  const [done, setDone] = useLocalState(`retos_done_v2_${lang}_${profile}`, {});

  function toggle(id, xp) {
    if (done[id]) return;
    setDone(prev => ({ ...prev, [id]: true }));
    onXP(xp);
  }

  const doneCount = Object.keys(done).filter(k => challenges.find(c => c.id === k)).length;
  const totalXP = challenges.filter(c => done[c.id]).reduce((s, c) => s + c.xp, 0);
  const allDone = doneCount === challenges.length;

  return (
    <div>
      {/* Header card */}
      <Card gradient="linear-gradient(135deg, rgba(41,182,246,0.15), rgba(41,182,246,0.06))">
        <h3 style={{ fontSize: 18, fontWeight: 800, color: "#FFFFFF", marginBottom: 4 }}>{tr.title}</h3>
        <p style={{ fontSize: 13, color: "rgba(255,255,255,0.75)", marginBottom: 12 }}>{tr.subtitle}</p>
        <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 24, fontWeight: 800, color: "#C9A84C" }}>{doneCount}/{challenges.length}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)" }}>{lang === "es" ? "Completados" : "Completed"}</div>
          </div>
          <div style={{ flex: 1, background: "rgba(255,255,255,0.10)", borderRadius: 99, height: 10 }}>
            <div style={{
              background: "linear-gradient(90deg, #29B6F6, #C9A84C)",
              borderRadius: 99, height: 10,
              width: `${(doneCount / challenges.length) * 100}%`,
              transition: "width 0.5s ease",
            }} />
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: "#29B6F6" }}>+{totalXP}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.45)" }}>XP</div>
          </div>
        </div>
      </Card>

      {allDone ? (
        <Card gradient="linear-gradient(135deg, rgba(201,168,76,0.18), rgba(201,168,76,0.06))" style={{ textAlign: "center", padding: "32px 18px" }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>🏆</div>
          <div style={{ fontSize: 18, fontWeight: 800, color: "rgba(201,168,76,0.9)" }}>{tr.allDone}</div>
        </Card>
      ) : (
        challenges.map(c => {
          const isDone = !!done[c.id];
          return (
            <div key={c.id} style={{
              background: isDone ? "linear-gradient(135deg,rgba(201,168,76,0.18),rgba(201,168,76,0.06))" : "#1E2E3E",
              border: isDone ? "2px solid rgba(201,168,76,0.55)" : "2px solid rgba(255,255,255,0.08)",
              borderRadius: 16, padding: "14px 16px", marginBottom: 10,
              display: "flex", alignItems: "center", gap: 12,
              boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
              transition: "all 0.3s ease",
              opacity: isDone ? 0.75 : 1,
            }}>
              <span style={{ fontSize: 26, flexShrink: 0 }}>{c.emoji}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: isDone ? "#C9A84C" : "rgba(255,255,255,0.9)", textDecoration: isDone ? "line-through" : "none" }}>
                  {c.text}
                </div>
                <div style={{ fontSize: 11, color: "#29B6F6", fontWeight: 700, marginTop: 2 }}>+{c.xp} {tr.xpEach}</div>
              </div>
              <button
                onClick={() => toggle(c.id, c.xp)}
                disabled={isDone}
                style={{
                  background: isDone
                    ? "linear-gradient(135deg, #C9A84C, #B8962C)"
                    : "linear-gradient(135deg, #29B6F6, #1E90D6)",
                  color: "#fff", border: "none", borderRadius: 10,
                  padding: "7px 14px", fontWeight: 700, fontSize: 12,
                  cursor: isDone ? "default" : "pointer",
                  flexShrink: 0,
                  boxShadow: isDone ? "none" : "0 3px 10px rgba(41,182,246,0.4)",
                }}
              >
                {isDone ? tr.completed : tr.pending}
              </button>
            </div>
          );
        })
      )}
    </div>
  );
}

/* ── Compound Tab ────────────────────────────────────────────────── */
function CompoundTab({ lang, t }) {
  const tc = t.compound;
  const [capital, setCapital] = useState(1000);
  const [monthly, setMonthly] = useState(100);
  const [years, setYears] = useState(20);
  const [rate, setRate] = useState(7);
  const [showChart, setShowChart] = useState(false);

  useEffect(() => { setShowChart(false); const t = setTimeout(() => setShowChart(true), 50); return () => clearTimeout(t); }, [capital, monthly, years, rate]);

  // Calculate compound growth year by year
  const yearlyData = [];
  let total = capital;
  for (let y = 1; y <= Math.min(years, 30); y++) {
    total = total * (1 + rate / 100) + monthly * 12 * (1 + rate / 200);
    const invested = capital + monthly * 12 * y;
    yearlyData.push({ year: y, total: Math.round(total), invested: Math.round(invested) });
  }

  const finalTotal = yearlyData[yearlyData.length - 1]?.total || 0;
  const totalInvested = capital + monthly * 12 * years;
  const gains = Math.max(0, finalTotal - totalInvested);
  const multiplier = totalInvested > 0 ? (finalTotal / totalInvested).toFixed(1) : 1;

  // Chart data — every N years
  const step = years <= 10 ? 1 : years <= 20 ? 2 : 5;
  const chartData = yearlyData
    .filter((_, i) => (i + 1) % step === 0 || i === yearlyData.length - 1)
    .slice(0, 12)
    .map(d => ({
      label: `Y${d.year}`,
      value: d.total,
      color: `hsl(${140 + (d.year / years) * 120},70%,50%)`,
    }));

  const accentColors = ["#C9A84C", "#29B6F6", "#E8C96A", "#0288D1"];

  return (
    <div>
      <Card>
        <h3 style={{ fontSize: 18, fontWeight: 800, color: "#FFFFFF", marginBottom: 4 }}>{tc.title}</h3>
        <p style={{ fontSize: 13, color: "rgba(255,255,255,0.45)", marginBottom: 20 }}>{tc.subtitle}</p>

        <Slider label={tc.capital}  value={capital}  min={0}    max={50000} step={100}  onChange={setCapital}  color="#C9A84C" unit="€" />
        <Slider label={tc.monthly}  value={monthly}  min={0}    max={2000}  step={10}   onChange={setMonthly}  color="#29B6F6" unit="€" />
        <Slider label={tc.years}    value={years}    min={1}    max={40}    step={1}    onChange={setYears}    color="#E8C96A" unit={` ${lang === "es" ? "años" : "yrs"}`} />
        <Slider label={tc.rate}     value={rate}     min={1}    max={20}    step={0.5}  onChange={setRate}     color="#0288D1" unit="%" />
      </Card>

      {/* Results */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
        {[
          { label: tc.invested,   value: `${fmt(totalInvested)}€`,   color: "#C9A84C", emoji: "💰" },
          { label: tc.gains,      value: `${fmt(gains)}€`,            color: "#29B6F6", emoji: "📈" },
          { label: tc.total,      value: `${fmt(finalTotal)}€`,       color: "#E8C96A", emoji: "🏆" },
          { label: tc.multiplier, value: `×${multiplier}`,            color: "#0288D1", emoji: "🚀" },
        ].map((item, i) => (
          <Card key={i} style={{ margin: 0, textAlign: "center", padding: "16px 10px" }}>
            <div style={{ fontSize: 26 }}>{item.emoji}</div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.45)", fontWeight: 500, marginTop: 4 }}>{item.label}</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: item.color, marginTop: 2 }}>{item.value}</div>
          </Card>
        ))}
      </div>

      {/* Bar Chart */}
      <Card>
        <div style={{ fontSize: 12, fontWeight: 700, color: "rgba(255,255,255,0.85)", marginBottom: 12, textAlign: "center" }}>
          📊 {tc.chartLabel}
        </div>
        {showChart && <BarChart data={chartData} height={130} />}
      </Card>

      <Card gradient="linear-gradient(135deg, rgba(41,182,246,0.10), rgba(41,182,246,0.04))">
        <p style={{ fontSize: 13, color: "rgba(255,255,255,0.88)", lineHeight: 1.6, fontStyle: "italic" }}>{tc.tip}</p>
      </Card>
    </div>
  );
}

/* ── Bottom Nav ──────────────────────────────────────────────────── */
function BottomNav({ tab, setTab, t }) {
  const items = [
    { key: "dashboard", emoji: "🏠", label: t.nav.dashboard },
    { key: "huchas",    emoji: "🪣", label: t.nav.huchas },
    { key: "method",    emoji: "📊", label: t.nav.method },
    { key: "retos",     emoji: "🎯", label: t.nav.retos },
    { key: "compound",  emoji: "💸", label: t.nav.compound },
  ];
  return (
    <div style={{
      position: "fixed", bottom: 0, left: 0, right: 0,
      background: "rgba(10,24,36,0.98)",
      backdropFilter: "blur(12px)",
      borderTop: "1px solid rgba(255,255,255,0.08)",
      display: "flex", justifyContent: "space-around",
      padding: "8px 0 calc(8px + env(safe-area-inset-bottom))",
      zIndex: 100,
    }}>
      {items.map(item => {
        const active = tab === item.key;
        return (
          <button key={item.key} onClick={() => setTab(item.key)} style={{
            background: "none", border: "none", cursor: "pointer",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 2,
            padding: "4px 8px", borderRadius: 12,
            transition: "transform 0.15s",
            transform: active ? "scale(1.12)" : "scale(1)",
          }}>
            <span style={{ fontSize: 20, filter: active ? "none" : "grayscale(0.6) opacity(0.6)" }}>{item.emoji}</span>
            <span style={{ fontSize: 9, fontWeight: active ? 700 : 400, color: active ? "#C9A84C" : "rgba(255,255,255,0.35)", letterSpacing: "0.02em" }}>
              {item.label}
            </span>
          </button>
        );
      })}
    </div>
  );
}

/* ── Header ──────────────────────────────────────────────────────── */
function Header({ lang, setLang, profile, setProfile, xp, streak, t }) {
  const p = T[lang].profiles[profile];
  return (
    <div style={{
      background: "rgba(10,24,36,0.97)",
      backdropFilter: "blur(12px)",
      borderBottom: "1px solid rgba(255,255,255,0.07)",
      padding: "10px 16px",
      display: "flex", alignItems: "center", justifyContent: "space-between",
      position: "sticky", top: 0, zIndex: 80,
    }}>
      <button onClick={() => setProfile(null)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontSize: 26 }}>{p.emoji}</span>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: p.color }}>{p.level}</div>
          <div style={{ fontSize: 13, fontWeight: 700, color: "#FFFFFF" }}>{p.label}</div>
        </div>
      </button>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 4, background: "#fef9ee", borderRadius: 20, padding: "4px 10px" }}>
          <span style={{ fontSize: 14 }}>⚡</span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#29B6F6" }}>{fmt(xp)}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 4, background: "rgba(255,255,255,0.08)", borderRadius: 20, padding: "4px 10px" }}>
          <span style={{ fontSize: 14 }}>🔥</span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#0288D1" }}>{streak}</span>
        </div>
        <button onClick={() => setLang(l => l === "es" ? "en" : "es")} style={{
          background: "rgba(255,255,255,0.12)", color: "#fff",
          border: "none", borderRadius: 20,
          padding: "5px 12px", fontWeight: 700, fontSize: 11,
          cursor: "pointer", letterSpacing: "0.05em",
        }}>{t.langToggle}</button>
      </div>
    </div>
  );
}

/* ── Global Styles (injected once) ──────────────────────────────── */
const GLOBAL_STYLE = `
  @keyframes toastIn {
    from { opacity: 0; transform: translateX(-50%) translateY(20px) scale(0.9); }
    to   { opacity: 1; transform: translateX(-50%) translateY(0)    scale(1);   }
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { background: #0C1E2B !important; }
  input[type=range] { -webkit-appearance: none; appearance: none; height: 6px; border-radius: 99px; outline: none; cursor: pointer; }
  input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%; background: currentColor; cursor: pointer; box-shadow: 0 2px 6px rgba(0,0,0,0.2); }
  input[type=number] { -moz-appearance: textfield; }
  input[type=number]::-webkit-outer-spin-button,
  input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
  ::-webkit-scrollbar { width: 4px; height: 4px; }
  ::-webkit-scrollbar-track { background: transparent; }
  ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 99px; }
`;

/* ══════════════════════════════════════════════════════════════════
   MAIN APP
   ══════════════════════════════════════════════════════════════════ */
function App() {
  const [lang, setLang] = useLocalState("ml_v2_lang", "es");
  const [profile, setProfile] = useLocalState("ml_v2_profile", null);
  const [tab, setTab] = useLocalState("ml_v2_tab", "dashboard");
  const [xp, setXP] = useLocalState("ml_v2_xp", 0);
  const [streak, setStreak] = useLocalState("ml_v2_streak", 1);
  const [savings, setSavings] = useLocalState("ml_v2_savings", 0);
  const [toast, setToast] = useState(null);
  const styleRef = useRef(false);

  // Inject global styles once
  useEffect(() => {
    if (styleRef.current) return;
    styleRef.current = true;
    const el = document.createElement("style");
    el.textContent = GLOBAL_STYLE;
    document.head.appendChild(el);
    // Override body bg
    document.body.style.background = "#0C1E2B";
    document.body.style.minHeight = "100vh";
  }, []);

  // Streak logic: update on daily visit
  useEffect(() => {
    const key = "ml_v2_last_visit";
    const today = new Date().toDateString();
    const last = localStorage.getItem(key);
    if (!last) { localStorage.setItem(key, today); return; }
    if (last === today) return;
    const yesterday = new Date(Date.now() - 86400000).toDateString();
    if (last === yesterday) setStreak(s => s + 1);
    else setStreak(1);
    localStorage.setItem(key, today);
  }, []);

  function addXP(amount) {
    setXP(x => x + amount);
    setToast(amount);
  }

  const t = T[lang];

  // No profile selected → show profile picker
  if (!profile) {
    return (
      <div style={{ background: "#0C1E2B", minHeight: "60vh" }}>
        {/* Lang toggle on profile screen */}
        <div style={{ display: "flex", justifyContent: "flex-end", padding: "12px 16px" }}>
          <button onClick={() => setLang(l => l === "es" ? "en" : "es")} style={{
            background: "rgba(255,255,255,0.12)", color: "#fff", border: "none",
            borderRadius: 20, padding: "5px 14px", fontWeight: 700, fontSize: 11,
            cursor: "pointer",
          }}>{t.langToggle}</button>
        </div>
        <ProfileSelect lang={lang} onSelect={p => { setProfile(p); addXP(5); }} />
      </div>
    );
  }

  return (
    <div style={{ background: "#0C1E2B", minHeight: "100vh", paddingBottom: 80 }}>
      <Header lang={lang} setLang={setLang} profile={profile} setProfile={setProfile} xp={xp} streak={streak} t={t} />

      <div style={{ maxWidth: 520, margin: "0 auto", padding: "16px 14px 0" }}>
        {tab === "dashboard" && <DashboardTab lang={lang} profile={profile} xp={xp} streak={streak} savings={savings} t={t} />}
        {tab === "huchas"    && <HuchasTab lang={lang} onXP={addXP} t={t} />}
        {tab === "method"    && <MethodTab lang={lang} onXP={addXP} t={t} />}
        {tab === "retos"     && <RetosTab lang={lang} profile={profile} onXP={addXP} t={t} />}
        {tab === "compound"  && <CompoundTab lang={lang} t={t} />}
      </div>

      <BottomNav tab={tab} setTab={setTab} t={t} />
      {toast && <XPToast amount={toast} onDone={() => setToast(null)} />}
    </div>
  );
}
