const { useState, useEffect, useMemo, useRef } = React;

/* Billing — plan, payment method, invoices, cancel */

function BillingPage({ go, user, setUser }) {
  const ciq = window.ContactIQ ? window.ContactIQ.useContactIQ() : { isAuthed: false, subscription: null };
  const [showCancel, setShowCancel] = useState(false);
  const [showPayment, setShowPayment] = useState(false);
  const [portalBusy, setPortalBusy] = useState(false);

  // Merge real subscription into the user object the screen renders against
  const liveUser = ciq.subscription ? {
    ...user,
    plan:         ciq.subscription.plan,
    cardLast4:    ciq.subscription.card_last4,
    paymentMethod: ciq.subscription.card_brand ? "card" : user.paymentMethod,
    trialEnds:    ciq.subscription.trial_ends_at ? ciq.subscription.trial_ends_at.slice(0,10) : user.trialEnds,
  } : user;

  const planStatus = liveUser.plan === "trial" ? "Trial" : liveUser.plan === "active" ? "Active" : liveUser.plan === "past_due" ? "Past due" : "Canceled";

  const invoices = [
    { id: "in_2026_05", date: "2026-05-08", amt: "$5.00", status: "paid", method: "Google Pay · Visa •••• 4242" },
    { id: "in_2026_04", date: "2026-04-08", amt: "$5.00", status: "paid", method: "Google Pay · Visa •••• 4242" },
    { id: "in_2026_03", date: "2026-03-08", amt: "$5.00", status: "paid", method: "Google Pay · Visa •••• 4242" },
    { id: "in_2026_02", date: "2026-02-08", amt: "$5.00", status: "paid", method: "Google Pay · Visa •••• 4242" },
  ];

  // Open Stripe Billing Portal: lets the user update card / cancel / view real
  // invoices. Falls back to the local modal flows when Stripe isn't configured.
  const openPortal = async () => {
    setPortalBusy(true);
    try {
      const url = await window.ContactIQ.openStripePortal();
      window.location.assign(url);
    } catch (err) {
      console.warn("[ContactIQ] portal unavailable, using local modal", err);
      setShowPayment(true);
    } finally {
      setPortalBusy(false);
    }
  };
  // Shadow the prop so the rest of the JSX (which already references `user`)
  // stays unchanged and picks up real subscription fields.
  user = liveUser;

  return (
    <>
      <div className="work-head">
        <div className="col" style={{ gap: 2 }}>
          <div className="title">Billing</div>
          <div className="sub">Manage your subscription, payment method, and invoices.</div>
        </div>
      </div>

      <div className="work-body">
        <div className="bill-grid">
          {/* Current plan */}
          <div className="card card-pad bill-plan">
            <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
              <div className="col" style={{ gap: 4 }}>
                <div className="eyebrow">CURRENT PLAN</div>
                <div style={{ font: "600 17px var(--font-sans)", letterSpacing: "-0.01em" }}>ContactIQ Extension</div>
              </div>
              <PlanPill plan={user.plan === "trial" ? "trial" : user.plan}/>
            </div>

            <div className="bill-price-row">
              <span className="mono" style={{ font: "700 32px var(--font-mono)", color: "var(--accent)", letterSpacing: "-0.02em" }}>$5.00</span>
              <span className="dim">/ month</span>
            </div>

            {user.plan === "trial" && (
              <div className="bill-trial-note">
                <I.Sparkle style={{ color: "var(--accent)" }}/>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 12 }}>Trial active</div>
                  <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>
                    Free until <span className="mono">Jun 8, 2026</span>. Your card on file will be charged $5.00 then.
                    Cancel anytime before that and you won't see a charge.
                  </div>
                </div>
              </div>
            )}

            {user.plan === "active" && (
              <div className="bill-renew">
                <span className="dim" style={{ fontSize: 12 }}>Next charge</span>
                <span className="mono" style={{ fontWeight: 600 }}>$5.00 · Jun 8, 2026</span>
              </div>
            )}

            <ul className="bill-feats">
              <li><I.Check style={{ color: "var(--green)" }}/> Unlimited lookups</li>
              <li><I.Check style={{ color: "var(--green)" }}/> All sources, per-field provenance</li>
              <li><I.Check style={{ color: "var(--green)" }}/> Personal history + CSV export</li>
              <li><I.Check style={{ color: "var(--green)" }}/> Chrome · Firefox · Edge · Safari</li>
            </ul>

            <div className="row tight" style={{ marginTop: 4 }}>
              {user.plan === "trial" && (
                <button className="btn primary" onClick={() => setShowPayment(true)}>Add payment method</button>
              )}
              {user.plan === "active" && (
                <>
                  <button className="btn" disabled={portalBusy} onClick={openPortal}>
                    {portalBusy ? "Opening…" : "Update payment"}
                  </button>
                  <button className="btn ghost danger" disabled={portalBusy} onClick={openPortal}>
                    Cancel subscription
                  </button>
                </>
              )}
            </div>
          </div>

          {/* Payment method */}
          <div className="card card-pad bill-pm">
            <div className="row" style={{ justifyContent: "space-between" }}>
              <span className="eyebrow">PAYMENT METHOD</span>
              <button className="btn ghost sm" onClick={() => setShowPayment(true)}>Change</button>
            </div>
            {user.paymentMethod === "google_pay" ? (
              <div className="bill-pm-row">
                <div className="bill-pm-icon"><GoogleG size={22}/></div>
                <div className="col" style={{ gap: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>Google Pay</div>
                  <div className="dim" style={{ fontSize: 11.5 }}>Visa •••• 4242 · {user.email}</div>
                </div>
              </div>
            ) : (
              <div className="bill-pm-empty">
                <div className="dim" style={{ fontSize: 12.5 }}>No payment method on file.</div>
                <button className="btn primary sm" onClick={() => setShowPayment(true)}>
                  <GoogleG size={14}/> Add Google Pay
                </button>
              </div>
            )}
          </div>

          {/* Usage summary */}
          <div className="card card-pad bill-usage">
            <div className="row" style={{ justifyContent: "space-between" }}>
              <span className="eyebrow">USAGE THIS PERIOD</span>
              <span className="dim mono" style={{ fontSize: 11 }}>May 8 – Jun 8</span>
            </div>
            <div className="bill-usage-row">
              <div className="bill-usage-cell">
                <span className="mono" style={{ font: "700 26px var(--font-mono)", color: "var(--accent)", letterSpacing: "-0.02em" }}>14</span>
                <span className="dim" style={{ fontSize: 11 }}>lookups</span>
              </div>
              <div className="bill-usage-cell">
                <span className="mono" style={{ font: "700 26px var(--font-mono)", letterSpacing: "-0.02em" }}>6</span>
                <span className="dim" style={{ fontSize: 11 }}>buildings</span>
              </div>
              <div className="bill-usage-cell">
                <span className="mono" style={{ font: "700 26px var(--font-mono)", letterSpacing: "-0.02em" }}>8</span>
                <span className="dim" style={{ fontSize: 11 }}>companies</span>
              </div>
            </div>
            <div className="dim" style={{ fontSize: 11.5 }}>Unlimited on your plan — these numbers are for your reference.</div>
            <button className="btn sm" onClick={() => go("dashboard")}>View full history <I.ChevR/></button>
          </div>

          {/* Invoices */}
          <div className="card bill-invoices">
            <div className="row" style={{ padding: "14px 18px", justifyContent: "space-between", borderBottom: "1px solid var(--border-1)" }}>
              <span className="eyebrow">INVOICES</span>
              <button className="btn ghost sm"><I.Download/> Download all</button>
            </div>
            {user.plan === "trial" ? (
              <div style={{ padding: 24, textAlign: "center" }} className="dim">
                No invoices yet. Your first charge will be on <span className="mono">Jun 8, 2026</span>.
              </div>
            ) : (
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Invoice</th>
                    <th>Method</th>
                    <th style={{ textAlign: "right" }}>Amount</th>
                    <th>Status</th>
                    <th>&nbsp;</th>
                  </tr>
                </thead>
                <tbody>
                  {invoices.map(inv => (
                    <tr key={inv.id}>
                      <td className="mono">{inv.date}</td>
                      <td className="mono dim">{inv.id}</td>
                      <td>{inv.method}</td>
                      <td className="num"><span className="mono">{inv.amt}</span></td>
                      <td><span className="pill green">Paid</span></td>
                      <td>
                        <button className="btn icon sm row-act"><I.Download/></button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>

      {showCancel && (
        <CancelModal
          onClose={() => setShowCancel(false)}
          onConfirm={() => { setUser(u => ({ ...u, plan: "canceled" })); setShowCancel(false); }}
        />
      )}
      {showPayment && (
        <AddPaymentModal
          onClose={() => setShowPayment(false)}
          onDone={() => {
            setUser(u => ({ ...u, plan: u.plan === "trial" ? "active" : u.plan, paymentMethod: "google_pay" }));
            setShowPayment(false);
          }}
        />
      )}
    </>
  );
}

function CancelModal({ onClose, onConfirm }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="col" style={{ gap: 2 }}>
            <div className="eyebrow">CANCEL SUBSCRIPTION</div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>Are you sure?</div>
          </div>
          <button className="btn icon" onClick={onClose}><I.X/></button>
        </div>
        <div className="modal-body">
          <p style={{ font: "400 13px var(--font-sans)", color: "var(--fg-2)", lineHeight: 1.55 }}>
            You'll keep access until <span className="mono" style={{ color: "var(--fg-1)", fontWeight: 600 }}>Jun 8, 2026</span>.
            After that the extension stops working and your lookup history goes read-only — we keep it on file
            so you can come back later.
          </p>
          <div className="cancel-warn">
            <I.Sparkle style={{ color: "var(--amber)" }}/>
            <span style={{ fontSize: 12 }}>
              You've made <b>412 lookups</b> over 7 weeks. That's roughly <span className="mono">$0.012</span> per lookup.
            </span>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Never mind</button>
          <button className="btn danger" onClick={onConfirm}>Cancel my subscription</button>
        </div>
      </div>
    </div>
  );
}

function AddPaymentModal({ onClose, onDone }) {
  const [phase, setPhase] = useState("ready");

  useEffect(() => {
    if (phase === "processing") {
      const t = setTimeout(() => setPhase("done"), 1300);
      return () => clearTimeout(t);
    }
    if (phase === "done") {
      const t = setTimeout(onDone, 900);
      return () => clearTimeout(t);
    }
  }, [phase]);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 420 }} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="col" style={{ gap: 2 }}>
            <div className="eyebrow">ADD PAYMENT METHOD</div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>One tap with Google Pay</div>
          </div>
          <button className="btn icon" onClick={onClose}><I.X/></button>
        </div>
        <div className="modal-body" style={{ gap: 14 }}>
          {phase === "ready" && (
            <>
              <p style={{ font: "400 13px var(--font-sans)", color: "var(--fg-2)", lineHeight: 1.55 }}>
                We charge <span className="mono" style={{ color: "var(--fg-1)", fontWeight: 600 }}>$5.00/mo</span> after your
                trial ends. No upcharges, no usage tiers. You can cancel anytime from this page.
              </p>
              <button className="gpay-btn" style={{ height: 44 }} onClick={() => setPhase("processing")}>
                <GoogleG size={20}/> Pay
              </button>
              <div className="dim" style={{ textAlign: "center", fontSize: 11 }}>
                Encrypted &amp; tokenized · processed by Google Pay
              </div>
            </>
          )}
          {phase === "processing" && (
            <div className="gpay-processing">
              <div className="gpay-spinner"/>
              <div style={{ fontWeight: 500 }}>Authorizing with Google…</div>
            </div>
          )}
          {phase === "done" && (
            <div className="gpay-processing">
              <div className="gpay-check"><I.Check style={{ width: 28, height: 28 }}/></div>
              <div style={{ fontWeight: 600 }}>Payment method added</div>
              <div className="dim" style={{ fontSize: 11 }}>Visa •••• 4242 via Google Pay</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.BillingPage = BillingPage;
