// 3-screen onboarding flow shown on first sign-in.
//
// Screen 1: Welcome — set the tone, explain what this is.
// Screen 2: Connect sources — checklist of data sources (mock connections).
//           Clicking "Connect" simulates an OAuth round-trip and flips the
//           pill to "Connected" with a green check.
// Screen 3: Customize — let Clemmie pick which KPIs/charts to feature on
//           the landing tab. Defaults selected.
// "Skip for now" is available on each screen; landing always uses the
// defaults if skipped.

const { useState: obState, useEffect: obEffect } = React;

const OB_SOURCES = [
  { id: 'membership_db', name: 'Member Database',  icon: 'Users',     why: 'Active members, tiers, renewals.' },
  { id: 'ga4',           name: 'Google Analytics 4', icon: 'BarChart3', why: 'Site traffic + conversion paths.' },
  { id: 'gsc',           name: 'Search Console',     icon: 'Search',    why: 'Organic search queries + impressions.' },
  { id: 'linkedin',      name: 'LinkedIn',           icon: 'Linkedin',  why: 'Organic + paid social engagement.' },
  { id: 'meta',          name: 'Meta',               icon: 'Facebook',  why: 'Organic + paid social engagement.' },
  { id: 'mailchimp',     name: 'Email Platform',     icon: 'Mail',      why: 'Sends, opens, clicks, unsubs.' },
  { id: 'cap_events',    name: 'CAP Events',         icon: 'Calendar',  why: 'Annual Meeting + HOD attendance.' },
  { id: 'cme',           name: 'CME Credit System',  icon: 'GraduationCap', why: 'Member engagement signal.' },
];

const OB_FEATURED = [
  { id: 'membership_growth',  label: 'Membership growth (new vs. churn)', defaultOn: true },
  { id: 'tier_breakdown',     label: 'Tier breakdown (Fellow / Resident / etc.)', defaultOn: true },
  { id: 'acquisition_channels', label: 'New-member acquisition channels',  defaultOn: true },
  { id: 'member_journey',     label: 'Member journey funnel',              defaultOn: true },
  { id: 'engagement',         label: 'Engagement breakdown',               defaultOn: true },
  { id: 'churn_risk',         label: 'Churn risk cohorts',                 defaultOn: false },
  { id: 'geo',                label: 'Geographic distribution',            defaultOn: false },
  { id: 'revenue',            label: 'Annual dues revenue',                defaultOn: false },
];

function CapOnboarding({ user, onComplete, pushToast }) {
  const [step, setStep] = obState(0);
  const [connected, setConnected] = obState({});
  const [connecting, setConnecting] = obState(null);
  const [featured, setFeatured] = obState(() => {
    const init = {};
    OB_FEATURED.forEach((f) => { init[f.id] = f.defaultOn; });
    return init;
  });

  function connectSource(id) {
    if (connected[id] || connecting) return;
    setConnecting(id);
    // Simulate OAuth round-trip.
    setTimeout(() => {
      setConnected((c) => ({ ...c, [id]: true }));
      setConnecting(null);
      const src = OB_SOURCES.find((s) => s.id === id);
      pushToast && pushToast(`Connected to ${src?.name || id}.`, 'success');
    }, 900);
  }

  function toggleFeatured(id) {
    setFeatured((f) => ({ ...f, [id]: !f[id] }));
  }

  function connectAll() {
    OB_SOURCES.forEach((s, i) => {
      setTimeout(() => {
        setConnecting(s.id);
        setTimeout(() => {
          setConnected((c) => ({ ...c, [s.id]: true }));
          setConnecting(null);
        }, 350);
      }, i * 180);
    });
  }

  return (
    <div className="ob-wrap">
      <div className="ob-card">
        {/* Progress rail */}
        <div className="ob-progress">
          {[0, 1, 2].map((i) => (
            <div key={i} className={`ob-step-dot ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`} />
          ))}
        </div>

        {step === 0 && (
          <ObWelcome user={user} onNext={() => setStep(1)} onSkip={onComplete} />
        )}
        {step === 1 && (
          <ObConnect
            connected={connected}
            connecting={connecting}
            onConnect={connectSource}
            onConnectAll={connectAll}
            onBack={() => setStep(0)}
            onNext={() => setStep(2)}
            onSkip={onComplete}
          />
        )}
        {step === 2 && (
          <ObCustomize
            featured={featured}
            onToggle={toggleFeatured}
            onBack={() => setStep(1)}
            onComplete={onComplete}
          />
        )}
      </div>
    </div>
  );
}
window.CapOnboarding = CapOnboarding;

