// training.jsx — In-app Training & Help view + first-login Welcome Tour.
//
// The Training view renders the team-training SOP as JSX (no markdown
// renderer dependency). The WelcomeTour shows once per user on first login;
// "seen" is persisted in localStorage keyed by uid so each teammate gets
// their own tour the first time they sign in on a device.

// ────────────────────────────── Welcome Tour ─────────────────────────────
const TOUR_SEEN_KEY = 'norwill-tour-seen-v1';

function tourSeenFor(uid) {
  try {
    const raw = JSON.parse(localStorage.getItem(TOUR_SEEN_KEY) || '{}');
    return !!raw[uid];
  } catch { return false; }
}

function markTourSeen(uid) {
  try {
    const raw = JSON.parse(localStorage.getItem(TOUR_SEEN_KEY) || '{}');
    raw[uid] = Date.now();
    localStorage.setItem(TOUR_SEEN_KEY, JSON.stringify(raw));
  } catch {}
}

function WelcomeTour({ authUser, onClose, onOpenTraining }) {
  const [step, setStep] = React.useState(0);
  const firstName = (authUser?.name || 'there').split(/\s+/)[0];

  const steps = [
    {
      title: 'Welcome, ' + firstName + ' 👋',
      eyebrow: 'Norwill Scorecard OS',
      body: (
        <React.Fragment>
          <p>This is the home for every number that runs Norwill — your daily metrics, weekly scorecard, quarterly Rocks, and the issues we IDS at the Friday Level 10.</p>
          <p>The whole flow takes <strong>under 60 seconds a day</strong>. Let's walk through it.</p>
        </React.Fragment>
      ),
    },
    {
      title: 'Enter your numbers',
      eyebrow: 'Step 1 of 4',
      body: (
        <React.Fragment>
          <p>Tap <strong>Metric Entry</strong> in the menu every weekday morning. The form opens on the tab that has metrics for you:</p>
          <ul>
            <li><strong>Today</strong> — daily metrics (defaults to yesterday).</li>
            <li><strong>This week</strong> — weekly metrics (Fri → Thu cycle).</li>
          </ul>
          <p>Type a number, tap out of the field, watch for the green <strong>saved ✓</strong>. That's it.</p>
        </React.Fragment>
      ),
    },
    {
      title: 'Track the team',
      eyebrow: 'Step 2 of 4',
      body: (
        <React.Fragment>
          <p>The <strong>13-Week Scorecard</strong> shows every metric the team owns, color-coded against target. The <strong>Rocks</strong> view shows our quarterly priorities and progress.</p>
          <p>If a number is red, you don't need to guess why — open an <strong>Issue</strong> and we'll IDS it Friday.</p>
        </React.Fragment>
      ),
    },
    {
      title: 'Need help? Stuck?',
      eyebrow: 'Step 3 of 4',
      body: (
        <React.Fragment>
          <p>Two things to remember:</p>
          <ul>
            <li><strong>Training</strong> in the menu has the full SOP — daily flow, weekly flow, troubleshooting. Bookmark it.</li>
            <li><strong>Send feedback</strong> in the sidebar goes straight to Dave + Olie. Use it the moment something is unclear.</li>
          </ul>
        </React.Fragment>
      ),
    },
    {
      title: 'You\'re ready',
      eyebrow: 'Step 4 of 4',
      body: (
        <React.Fragment>
          <p>Add the app to your phone's home screen so notifications and one-tap entry work the way they should.</p>
          <p>By Friday's Level 10, every row in your column should have a number. Let's go.</p>
        </React.Fragment>
      ),
    },
  ];

  const cur = steps[step];
  const isLast = step === steps.length - 1;

  const dismiss = () => {
    if (authUser?.uid) markTourSeen(authUser.uid);
    onClose();
  };

  const openTraining = () => {
    if (authUser?.uid) markTourSeen(authUser.uid);
    onClose();
    if (onOpenTraining) onOpenTraining();
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="welcome-tour-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(12, 20, 28, 0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
      }}
      onClick={(e) => { if (e.target === e.currentTarget) dismiss(); }}
    >
      <div
        className="slide-up"
        style={{
          width: '100%', maxWidth: 480,
          background: 'var(--surface-card)',
          borderRadius: 16, border: '1px solid var(--hairline)',
          boxShadow: '0 20px 60px rgba(0,0,0,0.25)',
          overflow: 'hidden', display: 'flex', flexDirection: 'column',
        }}
      >
        <div style={{
          padding: '20px 24px 4px',
          borderBottom: '1px solid var(--hairline)',
          background: 'linear-gradient(180deg, var(--forest-mist) 0%, var(--surface-card) 100%)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{
              fontSize: 10.5, letterSpacing: 0.1, textTransform: 'uppercase',
              color: 'var(--norwill-forest)', fontWeight: 700,
            }}>{cur.eyebrow}</span>
            <button
              onClick={dismiss}
              aria-label="Skip tour"
              style={{
                background: 'transparent', border: 'none',
                fontSize: 22, lineHeight: 1, color: 'var(--ink-500)',
                cursor: 'pointer', padding: 4,
              }}
            >×</button>
          </div>
          <h2 id="welcome-tour-title" style={{
            margin: 0, fontFamily: 'var(--font-display)',
            fontSize: 24, fontWeight: 600, letterSpacing: '-0.01em',
            color: 'var(--ink-900)', paddingBottom: 16,
          }}>{cur.title}</h2>
        </div>

        <div style={{
          padding: '18px 24px 8px', fontSize: 14.5, lineHeight: 1.6,
          color: 'var(--ink-700)',
        }}>
          {cur.body}
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '14px 24px 18px',
          borderTop: '1px solid var(--hairline)',
          background: 'var(--surface-sunk)',
        }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {steps.map((_, i) => (
              <span key={i} aria-hidden="true" style={{
                width: i === step ? 18 : 6, height: 6, borderRadius: 99,
                background: i === step ? 'var(--norwill-forest)' : 'var(--ink-200, rgba(0,0,0,0.18))',
                transition: 'width 180ms var(--ease-out, ease)',
              }}/>
            ))}
          </div>
          <span style={{ flex: 1 }}/>
          {step > 0 && (
            <button
              onClick={() => setStep(s => Math.max(0, s - 1))}
              style={btnGhost}
            >Back</button>
          )}
          {!isLast ? (
            <button onClick={() => setStep(s => s + 1)} style={btnPrimary}>Next</button>
          ) : (
            <React.Fragment>
              <button onClick={openTraining} style={btnGhost}>Open Training</button>
              <button onClick={dismiss} style={btnPrimary}>Get started</button>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

const btnPrimary = {
  padding: '8px 16px', borderRadius: 8,
  border: '1px solid var(--norwill-forest)',
  background: 'var(--norwill-forest)', color: '#fff',
  fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
};

const btnGhost = {
  padding: '8px 14px', borderRadius: 8,
  border: '1px solid var(--hairline)',
  background: 'var(--surface-card)', color: 'var(--ink-700)',
  fontSize: 13, fontWeight: 600, cursor: 'pointer',
};

// ─────────────────────────────── Training View ───────────────────────────
function Training({ persona, authUser, onReplayTour }) {
  const sections = [
    {
      id: 'setup', title: '1. One-time setup',
      lead: 'Do this once, on your phone. Takes 2 minutes.',
      items: [
        'Open the Scorecard URL in Safari (iPhone) or Chrome (Android).',
        'Sign in with your Norwill email + the password you set from the welcome link.',
        'Add to home screen — iPhone: Share → Add to Home Screen. Android: ⋮ → Add to home screen.',
        'Open the app from the home-screen icon. It now behaves like a real app.',
        'Allow notifications when prompted — that\'s how the 7:00 AM reminder gets to you.',
      ],
    },
    {
      id: 'daily', title: '2. Your daily flow',
      lead: 'Mon–Fri, takes under 60 seconds. The rule: enter yesterday\'s numbers before the 9 AM huddle.',
      items: [
        'Open the Scorecard from your home screen.',
        'Tap Metric Entry (or the "Enter numbers" button on My Scorecard).',
        'The form opens on the tab that has metrics for you (Today or This week).',
        'Today defaults to yesterday\'s date. That\'s the day we report on.',
        'Tap into each row, type the number, tap out (or hit Enter).',
        'Wait for the green "saved ✓" chip on each row. That\'s your confirmation.',
        'Done. Close the app.',
      ],
    },
    {
      id: 'weekly', title: '3. Your weekly flow',
      lead: 'Some metrics are weekly only — chart audit %, on-time documentation %, fill rate, hours, etc. Cycle ends Thursday.',
      items: [
        'Thursday afternoon: open Metric Entry.',
        'Tap the "This week" tab.',
        'Enter every weekly number for your function.',
        'Confirm each row shows "saved ✓".',
        'Missed Thursday? Friday morning works too — change the date picker to any day in that week.',
      ],
    },
    {
      id: 'backfill', title: '4. Backfilling',
      lead: 'Caught up at end of week, or out sick? You can still enter past numbers.',
      items: [
        'Open Metric Entry on the right tab.',
        'Change the date picker at the top of the form to the day (or week) you missed.',
        'Enter as normal. Re-entering overwrites whatever was there.',
      ],
    },
  ];

  const trouble = [
    ['Form says "you don\'t have any daily metrics"', 'Tap "Switch to weekly metrics →". Your role enters numbers weekly, not daily (that\'s normal — Olie is weekly-only).'],
    ['I entered the wrong number', 'Type the correct one in the same row and tap out. It overwrites the old value.'],
    ['I don\'t see a metric I expect to own', 'Tell Dave or Olie. They can reassign ownership in the Metrics Map view in 30 seconds.'],
    ['Page is showing a stale number', 'Pull down to refresh, or close and reopen the app.'],
    ['Something feels broken or confusing', 'Tap "Send feedback" in the sidebar. Dave + Olie see every message and reply in-app.'],
  ];

  const scrollTo = (id) => {
    const el = document.getElementById('train-' + id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div style={{ padding: 28, maxWidth: 920 }}>
      {/* Header --------------------------------------------------------- */}
      <div style={{ marginBottom: 22 }}>
        <div className="eyebrow" style={{ fontSize: 10.5 }}>Training & Help</div>
        <h2 style={{
          margin: '4px 0 4px', fontFamily: 'var(--font-display)',
          fontSize: 26, fontWeight: 600, letterSpacing: '-0.01em',
          color: 'var(--ink-900)',
        }}>How to use the Norwill Scorecard</h2>
        <div style={{ color: 'var(--ink-600)', fontSize: 13.5, maxWidth: 640, lineHeight: 1.55 }}>
          Everything you need to enter numbers, find your metrics, and keep
          the team's scorecard accurate. Bookmark this page — it's the same
          SOP we train every new teammate on.
        </div>
        {onReplayTour && (
          <button
            onClick={onReplayTour}
            className="btn btn-ghost btn-sm"
            style={{ marginTop: 12 }}
          >Replay welcome tour</button>
        )}
      </div>

      {/* Quick links ---------------------------------------------------- */}
      <div className="card" style={{
        padding: '14px 18px', marginBottom: 22,
        background: 'var(--forest-mist)',
        border: '1px solid rgba(53, 94, 44, 0.14)',
      }}>
        <div className="eyebrow" style={{ color: 'var(--norwill-forest)', marginBottom: 8 }}>Jump to</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {sections.map(s => (
            <button key={s.id} onClick={() => scrollTo(s.id)} style={chipBtn}>{s.title}</button>
          ))}
          <button onClick={() => scrollTo('trouble')} style={chipBtn}>Troubleshooting</button>
          <button onClick={() => scrollTo('rules')} style={chipBtn}>The non-negotiables</button>
        </div>
      </div>

      {/* Sections ------------------------------------------------------- */}
      {sections.map(sec => (
        <section key={sec.id} id={'train-' + sec.id} style={sectionStyle}>
          <h3 style={sectionTitleStyle}>{sec.title}</h3>
          <div style={leadStyle}>{sec.lead}</div>
          <ol style={listStyle}>
            {sec.items.map((it, i) => <li key={i} style={liStyle}>{it}</li>)}
          </ol>
        </section>
      ))}

      {/* Troubleshooting ------------------------------------------------ */}
      <section id="train-trouble" style={sectionStyle}>
        <h3 style={sectionTitleStyle}>5. Troubleshooting</h3>
        <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
            <thead>
              <tr style={{ background: 'var(--surface-sunk)', borderBottom: '1px solid var(--hairline)' }}>
                <th style={thStyle}>Situation</th>
                <th style={thStyle}>What to do</th>
              </tr>
            </thead>
            <tbody>
              {trouble.map((row, i) => (
                <tr key={i} style={{ borderBottom: i === trouble.length - 1 ? 'none' : '1px solid var(--hairline)' }}>
                  <td style={tdStyle}><strong>{row[0]}</strong></td>
                  <td style={tdStyle}>{row[1]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {/* Friday L10 ----------------------------------------------------- */}
      <section style={sectionStyle}>
        <h3 style={sectionTitleStyle}>6. The Friday Level 10 — what your numbers feed</h3>
        <div style={leadStyle}>
          The Scorecard view replaces the spreadsheet pre-work. Every Friday at the L10, the team scrolls through:
        </div>
        <ol style={listStyle}>
          <li style={liStyle}><strong>Scorecard</strong> — every metric you entered this week, color-coded against target.</li>
          <li style={liStyle}><strong>Rocks</strong> — quarterly priorities, with owners and progress.</li>
          <li style={liStyle}><strong>Issues</strong> — anything that needs to be solved this week (logged in-app, persists across weeks).</li>
        </ol>
        <div style={{ ...leadStyle, marginTop: 8, fontStyle: 'italic' }}>
          If your numbers aren't entered, your row shows blanks and the team has to ask. Don't be the blank row.
        </div>
      </section>

      {/* Non-negotiables ------------------------------------------------ */}
      <section id="train-rules" style={sectionStyle}>
        <h3 style={sectionTitleStyle}>7. The non-negotiables</h3>
        <ol style={listStyle}>
          <li style={liStyle}>Enter numbers every workday before 9 AM. It's a 60-second habit.</li>
          <li style={liStyle}>Backfill within the same week. Don't let gaps pile up.</li>
          <li style={liStyle}>Tap "Send feedback" the moment anything is unclear. Faster than texting.</li>
          <li style={liStyle}>Keep the app on your home screen. No icon = no notifications = forgotten entries.</li>
        </ol>
      </section>

      <div style={{ marginTop: 24, padding: '14px 16px', background: 'var(--surface-sunk)', borderRadius: 10, fontSize: 12, color: 'var(--ink-500)' }}>
        Last updated 2026-05-01. The full markdown version lives at <code>docs/team-training-sop.md</code> in the repo.
      </div>
    </div>
  );
}

const sectionStyle = {
  marginBottom: 26, paddingTop: 8,
};
const sectionTitleStyle = {
  margin: '0 0 6px', fontFamily: 'var(--font-display)',
  fontSize: 18.5, fontWeight: 600, letterSpacing: '-0.01em',
  color: 'var(--ink-900)',
};
const leadStyle = {
  fontSize: 13.5, color: 'var(--ink-600)',
  lineHeight: 1.55, marginBottom: 10, maxWidth: 720,
};
const listStyle = { paddingLeft: 22, margin: 0 };
const liStyle = {
  fontSize: 14, color: 'var(--ink-800)',
  lineHeight: 1.6, marginBottom: 4,
};
const thStyle = {
  textAlign: 'left', padding: '10px 14px',
  fontSize: 11.5, color: 'var(--ink-600)',
  fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.04,
};
const tdStyle = {
  padding: '12px 14px', verticalAlign: 'top',
  fontSize: 13.5, color: 'var(--ink-700)', lineHeight: 1.55,
};
const chipBtn = {
  padding: '6px 12px', borderRadius: 99,
  border: '1px solid rgba(53, 94, 44, 0.22)',
  background: 'var(--surface-card)', color: 'var(--norwill-forest)',
  fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
};

Object.assign(window, { Training, WelcomeTour, tourSeenFor, markTourSeen, TOUR_SEEN_KEY });
