/* ============================================================
   Credit Cards landing — interactive bits (compare tabs + tweaks)
   ============================================================ */
const { useState, useEffect } = React;

/* -------- Compare your rewards : tabbed module -------- */
const COMPARE_DATA = {
  travel: {
    label: "Travel Visa\u00AE",
    rewards: [
      { ic: "tent", html: "<strong>Up to 20% savings</strong> when you combine your Travel Credit Card<sup>3</sup> and Membership benefits" },
      { ic: "shield-check", html: "<strong>5% back</strong> in points at Camping World and Good Sam family of brands<sup>5</sup>" },
      { ic: "fuel", html: "<strong>3% back</strong> in points at campgrounds, gas &amp; EV charging stations, and grocery stores<sup>4</sup>" },
      { ic: "credit-card", html: "<strong>1% back</strong> in points everywhere else Visa\u00AE is accepted<sup>4</sup>" },
      { ic: "star", html: "<strong>15,000 bonus points</strong> when you spend $2,000 with your card outside the family of brands within 90 days of account opening<sup>1</sup>" },
    ],
    cardImg: "assets/cc-thumb-travel.png",
    cardAlt: "Good Sam Travel Credit Card",
    meta: [
      { ic: "dollar-sign", html: "<strong>$1,500 average annual benefit</strong><sup>**</sup><br/><small style='font-weight:400'>when you combine your Travel Card and Elite Membership<span class='hero-tooltip-wrap' style='top:0;margin-left:4px'><button class='hero-info-btn' aria-label='More info about savings'><svg width='16' height='16' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'><path d='M9.99984 13.3327V9.99935M9.99984 6.66602H10.0082M18.3332 9.99935C18.3332 14.6017 14.6022 18.3327 9.99984 18.3327C5.39746 18.3327 1.6665 14.6017 1.6665 9.99935C1.6665 5.39698 5.39746 1.66602 9.99984 1.66602C14.6022 1.66602 18.3332 5.39698 18.3332 9.99935Z' stroke='var(--gs-ink-700)' stroke-width='1.75' stroke-linecap='round' stroke-linejoin='round'/></svg></button><span class='hero-tooltip'>Save on average $500 when you use your Good Sam Travel Visa Signature® Credit Card. Save on average $1,000 with your Good Sam Elite Membership.</span></span></small>" },
      { ic: "calendar-check", html: "<strong>$249 annual fee</strong><sup>*</sup>" },
      { ic: "user-round", html: "<strong>Elite</strong> Good Sam Membership, ($149 value)<sup>2</sup>" },
    ],
  },
  visa: {
    label: "Rewards Visa\u00AE",
    rewards: [
      { ic: "shield-check", html: "<strong>5% back</strong> in points at Camping World and Good Sam family of brands<sup>5</sup>" },
      { ic: "fuel", html: "<strong>3% back</strong> in points at campgrounds and gas stations<sup>4</sup>" },
      { ic: "credit-card", html: "<strong>1% back</strong> in points everywhere else Visa\u00AE is accepted<sup>4</sup>" },
      { ic: "star", html: "<strong>2,500 bonus points</strong> when you spend $500 with your card outside the family of brands within 90 days of account opening<sup>6</sup>" },
    ],
    cardImg: "assets/cc-rewards-visa.png",
    cardAlt: "Good Sam Rewards Visa Signature Credit Card",
    meta: [
      { ic: "user-round", html: "<strong>1 year Standard</strong> Good Sam Membership with purchase at time of approval ($39 value)<sup>7</sup>" },
      { ic: "calendar-check", html: "<strong>No annual fee</strong><sup>*</sup>" },
      { ic: "dollar-sign", html: "<strong>Up to 13%</strong> in savings at Good Sam campgrounds" },
    ],
  },
  rewards: {
    label: "Rewards Card",
    rewards: [
      { ic: "star", html: "Rewards starting as low as <strong>1,000 points</strong>" },
      { ic: "shield-check", html: "<strong>5% back</strong> in points at Camping World and Good Sam family of brands<sup>5</sup>" },
      { ic: "wallet", html: "<strong>OR</strong>" },
      { ic: "dollar-sign", html: "<strong>6 months special financing</strong> on in-store purchases $299+ at Camping World family of brands<sup>8</sup>" },
    ],
    cardImg: "assets/cc-rewards.png",
    cardAlt: "Good Sam Rewards Credit Card",
    meta: [
      { ic: "user-round", html: "<strong>1 year Standard</strong> Good Sam Membership with purchase at time of approval ($39 value)<sup>7</sup>" },
      { ic: "calendar-check", html: "<strong>No annual fee</strong><sup>*</sup>" },
    ],
  },
};

