/* ============================================================
   Centralized demo / access model (client). Mirror of lib/access.js.
   All demo restrictions read from here — no hardcoding scattered in views.
   Tiers: 'visitor' (no login) | 'free' (signed in) | 'paid' (full data loaded).
   ============================================================ */
window.DEMO_COMPANIES = ['bhp', 'anglo', 'rio'];
window.DEMO_EXPORT_ROW_LIMIT = 25;
window.DEMO_DISCLAIMER =
  'Demo data is provided for selected public mining companies to demonstrate Kestrel’s ESG extraction and analysis tools. ' +
  'Results are generated from publicly available documents and may contain errors, omissions, hallucinations, source mismatches, or omissions. ' +
  'Users should verify outputs before relying on them.';

window.isDemoCompany = (id) => window.DEMO_COMPANIES.indexOf(id) !== -1;

// data.jsx sets window.KESTREL_DEMO = false once the full (paid) dataset loads.
window.accessTier = () => {
  const signedIn = !!(window.Clerk && window.Clerk.user);
  if (window.KESTREL_DEMO === false) return 'paid';
  return signedIn ? 'free' : 'visitor';
};
window.isDemoMode = () => window.accessTier() !== 'paid';
window.canViewCompany = (id) => window.accessTier() === 'paid' || window.isDemoCompany(id);
window.canCompare = () => window.accessTier() === 'paid';
// Rows a CSV export may contain: paid = all; free = preview; visitor = none (sign up).
window.exportRowLimit = () => {
  const t = window.accessTier();
  if (t === 'paid') return Infinity;
  if (t === 'free') return window.DEMO_EXPORT_ROW_LIMIT;
  return 0;
};

const _goRegister = () => { if (window.kestrelNavigate) window.kestrelNavigate({ page: 'register-interest' }); };

/* "Demo data" / "Demo company" pill. */
const DemoBadge = ({ label = 'Demo data', style }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999,
    background: 'rgba(166,225,94,0.16)', color: 'var(--moss-deep)', border: '1px solid rgba(166,225,94,0.45)',
    fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, ...style,
  }}>{label}</span>
);
window.DemoBadge = DemoBadge;

/* Disclaimer banner shown on demo pages (+ a Request access CTA). */
const DemoDisclaimer = ({ compact }) => (
  <div style={{
    border: '1px solid var(--line)', borderRadius: 12, background: 'var(--canvas-2)',
    padding: compact ? '12px 14px' : '14px 18px', display: 'flex', gap: 12, alignItems: 'flex-start',
  }}>
    <span style={{ flex: '0 0 auto', marginTop: 1 }}><DemoBadge /></span>
    <p style={{ margin: 0, fontSize: 12.5, lineHeight: '19px', color: 'var(--ink-2)' }}>
      {window.DEMO_DISCLAIMER}{' '}
      <button onClick={_goRegister} style={{ background: 'none', border: 'none', padding: 0, color: 'var(--moss-deep)', textDecoration: 'underline', textUnderlineOffset: '2px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit' }}>Request access</button>{' '}for full functionality.
    </p>
  </div>
);
window.DemoDisclaimer = DemoDisclaimer;

/* Lock panel for paid-only resources (non-demo companies, comparison). */
const LockNotice = ({ title = 'Full access required', body, cta = 'Request access' }) => (
  <section className="section"><div className="site-wrap" style={{ maxWidth: 560, padding: '64px 0 80px', textAlign: 'center' }}>
    <div style={{ width: 50, height: 50, borderRadius: 13, background: 'rgba(166,225,94,0.14)', color: 'var(--moss-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
      <Icon name="lock" size={21} />
    </div>
    <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--moss-deep)' }}>Kestrel · Full access</div>
    <h2 className="spade-h" style={{ fontSize: 'clamp(24px, 4vw, 36px)', marginTop: 12 }}>{title}</h2>
    {body && <p style={{ marginTop: 14, fontSize: 15.5, lineHeight: '25px', color: 'var(--ink-2)', maxWidth: 440, marginLeft: 'auto', marginRight: 'auto' }}>{body}</p>}
    <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 28, flexWrap: 'wrap' }}>
      <button className="btn btn-lime btn-lg" style={{ fontFamily: 'var(--mono)' }} onClick={() => (typeof openClerkSignIn === 'function') && openClerkSignIn()}>Sign in</button>
      <button className="btn btn-lg" style={{ fontFamily: 'var(--mono)' }} onClick={_goRegister}>{cta}</button>
    </div>
  </div></section>
);
window.LockNotice = LockNotice;

/* Reactive gate for routes. Re-renders on auth change + on data load (tier can
   flip demo→paid once the full dataset arrives). Demo companies are viewable by
   everyone; non-demo companies and comparison require full access. */
const TierGate = ({ kind, id, children }) => {
  const auth = useClerkAuth();
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => {
    const h = () => force();
    window.addEventListener('strix-loaded', h);
    return () => window.removeEventListener('strix-loaded', h);
  }, []);
  void auth; // (referenced so the hook subscription isn't tree-shaken)
  const allowed = kind === 'compare' ? window.canCompare()
    : kind === 'company' ? window.canViewCompany(id)
    : true;
  if (allowed) {
    // Demo-tier viewing a permitted (demo) company → prepend the disclaimer banner.
    if (kind === 'company' && window.isDemoMode && window.isDemoMode()) {
      return (<><div className="site-wrap" style={{ paddingTop: 18, paddingBottom: 2 }}><DemoDisclaimer /></div>{children}</>);
    }
    return children;
  }
  if (kind === 'compare') {
    return <LockNotice title="Unlock full comparison"
      body="Side-by-side company comparison is part of full access. BHP, Anglo American and Rio Tinto are available to explore individually as a demo."
      cta="Request access" />;
  }
  return <LockNotice title="Full access required"
    body="BHP, Anglo American and Rio Tinto are free to explore as a demo. Full access unlocks every company, full exports, and side-by-side comparison."
    cta="Request access" />;
};
window.TierGate = TierGate;
