/* global React, Icon, Pill */
const { useState: useStateB } = React;

/* Display metadata for each tier. Prices here are indicative; the authoritative
 * amount is the Stripe Price shown on the secure checkout page. Feature limits
 * mirror api/_plans.js (kept in sync intentionally). */
const PLAN_DISPLAY = {
  starter: { priceText: "€29", blurb: { en: "For a single venue getting started.", es: "Para un local que empieza." },
    features: { en: ["Up to 10 QR codes", "Up to 60 menu items", "Full analytics dashboard", "AI menu drafting"],
                es: ["Hasta 10 códigos QR", "Hasta 60 platos", "Panel de analíticas completo", "Borrador de menú con IA"] } },
  growth:  { priceText: "€59", blurb: { en: "For busy restaurants scaling placements.", es: "Para restaurantes en crecimiento." },
    features: { en: ["Up to 50 QR codes", "Up to 200 menu items", "Everything in Starter", "Priority email support"],
                es: ["Hasta 50 códigos QR", "Hasta 200 platos", "Todo lo de Starter", "Soporte prioritario"] } },
  pro:     { priceText: "€99", blurb: { en: "For groups and multi-location brands.", es: "Para grupos y multi-local." },
    features: { en: ["Unlimited QR codes", "Unlimited menu items", "Everything in Growth", "Dedicated onboarding"],
                es: ["Códigos QR ilimitados", "Platos ilimitados", "Todo lo de Growth", "Onboarding dedicado"] } },
};

const PlanCard = ({ tierKey, name, current, recommended, lang, busy, onPick }) => {
  const d = PLAN_DISPLAY[tierKey] || { priceText: "", blurb: {}, features: {} };
  return (
    <div className={`plan-card ${recommended ? "rec" : ""} ${current ? "current" : ""}`}>
      {recommended && <div className="plan-ribbon">{lang === "es" ? "Recomendado" : "Recommended"}</div>}
      <div className="plan-name">{name}</div>
      <div className="plan-price">{d.priceText}<span>/{lang === "es" ? "mes" : "mo"}</span></div>
      <div className="plan-blurb">{(d.blurb && d.blurb[lang]) || ""}</div>
      <ul className="plan-features">
        {((d.features && d.features[lang]) || []).map((f, i) => (
          <li key={i}><span className="pf-check"><Icon.check/></span>{f}</li>
        ))}
      </ul>
      <button
        className={`btn ${current ? "btn-secondary" : "btn-primary"} plan-btn`}
        style={current ? {} : { background: "var(--brand-purple)" }}
        disabled={busy || current}
        onClick={() => onPick(tierKey)}
      >
        {current ? (lang === "es" ? "Plan actual" : "Current plan") : busy ? (lang === "es" ? "Redirigiendo…" : "Redirecting…") : (lang === "es" ? "Elegir" : "Choose")}
      </button>
    </div>
  );
};

const Plans = ({ acct, lang, busyTier, onPick }) => {
  const tiers = (acct && acct.tiers) || [{ key: "starter", name: "Starter" }, { key: "growth", name: "Growth" }, { key: "pro", name: "Pro" }];
  const currentTier = acct && acct.subscription && acct.access && acct.access.active ? acct.subscription.tier : null;
  return (
    <div className="plan-grid">
      {tiers.map((t) => (
        <PlanCard key={t.key} tierKey={t.key} name={t.name}
          current={currentTier === t.key} recommended={t.key === "growth"}
          lang={lang} busy={busyTier === t.key} onPick={onPick}/>
      ))}
    </div>
  );
};

const lockCopy = (state, lang) => {
  const es = lang === "es";
  if (state === "trial_expired") return {
    title: es ? "Tu prueba gratuita ha terminado" : "Your free trial has ended",
    body: es ? "Elige un plan para reactivar tu panel y seguir publicando tu menú. Tus datos están a salvo." : "Choose a plan to reactivate your dashboard and keep publishing your menu. Your data is safe.",
  };
  if (state === "past_due") return {
    title: es ? "Pago pendiente" : "Payment past due",
    body: es ? "No pudimos procesar tu último pago. Actualiza tu método de pago para restaurar el acceso." : "We couldn't process your last payment. Update your payment method to restore access.",
  };
  return {
    title: es ? "Suscripción cancelada" : "Subscription canceled",
    body: es ? "Vuelve a suscribirte cuando quieras para recuperar el acceso completo." : "Re-subscribe any time to regain full access.",
  };
};

