/* maydays — account system + comments
   Prototype: accounts persist via localStorage (no real backend). */

const { useState: _aus, useEffect: _aue, useRef: _aur } = React;

const ACCT_USERS_KEY   = 'mayday_users_v1';
const ACCT_CURRENT_KEY = 'mayday_current_user_v1';
const COMMENTS_KEY     = 'mayday_comments_v1';

function _readJSON(key, fallback) {
  try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fallback; }
  catch (e) { return fallback; }
}
function _writeJSON(key, val) { try { localStorage.setItem(key, JSON.stringify(val)); } catch (e) {} }

/* ----- user list ----- */
function _listUsers() { return _readJSON(ACCT_USERS_KEY, []); }
function _saveUsers(arr) { _writeJSON(ACCT_USERS_KEY, arr); }
function _getCurrentUserId() {
  try { return localStorage.getItem(ACCT_CURRENT_KEY); } catch (e) { return null; }
}
function _setCurrentUserId(id) {
  if (id) localStorage.setItem(ACCT_CURRENT_KEY, id);
  else localStorage.removeItem(ACCT_CURRENT_KEY);
  window.dispatchEvent(new Event('mayday-auth-change'));
}
function getCurrentUser() {
  const id = _getCurrentUserId();
  if (!id) return null;
  return _listUsers().find(u => u.id === id) || null;
}

function useAccount() {
  const [user, setUser] = _aus(getCurrentUser());
  _aue(() => {
    const onChange = () => setUser(getCurrentUser());
    window.addEventListener('mayday-auth-change', onChange);
    return () => window.removeEventListener('mayday-auth-change', onChange);
  }, []);
  return user;
}

function signUp({ name, email, password }) {
  if (!name || !email || !password) throw new Error('All fields are required.');
  if (password.length < 4) throw new Error('Pick a password of at least 4 characters.');
  const users = _listUsers();
  if (users.find(u => u.email.toLowerCase() === email.toLowerCase())) {
    throw new Error('An account with that email already exists.');
  }
  const id = 'u_' + Math.random().toString(36).slice(2, 10);
  const newUser = { id, name: name.trim(), email: email.trim(), password, joinedAt: Date.now() };
  users.push(newUser);
  _saveUsers(users);
  _setCurrentUserId(id);
  return newUser;
}
function signIn({ email, password }) {
  const u = _listUsers().find(x => x.email.toLowerCase() === (email || '').toLowerCase());
  if (!u || u.password !== password) throw new Error('Email or password incorrect.');
  _setCurrentUserId(u.id);
  return u;
}
function signOut() { _setCurrentUserId(null); }

/* ----- per-user persistence helpers ----- */
function userKey(suffix) {
  const id = _getCurrentUserId() || 'guest';
  return `mayday_${suffix}_${id}`;
}
function loadUserData(suffix, fallback) { return _readJSON(userKey(suffix), fallback); }
function saveUserData(suffix, val) { _writeJSON(userKey(suffix), val); }

/* ====================================================
   Avatar circle
   ==================================================== */
function Avatar({ user, size = 32, color }) {
  const ch = user ? (user.name || user.email || '?').slice(0, 1).toUpperCase() : 'G';
  const bg = color || (user ? 'var(--clay)' : 'var(--muted-2)');
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: bg, color: '#FBF7F0',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'Newsreader, Georgia, serif', fontSize: Math.round(size * 0.46),
      fontStyle: 'italic', flexShrink: 0, letterSpacing: 0,
    }} title={user ? user.name : 'Guest'}>{ch}</div>
  );
}

/* ====================================================
   Auth Modal
   ==================================================== */