function CompareModule() {
  const [tab, setTab] = useState("travel");
  const data = COMPARE_DATA[tab];

  // Re-render lucide icons whenever the tab changes
  useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  }, [tab]);

  return (
    <div className="compare-card">
      <div className="compare-rewards">
        {data.rewards.map((r, i) => (
          <div className="row" key={tab + "-" + i}>
            <i data-lucide={r.ic} className="ic"></i>
            <p dangerouslySetInnerHTML={{ __html: r.html }}></p>
          </div>
        ))}
      </div>
      <div className="compare-side">
        <div className="card-img"><img src={data.cardImg} alt={data.cardAlt} /></div>
        <a href="#" className="btn btn-primary apply-here">Apply now</a>
        {data.meta.map((m, i) => (
          <div className="meta-row" key={tab + "-meta-" + i}>
            <i data-lucide={m.ic} className="ic"></i>
            <span dangerouslySetInnerHTML={{ __html: m.html }}></span>
          </div>
        ))}
      </div>
    </div>
  );
}

function CompareSection() {
  const [tab, setTab] = useState("travel");
  // Lift state into parent so tab buttons + module share it
  return (
    <>
      <div className="compare-tabs">
        <div className="pill-bar" role="tablist">
          {Object.entries(COMPARE_DATA).map(([k, v]) => (
            <button
              key={k}
              role="tab"
              aria-selected={tab === k}
              className={tab === k ? "active" : ""}
              onClick={() => setTab(k)}
            >{v.label}</button>
          ))}
        </div>
      </div>
      <CompareModuleStateful tab={tab} />
    </>
  );
}

