/**
 * UserJourney.jsx
 * Core session detection, personalization context, and layout resolution.
 *
 * Exports:
 *   useUserJourney()   — hook: returns journey context
 *   JourneyProvider    — context provider (wrap app root)
 *   trackEvent(type, data) — fire a journey event
 *   updatePatientContext(patch) — update patient state in localStorage + API
 *   updateProfessionalContext(patch) — update professional state
 */

const { createContext, useContext, useState, useEffect, useCallback, useRef } = React;

// ─── localStorage keys ────────────────────────────────────────────────────────
const KEYS = {
  SESSION_ID:    'td_session_id',
  VISIT_COUNT:   'td_visit_count',
  LAST_VISIT:    'td_last_visit',
  ROLE:          'td_role',
  PATIENT_CTX:   'td_patient_ctx',
  PRO_CTX:       'td_pro_ctx',
  LAYOUT_VER:    'td_layout_ver',
};

// ─── Role metadata ────────────────────────────────────────────────────────────
const ROLE_META = {
  patient:        { label: 'Patient',         portal: '#patient-portal',    color: '#1B3557' },
  dentist:        { label: 'Dentist',         portal: '#dentist-portal',    color: '#1B3557' },
  hygienist:      { label: 'Hygienist',       portal: '#hygienist-portal',  color: '#2D6A4F' },
  da:             { label: 'Dental Assistant',portal: '#hygienist-portal',  color: '#2D6A4F' },
  front_desk:     { label: 'Front Desk',      portal: '#dentist-portal',    color: '#1B3557' },
  office_manager: { label: 'Office Manager',  portal: '#dentist-portal',    color: '#1B3557' },
  admin:          { label: 'Admin',           portal: '#admin-editor',      color: '#6B21A8' },
  guest:          { label: 'Visitor',         portal: '/',                  color: '#1B3557' },
};

// ─── Default layout configs (when API unavailable) ────────────────────────────
const DEFAULT_LAYOUTS = {
  patient: {
    sections: [
      { id: 'hero',        type: 'hero',               enabled: true,  position: 1 },
      { id: 'history',     type: 'last_visit_context', enabled: true,  position: 2 },
      { id: 'quick_start', type: 'quick_start_tiles',  enabled: true,  position: 3 },
      { id: 'education',   type: 'education_rail',     enabled: true,  position: 4 },
      { id: 'emergency',   type: 'emergency_banner',   enabled: true,  position: 5 },
    ],
    theme: { primary: '#1B3557', accent: '#52C4A0', bg: '#FAF9F7', font: 'Inter', radius: '12px' },
    nav_items: [
      { label: 'Home',           route: '#dashboard',      icon: 'home'   },
      { label: 'Find a Dentist', route: '#directory',      icon: 'search' },
      { label: 'My Records',     route: '#wallet',         icon: 'folder' },
      { label: 'Second Opinion', route: '#second-opinion', icon: 'shield' },
    ],
    feature_flags: { show_education_rail: true, show_emergency_banner: true },
  },
  dentist: {
    sections: [
      { id: 'next_move',  type: 'next_move_card',      enabled: true,  position: 1 },
      { id: 'hitl_queue', type: 'hitl_queue_summary',  enabled: true,  position: 2 },
      { id: 'agents',     type: 'agent_grid',          enabled: true,  position: 3 },
      { id: 'metrics',    type: 'practice_metrics',    enabled: true,  position: 4 },
      { id: 'upgrade',    type: 'upgrade_cta',         enabled: true,  position: 6 },
    ],
    theme: { primary: '#1B3557', accent: '#52C4A0', bg: '#FAF9F7', font: 'Inter', radius: '12px' },
    nav_items: [
      { label: 'Dashboard', route: '/find/#dentist-portal', icon: 'grid',       badge_source: null },
      { label: 'Agents',    route: '/for-dentists/suite/#office', icon: 'cpu'                            },
      { label: 'Queue',     route: '/command/',           icon: 'clock',      badge_source: 'pending_hitl_count' },
      { label: 'Patients',  route: '/find/#forms',       icon: 'users'                          },
      { label: 'Billing',   route: '/for-dentists/suite/#treatment-plan', icon: 'dollar-sign'                    },
      { label: 'Reports',   route: '/for-dentists/suite/#practice-dna', icon: 'bar-chart-2'                    },
    ],
    feature_flags: { show_upgrade_cta: true, show_team_section: true, show_vps_score: true },
  },
  hygienist: {
    sections: [
      { id: 'next_move', type: 'next_move_card',   enabled: true, position: 1 },
      { id: 'schedule',  type: 'today_schedule',   enabled: true, position: 2 },
      { id: 'recall',    type: 'recall_queue',     enabled: true, position: 3 },
      { id: 'ce',        type: 'ce_progress',      enabled: true, position: 4 },
      { id: 'jobs',      type: 'job_board_preview',enabled: true, position: 5 },
    ],
    theme: { primary: '#2D6A4F', accent: '#74C69D', bg: '#FAF9F7', font: 'Inter', radius: '12px' },
    nav_items: [
      { label: 'Home',     route: '#hygienist-portal', icon: 'home'       },
      { label: 'Schedule', route: '#schedule',         icon: 'calendar'   },
      { label: 'Recall',   route: '#recall',           icon: 'refresh-cw' },
      { label: 'CE Hub',   route: '#ce-hub',           icon: 'book-open'  },
      { label: 'Jobs',     route: '#jobs',             icon: 'briefcase'  },
    ],
    feature_flags: { show_prn_board: true, show_education_rail: true },
  },
};