function AuthModal({ mode, onClose, onSwitchMode, onAuthed }) {
  const [name, setName]   = _aus('');
  const [email, setEmail] = _aus('');
  const [pw, setPw]       = _aus('');
  const [err, setErr]     = _aus('');
  const isSignUp = mode === 'signup';

  _aue(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const submit = (e) => {
    e.preventDefault(); setErr('');
    try {
      if (isSignUp) signUp({ name, email, password: pw });
      else signIn({ email, password: pw });
      onAuthed && onAuthed();
      onClose();
    } catch (er) { setErr(er.message); }
  };

  return (
    <div className="auth-ov" onClick={onClose}>
      <form className="auth-box" onClick={e => e.stopPropagation()} onSubmit={submit}>
        <button type="button" className="auth-close" onClick={onClose} aria-label="Close">×</button>
        <div className="eyebrow">{ORN.sprig} {isSignUp ? 'create an account' : 'welcome back'}</div>
        <h2 style={{ marginTop: 6 }}>{isSignUp ? 'Join maydays.' : 'Sign in to maydays.'}</h2>
        <p className="muted" style={{ fontSize: 13.5, marginTop: 4, marginBottom: 20 }}>
          {isSignUp
            ? 'Save progress, notes, comments, and quizzes across sessions.'
            : 'Pick up exactly where you left off.'}
        </p>

        {isSignUp && (
          <label className="auth-field">
            <span>Name</span>
            <input type="text" value={name} onChange={e => setName(e.target.value)} required autoFocus />
          </label>
        )}
        <label className="auth-field">
          <span>Email</span>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoFocus={!isSignUp} />
        </label>
        <label className="auth-field">
          <span>Password</span>
          <input type="password" value={pw} onChange={e => setPw(e.target.value)} required minLength="4" />
        </label>

        {err && <div className="auth-err">{err}</div>}

        <button type="submit" className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
          {isSignUp ? 'Create account' : 'Sign in'}
        </button>

        <div className="auth-switch">
          {isSignUp
            ? <span>Already have an account? <a onClick={() => onSwitchMode('signin')}>Sign in</a></span>
            : <span>New to maydays? <a onClick={() => onSwitchMode('signup')}>Create an account</a></span>}
        </div>

        <div className="auth-note mono">
          prototype · accounts stored locally in your browser
        </div>
      </form>
    </div>
  );
}

/* ====================================================
   Account menu (header avatar)
   ==================================================== */
function AccountMenu({ onNavigate }) {
  const user = useAccount();
  const [open, setOpen] = _aus(false);
  const [authMode, setAuthMode] = _aus(null);
  const ref = _aur(null);

  _aue(() => {
    const onDoc = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  return (
    <div className="acct-wrap" ref={ref}>
      <button className="acct-trigger" onClick={() => setOpen(o => !o)} title={user ? user.name : 'Sign in'}>
        <Avatar user={user} size={34} />
      </button>
      {open && (
        <div className="acct-menu">
          {user ? (
            <>
              <div className="acct-menu-head">
                <Avatar user={user} size={42} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 500 }}>{user.name}</div>
                  <div className="muted" style={{ fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.email}</div>
                </div>
              </div>
              <div className="acct-menu-list">
                <button onClick={() => { setOpen(false); onNavigate({ name: 'profile' }); }}>My profile</button>
                <button onClick={() => { setOpen(false); onNavigate({ name: 'library' }); }}>Library</button>
                <button onClick={() => { setOpen(false); onNavigate({ name: 'rapids' }); }}>Rapids</button>
                <div className="acct-menu-sep" />
                <button onClick={() => { signOut(); setOpen(false); }}>Sign out</button>
              </div>
            </>
          ) : (
            <>
              <div className="acct-menu-head" style={{ flexDirection: 'column', alignItems: 'flex-start', gap: 6 }}>
                <div className="eyebrow">{ORN.sprig} maydays</div>
                <div className="serif" style={{ fontSize: 19 }}>Save your progress.</div>
                <div className="muted" style={{ fontSize: 12.5 }}>Keep notes, comments, and quizzes across sessions.</div>
              </div>
              <div className="acct-menu-list">
                <button onClick={() => { setOpen(false); setAuthMode('signin'); }}>Sign in</button>
                <button onClick={() => { setOpen(false); setAuthMode('signup'); }}>Create an account</button>
              </div>
            </>
          )}
        </div>
      )}
      {authMode && (
        <AuthModal mode={authMode}
                   onClose={() => setAuthMode(null)}
                   onSwitchMode={setAuthMode} />
      )}
    </div>
  );
}

/* ====================================================
   Profile page
   ==================================================== */
function ProfilePage({ data, onNavigate }) {
  const user = useAccount();
  const [authMode, setAuthMode] = _aus(null);

  if (!user) {
    return (
      <div className="fade">
        <Crumbs items={[{ label: 'Home', to: { name: 'home' } }, { label: 'Profile' }]} onNavigate={onNavigate} />
        <div className="card" style={{ padding: 40, textAlign: 'center', maxWidth: 560, margin: '40px auto' }}>
          <div className="eyebrow">{ORN.sprig} profile</div>
          <h2 style={{ marginTop: 8, marginBottom: 10 }}>Sign in to see your profile.</h2>
          <p className="muted" style={{ marginBottom: 18 }}>
            maydays uses your account to save progress, notes, comments, and quiz results.
          </p>
          <div className="row" style={{ gap: 8, justifyContent: 'center' }}>
            <button className="btn" onClick={() => setAuthMode('signin')}>Sign in</button>
            <button className="btn ghost" onClick={() => setAuthMode('signup')}>Create an account</button>
          </div>
        </div>
        {authMode && <AuthModal mode={authMode} onClose={() => setAuthMode(null)} onSwitchMode={setAuthMode} />}
      </div>
    );
  }

  const rdxStatus = loadUserData('rdx_status', {});
  const ratings   = loadUserData('rdx_ratings', {});
  const totals = Object.values(rdxStatus).reduce((a, s) => {
    if (s === 'correct') a.correct++;
    else if (s === 'incorrect') a.incorrect++;
    return a;
  }, { correct: 0, incorrect: 0 });
  const seenCount = Object.keys(rdxStatus).length;
  const ratedCount = Object.keys(ratings).length;

  // count user's comments across the app
  const allComments = _readJSON(COMMENTS_KEY, {});
  const myComments = Object.values(allComments).flat().filter(c => c.userId === user.id).length;

  const joined = new Date(user.joinedAt);
  const joinedStr = joined.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });

  return (
    <div className="fade">
      <Crumbs items={[{ label: 'Home', to: { name: 'home' } }, { label: 'Profile' }]} onNavigate={onNavigate} />

      <div className="row" style={{ gap: 22, alignItems: 'flex-end', marginBottom: 24 }}>
        <Avatar user={user} size={84} />
        <div>
          <div className="eyebrow">{ORN.sprig} profile</div>
          <h1 style={{ marginTop: 6 }}>{user.name}</h1>
          <div className="muted" style={{ fontSize: 14 }}>{user.email} · joined {joinedStr}</div>
        </div>
      </div>

      <div className="grid-3">
        <div className="card" style={{ padding: 22 }}>
          <div className="eyebrow">RAPIDS</div>
          <div className="serif" style={{ fontSize: 32, marginTop: 4 }}>{totals.correct}</div>
          <div className="muted" style={{ fontSize: 13 }}>correct of {seenCount} seen · {totals.incorrect} missed</div>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <div className="eyebrow">COMMENTS</div>
          <div className="serif" style={{ fontSize: 32, marginTop: 4 }}>{myComments}</div>
          <div className="muted" style={{ fontSize: 13 }}>notes posted on lessons</div>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <div className="eyebrow">CONFIDENCE TAGS</div>
          <div className="serif" style={{ fontSize: 32, marginTop: 4 }}>{ratedCount}</div>
          <div className="muted" style={{ fontSize: 13 }}>self-ratings recorded</div>
        </div>
      </div>

      <BranchDivider />

      <div className="card" style={{ padding: 22 }}>
        <h4>Account</h4>
        <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center', marginTop: 14, flexWrap: 'wrap', gap: 12 }}>
          <div className="muted" style={{ fontSize: 13 }}>You are signed in as <b style={{ color: 'var(--ink)' }}>{user.email}</b>.</div>
          <button className="btn ghost sm" onClick={() => { signOut(); onNavigate({ name: 'home' }); }}>Sign out</button>
        </div>
      </div>
    </div>
  );
}

