/* Tier model — source of truth for plan-based feature gating.
 *
 * Persists the user's active plan in localStorage (`kestrel.tier`) and
 * exposes a hook + helpers so any section can conditionally render
 * based on plan ordinal. Order is strict: none < free < analyst < pro
 * < enterprise, so `hasTier(user, needed)` is a simple index compare.
 *
 * BILLING_ENABLED = false hides every paid-plan UI surface (pricing nav,
 * upsell cards, tier badges) and bypasses every `hasTier` gate so logged-out
 * visitors see all features. The tier model + capability lists are kept
 * intact so flipping this back to true restores paid gating without code
 * changes. Flip when ready to charge. */
const BILLING_ENABLED = false;
window.BILLING_ENABLED = BILLING_ENABLED;

const TIER_ORDER = ['none', 'free', 'analyst', 'pro', 'enterprise'];

const TIER_META = {
  none:       { label: 'No plan',     short: 'None',       price: '—',        accent: 'var(--ink-3)' },
  free:       { label: 'Free plan',   short: 'Free',       price: '£0',       accent: 'var(--ink-2)' },
  analyst:    { label: 'Analyst plan',short: 'Analyst',    price: '£49/mo',   accent: 'var(--moss)' },
  pro:        { label: 'Pro plan',    short: 'Pro',        price: '£129/mo',  accent: 'var(--moss-deep)' },
  enterprise: { label: 'Enterprise',  short: 'Enterprise', price: '£500+/mo', accent: '#C07A3E' },
};

/* Capabilities each tier unlocks. Strings line up verbatim with the pricing
 * page so the gates and the marketing promise stay in sync. */
const TIER_CAPS = {
  free: [
    'aggregate.dataset',
    'distribution.trend',
    'scorecard.readonly',
  ],
  analyst: [
    'explorer.passageLevel',
    'explorer.filters',
    'disclosure.sourceCitations',
    'export.csv.5k',
  ],
  pro: [
    'compare.multiCompany',
    'compare.leaderFlags',
    'export.csv.unlimited',
    'methodology.appendixPdf',
    'support.email',
  ],
  enterprise: [
    'team.seats',
    'api.access',
    'regulatory.evidencePacks',
    'dedicated.methodologyReview',
  ],
};

const TIER_EVENT = 'kestrel.tier.change';

const tierIndex = (t) => {
  const i = TIER_ORDER.indexOf(t);
  return i < 0 ? 0 : i;
};

const hasTier = (userTier, neededTier) => {
  if (!BILLING_ENABLED) return true;
  return tierIndex(userTier) >= tierIndex(neededTier);
};

const getTier = () => {
  try {
    const raw = localStorage.getItem('kestrel.tier');
    if (raw && TIER_ORDER.indexOf(raw) >= 0) return raw;
  } catch (e) {}
  return 'none';
};

const setTier = (t) => {
  if (TIER_ORDER.indexOf(t) < 0) return;
  try { localStorage.setItem('kestrel.tier', t); } catch (e) {}
  try { window.dispatchEvent(new CustomEvent(TIER_EVENT, { detail: t })); } catch (e) {}
};

const useTier = () => {
  const [tier, setTierState] = React.useState(getTier);
  React.useEffect(() => {
    const onEvt = (e) => setTierState(e.detail || getTier());
    const onStorage = (e) => { if (e.key === 'kestrel.tier') setTierState(getTier()); };
    window.addEventListener(TIER_EVENT, onEvt);
    window.addEventListener('storage', onStorage);
    return () => {
      window.removeEventListener(TIER_EVENT, onEvt);
      window.removeEventListener('storage', onStorage);
    };
  }, []);
  return [tier, (t) => { setTier(t); setTierState(t); }];
};

/* Shared "you need to upgrade to X" card. Kept visually close to the Kestrel
 * card language (sage tint, moss rule, dashed lock chip) so gated sections
 * feel coherent rather than pasted in. */
const TierLockCard = ({ needed, currentTier, onUpgrade, feature, description }) => {
  const meta = TIER_META[needed] || TIER_META.analyst;
  return (
    <div style={{
      padding:'40px 44px',
      border:'1px solid #DCE3CF',
      borderRadius:16,
      background:'linear-gradient(135deg, var(--sage-tint) 0%, var(--canvas) 120%)',
      display:'flex', gap:28, alignItems:'flex-start', flexWrap:'wrap',
    }}>
      <div style={{
        flexShrink:0, width:52, height:52, borderRadius:14,
        background:'var(--canvas)', border:'1px solid #DCE3CF',
        display:'flex', alignItems:'center', justifyContent:'center', color:'var(--moss-deep)',
      }}>
        <Icon name="lock" size={20}/>
      </div>
      <div style={{flex:'1 1 320px', minWidth:0}}>
        <div className="eyebrow" style={{color:'var(--moss-deep)', marginBottom:6}}>
          {meta.label} required
        </div>
        <div style={{fontSize:24, lineHeight:'32px', fontWeight:500, letterSpacing:'-0.015em', color:'var(--ink)'}}>
          {feature}
        </div>
        <p style={{marginTop:12, fontSize:14, lineHeight:'22px', color:'var(--ink-2)', maxWidth:520}}>
          {description}
        </p>
        <div style={{marginTop:18, display:'flex', gap:10, alignItems:'center', flexWrap:'wrap'}}>
          <button className="btn btn-primary" onClick={onUpgrade}>
            Upgrade to {meta.short} <Icon name="arrow-right" size={14} style={{marginLeft:4}} className="arrow"/>
          </button>
          <span style={{fontSize:12, color:'var(--ink-3)'}}>
            {currentTier === 'none' ? 'No plan active' : `Current: ${TIER_META[currentTier]?.short || currentTier}`} · {meta.price}
          </span>
        </div>
      </div>
    </div>
  );
};

window.TIER_ORDER = TIER_ORDER;
window.TIER_META = TIER_META;
window.TIER_CAPS = TIER_CAPS;
window.hasTier = hasTier;
window.getTier = getTier;
window.setTier = setTier;
window.useTier = useTier;
window.TierLockCard = TierLockCard;