function CompareModuleStateful({ tab }) {
  const data = COMPARE_DATA[tab];
  useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  }, [tab]);
  return (
    <div className="compare-card">
      <div className="compare-rewards">
        {data.rewards.map((r, i) => (
          <div className="row" key={tab + "-" + i}>
            <i data-lucide={r.ic} className="ic"></i>
            <p dangerouslySetInnerHTML={{ __html: r.html }}></p>
          </div>
        ))}
      </div>
      <div className="compare-side">
        <div className="card-img"><img src={data.cardImg} alt={data.cardAlt} /></div>
        <a href="#" className="btn btn-primary apply-here">Apply now</a>
        {data.meta.map((m, i) => (
          <div className="meta-row" key={tab + "-meta-" + i}>
            <i data-lucide={m.ic} className="ic"></i>
            <span dangerouslySetInnerHTML={{ __html: m.html }}></span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* -------- Tweaks panel -------- */
const HERO_BG_OPTIONS = {
  "Mountain hike (Getty)": "assets/hero-bg.jpg",
  "RV at sunset": "https://images.unsplash.com/photo-1523987355523-c7b5b0dd90a7?w=1800&auto=format&fit=crop",
  "Forest road": "https://images.unsplash.com/photo-1465056836041-7f43ac27dcb5?w=1800&auto=format&fit=crop",
  "Lake camp": "https://images.unsplash.com/photo-1504280390367-361c6d9f38f4?w=1800&auto=format&fit=crop",
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroBg": "Mountain hike (Getty)",
  "showHeroCard": true,
  "tabStyle": "Pill bar",
  "bannerCta": "Access account"
}/*EDITMODE-END*/;

function CCTweaks() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  // Apply hero bg via CSS var
  useEffect(() => {
    const url = HERO_BG_OPTIONS[tweaks.heroBg] || HERO_BG_OPTIONS["Mountain hike (Getty)"];
    document.documentElement.style.setProperty("--hero-bg", `url('${url}')`);
  }, [tweaks.heroBg]);

  // Show/hide hero card
  useEffect(() => {
    const el = document.querySelector(".hero-card-wrap");
    if (el) el.style.display = tweaks.showHeroCard ? "" : "none";
  }, [tweaks.showHeroCard]);

  // Tab style
  useEffect(() => {
    const bar = document.querySelector(".compare-tabs .pill-bar");
    if (!bar) return;
    if (tweaks.tabStyle === "Underline") {
      bar.style.border = "0";
      bar.style.borderBottom = "1px solid var(--gs-ink-200)";
      bar.style.borderRadius = "0";
      bar.querySelectorAll("button").forEach(b => {
        b.style.borderRadius = "0";
        if (b.classList.contains("active")) {
          b.style.background = "transparent";
          b.style.color = "var(--gs-green-700)";
          b.style.borderBottom = "2px solid var(--gs-green-700)";
        } else {
          b.style.background = "transparent";
          b.style.color = "";
          b.style.borderBottom = "2px solid transparent";
        }
      });
    } else {
      bar.style.border = "1px solid var(--gs-ink-200)";
      bar.style.borderRadius = "999px";
      bar.querySelectorAll("button").forEach(b => {
        b.style.borderRadius = "999px";
        b.style.background = "";
        b.style.color = "";
        b.style.borderBottom = "";
      });
    }
  }, [tweaks.tabStyle]);

  // CTA copy on banner
  useEffect(() => {
    const btn = document.querySelector(".already-card .btn");
    if (btn) btn.textContent = tweaks.bannerCta;
  }, [tweaks.bannerCta]);

  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection title="Hero">
        <window.TweakSelect
          label="Background image"
          value={tweaks.heroBg}
          options={Object.keys(HERO_BG_OPTIONS)}
          onChange={(v) => setTweak("heroBg", v)}
        />
        <window.TweakToggle
          label="Show floating card"
          value={tweaks.showHeroCard}
          onChange={(v) => setTweak("showHeroCard", v)}
        />
      </window.TweakSection>
      <window.TweakSection title="Compare module">
        <window.TweakRadio
          label="Tab style"
          value={tweaks.tabStyle}
          options={["Pill bar", "Underline"]}
          onChange={(v) => setTweak("tabStyle", v)}
        />
      </window.TweakSection>
      <window.TweakSection title="Cardholder banner">
        <window.TweakText
          label="Button label"
          value={tweaks.bannerCta}
          onChange={(v) => setTweak("bannerCta", v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* -------- Mount -------- */
const compareMount = document.getElementById("compare-mount");
if (compareMount) ReactDOM.createRoot(compareMount).render(<CompareSection />);

const tweaksMount = document.getElementById("tweaks-mount");
if (tweaksMount) ReactDOM.createRoot(tweaksMount).render(<CCTweaks />);

/* ============================================================
   Reward modals — Earn table / Redemption tables
   ============================================================ */
function GSModal({ open, onClose, title, children }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  return (
    <div
      className={"gs-modal-backdrop" + (open ? " is-open" : "")}
      role="dialog"
      aria-modal="true"
      aria-hidden={!open}
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="gs-modal">
        <div className="gs-modal-head">
          <h3>{title}</h3>
          <button type="button" className="close" aria-label="Close" onClick={onClose}>
            <i data-lucide="x" style={{width:18, height:18}}></i>
          </button>
        </div>
        <div className="gs-modal-body">{children}</div>
      </div>
    </div>
  );
}

const EARN_ROWS = [
  ["$50", "250"],
  ["$250", "1,250"],
  ["$500", "2,500"],
  ["$750", "3,750"],
  ["…$1,000", "5,000"],
];
const DISCOUNT_ROWS = [
  ["1,000", "$10"],
  ["1,500", "$15"],
  ["2,000", "$20"],
  ["2,500", "$25"],
  ["…5,000", "$50"],
];
const STATEMENT_ROWS = [
  ["1,500", "$10"],
  ["3,000", "$20"],
  ["4,500", "$30"],
  ["6,000", "$40"],
  ["…15,000", "$100"],
];

function RedeemButtons() {
  const [earnOpen, setEarnOpen] = useState(false);
  const [redeemOpen, setRedeemOpen] = useState(false);

  useEffect(() => {
    if ((earnOpen || redeemOpen) && window.lucide && window.lucide.createIcons) {
      requestAnimationFrame(() => window.lucide.createIcons());
    }
  }, [earnOpen, redeemOpen]);

  return (
    <>
      <div className="actions">
        <button type="button" className="btn btn-primary" onClick={() => setEarnOpen(true)}>View earn value</button>
        <button type="button" className="btn btn-secondary" onClick={() => setRedeemOpen(true)}>View redemption value</button>
      </div>

      <GSModal open={earnOpen} onClose={() => setEarnOpen(false)} title="Earn value">
        <h4>5% back in points</h4>
        <table className="earn-table">
          <thead><tr><th>Purchase amount</th><th>Points earned</th></tr></thead>
          <tbody>
            {EARN_ROWS.map(([a, b]) => (<tr key={a}><td>{a}</td><td>{b}</td></tr>))}
          </tbody>
        </table>
      </GSModal>

      <GSModal open={redeemOpen} onClose={() => setRedeemOpen(false)} title="Redemption value">
        <h4>Discount Value (family of brands):</h4>
        <p className="note">1,000 points = $10; earn every 500 points after 1,000</p>
        <table className="earn-table">
          <thead><tr><th>Points</th><th>Value</th></tr></thead>
          <tbody>
            {DISCOUNT_ROWS.map(([a, b]) => (<tr key={a}><td>{a}</td><td>{b}</td></tr>))}
          </tbody>
        </table>

        <h4>Statement Credit Value:</h4>
        <p className="note">1,500 points = $10; earn every 1,500 points</p>
        <table className="earn-table">
          <thead><tr><th>Points</th><th>Credit value</th></tr></thead>
          <tbody>
            {STATEMENT_ROWS.map(([a, b]) => (<tr key={a}><td>{a}</td><td>{b}</td></tr>))}
          </tbody>
        </table>
      </GSModal>
    </>
  );
}

const redeemMount = document.getElementById("redeem-mount");
if (redeemMount) ReactDOM.createRoot(redeemMount).render(<RedeemButtons />);