// Screen 2 (Allocation) and Screen 3 (Goals)

function AllocationScreen({ T, t, accent, theme, alloc, setAlloc, onNext }) {
  const items = [
    { key: "bank", label: t.bank, c: "#10b981" }, // Emerald green
    { key: "realEstate", label: t.realEstate, c: "#3b82f6" }, // Blue
    { key: "stocks", label: t.stocks, c: "#ec4899" }, // Pink
    { key: "bonds", label: t.bonds, c: "#f59e0b" }, // Amber
    { key: "gold", label: t.gold, c: "#eab308" }, // Yellow
    { key: "crypto", label: t.crypto, c: "#8b5cf6" }, // Violet
  ];
  const total = items.reduce((s, i) => s + (alloc[i.key] || 0), 0);
  const left = 100 - total;
  const balanced = total === 100;

  // Adjust slider, then redistribute the delta proportionally across the others
  const onChange = (key, raw) => {
    const v = Math.max(0, Math.min(100, Math.round(raw)));
    const others = items.filter(i => i.key !== key);
    const otherTotal = others.reduce((s, i) => s + (alloc[i.key] || 0), 0);
    const remaining = 100 - v;
    const next = { ...alloc, [key]: v };
    if (otherTotal === 0) {
      // distribute equally
      others.forEach(o => next[o.key] = Math.round(remaining / others.length));
    } else {
      others.forEach(o => {
        next[o.key] = Math.max(0, Math.round((alloc[o.key] / otherTotal) * remaining));
      });
    }
    // fix rounding to make sum = 100
    const newTotal = items.reduce((s, i) => s + next[i.key], 0);
    const diff = 100 - newTotal;
    if (diff !== 0) {
      const target = others.find(o => next[o.key] + diff >= 0) || others[0];
      next[target.key] = Math.max(0, next[target.key] + diff);
    }
    setAlloc(next);
  };

  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>{t.allocKicker}</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={42}>{t.allocTitle}</SerifTitle>
        <div style={{ height: 10 }} />
        <Body T={T} size={13}>{t.allocSub}</Body>

        <div style={{ height: 22 }} />

        {/* Stacked horizontal bar visualisation of the allocation */}
        <div style={{
          height: 12, borderRadius: 999, overflow: "hidden",
          display: "flex", background: T.surfaceStrong,
          border: `1px solid ${T.border}`,
        }}>
          {items.map(i => alloc[i.key] > 0 && (
            <div key={i.key} style={{
              width: `${alloc[i.key]}%`, background: i.c,
              transition: "width 220ms cubic-bezier(0.2, 0.8, 0.2, 1)",
            }} />
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10 }}>
          <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textMute, letterSpacing: 0.6, textTransform: "uppercase" }}>{t.allocTotal}</div>
          <div style={{ fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600, color: balanced ? accent.primary : "#A66B5C", fontVariantNumeric: "tabular-nums" }}>
            {total}% {balanced ? `· ${t.allocBalanced}` : `· ${t.allocLeft} ${left > 0 ? "+" : ""}${left}%`}
          </div>
        </div>

        <div style={{ height: 26 }} />

        {/* Slider rows */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {items.map(i => (
            <AllocRow key={i.key} T={T} accent={accent}
              label={i.label} color={i.c}
              value={alloc[i.key] || 0}
              onChange={(v) => onChange(i.key, v)}
            />
          ))}
        </div>

        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={!balanced}>{t.next}</PrimaryButton>
      </div>
    </div>
  );
}

function AllocRow({ label, color, value, onChange, T, accent }) {
  return (
    <div style={{ paddingBottom: 16, borderBottom: `1px solid ${T.border}` }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 8, height: 8, borderRadius: 2, background: color }} />
          <span style={{ fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500, color: T.text }}>{label}</span>
        </div>
        <span style={{ fontFamily: FONTS.fraunces, fontSize: 20, color: T.text, fontVariantNumeric: "tabular-nums", letterSpacing: -0.5 }}>
          {value}<span style={{ fontSize: 12, color: T.textMute, marginLeft: 2 }}>%</span>
        </span>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 12 }}>
        {[0, 5, 10, 30, 50, 75, 100].map(pct => (
          <button key={pct} onClick={() => onChange(pct)} style={{
            padding: "4px 8px", borderRadius: 6, 
            border: `1px solid ${value === pct ? color : T.border}`,
            background: value === pct ? `${color}20` : T.surface,
            color: value === pct ? color : T.text, 
            fontSize: 12, fontFamily: FONTS.ui, cursor: "pointer",
            transition: "all 150ms"
          }}>{pct}%</button>
        ))}
      </div>
    </div>
  );
}

