// rewards.jsx - VaultRewards: claim-free loyalty tiers (Bronze → Silver → Gold).
// Everyone starts on Bronze and accrues cashback monthly at their tier's annual
// rate. Tiers rise with consecutive claim-free years; a claim resets the tier
// clock to Bronze but the accrued balance is never clawed back. The ladder
// itself (rates + thresholds) is ops-managed and read live from the backend.
const { useState: useStateR, useEffect: useEffectR } = React;

const TIER_LOOK = {
  bronze: { grad: "linear-gradient(135deg,#b0764a,#8a5a34)", icon: "shield" },
  silver: { grad: "linear-gradient(135deg,#9aa5b8,#6e7a90)", icon: "trend" },
  gold: { grad: "linear-gradient(135deg,#e0b252,#b5872a)", icon: "sparkle" },
};

// Offline fallback mirroring lib/rewards defaults, so the page renders sensibly
// before the API answers (fresh accounts are Bronze with nothing accrued yet).
function localRewards(assets) {
  const insured = assets.filter((a) => a.insurer);
  const annualPremium = insured.reduce((s, a) => s + (a.premium || 0), 0);
  const cfg = { tiers: [
    { id: "bronze", name: "Bronze", ratePct: 5, afterYears: 0 },
    { id: "silver", name: "Silver", ratePct: 7, afterYears: 2 },
    { id: "gold", name: "Gold", ratePct: 9, afterYears: 5 },
  ] };
  return {
    tier: cfg.tiers[0],
    nextTier: { ...cfg.tiers[1], monthsToGo: 24, progressPct: 0 },
    claimFreeYears: 0, claimFreeSince: new Date().toISOString().slice(0, 10),
    accruedNaira: 0,
    monthlyAccrualNaira: Math.round(annualPremium * 0.05 / 12),
    annualPremiumNaira: annualPremium,
    perPolicy: insured.map((a) => ({ asset: a.name, insurer: a.insurer, premiumNaira: a.premium || 0, accruedNaira: 0 })),
    wasReset: false,
    config: cfg,
  };
}

