/* Dulius App UI Kit — Live Offers */

function MatchRing({ value, size = 44 }) {
  const r = size / 2 - 4;
  const c = 2 * Math.PI * r;
  const color = value >= 90 ? "#1B5C2E" : value >= 80 ? "#2DBD6E" : "#F5A623";
  return (
    <div className="dmatch" style={{ width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#E8F0E8" strokeWidth="4" />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth="4"
          strokeDasharray={`${(value/100)*c} ${c}`} strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`} />
      </svg>
      <span className="dmatch-val dnum" style={{ color }}>{value}</span>
    </div>
  );
}

function OfferRow({ o, compact = false, onApply, selectable, selected, onToggle }) {
  return (
    <div className={`doffer ${compact ? "compact" : ""} ${selected ? "selected" : ""}`}>
      {selectable && (
        <button className={`doffer-check ${selected ? "on" : ""}`} onClick={() => onToggle(o)} aria-pressed={selected}>
          {selected && <Icon name="check" size={14} />}
        </button>
      )}
      <div className="doffer-logo">{o.initials}</div>
      <div className="doffer-main">
        <div className="doffer-l1">
          <span className="doffer-lender">{o.lender}</span>
          <Badge tone={o.status === "Best match" ? "success" : o.status === "Likely" ? "info" : "neutral"} dot>{o.status}</Badge>
        </div>
        <div className="doffer-l2">{o.type} · {o.amount}</div>
        {!compact && (
          <div className="doffer-tags">
            {o.tags.map((t, i) => <span key={i} className="doffer-tag">{t}</span>)}
          </div>
        )}
      </div>
      <div className="doffer-terms">
        <div className="doffer-apr dnum">{o.apr}</div>
        <div className="doffer-aprl">{String(o.apr).includes("factor") ? "factor rate" : "est. APR"}</div>
        <div className="doffer-term">{o.term}</div>
      </div>
      {!compact && <div className="doffer-match"><MatchRing value={o.match} /><span className="doffer-matchl">match</span></div>}
      <div className="doffer-cta">{o.live ? <button type="button" onClick={() => window.duliusRespondToOffer && window.duliusRespondToOffer(o.applicationId, "declined")} style={{ background: "none", border: "none", color: "#8a8f99", fontWeight: 600, cursor: "pointer", marginRight: "10px", fontSize: "13px" }}>Decline</button> : null}
        <Button variant={compact ? "secondary" : "primary"} size={compact ? "sm" : "md"} iconRight="arrow-right" onClick={() => o.live ? (window.duliusRespondToOffer && window.duliusRespondToOffer(o.applicationId, "accepted")) : (onApply && onApply(o))}>
          {o.live ? "Accept offer" : (compact ? "View" : "Apply")}
        </Button>
      </div>
    </div>
  );
}

function RenewalOfferCard({ o, onReview }) {
  return (
    <div className={`drenewal ${o.dulius ? "dulius" : "partner"}`}>
      <div className="drenewal-top">
        <div className="drenewal-id">
          <div className="drenewal-logo">{o.initials}</div>
          <div>
            <div className="drenewal-lender">{o.lender}</div>
            <div className="drenewal-renews"><Icon name="refresh-cw" size={12} /> Renews your {o.renews}</div>
          </div>
        </div>
        <div className="drenewal-top-right">
          <span className="drenewal-tag">{o.dulius ? "Dulius renewal" : "Lender renewal"}</span>
          <span className="drenewal-expiry"><Icon name="clock" size={13} /> {o.expires} left</span>
        </div>
      </div>
      <div className="drenewal-terms">
        <div className="drenewal-term"><span className="drenewal-term-v dnum">{o.amount}</span><span className="drenewal-term-l">new capital</span></div>
        <div className="drenewal-term"><span className="drenewal-term-v dnum">{o.apr}</span><span className="drenewal-term-l">rate</span></div>
        <div className="drenewal-term"><span className="drenewal-term-v dnum">{o.term}</span><span className="drenewal-term-l">term</span></div>
      </div>
      <div className="drenewal-highlight"><Icon name="trending-up" size={14} /> {o.highlight}</div>
      <div className="drenewal-actions">
        <Button variant="accent" size="md" iconRight="arrow-right" onClick={() => onReview(o)} style={{ flex: 1 }}>Review &amp; accept renewal</Button>
        <button className="drenewal-decline" onClick={() => onReview(o)}>Details</button>
      </div>
    </div>
  );
}

function RenewalReviewModal({ o, onClose, onApply }) {
  const [accepted, setAccepted] = React.useState(false);
  return (
    <div className="dmodal-scrim" onClick={onClose}>
      <div className="dmodal wide" onClick={(e) => e.stopPropagation()}>
        {accepted ? (
          <React.Fragment>
            <div className="dmodal-icon" style={{ background: "var(--green-500)", color: "#08311A" }}><Icon name="check" size={24} /></div>
            <h3 className="dmodal-t">Renewal accepted</h3>
            <p className="dmodal-s">{o.dulius
              ? <span>We're preparing your <strong>{o.lender}</strong> renewal for <strong>{o.amount}</strong>. It replaces your current {o.renews} on funding — you'll review and e-sign the agreement next.</span>
              : <span>We've told <strong>{o.lender}</strong> you want to move forward with the <strong>{o.amount}</strong> renewal. We'll coordinate the paperwork and keep you posted.</span>}</p>
            <Button variant="primary" style={{ width: "100%" }} onClick={() => { onApply && onApply(o); onClose(); }}>Continue to agreement</Button>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="dmodal-icon"><Icon name="refresh-cw" size={24} /></div>
            <h3 className="dmodal-t">{o.lender} renewal</h3>
            <p className="dmodal-s">{o.dulius ? "A renewal offer from Dulius" : "A renewal offer from your lender"} on your {o.renews}.</p>
            <div className="drenewal-rev-grid">
              <div className="drenewal-rev-row"><span>New capital</span><span className="dnum">{o.amount}</span></div>
              <div className="drenewal-rev-row"><span>Rate</span><span className="dnum">{o.apr}</span></div>
              <div className="drenewal-rev-row"><span>Term</span><span className="dnum">{o.term}</span></div>
              <div className="drenewal-rev-row"><span>Replaces</span><span className="dnum">{o.renews}</span></div>
              <div className="drenewal-rev-row highlight"><span>Why it's better</span><span>{o.benefit}</span></div>
            </div>
            <div className="dmodal-info"><Icon name={o.dulius ? "zap" : "shield-check"} size={15} /> {o.dulius ? "Renews instantly through Dulius, and your score keeps building." : "Dulius coordinates the renewal paperwork with your lender on your behalf."}</div>
            <Button variant="accent" style={{ width: "100%" }} iconRight="arrow-right" onClick={() => setAccepted(true)}>Accept renewal</Button>
            <button className="dmodal-cancel" onClick={onClose}>Not now</button>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function Offers({ onApply, onApplyFunding, onNav }) {
  const d = DULIUS;
  const [filter, setFilter] = React.useState("All");
  const [sel, setSel] = React.useState([]);
  const [modal, setModal] = React.useState(null); // "negotiate" | "protect"
  const [renewal, setRenewal] = React.useState(null);
  const [accepted, setAccepted] = React.useState(false);
  const closeModal = () => { setModal(null); setAccepted(false); };
  const filters = ["All", "Dulius program", "MCA", "Line of credit", "Term loan"];
  const list = filter === "All" ? d.offers : d.offers.filter((o) => o.type === filter);
  const offerPlan = (DULIUS.plans && DULIUS.plans.current) || "Free";
  const offerCapped = offerPlan === "Free";
  const shownList = offerCapped ? list.slice(0, 2) : list;
  const hiddenOffers = offerCapped ? Math.max(0, list.length - 2) : 0;
  const toggle = (o) => setSel((s) => s.includes(o.lender) ? s.filter((x) => x !== o.lender) : [...s, o.lender]);
  const selectedOffers = d.offers.filter((o) => sel.includes(o.lender));
  const renewals = d.renewalOffers || [];

  return (
    <div className="dscreen">
      {renewals.length > 0 && (
        <div className="drenewal-sec">
          <div className="drenewal-sec-head">
            <div className="drenewal-sec-title"><Icon name="refresh-cw" size={18} /> Renewal offers</div>
            <span className="drenewal-sec-sub">Fresh capital on your active deals — from Dulius and your other lenders</span>
          </div>
          <div className="drenewal-grid">
            {renewals.map((o) => <RenewalOfferCard key={o.id} o={o} onReview={setRenewal} />)}
          </div>
        </div>
      )}

      <Card className="dofferbanner" pad={false}>
        <div className="dofferbanner-in">
          <div className="dofferbanner-icon"><Icon name="sparkles" size={22} /></div>
          <div className="dofferbanner-txt">
            <div className="dofferbanner-t">{offerCapped ? "Up to 2 matched offers this month" : "Funders matched to your profile"}</div>
            <div className="dofferbanner-s">Matched to your <strong>{DULIUS.score.band}</strong> score · ranked by fit · checking won't affect it · matches aren't a guarantee of approval</div>
          </div>
          <Button variant="accent" icon="file-plus" onClick={() => onApplyFunding && onApplyFunding()}>Apply for funding</Button>
        </div>
      </Card>

      <div className="dfilters">
        {filters.map((f) => (
          <button key={f} className={`dchip ${filter === f ? "active" : ""}`} onClick={() => setFilter(f)}>{f}</button>
        ))}
        <div className="dfilters-spacer" />
        <span className="doffer-selhint">Select offers to apply or have us negotiate</span>
      </div>

      <Card className="dpanel" pad={false}>
        <div className="dofferlist">
          {shownList.map((o, i) => <OfferRow key={i} o={o} onApply={onApply} selectable selected={sel.includes(o.lender)} onToggle={toggle} />)}
          {hiddenOffers > 0 && (
            <div className="doffer-lockrow" style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: 8, padding: "14px 16px", background: "#f6faf7", borderTop: "1px solid #eef3ef", fontSize: 13.5 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, color: "#143222", fontWeight: 600 }}><Icon name="lock" size={16} /> {hiddenOffers} more match{hiddenOffers > 1 ? "es" : ""} hidden on Free</div>
              <a className="dlink" href="#" style={{ fontWeight: 700 }} onClick={(e) => { e.preventDefault(); if (onNav) onNav("plans"); }}>Free shows up to 2/mo — Upgrade to Premium for unlimited →</a>
            </div>
          )}
          {list.length === 0 && <div className="dempty">No offers in this category yet.</div>}
        </div>
      </Card>

      {/* Selection action bar */}
      {sel.length > 0 && (
        <div className="dselbar">
          <div className="dselbar-count"><span className="dselbar-n dnum">{sel.length}</span> offer{sel.length > 1 ? "s" : ""} selected</div>
          <div className="dselbar-actions">
            <button className="dselbtn ghost" onClick={() => setModal("protect")}><Icon name="shield" size={17} /> Add dispute protection</button>
            <button className="dselbtn ghost" onClick={() => setModal("negotiate")}><Icon name="handshake" size={17} /> Have us negotiate</button>
            <button className="dselbtn primary" onClick={() => onApply(selectedOffers[0])}><Icon name="arrow-right" size={17} /> Apply to selected</button>
          </div>
        </div>
      )}

      {modal === "negotiate" && (
        <div className="dmodal-scrim" onClick={closeModal}>
          <div className="dmodal" onClick={(e) => e.stopPropagation()}>
            {accepted ? (
              <React.Fragment>
                <div className="dmodal-icon" style={{ background: "var(--green-500)", color: "#08311A" }}><Icon name="check" size={24} /></div>
                <h3 className="dmodal-t">Negotiation requested</h3>
                <p className="dmodal-s">Our team will reach out to {sel.length > 1 ? "these lenders" : "this lender"} and negotiate on your behalf. You're only charged if terms improve.</p>
                <Button variant="primary" style={{ width: "100%" }} onClick={closeModal}>Got it</Button>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div className="dmodal-icon"><Icon name="handshake" size={24} /></div>
                <h3 className="dmodal-t">Have Dulius negotiate</h3>
                <p className="dmodal-s">We'll contact you and {sel.length > 1 ? "these lenders" : "this lender"} directly to negotiate better terms on the {sel.length} offer{sel.length > 1 ? "s" : ""} you selected.</p>
                <div className="dmodal-pricerow"><span>Only charged if funded</span><span className="dnum">$299</span></div>
                <div className="dmodal-info"><Icon name="info" size={15} /> You're not charged anything unless the deal funds or your terms improve.</div>
                <Button variant="accent" style={{ width: "100%" }} iconRight="arrow-right" onClick={() => setAccepted(true)}>Request negotiation — $299</Button>
                <button className="dmodal-cancel" onClick={closeModal}>Not now</button>
              </React.Fragment>
            )}
          </div>
        </div>
      )}

      {modal === "protect" && (
        <div className="dmodal-scrim" onClick={closeModal}>
          <div className="dmodal wide" onClick={(e) => e.stopPropagation()}>
            {accepted ? (
              <React.Fragment>
                <div className="dmodal-icon" style={{ background: "var(--green-500)", color: "#08311A" }}><Icon name="shield-check" size={24} /></div>
                <h3 className="dmodal-t">Dispute Protection added</h3>
                <p className="dmodal-s">You're covered on every active Dulius deal at {DULIUS.protection.price}. Manage it anytime from Disputes or Billing.</p>
                <Button variant="primary" style={{ width: "100%" }} onClick={closeModal}>Done</Button>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div className="dmodal-icon"><Icon name="shield-check" size={24} /></div>
                <h3 className="dmodal-t">{DULIUS.protection.name}</h3>
                <p className="dmodal-s"><strong>{DULIUS.protection.tagline}</strong> {DULIUS.protection.desc}</p>
                <div className="dsvc-includes" style={{ marginBottom: 14 }}>
                  {DULIUS.protection.includes.map((it, i) => <div key={i} className="dsvc-inc"><Icon name="check" size={15} /><span>{it}</span></div>)}
                </div>
                <div className="dmodal-pricerow"><span>Coverage on every active deal</span><span className="dnum">{DULIUS.protection.price}</span></div>
                {DULIUS.plans.current !== "Pro" && <div className="dmodal-info"><Icon name="gem" size={15} /> Pro members pay {DULIUS.protection.proPrice} — your {DULIUS.plans.current} plan can upgrade for the lower rate.</div>}
                <Button variant="accent" style={{ width: "100%" }} iconRight="arrow-right" onClick={() => setAccepted(true)}>Add Dispute Protection</Button>
                <button className="dmodal-cancel" onClick={closeModal}>Not now</button>
              </React.Fragment>
            )}
          </div>
        </div>
      )}
      {renewal && <RenewalReviewModal o={renewal} onClose={() => setRenewal(null)} onApply={onApply} />}
    </div>
  );
}

Object.assign(window, { Offers, OfferRow, MatchRing, RenewalOfferCard, RenewalReviewModal });