// ─── Generate stable anonymous session ID ─────────────────────────────────────
function getOrCreateSessionId() {
  let id = localStorage.getItem(KEYS.SESSION_ID);
  if (!id) {
    id = 'td_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 9);
    localStorage.setItem(KEYS.SESSION_ID, id);
  }
  return id;
}

// ─── Context ──────────────────────────────────────────────────────────────────
const JourneyContext = createContext(null);

// ─── Provider ─────────────────────────────────────────────────────────────────
function JourneyProvider({ children }) {
  const [journey, setJourney] = useState(null);
  const [loading, setLoading] = useState(true);
  const initialized = useRef(false);

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;
    initJourney();
  }, []);

  async function initJourney() {
    // 1. Read localStorage state
    const sessionId    = getOrCreateSessionId();
    const rawCount     = parseInt(localStorage.getItem(KEYS.VISIT_COUNT) || '0', 10);
    const visitCount   = rawCount + 1;
    const role         = localStorage.getItem(KEYS.ROLE) || null;
    const lastVisit    = localStorage.getItem(KEYS.LAST_VISIT);
    const patientCtx   = safeJSON(localStorage.getItem(KEYS.PATIENT_CTX), {});
    const proCtx       = safeJSON(localStorage.getItem(KEYS.PRO_CTX), {});
    const isNew        = visitCount === 1 || !role;

    // 2. Increment visit count + record timestamp
    localStorage.setItem(KEYS.VISIT_COUNT, String(visitCount));
    localStorage.setItem(KEYS.LAST_VISIT, new Date().toISOString());

    // 3. Build local context immediately (shows UI without waiting for API)
    const localContext = buildContext({
      sessionId, visitCount, role, lastVisit, patientCtx, proCtx, isNew, layoutConfig: null,
    });
    setJourney(localContext);
    setLoading(false);

    // 4. Fetch server context in background (enriches layout, onboarding state)
    try {
      const params = new URLSearchParams({ session_id: sessionId });
      if (role) params.set('role', role);
      if (proCtx.practiceId) params.set('practice_id', proCtx.practiceId);

      const res = await fetch(`/api/user/journey?${params}`);
      if (res.ok) {
        const data = await res.json();
        const layoutConfig = data.layoutConfig || DEFAULT_LAYOUTS[role] || DEFAULT_LAYOUTS.patient;
        setJourney(prev => ({
          ...prev,
          layoutConfig,
          onboarding: data.onboarding,
          nextRecommendedAction: data.nextRecommendedAction,
          serverSynced: true,
        }));
      }
    } catch (_) {
      // Use local defaults silently
    }
  }

  function buildContext({ sessionId, visitCount, role, lastVisit, patientCtx, proCtx, isNew, layoutConfig }) {
    const effectiveRole = role || 'guest';
    const roleMeta = ROLE_META[effectiveRole] || ROLE_META.guest;
    const layout = layoutConfig || DEFAULT_LAYOUTS[effectiveRole] || DEFAULT_LAYOUTS.patient;

    return {
      sessionId,
      visitCount,
      isNew,
      role: effectiveRole,
      roleMeta,
      lastVisit: lastVisit ? new Date(lastVisit) : null,
      daysSinceLastVisit: lastVisit ? Math.floor((Date.now() - new Date(lastVisit)) / 86400000) : null,
      patientCtx,
      proCtx,
      layoutConfig: layout,
      onboarding: null,
      nextRecommendedAction: null,
      serverSynced: false,

      // Mutation helpers
      setRole: (newRole) => {
        localStorage.setItem(KEYS.ROLE, newRole);
        setJourney(prev => ({ ...prev, role: newRole, roleMeta: ROLE_META[newRole] || ROLE_META.guest }));
        trackEvent('role_selected', { role: newRole });
      },
      updatePatientCtx: (patch) => {
        const next = { ...patientCtx, ...patch };
        localStorage.setItem(KEYS.PATIENT_CTX, JSON.stringify(next));
        setJourney(prev => ({ ...prev, patientCtx: next }));
        trackEventRaw(sessionId, 'patient_context_updated', patch);
      },
      updateProCtx: (patch) => {
        const next = { ...proCtx, ...patch };
        localStorage.setItem(KEYS.PRO_CTX, JSON.stringify(next));
        setJourney(prev => ({ ...prev, proCtx: next }));
        trackEventRaw(sessionId, 'professional_context_updated', patch);
      },
      reset: () => {
        Object.values(KEYS).forEach(k => localStorage.removeItem(k));
        window.location.reload();
      },
    };
  }

  return React.createElement(JourneyContext.Provider, { value: { journey, loading } }, children);
}