function Rewards({ assets, profile, userName, onChat, addToast, claims = [] }) {
  const D = window.VC_DATA;
  const [rw, setRw] = useStateR(() => localRewards(assets));
  const [live, setLive] = useStateR(false);
  const [redeemed, setRedeemed] = useStateR(false);
  const [redeemOpen, setRedeemOpen] = useStateR(false);

  useEffectR(() => {
    let on = true;
    fetch("/api/rewards").then((r) => (r.ok ? r.json() : null)).then((d) => {
      if (on && d && d.tier) { setRw(d); setLive(true); }
    }).catch(() => {});
    return () => { on = false; };
  }, [assets.length, claims.length]);

  const look = TIER_LOOK[rw.tier.id] || TIER_LOOK.bronze;
  const balance = redeemed ? 0 : rw.accruedNaira;
  const animVal = window.useCountUp(balance, 1200, [balance]);
  const progress = rw.nextTier ? rw.nextTier.progressPct / 100 : 1;

  return (
    <div className="vc-page" style={{ padding: "28px 34px 60px", maxWidth: 1180, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
        <div>
          <h1 className="display" style={{ fontSize: 32, display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ display: "grid", placeItems: "center", width: 40, height: 40, borderRadius: 13, background: "var(--accent-soft)", color: "var(--accent)" }}><window.Icon name="trend" size={22} /></span>
            VaultRewards
          </h1>
          <p style={{ color: "var(--text-muted)", fontSize: 15, marginTop: 8 }}>Stay claim-free, climb the tiers, and earn up to <b>{rw.config.tiers[rw.config.tiers.length - 1].ratePct}%</b> of your annual premium back every year.</p>
        </div>
      </div>

      {/* hero: current tier + accrued balance */}
      <div style={{ position: "relative", overflow: "hidden", borderRadius: 26, padding: "32px 34px", marginTop: 22, background: look.grad, color: "#fff", boxShadow: "var(--shadow-md)" }}>
        <div style={{ position: "absolute", right: -60, top: -60, width: 240, height: 240, borderRadius: 999, background: "rgba(255,255,255,.12)" }} />
        <div style={{ position: "absolute", right: 80, bottom: -90, width: 200, height: 200, borderRadius: 999, background: "rgba(255,255,255,.08)" }} />
        <div className="vc-grid" style={{ position: "relative", display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 30, alignItems: "center" }}>
          <div>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 13px", borderRadius: 999, background: "rgba(255,255,255,.2)", fontSize: 12.5, fontWeight: 700, backdropFilter: "blur(6px)" }}>
              <window.Icon name={look.icon} size={14} />{rw.tier.name} tier · up to {rw.tier.ratePct}% a year
            </div>
            <div style={{ fontSize: 13.5, opacity: 0.92, fontWeight: 600, marginTop: 18 }}>Cashback accrued</div>
            <div className="display mono" style={{ fontSize: 52, lineHeight: 1, marginTop: 6 }}>{D.fmtFull(Math.round(animVal))}</div>
            <div style={{ fontSize: 13.5, opacity: 0.92, marginTop: 8 }}>
              {rw.annualPremiumNaira
                ? `Accruing ~${D.fmtFull(rw.monthlyAccrualNaira)} each claim-free month (${rw.tier.ratePct}% of ${D.fmtFull(rw.annualPremiumNaira)} premium / 12)`
                : "Insure an asset to start accruing cashback every month."}
            </div>
            {rw.nextTier && (
              <div style={{ marginTop: 18, maxWidth: 400 }}>
                <div style={{ height: 9, borderRadius: 999, background: "rgba(255,255,255,.25)", overflow: "hidden" }}>
                  <div style={{ height: "100%", width: (progress * 100) + "%", borderRadius: 999, background: "#fff", transition: "width .6s var(--ease)" }} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, opacity: 0.92, marginTop: 7, fontWeight: 600 }}>
                  <span>{rw.tier.name}</span>
                  <span>{rw.nextTier.monthsToGo} claim-free month{rw.nextTier.monthsToGo > 1 ? "s" : ""} to {rw.nextTier.name} ({rw.nextTier.ratePct}%)</span>
                </div>
              </div>
            )}
            <div style={{ display: "flex", gap: 10, marginTop: 22, flexWrap: "wrap" }}>
              <button onClick={() => setRedeemOpen(true)} disabled={redeemed || !balance} style={{ padding: "13px 24px", borderRadius: 999, background: "#fff", color: "#33261a", fontWeight: 700, fontSize: 14.5, opacity: redeemed || !balance ? 0.6 : 1, display: "inline-flex", alignItems: "center", gap: 8 }}><window.Icon name="download" size={17} />{redeemed ? "Redeemed ✓" : "Redeem cashback"}</button>
              <button onClick={() => onChat("How does VaultRewards work?")} style={{ padding: "13px 22px", borderRadius: 999, background: "rgba(255,255,255,.2)", color: "#fff", fontWeight: 700, fontSize: 14.5, backdropFilter: "blur(6px)", display: "inline-flex", alignItems: "center", gap: 8 }}><window.Icon name="sparkle" size={16} />Ask Cova</button>
            </div>
          </div>
          {/* claim-free clock dial */}
          <div style={{ display: "grid", placeItems: "center" }}>
            <div style={{ position: "relative", width: 180, height: 180 }}>
              <svg width="180" height="180" style={{ transform: "rotate(-90deg)" }}>
                <circle cx="90" cy="90" r="78" fill="none" stroke="rgba(255,255,255,.25)" strokeWidth="14" />
                <circle cx="90" cy="90" r="78" fill="none" stroke="#fff" strokeWidth="14" strokeLinecap="round" strokeDasharray={2 * Math.PI * 78} strokeDashoffset={2 * Math.PI * 78 * (1 - progress)} />
              </svg>
              <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
                <div>
                  <div className="display" style={{ fontSize: 40 }}>{rw.claimFreeYears >= 1 ? rw.claimFreeYears.toFixed(1) : Math.round(rw.claimFreeYears * 12)}</div>
                  <div style={{ fontSize: 12, opacity: 0.92, fontWeight: 600 }}>{rw.claimFreeYears >= 1 ? (rw.claimFreeYears.toFixed(1) === "1.0" ? "year" : "years") : (Math.round(rw.claimFreeYears * 12) === 1 ? "month" : "months")} claim-free</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* the ladder + how it works */}
      <div className="vc-grid" style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 16, marginTop: 16 }}>
        <div style={{ padding: 22, borderRadius: 20, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)" }}>
          <h3 className="display" style={{ fontSize: 17 }}>The tier ladder</h3>
          <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 6 }}>
            Everyone starts on <b>{rw.config.tiers[0].name}</b>. Tiers rise with consecutive claim-free years. You're on <b style={{ color: "var(--accent)" }}>{rw.tier.name}</b>{rw.wasReset ? " (a past claim restarted your clock)" : ""}.
          </p>
          <div className="vc-grid-2" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10, marginTop: 18 }}>
            {rw.config.tiers.map((t2) => {
              const on = rw.tier.id === t2.id;
              const lk = TIER_LOOK[t2.id] || TIER_LOOK.bronze;
              return (
                <div key={t2.id} style={{ padding: 14, borderRadius: 14, textAlign: "center", background: on ? "var(--accent-soft)" : "var(--surface-2)", border: "1.5px solid " + (on ? "var(--accent)" : "var(--border)") }}>
                  <div style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 11, margin: "0 auto", background: lk.grad, color: "#fff" }}><window.Icon name={lk.icon} size={17} /></div>
                  <div style={{ fontWeight: 700, fontSize: 13.5, marginTop: 9, color: on ? "var(--accent-ink)" : "var(--text)" }}>{t2.name}</div>
                  <div className="mono" style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>{t2.ratePct}%</div>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", fontWeight: 600, marginTop: 4 }}>{t2.afterYears ? `after ${t2.afterYears} claim-free yr${t2.afterYears > 1 ? "s" : ""}` : "from day one"}</div>
                  {on && <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--accent)", marginTop: 4 }}>CURRENT</div>}
                </div>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 14, padding: 12, borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
            <window.Icon name="alert" size={15} style={{ color: "var(--warning)", flexShrink: 0, marginTop: 1 }} />
            <span style={{ fontSize: 12.5, color: "var(--text-muted)", lineHeight: 1.5 }}>Lodging a claim resets you to {rw.config.tiers[0].name}, but everything you've already accrued stays yours to redeem.</span>
          </div>
        </div>

        <div style={{ padding: 22, borderRadius: 20, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)" }}>
          <h3 className="display" style={{ fontSize: 17 }}>How it works</h3>
          <div style={{ display: "grid", gap: 14, marginTop: 16 }}>
            {[["shield", "Insure your assets", "Cover anything in your VaultLog, individually or bundled."],
              ["check", "Accrue every month", `Each claim-free month adds 1/12 of your tier's annual rate (${rw.tier.ratePct}% on ${rw.tier.name}) on the premiums you pay.`],
              ["trend", "Climb the tiers", `Stay claim-free ${rw.config.tiers[1].afterYears} years for ${rw.config.tiers[1].name} (${rw.config.tiers[1].ratePct}%), ${rw.config.tiers[2].afterYears} for ${rw.config.tiers[2].name} (${rw.config.tiers[2].ratePct}%).`],
              ["download", "Get paid back", "Redeem to your wallet, bank, or roll into next year's premium."]].map(([ic, t2, d2]) => (
              <div key={t2} style={{ display: "flex", gap: 12 }}>
                <span style={{ display: "grid", placeItems: "center", width: 34, height: 34, borderRadius: 10, flexShrink: 0, background: "var(--accent-soft)", color: "var(--accent)" }}><window.Icon name={ic} size={17} /></span>
                <div><div style={{ fontWeight: 700, fontSize: 14 }}>{t2}</div><div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2, lineHeight: 1.45 }}>{d2}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* per-policy accrual */}
      <div style={{ padding: 22, borderRadius: 20, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)", marginTop: 16 }}>
        <h3 className="display" style={{ fontSize: 17, marginBottom: 4 }}>Cashback by policy</h3>
        <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginBottom: 14 }}>{rw.tier.ratePct}% of each premium a year on {rw.tier.name}, credited monthly while you stay claim-free.</p>
        <div style={{ display: "grid", gap: 2 }}>
          {rw.perPolicy.map((p2) => (
            <div key={p2.asset} style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr", gap: 12, alignItems: "center", padding: "12px 0", borderTop: "1px solid var(--border)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <span style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 10, background: "var(--accent-soft)", color: "var(--accent)", flexShrink: 0 }}><window.Icon name="shield" size={17} /></span>
                <div><div style={{ fontWeight: 700, fontSize: 13.5 }}>{p2.asset}</div><div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{p2.insurer}</div></div>
              </div>
              <div style={{ textAlign: "right" }}><div style={{ fontSize: 11, color: "var(--text-faint)" }}>Premium</div><div className="mono" style={{ fontSize: 13.5, fontWeight: 600 }}>{D.fmtFull(p2.premiumNaira)}</div></div>
              <div style={{ textAlign: "right" }}><div style={{ fontSize: 11, color: "var(--text-faint)" }}>Accrued so far</div><div className="mono" style={{ fontSize: 14, fontWeight: 700, color: "var(--success)" }}>{D.fmtFull(p2.accruedNaira)}</div></div>
            </div>
          ))}
          {rw.perPolicy.length === 0 && <div style={{ padding: 28, textAlign: "center", color: "var(--text-faint)", border: "1px dashed var(--border-strong)", borderRadius: 14 }}>No active policies yet. Insure an asset and the accrual starts with your first month.</div>}
          {rw.perPolicy.length > 0 && (
            <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr", gap: 12, padding: "14px 0 0", borderTop: "2px solid var(--text)", marginTop: 4 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>Total accrued</div>
              <div></div>
              <div className="mono" style={{ textAlign: "right", fontSize: 17, fontWeight: 700, color: "var(--success)" }}>{D.fmtFull(rw.accruedNaira)}</div>
            </div>
          )}
        </div>
      </div>

      {/* redeem overlay */}
      <window.Overlay open={redeemOpen} onClose={() => setRedeemOpen(false)} width={440}>
        <RedeemFlow amount={balance} onClose={() => setRedeemOpen(false)} onDone={() => { setRedeemed(true); setRedeemOpen(false); addToast(`${D.fmtFull(balance)} cashback redeemed`, "trend"); }} />
      </window.Overlay>
    </div>
  );
}

