// Member dashboard — AI-reviewed (no clinician language). No "protocol" word.

const Dashboard = ({ track, contact, vials, providerSupport, checkoutHydration, onLogout, onTelehealth, onVerify }) => {
  const trackInfo = CATEGORIES.find(t => t.id === track) || CATEGORIES[0];
  const [memberProfile, setMemberProfile] = React.useState(null);
  const [profileLoaded, setProfileLoaded] = React.useState(false);
  const [savingPreference, setSavingPreference] = React.useState(false);
  const [preferenceMessage, setPreferenceMessage] = React.useState('');
  React.useEffect(() => {
    let alive = true;
    fetch('/api/site/member')
      .then((res) => res.ok ? res.json() : null)
      .then((data) => {
        if (!alive || !data) return;
        setMemberProfile(data);
      })
      .catch(() => {})
      .finally(() => {
        if (alive) setProfileLoaded(true);
      });
    return () => { alive = false; };
  }, []);

  const memberUser = memberProfile?.user || null;
  const latestOrder = memberProfile?.latest_order || null;
  const subscription = memberProfile?.subscription || null;
  const preferences = memberProfile?.preferences || null;
  const vialList = vials && vials.length ? vials : [{ id: 'primary', name: `Primary peptide · ${trackInfo.name.toLowerCase()}` }];
  const activePlan = preferences?.peptidePlan || vialList[0] && {
    id: vialList[0].planId || (vialList.length === 3 ? 'full' : vialList.length === 2 ? 'paired' : 'solo'),
    slots: vialList[0].planSlots || vialList.length,
    price: vialList[0].planPrice || (vialList.length === 3 ? 877 : vialList.length === 2 ? 578 : 299),
    name: `${vialList[0].planSlots || vialList.length} peptide plan`,
  };
  const activeSupport = preferences?.providerSupport || providerSupport || null;
  const reviewStatus = memberProfile?.compliance?.status || latestOrder?.status || 'Not submitted';
  const verificationComplete = ['verified', 'approved', 'cleared', 'active'].includes(String(reviewStatus).toLowerCase());
  const [planDraft, setPlanDraft] = React.useState(activePlan);
  const [supportDraft, setSupportDraft] = React.useState(activeSupport || { id: 'none', tier: 'none', price: 0, name: 'Not now' });
  React.useEffect(() => {
    if (activePlan) setPlanDraft(activePlan);
    if (activeSupport) setSupportDraft(activeSupport);
  }, [activePlan?.id, activeSupport?.id]);
  const monthly = latestOrder?.total_cents ? Math.round(Number(latestOrder.total_cents) / 100) : (vialList[0]?.planPrice || (vialList.length === 3 ? 877 : vialList.length === 2 ? 578 : 299));
  const displayName = memberUser?.name || contact?.legalName || 'Member';
  const displayEmail = memberUser?.email || contact?.email || '';
  const displayPhone = memberUser?.phone || contact?.phone || '';
  const fname = (displayName || 'Member').split(' ')[0] || 'Member';
  const memberKey = React.useMemo(() => {
    const seed = (displayEmail || displayPhone || displayName || 'member').toLowerCase();
    let hash = 0;
    for (let i = 0; i < seed.length; i += 1) hash = ((hash << 5) - hash + seed.charCodeAt(i)) >>> 0;
    return String(hash % 1000000000).padStart(9, '0');
  }, [displayEmail, displayName, displayPhone]);
  const [activeTab, setActiveTab] = React.useState('overview');
  const savePreferences = async () => {
    setSavingPreference(true);
    setPreferenceMessage('');
    try {
      const res = await fetch('/api/site/member-preferences', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ peptidePlan: planDraft, providerSupport: supportDraft }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Could not save changes');
      setMemberProfile((current) => ({ ...(current || {}), preferences: data.preferences }));
      setPreferenceMessage('Saved to your member record.');
    } catch (err) {
      setPreferenceMessage(err instanceof Error ? err.message : 'Could not save changes');
    } finally {
      setSavingPreference(false);
    }
  };
  const timelineRows = [
    { date: 'ACTIVE', title: 'Membership activated', tag: 'CURRENT', tagClass: 'now', body: 'Your account, assessment, and selected plan are connected.' },
    { date: 'VERIFY', title: 'Verification', body: 'Upload ID and video so fulfillment can move through review.' },
    { date: 'REVIEW', title: 'Assessment review', body: 'Your answers, selected vials, and verification stay together on your member record.' },
    { date: 'SHIP', title: 'Fulfillment', tag: 'COLD-CHAIN', tagClass: 'ship', body: `${vialList.map(v => v.name).join(' + ')}, prepared after review clears.` },
  ];

  return (
    <div className="shell">
      <nav className="nav">
        <div className="nav-inner">
          <Logo size={20} asLink />
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>
            MEMBER · ACTIVE
          </div>
          <div className="nav-cta">
            <span className="mono" style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{fname} · {trackInfo.name}</span>
            <button className="btn btn-soft btn-sm" onClick={onLogout}>Log out</button>
          </div>
        </div>
      </nav>

      <div className="dash">
        <aside className="dash-side">
          {[
            { id: 'overview', label: 'Overview' },
            { id: 'profile', label: 'Profile' },
            { id: 'plan', label: 'My plan', badge: 'NEW' },
            { id: 'shipments', label: 'Shipments' },
            { id: 'messages', label: 'Messages', badge: '1' },
            { id: 'verification', label: 'Verification', isAction: true },
            { id: 'telehealth', label: 'Provider on call', isAction: true },
            { id: 'billing', label: 'Billing' },
            { id: 'library', label: 'Library' },
          ].map(it => (
            <button
              key={it.id}
              className={`dash-side-link ${activeTab === it.id ? 'is-active' : ''}`}
              onClick={() => {
                if (it.isAction && it.id === 'verification' && onVerify) {
                  onVerify();
                  return;
                }
                if (it.isAction && it.id === 'telehealth' && onTelehealth) {
                  onTelehealth();
                } else {
                  setActiveTab(it.id);
                }
              }}
            >
              <span>{it.label}</span>
              {it.badge && <span className="badge">{it.badge}</span>}
            </button>
          ))}
        </aside>

        <main className="dash-main">
          {checkoutHydration?.status === 'loading' && (
            <div className="dash-notice">Loading your checkout...</div>
          )}
          {checkoutHydration?.status === 'pending' && (
            <div className="dash-notice">Payment received. Your member record is being prepared.</div>
          )}
          {checkoutHydration?.status === 'ready' && (
            <div className="dash-notice">Payment received. Your member record is active.</div>
          )}
          {checkoutHydration?.status === 'error' && (
            <div className="dash-notice is-error">{checkoutHydration.error}</div>
          )}
          <div className="dash-hero">
            <div>
              <div className="dash-hero-eyebrow">— MEMBER ACCOUNT · ACTIVE</div>
              <h1>
                Welcome in, {fname}.<br />
                You are <em>never undertreated</em> here.
              </h1>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', color: 'rgba(244,237,228,0.6)', textTransform: 'uppercase', marginBottom: 8 }}>YOUR VIALS</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
                {vialList.map(v => (
                  <div key={v.id} className="serif" style={{ fontSize: 18, lineHeight: 1.2, letterSpacing: '-0.01em' }}>{v.name}</div>
                ))}
              </div>
              <button className="btn" style={{ background: 'var(--bg)', color: 'var(--ink)' }} onClick={() => setActiveTab('plan')}>
                View plan details →
              </button>
            </div>
          </div>

          {activeTab === 'overview' && (
            <>
              <div className="dash-grid">
                <div className="dash-card">
                  <h3>Next shipment</h3>
                  <div className="stat serif"><em>Pending</em></div>
                  <div className="meta">Cold-chain fulfillment begins after review clears.</div>
                </div>
                <div className="dash-card">
                  <h3>Verification</h3>
                  <div className="stat serif">{verificationComplete ? <em>Done</em> : <em>Needed</em>}</div>
                  <div className="meta">{verificationComplete ? 'Your verification is on file.' : 'Finish ID and video before fulfillment.'}</div>
                  {!verificationComplete && (
                    <button className="btn btn-soft btn-sm" onClick={onVerify} style={{ marginTop: 14 }}>
                      Start verification →
                    </button>
                  )}
                </div>
                <div className="dash-card">
                  <h3>Membership</h3>
                  <div className="stat serif">$<em>{monthly}</em><span style={{ fontSize: 18, color: 'var(--ink-mute)', fontFamily: 'JetBrains Mono', marginLeft: 8 }}>/MO</span></div>
                  <div className="meta">{subscription?.care_tier && subscription.care_tier !== 'none' ? 'Provider care active' : `${vialList.length} vial${vialList.length > 1 ? 's' : ''}`} · {profileLoaded ? 'member record loaded' : 'loading member record'}</div>
                </div>
                <div className="dash-card dash-card-cta" onClick={() => onTelehealth && onTelehealth()} style={{ cursor: 'pointer' }}>
                  <h3>Provider on call</h3>
                  <div className="stat serif">Open <em>care</em></div>
                  <div className="meta">Provider care rooms and private support when your tier includes it →</div>
                </div>
                <div className="dash-card">
                  <h3>Category</h3>
                  <div className="stat serif"><em>{trackInfo.name}</em></div>
                  <div className="meta">{vialList.length} vial{vialList.length > 1 ? 's' : ''} active</div>
                </div>
              </div>
              <DashboardTimeline rows={timelineRows} />
            </>
          )}

          {activeTab === 'plan' && (
            <DashboardPanel eyebrow={`${trackInfo.name} · active membership`} title="My plan">
              <div className="dash-detail-grid">
                {vialList.map((v, i) => (
                  <div key={v.id} className="dash-detail-card">
                    <h3>{i === 0 ? 'Primary vial' : 'Companion vial'}</h3>
                    <div className="dash-detail-title serif">{v.name}</div>
                    <p>Compounded for your current {trackInfo.name.toLowerCase()} goal. Dose notes and refill guidance appear here after review.</p>
                  </div>
                ))}
                <div className="dash-detail-card">
                  <h3>Monthly total</h3>
                  <div className="dash-detail-price serif">${monthly}<span>/mo</span></div>
                  <p>Includes cold-chain shipping, COA, member library, and check-ins.</p>
                </div>
              </div>
              <PlanControls
                planDraft={planDraft}
                supportDraft={supportDraft}
                onPlan={setPlanDraft}
                onSupport={setSupportDraft}
                onSave={savePreferences}
                saving={savingPreference}
                message={preferenceMessage}
              />
            </DashboardPanel>
          )}

          {activeTab === 'profile' && (
            <DashboardPanel eyebrow="Member record" title="Profile">
              <div className="account-card">
                <div className="account-row">
                  <div>
                    <div className="account-label">Member ID</div>
                    <div className="account-value">{memberKey}</div>
                  </div>
                </div>
                <div className="account-row">
                  <div>
                    <div className="account-label">Name</div>
                    <div className="account-value">{displayName || 'Member'}</div>
                  </div>
                </div>
                <div className="account-row">
                  <div>
                    <div className="account-label">Email</div>
                    <div className="account-value">{displayEmail || 'Not added yet'}</div>
                  </div>
                </div>
                <div className="account-row">
                  <div>
                    <div className="account-label">Phone</div>
                    <div className="account-value">{displayPhone || 'Not added yet'}</div>
                  </div>
                </div>
                <div className="account-row">
                  <div>
                    <div className="account-label">Linked access</div>
                    <div className="account-value">{subscription?.care_tier && subscription.care_tier !== 'none' ? 'Peptides · Provider care · Verification' : 'Peptides · Verification'}</div>
                  </div>
                </div>
                <div className="account-row">
                  <div>
                    <div className="account-label">Review status</div>
                    <div className="account-value">{reviewStatus}</div>
                  </div>
                </div>
              </div>
            </DashboardPanel>
          )}

          {activeTab === 'shipments' && (
            <DashboardPanel eyebrow="Cold-chain tracking" title="Shipments">
              <DashboardTimeline rows={[
                { date: 'REVIEW', title: 'Shipment preparing', tag: 'NEXT', tagClass: 'ship', body: 'Your first box is queued for fulfillment once review clears.' },
                { date: 'TRACK', title: 'Tracking appears here', body: 'Carrier, tracking number, delivery status, and COA download will live in this panel.' },
                { date: 'DELIVER', title: 'Delivery confirmation', body: 'We ask for a quick confirmation so your refill record stays accurate.' },
              ]} />
            </DashboardPanel>
          )}

          {activeTab === 'messages' && (
            <DashboardPanel eyebrow="1 unread" title="Messages">
              <div className="dash-message">
                <div className="dash-message-top">
                  <strong>Assessment review</strong>
                  <span className="mono">TODAY · 9:14 AM</span>
                </div>
                <p>Your assessment is in review. If anything needs clarification, you will see the question here before your first shipment is released.</p>
                <textarea className="dash-reply" placeholder="Write a reply..." />
                <button className="btn btn-primary">Send reply</button>
              </div>
            </DashboardPanel>
          )}

          {activeTab === 'billing' && (
            <DashboardPanel eyebrow="Membership billing" title="Billing">
              <div className="dash-detail-grid">
                <div className="dash-detail-card">
                  <h3>Next bill</h3>
                  <div className="dash-detail-title serif">26 May</div>
                  <p>${monthly}.00 for {vialList.length} active vial{vialList.length > 1 ? 's' : ''}.</p>
                </div>
                <div className="dash-detail-card">
                  <h3>Payment method</h3>
                  <div className="dash-detail-title serif">Card ending 4242</div>
                  <p>Update, pause, or cancel from this panel before the next refill.</p>
                </div>
              </div>
            </DashboardPanel>
          )}

          {activeTab === 'library' && (
            <DashboardPanel eyebrow="Member resources" title="Library">
              <div className="dash-library">
                {['How to store your vial', 'How to prepare for review', 'Reading your COA', 'When to message the care team'].map(item => (
                  <button key={item} className="dash-library-row">
                    <span>{item}</span>
                    <span>Read →</span>
                  </button>
                ))}
              </div>
            </DashboardPanel>
          )}
        </main>
      </div>
    </div>
  );
};