const Paywall = ({ acct, lang, busyTier, manageBusy, onPick, onManage }) => {
  const state = acct && acct.access ? acct.access.state : "trial_expired";
  const c = lockCopy(state, lang);
  const hasCustomer = acct && acct.subscription && acct.subscription.hasStripeCustomer;
  return (
    <div className="paywall">
      <div className="paywall-head">
        <div className="paywall-lock"><Icon.alert/></div>
        <div className="paywall-title">{c.title}</div>
        <div className="paywall-body">{c.body}</div>
      </div>
      <Plans acct={acct} lang={lang} busyTier={busyTier} onPick={onPick}/>
      {hasCustomer && (
        <div className="paywall-foot">
          <button className="btn btn-ghost" disabled={manageBusy} onClick={onManage}>
            {manageBusy ? (lang === "es" ? "Abriendo…" : "Opening…") : (lang === "es" ? "Gestionar facturación" : "Manage billing")}
          </button>
        </div>
      )}
    </div>
  );
};

const TrialBanner = ({ access, lang, onSubscribe }) => {
  const es = lang === "es";
  const days = access.daysLeft != null ? access.daysLeft : 0;
  const urgent = days <= 7;
  return (
    <div className={`trial-banner ${urgent ? "urgent" : ""}`}>
      <div className="trial-banner-l">
        <span className="trial-dot"/>
        <span>
          {es ? <><strong>{days} día{days === 1 ? "" : "s"}</strong> restantes de tu prueba gratuita</> : <><strong>{days} day{days === 1 ? "" : "s"}</strong> left in your free trial</>}
          {urgent && <span className="trial-sub"> · {es ? "suscríbete para no perder acceso" : "subscribe to keep access"}</span>}
        </span>
      </div>
      <button className="btn btn-primary trial-cta" style={{ background: "var(--brand-purple)" }} onClick={onSubscribe}>
        {es ? "Elegir un plan" : "Choose a plan"}
      </button>
    </div>
  );
};

const BillingTab = ({ acct, lang, busyTier, manageBusy, onPick, onManage }) => {
  const es = lang === "es";
  const sub = (acct && acct.subscription) || {};
  const access = (acct && acct.access) || {};
  const statusLabel = {
    active: es ? "Activa" : "Active",
    trial: es ? "Prueba gratuita" : "Free trial",
    trial_expired: es ? "Prueba terminada" : "Trial ended",
    past_due: es ? "Pago pendiente" : "Past due",
    canceled: es ? "Cancelada" : "Canceled",
  }[access.state] || access.state;
  const tone = access.active ? "var(--brand-green)" : "var(--brand-orange)";

  return (
    <div className="billing-tab">
      <div className="panel billing-status">
        <div>
          <div className="panel-title">{es ? "Tu suscripción" : "Your subscription"}</div>
          <div className="billing-status-row">
            <Pill color={tone}>{statusLabel}</Pill>
            {sub.tier && <span className="billing-tier">{sub.tier.charAt(0).toUpperCase() + sub.tier.slice(1)}</span>}
            {access.state === "trial" && access.daysLeft != null && (
              <span className="billing-sub">{access.daysLeft} {es ? "días restantes" : "days left"}</span>
            )}
          </div>
        </div>
        {sub.hasStripeCustomer && (
          <button className="btn btn-secondary" disabled={manageBusy} onClick={onManage}>
            {manageBusy ? (es ? "Abriendo…" : "Opening…") : (es ? "Gestionar facturación" : "Manage billing")}
          </button>
        )}
      </div>

      <div className="billing-plans-head">{es ? "Planes" : "Plans"}</div>
      <Plans acct={acct} lang={lang} busyTier={busyTier} onPick={onPick}/>
      <div className="billing-note">
        {es ? "El pago se procesa de forma segura con Stripe. El precio final se confirma en la página de pago." : "Payment is processed securely by Stripe. The final price is confirmed on the checkout page."}
      </div>
    </div>
  );
};

Object.assign(window, { Plans, Paywall, TrialBanner, BillingTab });