/* ====================================================
   Comments helpers + UI
   ==================================================== */
function _loadAllComments() { return _readJSON(COMMENTS_KEY, {}); }
function _saveAllComments(obj) { _writeJSON(COMMENTS_KEY, obj); }
function loadCommentsFor(lessonId) { return _loadAllComments()[lessonId] || []; }
function postComment(lessonId, comment) {
  const all = _loadAllComments();
  if (!all[lessonId]) all[lessonId] = [];
  all[lessonId].unshift(comment);
  _saveAllComments(all);
}
function deleteComment(lessonId, commentId) {
  const all = _loadAllComments();
  if (all[lessonId]) {
    all[lessonId] = all[lessonId].filter(c => c.id !== commentId);
    _saveAllComments(all);
  }
}

function timeAgo(ts) {
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 60) return 'just now';
  const m = Math.floor(s / 60); if (m < 60) return m + 'm ago';
  const h = Math.floor(m / 60); if (h < 24) return h + 'h ago';
  const d = Math.floor(h / 24); if (d < 30) return d + 'd ago';
  const mo = Math.floor(d / 30); if (mo < 12) return mo + 'mo ago';
  return Math.floor(mo / 12) + 'y ago';
}

function CommentsSection({ lessonId, lessonTitle }) {
  const user = useAccount();
  const [comments, setComments] = _aus(loadCommentsFor(lessonId));
  const [body, setBody] = _aus('');
  const [authMode, setAuthMode] = _aus(null);

  _aue(() => { setComments(loadCommentsFor(lessonId)); setBody(''); }, [lessonId]);

  const post = () => {
    if (!user) { setAuthMode('signin'); return; }
    const text = body.trim();
    if (!text) return;
    postComment(lessonId, {
      id: 'c_' + Math.random().toString(36).slice(2, 10),
      userId: user.id, userName: user.name,
      body: text, createdAt: Date.now(),
    });
    setComments(loadCommentsFor(lessonId));
    setBody('');
  };

  const remove = (id) => {
    if (!confirm('Delete this comment?')) return;
    deleteComment(lessonId, id);
    setComments(loadCommentsFor(lessonId));
  };

  return (
    <div className="comments">
      <div className="comments-head">
        <div className="eyebrow">{ORN.sprig} comments</div>
        <h3>Discussion <span className="muted" style={{ fontSize: 14 }}>· {comments.length}</span></h3>
        <p className="muted" style={{ fontSize: 13.5, marginTop: 4 }}>
          Share a mnemonic, link a paper, or call out where this lesson tripped you up.
        </p>
      </div>

      <div className="comment-compose">
        <Avatar user={user} size={36} />
        <div style={{ flex: 1, minWidth: 0 }}>
          {user ? (
            <>
              <textarea value={body} onChange={e => setBody(e.target.value)}
                placeholder={`Comment on ${lessonTitle || 'this lesson'}...`} rows={3} />
              <div className="row" style={{ justifyContent: 'flex-end', gap: 8, marginTop: 6 }}>
                <button className="btn ghost sm" onClick={() => setBody('')} disabled={!body.trim()}>Clear</button>
                <button className="btn sm" onClick={post} disabled={!body.trim()}>Post comment</button>
              </div>
            </>
          ) : (
            <div className="comment-signin">
              <div>
                <div style={{ fontWeight: 500, marginBottom: 2 }}>Sign in to post a comment.</div>
                <div className="muted" style={{ fontSize: 12.5 }}>Your name will appear next to it.</div>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <button className="btn sm" onClick={() => setAuthMode('signin')}>Sign in</button>
                <button className="btn ghost sm" onClick={() => setAuthMode('signup')}>Create account</button>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="comment-list">
        {comments.length === 0 && (
          <div className="comment-empty muted">No comments yet. Be the first to drop a note.</div>
        )}
        {comments.map(c => (
          <div key={c.id} className="comment">
            <Avatar user={{ name: c.userName }} size={36} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div>
                  <b>{c.userName}</b>
                  <span className="muted" style={{ fontSize: 12, marginLeft: 8 }}>{timeAgo(c.createdAt)}</span>
                </div>
                {user && user.id === c.userId && (
                  <button className="comment-del" onClick={() => remove(c.id)}>delete</button>
                )}
              </div>
              <div className="comment-body">{c.body}</div>
            </div>
          </div>
        ))}
      </div>

      {authMode && <AuthModal mode={authMode} onClose={() => setAuthMode(null)} onSwitchMode={setAuthMode} />}
    </div>
  );
}

Object.assign(window, {
  useAccount, getCurrentUser, signIn, signUp, signOut,
  loadUserData, saveUserData,
  Avatar, AuthModal, AccountMenu, ProfilePage, CommentsSection,
  timeAgo,
});