const DashboardPanel = ({ eyebrow, title, children }) => (
  <section className="dash-panel">
    <div className="dash-panel-head">
      <div className="dash-hero-eyebrow">{eyebrow}</div>
      <h2 className="serif">{title}</h2>
    </div>
    {children}
  </section>
);

const PlanControls = ({ planDraft, supportDraft, onPlan, onSupport, onSave, saving, message }) => {
  const plans = window.PLAN_OPTIONS || [
    { id: 'solo', slots: 1, price: 299, name: '1 peptide plan' },
    { id: 'paired', slots: 2, price: 578, name: '2 peptide plan' },
    { id: 'full', slots: 3, price: 877, name: '3 peptide plan' },
  ];
  const support = window.SUPPORT_OPTIONS || [
    { id: 'none', tier: 'none', price: 0, name: 'Not now' },
    { id: 'monthly-care', tier: 'group_monthly', price: 129, name: 'Provider care rooms' },
    { id: 'twice-care', tier: 'group_twice_monthly', price: 199, name: 'Provider care rooms plus' },
    { id: 'direct-support', tier: 'private_access', price: 299, name: 'Provider care rooms + 1:1' },
  ];

  return (
    <div className="dash-plan-controls">
      <div>
        <div className="account-label">Peptides</div>
        <div className="dash-choice-row">
          {plans.map((plan) => (
            <button
              key={plan.id}
              className={`dash-pill ${planDraft?.id === plan.id ? 'is-active' : ''}`}
              onClick={() => onPlan(plan)}
            >
              {plan.slots}
            </button>
          ))}
        </div>
      </div>
      <div>
        <div className="account-label">Provider support</div>
        <div className="dash-support-list">
          {support.map((item) => (
            <button
              key={item.id}
              className={`dash-support-choice ${supportDraft?.id === item.id ? 'is-active' : ''}`}
              onClick={() => onSupport(item)}
            >
              <span>{item.name}</span>
              <span>{item.price ? `$${item.price}/mo` : '$0'}</span>
            </button>
          ))}
        </div>
      </div>
      <button className="btn btn-primary" onClick={onSave} disabled={saving}>
        {saving ? 'Saving...' : 'Save changes'}
      </button>
      {message && <div className="dash-pref-message">{message}</div>}
    </div>
  );
};

const DashboardTimeline = ({ rows }) => (
  <div className="dash-timeline">
    <h2 className="serif">Your timeline.</h2>
    {rows.map((row) => (
      <div className="timeline-item" key={`${row.date}-${row.title}`}>
        <span className="timeline-date">{row.date}</span>
        <div className="timeline-body">
          <strong>
            {row.title}
            {row.tag && <span className={`timeline-tag ${row.tagClass || ''}`}>{row.tag}</span>}
          </strong>
          <p>{row.body}</p>
        </div>
      </div>
    ))}
  </div>
);

Object.assign(window, { Dashboard });
