/* Dulius App UI Kit — Plans & Billing (subscription model) */

const DULIUS_PLAN_KEY = "dulius:plan:v1";

function getStoredDuliusPlan(fallback) {
  try {
    var raw = localStorage.getItem(DULIUS_PLAN_KEY);
    if (raw == null || raw === "") return fallback;
    try { var parsed = JSON.parse(raw); if (typeof parsed === "string") return parsed; } catch (e) {}
    return raw;
  } catch (e) { return fallback; }
}

function setStoredDuliusPlan(plan) {
  if (window.duliusSavePlan) { try { window.duliusSavePlan(plan); } catch (e) {} }
  try { localStorage.setItem(DULIUS_PLAN_KEY, plan); } catch (e) {}
  DULIUS.user.plan = plan;
  window.dispatchEvent(new CustomEvent("dulius:plan-updated", { detail: { plan } }));
}

function ensureDuliusPlansStyles() {
  if (document.getElementById("dulius-plans-styles")) return;
  var s = document.createElement("style");
  s.id = "dulius-plans-styles";
  s.textContent = ".dcycle{display:inline-flex;gap:4px;background:var(--ds-surface-2,#f1f1ef);border:1px solid var(--ds-border,#e4e4e1);border-radius:999px;padding:4px}.dcycle-opt{display:inline-flex;align-items:center;gap:8px;border:0;background:transparent;color:var(--ds-text-2,#6b6b66);font:inherit;font-size:13px;font-weight:600;padding:7px 14px;border-radius:999px;cursor:pointer}.dcycle-opt.on{background:var(--ds-bg,#fff);color:var(--ds-text,#1a1a18);box-shadow:0 1px 3px rgba(0,0,0,.08)}.dcycle-save{font-size:11px;font-weight:700;color:#0a7d3c;background:#e6f6ec;border-radius:999px;padding:2px 7px}.dplan-renew{margin-top:6px;font-size:11.5px;line-height:1.35;color:var(--ds-text-2,#6b6b66)}.dsavings{display:flex;gap:14px;align-items:flex-start;border:1px solid #d9ead9;background:linear-gradient(180deg,#f4fbf5,#fff)}.dsavings-icon{flex:0 0 auto;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;background:#e6f6ec;color:#0a7d3c}.dsavings-body{flex:1;min-width:0}.dsavings-t{font-weight:700;font-size:15px;color:var(--ds-text,#1a1a18);margin-bottom:10px}.dsavings-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:560px){.dsavings-grid{grid-template-columns:1fr}}.dsavings-item{display:flex;flex-direction:column;gap:3px;background:var(--ds-bg,#fff);border:1px solid var(--ds-border,#e4e4e1);border-radius:10px;padding:11px 13px}.dsavings-h{font-size:12px;font-weight:600;color:var(--ds-text-2,#6b6b66);text-transform:uppercase;letter-spacing:.03em}.dsavings-row{display:flex;align-items:baseline;gap:8px}.dsavings-was{color:#9a9a95;text-decoration:line-through;font-size:14px}.dsavings-arrow{color:#0a7d3c;font-weight:700}.dsavings-now{font-size:18px;font-weight:800;color:var(--ds-text,#1a1a18)}.dsavings-em{font-size:12px;font-weight:600;color:#0a7d3c}.dsavings-foot{margin-top:10px;font-size:12px;line-height:1.45;color:var(--ds-text-2,#6b6b66)}.dplan-addons-sub{margin:-2px 0 10px;font-size:12px}.daddon-was{color:#9a9a95;text-decoration:line-through;margin-right:7px;font-size:13px}.daddon{align-items:flex-start}.daddon-info{display:flex;flex-direction:column;gap:3px;flex:1;min-width:0;padding-right:14px}.daddon-desc{font-size:12px;font-weight:400;line-height:1.45;color:var(--ds-text-2,#6b6b66)}.daddon-right{flex:0 0 auto;display:flex;align-items:center;flex-wrap:wrap;justify-content:flex-end;row-gap:6px}.daddon-prem{opacity:.78}";
  document.head.appendChild(s);
}

