// PatientRouter — post-teaser handoff (#patient-router?role=patient|pro|…).
// Does not replace classic landing; routes by role into existing hash screens.

const ROUTER_ROLES = new Set(['patient', 'pro', 'practice', 'industry', 'other']);

function parseRouterParams() {
  const hash = window.location.hash || '';
  const q = hash.indexOf('?');
  const params = q >= 0 ? new URLSearchParams(hash.slice(q + 1)) : new URLSearchParams();
  const role = String(params.get('role') || '').trim().toLowerCase();
  const sub = String(params.get('sub') || '').trim().toLowerCase();
  return {
    role: ROUTER_ROLES.has(role) ? role : null,
    sub: sub || null,
  };
}

function persistRouterSub(sub) {
  if (!sub) return;
  if (window.TDRoleSub?.set) window.TDRoleSub.set(sub);
  else {
    try { localStorage.setItem('td_role_sub', sub); } catch (_) {}
  }
}

function PatientRouter({ go }) {
  const { role, sub } = parseRouterParams();

  React.useEffect(() => {
    if (!go || !role) {
      if (go) go('landing');
      return;
    }
    if ((role === 'industry' || role === 'other') && sub) persistRouterSub(sub);
    if (role === 'patient') go('triage');
    else if (role === 'pro' || role === 'practice') {
      try { localStorage.setItem('td_role', 'dentist'); } catch (_) {}
      go('professional-dashboard');
    } else if (role === 'industry') go('industry');
    else if (role === 'other') go('other');
    else go('landing');
  }, [go, role, sub]);

  if (!role) return null;

  const label = {
    patient: 'Patient',
    pro: 'Dental professional',
    practice: 'Practice',
    industry: 'Industry',
    other: 'Other',
  }[role];

  return (
    <div className="screen-container gap-screen animate-fade-in-up">
      <p className="t-eyebrow">Stakeholder router</p>
      <h1 className="section-title" style={{ marginTop: 8 }}>Welcome, {label}.</h1>
      <p className="section-subtitle" style={{ marginTop: 12 }}>
        Routing you to the right starting point…
      </p>
      <div className="disclaimer-banner" style={{ marginTop: 16 }}>
        Information, not diagnosis — confirm with a licensed dentist.
      </div>
      <p className="section-subtitle" style={{ marginTop: 24 }}>
        <a href="/methodology/" className="methodology-link">How we measure recognition →</a>
      </p>
    </div>
  );
}

window.PatientRouter = PatientRouter;