function ObWelcome({ user, onNext, onSkip }) {
  const firstName = (user?.name || '').split(' ')[0] || 'there';
  return (
    <div className="ob-content">
      <div className="ob-eyebrow">Welcome</div>
      <h1 className="ob-title">
        Hi <span style={{ color: 'var(--brand-red)', fontStyle: 'italic', textTransform: 'none' }}>{firstName}</span>.<br/>
        Let's set up your dashboard.
      </h1>
      <p className="ob-body">
        This is a private preview of the membership dashboard Rottman Creative is
        building for the College of American Pathologists. In about a minute we'll
        walk through which data sources to plug in and which views to feature.
      </p>
      <p className="ob-body" style={{ color: 'var(--ink-stone)', fontSize: 13 }}>
        Everything you see is illustrative for now — once we connect real systems,
        the same charts populate with live numbers automatically.
      </p>
      <div className="ob-actions">
        <button className="tlink" onClick={onSkip} style={{ fontSize: 12 }}>Skip for now</button>
        <Pill variant="filled" onClick={onNext} style={{ minHeight: 40 }}>
          Get started →
        </Pill>
      </div>
    </div>
  );
}

function ObConnect({ connected, connecting, onConnect, onConnectAll, onBack, onNext, onSkip }) {
  const totalConnected = Object.values(connected).filter(Boolean).length;
  return (
    <div className="ob-content">
      <div className="ob-eyebrow">Step 2 of 3 · Connect sources</div>
      <h1 className="ob-title">
        Which systems should we <span style={{ color: 'var(--brand-red)', fontStyle: 'italic', textTransform: 'none' }}>pull from</span>?
      </h1>
      <p className="ob-body">
        Click each tile to authorize. Don't worry about getting them all today —
        Rottman Creative will help you connect the rest before the diagnostic
        report drops at end of Month 3.
      </p>

      <div className="ob-source-grid">
        {OB_SOURCES.map((s) => {
          const isConnected = !!connected[s.id];
          const isLoading = connecting === s.id;
          return (
            <button key={s.id}
              className={`ob-source ${isConnected ? 'connected' : ''} ${isLoading ? 'loading' : ''}`}
              onClick={() => onConnect(s.id)}
              disabled={isConnected || isLoading}>
              <div className="ob-source-icon">
                <Icon name={s.icon} size={18} />
              </div>
              <div className="ob-source-body">
                <div className="ob-source-name">{s.name}</div>
                <div className="ob-source-why">{s.why}</div>
              </div>
              <div className="ob-source-status">
                {isConnected ? (
                  <span className="ob-status-connected"><Icon name="Check" size={12} /> Connected</span>
                ) : isLoading ? (
                  <span className="ob-status-loading">Connecting…</span>
                ) : (
                  <span className="ob-status-cta">Connect</span>
                )}
              </div>
            </button>
          );
        })}
      </div>

      <div className="ob-actions">
        <button className="tlink" onClick={onBack} style={{ fontSize: 12 }}>← Back</button>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <button className="tlink" onClick={onConnectAll} style={{ fontSize: 12 }}>
            Connect all (demo)
          </button>
          <button className="tlink" onClick={onSkip} style={{ fontSize: 12 }}>Skip</button>
          <Pill variant="filled" onClick={onNext} style={{ minHeight: 40 }}>
            {totalConnected > 0 ? `Continue (${totalConnected} connected) →` : 'Continue →'}
          </Pill>
        </div>
      </div>
    </div>
  );
}

function ObCustomize({ featured, onToggle, onBack, onComplete }) {
  const onCount = Object.values(featured).filter(Boolean).length;
  return (
    <div className="ob-content">
      <div className="ob-eyebrow">Step 3 of 3 · Featured views</div>
      <h1 className="ob-title">
        What do you want <span style={{ color: 'var(--brand-red)', fontStyle: 'italic', textTransform: 'none' }}>front and center</span>?
      </h1>
      <p className="ob-body">
        Pick which cards land on your Membership view. You can change this any
        time from Settings. Defaults are tuned for what we think you'll want
        first; tap any to toggle.
      </p>

      <div className="ob-feature-grid">
        {OB_FEATURED.map((f) => {
          const on = !!featured[f.id];
          return (
            <button key={f.id} className={`ob-feature ${on ? 'on' : ''}`} onClick={() => onToggle(f.id)}>
              <Icon name={on ? 'CheckSquare' : 'Square'} size={14} />
              <span>{f.label}</span>
            </button>
          );
        })}
      </div>

      <div className="ob-actions">
        <button className="tlink" onClick={onBack} style={{ fontSize: 12 }}>← Back</button>
        <Pill variant="filled" onClick={onComplete} style={{ minHeight: 40 }}>
          Open my dashboard →
        </Pill>
      </div>
    </div>
  );
}