function GoalsScreen({ T, t, accent, theme, goals, setGoals, onNext }) {
  const cards = [
    { key: "growth", title: t.goal1Title, body: t.goal1Body, img: "uploads/high_growth_icon_1778013442682.png" },
    { key: "preserve", title: t.goal2Title, body: t.goal2Body, img: "uploads/preservation_icon_1778013461383.png" },
    { key: "income", title: t.goal3Title, body: t.goal3Body, img: "uploads/passive_income_icon_1778013476266.png" },
    { key: "retire", title: t.goal4Title, body: t.goal4Body, img: "uploads/retirement_icon_1778013493933.png" },
    { key: "children", title: t.goal5Title, body: t.goal5Body, img: "uploads/children_icon_1778013507207.png" },
    { key: "freedom", title: t.goal6Title, body: t.goal6Body, img: "uploads/financial_freedom_icon_1778013524803.png" },
  ];
  const toggle = (k) => {
    if (goals.includes(k)) setGoals(goals.filter(g => g !== k));
    else if (goals.length < 3) setGoals([...goals, k]);
  };
  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>{t.goalsKicker}</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={40}>{t.goalsTitle}</SerifTitle>
        <div style={{ height: 10 }} />
        <Body T={T} size={13}>{t.goalsSub}</Body>

        <div style={{ height: 8 }} />
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <span style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textMute, letterSpacing: 0.6, textTransform: "uppercase" }}>
            {goals.length} / 3 {t.selected.toLowerCase()}
          </span>
        </div>

        <div style={{ height: 16 }} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {cards.map((c, idx) => {
            const sel = goals.includes(c.key);
            const order = goals.indexOf(c.key);
            return (
              <button key={c.key} onClick={() => toggle(c.key)} style={{
                position: "relative", textAlign: "left",
                padding: "14px 12px", height: 115,
                borderRadius: 14, cursor: "pointer",
                background: sel ? accent.primarySoft : T.surface,
                border: `1px solid ${sel ? accent.primary : T.border}`,
                boxShadow: sel ? `0 0 0 3px ${accent.primaryGlow}, inset 0 1px 0 ${accent.primary}30` : "none",
                transition: "all 200ms cubic-bezier(0.2, 0.8, 0.2, 1)",
                overflow: "hidden",
                display: "flex", flexDirection: "column", justifyContent: "flex-start", alignItems: "flex-start",
              }}>
                <img src={c.img} style={{ 
                  position: "absolute", right: -15, bottom: -15, 
                  width: 90, height: 90, 
                  objectFit: "cover", 
                  opacity: sel ? 1 : 0.7, 
                  transition: "opacity 200ms",
                  zIndex: 0,
                  pointerEvents: "none"
                }} />
                {sel && (
                  <div style={{
                    position: "absolute", top: 10, right: 10,
                    width: 22, height: 22, borderRadius: "50%", background: accent.primary,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontFamily: FONTS.ui, fontSize: 11, fontWeight: 700, color: "#0B0F19",
                    zIndex: 2
                  }}>{order + 1}</div>
                )}
                <div style={{ position: "relative", zIndex: 1, width: "100%" }}>
                  <div style={{ fontFamily: FONTS.fraunces, fontSize: 15, fontWeight: 500, color: T.text, lineHeight: 1.25, letterSpacing: -0.3, marginBottom: 4 }}>
                    {c.title}
                  </div>
                  <Body T={T} size={11} style={{ lineHeight: 1.35, opacity: 0.85, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden", paddingRight: 4 }}>{c.body}</Body>
                </div>
              </button>
            );
          })}
        </div>

        <div style={{ height: 28 }} />
        <SerifTitle T={T} size={22}>Thời hạn đầu tư</SerifTitle>
        <div style={{ height: 16 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {[
            { value: "lt2", label: "Dưới 2 năm" },
            { value: "2to5", label: "2 - 5 năm" },
            { value: "5to10", label: "5 - 10 năm" },
            { value: "gt10", label: "Trên 10 năm / để lại cho con cái" },
          ].map(opt => (
            <button key={opt.value} onClick={() => setTimeHorizon(opt.value)} style={{
              textAlign: "left", padding: "16px", borderRadius: 14,
              background: timeHorizon === opt.value ? accent.primarySoft : T.surface,
              border: `1px solid ${timeHorizon === opt.value ? accent.primary : T.border}`,
              color: T.text, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500, cursor: "pointer",
              transition: "all 150ms"
            }}>{opt.label}</button>
          ))}
        </div>

        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={goals.length === 0 || !timeHorizon}>{t.analyze}</PrimaryButton>
      </div>
    </div>
  );
}

function AssetPerformanceScreen({ T, t, accent, theme, alloc, assetPerf, setAssetPerf, onNext }) {
  const items = [
    { key: "bank", label: t.bank, icon: "🏦" },
    { key: "realEstate", label: t.realEstate, icon: "🏠" },
    { key: "stocks", label: t.stocks, icon: "📈" },
    { key: "bonds", label: t.bonds, icon: "📜" },
    { key: "gold", label: t.gold, icon: "🥇" },
    { key: "crypto", label: t.crypto, icon: "₿" },
  ];
  
  const perfOptions = {
    bank: ["< 4%", "4–5%", "5–6%", "6–7%", "> 7%", "Không rõ"],
    gold: ["< 1 năm", "1–3 năm", "3–5 năm", "> 5 năm", "Mua nhiều lần"],
    realEstate: ["Đang tăng tốt", "Giữ nguyên / tăng nhẹ", "Khó bán / giảm", "Cho thuê — có dòng tiền", "Không cho thuê"],
    stocks: ["Lỗ", "Hoà vốn", "Lãi 0–10%", "Lãi 10–25%", "Lãi 25–50%", "Không theo dõi"],
    bonds: ["Không rõ", "Đang nhận lãi tốt", "Chậm trả lãi"], 
    crypto: ["Lỗ", "Hoà vốn", "Lãi", "Không theo dõi"] 
  };

  const activeAssets = items.filter(i => alloc[i.key] > 0);
  const allSet = activeAssets.every(i => (assetPerf || {})[i.key]);

  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>HIỆU SUẤT HIỆN TẠI</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={32}>Hiệu suất hiện tại của bạn</SerifTitle>
        <div style={{ height: 10 }} />
        <Body T={T} size={13}>Chúng tôi cần ước lượng để so sánh với chuẩn tối ưu.</Body>

        <div style={{ height: 26 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {activeAssets.map(i => (
            <div key={i.key} style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 16, padding: 16 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
                <span style={{ fontSize: 16, fontWeight: 600, fontFamily: FONTS.ui, color: T.text }}>{i.icon} {i.label}</span>
                <span style={{ fontSize: 14, color: accent.primary, fontWeight: 600, fontFamily: FONTS.ui }}>{alloc[i.key]}%</span>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {perfOptions[i.key].map(opt => (
                  <button key={opt} onClick={() => setAssetPerf({ ...(assetPerf || {}), [i.key]: opt })} style={{
                    padding: "6px 12px", borderRadius: 8,
                    border: `1px solid ${(assetPerf || {})[i.key] === opt ? accent.primary : T.border}`,
                    background: (assetPerf || {})[i.key] === opt ? `${accent.primary}20` : "transparent",
                    color: (assetPerf || {})[i.key] === opt ? accent.primary : T.text,
                    fontSize: 13, fontFamily: FONTS.ui, cursor: "pointer", transition: "all 150ms"
                  }}>{opt}</button>
                ))}
              </div>
            </div>
          ))}
        </div>

        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={!allSet}>{t.next}</PrimaryButton>
      </div>
    </div>
  );
}

function RiskToleranceScreen({ T, t, accent, theme, riskTol, setRiskTol, onNext }) {
  const options = [
    { value: "withdraw", label: "\"Nếu giảm 10%, tôi rút hết\"" },
    { value: "hold1020", label: "\"Tôi chịu được giảm 10-20% nếu kỳ vọng dài hạn tốt\"" },
    { value: "hold2030", label: "\"Tôi chịu được giảm 20-30%\" - tôi đầu tư dài hạn" },
    { value: "ignore", label: "\"Tôi không quan tâm biến động ngắn hạn\"" },
  ];
  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>KHẨU VỊ RỦI RO</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={32}>Khi danh mục giảm mạnh, bạn sẽ...</SerifTitle>
        <div style={{ height: 26 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {options.map(opt => (
            <button key={opt.value} onClick={() => setRiskTol(opt.value)} style={{
              textAlign: "left", padding: "16px", borderRadius: 14,
              background: riskTol === opt.value ? accent.primarySoft : T.surface,
              border: `1px solid ${riskTol === opt.value ? accent.primary : T.border}`,
              color: T.text, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500, cursor: "pointer", transition: "all 150ms", lineHeight: 1.4
            }}>{opt.label}</button>
          ))}
        </div>
        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={!riskTol}>{t.next}</PrimaryButton>
      </div>
    </div>
  );
}

function ExpectedReturnScreen({ T, t, accent, theme, expRet, setExpRet, onNext }) {
  const options = [
    { value: "bank", label: "Ngang lãi suất ngân hàng (~5–7%)" },
    { value: "bank_plus", label: "Tốt hơn ngân hàng một chút (8–12%)" },
    { value: "market", label: "Tốt hơn đáng kể (12–20%)" },
    { value: "max", label: "Tối đa hoá (20%+)" },
  ];
  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>MỤC TIÊU LỢI NHUẬN</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={32}>Kỳ vọng lợi nhuận hàng năm?</SerifTitle>
        <div style={{ height: 26 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {options.map(opt => (
            <button key={opt.value} onClick={() => setExpRet(opt.value)} style={{
              textAlign: "left", padding: "16px", borderRadius: 14,
              background: expRet === opt.value ? accent.primarySoft : T.surface,
              border: `1px solid ${expRet === opt.value ? accent.primary : T.border}`,
              color: T.text, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500, cursor: "pointer", transition: "all 150ms"
            }}>{opt.label}</button>
          ))}
        </div>
        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={!expRet}>{t.next}</PrimaryButton>
      </div>
    </div>
  );
}

function PrimaryConcernsScreen({ T, t, accent, theme, concerns, setConcerns, onNext }) {
  const options = [
    { value: "bank_low", label: "Tiền gửi không đủ sinh lời" },
    { value: "asset_stagnant", label: "Vàng / BĐS không còn tăng tốt" },
    { value: "stock_picking", label: "Không biết chọn cổ phiếu nào" },
    { value: "scam", label: "Sợ bị lừa đảo, mất tiền" },
    { value: "diversify", label: "Muốn đa dạng nhưng không biết cách" },
    { value: "time", label: "Không có thời gian theo dõi" },
  ];
  const toggle = (k) => {
    if (concerns.includes(k)) setConcerns(concerns.filter(c => c !== k));
    else if (concerns.length < 2) setConcerns([...concerns, k]);
  };
  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>NỖI LO TÀI CHÍNH</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={32}>Lo ngại chính của bạn?</SerifTitle>
        <div style={{ height: 10 }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Body T={T} size={13}>Chọn tối đa 2 lựa chọn</Body>
          <span style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textMute, letterSpacing: 0.6, textTransform: "uppercase" }}>{concerns.length} / 2</span>
        </div>
        <div style={{ height: 26 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {options.map(opt => {
            const sel = concerns.includes(opt.value);
            return (
              <button key={opt.value} onClick={() => toggle(opt.value)} style={{
                textAlign: "left", padding: "16px", borderRadius: 14,
                background: sel ? accent.primarySoft : T.surface,
                border: `1px solid ${sel ? accent.primary : T.border}`,
                color: T.text, fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500, cursor: "pointer", transition: "all 150ms"
              }}>{opt.label}</button>
            );
          })}
        </div>
        <div style={{ height: 32 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={concerns.length === 0}>{t.next}</PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, { AllocationScreen, GoalsScreen, AssetPerformanceScreen, RiskToleranceScreen, ExpectedReturnScreen, PrimaryConcernsScreen });
