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

function AllocationScreen({ T, t, accent, theme, alloc, setAlloc, onNext }) {
  const items = [
    { key: "bank", label: t.bank, c: accent.chart[0] },
    { key: "realEstate", label: t.realEstate, c: accent.chart[1] },
    { key: "stocks", label: t.stocks, c: accent.chart[2] },
    { key: "bonds", label: t.bonds, c: accent.chart[3] },
    { key: "gold", label: t.gold, c: accent.chart[4] },
    { key: "crypto", label: t.crypto, c: accent.chart[5] },
  ];
  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>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 8, height: 8, borderRadius: 2, background: color }} />
          <span style={{ fontFamily: FONTS.ui, fontSize: 13, fontWeight: 500, color: T.text }}>{label}</span>
        </div>
        <span style={{ fontFamily: FONTS.fraunces, fontSize: 22, color: T.text, fontVariantNumeric: "tabular-nums", letterSpacing: -0.5 }}>
          {value}<span style={{ fontSize: 12, color: T.textMute, marginLeft: 2 }}>%</span>
        </span>
      </div>
      <div style={{ position: "relative", height: 6, background: T.surfaceStrong, borderRadius: 999 }}>
        <div style={{ position: "absolute", left: 0, top: 0, height: "100%", width: `${value}%`, background: color, borderRadius: 999, transition: "width 180ms" }} />
        <input type="range" min="0" max="100" value={value} onChange={(e) => onChange(parseInt(e.target.value))}
          style={{
            position: "absolute", inset: -12, width: "100%", height: 30,
            opacity: 0, cursor: "grab",
          }}
        />
        <div style={{
          position: "absolute", left: `${value}%`, top: "50%",
          transform: "translate(-50%, -50%)",
          width: 20, height: 20, borderRadius: "50%",
          background: T.bgElev2, border: `2px solid ${color}`,
          boxShadow: `0 4px 12px ${color}50`,
          pointerEvents: "none",
        }} />
      </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 }} />
        <PrimaryButton onClick={onNext} accent={accent} T={T} disabled={goals.length === 0}>{t.analyze}</PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, { AllocationScreen, GoalsScreen });
