/* global React */
const { useState, useEffect, useMemo, useRef } = React;

/* ============== Brand mark (gothic lancet window with trefoil) ============== */
/* Drawn from the 1865 illustration of the chapel — a single pointed-arch     */
/* window with quatrefoil tracery. Monastic, original, recognisable.            */
function HallMark({ size = 48, color, decorative = false }) {
  const stroke = color || 'currentColor';
  const opacity = decorative ? 0.6 : 1;
  // viewBox is taller than wide — lancet windows are vertical.
  const w = size * 0.7;
  return (
    <svg width={w} height={size} viewBox="0 0 42 60" style={{ opacity }} aria-hidden="true">
      <g fill="none" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        {/* Outer pointed arch — the window frame */}
        <path d="M 4 58 L 4 22 Q 4 4 21 3 Q 38 4 38 22 L 38 58 Z" />
        {/* Sill */}
        <line x1="4" y1="52" x2="38" y2="52" />
        {/* Central mullion */}
        <line x1="21" y1="18" x2="21" y2="52" />
        {/* Inner twin lancets */}
        <path d="M 9 42 L 9 30 Q 9 21 21 19" />
        <path d="M 33 42 L 33 30 Q 33 21 21 19" />
        {/* Quatrefoil oculus at the head */}
        <circle cx="21" cy="13" r="3.2" />
        <circle cx="21" cy="13" r="1" fill={stroke} />
      </g>
    </svg>
  );
}

/* Back-compat alias — some screens still import the old name. */
const OliveBranch = HallMark;

function Brand({ size = 'md', showMotif = true }) {
  const big = size === 'lg';
  return (
    <div className="brand">
      {showMotif && <HallMark size={big ? 64 : 44} color="var(--olive-deep)" />}
      <div>
        <div className="brand-name" style={big ? { fontSize: 30 } : null}>St Katherine&rsquo;s Hall</div>
        <div className="brand-sub">Community Voice &middot; since 1232</div>
      </div>
    </div>
  );
}

/* ============== Avatar ============== */
function Avatar({ member, size }) {
  if (!member) return null;
  const initials = (member.first?.[0] || '?') + (member.last?.[0] || '');
  return <span className={'avatar ' + (size || '')}>{initials}</span>;
}

function displayName(member, mode) {
  if (!member) return 'Unknown';
  if (member.isLeaf && member.id === 'leaf') return 'LEAF';
  if (mode === 'initials') return member.first + ' ' + (member.last?.[0] || '') + '.';
  if (mode === 'pseudonyms') return member.pseudo || (member.first + ' ' + (member.last?.[0] || ''));
  return member.name;
}

/* ============== Pills & rank dots ============== */
function StagePill({ stage }) {
  const cls = stage.toLowerCase().replace(/\s+/g, '-');
  return <span className={'pill ' + cls}>{stage}</span>;
}

function RankDots({ value, interactive, onChange, terra }) {
  const v = Math.round(value || 0);
  return (
    <span className={'rank-dots' + (interactive ? ' interactive' : '')}>
      {[1,2,3,4,5].map(n => (
        <span
          key={n}
          className={'dot' + (n <= v ? ' filled' : '') + (terra && n <= v ? ' terra' : '')}
          onClick={interactive ? (e) => { e.stopPropagation(); onChange && onChange(n); } : undefined}
        />
      ))}
    </span>
  );
}

/* ============== Owner chip / facepile ============== */
function OwnerChip({ idea, nameMode, currentUserId }) {
  const { MEMBER_BY_ID } = window.OB_DATA;
  const owners = (idea.owners || []).map(id => MEMBER_BY_ID[id]).filter(Boolean);

  if (owners.length === 0) {
    // Unclaimed — show the "looking for an owner" badge with proposer footnote.
    return (
      <span className="owner-chip unclaimed" title={idea.proposer}>
        <span className="unclaimed-dot" />
        <span>Looking for an owner</span>
      </span>
    );
  }

  if (owners.length === 1) {
    const o = owners[0];
    return (
      <span className="owner-chip">
        <Avatar member={o} size="sm" />
        <span>{currentUserId === o.id ? 'You' : displayName(o, nameMode)}</span>
      </span>
    );
  }

  // Multiple owners → facepile + "X & Y" or "X + N others"
  return (
    <span className="owner-chip">
      <span className="facepile">
        {owners.slice(0, 3).map(o => <Avatar key={o.id} member={o} size="sm" />)}
      </span>
      <span>
        {owners.length === 2
          ? `${owners[0].first} & ${owners[1].first}`
          : `${owners[0].first} + ${owners.length - 1} others`}
      </span>
    </span>
  );
}