function RedeemFlow({ amount, onClose, onDone }) {
  const D = window.VC_DATA;
  const [dest, setDest] = useStateR("wallet");
  const [stage, setStage] = useStateR("pick");
  const opts = [
    { id: "wallet", icon: "vault", label: "VaultCova wallet", sub: "Instant" },
    { id: "bank", icon: "building", label: "Bank account", sub: "Wema · ****0142" },
    { id: "premium", icon: "shield", label: "Apply to next premium", sub: "Reduce what you owe" },
  ];
  const go = () => { setStage("done"); setTimeout(onDone, 1300); };
  return stage === "pick" ? (
    <div style={{ padding: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div><h2 className="display" style={{ fontSize: 21 }}>Redeem cashback</h2><p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 4 }}>Where should we send {D.fmtFull(amount)}?</p></div>
        <button onClick={onClose} style={{ display: "grid", placeItems: "center", width: 34, height: 34, borderRadius: 999, background: "var(--surface-3)" }}><window.Icon name="close" size={17} /></button>
      </div>
      <div style={{ display: "grid", gap: 9, marginTop: 18 }}>
        {opts.map((o) => {
          const on = dest === o.id;
          return (
            <button key={o.id} onClick={() => setDest(o.id)} style={{ display: "flex", alignItems: "center", gap: 12, padding: 13, borderRadius: 13, textAlign: "left", background: on ? "var(--accent-soft)" : "var(--surface)", border: "1.5px solid " + (on ? "var(--accent)" : "var(--border)") }}>
              <span style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: 11, background: on ? "var(--accent)" : "var(--surface-3)", color: on ? "#fff" : "var(--text-muted)" }}><window.Icon name={o.icon} size={18} /></span>
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }}>{o.label}</div><div style={{ fontSize: 12, color: "var(--text-faint)" }}>{o.sub}</div></div>
              {on && <window.Icon name="check" size={18} stroke={3} style={{ color: "var(--accent)" }} />}
            </button>
          );
        })}
      </div>
      <window.Btn size="lg" iconR="arrowR" style={{ width: "100%", justifyContent: "center", marginTop: 18 }} onClick={go}>Redeem {D.fmtFull(amount)}</window.Btn>
    </div>
  ) : (
    <div style={{ padding: 44, textAlign: "center" }}>
      <span style={{ display: "grid", placeItems: "center", width: 72, height: 72, borderRadius: 999, background: "var(--success)", color: "#fff", margin: "0 auto", animation: "vc-scale-in .4s var(--ease) both" }}><window.Icon name="check" size={40} stroke={3} /></span>
      <h2 className="display" style={{ fontSize: 23, marginTop: 18 }}>Cashback on its way!</h2>
      <p style={{ fontSize: 14, color: "var(--text-muted)", marginTop: 6 }}>{D.fmtFull(amount)} redeemed. Thanks for staying covered with VaultCova.</p>
    </div>
  );
}

Object.assign(window, { Rewards });