function PlanCard({ t, current, cycle, onChoose }) {
  const isCurrent = t.name === current;
  const annual = cycle === "annual";
  const price = annual ? t.annual : t.monthly;
  const rank = { Free: 0, Premium: 1, Pro: 2 };
  const actionLabel = rank[t.name] < rank[current] ? "Downgrade" : `Upgrade to ${t.name}`;
  return (
    <Card className={`dplan ${t.popular ? "popular" : ""} ${isCurrent ? "current" : ""}`}>
      {t.popular && <div className="dplan-flag">Most popular</div>}
      <div className="dplan-name">{t.name}</div>
      <div className="dplan-blurb">{t.blurb}</div>
      <div className="dplan-price">
        <span className="dplan-amt dnum">${price}</span>
        <span className="dplan-per">{price === 0 ? "free forever" : (annual ? "/year" : "/month")}</span>
      </div>
      {price > 0 && (annual
        ? <div className="dplan-renew">{"2 months free · about $" + Math.round(t.annual/12) + "/mo billed yearly · auto-renews"}</div>
        : <div className="dplan-renew">Billed monthly · auto-renews · cancel anytime</div>)}
      {isCurrent ? (
        <Button variant="secondary" style={{ width: "100%" }} icon="check">Current plan</Button>
      ) : (
        <Button variant={t.popular ? "accent" : "primary"} style={{ width: "100%" }} iconRight={t.name === "Free" ? null : "arrow-right"} onClick={() => onChoose(t.name)}>{actionLabel}</Button>
      )}
      <div className="dplan-features">
        {t.features.map((f, i) => (
          <div key={i} className="dplan-feature"><Icon name="check" size={16} /><span>{f}</span></div>
        ))}
      </div>
    </Card>
  );
}