/* ============== Idea card (for list) ============== */
function IdeaCard({ idea, onOpen, nameMode, currentUserId }) {
  return (
    <div className="idea-card" onClick={() => onOpen(idea.id)}>
      <div className="row1">
        <h3>{idea.title}</h3>
        <StagePill stage={idea.stage} />
      </div>
      <p className="summary">{idea.summary}</p>
      <div className="meta">
        <OwnerChip idea={idea} nameMode={nameMode} currentUserId={currentUserId} />
        <span style={{ color: 'var(--rule)' }}>·</span>
        <span><span className="tag">{idea.theme}</span></span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 18, alignItems: 'center' }}>
          <span className="rank" title="Need">
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Need</span>
            <RankDots value={idea.rankings.need} />
          </span>
          <span className="rank" title="Practicality">
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Practical</span>
            <RankDots value={idea.rankings.practicality} terra />
          </span>
          <span style={{ fontSize: 12, color: 'var(--ink-faint)' }}>{idea.commentsCount} {idea.commentsCount === 1 ? 'voice' : 'voices'}</span>
        </span>
      </div>
    </div>
  );
}

/* ============== Topbar ============== */
function Topbar({ current, onNav, currentUser, onSignOut, showMotif, nameMode, adminBadge }) {
  const isLeaf = currentUser?.isLeaf;
  const items = [
    { id: 'welcome', label: 'Welcome' },
    { id: 'voice', label: 'Community Voice' },
    { id: 'library', label: 'Library' },
    { id: 'members', label: 'Members' }
  ];
  if (isLeaf) items.push({ id: 'admin', label: 'LEAF host', badge: adminBadge });
  return (
    <div className="topbar">
      <div className="brand" onClick={() => onNav('welcome')} style={{ cursor: 'pointer' }}>
        {showMotif && <HallMark size={40} color="var(--olive-deep)" />}
        <div>
          <div className="brand-name">St Katherine&rsquo;s Hall</div>
          <div className="brand-sub">Community Voice &middot; since 1232</div>
        </div>
      </div>
      <nav>
        {items.map(it => (
          <a key={it.id} className={current === it.id ? 'active' : ''} onClick={() => onNav(it.id)}>
            {it.label}
            {it.badge > 0 && <span className="nav-badge">{it.badge}</span>}
          </a>
        ))}
      </nav>
      <div className="user-chip" onClick={onSignOut} title="Sign out">
        <Avatar member={currentUser} size="sm" />
        <span>{displayName(currentUser, nameMode)}</span>
        {isLeaf && <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--accent)' }}>&middot; host</span>}
      </div>
    </div>
  );
}

/* ============== Discussion thread (idea detail) ============== */
function Discussion({ comments, onPost, nameMode, currentUser }) {
  const { MEMBER_BY_ID } = window.OB_DATA;
  const [text, setText] = useState('');
  return (
    <section>
      <h4>Discussion</h4>
      <div className="thread" style={{ marginTop: 18 }}>
        {comments.length === 0 && (
          <div style={{ fontStyle: 'italic', color: 'var(--ink-faint)', padding: '14px 0' }}>
            No comments yet. The first thought belongs to whoever offers it.
          </div>
        )}
        {comments.map((c, i) => {
          const m = MEMBER_BY_ID[c.author];
          return (
            <div key={i} className={'comment' + (c.leaf ? ' leaf' : '')}>
              <Avatar member={m} />
              <div className="body">
                <div className="head">
                  <span className="who">{displayName(m, nameMode)}</span>
                  {c.leaf && <span className="leaf-badge">LEAF</span>}
                  <span className="when">{c.when}</span>
                </div>
                <div className="text">{c.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div className="compose">
        <Avatar member={currentUser} />
        <div className="compose-box">
          <textarea
            placeholder="Add to the conversation…"
            value={text}
            onChange={e => setText(e.target.value)}
          />
          <div className="actions">
            <button className="btn btn-secondary btn-sm" onClick={() => setText('')} disabled={!text}>Clear</button>
            <button
              className="btn btn-primary btn-sm"
              disabled={!text.trim()}
              onClick={() => { onPost(text.trim()); setText(''); }}
            >
              Add comment
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== Stage track (sidebar) ============== */
function StageTrack({ stage }) {
  const { STAGES } = window.OB_DATA;
  const ix = STAGES.indexOf(stage);
  return (
    <div className="stage-track">
      {STAGES.map((s, i) => (
        <div key={s} className={'step ' + (i < ix ? 'done' : i === ix ? 'current' : '')}>
          <span className="dot" />
          <span>{s}</span>
        </div>
      ))}
    </div>
  );
}

/* ============== Counts row ============== */
function CountsRow({ ideas }) {
  const groups = ideas.reduce((acc, i) => { acc[i.stage] = (acc[i.stage] || 0) + 1; return acc; }, {});
  const items = [
    { l: 'Open for discussion', n: (groups['Proposed'] || 0) + (groups['In Discussion'] || 0) },
    { l: 'Under consideration', n: groups['Under Consideration'] || 0 },
    { l: 'In development', n: groups['In Development'] || 0 },
    { l: 'Decided', n: groups['Decided'] || 0 },
    { l: 'Archived', n: groups['Archived'] || 0 }
  ];
  return (
    <div className="counts-row">
      {items.map(it => (
        <div className="count" key={it.l}>
          <span className="n">{it.n}</span>
          <span className="l">{it.l}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  HallMark, OliveBranch, Brand, Avatar, displayName,
  StagePill, RankDots, IdeaCard, OwnerChip, Topbar,
  Discussion, StageTrack, CountsRow
});