// ─── Hook ─────────────────────────────────────────────────────────────────────
function useUserJourney() {
  const ctx = useContext(JourneyContext);
  if (!ctx) throw new Error('useUserJourney must be used inside JourneyProvider');
  return ctx;
}

// ─── Event tracking (fire-and-forget) ─────────────────────────────────────────
function trackEvent(eventType, data = {}) {
  const sessionId = localStorage.getItem(KEYS.SESSION_ID);
  if (!sessionId) return;
  trackEventRaw(sessionId, eventType, data);
}

async function trackEventRaw(sessionId, eventType, data = {}) {
  try {
    await fetch('/api/user/journey', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        session_id: sessionId,
        event_type: eventType,
        event_data: data,
        path: window.location.hash || '/',
      }),
    });
  } catch (_) { /* silent */ }
}

// ─── Utility ──────────────────────────────────────────────────────────────────
function safeJSON(str, fallback) {
  try { return JSON.parse(str) || fallback; } catch (_) { return fallback; }
}

// ─── Role Selector Modal (used on first visit) ────────────────────────────────
function RoleSelectorModal({ onSelect }) {
  const roles = [
    { id: 'patient',   label: 'I\'m a Patient',          icon: 'smile',     desc: 'Find dentists, get estimates, manage my dental health' },
    { id: 'dentist',   label: 'I\'m a Dentist / Owner',  icon: 'tooth',     desc: 'Access practice tools, AI agents, and patient management' },
    { id: 'hygienist', label: 'I\'m a Hygienist / DA',   icon: 'sparkles',  desc: 'Scheduling, CE credits, job board, and recall tools' },
    { id: 'front_desk',label: 'I\'m Front Desk / Admin', icon: 'clipboard', desc: 'Appointments, insurance verification, patient communications' },
  ];

  return React.createElement('div', {
    style: {
      position: 'fixed', inset: 0, background: 'rgba(27,53,87,0.7)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9999, backdropFilter: 'blur(4px)',
    }
  },
    React.createElement('div', {
      style: {
        background: '#FAF9F7', borderRadius: 20, padding: '48px 40px',
        maxWidth: 560, width: '90%', boxShadow: '0 24px 64px rgba(27,53,87,0.18)',
      }
    },
      React.createElement('div', { style: { marginBottom: 8, fontSize: 11, letterSpacing: 2, color: '#52C4A0', textTransform: 'uppercase', fontWeight: 700 } }, 'Welcome to TheDentist.ai'),
      React.createElement('h2', { style: { margin: '0 0 8px', fontSize: 26, fontWeight: 700, color: '#1B3557', lineHeight: 1.2 } }, 'Who are you?'),
      React.createElement('p', { style: { margin: '0 0 32px', color: '#64748B', fontSize: 14 } }, 'We\'ll personalize your experience based on your role.'),
      React.createElement('div', { style: { display: 'grid', gap: 12 } },
        roles.map(r =>
          React.createElement('button', {
            key: r.id,
            onClick: () => onSelect(r.id),
            style: {
              display: 'flex', alignItems: 'center', gap: 16,
              background: 'white', border: '1.5px solid #E2E8F0',
              borderRadius: 12, padding: '16px 20px',
              cursor: 'pointer', textAlign: 'left', width: '100%',
              transition: 'all 0.15s ease',
            },
            onMouseEnter: e => { e.currentTarget.style.borderColor = '#52C4A0'; e.currentTarget.style.background = '#F0FDF9'; },
            onMouseLeave: e => { e.currentTarget.style.borderColor = '#E2E8F0'; e.currentTarget.style.background = 'white'; },
          },
            window.FlatIcon
              ? React.createElement(window.FlatIcon, { name: r.icon, size: 28, color: '#52C4A0', style: { flexShrink: 0 } })
              : null,
            React.createElement('div', null,
              React.createElement('div', { style: { fontWeight: 600, color: '#1B3557', fontSize: 15, marginBottom: 2 } }, r.label),
              React.createElement('div', { style: { color: '#64748B', fontSize: 13 } }, r.desc),
            ),
            React.createElement('span', { style: { marginLeft: 'auto', color: '#CBD5E1', fontSize: 20 } }, '›'),
          )
        )
      ),
      React.createElement('p', {
        style: { marginTop: 20, textAlign: 'center', fontSize: 12, color: '#94A3B8', cursor: 'pointer' },
        onClick: () => onSelect('guest'),
      }, 'Skip — browse as a visitor'),
    )
  );
}

// ─── Return greeting helper ────────────────────────────────────────────────────
function getReturnGreeting(journey) {
  const { daysSinceLastVisit, patientCtx, proCtx, role } = journey;
  if (role === 'patient') {
    if (daysSinceLastVisit < 1) return 'Welcome back!';
    if (daysSinceLastVisit < 7) return `Good to see you again.`;
    if (daysSinceLastVisit < 30) return `It's been ${daysSinceLastVisit} days — welcome back.`;
    return `Been a while! Welcome back.`;
  }
  if (['dentist','front_desk','office_manager'].includes(role)) {
    return proCtx.practiceName ? `Welcome back, ${proCtx.practiceName}` : 'Welcome back to your practice portal.';
  }
  return 'Welcome back.';
}

// Expose globals
window.JourneyProvider = JourneyProvider;
window.useUserJourney = useUserJourney;
window.trackEvent = trackEvent;
window.RoleSelectorModal = RoleSelectorModal;
window.getReturnGreeting = getReturnGreeting;
window.JOURNEY_KEYS = KEYS;
window.ROLE_META = ROLE_META;
window.DEFAULT_LAYOUTS = DEFAULT_LAYOUTS;