function Plans() {
  const p = DULIUS.plans;
  const [current, setCurrent] = React.useState(() => getStoredDuliusPlan(p.current));
  const [addCard, setAddCard] = React.useState(false);
  const [pending, setPending] = React.useState(null);
  const [payStep, setPayStep] = React.useState(false);
  const [cycle, setCycle] = React.useState("monthly");
  ensureDuliusPlansStyles();
  const cur = p.tiers.find((t) => t.name === current);
  const rank = { Free: 0, Premium: 1, Pro: 2 };
  const activatePlan = (name) => { setStoredDuliusPlan(name); setCurrent(name); setPending(null); setPayStep(false); };
  const choose = (name) => { if (name !== current) setPending(name); };
  return (
    <div className="dscreen">
      <Card className="dbillingbar">
        <div className="dbillingbar-l">
          <div className="dbillingbar-icon"><Icon name="gem" size={20} /></div>
          <div>
            <div className="dbillingbar-t">You're on <strong>Dulius {current}</strong></div>
            <div className="dbillingbar-s">{cur && cur.monthly > 0 ? `Next invoice $${cur.monthly} on Jun 28, 2026 · Visa ••4242` : "Free plan · no billing"}</div>
          </div>
        </div>
        <Button variant="ghost" size="sm" icon="credit-card" onClick={() => setAddCard(true)}>Manage billing</Button>
      </Card>

      <div className="dplans-toggle-row">
        <h3 className="ds-h3">Choose your plan</h3>
        <div className="dcycle">
          <button type="button" className={"dcycle-opt " + (cycle === "monthly" ? "on" : "")} onClick={() => setCycle("monthly")}>Monthly</button>
          <button type="button" className={"dcycle-opt " + (cycle === "annual" ? "on" : "")} onClick={() => setCycle("annual")}>Annual<span className="dcycle-save">2 months free</span></button>
        </div>
      </div>

      <div className="dplansgrid">
        {p.tiers.map((t, i) => <PlanCard key={i} t={t} current={current} cycle={cycle} onChoose={choose} />)}
      </div>

      <Card className="dpanel dsavings">
        <div className="dsavings-icon"><Icon name="gem" size={20} /></div>
        <div className="dsavings-body">
          <div className="dsavings-t">Your membership pays for itself on a single deal</div>
          <div className="dsavings-grid">
            <div className="dsavings-item">
              <span className="dsavings-h">Funded-deal negotiation</span>
              <span className="dsavings-row"><span className="dsavings-was dnum">$299</span><span className="dsavings-arrow">→</span><span className="dsavings-now dnum">$99 on Pro</span></span>
              <span className="dsavings-em">Save $200 on a single funded deal</span>
            </div>
            <div className="dsavings-item">
              <span className="dsavings-h">Dispute assistance</span>
              <span className="dsavings-row"><span className="dsavings-was dnum">$119</span><span className="dsavings-arrow">→</span><span className="dsavings-now dnum">$49 on Pro</span></span>
              <span className="dsavings-em">Save $70 every dispute</span>
            </div>
          </div>
          <div className="dsavings-foot">Negotiation is a success fee — only charged if you actually get funded, never upfront. One funded deal on Pro saves more than four months of membership.</div>
        </div>
      </Card>

      <Card className="dpanel dplan-addons">
        <h3 className="ds-h3">Add-on services</h3>
        <div className="dmuted dplan-addons-sub">Prices shown for your current plan ({current}) — upgrade to drop them.</div>
        <div className="daddons">
          {p.addons.map((a, i) => {
            const ord = { Free: 0, Premium: 1, Pro: 2 };
            const cu = ord[current] != null ? ord[current] : 0;
            const bp = a.byPlan || {};
            const myPrice = bp[current] || a.price || "";
            const basePrice = bp.Free || a.price || "";
            const discounted = myPrice !== basePrice;
            const showPremium = cu < 1 && a.premiumPrice && a.premiumPrice !== basePrice;
            const showPro = cu < 2 && a.proPrice && a.proPrice !== myPrice;
            return (
              <div key={i} className="daddon">
                <span className="daddon-info">
                  <span className="daddon-name">{a.name}{a.note && <span className="daddon-note"> · {a.note}</span>}</span>
                  {a.desc && <span className="daddon-desc">{a.desc}</span>}
                </span>
                <span className="daddon-right">
                  {showPremium && <span className="daddon-pro daddon-prem"><Icon name="gem" size={12} /> {a.premiumPrice} with Premium</span>}
                  {showPro && <span className="daddon-pro"><Icon name="gem" size={12} /> {a.proPrice} with Pro</span>}
                  {discounted && <span className="daddon-was dnum">{basePrice}</span>}
                  <span className="daddon-price dnum">{myPrice}</span>
                </span>
              </div>
            );
          })}
        </div>
      </Card>

      <Card className="dpanel dplan-note">
        <Icon name="shield-check" size={20} />
        <div>All plans include soft-pull score checks that never affect your score, bank-grade encryption, and the ability to cancel anytime.</div>
      </Card>

      {/* Upgrade / downgrade flow — paid upgrades collect card before activating */}
      {pending && (() => {
        const isUpgrade = rank[pending] > rank[current];
        const price = p.tiers.find(t => t.name === pending).monthly;
        const needsCard = isUpgrade && price > 0;
        return (
          <div className="dmodal-scrim" onClick={() => { setPending(null); setPayStep(false); }}>
            <div className="dmodal" onClick={(e) => e.stopPropagation()}>
              {!needsCard ? (
                <React.Fragment>
                  <div className="dmodal-icon"><Icon name={isUpgrade ? "arrow-up-circle" : "arrow-down-circle"} size={24} /></div>
                  <h3 className="dmodal-t">{isUpgrade ? "Upgrade" : "Downgrade"} to Dulius {pending}?</h3>
                  <p className="dmodal-s">{isUpgrade ? "You'll unlock more features immediately." : "You'll keep your current features until the end of this billing cycle, then move to " + pending + "."}</p>
                  <div className="dmodal-pricerow"><span>New plan</span><span className="dnum">${price}/mo</span></div>
                  <Button variant="accent" style={{ width: "100%" }} onClick={() => activatePlan(pending)}>Confirm {isUpgrade ? "upgrade" : "downgrade"}</Button>
                  <button className="dmodal-cancel" onClick={() => setPending(null)}>Not now</button>
                </React.Fragment>
              ) : !payStep ? (
                <React.Fragment>
                  <div className="dmodal-icon"><Icon name="gem" size={24} /></div>
                  <h3 className="dmodal-t">Upgrade to Dulius {pending}</h3>
                  <p className="dmodal-s">Unlock {pending === "Pro" ? "every tool — score simulator, priority matching, and discounted services" : "your full score breakdown, score path, and unlimited offers"}.</p>
                  <div className="dpaysum">
                    <div className="dpaysum-row"><span>Dulius {pending}</span><span className="dnum">${price}/mo</span></div>
                    <div className="dpaysum-row"><span>Due today</span><span className="dnum">${price}.00</span></div>
                    <div className="dpaysum-row total"><span>Then ${price}/mo</span><span className="dmuted">cancel anytime</span></div>
                  </div>
                  <Button variant="accent" style={{ width: "100%" }} iconRight="arrow-right" onClick={() => setPayStep(true)}>Continue to payment</Button>
                  <button className="dmodal-cancel" onClick={() => setPending(null)}>Not now</button>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <button className="dpayback" onClick={() => setPayStep(false)}><Icon name="arrow-left" size={15} /> Back</button>
                  <h3 className="dmodal-t left">Payment details</h3>
                  <p className="dmodal-s left" style={{ marginTop: 2 }}>Dulius {pending} · <strong className="dnum">${price}/mo</strong>, starting today.</p>
                  <div className="dcardform" style={{ marginTop: 8 }}>
                    <label className="dcardf full"><span>Name on card</span><div className="ofield-in"><Icon name="user-round" size={18} /><input placeholder="Marcus Thompson" /></div></label>
                    <label className="dcardf full"><span>Card number</span><div className="ofield-in"><Icon name="credit-card" size={18} /><input placeholder="1234 5678 9012 3456" /></div></label>
                    <label className="dcardf"><span>Expiry</span><div className="ofield-in"><input placeholder="MM / YY" /></div></label>
                    <label className="dcardf"><span>CVC</span><div className="ofield-in"><input placeholder="123" /></div></label>
                    <label className="dcardf full"><span>Billing ZIP</span><div className="ofield-in"><Icon name="map-pin" size={18} /><input placeholder="00000" /></div></label>
                  </div>
                  <div className="dmodal-info"><Icon name="lock" size={15} /> Billing setup is saved locally until Stripe checkout is connected. Cancel anytime.</div>
                  <Button variant="accent" style={{ width: "100%" }} icon="lock" onClick={() => activatePlan(pending)}>Activate Dulius {pending}</Button>
                  <button className="dmodal-cancel" onClick={() => setPending(null)}>Cancel</button>
                </React.Fragment>
              )}
            </div>
          </div>
        );
      })()}

      {/* Add / update card */}
      {addCard && (
        <div className="dmodal-scrim" onClick={() => setAddCard(false)}>
          <div className="dmodal wide" onClick={(e) => e.stopPropagation()}>
            <h3 className="dmodal-t left">Payment method</h3>
            <div className="dcardvis"><span className="dcardvis-chip" /><span className="dcardvis-num dnum">•••• •••• •••• 4242</span><span className="dcardvis-name">MARCUS THOMPSON</span></div>
            <div className="dcardform">
              <label className="dcardf full"><span>Card number</span><div className="ofield-in"><Icon name="credit-card" size={18} /><input placeholder="1234 5678 9012 3456" /></div></label>
              <label className="dcardf"><span>Expiry</span><div className="ofield-in"><input placeholder="MM / YY" /></div></label>
              <label className="dcardf"><span>CVC</span><div className="ofield-in"><input placeholder="123" /></div></label>
            </div>
            <div className="dmodal-info"><Icon name="lock" size={15} /> Billing details are saved locally until checkout is connected.</div>
            <Button variant="accent" style={{ width: "100%" }} onClick={() => setAddCard(false)}>Save billing details</Button>
            <button className="dmodal-cancel" onClick={() => setAddCard(false)}>Cancel</button>
          </div>
        </div>
      )}
    </div>
  );
}
Object.assign(window, { Plans, PlanCard });

// build 1780608606372
