// client-app.jsx — Client portal shell. Gated behind the purchased add-on.
// If the company hasn't bought the Client Portal module, shows a "not enabled"
// notice instead of the app. Otherwise: login → scoped dashboard.

function ClientApp() {
  const [tweaks, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  useEffect(() => {
    window.__currentTweaks = tweaks; window.dispatchEvent(new Event('tweaks-changed'));
    const root = document.documentElement; root.style.setProperty('--accent', tweaks.accent);
    const h = tweaks.accent.replace('#',''); const r=parseInt(h.slice(0,2),16),g=parseInt(h.slice(2,4),16),b=parseInt(h.slice(4,6),16);
    root.style.setProperty('--accent-deep', `#${Math.round(r*0.78).toString(16).padStart(2,'0')}${Math.round(g*0.78).toString(16).padStart(2,'0')}${Math.round(b*0.78).toString(16).padStart(2,'0')}`);
    root.style.setProperty('--accent-soft', `#${Math.round(r+(255-r)*0.86).toString(16).padStart(2,'0')}${Math.round(g+(255-g)*0.86).toString(16).padStart(2,'0')}${Math.round(b+(255-b)*0.86).toString(16).padStart(2,'0')}`);
    document.title = `${tweaks.companyName} — Client Portal`;
  }, [tweaks]);

  return (
    <ClientProvider>
      <div style={{ minHeight: '100vh', width: '100%', background: 'radial-gradient(circle at 30% 10%, #20262e 0%, #0a0d11 60%, #06080b 100%)', display: 'grid', placeItems: 'center', padding: 16 }}>
        <ClientFrame><ClientGate /></ClientFrame>
      </div>
      <TweaksPanel title="Tweaks">
        <TweakSection label="White-label">
          <TweakText label="Company name" value={tweaks.companyName} onChange={v => setTweak('companyName', v)} />
        </TweakSection>
        <TweakSection label="Theme">
          <TweakColor label="Accent" value={tweaks.accent} options={['#E55B13','#1D6FB8','#137C50','#5B3FB8','#0F172A']} onChange={v => setTweak('accent', v)} />
        </TweakSection>
      </TweaksPanel>
    </ClientProvider>
  );
}

function ClientFrame({ children }) {
  const W = 1440, H = 1000;
  const [scale, setScale] = useState(1);
  useEffect(() => {
    const c = () => setScale(Math.min((window.innerWidth - 32) / W, (window.innerHeight - 32) / H, 1));
    c(); window.addEventListener('resize', c); return () => window.removeEventListener('resize', c);
  }, []);
  return (
    <div style={{ width: W * scale, height: H * scale, borderRadius: 14, overflow: 'hidden', boxShadow: '0 50px 100px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05)' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left', width: W, height: H, display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
        <div style={{ height: 38, flexShrink: 0, background: '#E9EAEC', borderBottom: '1px solid #D4D6DA', display: 'flex', alignItems: 'center', padding: '0 14px', gap: 14 }}>
          <div style={{ display: 'flex', gap: 7 }}>{['#FF5F57','#FEBC2E','#28C840'].map(c => <span key={c} style={{ width: 12, height: 12, borderRadius: 6, background: c }} />)}</div>
          <div style={{ flex: 1, maxWidth: 460, margin: '0 auto', padding: '5px 14px', borderRadius: 6, background: '#fff', border: '1px solid #D4D6DA', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-2)', textAlign: 'center' }}>🔒 partners.railflagspro.com</div>
          <div style={{ width: 30 }} />
        </div>
        <div style={{ flex: 1, display: 'flex', overflow: 'hidden', position: 'relative' }}>{children}</div>
      </div>
    </div>
  );
}

// ── Entitlement + auth gate ──────────────────────────────────
function ClientGate() {
  const { session, client } = useClient();
  const [subLoaded, setSubLoaded] = useState(false);
  const [hasPortal, setHasPortal] = useState(null);

  // Load subscription entitlement after login
  useEffect(() => {
    if (!session) { setSubLoaded(false); setHasPortal(null); return; }

    const checkPortal = async () => {
      try {
        let sub = null;
        // Prefer new entitlements helper; fall back to legacy subscription helper
        if (typeof RFP_ENTITLEMENTS !== 'undefined') {
          RFP_ENTITLEMENTS.clearCache();
          sub = await RFP_ENTITLEMENTS.getSubscription();
        }
        if (!sub) sub = await RFP.subscription.load();

        if (!sub) {
          // No subscription found — null means unknown (offline or demo)
          setHasPortal(null);
        } else {
          // Support both old and new column names
          const portalEnabled = sub.client_portal_enabled !== undefined
            ? sub.client_portal_enabled
            : sub.has_client_portal;
          setHasPortal(!!portalEnabled);
        }
      } catch (e) {
        // On error: allow access (don't block demo users)
        setHasPortal(true);
      } finally {
        setSubLoaded(true);
      }
    };

    checkPortal();
  }, [session]);

  if (!session || !client) return <ClientLogin />;

  // While loading subscription, show a brief loading state
  if (!subLoaded) {
    return (
      <div style={{ flex: 1, display: 'grid', placeItems: 'center', background: 'var(--paper)' }}>
        <div style={{ fontSize: 13, color: 'var(--muted)' }}>Loading…</div>
      </div>
    );
  }

  // If subscription loaded and explicitly no client portal, show paywall
  // null means unknown (Supabase unavailable) — allow through for demo
  if (hasPortal === false) return <AddonLocked />;
  return <ClientShell />;
}

// Shown when the add-on hasn't been purchased
function AddonLocked() {
  const { tweaks } = useTweakValues();
  return (
    <div style={{ flex: 1, display: 'grid', placeItems: 'center', background: 'var(--paper)', padding: 40 }}>
      <div style={{ maxWidth: 480, textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: 16, background: 'var(--accent-soft)', color: 'var(--accent-deep)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}><IconUser size={30} /></div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>ADD-ON REQUIRED</div>
        <h2 style={{ margin: '0 0 12px', fontSize: 24, fontWeight: 700, letterSpacing: -0.5 }}>Client Portal Add-On Required</h2>
        <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 24 }}>
          The Client Portal is available as a $500/mo add-on. Your clients can view job status, compliance documents, and pay invoices directly.
        </p>
        <a href="https://madethis.com/checkout/railflagging-pro/md770567j4eq554s89d7h7bhh588c2k6"
          target="_blank" rel="noopener noreferrer"
          style={{ display: 'inline-block', padding: '12px 28px', background: 'var(--accent)', color: '#fff', borderRadius: 9, fontWeight: 700, fontSize: 14, textDecoration: 'none', marginBottom: 16 }}>
          Add Client Portal — $500/mo
        </a>
        <div style={{ fontSize: 12, color: 'var(--muted-2)', marginTop: 8 }}>
          Contact <a href="https://railflagging-pro.madethis.app/#contact" style={{ color: 'var(--accent-deep)' }}>support</a> if you believe this is an error.
        </div>
      </div>
    </div>
  );
}

// ── Login (scoped to railroad customer accounts) ─────────────
function ClientLogin() {
  const { tweaks } = useTweakValues();
  const { doLogin } = useClient();
  const [email, setEmail] = useState('bnsf.portal@demo-rwic.com');
  const [pw, setPw] = useState('demo123');
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);
  const submit = async () => {
    setErr('');
    setLoading(true);
    try {
      const res = await doLogin(email, pw);
      if (!res.ok) setErr(res.error);
    } catch (e) {
      setErr(e.message || 'Login failed.');
    } finally {
      setLoading(false);
    }
  };
  // Demo accounts: live Supabase auth user + legacy prototype users
  const demos = [
    ['BNSF Railway (live)', 'bnsf.portal@demo-rwic.com'],
    ['BNSF Railway (proto)', 'jcole@bnsf.com'],
  ];
  return (
    <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.1fr 0.9fr' }}>
      <div style={{ background: 'linear-gradient(160deg, #0E1622 0%, #1a2536 100%)', color: '#fff', padding: 56, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -80, right: -80, width: 320, height: 320, borderRadius: '50%', background: 'var(--accent)', opacity: 0.16, filter: 'blur(10px)' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: '#0F172A', border: '1px solid rgba(255,255,255,0.15)', display: 'grid', placeItems: 'center', fontWeight: 700, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'var(--accent)', clipPath: 'polygon(0 100%, 100% 100%, 100% 58%, 0 90%)' }} />
            <span style={{ position: 'relative', zIndex: 1 }}>{(tweaks.companyName||'RF').split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase()}</span>
          </div>
          <div style={{ fontWeight: 700, fontSize: 17 }}>{tweaks.companyName}</div>
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 30, fontWeight: 700, letterSpacing: -0.8, lineHeight: 1.15 }}>Your crews,<br />your compliance,<br />your invoices.</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.65)', marginTop: 12, lineHeight: 1.6, maxWidth: 330 }}>A live window into the flagging work on your railroad — scoped to your company only.</div>
        </div>
        <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.4)', position: 'relative' }} className="mono">Partner access · {tweaks.companyName}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48, background: 'var(--paper)' }}>
        <div style={{ width: '100%', maxWidth: 340 }}>
          <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: -0.4 }}>Customer sign in</div>
          <div style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 4, marginBottom: 20 }}>Railroad partner accounts.</div>
          <label style={{ display: 'block', marginBottom: 12 }}><div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Email</div>
            <input value={email} onChange={e=>setEmail(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} style={cInput} /></label>
          <label style={{ display: 'block', marginBottom: 14 }}><div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>Password</div>
            <input type="password" value={pw} onChange={e=>setPw(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} style={cInput} /></label>
          {err && <div style={{ background: 'var(--bad-soft)', color: 'var(--bad)', padding: '8px 12px', borderRadius: 8, fontSize: 12.5, marginBottom: 14 }}>{err}</div>}
          <Button variant="primary" size="lg" style={{ width: '100%', opacity: loading ? 0.7 : 1 }} onClick={submit} disabled={loading}>{loading ? 'Signing in…' : 'Sign in'}</Button>
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Demo accounts · password demo123</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              {demos.map(([label, em]) => (
                <button key={em} onClick={() => { setEmail(em); setPw('demo123'); }} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 10px', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, cursor: 'pointer', fontSize: 12.5, width: '100%' }}>
                  <span style={{ fontWeight: 600 }}>{label}</span><span className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>{em}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
const cInput = { width: '100%', padding: '10px 12px', border: '1px solid var(--line-strong)', borderRadius: 9, fontSize: 14, fontFamily: 'inherit', background: 'var(--panel)', outline: 'none' };

Object.assign(window, { ClientApp, ClientFrame, ClientGate, AddonLocked, ClientLogin, cInput });
ReactDOM.createRoot(document.getElementById('root')).render(<ClientApp />);
