/* global React, Icon, Avatar, PageHeader, AnswerValue, apiGet, headshotCandidates */

// SMART Goals — the member-facing feed: everyone's posts for a cycle, newest cycle
// first. Reads GET /api/smart-goals/feed, which never says who did NOT post.
// Admin tracking stays under Notify → SMART goals. See tasks/smart-goals-feed.md.

const fmtGoalsDate = (iso, withTime = false) => (iso
  ? new Date(iso).toLocaleString(undefined, withTime
    ? { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }
    : { month: 'short', day: 'numeric' })
  : '');

const initialsOf = (name) => String(name || '')
  .split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part[0].toUpperCase()).join('') || '?';

// A member's headshot, walking the candidate URLs on load errors and ending on initials.
function GoalsAuthorPhoto({ member, name }) {
  const candidates = member ? headshotCandidates(member) : [];
  const [attempt, setAttempt] = React.useState(0);
  const photo = candidates[attempt];
  if (!photo) return <Avatar initials={member?.initials || initialsOf(name)} size={36}/>;
  return (
    <img key={photo} src={photo} alt="" className="goals-photo"
      onError={() => setAttempt((n) => n + 1)}/>
  );
}

function GoalsPost({ post, fields, member, isMine }) {
  // Skip questions this person left empty (e.g. no blockers) so the feed stays short.
  const answered = fields.filter((f) => {
    const v = post.answers?.[f.id];
    return Array.isArray(v) ? v.length > 0 : v != null && String(v).trim() !== '';
  });
  return (
    <article className={`card goals-post ${isMine ? 'mine' : ''}`}>
      <header className="goals-post-head">
        <GoalsAuthorPhoto member={member} name={post.name}/>
        <div style={{ minWidth: 0 }}>
          <div className="goals-post-name wrap-anywhere">
            {post.name}{isMine && <span className="goals-you">You</span>}
          </div>
          <div className="muted" style={{ fontSize: 11.5 }}>{fmtGoalsDate(post.respondedAt, true)}</div>
        </div>
      </header>
      {answered.map((f) => (
        <section key={f.id} className="goals-post-section">
          <div className="goals-post-label">{f.label}</div>
          <div className="goals-post-body"><AnswerValue field={f} value={post.answers[f.id]}/></div>
        </section>
      ))}
    </article>
  );
}

function SmartGoalsFeed({ members = [], currentUser }) {
  const [feed, setFeed] = React.useState(null);
  const [error, setError] = React.useState('');
  const [cycleId, setCycleId] = React.useState('');
  const [query, setQuery] = React.useState('');

  React.useEffect(() => {
    let cancelled = false;
    apiGet('/api/smart-goals/feed')
      .then((data) => {
        if (cancelled) return;
        setFeed(data);
        if (data.cycles.length) setCycleId(data.cycles[0].notificationId);
      })
      .catch((err) => { if (!cancelled) setError(err.message || 'Could not load SMART goals.'); });
    return () => { cancelled = true; };
  }, []);

  const membersByEmail = React.useMemo(() => {
    const map = new Map();
    members.forEach((m) => { if (m.email) map.set(String(m.email).toLowerCase(), m); });
    return map;
  }, [members]);

  const myEmail = String(currentUser?.email || '').toLowerCase();
  const mine = feed?.mine;
  const postAction = mine && (
    <button type="button" className={`btn ${mine.posted ? 'btn-ghost' : 'btn-primary'}`}
      onClick={() => { window.location.hash = `respond/${encodeURIComponent(mine.notificationId)}`; }}>
      <Icon name={mine.posted ? 'edit' : 'plus'} size={13}/> {mine.posted ? 'Edit your post' : 'Post your SMART goals'}
    </button>
  );

  const header = (
    <PageHeader eyebrow="Club · SMART Goals" title="SMART Goals"
      sub="What everyone has done over the past two weeks, what's blocking them, what they learned and what's next."
      actions={postAction}/>
  );

  if (error) return <>{header}<div className="card" style={{ padding: 24 }}><div className="form-error">{error}</div></div></>;
  if (!feed) return <>{header}<div className="card" style={{ padding: 24 }}><div className="muted">Loading…</div></div></>;
  if (feed.cycles.length === 0) {
    return <>{header}<div className="card" style={{ padding: 24 }}><div className="muted">No SMART goals have gone out yet.</div></div></>;
  }

  const cycle = feed.cycles.find((c) => c.notificationId === cycleId) || feed.cycles[0];
  const needle = query.trim().toLowerCase();
  const posts = cycle.posts
    .filter((p) => !needle || p.name.toLowerCase().includes(needle))
    // Your own post first, then everyone else alphabetically (the server's order).
    .sort((a, b) => (b.email.toLowerCase() === myEmail) - (a.email.toLowerCase() === myEmail));

  return (
    <>
      {header}
      <div className="goals-toolbar">
        <label className="field goals-cycle">
          <span className="field-label">Cycle</span>
          <select className="input" value={cycle.notificationId} onChange={(e) => setCycleId(e.target.value)}>
            {feed.cycles.map((c) => (
              <option key={c.notificationId} value={c.notificationId}>
                {fmtGoalsDate(c.sentAt)} ({c.posts.length} post{c.posts.length === 1 ? '' : 's'})
              </option>
            ))}
          </select>
        </label>
        <label className="field goals-search">
          <span className="field-label">Find someone</span>
          <input className="input" type="search" placeholder="Name" value={query}
            onChange={(e) => setQuery(e.target.value)}/>
        </label>
      </div>

      {mine && !mine.posted && mine.notificationId === cycle.notificationId && (
        <div className="goals-nudge">
          You haven't posted for this cycle yet. It takes two minutes, and everyone here can read it.
        </div>
      )}

      {posts.length === 0 ? (
        <div className="card" style={{ padding: 24 }}>
          <div className="muted">{needle ? 'No one by that name posted this cycle.' : 'No posts yet for this cycle.'}</div>
        </div>
      ) : (
        <div className="goals-grid">
          {posts.map((post) => (
            <GoalsPost key={post.email} post={post} fields={cycle.fields}
              member={membersByEmail.get(post.email.toLowerCase())}
              isMine={post.email.toLowerCase() === myEmail}/>
          ))}
        </div>
      )}
    </>
  );
}

window.SmartGoalsFeed = SmartGoalsFeed;
